@camstack/server 0.2.2 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/{src/agent-status-page.ts → dist/agent-status-page.js} +30 -45
  2. package/dist/api/addon-upload.js +441 -0
  3. package/dist/api/addons-custom.router.js +91 -0
  4. package/dist/api/auth-whoami.js +55 -0
  5. package/dist/api/bridge-addons.router.js +109 -0
  6. package/dist/api/capabilities.router.js +229 -0
  7. package/dist/api/core/addon-settings.router.js +117 -0
  8. package/dist/api/core/agents.router.js +73 -0
  9. package/dist/api/core/auth.router.js +286 -0
  10. package/dist/api/core/bulk-update-coordinator.js +229 -0
  11. package/dist/api/core/cap-providers.js +1124 -0
  12. package/dist/api/core/capabilities.router.js +138 -0
  13. package/dist/api/core/collection-preference.js +17 -0
  14. package/dist/api/core/event-bus-proxy.router.js +45 -0
  15. package/dist/api/core/hwaccel.router.js +91 -0
  16. package/dist/api/core/live-events.router.js +61 -0
  17. package/dist/api/core/logs.router.js +172 -0
  18. package/dist/api/core/notifications.router.js +67 -0
  19. package/dist/api/core/repl.router.js +35 -0
  20. package/dist/api/core/settings-backend.router.js +121 -0
  21. package/dist/api/core/stream-probe.router.js +58 -0
  22. package/dist/api/core/system-events.router.js +100 -0
  23. package/dist/api/health/health.routes.js +68 -0
  24. package/{src/api/oauth2/consent-page.ts → dist/api/oauth2/consent-page.js} +11 -20
  25. package/dist/api/oauth2/oauth2-routes.js +219 -0
  26. package/dist/api/trpc/cap-mount-helpers.js +194 -0
  27. package/dist/api/trpc/cap-route-error-formatter.js +133 -0
  28. package/dist/api/trpc/client-ip.js +147 -0
  29. package/dist/api/trpc/core-cap-bridge.js +115 -0
  30. package/dist/api/trpc/generated-cap-mounts.js +388 -0
  31. package/dist/api/trpc/generated-cap-routers.js +7635 -0
  32. package/dist/api/trpc/scope-access.js +93 -0
  33. package/dist/api/trpc/trpc.context.js +184 -0
  34. package/dist/api/trpc/trpc.middleware.js +139 -0
  35. package/dist/api/trpc/trpc.router.js +188 -0
  36. package/dist/auth/session-cookie.js +47 -0
  37. package/dist/boot/boot-config.js +241 -0
  38. package/dist/boot/integration-id-backfill.js +76 -0
  39. package/dist/boot/post-boot.service.js +85 -0
  40. package/dist/core/addon/addon-call-gateway.js +99 -0
  41. package/dist/core/addon/addon-package.service.js +1560 -0
  42. package/dist/core/addon/addon-registry.service.js +2739 -0
  43. package/{src/core/addon/addon-row-manifest.ts → dist/core/addon/addon-row-manifest.js} +5 -5
  44. package/dist/core/addon/addon-search.service.js +62 -0
  45. package/dist/core/addon/addon-settings-provider.js +102 -0
  46. package/dist/core/addon/addon.tokens.js +5 -0
  47. package/dist/core/addon-bridge/addon-bridge.service.js +145 -0
  48. package/dist/core/addon-pages/addon-pages.service.js +107 -0
  49. package/dist/core/addon-widgets/addon-widgets.service.js +120 -0
  50. package/dist/core/agent/agent-registry.service.js +477 -0
  51. package/dist/core/auth/auth.service.js +10 -0
  52. package/dist/core/capability/capability.service.js +58 -0
  53. package/dist/core/config/config.schema.js +7 -0
  54. package/dist/core/config/config.service.js +10 -0
  55. package/dist/core/events/event-bus.service.js +83 -0
  56. package/dist/core/feature/feature.service.js +10 -0
  57. package/dist/core/lifecycle/lifecycle-state-machine.js +6 -0
  58. package/dist/core/logging/log-ring-buffer.js +6 -0
  59. package/dist/core/logging/logging.service.js +130 -0
  60. package/dist/core/logging/scoped-logger.js +6 -0
  61. package/dist/core/moleculer/cap-call-fn.js +50 -0
  62. package/dist/core/moleculer/cap-route-authority.js +122 -0
  63. package/dist/core/moleculer/moleculer.service.js +898 -0
  64. package/dist/core/network/network-quality.service.js +7 -0
  65. package/dist/core/notification/notification-wrapper.service.js +33 -0
  66. package/dist/core/notification/toast-wrapper.service.js +25 -0
  67. package/dist/core/provider/provider.tokens.js +4 -0
  68. package/dist/core/repl/repl-engine.service.js +140 -0
  69. package/dist/core/storage/fs-storage-backend.js +6 -0
  70. package/dist/core/storage/storage-location-manager.js +6 -0
  71. package/dist/core/storage/storage.service.js +7 -0
  72. package/dist/core/streaming/stream-probe.service.js +209 -0
  73. package/dist/core/topology/topology-emitter.service.js +106 -0
  74. package/dist/launcher.js +325 -0
  75. package/dist/main.js +1098 -0
  76. package/dist/manual-boot.js +227 -0
  77. package/package.json +5 -1
  78. package/src/__tests__/addon-install-e2e.test.ts +0 -74
  79. package/src/__tests__/addon-pages-e2e.test.ts +0 -200
  80. package/src/__tests__/addon-route-session.test.ts +0 -17
  81. package/src/__tests__/addon-settings-router.spec.ts +0 -67
  82. package/src/__tests__/addon-upload.spec.ts +0 -475
  83. package/src/__tests__/agent-registry.spec.ts +0 -179
  84. package/src/__tests__/agent-status-page.spec.ts +0 -82
  85. package/src/__tests__/auth-session-cookie.test.ts +0 -48
  86. package/src/__tests__/bulk-update-coordinator.spec.ts +0 -303
  87. package/src/__tests__/cap-ownership-authority.spec.ts +0 -431
  88. package/src/__tests__/cap-providers/cap-providers-location-import.spec.ts +0 -206
  89. package/src/__tests__/cap-providers/cap-usage-graph.spec.ts +0 -37
  90. package/src/__tests__/cap-providers/compute-topology-categories.spec.ts +0 -110
  91. package/src/__tests__/cap-providers/integrations-delete-cascade.spec.ts +0 -292
  92. package/src/__tests__/cap-providers-bulk-update.spec.ts +0 -408
  93. package/src/__tests__/cap-route-adapter.spec.ts +0 -302
  94. package/src/__tests__/cap-routers/_meta.spec.ts +0 -199
  95. package/src/__tests__/cap-routers/addon-settings.router.spec.ts +0 -115
  96. package/src/__tests__/cap-routers/broker-routing.router.spec.ts +0 -177
  97. package/src/__tests__/cap-routers/cap-route-error-formatter.spec.ts +0 -125
  98. package/src/__tests__/cap-routers/capabilities-node.spec.ts +0 -68
  99. package/src/__tests__/cap-routers/device-link-overlay.spec.ts +0 -137
  100. package/src/__tests__/cap-routers/device-manager-aggregate.router.spec.ts +0 -194
  101. package/src/__tests__/cap-routers/harness.ts +0 -163
  102. package/src/__tests__/cap-routers/metrics-provider.router.spec.ts +0 -133
  103. package/src/__tests__/cap-routers/null-provider-guard.spec.ts +0 -64
  104. package/src/__tests__/cap-routers/pipeline-executor.router.spec.ts +0 -159
  105. package/src/__tests__/cap-routers/settings-store.router.spec.ts +0 -291
  106. package/src/__tests__/capability-e2e.test.ts +0 -384
  107. package/src/__tests__/cli-e2e.test.ts +0 -150
  108. package/src/__tests__/core-cap-bridge.spec.ts +0 -91
  109. package/src/__tests__/dev-bootstrap-shm-ring.spec.ts +0 -40
  110. package/src/__tests__/device-settings-contribution-dispatch.spec.ts +0 -280
  111. package/src/__tests__/embedded-deps-e2e.test.ts +0 -125
  112. package/src/__tests__/event-bus-proxy-router.spec.ts +0 -75
  113. package/src/__tests__/fixtures/mock-analysis-addon-a.ts +0 -37
  114. package/src/__tests__/fixtures/mock-analysis-addon-b.ts +0 -37
  115. package/src/__tests__/fixtures/mock-log-addon.ts +0 -37
  116. package/src/__tests__/fixtures/mock-storage-addon.ts +0 -40
  117. package/src/__tests__/framework-allowlist.spec.ts +0 -96
  118. package/src/__tests__/framework-installer-defer-restart.spec.ts +0 -165
  119. package/src/__tests__/https-e2e.test.ts +0 -124
  120. package/src/__tests__/lifecycle-e2e.test.ts +0 -189
  121. package/src/__tests__/live-events-subscription.spec.ts +0 -149
  122. package/src/__tests__/moleculer/uds-readiness.spec.ts +0 -150
  123. package/src/__tests__/moleculer/uds-topology.spec.ts +0 -418
  124. package/src/__tests__/moleculer/uds-unowned-call.spec.ts +0 -383
  125. package/src/__tests__/moleculer-register-node-idempotency.spec.ts +0 -273
  126. package/src/__tests__/native-cap-route.spec.ts +0 -427
  127. package/src/__tests__/oauth2-account-linking.spec.ts +0 -867
  128. package/src/__tests__/post-boot-restart.spec.ts +0 -161
  129. package/src/__tests__/singleton-contention.test.ts +0 -499
  130. package/src/__tests__/streaming-diagnostic.test.ts +0 -615
  131. package/src/__tests__/streaming-scale.test.ts +0 -314
  132. package/src/__tests__/uds-addon-call-wiring.spec.ts +0 -242
  133. package/src/__tests__/uds-log-ingest.spec.ts +0 -183
  134. package/src/api/__tests__/addons-custom.spec.ts +0 -148
  135. package/src/api/__tests__/capabilities.router.test.ts +0 -56
  136. package/src/api/addon-upload.ts +0 -529
  137. package/src/api/addons-custom.router.ts +0 -101
  138. package/src/api/auth-whoami.ts +0 -101
  139. package/src/api/bridge-addons.router.ts +0 -122
  140. package/src/api/capabilities.router.ts +0 -265
  141. package/src/api/core/__tests__/auth-router-totp.spec.ts +0 -297
  142. package/src/api/core/__tests__/integration-markers.spec.ts +0 -10
  143. package/src/api/core/addon-settings.router.ts +0 -127
  144. package/src/api/core/agents.router.ts +0 -86
  145. package/src/api/core/auth.router.ts +0 -322
  146. package/src/api/core/bulk-update-coordinator.ts +0 -305
  147. package/src/api/core/cap-providers.ts +0 -1339
  148. package/src/api/core/capabilities.router.ts +0 -149
  149. package/src/api/core/collection-preference.ts +0 -40
  150. package/src/api/core/event-bus-proxy.router.ts +0 -45
  151. package/src/api/core/hwaccel.router.ts +0 -108
  152. package/src/api/core/live-events.router.ts +0 -67
  153. package/src/api/core/logs.router.ts +0 -195
  154. package/src/api/core/notifications.router.ts +0 -66
  155. package/src/api/core/repl.router.ts +0 -39
  156. package/src/api/core/settings-backend.router.ts +0 -140
  157. package/src/api/core/stream-probe.router.ts +0 -57
  158. package/src/api/core/system-events.router.ts +0 -125
  159. package/src/api/health/health.routes.ts +0 -117
  160. package/src/api/oauth2/__tests__/oauth2-routes.spec.ts +0 -62
  161. package/src/api/oauth2/oauth2-routes.ts +0 -281
  162. package/src/api/trpc/__tests__/client-ip.spec.ts +0 -146
  163. package/src/api/trpc/__tests__/scope-access-device.spec.ts +0 -268
  164. package/src/api/trpc/__tests__/scope-access.spec.ts +0 -102
  165. package/src/api/trpc/__tests__/webrtc-session-ua-enrich.spec.ts +0 -136
  166. package/src/api/trpc/cap-mount-helpers.ts +0 -245
  167. package/src/api/trpc/cap-route-error-formatter.ts +0 -171
  168. package/src/api/trpc/client-ip.ts +0 -147
  169. package/src/api/trpc/core-cap-bridge.ts +0 -154
  170. package/src/api/trpc/generated-cap-mounts.ts +0 -1240
  171. package/src/api/trpc/generated-cap-routers.ts +0 -11523
  172. package/src/api/trpc/scope-access.ts +0 -110
  173. package/src/api/trpc/trpc.context.ts +0 -258
  174. package/src/api/trpc/trpc.middleware.ts +0 -146
  175. package/src/api/trpc/trpc.router.ts +0 -389
  176. package/src/auth/session-cookie.ts +0 -54
  177. package/src/boot/__tests__/integration-id-backfill.spec.ts +0 -131
  178. package/src/boot/boot-config.ts +0 -259
  179. package/src/boot/integration-id-backfill.ts +0 -109
  180. package/src/boot/post-boot.service.ts +0 -105
  181. package/src/core/addon/__tests__/addon-registry-capability.test.ts +0 -62
  182. package/src/core/addon/__tests__/addon-row-manifest.spec.ts +0 -62
  183. package/src/core/addon/addon-call-gateway.ts +0 -171
  184. package/src/core/addon/addon-package.service.ts +0 -1787
  185. package/src/core/addon/addon-registry.service.ts +0 -3130
  186. package/src/core/addon/addon-search.service.ts +0 -91
  187. package/src/core/addon/addon-settings-provider.ts +0 -220
  188. package/src/core/addon/addon.tokens.ts +0 -2
  189. package/src/core/addon-bridge/addon-bridge.service.ts +0 -130
  190. package/src/core/addon-pages/addon-pages.service.spec.ts +0 -117
  191. package/src/core/addon-pages/addon-pages.service.ts +0 -82
  192. package/src/core/addon-widgets/addon-widgets.service.ts +0 -95
  193. package/src/core/agent/agent-registry.service.ts +0 -529
  194. package/src/core/auth/auth.service.spec.ts +0 -86
  195. package/src/core/auth/auth.service.ts +0 -8
  196. package/src/core/capability/capability.service.ts +0 -66
  197. package/src/core/config/config.schema.ts +0 -3
  198. package/src/core/config/config.service.spec.ts +0 -175
  199. package/src/core/config/config.service.ts +0 -7
  200. package/src/core/events/event-bus.service.spec.ts +0 -235
  201. package/src/core/events/event-bus.service.ts +0 -89
  202. package/src/core/feature/feature.service.spec.ts +0 -99
  203. package/src/core/feature/feature.service.ts +0 -8
  204. package/src/core/lifecycle/lifecycle-state-machine.spec.ts +0 -166
  205. package/src/core/lifecycle/lifecycle-state-machine.ts +0 -3
  206. package/src/core/logging/log-ring-buffer.ts +0 -3
  207. package/src/core/logging/logging.service.spec.ts +0 -287
  208. package/src/core/logging/logging.service.ts +0 -143
  209. package/src/core/logging/scoped-logger.ts +0 -3
  210. package/src/core/moleculer/cap-call-fn.spec.ts +0 -173
  211. package/src/core/moleculer/cap-call-fn.ts +0 -107
  212. package/src/core/moleculer/cap-route-authority.ts +0 -194
  213. package/src/core/moleculer/moleculer.service.ts +0 -1072
  214. package/src/core/network/network-quality.service.spec.ts +0 -53
  215. package/src/core/network/network-quality.service.ts +0 -5
  216. package/src/core/notification/notification-wrapper.service.ts +0 -34
  217. package/src/core/notification/toast-wrapper.service.ts +0 -27
  218. package/src/core/provider/provider.tokens.ts +0 -1
  219. package/src/core/repl/repl-engine.service.spec.ts +0 -444
  220. package/src/core/repl/repl-engine.service.ts +0 -155
  221. package/src/core/storage/fs-storage-backend.spec.ts +0 -70
  222. package/src/core/storage/fs-storage-backend.ts +0 -3
  223. package/src/core/storage/storage-location-manager.spec.ts +0 -130
  224. package/src/core/storage/storage-location-manager.ts +0 -3
  225. package/src/core/storage/storage.service.spec.ts +0 -73
  226. package/src/core/storage/storage.service.ts +0 -3
  227. package/src/core/streaming/stream-probe.service.ts +0 -221
  228. package/src/core/topology/topology-emitter.service.ts +0 -105
  229. package/src/launcher.ts +0 -314
  230. package/src/main.ts +0 -1245
  231. package/src/manual-boot.ts +0 -301
  232. package/tsconfig.build.json +0 -8
  233. package/tsconfig.json +0 -33
  234. package/vitest.config.ts +0 -26
@@ -0,0 +1,325 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ /**
37
+ * Launcher -- entry point that ensures required addons are installed
38
+ * before main.ts loads. This solves the chicken-and-egg problem:
39
+ * main.ts has static imports from @camstack/core, but core lives in
40
+ * data/addons/ and may not exist on first boot.
41
+ *
42
+ * 1. Run AddonInstaller.ensureRequiredPackages (zero core dependencies)
43
+ * 2. Create symlinks so @camstack/core resolves from data/addons/
44
+ * 3. Dynamically import main.ts (which has static @camstack/core imports)
45
+ */
46
+ const fs = __importStar(require("node:fs"));
47
+ const path = __importStar(require("node:path"));
48
+ const tar = __importStar(require("tar"));
49
+ const yaml = __importStar(require("js-yaml"));
50
+ const kernel_1 = require("@camstack/kernel");
51
+ /** Path of the manifest file embedded inside every archive. */
52
+ const ARCHIVE_MANIFEST_NAME = '.camstack-backup-manifest.json';
53
+ /** Resolve the data directory from env or default */
54
+ const DATA_DIR = process.env['CAMSTACK_DATA'] ?? 'camstack-data';
55
+ const RESTORE_MARKER_FILE = '.pending-restore.json';
56
+ /**
57
+ * Apply a pending system-restore archive over `dataDir` if a marker is
58
+ * present. Runs BEFORE the addon installer so the restored snapshot's
59
+ * `addons/` folder is what `ensureRequiredPackages` picks up.
60
+ *
61
+ * Marker contract is owned by `SystemBackupService.scheduleRestoreMarker`
62
+ * (packages/core/src/builtins/system-backup) — kept inline here so the
63
+ * launcher remains zero-core-deps. Schema:
64
+ * { archivePath: string, requestedAt: number, source: string }
65
+ *
66
+ * Failure modes:
67
+ * - marker malformed → log + leave it in place (operator visibility)
68
+ * - archive missing → log + clear marker (auto-recover from stale)
69
+ * - tar fails → throw → launcher exits non-zero, marker preserved
70
+ */
71
+ async function applyPendingRestore(dataDir) {
72
+ const markerPath = path.join(dataDir, RESTORE_MARKER_FILE);
73
+ if (!fs.existsSync(markerPath))
74
+ return;
75
+ console.log(`[launcher] Pending restore marker found at ${markerPath}`);
76
+ let archivePath = null;
77
+ let locations = null;
78
+ try {
79
+ const raw = fs.readFileSync(markerPath, 'utf-8');
80
+ const parsed = JSON.parse(raw);
81
+ if (typeof parsed === 'object' &&
82
+ parsed != null &&
83
+ typeof parsed.archivePath === 'string') {
84
+ archivePath = parsed.archivePath;
85
+ }
86
+ const locField = parsed.locations;
87
+ if (Array.isArray(locField) && locField.every((l) => typeof l === 'string')) {
88
+ locations = locField;
89
+ }
90
+ }
91
+ catch (err) {
92
+ console.error('[launcher] Restore marker malformed — leaving in place:', err);
93
+ return;
94
+ }
95
+ if (archivePath == null) {
96
+ console.error('[launcher] Restore marker missing archivePath — clearing');
97
+ fs.rmSync(markerPath, { force: true });
98
+ return;
99
+ }
100
+ if (!fs.existsSync(archivePath)) {
101
+ console.error(`[launcher] Restore archive ${archivePath} missing — clearing marker`);
102
+ fs.rmSync(markerPath, { force: true });
103
+ return;
104
+ }
105
+ const scope = locations ? ` (only: ${locations.join(', ')})` : '';
106
+ console.log(`[launcher] Restoring snapshot from ${archivePath} into ${dataDir}${scope}`);
107
+ fs.mkdirSync(dataDir, { recursive: true });
108
+ // Same filter logic SystemBackupService.extractArchive uses — kept
109
+ // inline here so the launcher stays zero-core-deps. The shape is
110
+ // straightforward enough to duplicate.
111
+ const allowedPrefixes = locations
112
+ ? locations.map((loc) => loc.replace(/^\.\//, '').replace(/\/+$/, ''))
113
+ : null;
114
+ await tar.extract({
115
+ file: archivePath,
116
+ cwd: dataDir,
117
+ filter: (p) => {
118
+ if (p === ARCHIVE_MANIFEST_NAME || p === `./${ARCHIVE_MANIFEST_NAME}`)
119
+ return false;
120
+ if (!allowedPrefixes)
121
+ return true;
122
+ const normalized = p.replace(/^\.\//, '');
123
+ return allowedPrefixes.some((prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`));
124
+ },
125
+ });
126
+ fs.rmSync(markerPath, { force: true });
127
+ console.log('[launcher] Restore complete; marker cleared');
128
+ }
129
+ /** Narrow `CAMSTACK_INSTALL_SOURCE` env into the typed union. */
130
+ function parseInstallSource(value) {
131
+ if (value === 'npm' || value === 'local' || value === 'symlink')
132
+ return value;
133
+ return undefined;
134
+ }
135
+ /**
136
+ * Locate + parse `config.yaml` relative to the data dir. Returns the
137
+ * raw object on success, `null` when missing or unparseable. The
138
+ * launcher uses this BEFORE @camstack/core is imported so it must stay
139
+ * free of core deps — just js-yaml + the kernel's bootstrapSchema for
140
+ * shape validation by the call site.
141
+ */
142
+ function readConfigYaml(dataDir) {
143
+ const candidates = [
144
+ path.resolve(dataDir, '..', 'config.yaml'),
145
+ path.resolve(dataDir, 'config.yaml'),
146
+ path.resolve(process.cwd(), 'config.yaml'),
147
+ ];
148
+ const found = candidates.find((p) => fs.existsSync(p));
149
+ if (!found)
150
+ return null;
151
+ try {
152
+ return yaml.load(fs.readFileSync(found, 'utf-8')) ?? {};
153
+ }
154
+ catch (err) {
155
+ console.warn(`[launcher] Could not parse ${found}: ${err instanceof Error ? err.message : String(err)}`);
156
+ return null;
157
+ }
158
+ }
159
+ /**
160
+ * Read `bootstrap.installSource` from `<dataDir>/config.yaml` if present.
161
+ * Returns the configured value or `null` when absent.
162
+ *
163
+ * Production deployments should leave this unset (defaults to 'npm');
164
+ * `symlink` is a dev-time convenience that points data/addons/<pkg>
165
+ * directly at the workspace source dir — never set in shipped
166
+ * containers or Electron bundles.
167
+ */
168
+ function readBootstrapInstallSource(dataDir) {
169
+ const raw = readConfigYaml(dataDir);
170
+ if (raw === null)
171
+ return undefined;
172
+ const validation = kernel_1.bootstrapSchema.safeParse(raw);
173
+ if (!validation.success)
174
+ return undefined;
175
+ return parseInstallSource(validation.data.bootstrap.installSource);
176
+ }
177
+ /**
178
+ * Read `bootstrap.requiredAddons` from `<dataDir>/config.yaml` if present.
179
+ * Returns the parsed array, an empty array when explicitly set to `[]`,
180
+ * or `null` when the field is absent (caller should fall back to the
181
+ * kernel's REQUIRED_PACKAGES constant).
182
+ *
183
+ * Inline YAML parse rather than going through ConfigManager: the
184
+ * launcher runs before @camstack/core is imported and must stay free of
185
+ * core dependencies. Just yaml.load + bootstrapSchema (kernel) for
186
+ * shape validation.
187
+ */
188
+ function readBootstrapRequiredAddons(dataDir) {
189
+ const raw = readConfigYaml(dataDir);
190
+ if (raw === null)
191
+ return null;
192
+ const validation = kernel_1.bootstrapSchema.safeParse(raw);
193
+ if (!validation.success) {
194
+ console.warn(`[launcher] config.yaml failed bootstrapSchema validation: ${validation.error.message}`);
195
+ return null;
196
+ }
197
+ return validation.data.bootstrap.requiredAddons ?? null;
198
+ }
199
+ async function launch() {
200
+ const dataDir = DATA_DIR;
201
+ const addonsDir = path.resolve(dataDir, 'addons');
202
+ // Restore must happen first so the snapshot's `addons/` is what the
203
+ // installer + symlink step pick up — otherwise we'd install a stale
204
+ // set and overwrite it a step later.
205
+ await applyPendingRestore(dataDir);
206
+ // Install source resolution:
207
+ // 1. CAMSTACK_BUNDLED_ADDONS_DIR — set by Electron-packaged builds
208
+ // to <resourcesPath>/addons. Pre-built addons ship with the
209
+ // bundle, copied at first launch (`'local'` mode).
210
+ // 2. CAMSTACK_INSTALL_SOURCE=local — explicit opt-in to copy from
211
+ // the monorepo workspace (used by e2e + dev bootstrap). Hub
212
+ // auto-detects `packages/` via detectWorkspacePackagesDir.
213
+ // 3. Otherwise: 'npm' from the registry. Local development pushes
214
+ // via `camstack deploy` (CLI tarball upload), bypassing this
215
+ // bootstrap entirely.
216
+ console.log('[launcher] Checking required packages...');
217
+ // Install source resolution:
218
+ // CAMSTACK_INSTALL_SOURCE env: 'npm' | 'local' | 'symlink' | undefined.
219
+ // CAMSTACK_BUNDLED_ADDONS_DIR: Electron path, forces 'local'.
220
+ // bootstrap.installSource (config.yaml): same set as env. Env wins.
221
+ const rawEnvSource = process.env['CAMSTACK_INSTALL_SOURCE'];
222
+ const yamlSource = readBootstrapInstallSource(dataDir);
223
+ const explicitSource = parseInstallSource(rawEnvSource) ?? yamlSource;
224
+ const bundledDir = process.env['CAMSTACK_BUNDLED_ADDONS_DIR'];
225
+ let workspaceDir = null;
226
+ let resolvedSource = explicitSource;
227
+ if (bundledDir && fs.existsSync(bundledDir)) {
228
+ workspaceDir = bundledDir;
229
+ resolvedSource = 'local';
230
+ console.log(`[launcher] Using bundled addons from ${bundledDir}`);
231
+ }
232
+ else if (explicitSource === 'local' || explicitSource === 'symlink') {
233
+ workspaceDir = (0, kernel_1.detectWorkspacePackagesDir)(__dirname);
234
+ if (workspaceDir === null) {
235
+ console.warn(`[launcher] installSource=${explicitSource} requested but no workspace ` +
236
+ `packages/ dir found from ${__dirname} — falling back to 'npm'`);
237
+ resolvedSource = 'npm';
238
+ }
239
+ }
240
+ const installer = new kernel_1.AddonInstaller({
241
+ addonsDir,
242
+ workspacePackagesDir: workspaceDir ?? undefined,
243
+ installSource: resolvedSource,
244
+ });
245
+ // bootstrap.requiredAddons from config.yaml — if set, REPLACES the
246
+ // kernel's hard-coded REQUIRED_PACKAGES. The kernel never reaches into
247
+ // SQL before this list is installed; everything here must be a known
248
+ // package name that can be resolved from the workspace, the bundle, or
249
+ // npm. Default (undefined) → fall back to the in-kernel constant.
250
+ const bootstrapRequired = readBootstrapRequiredAddons(dataDir);
251
+ if (bootstrapRequired !== null) {
252
+ console.log(`[launcher] bootstrap.requiredAddons from config.yaml: ${bootstrapRequired.length} packages`);
253
+ await installer.ensureRequiredPackages(bootstrapRequired);
254
+ }
255
+ else {
256
+ await installer.ensureRequiredPackages();
257
+ }
258
+ // Self-contained addon bundles (build preset `self-contained`) inline
259
+ // @camstack/types + zod + @camstack/sdk into each addon's dist. The
260
+ // hub no longer plants peer-dep symlinks under
261
+ // addonsDir/node_modules/@camstack/ — addons resolve everything from
262
+ // their own bundle. Kept the serverDir derivation in case future
263
+ // tooling needs it (NODE_PATH extension below still uses it).
264
+ const serverDir = path.resolve(__dirname, '..');
265
+ const nodeModulesDir = path.join(serverDir, 'node_modules');
266
+ // Extend Node's module resolution so addons in `data/addons/`
267
+ // (which sit outside the server tree on packaged builds — e.g.
268
+ // `~/Library/Application Support/.../data/addons/`) can resolve
269
+ // third-party peer deps from the hub's own `node_modules`.
270
+ //
271
+ // Why: an addon's runtime file `data/addons/@scope/<x>/dist/x.js`
272
+ // walks UP looking for `node_modules/<pkg>`. With user-data
273
+ // outside the workspace, the walk dead-ends well before hitting
274
+ // the hub's tree. NODE_PATH instructs Node to ALSO check the
275
+ // listed dirs after the regular walk fails.
276
+ //
277
+ // The workspace-root node_modules holds hoisted deps (zod, werift,
278
+ // etc); the server-local node_modules has direct deps. Listing
279
+ // both covers every realistic resolution.
280
+ const workspaceRootNodeModules = path.resolve(serverDir, '..', '..', 'node_modules');
281
+ const extraNodePaths = [nodeModulesDir, workspaceRootNodeModules].filter((p) => fs.existsSync(p));
282
+ if (extraNodePaths.length > 0) {
283
+ const sep = process.platform === 'win32' ? ';' : ':';
284
+ process.env['NODE_PATH'] = process.env['NODE_PATH']
285
+ ? `${process.env['NODE_PATH']}${sep}${extraNodePaths.join(sep)}`
286
+ : extraNodePaths.join(sep);
287
+ // Re-init Node's module path cache so the change takes effect for
288
+ // subsequent require()/import() calls. Without this the resolver
289
+ // already cached the empty list at startup.
290
+ const Module = require('node:module');
291
+ Module._initPaths();
292
+ console.log(`[launcher] NODE_PATH extended with: ${extraNodePaths.join(sep)}`);
293
+ }
294
+ // Now safe to load main.ts (which has static imports from @camstack/core)
295
+ console.log('[launcher] Starting server...');
296
+ await Promise.resolve().then(() => __importStar(require('./main')));
297
+ }
298
+ // Signal handlers — forward to default exit so NestJS shutdown hooks
299
+ // (Moleculer broker stopped() → kills spawned workers) run cleanly.
300
+ // Without these, TTY close / `npm run serve` kill leaves workers orphaned.
301
+ let shuttingDown = false;
302
+ const handleSignal = (signal) => {
303
+ if (shuttingDown)
304
+ return;
305
+ shuttingDown = true;
306
+ console.log(`[launcher] Received ${signal} — shutting down`);
307
+ process.exit(0);
308
+ };
309
+ process.on('SIGHUP', handleSignal);
310
+ process.on('SIGTERM', handleSignal);
311
+ process.on('SIGINT', handleSignal);
312
+ // Parent-death watchdog (macOS: no PR_SET_PDEATHSIG). If tsx watch / npm
313
+ // get orphaned to init, self-destruct so NestJS shutdown hooks fire before
314
+ // the process tree turns into a zombie.
315
+ const initialPpid = process.ppid;
316
+ setInterval(() => {
317
+ if (process.ppid === 1 && initialPpid !== 1) {
318
+ console.error('[launcher] Parent died (reparented to init) — exiting');
319
+ process.exit(0);
320
+ }
321
+ }, 2000).unref();
322
+ launch().catch((err) => {
323
+ console.error('[launcher] FATAL:', err);
324
+ process.exit(1);
325
+ });