@camstack/kernel 0.1.7 → 0.1.9
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.
- package/dist/addon-installer-2BW2KLQD.mjs +7 -0
- package/dist/chunk-67QMERMP.mjs +411 -0
- package/dist/chunk-67QMERMP.mjs.map +1 -0
- package/dist/chunk-S5YWNNPK.mjs +135 -0
- package/dist/{chunk-RHK5CCAL.mjs.map → chunk-S5YWNNPK.mjs.map} +1 -1
- package/dist/index.d.mts +645 -0
- package/dist/index.d.ts +645 -0
- package/dist/index.js +1746 -2037
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1253 -1462
- package/dist/index.mjs.map +1 -1
- package/dist/worker/addon-worker-entry.d.mts +2 -0
- package/dist/worker/addon-worker-entry.d.ts +2 -0
- package/dist/worker/addon-worker-entry.js +300 -430
- package/dist/worker/addon-worker-entry.js.map +1 -1
- package/dist/worker/addon-worker-entry.mjs +4 -8
- package/dist/worker/addon-worker-entry.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/addon-installer-WQBOEZQT.mjs +0 -6
- package/dist/chunk-GJ3DKNOD.mjs +0 -494
- package/dist/chunk-GJ3DKNOD.mjs.map +0 -1
- package/dist/chunk-LZOMFHX3.mjs +0 -38
- package/dist/chunk-LZOMFHX3.mjs.map +0 -1
- package/dist/chunk-RHK5CCAL.mjs +0 -154
- /package/dist/{addon-installer-WQBOEZQT.mjs.map → addon-installer-2BW2KLQD.mjs.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -5,9 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
10
|
-
};
|
|
11
8
|
var __export = (target, all) => {
|
|
12
9
|
for (var name in all)
|
|
13
10
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -30,2125 +27,1837 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
27
|
));
|
|
31
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
29
|
|
|
33
|
-
// src/
|
|
34
|
-
var
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
AddonEngineManager: () => AddonEngineManager,
|
|
34
|
+
AddonInstaller: () => AddonInstaller,
|
|
35
|
+
AddonLoader: () => AddonLoader,
|
|
36
|
+
AddonWorkerHost: () => AddonWorkerHost,
|
|
37
|
+
CapabilityRegistry: () => CapabilityRegistry,
|
|
38
|
+
ConfigManager: () => ConfigManager,
|
|
39
|
+
DEFAULT_DATA_PATH: () => DEFAULT_DATA_PATH,
|
|
40
|
+
INFRA_CAPABILITIES: () => INFRA_CAPABILITIES,
|
|
41
|
+
RUNTIME_DEFAULTS: () => RUNTIME_DEFAULTS,
|
|
42
|
+
WorkerProcessManager: () => WorkerProcessManager,
|
|
43
|
+
bootstrapSchema: () => bootstrapSchema,
|
|
44
|
+
copyDirRecursive: () => copyDirRecursive,
|
|
45
|
+
copyExtraFileDirs: () => copyExtraFileDirs,
|
|
46
|
+
detectWorkspacePackagesDir: () => detectWorkspacePackagesDir,
|
|
47
|
+
ensureDir: () => ensureDir,
|
|
48
|
+
ensureLibraryBuilt: () => ensureLibraryBuilt,
|
|
49
|
+
installPackageFromNpmSync: () => installPackageFromNpmSync,
|
|
50
|
+
isInfraCapability: () => isInfraCapability,
|
|
51
|
+
isSourceNewer: () => isSourceNewer,
|
|
52
|
+
stripCamstackDeps: () => stripCamstackDeps,
|
|
53
|
+
symlinkAddonsToNodeModules: () => symlinkAddonsToNodeModules
|
|
54
|
+
});
|
|
55
|
+
module.exports = __toCommonJS(src_exports);
|
|
56
|
+
|
|
57
|
+
// src/addon-loader.ts
|
|
58
|
+
var fs = __toESM(require("fs"));
|
|
59
|
+
var path = __toESM(require("path"));
|
|
60
|
+
function resolveAddonClass(mod) {
|
|
61
|
+
let candidate = mod["default"] ?? mod[Object.keys(mod)[0]];
|
|
62
|
+
if (candidate && typeof candidate === "object" && "default" in candidate) {
|
|
63
|
+
candidate = candidate["default"];
|
|
64
|
+
}
|
|
65
|
+
return typeof candidate === "function" ? candidate : void 0;
|
|
66
|
+
}
|
|
67
|
+
var AddonLoader = class {
|
|
68
|
+
addons = /* @__PURE__ */ new Map();
|
|
69
|
+
/** Scan addons directory and load all addon packages.
|
|
70
|
+
* Supports scoped layout: addons/@scope/package-name/ */
|
|
71
|
+
async loadFromDirectory(addonsDir) {
|
|
72
|
+
if (!fs.existsSync(addonsDir)) return;
|
|
73
|
+
const entries = fs.readdirSync(addonsDir, { withFileTypes: true });
|
|
74
|
+
for (const entry of entries) {
|
|
75
|
+
if (!entry.isDirectory()) continue;
|
|
76
|
+
if (entry.name.startsWith("@")) {
|
|
77
|
+
const scopeDir = path.join(addonsDir, entry.name);
|
|
78
|
+
const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
79
|
+
for (const scopeEntry of scopeEntries) {
|
|
80
|
+
if (!scopeEntry.isDirectory()) continue;
|
|
81
|
+
await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
await this.tryLoadAddon(path.join(addonsDir, entry.name));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async tryLoadAddon(addonDir) {
|
|
89
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
90
|
+
if (!fs.existsSync(pkgJsonPath)) return;
|
|
91
|
+
try {
|
|
92
|
+
await this.loadFromAddonDir(addonDir);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
console.warn(`Failed to load addon from ${addonDir}: ${err}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Load addon from a specific directory (package.json + dist/) */
|
|
98
|
+
async loadFromAddonDir(addonDir) {
|
|
99
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
100
|
+
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
101
|
+
const packageName = pkgJson["name"];
|
|
102
|
+
const packageVersion = pkgJson["version"] ?? "0.0.0";
|
|
103
|
+
const manifest = pkgJson["camstack"];
|
|
104
|
+
if (!manifest?.addons?.length) return;
|
|
105
|
+
for (const declaration of manifest.addons) {
|
|
106
|
+
const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
|
|
107
|
+
let entryPath = path.resolve(addonDir, entryFile);
|
|
108
|
+
if (!fs.existsSync(entryPath)) {
|
|
109
|
+
const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
|
|
110
|
+
const alternatives = [
|
|
111
|
+
`${base}.cjs`,
|
|
112
|
+
`${base}.mjs`,
|
|
113
|
+
path.resolve(addonDir, "dist", "index.js"),
|
|
114
|
+
path.resolve(addonDir, "dist", "index.cjs"),
|
|
115
|
+
path.resolve(addonDir, "dist", "index.mjs"),
|
|
116
|
+
path.resolve(addonDir, declaration.entry)
|
|
117
|
+
];
|
|
118
|
+
entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
|
|
119
|
+
}
|
|
120
|
+
if (!fs.existsSync(entryPath)) {
|
|
121
|
+
throw new Error(`Entry not found: ${entryPath}`);
|
|
122
|
+
}
|
|
123
|
+
const mod = await import(entryPath);
|
|
124
|
+
const AddonClass = resolveAddonClass(mod);
|
|
125
|
+
if (!AddonClass) {
|
|
126
|
+
throw new Error(`No addon class in ${entryPath}`);
|
|
127
|
+
}
|
|
128
|
+
this.addons.set(declaration.id, {
|
|
129
|
+
declaration,
|
|
130
|
+
packageName,
|
|
131
|
+
packageVersion,
|
|
132
|
+
packageDisplayName: manifest.displayName,
|
|
133
|
+
addonClass: AddonClass
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Load addon from a direct path (for development/testing) */
|
|
138
|
+
async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
|
|
139
|
+
const mod = await import(modulePath);
|
|
140
|
+
const AddonClass = resolveAddonClass(mod);
|
|
141
|
+
if (!AddonClass) {
|
|
142
|
+
throw new Error(`Module ${modulePath} has no default export`);
|
|
143
|
+
}
|
|
144
|
+
this.addons.set(addonId, {
|
|
145
|
+
declaration: {
|
|
146
|
+
id: addonId,
|
|
147
|
+
entry: modulePath,
|
|
148
|
+
slot: "detector",
|
|
149
|
+
...declaration
|
|
150
|
+
},
|
|
151
|
+
packageName,
|
|
152
|
+
packageVersion,
|
|
153
|
+
addonClass: AddonClass
|
|
54
154
|
});
|
|
55
|
-
var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
|
|
56
|
-
var ownKeys = function(o) {
|
|
57
|
-
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
58
|
-
var ar = [];
|
|
59
|
-
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
60
|
-
return ar;
|
|
61
|
-
};
|
|
62
|
-
return ownKeys(o);
|
|
63
|
-
};
|
|
64
|
-
return function(mod) {
|
|
65
|
-
if (mod && mod.__esModule) return mod;
|
|
66
|
-
var result = {};
|
|
67
|
-
if (mod != null) {
|
|
68
|
-
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
69
|
-
}
|
|
70
|
-
__setModuleDefault(result, mod);
|
|
71
|
-
return result;
|
|
72
|
-
};
|
|
73
|
-
})();
|
|
74
|
-
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
75
|
-
exports2.AddonLoader = void 0;
|
|
76
|
-
var fs = __importStar(require("fs"));
|
|
77
|
-
var path = __importStar(require("path"));
|
|
78
|
-
function resolveAddonClass(mod) {
|
|
79
|
-
let candidate = mod["default"] ?? mod[Object.keys(mod)[0]];
|
|
80
|
-
if (candidate && typeof candidate === "object" && "default" in candidate) {
|
|
81
|
-
candidate = candidate["default"];
|
|
82
|
-
}
|
|
83
|
-
return typeof candidate === "function" ? candidate : void 0;
|
|
84
|
-
}
|
|
85
|
-
var AddonLoader2 = class {
|
|
86
|
-
addons = /* @__PURE__ */ new Map();
|
|
87
|
-
/** Scan addons directory and load all addon packages.
|
|
88
|
-
* Supports scoped layout: addons/@scope/package-name/ */
|
|
89
|
-
async loadFromDirectory(addonsDir) {
|
|
90
|
-
if (!fs.existsSync(addonsDir))
|
|
91
|
-
return;
|
|
92
|
-
const entries = fs.readdirSync(addonsDir, { withFileTypes: true });
|
|
93
|
-
for (const entry of entries) {
|
|
94
|
-
if (!entry.isDirectory())
|
|
95
|
-
continue;
|
|
96
|
-
if (entry.name.startsWith("@")) {
|
|
97
|
-
const scopeDir = path.join(addonsDir, entry.name);
|
|
98
|
-
const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
99
|
-
for (const scopeEntry of scopeEntries) {
|
|
100
|
-
if (!scopeEntry.isDirectory())
|
|
101
|
-
continue;
|
|
102
|
-
await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
|
|
103
|
-
}
|
|
104
|
-
continue;
|
|
105
|
-
}
|
|
106
|
-
await this.tryLoadAddon(path.join(addonsDir, entry.name));
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
async tryLoadAddon(addonDir) {
|
|
110
|
-
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
111
|
-
if (!fs.existsSync(pkgJsonPath))
|
|
112
|
-
return;
|
|
113
|
-
try {
|
|
114
|
-
await this.loadFromAddonDir(addonDir);
|
|
115
|
-
} catch (err) {
|
|
116
|
-
console.warn(`Failed to load addon from ${addonDir}: ${err}`);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
/** Load addon from a specific directory (package.json + dist/) */
|
|
120
|
-
async loadFromAddonDir(addonDir) {
|
|
121
|
-
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
122
|
-
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
123
|
-
const packageName = pkgJson["name"];
|
|
124
|
-
const packageVersion = pkgJson["version"] ?? "0.0.0";
|
|
125
|
-
const manifest = pkgJson["camstack"];
|
|
126
|
-
if (!manifest?.addons?.length)
|
|
127
|
-
return;
|
|
128
|
-
for (const declaration of manifest.addons) {
|
|
129
|
-
const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
|
|
130
|
-
let entryPath = path.resolve(addonDir, entryFile);
|
|
131
|
-
if (!fs.existsSync(entryPath)) {
|
|
132
|
-
const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
|
|
133
|
-
const alternatives = [
|
|
134
|
-
`${base}.cjs`,
|
|
135
|
-
`${base}.mjs`,
|
|
136
|
-
path.resolve(addonDir, "dist", "index.js"),
|
|
137
|
-
path.resolve(addonDir, "dist", "index.cjs"),
|
|
138
|
-
path.resolve(addonDir, "dist", "index.mjs"),
|
|
139
|
-
path.resolve(addonDir, declaration.entry)
|
|
140
|
-
];
|
|
141
|
-
entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
|
|
142
|
-
}
|
|
143
|
-
if (!fs.existsSync(entryPath)) {
|
|
144
|
-
throw new Error(`Entry not found: ${entryPath}`);
|
|
145
|
-
}
|
|
146
|
-
const mod = await Promise.resolve(`${entryPath}`).then((s) => __importStar(require(s)));
|
|
147
|
-
const AddonClass = resolveAddonClass(mod);
|
|
148
|
-
if (!AddonClass) {
|
|
149
|
-
throw new Error(`No addon class in ${entryPath}`);
|
|
150
|
-
}
|
|
151
|
-
this.addons.set(declaration.id, {
|
|
152
|
-
declaration,
|
|
153
|
-
packageName,
|
|
154
|
-
packageVersion,
|
|
155
|
-
packageDisplayName: manifest.displayName,
|
|
156
|
-
addonClass: AddonClass
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
/** Load addon from a direct path (for development/testing) */
|
|
161
|
-
async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
|
|
162
|
-
const mod = await Promise.resolve(`${modulePath}`).then((s) => __importStar(require(s)));
|
|
163
|
-
const AddonClass = resolveAddonClass(mod);
|
|
164
|
-
if (!AddonClass) {
|
|
165
|
-
throw new Error(`Module ${modulePath} has no default export`);
|
|
166
|
-
}
|
|
167
|
-
this.addons.set(addonId, {
|
|
168
|
-
declaration: {
|
|
169
|
-
id: addonId,
|
|
170
|
-
entry: modulePath,
|
|
171
|
-
slot: "detector",
|
|
172
|
-
...declaration
|
|
173
|
-
},
|
|
174
|
-
packageName,
|
|
175
|
-
packageVersion,
|
|
176
|
-
addonClass: AddonClass
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
/** Get a registered addon by ID */
|
|
180
|
-
getAddon(addonId) {
|
|
181
|
-
return this.addons.get(addonId);
|
|
182
|
-
}
|
|
183
|
-
/** List all registered addons */
|
|
184
|
-
listAddons() {
|
|
185
|
-
return [...this.addons.values()];
|
|
186
|
-
}
|
|
187
|
-
/** Check if an addon is registered */
|
|
188
|
-
hasAddon(addonId) {
|
|
189
|
-
return this.addons.has(addonId);
|
|
190
|
-
}
|
|
191
|
-
/** Create a new instance of an addon (not yet initialized) */
|
|
192
|
-
createInstance(addonId) {
|
|
193
|
-
const registered = this.addons.get(addonId);
|
|
194
|
-
if (!registered) {
|
|
195
|
-
throw new Error(`Addon "${addonId}" is not registered`);
|
|
196
|
-
}
|
|
197
|
-
return new registered.addonClass();
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
exports2.AddonLoader = AddonLoader2;
|
|
201
155
|
}
|
|
202
|
-
|
|
156
|
+
/** Get a registered addon by ID */
|
|
157
|
+
getAddon(addonId) {
|
|
158
|
+
return this.addons.get(addonId);
|
|
159
|
+
}
|
|
160
|
+
/** List all registered addons */
|
|
161
|
+
listAddons() {
|
|
162
|
+
return [...this.addons.values()];
|
|
163
|
+
}
|
|
164
|
+
/** Check if an addon is registered */
|
|
165
|
+
hasAddon(addonId) {
|
|
166
|
+
return this.addons.has(addonId);
|
|
167
|
+
}
|
|
168
|
+
/** Create a new instance of an addon (not yet initialized) */
|
|
169
|
+
createInstance(addonId) {
|
|
170
|
+
const registered = this.addons.get(addonId);
|
|
171
|
+
if (!registered) {
|
|
172
|
+
throw new Error(`Addon "${addonId}" is not registered`);
|
|
173
|
+
}
|
|
174
|
+
return new registered.addonClass();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
203
177
|
|
|
204
|
-
// src/addon-engine-manager.
|
|
205
|
-
var
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
var node_crypto_1 = require("crypto");
|
|
211
|
-
var AddonEngineManager2 = class {
|
|
212
|
-
loader;
|
|
213
|
-
baseContext;
|
|
214
|
-
engines = /* @__PURE__ */ new Map();
|
|
215
|
-
constructor(loader, baseContext) {
|
|
216
|
-
this.loader = loader;
|
|
217
|
-
this.baseContext = baseContext;
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* Get or create an addon engine for the given effective config.
|
|
221
|
-
* Cameras with the same addonId + effective config share the same engine.
|
|
222
|
-
*/
|
|
223
|
-
async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
|
|
224
|
-
const effectiveConfig = { ...globalConfig, ...cameraOverride };
|
|
225
|
-
const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
226
|
-
const existing = this.engines.get(configKey);
|
|
227
|
-
if (existing)
|
|
228
|
-
return existing;
|
|
229
|
-
const addon = this.loader.createInstance(addonId);
|
|
230
|
-
await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
|
|
231
|
-
this.engines.set(configKey, addon);
|
|
232
|
-
return addon;
|
|
233
|
-
}
|
|
234
|
-
/** Get all active engines */
|
|
235
|
-
getActiveEngines() {
|
|
236
|
-
return new Map(this.engines);
|
|
237
|
-
}
|
|
238
|
-
/** Shutdown a specific engine by its config key */
|
|
239
|
-
async shutdownEngine(configKey) {
|
|
240
|
-
const engine = this.engines.get(configKey);
|
|
241
|
-
if (engine) {
|
|
242
|
-
await engine.shutdown();
|
|
243
|
-
this.engines.delete(configKey);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
/** Shutdown all engines */
|
|
247
|
-
async shutdownAll() {
|
|
248
|
-
for (const [, engine] of this.engines) {
|
|
249
|
-
await engine.shutdown();
|
|
250
|
-
}
|
|
251
|
-
this.engines.clear();
|
|
252
|
-
}
|
|
253
|
-
/** Compute a deterministic config key (visible for tests) */
|
|
254
|
-
computeConfigKey(addonId, effectiveConfig) {
|
|
255
|
-
return `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
256
|
-
}
|
|
257
|
-
hashConfig(config) {
|
|
258
|
-
const sorted = JSON.stringify(config, Object.keys(config).sort());
|
|
259
|
-
return (0, node_crypto_1.createHash)("md5").update(sorted).digest("hex").slice(0, 12);
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
exports2.AddonEngineManager = AddonEngineManager2;
|
|
178
|
+
// src/addon-engine-manager.ts
|
|
179
|
+
var import_node_crypto = require("crypto");
|
|
180
|
+
var AddonEngineManager = class {
|
|
181
|
+
constructor(loader, baseContext) {
|
|
182
|
+
this.loader = loader;
|
|
183
|
+
this.baseContext = baseContext;
|
|
263
184
|
}
|
|
264
|
-
|
|
185
|
+
engines = /* @__PURE__ */ new Map();
|
|
186
|
+
/**
|
|
187
|
+
* Get or create an addon engine for the given effective config.
|
|
188
|
+
* Cameras with the same addonId + effective config share the same engine.
|
|
189
|
+
*/
|
|
190
|
+
async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
|
|
191
|
+
const effectiveConfig = { ...globalConfig, ...cameraOverride };
|
|
192
|
+
const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
193
|
+
const existing = this.engines.get(configKey);
|
|
194
|
+
if (existing) return existing;
|
|
195
|
+
const addon = this.loader.createInstance(addonId);
|
|
196
|
+
await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
|
|
197
|
+
this.engines.set(configKey, addon);
|
|
198
|
+
return addon;
|
|
199
|
+
}
|
|
200
|
+
/** Get all active engines */
|
|
201
|
+
getActiveEngines() {
|
|
202
|
+
return new Map(this.engines);
|
|
203
|
+
}
|
|
204
|
+
/** Shutdown a specific engine by its config key */
|
|
205
|
+
async shutdownEngine(configKey) {
|
|
206
|
+
const engine = this.engines.get(configKey);
|
|
207
|
+
if (engine) {
|
|
208
|
+
await engine.shutdown();
|
|
209
|
+
this.engines.delete(configKey);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** Shutdown all engines */
|
|
213
|
+
async shutdownAll() {
|
|
214
|
+
for (const [, engine] of this.engines) {
|
|
215
|
+
await engine.shutdown();
|
|
216
|
+
}
|
|
217
|
+
this.engines.clear();
|
|
218
|
+
}
|
|
219
|
+
/** Compute a deterministic config key (visible for tests) */
|
|
220
|
+
computeConfigKey(addonId, effectiveConfig) {
|
|
221
|
+
return `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
222
|
+
}
|
|
223
|
+
hashConfig(config) {
|
|
224
|
+
const sorted = JSON.stringify(config, Object.keys(config).sort());
|
|
225
|
+
return (0, import_node_crypto.createHash)("md5").update(sorted).digest("hex").slice(0, 12);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
265
228
|
|
|
266
|
-
// src/
|
|
267
|
-
var
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
229
|
+
// src/addon-installer.ts
|
|
230
|
+
var import_node_child_process2 = require("child_process");
|
|
231
|
+
var import_node_util = require("util");
|
|
232
|
+
var fs3 = __toESM(require("fs"));
|
|
233
|
+
var path3 = __toESM(require("path"));
|
|
234
|
+
var os2 = __toESM(require("os"));
|
|
235
|
+
|
|
236
|
+
// src/fs-utils.ts
|
|
237
|
+
var import_node_child_process = require("child_process");
|
|
238
|
+
var fs2 = __toESM(require("fs"));
|
|
239
|
+
var os = __toESM(require("os"));
|
|
240
|
+
var path2 = __toESM(require("path"));
|
|
241
|
+
function ensureDir(dirPath) {
|
|
242
|
+
fs2.mkdirSync(dirPath, { recursive: true });
|
|
243
|
+
}
|
|
244
|
+
function copyDirRecursive(src, dest) {
|
|
245
|
+
ensureDir(dest);
|
|
246
|
+
const entries = fs2.readdirSync(src, { withFileTypes: true });
|
|
247
|
+
for (const entry of entries) {
|
|
248
|
+
const srcPath = path2.join(src, entry.name);
|
|
249
|
+
const destPath = path2.join(dest, entry.name);
|
|
250
|
+
if (entry.isDirectory()) {
|
|
251
|
+
copyDirRecursive(srcPath, destPath);
|
|
252
|
+
} else {
|
|
253
|
+
fs2.copyFileSync(srcPath, destPath);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function stripCamstackDeps(pkg) {
|
|
258
|
+
const result = { ...pkg };
|
|
259
|
+
for (const depType of ["dependencies", "peerDependencies", "devDependencies"]) {
|
|
260
|
+
const deps = result[depType];
|
|
261
|
+
if (deps) {
|
|
262
|
+
const filtered = {};
|
|
263
|
+
for (const [name, version] of Object.entries(deps)) {
|
|
264
|
+
if (!name.startsWith("@camstack/")) {
|
|
265
|
+
filtered[name] = version;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
result[depType] = Object.keys(filtered).length > 0 ? filtered : void 0;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
delete result.devDependencies;
|
|
272
|
+
return result;
|
|
273
|
+
}
|
|
274
|
+
function copyExtraFileDirs(pkgJson, sourceDir, destDir) {
|
|
275
|
+
const files = pkgJson.files;
|
|
276
|
+
if (!files) return;
|
|
277
|
+
for (const fileEntry of files) {
|
|
278
|
+
if (fileEntry === "dist" || fileEntry.includes("*")) continue;
|
|
279
|
+
const srcPath = path2.join(sourceDir, fileEntry);
|
|
280
|
+
if (!fs2.existsSync(srcPath)) continue;
|
|
281
|
+
const destPath = path2.join(destDir, fileEntry);
|
|
282
|
+
const stat = fs2.statSync(srcPath);
|
|
283
|
+
if (stat.isDirectory()) {
|
|
284
|
+
copyDirRecursive(srcPath, destPath);
|
|
285
|
+
} else if (stat.isFile()) {
|
|
286
|
+
ensureDir(path2.dirname(destPath));
|
|
287
|
+
fs2.copyFileSync(srcPath, destPath);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function symlinkAddonsToNodeModules(addonsDir, nodeModulesDir) {
|
|
292
|
+
const camstackDir = path2.join(nodeModulesDir, "@camstack");
|
|
293
|
+
ensureDir(camstackDir);
|
|
294
|
+
const packagesToLink = ["core"];
|
|
295
|
+
for (const pkg of packagesToLink) {
|
|
296
|
+
const addonDir = path2.join(addonsDir, "@camstack", pkg);
|
|
297
|
+
const linkPath = path2.join(camstackDir, pkg);
|
|
298
|
+
if (!fs2.existsSync(addonDir)) continue;
|
|
299
|
+
try {
|
|
300
|
+
const stat = fs2.lstatSync(linkPath);
|
|
301
|
+
if (stat.isSymbolicLink() || stat.isDirectory()) {
|
|
302
|
+
fs2.rmSync(linkPath, { recursive: true, force: true });
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
305
|
+
}
|
|
306
|
+
fs2.symlinkSync(addonDir, linkPath, "dir");
|
|
307
|
+
console.log(`[symlink] node_modules/@camstack/${pkg} -> ${addonDir}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function isSourceNewer(packageDir) {
|
|
311
|
+
const srcDir = path2.join(packageDir, "src");
|
|
312
|
+
const distDir = path2.join(packageDir, "dist");
|
|
313
|
+
if (!fs2.existsSync(srcDir) || !fs2.existsSync(distDir)) return true;
|
|
314
|
+
try {
|
|
315
|
+
const distMtime = fs2.statSync(distDir).mtimeMs;
|
|
316
|
+
const entries = fs2.readdirSync(srcDir, { withFileTypes: true, recursive: true });
|
|
317
|
+
for (const entry of entries) {
|
|
318
|
+
if (!entry.isFile()) continue;
|
|
319
|
+
const filePath = path2.join(entry.parentPath ?? entry.path, entry.name);
|
|
320
|
+
if (fs2.statSync(filePath).mtimeMs > distMtime) return true;
|
|
321
|
+
}
|
|
322
|
+
return false;
|
|
323
|
+
} catch {
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function ensureLibraryBuilt(packageName, packagesDir) {
|
|
328
|
+
const dirName = packageName.replace("@camstack/", "");
|
|
329
|
+
const sourceDir = path2.join(packagesDir, dirName);
|
|
330
|
+
if (!fs2.existsSync(sourceDir)) return;
|
|
331
|
+
const distDir = path2.join(sourceDir, "dist");
|
|
332
|
+
const hasIndex = fs2.existsSync(path2.join(distDir, "index.js")) || fs2.existsSync(path2.join(distDir, "index.mjs"));
|
|
333
|
+
if (hasIndex) return;
|
|
334
|
+
console.warn(`[ensureLibraryBuilt] ${packageName} has no dist/ \u2014 run 'npm run build' first`);
|
|
335
|
+
}
|
|
336
|
+
function installPackageFromNpmSync(packageName, targetDir) {
|
|
337
|
+
const tmpDir = fs2.mkdtempSync(path2.join(os.tmpdir(), "camstack-install-"));
|
|
338
|
+
try {
|
|
339
|
+
const stdout = (0, import_node_child_process.execFileSync)("npm", ["pack", packageName, "--pack-destination", tmpDir], {
|
|
340
|
+
timeout: 12e4,
|
|
341
|
+
encoding: "utf-8"
|
|
287
342
|
});
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
343
|
+
const tgzFilename = stdout.trim().split("\n").pop()?.trim();
|
|
344
|
+
if (!tgzFilename) throw new Error("npm pack produced no output");
|
|
345
|
+
const tgzPath = path2.join(tmpDir, tgzFilename);
|
|
346
|
+
const extractDir = path2.join(tmpDir, "extracted");
|
|
347
|
+
ensureDir(extractDir);
|
|
348
|
+
(0, import_node_child_process.execFileSync)("tar", ["-xzf", tgzPath, "-C", extractDir], { timeout: 3e4 });
|
|
349
|
+
const packageSubDir = path2.join(extractDir, "package");
|
|
350
|
+
const srcPkgJsonDir = fs2.existsSync(path2.join(packageSubDir, "package.json")) ? packageSubDir : extractDir;
|
|
351
|
+
fs2.rmSync(targetDir, { recursive: true, force: true });
|
|
352
|
+
ensureDir(targetDir);
|
|
353
|
+
fs2.copyFileSync(path2.join(srcPkgJsonDir, "package.json"), path2.join(targetDir, "package.json"));
|
|
354
|
+
const distSrc = path2.join(srcPkgJsonDir, "dist");
|
|
355
|
+
if (fs2.existsSync(distSrc)) {
|
|
356
|
+
copyDirRecursive(distSrc, path2.join(targetDir, "dist"));
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
const npmPkg = JSON.parse(fs2.readFileSync(path2.join(srcPkgJsonDir, "package.json"), "utf-8"));
|
|
360
|
+
copyExtraFileDirs(npmPkg, srcPkgJsonDir, targetDir);
|
|
361
|
+
} catch {
|
|
362
|
+
}
|
|
363
|
+
} finally {
|
|
364
|
+
fs2.rmSync(tmpDir, { recursive: true, force: true });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/addon-installer.ts
|
|
369
|
+
var execFileAsync = (0, import_node_util.promisify)(import_node_child_process2.execFile);
|
|
370
|
+
var AddonInstaller = class _AddonInstaller {
|
|
371
|
+
addonsDir;
|
|
372
|
+
registry;
|
|
373
|
+
workspacePackagesDir;
|
|
374
|
+
constructor(config) {
|
|
375
|
+
this.addonsDir = config.addonsDir;
|
|
376
|
+
this.registry = config.registry;
|
|
377
|
+
this.workspacePackagesDir = config.workspacePackagesDir;
|
|
378
|
+
}
|
|
379
|
+
/** Required addon packages that must be installed for the server to function */
|
|
380
|
+
static REQUIRED_PACKAGES = [
|
|
381
|
+
"@camstack/core",
|
|
382
|
+
"@camstack/addon-stream-broker",
|
|
383
|
+
"@camstack/addon-recording",
|
|
384
|
+
"@camstack/addon-vision",
|
|
385
|
+
"@camstack/addon-admin-ui",
|
|
386
|
+
"@camstack/addon-webrtc-adaptive",
|
|
387
|
+
"@camstack/addon-analytics",
|
|
388
|
+
"@camstack/addon-scene-intelligence",
|
|
389
|
+
"@camstack/addon-advanced-notifier"
|
|
390
|
+
];
|
|
391
|
+
/** Ensure the addons directory exists */
|
|
392
|
+
async initialize() {
|
|
393
|
+
ensureDir(this.addonsDir);
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Ensure all required packages are installed in the addons directory.
|
|
397
|
+
* This replaces the standalone first-boot-installer.ts.
|
|
398
|
+
*/
|
|
399
|
+
async ensureRequiredPackages() {
|
|
400
|
+
ensureDir(this.addonsDir);
|
|
401
|
+
if (this.workspacePackagesDir) {
|
|
402
|
+
console.log(`[AddonInstaller] Workspace detected: ${this.workspacePackagesDir}`);
|
|
403
|
+
ensureLibraryBuilt("@camstack/kernel", this.workspacePackagesDir);
|
|
404
|
+
ensureLibraryBuilt("@camstack/types", this.workspacePackagesDir);
|
|
405
|
+
}
|
|
406
|
+
for (const packageName of _AddonInstaller.REQUIRED_PACKAGES) {
|
|
407
|
+
const addonDir = path3.join(this.addonsDir, packageName);
|
|
408
|
+
const pkgJsonPath = path3.join(addonDir, "package.json");
|
|
409
|
+
const forceNpm = process.env["CAMSTACK_INSTALL_SOURCE"] === "npm";
|
|
410
|
+
const useWorkspace = this.workspacePackagesDir && !forceNpm;
|
|
411
|
+
if (fs3.existsSync(pkgJsonPath)) {
|
|
412
|
+
if (!useWorkspace) {
|
|
413
|
+
console.log(`[AddonInstaller] ${packageName} \u2014 already installed (npm), skipping`);
|
|
414
|
+
continue;
|
|
302
415
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
308
|
-
exports2.ensureDir = ensureDir2;
|
|
309
|
-
exports2.copyDirRecursive = copyDirRecursive2;
|
|
310
|
-
exports2.stripCamstackDeps = stripCamstackDeps2;
|
|
311
|
-
exports2.copyExtraFileDirs = copyExtraFileDirs2;
|
|
312
|
-
exports2.symlinkAddonsToNodeModules = symlinkAddonsToNodeModules2;
|
|
313
|
-
exports2.isSourceNewer = isSourceNewer2;
|
|
314
|
-
exports2.ensureLibraryBuilt = ensureLibraryBuilt2;
|
|
315
|
-
exports2.installPackageFromNpmSync = installPackageFromNpmSync2;
|
|
316
|
-
var node_child_process_1 = require("child_process");
|
|
317
|
-
var fs = __importStar(require("fs"));
|
|
318
|
-
var path = __importStar(require("path"));
|
|
319
|
-
function ensureDir2(dirPath) {
|
|
320
|
-
fs.mkdirSync(dirPath, { recursive: true });
|
|
321
|
-
}
|
|
322
|
-
function copyDirRecursive2(src, dest) {
|
|
323
|
-
ensureDir2(dest);
|
|
324
|
-
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
325
|
-
for (const entry of entries) {
|
|
326
|
-
const srcPath = path.join(src, entry.name);
|
|
327
|
-
const destPath = path.join(dest, entry.name);
|
|
328
|
-
if (entry.isDirectory()) {
|
|
329
|
-
copyDirRecursive2(srcPath, destPath);
|
|
330
|
-
} else {
|
|
331
|
-
fs.copyFileSync(srcPath, destPath);
|
|
416
|
+
const srcPkgDir = this.findWorkspacePackage(packageName);
|
|
417
|
+
if (srcPkgDir && !isSourceNewer(srcPkgDir)) {
|
|
418
|
+
console.log(`[AddonInstaller] ${packageName} \u2014 workspace up-to-date, skipping`);
|
|
419
|
+
continue;
|
|
332
420
|
}
|
|
333
421
|
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
for (const [name, version] of Object.entries(deps)) {
|
|
342
|
-
if (!name.startsWith("@camstack/")) {
|
|
343
|
-
filtered[name] = version;
|
|
344
|
-
}
|
|
422
|
+
try {
|
|
423
|
+
if (useWorkspace) {
|
|
424
|
+
const pkgDir = this.findWorkspacePackage(packageName);
|
|
425
|
+
if (pkgDir) {
|
|
426
|
+
console.log(`[AddonInstaller] ${packageName} \u2014 installing from workspace`);
|
|
427
|
+
await this.installFromWorkspace(packageName);
|
|
428
|
+
continue;
|
|
345
429
|
}
|
|
346
|
-
result[depType] = Object.keys(filtered).length > 0 ? filtered : void 0;
|
|
347
430
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
if (!files)
|
|
355
|
-
return;
|
|
356
|
-
for (const fileEntry of files) {
|
|
357
|
-
if (fileEntry === "dist" || fileEntry.includes("*"))
|
|
358
|
-
continue;
|
|
359
|
-
const srcPath = path.join(sourceDir, fileEntry);
|
|
360
|
-
if (!fs.existsSync(srcPath))
|
|
361
|
-
continue;
|
|
362
|
-
const destPath = path.join(destDir, fileEntry);
|
|
363
|
-
const stat = fs.statSync(srcPath);
|
|
364
|
-
if (stat.isDirectory()) {
|
|
365
|
-
copyDirRecursive2(srcPath, destPath);
|
|
366
|
-
} else if (stat.isFile()) {
|
|
367
|
-
ensureDir2(path.dirname(destPath));
|
|
368
|
-
fs.copyFileSync(srcPath, destPath);
|
|
431
|
+
console.log(`[AddonInstaller] ${packageName} \u2014 installing from npm`);
|
|
432
|
+
await this.installFromNpm(packageName);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
435
|
+
if (packageName === "@camstack/core") {
|
|
436
|
+
throw new Error(`Required package ${packageName} failed to install: ${msg}`);
|
|
369
437
|
}
|
|
438
|
+
console.error(`[AddonInstaller] Failed to install ${packageName}: ${msg}`);
|
|
370
439
|
}
|
|
371
440
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
if (!fs.existsSync(addonDir))
|
|
380
|
-
continue;
|
|
441
|
+
}
|
|
442
|
+
findWorkspacePackage(packageName) {
|
|
443
|
+
if (!this.workspacePackagesDir) return null;
|
|
444
|
+
const shortName = packageName.replace("@camstack/", "");
|
|
445
|
+
for (const dirName of [shortName, `addon-${shortName}`, shortName.replace("addon-", "")]) {
|
|
446
|
+
const candidate = path3.join(this.workspacePackagesDir, dirName);
|
|
447
|
+
if (fs3.existsSync(path3.join(candidate, "package.json"))) {
|
|
381
448
|
try {
|
|
382
|
-
const
|
|
383
|
-
if (
|
|
384
|
-
fs.rmSync(linkPath, { recursive: true, force: true });
|
|
385
|
-
}
|
|
449
|
+
const pkg = JSON.parse(fs3.readFileSync(path3.join(candidate, "package.json"), "utf-8"));
|
|
450
|
+
if (pkg.name === packageName) return candidate;
|
|
386
451
|
} catch {
|
|
387
452
|
}
|
|
388
|
-
fs.symlinkSync(addonDir, linkPath, "dir");
|
|
389
|
-
console.log(`[symlink] node_modules/@camstack/${pkg} -> ${addonDir}`);
|
|
390
453
|
}
|
|
391
454
|
}
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
/** Install addon from a tgz file (uploaded or downloaded) */
|
|
458
|
+
async installFromTgz(tgzPath) {
|
|
459
|
+
const tmpDir = fs3.mkdtempSync(path3.join(os2.tmpdir(), "camstack-addon-install-"));
|
|
460
|
+
try {
|
|
461
|
+
await execFileAsync("tar", ["-xzf", tgzPath, "-C", tmpDir], { timeout: 3e4 });
|
|
462
|
+
const extractedDir = path3.join(tmpDir, "package");
|
|
463
|
+
const pkgJsonPath = fs3.existsSync(path3.join(extractedDir, "package.json")) ? path3.join(extractedDir, "package.json") : path3.join(tmpDir, "package.json");
|
|
464
|
+
if (!fs3.existsSync(pkgJsonPath)) {
|
|
465
|
+
throw new Error("No package.json found in tgz archive");
|
|
466
|
+
}
|
|
467
|
+
const pkgJson = JSON.parse(fs3.readFileSync(pkgJsonPath, "utf-8"));
|
|
468
|
+
if (!pkgJson.camstack?.addons) {
|
|
469
|
+
throw new Error(`Package ${pkgJson.name} has no camstack.addons manifest`);
|
|
470
|
+
}
|
|
471
|
+
const targetDir = path3.join(this.addonsDir, pkgJson.name);
|
|
472
|
+
fs3.rmSync(targetDir, { recursive: true, force: true });
|
|
473
|
+
ensureDir(targetDir);
|
|
474
|
+
const sourceDir = path3.dirname(pkgJsonPath);
|
|
475
|
+
fs3.copyFileSync(pkgJsonPath, path3.join(targetDir, "package.json"));
|
|
476
|
+
const sourceDist = path3.join(sourceDir, "dist");
|
|
477
|
+
if (fs3.existsSync(sourceDist)) {
|
|
478
|
+
copyDirRecursive(sourceDist, path3.join(targetDir, "dist"));
|
|
479
|
+
}
|
|
480
|
+
copyExtraFileDirs(pkgJson, sourceDir, targetDir);
|
|
481
|
+
return { name: pkgJson.name, version: pkgJson.version };
|
|
482
|
+
} finally {
|
|
483
|
+
fs3.rmSync(tmpDir, { recursive: true, force: true });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Install addon — prefers workspace if available, falls back to npm.
|
|
488
|
+
* This ensures dev builds (with vite output, etc.) are used when in workspace mode.
|
|
489
|
+
*/
|
|
490
|
+
async install(packageName, version) {
|
|
491
|
+
if (this.workspacePackagesDir) {
|
|
492
|
+
const workspaceDirName = packageName.replace("@camstack/", "");
|
|
493
|
+
const sourceDir = path3.join(this.workspacePackagesDir, workspaceDirName);
|
|
494
|
+
if (fs3.existsSync(path3.join(sourceDir, "package.json"))) {
|
|
495
|
+
return this.installFromWorkspace(packageName);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return this.installFromNpm(packageName, version);
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Install addon from workspace by copying package.json + dist/ to addons dir.
|
|
502
|
+
* Does NOT build — expects dist/ to already exist (run `npm run build` separately).
|
|
503
|
+
*/
|
|
504
|
+
async installFromWorkspace(packageName) {
|
|
505
|
+
if (!this.workspacePackagesDir) {
|
|
506
|
+
throw new Error("Workspace packages directory not configured");
|
|
507
|
+
}
|
|
508
|
+
const workspaceDirName = packageName.replace("@camstack/", "");
|
|
509
|
+
const sourceDir = path3.join(this.workspacePackagesDir, workspaceDirName);
|
|
510
|
+
const sourcePkgJson = path3.join(sourceDir, "package.json");
|
|
511
|
+
if (!fs3.existsSync(sourcePkgJson)) {
|
|
512
|
+
throw new Error(`Workspace package not found: ${sourceDir}`);
|
|
513
|
+
}
|
|
514
|
+
const distDir = path3.join(sourceDir, "dist");
|
|
515
|
+
if (!fs3.existsSync(distDir)) {
|
|
516
|
+
throw new Error(`${packageName} has no dist/ directory \u2014 run 'npm run build' first`);
|
|
517
|
+
}
|
|
518
|
+
const targetDir = path3.join(this.addonsDir, packageName);
|
|
519
|
+
fs3.rmSync(targetDir, { recursive: true, force: true });
|
|
520
|
+
ensureDir(targetDir);
|
|
521
|
+
const pkgData = JSON.parse(fs3.readFileSync(sourcePkgJson, "utf-8"));
|
|
522
|
+
const strippedPkg = stripCamstackDeps(pkgData);
|
|
523
|
+
fs3.writeFileSync(path3.join(targetDir, "package.json"), JSON.stringify(strippedPkg, null, 2));
|
|
524
|
+
copyDirRecursive(distDir, path3.join(targetDir, "dist"));
|
|
525
|
+
copyExtraFileDirs(pkgData, sourceDir, targetDir);
|
|
526
|
+
fs3.writeFileSync(path3.join(targetDir, ".install-source"), "workspace");
|
|
527
|
+
try {
|
|
528
|
+
await execFileAsync("npm", ["install", "--omit=dev", "--ignore-scripts=false"], {
|
|
529
|
+
cwd: targetDir,
|
|
530
|
+
timeout: 12e4
|
|
531
|
+
});
|
|
532
|
+
} catch {
|
|
533
|
+
}
|
|
534
|
+
return { name: pkgData.name, version: pkgData.version };
|
|
535
|
+
}
|
|
536
|
+
/** Install addon from npm (download tgz, then extract) */
|
|
537
|
+
async installFromNpm(packageName, version) {
|
|
538
|
+
const tmpDir = fs3.mkdtempSync(path3.join(os2.tmpdir(), "camstack-addon-npm-"));
|
|
539
|
+
const packageSpec = version ? `${packageName}@${version}` : packageName;
|
|
540
|
+
const args = ["pack", packageSpec, "--pack-destination", tmpDir];
|
|
541
|
+
if (this.registry) {
|
|
542
|
+
args.push("--registry", this.registry);
|
|
543
|
+
}
|
|
544
|
+
console.log(`[AddonInstaller] npm pack ${packageSpec} \u2192 ${tmpDir}`);
|
|
545
|
+
try {
|
|
546
|
+
const { stdout } = await execFileAsync("npm", args, {
|
|
547
|
+
timeout: 12e4
|
|
548
|
+
});
|
|
549
|
+
const tgzFiles = fs3.readdirSync(tmpDir).filter((f) => f.endsWith(".tgz"));
|
|
550
|
+
console.log(`[AddonInstaller] npm pack stdout: ${stdout.trim()}, tgzFiles: ${tgzFiles.join(", ")}`);
|
|
551
|
+
if (tgzFiles.length === 0) {
|
|
552
|
+
throw new Error(`npm pack produced no tgz file for ${packageSpec}. stdout: ${stdout.trim()}`);
|
|
553
|
+
}
|
|
554
|
+
const tgzPath = path3.join(tmpDir, tgzFiles[0]);
|
|
555
|
+
const result = await this.installFromTgz(tgzPath);
|
|
556
|
+
console.log(`[AddonInstaller] installFromTgz result: ${result.name}@${result.version} \u2192 ${path3.join(this.addonsDir, result.name)}`);
|
|
557
|
+
const targetDir = path3.join(this.addonsDir, result.name);
|
|
558
|
+
fs3.writeFileSync(path3.join(targetDir, ".install-source"), "npm");
|
|
559
|
+
return result;
|
|
560
|
+
} finally {
|
|
561
|
+
fs3.rmSync(tmpDir, { recursive: true, force: true });
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
/** Uninstall addon (delete directory) */
|
|
565
|
+
async uninstall(packageName) {
|
|
566
|
+
const addonDir = path3.join(this.addonsDir, packageName);
|
|
567
|
+
if (fs3.existsSync(addonDir)) {
|
|
568
|
+
fs3.rmSync(addonDir, { recursive: true, force: true });
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const legacyDir = path3.join(this.addonsDir, packageName.replace(/^@[^/]+\//, ""));
|
|
572
|
+
if (fs3.existsSync(legacyDir)) {
|
|
573
|
+
fs3.rmSync(legacyDir, { recursive: true, force: true });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** List installed addons (directories with package.json containing camstack.addons) */
|
|
577
|
+
listInstalled() {
|
|
578
|
+
if (!fs3.existsSync(this.addonsDir)) return [];
|
|
579
|
+
const packageDirs = [];
|
|
580
|
+
for (const entry of fs3.readdirSync(this.addonsDir, { withFileTypes: true })) {
|
|
581
|
+
if (!entry.isDirectory()) continue;
|
|
582
|
+
if (entry.name.startsWith("@")) {
|
|
583
|
+
const scopeDir = path3.join(this.addonsDir, entry.name);
|
|
584
|
+
for (const inner of fs3.readdirSync(scopeDir, { withFileTypes: true })) {
|
|
585
|
+
if (inner.isDirectory()) packageDirs.push(path3.join(scopeDir, inner.name));
|
|
586
|
+
}
|
|
587
|
+
} else {
|
|
588
|
+
packageDirs.push(path3.join(this.addonsDir, entry.name));
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return packageDirs.map((dir) => {
|
|
592
|
+
const pkgPath = path3.join(dir, "package.json");
|
|
593
|
+
if (!fs3.existsSync(pkgPath)) return null;
|
|
397
594
|
try {
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
if (fs.statSync(filePath).mtimeMs > distMtime)
|
|
405
|
-
return true;
|
|
406
|
-
}
|
|
407
|
-
return false;
|
|
595
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
|
|
596
|
+
if (!pkg.camstack?.addons) return null;
|
|
597
|
+
const sourceFile = path3.join(dir, ".install-source");
|
|
598
|
+
const installSource = fs3.existsSync(sourceFile) ? fs3.readFileSync(sourceFile, "utf-8").trim() : void 0;
|
|
599
|
+
const result = { name: pkg.name, version: pkg.version, dir, ...installSource ? { installSource } : {} };
|
|
600
|
+
return result;
|
|
408
601
|
} catch {
|
|
409
|
-
return
|
|
602
|
+
return null;
|
|
410
603
|
}
|
|
604
|
+
}).filter((item) => item !== null);
|
|
605
|
+
}
|
|
606
|
+
/** Check if an addon is installed */
|
|
607
|
+
isInstalled(packageName) {
|
|
608
|
+
if (fs3.existsSync(path3.join(this.addonsDir, packageName, "package.json"))) return true;
|
|
609
|
+
const legacy = packageName.replace(/^@[^/]+\//, "");
|
|
610
|
+
return fs3.existsSync(path3.join(this.addonsDir, legacy, "package.json"));
|
|
611
|
+
}
|
|
612
|
+
/** Get installed package info */
|
|
613
|
+
getInstalledPackage(packageName) {
|
|
614
|
+
let pkgPath = path3.join(this.addonsDir, packageName, "package.json");
|
|
615
|
+
if (!fs3.existsSync(pkgPath)) {
|
|
616
|
+
pkgPath = path3.join(this.addonsDir, packageName.replace(/^@[^/]+\//, ""), "package.json");
|
|
617
|
+
}
|
|
618
|
+
if (!fs3.existsSync(pkgPath)) return null;
|
|
619
|
+
try {
|
|
620
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
|
|
621
|
+
return { name: pkg.name, version: pkg.version, dir: path3.dirname(pkgPath) };
|
|
622
|
+
} catch {
|
|
623
|
+
return null;
|
|
411
624
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "camstack-install-"));
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
// src/workspace-detect.ts
|
|
629
|
+
var fs4 = __toESM(require("fs"));
|
|
630
|
+
var path4 = __toESM(require("path"));
|
|
631
|
+
function detectWorkspacePackagesDir(startDir) {
|
|
632
|
+
let current = path4.resolve(startDir);
|
|
633
|
+
for (let i = 0; i < 6; i++) {
|
|
634
|
+
current = path4.dirname(current);
|
|
635
|
+
const packagesDir = path4.join(current, "packages");
|
|
636
|
+
const rootPkgJson = path4.join(current, "package.json");
|
|
637
|
+
if (fs4.existsSync(packagesDir) && fs4.existsSync(rootPkgJson)) {
|
|
426
638
|
try {
|
|
427
|
-
const
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
});
|
|
431
|
-
const tgzFilename = stdout.trim().split("\n").pop()?.trim();
|
|
432
|
-
if (!tgzFilename)
|
|
433
|
-
throw new Error("npm pack produced no output");
|
|
434
|
-
const tgzPath = path.join(tmpDir, tgzFilename);
|
|
435
|
-
const extractDir = path.join(tmpDir, "extracted");
|
|
436
|
-
ensureDir2(extractDir);
|
|
437
|
-
(0, node_child_process_1.execFileSync)("tar", ["-xzf", tgzPath, "-C", extractDir], { timeout: 3e4 });
|
|
438
|
-
const packageSubDir = path.join(extractDir, "package");
|
|
439
|
-
const srcPkgJsonDir = fs.existsSync(path.join(packageSubDir, "package.json")) ? packageSubDir : extractDir;
|
|
440
|
-
fs.rmSync(targetDir, { recursive: true, force: true });
|
|
441
|
-
ensureDir2(targetDir);
|
|
442
|
-
fs.copyFileSync(path.join(srcPkgJsonDir, "package.json"), path.join(targetDir, "package.json"));
|
|
443
|
-
const distSrc = path.join(srcPkgJsonDir, "dist");
|
|
444
|
-
if (fs.existsSync(distSrc)) {
|
|
445
|
-
copyDirRecursive2(distSrc, path.join(targetDir, "dist"));
|
|
446
|
-
}
|
|
447
|
-
try {
|
|
448
|
-
const npmPkg = JSON.parse(fs.readFileSync(path.join(srcPkgJsonDir, "package.json"), "utf-8"));
|
|
449
|
-
copyExtraFileDirs2(npmPkg, srcPkgJsonDir, targetDir);
|
|
450
|
-
} catch {
|
|
639
|
+
const rootPkg = JSON.parse(fs4.readFileSync(rootPkgJson, "utf-8"));
|
|
640
|
+
if (rootPkg.workspaces || rootPkg.name === "camstack-server" || rootPkg.name === "camstack") {
|
|
641
|
+
return packagesDir;
|
|
451
642
|
}
|
|
452
|
-
}
|
|
453
|
-
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
643
|
+
} catch {
|
|
454
644
|
}
|
|
455
645
|
}
|
|
456
646
|
}
|
|
457
|
-
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
458
649
|
|
|
459
|
-
// src/
|
|
460
|
-
var
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
}
|
|
479
|
-
|
|
650
|
+
// src/capability-registry.ts
|
|
651
|
+
var CapabilityRegistry = class {
|
|
652
|
+
constructor(logger, configReader) {
|
|
653
|
+
this.logger = logger;
|
|
654
|
+
this.configReader = configReader;
|
|
655
|
+
}
|
|
656
|
+
capabilities = /* @__PURE__ */ new Map();
|
|
657
|
+
/** Per-device singleton overrides: deviceId → (capability → addonId) */
|
|
658
|
+
deviceOverrides = /* @__PURE__ */ new Map();
|
|
659
|
+
/** Per-device collection filters: deviceId → (capability → addonIds[]) */
|
|
660
|
+
deviceCollectionFilters = /* @__PURE__ */ new Map();
|
|
661
|
+
/**
|
|
662
|
+
* Declare a capability (typically called when addon manifests are loaded).
|
|
663
|
+
* Must be called before registerProvider/registerConsumer for that capability.
|
|
664
|
+
*/
|
|
665
|
+
declareCapability(declaration) {
|
|
666
|
+
if (this.capabilities.has(declaration.name)) {
|
|
667
|
+
this.logger.debug(`Capability "${declaration.name}" already declared, skipping`);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
this.capabilities.set(declaration.name, {
|
|
671
|
+
declaration,
|
|
672
|
+
available: /* @__PURE__ */ new Map(),
|
|
673
|
+
activeAddonId: null,
|
|
674
|
+
activeProvider: null,
|
|
675
|
+
activeCollection: [],
|
|
676
|
+
consumers: /* @__PURE__ */ new Set()
|
|
480
677
|
});
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
var fs_utils_js_1 = require_fs_utils();
|
|
508
|
-
var execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
509
|
-
var AddonInstaller2 = class _AddonInstaller {
|
|
510
|
-
addonsDir;
|
|
511
|
-
registry;
|
|
512
|
-
workspacePackagesDir;
|
|
513
|
-
constructor(config) {
|
|
514
|
-
this.addonsDir = config.addonsDir;
|
|
515
|
-
this.registry = config.registry;
|
|
516
|
-
this.workspacePackagesDir = config.workspacePackagesDir;
|
|
517
|
-
}
|
|
518
|
-
/** Required addon packages that must be installed for the server to function */
|
|
519
|
-
static REQUIRED_PACKAGES = [
|
|
520
|
-
"@camstack/core",
|
|
521
|
-
"@camstack/addon-pipeline",
|
|
522
|
-
"@camstack/addon-vision",
|
|
523
|
-
"@camstack/addon-admin-ui",
|
|
524
|
-
"@camstack/addon-webrtc-adaptive",
|
|
525
|
-
"@camstack/addon-pipeline-analysis",
|
|
526
|
-
"@camstack/addon-scene-intelligence",
|
|
527
|
-
"@camstack/addon-advanced-notifier"
|
|
528
|
-
];
|
|
529
|
-
/** Ensure the addons directory exists */
|
|
530
|
-
async initialize() {
|
|
531
|
-
(0, fs_utils_js_1.ensureDir)(this.addonsDir);
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Ensure all required packages are installed in the addons directory.
|
|
535
|
-
* This replaces the standalone first-boot-installer.ts.
|
|
536
|
-
*/
|
|
537
|
-
async ensureRequiredPackages() {
|
|
538
|
-
(0, fs_utils_js_1.ensureDir)(this.addonsDir);
|
|
539
|
-
if (this.workspacePackagesDir) {
|
|
540
|
-
console.log(`[AddonInstaller] Workspace detected: ${this.workspacePackagesDir}`);
|
|
541
|
-
(0, fs_utils_js_1.ensureLibraryBuilt)("@camstack/kernel", this.workspacePackagesDir);
|
|
542
|
-
(0, fs_utils_js_1.ensureLibraryBuilt)("@camstack/types", this.workspacePackagesDir);
|
|
543
|
-
}
|
|
544
|
-
for (const packageName of _AddonInstaller.REQUIRED_PACKAGES) {
|
|
545
|
-
const addonDir = path.join(this.addonsDir, packageName);
|
|
546
|
-
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
547
|
-
const forceNpm = process.env["CAMSTACK_INSTALL_SOURCE"] === "npm";
|
|
548
|
-
const useWorkspace = this.workspacePackagesDir && !forceNpm;
|
|
549
|
-
if (fs.existsSync(pkgJsonPath)) {
|
|
550
|
-
if (!useWorkspace) {
|
|
551
|
-
continue;
|
|
552
|
-
}
|
|
553
|
-
const srcPkgDir = this.findWorkspacePackage(packageName);
|
|
554
|
-
if (srcPkgDir && !(0, fs_utils_js_1.isSourceNewer)(srcPkgDir)) {
|
|
555
|
-
continue;
|
|
556
|
-
}
|
|
557
|
-
}
|
|
678
|
+
this.logger.debug(`Capability declared: ${declaration.name} (mode=${declaration.mode})`);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Register a capability provider (called by addon loader when addon is enabled).
|
|
682
|
+
* For singleton: auto-activates if user-preferred or first registered.
|
|
683
|
+
* For collection: adds to active set and notifies consumers.
|
|
684
|
+
*/
|
|
685
|
+
registerProvider(capability, addonId, provider) {
|
|
686
|
+
const state = this.capabilities.get(capability);
|
|
687
|
+
if (!state) {
|
|
688
|
+
this.logger.warn(`Cannot register provider for undeclared capability "${capability}"`);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
state.available.set(addonId, provider);
|
|
692
|
+
this.logger.info(`Provider registered: ${addonId} \u2192 ${capability}`);
|
|
693
|
+
if (state.declaration.mode === "singleton") {
|
|
694
|
+
const userChoice = this.configReader(capability);
|
|
695
|
+
if (userChoice === addonId) {
|
|
696
|
+
this.activateSingleton(state, addonId, provider);
|
|
697
|
+
} else if (userChoice === void 0 && state.activeAddonId === null) {
|
|
698
|
+
this.activateSingleton(state, addonId, provider);
|
|
699
|
+
}
|
|
700
|
+
} else {
|
|
701
|
+
state.activeCollection.push({ addonId, provider });
|
|
702
|
+
for (const consumer of state.consumers) {
|
|
703
|
+
if (consumer.onAdded) {
|
|
558
704
|
try {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
continue;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
await this.installFromNpm(packageName);
|
|
567
|
-
} catch (err) {
|
|
568
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
569
|
-
if (packageName === "@camstack/core") {
|
|
570
|
-
throw new Error(`Required package ${packageName} failed to install: ${msg}`);
|
|
571
|
-
}
|
|
572
|
-
console.error(`[AddonInstaller] Failed to install ${packageName}: ${msg}`);
|
|
705
|
+
consumer.onAdded(provider);
|
|
706
|
+
} catch (error) {
|
|
707
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
708
|
+
this.logger.error(`Consumer onAdded failed for ${capability}: ${msg}`);
|
|
573
709
|
}
|
|
574
710
|
}
|
|
575
711
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Unregister a provider (called when addon is disabled/uninstalled).
|
|
716
|
+
*/
|
|
717
|
+
unregisterProvider(capability, addonId) {
|
|
718
|
+
const state = this.capabilities.get(capability);
|
|
719
|
+
if (!state) return;
|
|
720
|
+
const provider = state.available.get(addonId);
|
|
721
|
+
state.available.delete(addonId);
|
|
722
|
+
if (state.declaration.mode === "singleton") {
|
|
723
|
+
if (state.activeAddonId === addonId) {
|
|
724
|
+
state.activeAddonId = null;
|
|
725
|
+
state.activeProvider = null;
|
|
726
|
+
this.logger.info(`Singleton deactivated: ${capability} (was ${addonId})`);
|
|
727
|
+
}
|
|
728
|
+
} else {
|
|
729
|
+
const idx = state.activeCollection.findIndex((e) => e.addonId === addonId);
|
|
730
|
+
if (idx !== -1) {
|
|
731
|
+
state.activeCollection.splice(idx, 1);
|
|
732
|
+
for (const consumer of state.consumers) {
|
|
733
|
+
if (consumer.onRemoved && provider !== void 0) {
|
|
583
734
|
try {
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
735
|
+
consumer.onRemoved(provider);
|
|
736
|
+
} catch (error) {
|
|
737
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
738
|
+
this.logger.error(`Consumer onRemoved failed for ${capability}: ${msg}`);
|
|
588
739
|
}
|
|
589
740
|
}
|
|
590
741
|
}
|
|
591
|
-
return null;
|
|
592
|
-
}
|
|
593
|
-
/** Install addon from a tgz file (uploaded or downloaded) */
|
|
594
|
-
async installFromTgz(tgzPath) {
|
|
595
|
-
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "camstack-addon-install-"));
|
|
596
|
-
try {
|
|
597
|
-
await execFileAsync("tar", ["-xzf", tgzPath, "-C", tmpDir], { timeout: 3e4 });
|
|
598
|
-
const extractedDir = path.join(tmpDir, "package");
|
|
599
|
-
const pkgJsonPath = fs.existsSync(path.join(extractedDir, "package.json")) ? path.join(extractedDir, "package.json") : path.join(tmpDir, "package.json");
|
|
600
|
-
if (!fs.existsSync(pkgJsonPath)) {
|
|
601
|
-
throw new Error("No package.json found in tgz archive");
|
|
602
|
-
}
|
|
603
|
-
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
604
|
-
if (!pkgJson.camstack?.addons) {
|
|
605
|
-
throw new Error(`Package ${pkgJson.name} has no camstack.addons manifest`);
|
|
606
|
-
}
|
|
607
|
-
const targetDir = path.join(this.addonsDir, pkgJson.name);
|
|
608
|
-
fs.rmSync(targetDir, { recursive: true, force: true });
|
|
609
|
-
(0, fs_utils_js_1.ensureDir)(targetDir);
|
|
610
|
-
const sourceDir = path.dirname(pkgJsonPath);
|
|
611
|
-
fs.copyFileSync(pkgJsonPath, path.join(targetDir, "package.json"));
|
|
612
|
-
const sourceDist = path.join(sourceDir, "dist");
|
|
613
|
-
if (fs.existsSync(sourceDist)) {
|
|
614
|
-
(0, fs_utils_js_1.copyDirRecursive)(sourceDist, path.join(targetDir, "dist"));
|
|
615
|
-
}
|
|
616
|
-
(0, fs_utils_js_1.copyExtraFileDirs)(pkgJson, sourceDir, targetDir);
|
|
617
|
-
return { name: pkgJson.name, version: pkgJson.version };
|
|
618
|
-
} finally {
|
|
619
|
-
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
/**
|
|
623
|
-
* Install addon — prefers workspace if available, falls back to npm.
|
|
624
|
-
* This ensures dev builds (with vite output, etc.) are used when in workspace mode.
|
|
625
|
-
*/
|
|
626
|
-
async install(packageName, version) {
|
|
627
|
-
if (this.workspacePackagesDir) {
|
|
628
|
-
const workspaceDirName = packageName.replace("@camstack/", "");
|
|
629
|
-
const sourceDir = path.join(this.workspacePackagesDir, workspaceDirName);
|
|
630
|
-
if (fs.existsSync(path.join(sourceDir, "package.json"))) {
|
|
631
|
-
return this.installFromWorkspace(packageName);
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
return this.installFromNpm(packageName, version);
|
|
635
742
|
}
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const targetDir = path.join(this.addonsDir, packageName);
|
|
655
|
-
fs.rmSync(targetDir, { recursive: true, force: true });
|
|
656
|
-
(0, fs_utils_js_1.ensureDir)(targetDir);
|
|
657
|
-
const pkgData = JSON.parse(fs.readFileSync(sourcePkgJson, "utf-8"));
|
|
658
|
-
const strippedPkg = (0, fs_utils_js_1.stripCamstackDeps)(pkgData);
|
|
659
|
-
fs.writeFileSync(path.join(targetDir, "package.json"), JSON.stringify(strippedPkg, null, 2));
|
|
660
|
-
(0, fs_utils_js_1.copyDirRecursive)(distDir, path.join(targetDir, "dist"));
|
|
661
|
-
(0, fs_utils_js_1.copyExtraFileDirs)(pkgData, sourceDir, targetDir);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Register a consumer that wants to be notified when providers change.
|
|
747
|
+
* If a provider is already active, the consumer is immediately notified.
|
|
748
|
+
* Returns a disposer function for cleanup.
|
|
749
|
+
*/
|
|
750
|
+
registerConsumer(registration) {
|
|
751
|
+
const state = this.capabilities.get(registration.capability);
|
|
752
|
+
if (!state) {
|
|
753
|
+
this.logger.debug(`Consumer registered for undeclared capability "${registration.capability}" \u2014 auto-declaring`);
|
|
754
|
+
this.declareCapability({ name: registration.capability, mode: "singleton" });
|
|
755
|
+
return this.registerConsumer(registration);
|
|
756
|
+
}
|
|
757
|
+
const untypedReg = registration;
|
|
758
|
+
state.consumers.add(untypedReg);
|
|
759
|
+
if (state.declaration.mode === "singleton") {
|
|
760
|
+
if (state.activeProvider !== null && registration.onSet) {
|
|
662
761
|
try {
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
});
|
|
667
|
-
} catch {
|
|
762
|
+
registration.onSet(state.activeProvider);
|
|
763
|
+
} catch (error) {
|
|
764
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
765
|
+
this.logger.error(`Consumer onSet (immediate) failed for ${registration.capability}: ${msg}`);
|
|
668
766
|
}
|
|
669
|
-
return { name: pkgData.name, version: pkgData.version };
|
|
670
767
|
}
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
const
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
try {
|
|
680
|
-
const { stdout } = await execFileAsync("npm", args, {
|
|
681
|
-
timeout: 12e4
|
|
682
|
-
});
|
|
683
|
-
const tgzFiles = fs.readdirSync(tmpDir).filter((f) => f.endsWith(".tgz"));
|
|
684
|
-
if (tgzFiles.length === 0) {
|
|
685
|
-
throw new Error(`npm pack produced no tgz file for ${packageSpec}. stdout: ${stdout.trim()}`);
|
|
768
|
+
} else {
|
|
769
|
+
if (registration.onAdded) {
|
|
770
|
+
for (const entry of state.activeCollection) {
|
|
771
|
+
try {
|
|
772
|
+
registration.onAdded(entry.provider);
|
|
773
|
+
} catch (error) {
|
|
774
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
775
|
+
this.logger.error(`Consumer onAdded (immediate) failed for ${registration.capability}: ${msg}`);
|
|
686
776
|
}
|
|
687
|
-
const tgzPath = path.join(tmpDir, tgzFiles[0]);
|
|
688
|
-
const result = await this.installFromTgz(tgzPath);
|
|
689
|
-
return result;
|
|
690
|
-
} finally {
|
|
691
|
-
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
/** Uninstall addon (delete directory) */
|
|
695
|
-
async uninstall(packageName) {
|
|
696
|
-
const addonDir = path.join(this.addonsDir, packageName);
|
|
697
|
-
if (fs.existsSync(addonDir)) {
|
|
698
|
-
fs.rmSync(addonDir, { recursive: true, force: true });
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
const legacyDir = path.join(this.addonsDir, packageName.replace(/^@[^/]+\//, ""));
|
|
702
|
-
if (fs.existsSync(legacyDir)) {
|
|
703
|
-
fs.rmSync(legacyDir, { recursive: true, force: true });
|
|
704
777
|
}
|
|
705
778
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
779
|
+
}
|
|
780
|
+
return () => {
|
|
781
|
+
state.consumers.delete(untypedReg);
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Get the active singleton provider for a capability.
|
|
786
|
+
* Returns null if none set.
|
|
787
|
+
*/
|
|
788
|
+
getSingleton(capability) {
|
|
789
|
+
const state = this.capabilities.get(capability);
|
|
790
|
+
if (!state || state.declaration.mode !== "singleton") return null;
|
|
791
|
+
return state.activeProvider ?? null;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Get all active collection providers for a capability.
|
|
795
|
+
*/
|
|
796
|
+
getCollection(capability) {
|
|
797
|
+
const state = this.capabilities.get(capability);
|
|
798
|
+
if (!state || state.declaration.mode !== "collection") return [];
|
|
799
|
+
return state.activeCollection.map((e) => e.provider);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Set which addon should be the active singleton for a capability.
|
|
803
|
+
* Call with `immediate: true` to also swap the runtime provider now
|
|
804
|
+
* (consumers' onSet will be awaited).
|
|
805
|
+
*/
|
|
806
|
+
async setActiveSingleton(capability, addonId, immediate = false) {
|
|
807
|
+
const state = this.capabilities.get(capability);
|
|
808
|
+
if (!state) {
|
|
809
|
+
throw new Error(`Unknown capability: ${capability}`);
|
|
810
|
+
}
|
|
811
|
+
if (state.declaration.mode !== "singleton") {
|
|
812
|
+
throw new Error(`Capability "${capability}" is not a singleton`);
|
|
813
|
+
}
|
|
814
|
+
const provider = state.available.get(addonId);
|
|
815
|
+
if (!provider) {
|
|
816
|
+
throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
|
|
817
|
+
}
|
|
818
|
+
if (immediate) {
|
|
819
|
+
await this.activateSingletonAsync(state, addonId, provider);
|
|
820
|
+
}
|
|
821
|
+
this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Get the mode declared for a capability.
|
|
825
|
+
*/
|
|
826
|
+
getMode(capability) {
|
|
827
|
+
return this.capabilities.get(capability)?.declaration.mode;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* List all registered capabilities with their providers.
|
|
831
|
+
*/
|
|
832
|
+
listCapabilities() {
|
|
833
|
+
const result = [];
|
|
834
|
+
for (const [name, state] of this.capabilities) {
|
|
835
|
+
result.push({
|
|
836
|
+
name,
|
|
837
|
+
mode: state.declaration.mode,
|
|
838
|
+
providers: [...state.available.keys()],
|
|
839
|
+
activeProvider: state.activeAddonId
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
return result;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Check if all dependencies for a capability are satisfied (have active providers).
|
|
846
|
+
*/
|
|
847
|
+
areDependenciesMet(declaration) {
|
|
848
|
+
if (!declaration.dependsOn?.length) return true;
|
|
849
|
+
return declaration.dependsOn.every((dep) => {
|
|
850
|
+
const state = this.capabilities.get(dep);
|
|
851
|
+
if (!state) return false;
|
|
852
|
+
if (state.declaration.mode === "singleton") {
|
|
853
|
+
return state.activeProvider !== null;
|
|
854
|
+
}
|
|
855
|
+
return state.activeCollection.length > 0;
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Get the dependency-ordered list of capability names for boot sequencing.
|
|
860
|
+
* Returns capabilities sorted topologically by dependsOn.
|
|
861
|
+
* Throws if a cycle is detected.
|
|
862
|
+
*/
|
|
863
|
+
getBootOrder() {
|
|
864
|
+
const visited = /* @__PURE__ */ new Set();
|
|
865
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
866
|
+
const order = [];
|
|
867
|
+
const visit = (name) => {
|
|
868
|
+
if (visited.has(name)) return;
|
|
869
|
+
if (visiting.has(name)) {
|
|
870
|
+
throw new Error(`Circular dependency detected involving capability "${name}"`);
|
|
871
|
+
}
|
|
872
|
+
visiting.add(name);
|
|
873
|
+
const state = this.capabilities.get(name);
|
|
874
|
+
if (state?.declaration.dependsOn) {
|
|
875
|
+
for (const dep of state.declaration.dependsOn) {
|
|
876
|
+
visit(dep);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
visiting.delete(name);
|
|
880
|
+
visited.add(name);
|
|
881
|
+
order.push(name);
|
|
882
|
+
};
|
|
883
|
+
for (const name of this.capabilities.keys()) {
|
|
884
|
+
visit(name);
|
|
885
|
+
}
|
|
886
|
+
return order;
|
|
887
|
+
}
|
|
888
|
+
// ---- Per-device overrides ----
|
|
889
|
+
/**
|
|
890
|
+
* Set a per-device singleton override. When resolveForDevice is called for
|
|
891
|
+
* this device + capability, the specified addon's provider is returned
|
|
892
|
+
* instead of the global singleton.
|
|
893
|
+
*/
|
|
894
|
+
setDeviceOverride(deviceId, capability, addonId) {
|
|
895
|
+
const state = this.capabilities.get(capability);
|
|
896
|
+
if (!state) {
|
|
897
|
+
this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (!state.available.has(addonId)) {
|
|
901
|
+
this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
let deviceMap = this.deviceOverrides.get(deviceId);
|
|
905
|
+
if (!deviceMap) {
|
|
906
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
907
|
+
this.deviceOverrides.set(deviceId, deviceMap);
|
|
908
|
+
}
|
|
909
|
+
deviceMap.set(capability, addonId);
|
|
910
|
+
this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Clear a per-device singleton override, reverting to the global singleton.
|
|
914
|
+
*/
|
|
915
|
+
clearDeviceOverride(deviceId, capability) {
|
|
916
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
917
|
+
if (!deviceMap) return;
|
|
918
|
+
deviceMap.delete(capability);
|
|
919
|
+
if (deviceMap.size === 0) {
|
|
920
|
+
this.deviceOverrides.delete(deviceId);
|
|
921
|
+
}
|
|
922
|
+
this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Get all per-device singleton overrides for a device.
|
|
926
|
+
* Returns a Map of capability name to addon ID.
|
|
927
|
+
*/
|
|
928
|
+
getDeviceOverrides(deviceId) {
|
|
929
|
+
return new Map(this.deviceOverrides.get(deviceId) ?? []);
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Resolve a singleton provider for a specific device.
|
|
933
|
+
* 1. Check device override — return that addon's provider
|
|
934
|
+
* 2. Fallback to global singleton
|
|
935
|
+
*/
|
|
936
|
+
resolveForDevice(capability, deviceId) {
|
|
937
|
+
const state = this.capabilities.get(capability);
|
|
938
|
+
if (!state || state.declaration.mode !== "singleton") return null;
|
|
939
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
940
|
+
if (deviceMap) {
|
|
941
|
+
const overrideAddonId = deviceMap.get(capability);
|
|
942
|
+
if (overrideAddonId) {
|
|
943
|
+
const provider = state.available.get(overrideAddonId);
|
|
944
|
+
if (provider) return provider;
|
|
945
|
+
this.logger.warn(
|
|
946
|
+
`Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`
|
|
947
|
+
);
|
|
723
948
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
949
|
+
}
|
|
950
|
+
return state.activeProvider ?? null;
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Set a per-device collection filter. When resolveCollectionForDevice is called
|
|
954
|
+
* for this device + capability, only providers from the specified addon IDs
|
|
955
|
+
* are returned instead of the full collection.
|
|
956
|
+
*/
|
|
957
|
+
setDeviceCollectionFilter(deviceId, capability, addonIds) {
|
|
958
|
+
const state = this.capabilities.get(capability);
|
|
959
|
+
if (!state) {
|
|
960
|
+
this.logger.warn(`Cannot set device collection filter for undeclared capability "${capability}"`);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
let deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
964
|
+
if (!deviceMap) {
|
|
965
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
966
|
+
this.deviceCollectionFilters.set(deviceId, deviceMap);
|
|
967
|
+
}
|
|
968
|
+
deviceMap.set(capability, [...addonIds]);
|
|
969
|
+
this.logger.info(`Device collection filter set: ${deviceId} \u2192 ${capability} = [${addonIds.join(", ")}]`);
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Clear a per-device collection filter, reverting to the full collection.
|
|
973
|
+
*/
|
|
974
|
+
clearDeviceCollectionFilter(deviceId, capability) {
|
|
975
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
976
|
+
if (!deviceMap) return;
|
|
977
|
+
deviceMap.delete(capability);
|
|
978
|
+
if (deviceMap.size === 0) {
|
|
979
|
+
this.deviceCollectionFilters.delete(deviceId);
|
|
980
|
+
}
|
|
981
|
+
this.logger.info(`Device collection filter cleared: ${deviceId} \u2192 ${capability}`);
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Resolve collection providers for a specific device.
|
|
985
|
+
* If a filter exists for the device + capability, only those addon's providers are returned.
|
|
986
|
+
* If no filter exists, the full collection is returned.
|
|
987
|
+
*/
|
|
988
|
+
resolveCollectionForDevice(capability, deviceId) {
|
|
989
|
+
const state = this.capabilities.get(capability);
|
|
990
|
+
if (!state || state.declaration.mode !== "collection") return [];
|
|
991
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
992
|
+
if (deviceMap) {
|
|
993
|
+
const filterAddonIds = deviceMap.get(capability);
|
|
994
|
+
if (filterAddonIds) {
|
|
995
|
+
const filterSet = new Set(filterAddonIds);
|
|
996
|
+
return state.activeCollection.filter((e) => filterSet.has(e.addonId)).map((e) => e.provider);
|
|
730
997
|
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
998
|
+
}
|
|
999
|
+
return state.activeCollection.map((e) => e.provider);
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Get a specific addon's provider by addon ID, regardless of whether it's the active singleton.
|
|
1003
|
+
* Useful for per-device overrides that need to look up any registered provider.
|
|
1004
|
+
*/
|
|
1005
|
+
getProviderByAddonId(capability, addonId) {
|
|
1006
|
+
const state = this.capabilities.get(capability);
|
|
1007
|
+
if (!state) return null;
|
|
1008
|
+
const provider = state.available.get(addonId);
|
|
1009
|
+
return provider ?? null;
|
|
1010
|
+
}
|
|
1011
|
+
activateSingleton(state, addonId, provider) {
|
|
1012
|
+
state.activeAddonId = addonId;
|
|
1013
|
+
state.activeProvider = provider;
|
|
1014
|
+
this.logger.info(`Singleton activated: ${state.declaration.name} \u2192 ${addonId}`);
|
|
1015
|
+
for (const consumer of state.consumers) {
|
|
1016
|
+
if (consumer.onSet) {
|
|
739
1017
|
try {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
1018
|
+
consumer.onSet(provider);
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1021
|
+
this.logger.error(`Consumer onSet failed for ${state.declaration.name}: ${msg}`);
|
|
744
1022
|
}
|
|
745
1023
|
}
|
|
746
|
-
}
|
|
747
|
-
exports2.AddonInstaller = AddonInstaller2;
|
|
1024
|
+
}
|
|
748
1025
|
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
return m[k];
|
|
761
|
-
} };
|
|
762
|
-
}
|
|
763
|
-
Object.defineProperty(o, k2, desc);
|
|
764
|
-
}) : (function(o, m, k, k2) {
|
|
765
|
-
if (k2 === void 0) k2 = k;
|
|
766
|
-
o[k2] = m[k];
|
|
767
|
-
}));
|
|
768
|
-
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
|
|
769
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
770
|
-
}) : function(o, v) {
|
|
771
|
-
o["default"] = v;
|
|
772
|
-
});
|
|
773
|
-
var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
|
|
774
|
-
var ownKeys = function(o) {
|
|
775
|
-
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
776
|
-
var ar = [];
|
|
777
|
-
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
778
|
-
return ar;
|
|
779
|
-
};
|
|
780
|
-
return ownKeys(o);
|
|
781
|
-
};
|
|
782
|
-
return function(mod) {
|
|
783
|
-
if (mod && mod.__esModule) return mod;
|
|
784
|
-
var result = {};
|
|
785
|
-
if (mod != null) {
|
|
786
|
-
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
787
|
-
}
|
|
788
|
-
__setModuleDefault(result, mod);
|
|
789
|
-
return result;
|
|
790
|
-
};
|
|
791
|
-
})();
|
|
792
|
-
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
793
|
-
exports2.detectWorkspacePackagesDir = detectWorkspacePackagesDir2;
|
|
794
|
-
var fs = __importStar(require("fs"));
|
|
795
|
-
var path = __importStar(require("path"));
|
|
796
|
-
function detectWorkspacePackagesDir2(startDir) {
|
|
797
|
-
let current = path.resolve(startDir);
|
|
798
|
-
for (let i = 0; i < 6; i++) {
|
|
799
|
-
current = path.dirname(current);
|
|
800
|
-
const packagesDir = path.join(current, "packages");
|
|
801
|
-
const rootPkgJson = path.join(current, "package.json");
|
|
802
|
-
if (fs.existsSync(packagesDir) && fs.existsSync(rootPkgJson)) {
|
|
803
|
-
try {
|
|
804
|
-
const rootPkg = JSON.parse(fs.readFileSync(rootPkgJson, "utf-8"));
|
|
805
|
-
if (rootPkg.workspaces || rootPkg.name === "camstack-server" || rootPkg.name === "camstack") {
|
|
806
|
-
return packagesDir;
|
|
807
|
-
}
|
|
808
|
-
} catch {
|
|
809
|
-
}
|
|
1026
|
+
async activateSingletonAsync(state, addonId, provider) {
|
|
1027
|
+
state.activeAddonId = addonId;
|
|
1028
|
+
state.activeProvider = provider;
|
|
1029
|
+
this.logger.info(`Singleton activated (async): ${state.declaration.name} \u2192 ${addonId}`);
|
|
1030
|
+
for (const consumer of state.consumers) {
|
|
1031
|
+
if (consumer.onSet) {
|
|
1032
|
+
try {
|
|
1033
|
+
await consumer.onSet(provider);
|
|
1034
|
+
} catch (error) {
|
|
1035
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1036
|
+
this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
|
|
810
1037
|
}
|
|
811
1038
|
}
|
|
812
|
-
return null;
|
|
813
1039
|
}
|
|
814
1040
|
}
|
|
1041
|
+
};
|
|
1042
|
+
|
|
1043
|
+
// src/infra-capabilities.ts
|
|
1044
|
+
var INFRA_CAPABILITIES = [
|
|
1045
|
+
{ name: "storage", required: true },
|
|
1046
|
+
{ name: "settings-store", required: true },
|
|
1047
|
+
{ name: "log-destination", required: false }
|
|
1048
|
+
];
|
|
1049
|
+
var infraNames = new Set(INFRA_CAPABILITIES.map((c) => c.name));
|
|
1050
|
+
function isInfraCapability(name) {
|
|
1051
|
+
return infraNames.has(name);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// src/config-manager.ts
|
|
1055
|
+
var fs5 = __toESM(require("fs"));
|
|
1056
|
+
var yaml = __toESM(require("js-yaml"));
|
|
1057
|
+
|
|
1058
|
+
// src/config-schema.ts
|
|
1059
|
+
var import_zod = require("zod");
|
|
1060
|
+
var DEFAULT_DATA_PATH = "camstack-data";
|
|
1061
|
+
var bootstrapSchema = import_zod.z.object({
|
|
1062
|
+
/** Server mode: 'hub' (full server) or 'agent' (worker node) */
|
|
1063
|
+
mode: import_zod.z.enum(["hub", "agent"]).default("hub"),
|
|
1064
|
+
server: import_zod.z.object({
|
|
1065
|
+
port: import_zod.z.number().default(4443),
|
|
1066
|
+
host: import_zod.z.string().default("0.0.0.0"),
|
|
1067
|
+
dataPath: import_zod.z.string().default(DEFAULT_DATA_PATH)
|
|
1068
|
+
}).default({}),
|
|
1069
|
+
auth: import_zod.z.object({
|
|
1070
|
+
jwtSecret: import_zod.z.string().nullable().default(null),
|
|
1071
|
+
adminUsername: import_zod.z.string().default("admin"),
|
|
1072
|
+
adminPassword: import_zod.z.string().default(process.env.ADMIN_PASSWORD ?? "changeme")
|
|
1073
|
+
}).default({}),
|
|
1074
|
+
/** Hub connection config — only used when mode='agent' */
|
|
1075
|
+
hub: import_zod.z.object({
|
|
1076
|
+
url: import_zod.z.string().default("ws://localhost:4443/agent"),
|
|
1077
|
+
token: import_zod.z.string().default("")
|
|
1078
|
+
}).default({}),
|
|
1079
|
+
/** Agent-specific config — only used when mode='agent' */
|
|
1080
|
+
agent: import_zod.z.object({
|
|
1081
|
+
name: import_zod.z.string().default(""),
|
|
1082
|
+
/** Port for the agent status page (minimal HTML) */
|
|
1083
|
+
statusPort: import_zod.z.number().default(4444)
|
|
1084
|
+
}).default({}),
|
|
1085
|
+
/** TLS configuration */
|
|
1086
|
+
tls: import_zod.z.object({
|
|
1087
|
+
/** Enable HTTPS (default: true) */
|
|
1088
|
+
enabled: import_zod.z.boolean().default(true),
|
|
1089
|
+
/** Path to custom cert file (PEM). If not set, auto-generates self-signed. */
|
|
1090
|
+
certPath: import_zod.z.string().optional(),
|
|
1091
|
+
/** Path to custom key file (PEM). Required if certPath is set. */
|
|
1092
|
+
keyPath: import_zod.z.string().optional()
|
|
1093
|
+
}).default({})
|
|
815
1094
|
});
|
|
1095
|
+
var RUNTIME_DEFAULTS = {
|
|
1096
|
+
"features.streaming": true,
|
|
1097
|
+
"features.notifications": true,
|
|
1098
|
+
"features.objectDetection": false,
|
|
1099
|
+
"features.remoteAccess": true,
|
|
1100
|
+
"features.agentCluster": false,
|
|
1101
|
+
"features.smartHome": true,
|
|
1102
|
+
"features.recordings": true,
|
|
1103
|
+
"features.backup": true,
|
|
1104
|
+
"features.repl": true,
|
|
1105
|
+
"retention.detectionEventsDays": 30,
|
|
1106
|
+
"retention.audioLevelsDays": 7,
|
|
1107
|
+
"logging.level": "info",
|
|
1108
|
+
"logging.retentionDays": 30,
|
|
1109
|
+
"eventBus.ringBufferSize": 1e4,
|
|
1110
|
+
"storage.provider": "sqlite-storage",
|
|
1111
|
+
"storage.locations": {
|
|
1112
|
+
data: "camstack-data/data",
|
|
1113
|
+
media: "camstack-data/media",
|
|
1114
|
+
recordings: "camstack-data/recordings",
|
|
1115
|
+
cache: "/tmp/camstack-cache",
|
|
1116
|
+
logs: "camstack-data/logs",
|
|
1117
|
+
models: "camstack-data/models"
|
|
1118
|
+
},
|
|
1119
|
+
"providers": [],
|
|
1120
|
+
// Recording
|
|
1121
|
+
"recording.segmentDurationSeconds": 4,
|
|
1122
|
+
"recording.defaultRetentionDays": 30,
|
|
1123
|
+
// Streaming ports are addon-specific (go2rtc owns its defaults)
|
|
1124
|
+
// FFmpeg
|
|
1125
|
+
"ffmpeg.binaryPath": "ffmpeg",
|
|
1126
|
+
"ffmpeg.hwAccel": "auto",
|
|
1127
|
+
"ffmpeg.threadCount": 0,
|
|
1128
|
+
// Detection defaults
|
|
1129
|
+
"detection.defaultMotionFps": 2,
|
|
1130
|
+
"detection.defaultDetectionFps": 5,
|
|
1131
|
+
"detection.defaultCooldownSeconds": 10,
|
|
1132
|
+
"detection.defaultConfidenceThreshold": 0.4,
|
|
1133
|
+
"detection.trackerMaxAgeFrames": 30,
|
|
1134
|
+
"detection.trackerMinHits": 3,
|
|
1135
|
+
"detection.trackerIouThreshold": 0.3,
|
|
1136
|
+
// Backup retention is addon-specific (local-backup owns its default)
|
|
1137
|
+
// Auth (runtime)
|
|
1138
|
+
"auth.tokenExpiry": "24h"
|
|
1139
|
+
};
|
|
816
1140
|
|
|
817
|
-
// src/
|
|
818
|
-
var
|
|
819
|
-
"
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
/**
|
|
855
|
-
* Register a capability provider (called by addon loader when addon is enabled).
|
|
856
|
-
* For singleton: auto-activates if user-preferred or first registered.
|
|
857
|
-
* For collection: adds to active set and notifies consumers.
|
|
858
|
-
*/
|
|
859
|
-
registerProvider(capability, addonId, provider) {
|
|
860
|
-
const state = this.capabilities.get(capability);
|
|
861
|
-
if (!state) {
|
|
862
|
-
this.logger.warn(`Cannot register provider for undeclared capability "${capability}"`);
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
state.available.set(addonId, provider);
|
|
866
|
-
this.logger.info(`Provider registered: ${addonId} \u2192 ${capability}`);
|
|
867
|
-
if (state.declaration.mode === "singleton") {
|
|
868
|
-
const userChoice = this.configReader(capability);
|
|
869
|
-
if (userChoice === addonId) {
|
|
870
|
-
this.activateSingleton(state, addonId, provider);
|
|
871
|
-
} else if (userChoice === void 0 && state.activeAddonId === null) {
|
|
872
|
-
this.activateSingleton(state, addonId, provider);
|
|
873
|
-
}
|
|
874
|
-
} else {
|
|
875
|
-
state.activeCollection.push({ addonId, provider });
|
|
876
|
-
for (const consumer of state.consumers) {
|
|
877
|
-
if (consumer.onAdded) {
|
|
878
|
-
try {
|
|
879
|
-
consumer.onAdded(provider);
|
|
880
|
-
} catch (error) {
|
|
881
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
882
|
-
this.logger.error(`Consumer onAdded failed for ${capability}: ${msg}`);
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
/**
|
|
889
|
-
* Unregister a provider (called when addon is disabled/uninstalled).
|
|
890
|
-
*/
|
|
891
|
-
unregisterProvider(capability, addonId) {
|
|
892
|
-
const state = this.capabilities.get(capability);
|
|
893
|
-
if (!state)
|
|
894
|
-
return;
|
|
895
|
-
const provider = state.available.get(addonId);
|
|
896
|
-
state.available.delete(addonId);
|
|
897
|
-
if (state.declaration.mode === "singleton") {
|
|
898
|
-
if (state.activeAddonId === addonId) {
|
|
899
|
-
state.activeAddonId = null;
|
|
900
|
-
state.activeProvider = null;
|
|
901
|
-
this.logger.info(`Singleton deactivated: ${capability} (was ${addonId})`);
|
|
902
|
-
}
|
|
903
|
-
} else {
|
|
904
|
-
const idx = state.activeCollection.findIndex((e) => e.addonId === addonId);
|
|
905
|
-
if (idx !== -1) {
|
|
906
|
-
state.activeCollection.splice(idx, 1);
|
|
907
|
-
for (const consumer of state.consumers) {
|
|
908
|
-
if (consumer.onRemoved && provider !== void 0) {
|
|
909
|
-
try {
|
|
910
|
-
consumer.onRemoved(provider);
|
|
911
|
-
} catch (error) {
|
|
912
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
913
|
-
this.logger.error(`Consumer onRemoved failed for ${capability}: ${msg}`);
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
/**
|
|
921
|
-
* Register a consumer that wants to be notified when providers change.
|
|
922
|
-
* If a provider is already active, the consumer is immediately notified.
|
|
923
|
-
* Returns a disposer function for cleanup.
|
|
924
|
-
*/
|
|
925
|
-
registerConsumer(registration) {
|
|
926
|
-
const state = this.capabilities.get(registration.capability);
|
|
927
|
-
if (!state) {
|
|
928
|
-
this.logger.debug(`Consumer registered for undeclared capability "${registration.capability}" \u2014 auto-declaring`);
|
|
929
|
-
this.declareCapability({ name: registration.capability, mode: "singleton" });
|
|
930
|
-
return this.registerConsumer(registration);
|
|
931
|
-
}
|
|
932
|
-
const untypedReg = registration;
|
|
933
|
-
state.consumers.add(untypedReg);
|
|
934
|
-
if (state.declaration.mode === "singleton") {
|
|
935
|
-
if (state.activeProvider !== null && registration.onSet) {
|
|
936
|
-
try {
|
|
937
|
-
registration.onSet(state.activeProvider);
|
|
938
|
-
} catch (error) {
|
|
939
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
940
|
-
this.logger.error(`Consumer onSet (immediate) failed for ${registration.capability}: ${msg}`);
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
} else {
|
|
944
|
-
if (registration.onAdded) {
|
|
945
|
-
for (const entry of state.activeCollection) {
|
|
946
|
-
try {
|
|
947
|
-
registration.onAdded(entry.provider);
|
|
948
|
-
} catch (error) {
|
|
949
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
950
|
-
this.logger.error(`Consumer onAdded (immediate) failed for ${registration.capability}: ${msg}`);
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
return () => {
|
|
956
|
-
state.consumers.delete(untypedReg);
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
/**
|
|
960
|
-
* Get the active singleton provider for a capability.
|
|
961
|
-
* Returns null if none set.
|
|
962
|
-
*/
|
|
963
|
-
getSingleton(capability) {
|
|
964
|
-
const state = this.capabilities.get(capability);
|
|
965
|
-
if (!state || state.declaration.mode !== "singleton")
|
|
966
|
-
return null;
|
|
967
|
-
return state.activeProvider ?? null;
|
|
968
|
-
}
|
|
969
|
-
/**
|
|
970
|
-
* Get all active collection providers for a capability.
|
|
971
|
-
*/
|
|
972
|
-
getCollection(capability) {
|
|
973
|
-
const state = this.capabilities.get(capability);
|
|
974
|
-
if (!state || state.declaration.mode !== "collection")
|
|
975
|
-
return [];
|
|
976
|
-
return state.activeCollection.map((e) => e.provider);
|
|
977
|
-
}
|
|
978
|
-
/**
|
|
979
|
-
* Set which addon should be the active singleton for a capability.
|
|
980
|
-
* Call with `immediate: true` to also swap the runtime provider now
|
|
981
|
-
* (consumers' onSet will be awaited).
|
|
982
|
-
*/
|
|
983
|
-
async setActiveSingleton(capability, addonId, immediate = false) {
|
|
984
|
-
const state = this.capabilities.get(capability);
|
|
985
|
-
if (!state) {
|
|
986
|
-
throw new Error(`Unknown capability: ${capability}`);
|
|
987
|
-
}
|
|
988
|
-
if (state.declaration.mode !== "singleton") {
|
|
989
|
-
throw new Error(`Capability "${capability}" is not a singleton`);
|
|
990
|
-
}
|
|
991
|
-
const provider = state.available.get(addonId);
|
|
992
|
-
if (!provider) {
|
|
993
|
-
throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
|
|
994
|
-
}
|
|
995
|
-
if (immediate) {
|
|
996
|
-
await this.activateSingletonAsync(state, addonId, provider);
|
|
997
|
-
}
|
|
998
|
-
this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* Get the mode declared for a capability.
|
|
1002
|
-
*/
|
|
1003
|
-
getMode(capability) {
|
|
1004
|
-
return this.capabilities.get(capability)?.declaration.mode;
|
|
1005
|
-
}
|
|
1006
|
-
/**
|
|
1007
|
-
* List all registered capabilities with their providers.
|
|
1008
|
-
*/
|
|
1009
|
-
listCapabilities() {
|
|
1010
|
-
const result = [];
|
|
1011
|
-
for (const [name, state] of this.capabilities) {
|
|
1012
|
-
result.push({
|
|
1013
|
-
name,
|
|
1014
|
-
mode: state.declaration.mode,
|
|
1015
|
-
providers: [...state.available.keys()],
|
|
1016
|
-
activeProvider: state.activeAddonId
|
|
1017
|
-
});
|
|
1018
|
-
}
|
|
1019
|
-
return result;
|
|
1020
|
-
}
|
|
1021
|
-
/**
|
|
1022
|
-
* Check if all dependencies for a capability are satisfied (have active providers).
|
|
1023
|
-
*/
|
|
1024
|
-
areDependenciesMet(declaration) {
|
|
1025
|
-
if (!declaration.dependsOn?.length)
|
|
1026
|
-
return true;
|
|
1027
|
-
return declaration.dependsOn.every((dep) => {
|
|
1028
|
-
const state = this.capabilities.get(dep);
|
|
1029
|
-
if (!state)
|
|
1030
|
-
return false;
|
|
1031
|
-
if (state.declaration.mode === "singleton") {
|
|
1032
|
-
return state.activeProvider !== null;
|
|
1033
|
-
}
|
|
1034
|
-
return state.activeCollection.length > 0;
|
|
1035
|
-
});
|
|
1036
|
-
}
|
|
1037
|
-
/**
|
|
1038
|
-
* Get the dependency-ordered list of capability names for boot sequencing.
|
|
1039
|
-
* Returns capabilities sorted topologically by dependsOn.
|
|
1040
|
-
* Throws if a cycle is detected.
|
|
1041
|
-
*/
|
|
1042
|
-
getBootOrder() {
|
|
1043
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1044
|
-
const visiting = /* @__PURE__ */ new Set();
|
|
1045
|
-
const order = [];
|
|
1046
|
-
const visit = (name) => {
|
|
1047
|
-
if (visited.has(name))
|
|
1048
|
-
return;
|
|
1049
|
-
if (visiting.has(name)) {
|
|
1050
|
-
throw new Error(`Circular dependency detected involving capability "${name}"`);
|
|
1051
|
-
}
|
|
1052
|
-
visiting.add(name);
|
|
1053
|
-
const state = this.capabilities.get(name);
|
|
1054
|
-
if (state?.declaration.dependsOn) {
|
|
1055
|
-
for (const dep of state.declaration.dependsOn) {
|
|
1056
|
-
visit(dep);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
visiting.delete(name);
|
|
1060
|
-
visited.add(name);
|
|
1061
|
-
order.push(name);
|
|
1062
|
-
};
|
|
1063
|
-
for (const name of this.capabilities.keys()) {
|
|
1064
|
-
visit(name);
|
|
1065
|
-
}
|
|
1066
|
-
return order;
|
|
1067
|
-
}
|
|
1068
|
-
// ---- Per-device overrides ----
|
|
1069
|
-
/**
|
|
1070
|
-
* Set a per-device singleton override. When resolveForDevice is called for
|
|
1071
|
-
* this device + capability, the specified addon's provider is returned
|
|
1072
|
-
* instead of the global singleton.
|
|
1073
|
-
*/
|
|
1074
|
-
setDeviceOverride(deviceId, capability, addonId) {
|
|
1075
|
-
const state = this.capabilities.get(capability);
|
|
1076
|
-
if (!state) {
|
|
1077
|
-
this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
|
|
1078
|
-
return;
|
|
1079
|
-
}
|
|
1080
|
-
if (!state.available.has(addonId)) {
|
|
1081
|
-
this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
|
|
1082
|
-
return;
|
|
1083
|
-
}
|
|
1084
|
-
let deviceMap = this.deviceOverrides.get(deviceId);
|
|
1085
|
-
if (!deviceMap) {
|
|
1086
|
-
deviceMap = /* @__PURE__ */ new Map();
|
|
1087
|
-
this.deviceOverrides.set(deviceId, deviceMap);
|
|
1088
|
-
}
|
|
1089
|
-
deviceMap.set(capability, addonId);
|
|
1090
|
-
this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
|
|
1091
|
-
}
|
|
1092
|
-
/**
|
|
1093
|
-
* Clear a per-device singleton override, reverting to the global singleton.
|
|
1094
|
-
*/
|
|
1095
|
-
clearDeviceOverride(deviceId, capability) {
|
|
1096
|
-
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
1097
|
-
if (!deviceMap)
|
|
1098
|
-
return;
|
|
1099
|
-
deviceMap.delete(capability);
|
|
1100
|
-
if (deviceMap.size === 0) {
|
|
1101
|
-
this.deviceOverrides.delete(deviceId);
|
|
1102
|
-
}
|
|
1103
|
-
this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
|
|
1104
|
-
}
|
|
1105
|
-
/**
|
|
1106
|
-
* Get all per-device singleton overrides for a device.
|
|
1107
|
-
* Returns a Map of capability name to addon ID.
|
|
1108
|
-
*/
|
|
1109
|
-
getDeviceOverrides(deviceId) {
|
|
1110
|
-
return new Map(this.deviceOverrides.get(deviceId) ?? []);
|
|
1111
|
-
}
|
|
1112
|
-
/**
|
|
1113
|
-
* Resolve a singleton provider for a specific device.
|
|
1114
|
-
* 1. Check device override — return that addon's provider
|
|
1115
|
-
* 2. Fallback to global singleton
|
|
1116
|
-
*/
|
|
1117
|
-
resolveForDevice(capability, deviceId) {
|
|
1118
|
-
const state = this.capabilities.get(capability);
|
|
1119
|
-
if (!state || state.declaration.mode !== "singleton")
|
|
1120
|
-
return null;
|
|
1121
|
-
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
1122
|
-
if (deviceMap) {
|
|
1123
|
-
const overrideAddonId = deviceMap.get(capability);
|
|
1124
|
-
if (overrideAddonId) {
|
|
1125
|
-
const provider = state.available.get(overrideAddonId);
|
|
1126
|
-
if (provider)
|
|
1127
|
-
return provider;
|
|
1128
|
-
this.logger.warn(`Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`);
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
return state.activeProvider ?? null;
|
|
1132
|
-
}
|
|
1133
|
-
/**
|
|
1134
|
-
* Set a per-device collection filter. When resolveCollectionForDevice is called
|
|
1135
|
-
* for this device + capability, only providers from the specified addon IDs
|
|
1136
|
-
* are returned instead of the full collection.
|
|
1137
|
-
*/
|
|
1138
|
-
setDeviceCollectionFilter(deviceId, capability, addonIds) {
|
|
1139
|
-
const state = this.capabilities.get(capability);
|
|
1140
|
-
if (!state) {
|
|
1141
|
-
this.logger.warn(`Cannot set device collection filter for undeclared capability "${capability}"`);
|
|
1142
|
-
return;
|
|
1143
|
-
}
|
|
1144
|
-
let deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
1145
|
-
if (!deviceMap) {
|
|
1146
|
-
deviceMap = /* @__PURE__ */ new Map();
|
|
1147
|
-
this.deviceCollectionFilters.set(deviceId, deviceMap);
|
|
1148
|
-
}
|
|
1149
|
-
deviceMap.set(capability, [...addonIds]);
|
|
1150
|
-
this.logger.info(`Device collection filter set: ${deviceId} \u2192 ${capability} = [${addonIds.join(", ")}]`);
|
|
1151
|
-
}
|
|
1152
|
-
/**
|
|
1153
|
-
* Clear a per-device collection filter, reverting to the full collection.
|
|
1154
|
-
*/
|
|
1155
|
-
clearDeviceCollectionFilter(deviceId, capability) {
|
|
1156
|
-
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
1157
|
-
if (!deviceMap)
|
|
1158
|
-
return;
|
|
1159
|
-
deviceMap.delete(capability);
|
|
1160
|
-
if (deviceMap.size === 0) {
|
|
1161
|
-
this.deviceCollectionFilters.delete(deviceId);
|
|
1162
|
-
}
|
|
1163
|
-
this.logger.info(`Device collection filter cleared: ${deviceId} \u2192 ${capability}`);
|
|
1164
|
-
}
|
|
1165
|
-
/**
|
|
1166
|
-
* Resolve collection providers for a specific device.
|
|
1167
|
-
* If a filter exists for the device + capability, only those addon's providers are returned.
|
|
1168
|
-
* If no filter exists, the full collection is returned.
|
|
1169
|
-
*/
|
|
1170
|
-
resolveCollectionForDevice(capability, deviceId) {
|
|
1171
|
-
const state = this.capabilities.get(capability);
|
|
1172
|
-
if (!state || state.declaration.mode !== "collection")
|
|
1173
|
-
return [];
|
|
1174
|
-
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
1175
|
-
if (deviceMap) {
|
|
1176
|
-
const filterAddonIds = deviceMap.get(capability);
|
|
1177
|
-
if (filterAddonIds) {
|
|
1178
|
-
const filterSet = new Set(filterAddonIds);
|
|
1179
|
-
return state.activeCollection.filter((e) => filterSet.has(e.addonId)).map((e) => e.provider);
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
return state.activeCollection.map((e) => e.provider);
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Get a specific addon's provider by addon ID, regardless of whether it's the active singleton.
|
|
1186
|
-
* Useful for per-device overrides that need to look up any registered provider.
|
|
1187
|
-
*/
|
|
1188
|
-
getProviderByAddonId(capability, addonId) {
|
|
1189
|
-
const state = this.capabilities.get(capability);
|
|
1190
|
-
if (!state)
|
|
1191
|
-
return null;
|
|
1192
|
-
const provider = state.available.get(addonId);
|
|
1193
|
-
return provider ?? null;
|
|
1194
|
-
}
|
|
1195
|
-
activateSingleton(state, addonId, provider) {
|
|
1196
|
-
state.activeAddonId = addonId;
|
|
1197
|
-
state.activeProvider = provider;
|
|
1198
|
-
this.logger.info(`Singleton activated: ${state.declaration.name} \u2192 ${addonId}`);
|
|
1199
|
-
for (const consumer of state.consumers) {
|
|
1200
|
-
if (consumer.onSet) {
|
|
1201
|
-
try {
|
|
1202
|
-
consumer.onSet(provider);
|
|
1203
|
-
} catch (error) {
|
|
1204
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
1205
|
-
this.logger.error(`Consumer onSet failed for ${state.declaration.name}: ${msg}`);
|
|
1206
|
-
}
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1141
|
+
// src/config-manager.ts
|
|
1142
|
+
var ENV_VAR_MAP = {
|
|
1143
|
+
CAMSTACK_PORT: "server.port",
|
|
1144
|
+
CAMSTACK_HOST: "server.host",
|
|
1145
|
+
CAMSTACK_DATA: "server.dataPath",
|
|
1146
|
+
CAMSTACK_JWT_SECRET: "auth.jwtSecret",
|
|
1147
|
+
CAMSTACK_ADMIN_USER: "auth.adminUsername",
|
|
1148
|
+
CAMSTACK_ADMIN_PASS: "auth.adminPassword"
|
|
1149
|
+
};
|
|
1150
|
+
var ConfigManager = class _ConfigManager {
|
|
1151
|
+
constructor(configPath) {
|
|
1152
|
+
this.configPath = configPath;
|
|
1153
|
+
const rawYaml = this.loadYaml();
|
|
1154
|
+
const merged = this.applyEnvOverrides(rawYaml);
|
|
1155
|
+
this.bootstrapConfig = bootstrapSchema.parse(merged);
|
|
1156
|
+
this.warnDefaultCredentials();
|
|
1157
|
+
}
|
|
1158
|
+
// Non-readonly so update() can sync the in-memory view after a write.
|
|
1159
|
+
bootstrapConfig;
|
|
1160
|
+
settingsStore = null;
|
|
1161
|
+
/** Called by main.ts after the SQLite DB is ready (Phase 2). */
|
|
1162
|
+
setSettingsStore(store) {
|
|
1163
|
+
this.settingsStore = store;
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Get a config value by dot-notation path.
|
|
1167
|
+
* Priority: bootstrap config -> SQL system_settings -> RUNTIME_DEFAULTS fallback.
|
|
1168
|
+
*/
|
|
1169
|
+
get(path5) {
|
|
1170
|
+
const bootstrapValue = this.getFromBootstrap(path5);
|
|
1171
|
+
if (bootstrapValue !== void 0) {
|
|
1172
|
+
return bootstrapValue;
|
|
1173
|
+
}
|
|
1174
|
+
if (this.settingsStore !== null) {
|
|
1175
|
+
const sqlValue = this.settingsStore.getSystem(path5);
|
|
1176
|
+
if (sqlValue !== void 0) {
|
|
1177
|
+
return sqlValue;
|
|
1209
1178
|
}
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
this.logger.info(`Singleton activated (async): ${state.declaration.name} \u2192 ${addonId}`);
|
|
1214
|
-
for (const consumer of state.consumers) {
|
|
1215
|
-
if (consumer.onSet) {
|
|
1216
|
-
try {
|
|
1217
|
-
await consumer.onSet(provider);
|
|
1218
|
-
} catch (error) {
|
|
1219
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
1220
|
-
this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1179
|
+
const sqlNested = this.getNestedFromSystemSettings(path5);
|
|
1180
|
+
if (sqlNested !== void 0) {
|
|
1181
|
+
return sqlNested;
|
|
1224
1182
|
}
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1183
|
+
}
|
|
1184
|
+
if (path5 in RUNTIME_DEFAULTS) {
|
|
1185
|
+
return RUNTIME_DEFAULTS[path5];
|
|
1186
|
+
}
|
|
1187
|
+
const nested = this.getFromRuntimeDefaults(path5);
|
|
1188
|
+
if (nested !== void 0) {
|
|
1189
|
+
return nested;
|
|
1190
|
+
}
|
|
1191
|
+
return void 0;
|
|
1227
1192
|
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
exports2.INFRA_CAPABILITIES = void 0;
|
|
1236
|
-
exports2.isInfraCapability = isInfraCapability2;
|
|
1237
|
-
exports2.INFRA_CAPABILITIES = [
|
|
1238
|
-
{ name: "storage", required: true },
|
|
1239
|
-
{ name: "settings-store", required: true },
|
|
1240
|
-
{ name: "log-destination", required: false }
|
|
1241
|
-
];
|
|
1242
|
-
var infraNames = new Set(exports2.INFRA_CAPABILITIES.map((c) => c.name));
|
|
1243
|
-
function isInfraCapability2(name) {
|
|
1244
|
-
return infraNames.has(name);
|
|
1193
|
+
/**
|
|
1194
|
+
* Write a value to SQL system_settings.
|
|
1195
|
+
* Throws if the settings store is not yet wired.
|
|
1196
|
+
*/
|
|
1197
|
+
set(key, value) {
|
|
1198
|
+
if (this.settingsStore === null) {
|
|
1199
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1245
1200
|
}
|
|
1201
|
+
this.settingsStore.setSystem(key, value);
|
|
1246
1202
|
}
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
"
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
"
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
"
|
|
1328
|
-
"
|
|
1329
|
-
"
|
|
1330
|
-
"
|
|
1331
|
-
"
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1203
|
+
/**
|
|
1204
|
+
* Bulk-read all system_settings keys that belong to a logical section.
|
|
1205
|
+
* A "section" is the first segment of a dot-notation key (e.g. 'features', 'logging').
|
|
1206
|
+
*/
|
|
1207
|
+
getSection(section) {
|
|
1208
|
+
if (this.settingsStore !== null) {
|
|
1209
|
+
const nested = this.getNestedFromSystemSettings(section);
|
|
1210
|
+
if (nested !== void 0) return nested;
|
|
1211
|
+
}
|
|
1212
|
+
const bootstrapValue = this.bootstrapConfig[section];
|
|
1213
|
+
if (bootstrapValue !== void 0 && bootstrapValue !== null && typeof bootstrapValue === "object") {
|
|
1214
|
+
return bootstrapValue;
|
|
1215
|
+
}
|
|
1216
|
+
return this.getFromRuntimeDefaults(section) ?? {};
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Bulk-write a section of runtime settings to SQL system_settings.
|
|
1220
|
+
* Each entry in `data` is stored as `section.key`.
|
|
1221
|
+
*/
|
|
1222
|
+
setSection(section, data) {
|
|
1223
|
+
if (this.settingsStore === null) {
|
|
1224
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1225
|
+
}
|
|
1226
|
+
for (const [key, value] of Object.entries(data)) {
|
|
1227
|
+
this.settingsStore.setSystem(`${section}.${key}`, value);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
// ---------------------------------------------------------------------------
|
|
1231
|
+
// Addon / Provider / Device scoped config
|
|
1232
|
+
// ---------------------------------------------------------------------------
|
|
1233
|
+
/** Read all config for an addon from addon_settings. */
|
|
1234
|
+
getAddonConfig(addonId) {
|
|
1235
|
+
if (this.settingsStore !== null) {
|
|
1236
|
+
return this.settingsStore.getAllAddon(addonId);
|
|
1237
|
+
}
|
|
1238
|
+
return this.getFromBootstrap(`addons.${addonId}`) ?? {};
|
|
1239
|
+
}
|
|
1240
|
+
/** Write (bulk-replace) config for an addon to addon_settings. */
|
|
1241
|
+
setAddonConfig(addonId, config) {
|
|
1242
|
+
if (this.settingsStore === null) {
|
|
1243
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1244
|
+
}
|
|
1245
|
+
this.settingsStore.setAllAddon(addonId, config);
|
|
1246
|
+
}
|
|
1247
|
+
/** Read all config for a provider from provider_settings. */
|
|
1248
|
+
getProviderConfig(providerId) {
|
|
1249
|
+
if (this.settingsStore !== null) {
|
|
1250
|
+
return this.settingsStore.getAllProvider(providerId);
|
|
1251
|
+
}
|
|
1252
|
+
return {};
|
|
1253
|
+
}
|
|
1254
|
+
/** Write (upsert) a single key for a provider to provider_settings. */
|
|
1255
|
+
setProviderConfig(providerId, key, value) {
|
|
1256
|
+
if (this.settingsStore === null) {
|
|
1257
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1258
|
+
}
|
|
1259
|
+
this.settingsStore.setProvider(providerId, key, value);
|
|
1260
|
+
}
|
|
1261
|
+
/** Read all config for a device from device_settings. */
|
|
1262
|
+
getDeviceConfig(deviceId) {
|
|
1263
|
+
if (this.settingsStore !== null) {
|
|
1264
|
+
return this.settingsStore.getAllDevice(deviceId);
|
|
1265
|
+
}
|
|
1266
|
+
return {};
|
|
1267
|
+
}
|
|
1268
|
+
/** Write (upsert) a single key for a device to device_settings. */
|
|
1269
|
+
setDeviceConfig(deviceId, key, value) {
|
|
1270
|
+
if (this.settingsStore === null) {
|
|
1271
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1272
|
+
}
|
|
1273
|
+
this.settingsStore.setDevice(deviceId, key, value);
|
|
1274
|
+
}
|
|
1275
|
+
/** Get a value from the parsed bootstrap config */
|
|
1276
|
+
getBootstrap(path5) {
|
|
1277
|
+
return this.getFromBootstrap(path5);
|
|
1278
|
+
}
|
|
1279
|
+
/** Features accessor -- reads from SQL when available, falls back to RUNTIME_DEFAULTS */
|
|
1280
|
+
get features() {
|
|
1281
|
+
const g = (key) => this.get(`features.${key}`) ?? RUNTIME_DEFAULTS[`features.${key}`];
|
|
1282
|
+
return {
|
|
1283
|
+
streaming: g("streaming"),
|
|
1284
|
+
notifications: g("notifications"),
|
|
1285
|
+
objectDetection: g("objectDetection"),
|
|
1286
|
+
remoteAccess: g("remoteAccess"),
|
|
1287
|
+
agentCluster: g("agentCluster"),
|
|
1288
|
+
smartHome: g("smartHome"),
|
|
1289
|
+
recordings: g("recordings"),
|
|
1290
|
+
backup: g("backup"),
|
|
1291
|
+
repl: g("repl")
|
|
1335
1292
|
};
|
|
1336
1293
|
}
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
Object.defineProperty(o, k2, desc);
|
|
1352
|
-
}) : (function(o, m, k, k2) {
|
|
1353
|
-
if (k2 === void 0) k2 = k;
|
|
1354
|
-
o[k2] = m[k];
|
|
1355
|
-
}));
|
|
1356
|
-
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
|
|
1357
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
1358
|
-
}) : function(o, v) {
|
|
1359
|
-
o["default"] = v;
|
|
1360
|
-
});
|
|
1361
|
-
var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
|
|
1362
|
-
var ownKeys = function(o) {
|
|
1363
|
-
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
1364
|
-
var ar = [];
|
|
1365
|
-
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
1366
|
-
return ar;
|
|
1367
|
-
};
|
|
1368
|
-
return ownKeys(o);
|
|
1369
|
-
};
|
|
1370
|
-
return function(mod) {
|
|
1371
|
-
if (mod && mod.__esModule) return mod;
|
|
1372
|
-
var result = {};
|
|
1373
|
-
if (mod != null) {
|
|
1374
|
-
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
1375
|
-
}
|
|
1376
|
-
__setModuleDefault(result, mod);
|
|
1377
|
-
return result;
|
|
1378
|
-
};
|
|
1379
|
-
})();
|
|
1380
|
-
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
1381
|
-
exports2.ConfigManager = void 0;
|
|
1382
|
-
var fs = __importStar(require("fs"));
|
|
1383
|
-
var yaml = __importStar(require("js-yaml"));
|
|
1384
|
-
var config_schema_js_1 = require_config_schema();
|
|
1385
|
-
var ENV_VAR_MAP = {
|
|
1386
|
-
CAMSTACK_PORT: "server.port",
|
|
1387
|
-
CAMSTACK_HOST: "server.host",
|
|
1388
|
-
CAMSTACK_DATA: "server.dataPath",
|
|
1389
|
-
CAMSTACK_JWT_SECRET: "auth.jwtSecret",
|
|
1390
|
-
CAMSTACK_ADMIN_USER: "auth.adminUsername",
|
|
1391
|
-
CAMSTACK_ADMIN_PASS: "auth.adminPassword"
|
|
1294
|
+
/**
|
|
1295
|
+
* Returns a merged view of bootstrap config + runtime defaults for backward compat.
|
|
1296
|
+
*/
|
|
1297
|
+
get raw() {
|
|
1298
|
+
const features = {
|
|
1299
|
+
streaming: RUNTIME_DEFAULTS["features.streaming"],
|
|
1300
|
+
notifications: RUNTIME_DEFAULTS["features.notifications"],
|
|
1301
|
+
objectDetection: RUNTIME_DEFAULTS["features.objectDetection"],
|
|
1302
|
+
remoteAccess: RUNTIME_DEFAULTS["features.remoteAccess"],
|
|
1303
|
+
agentCluster: RUNTIME_DEFAULTS["features.agentCluster"],
|
|
1304
|
+
smartHome: RUNTIME_DEFAULTS["features.smartHome"],
|
|
1305
|
+
recordings: RUNTIME_DEFAULTS["features.recordings"],
|
|
1306
|
+
backup: RUNTIME_DEFAULTS["features.backup"],
|
|
1307
|
+
repl: RUNTIME_DEFAULTS["features.repl"]
|
|
1392
1308
|
};
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
}
|
|
1474
|
-
}
|
|
1475
|
-
// ---------------------------------------------------------------------------
|
|
1476
|
-
// Addon / Provider / Device scoped config
|
|
1477
|
-
// ---------------------------------------------------------------------------
|
|
1478
|
-
/** Read all config for an addon from addon_settings. */
|
|
1479
|
-
getAddonConfig(addonId) {
|
|
1480
|
-
if (this.settingsStore !== null) {
|
|
1481
|
-
return this.settingsStore.getAllAddon(addonId);
|
|
1482
|
-
}
|
|
1483
|
-
return this.getFromBootstrap(`addons.${addonId}`) ?? {};
|
|
1484
|
-
}
|
|
1485
|
-
/** Write (bulk-replace) config for an addon to addon_settings. */
|
|
1486
|
-
setAddonConfig(addonId, config) {
|
|
1487
|
-
if (this.settingsStore === null) {
|
|
1488
|
-
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1489
|
-
}
|
|
1490
|
-
this.settingsStore.setAllAddon(addonId, config);
|
|
1491
|
-
}
|
|
1492
|
-
/** Read all config for a provider from provider_settings. */
|
|
1493
|
-
getProviderConfig(providerId) {
|
|
1494
|
-
if (this.settingsStore !== null) {
|
|
1495
|
-
return this.settingsStore.getAllProvider(providerId);
|
|
1496
|
-
}
|
|
1497
|
-
return {};
|
|
1498
|
-
}
|
|
1499
|
-
/** Write (upsert) a single key for a provider to provider_settings. */
|
|
1500
|
-
setProviderConfig(providerId, key, value) {
|
|
1501
|
-
if (this.settingsStore === null) {
|
|
1502
|
-
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1503
|
-
}
|
|
1504
|
-
this.settingsStore.setProvider(providerId, key, value);
|
|
1505
|
-
}
|
|
1506
|
-
/** Read all config for a device from device_settings. */
|
|
1507
|
-
getDeviceConfig(deviceId) {
|
|
1508
|
-
if (this.settingsStore !== null) {
|
|
1509
|
-
return this.settingsStore.getAllDevice(deviceId);
|
|
1510
|
-
}
|
|
1511
|
-
return {};
|
|
1512
|
-
}
|
|
1513
|
-
/** Write (upsert) a single key for a device to device_settings. */
|
|
1514
|
-
setDeviceConfig(deviceId, key, value) {
|
|
1515
|
-
if (this.settingsStore === null) {
|
|
1516
|
-
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1517
|
-
}
|
|
1518
|
-
this.settingsStore.setDevice(deviceId, key, value);
|
|
1519
|
-
}
|
|
1520
|
-
/** Get a value from the parsed bootstrap config */
|
|
1521
|
-
getBootstrap(path) {
|
|
1522
|
-
return this.getFromBootstrap(path);
|
|
1523
|
-
}
|
|
1524
|
-
/** Features accessor -- reads from SQL when available, falls back to RUNTIME_DEFAULTS */
|
|
1525
|
-
get features() {
|
|
1526
|
-
const g = (key) => this.get(`features.${key}`) ?? config_schema_js_1.RUNTIME_DEFAULTS[`features.${key}`];
|
|
1527
|
-
return {
|
|
1528
|
-
streaming: g("streaming"),
|
|
1529
|
-
notifications: g("notifications"),
|
|
1530
|
-
objectDetection: g("objectDetection"),
|
|
1531
|
-
remoteAccess: g("remoteAccess"),
|
|
1532
|
-
agentCluster: g("agentCluster"),
|
|
1533
|
-
smartHome: g("smartHome"),
|
|
1534
|
-
recordings: g("recordings"),
|
|
1535
|
-
backup: g("backup"),
|
|
1536
|
-
repl: g("repl")
|
|
1537
|
-
};
|
|
1538
|
-
}
|
|
1539
|
-
/**
|
|
1540
|
-
* Returns a merged view of bootstrap config + runtime defaults for backward compat.
|
|
1541
|
-
*/
|
|
1542
|
-
get raw() {
|
|
1543
|
-
const features = {
|
|
1544
|
-
streaming: config_schema_js_1.RUNTIME_DEFAULTS["features.streaming"],
|
|
1545
|
-
notifications: config_schema_js_1.RUNTIME_DEFAULTS["features.notifications"],
|
|
1546
|
-
objectDetection: config_schema_js_1.RUNTIME_DEFAULTS["features.objectDetection"],
|
|
1547
|
-
remoteAccess: config_schema_js_1.RUNTIME_DEFAULTS["features.remoteAccess"],
|
|
1548
|
-
agentCluster: config_schema_js_1.RUNTIME_DEFAULTS["features.agentCluster"],
|
|
1549
|
-
smartHome: config_schema_js_1.RUNTIME_DEFAULTS["features.smartHome"],
|
|
1550
|
-
recordings: config_schema_js_1.RUNTIME_DEFAULTS["features.recordings"],
|
|
1551
|
-
backup: config_schema_js_1.RUNTIME_DEFAULTS["features.backup"],
|
|
1552
|
-
repl: config_schema_js_1.RUNTIME_DEFAULTS["features.repl"]
|
|
1553
|
-
};
|
|
1554
|
-
return {
|
|
1555
|
-
...this.bootstrapConfig,
|
|
1556
|
-
features,
|
|
1557
|
-
storage: config_schema_js_1.RUNTIME_DEFAULTS["storage.locations"] !== void 0 ? {
|
|
1558
|
-
provider: config_schema_js_1.RUNTIME_DEFAULTS["storage.provider"],
|
|
1559
|
-
locations: config_schema_js_1.RUNTIME_DEFAULTS["storage.locations"]
|
|
1560
|
-
} : { provider: "sqlite-storage", locations: {} },
|
|
1561
|
-
logging: {
|
|
1562
|
-
level: config_schema_js_1.RUNTIME_DEFAULTS["logging.level"],
|
|
1563
|
-
retentionDays: config_schema_js_1.RUNTIME_DEFAULTS["logging.retentionDays"]
|
|
1564
|
-
},
|
|
1565
|
-
eventBus: {
|
|
1566
|
-
ringBufferSize: config_schema_js_1.RUNTIME_DEFAULTS["eventBus.ringBufferSize"]
|
|
1567
|
-
},
|
|
1568
|
-
retention: {
|
|
1569
|
-
detectionEventsDays: config_schema_js_1.RUNTIME_DEFAULTS["retention.detectionEventsDays"],
|
|
1570
|
-
audioLevelsDays: config_schema_js_1.RUNTIME_DEFAULTS["retention.audioLevelsDays"]
|
|
1571
|
-
},
|
|
1572
|
-
providers: config_schema_js_1.RUNTIME_DEFAULTS["providers"]
|
|
1573
|
-
};
|
|
1574
|
-
}
|
|
1575
|
-
/** Sections that live in config.yaml. Everything else goes to SQL. */
|
|
1576
|
-
static BOOTSTRAP_SECTIONS = /* @__PURE__ */ new Set(["server", "auth", "mode"]);
|
|
1577
|
-
/**
|
|
1578
|
-
* Atomically update one top-level section of config.yaml and sync in-memory.
|
|
1579
|
-
* Only bootstrap sections (server, auth, mode) are written to YAML.
|
|
1580
|
-
* Runtime settings must use setSection() which writes to SQL.
|
|
1581
|
-
*/
|
|
1582
|
-
update(section, data) {
|
|
1583
|
-
if (!_ConfigManager.BOOTSTRAP_SECTIONS.has(section)) {
|
|
1584
|
-
throw new Error(`[ConfigManager] Section "${section}" is a runtime setting \u2014 use setSection() to write to DB, not update() which writes to config.yaml`);
|
|
1585
|
-
}
|
|
1586
|
-
let raw = {};
|
|
1587
|
-
if (fs.existsSync(this.configPath)) {
|
|
1588
|
-
raw = yaml.load(fs.readFileSync(this.configPath, "utf-8")) ?? {};
|
|
1589
|
-
}
|
|
1590
|
-
const existing = raw[section] ?? {};
|
|
1591
|
-
raw[section] = { ...existing, ...data };
|
|
1592
|
-
const validation = config_schema_js_1.bootstrapSchema.safeParse(raw);
|
|
1593
|
-
if (!validation.success) {
|
|
1594
|
-
throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
|
|
1595
|
-
}
|
|
1596
|
-
const tmpPath = `${this.configPath}.tmp`;
|
|
1597
|
-
fs.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
|
|
1598
|
-
fs.renameSync(tmpPath, this.configPath);
|
|
1599
|
-
this.bootstrapConfig = validation.data;
|
|
1600
|
-
}
|
|
1601
|
-
/**
|
|
1602
|
-
* Deep-set a value in a nested plain object using a dot-notation path.
|
|
1603
|
-
* Returns a new object (immutable).
|
|
1604
|
-
*/
|
|
1605
|
-
setNested(obj, path, value) {
|
|
1606
|
-
const [head, ...rest] = path.split(".");
|
|
1607
|
-
if (!head)
|
|
1608
|
-
return obj;
|
|
1609
|
-
if (rest.length === 0) {
|
|
1610
|
-
return { ...obj, [head]: value };
|
|
1611
|
-
}
|
|
1612
|
-
const child = obj[head] ?? {};
|
|
1613
|
-
return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
|
|
1614
|
-
}
|
|
1615
|
-
/**
|
|
1616
|
-
* Apply env var overrides onto the raw YAML object.
|
|
1617
|
-
* Only bootstrap-level env vars are applied.
|
|
1618
|
-
*/
|
|
1619
|
-
applyEnvOverrides(raw) {
|
|
1620
|
-
let result = { ...raw };
|
|
1621
|
-
for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
|
|
1622
|
-
const envValue = process.env[envKey];
|
|
1623
|
-
if (envValue === void 0 || envValue === "")
|
|
1624
|
-
continue;
|
|
1625
|
-
const coerced = configPath === "server.port" ? Number(envValue) : envValue;
|
|
1626
|
-
result = this.setNested(result, configPath, coerced);
|
|
1627
|
-
console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
|
|
1628
|
-
}
|
|
1629
|
-
return result;
|
|
1630
|
-
}
|
|
1631
|
-
loadYaml() {
|
|
1632
|
-
if (!fs.existsSync(this.configPath)) {
|
|
1633
|
-
console.warn(`[ConfigManager] Config file not found at: ${this.configPath}
|
|
1309
|
+
return {
|
|
1310
|
+
...this.bootstrapConfig,
|
|
1311
|
+
features,
|
|
1312
|
+
storage: RUNTIME_DEFAULTS["storage.locations"] !== void 0 ? {
|
|
1313
|
+
provider: RUNTIME_DEFAULTS["storage.provider"],
|
|
1314
|
+
locations: RUNTIME_DEFAULTS["storage.locations"]
|
|
1315
|
+
} : { provider: "sqlite-storage", locations: {} },
|
|
1316
|
+
logging: {
|
|
1317
|
+
level: RUNTIME_DEFAULTS["logging.level"],
|
|
1318
|
+
retentionDays: RUNTIME_DEFAULTS["logging.retentionDays"]
|
|
1319
|
+
},
|
|
1320
|
+
eventBus: {
|
|
1321
|
+
ringBufferSize: RUNTIME_DEFAULTS["eventBus.ringBufferSize"]
|
|
1322
|
+
},
|
|
1323
|
+
retention: {
|
|
1324
|
+
detectionEventsDays: RUNTIME_DEFAULTS["retention.detectionEventsDays"],
|
|
1325
|
+
audioLevelsDays: RUNTIME_DEFAULTS["retention.audioLevelsDays"]
|
|
1326
|
+
},
|
|
1327
|
+
providers: RUNTIME_DEFAULTS["providers"]
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
/** Sections that live in config.yaml. Everything else goes to SQL. */
|
|
1331
|
+
static BOOTSTRAP_SECTIONS = /* @__PURE__ */ new Set(["server", "auth", "mode"]);
|
|
1332
|
+
/**
|
|
1333
|
+
* Atomically update one top-level section of config.yaml and sync in-memory.
|
|
1334
|
+
* Only bootstrap sections (server, auth, mode) are written to YAML.
|
|
1335
|
+
* Runtime settings must use setSection() which writes to SQL.
|
|
1336
|
+
*/
|
|
1337
|
+
update(section, data) {
|
|
1338
|
+
if (!_ConfigManager.BOOTSTRAP_SECTIONS.has(section)) {
|
|
1339
|
+
throw new Error(
|
|
1340
|
+
`[ConfigManager] Section "${section}" is a runtime setting \u2014 use setSection() to write to DB, not update() which writes to config.yaml`
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
let raw = {};
|
|
1344
|
+
if (fs5.existsSync(this.configPath)) {
|
|
1345
|
+
raw = yaml.load(fs5.readFileSync(this.configPath, "utf-8")) ?? {};
|
|
1346
|
+
}
|
|
1347
|
+
const existing = raw[section] ?? {};
|
|
1348
|
+
raw[section] = { ...existing, ...data };
|
|
1349
|
+
const validation = bootstrapSchema.safeParse(raw);
|
|
1350
|
+
if (!validation.success) {
|
|
1351
|
+
throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
|
|
1352
|
+
}
|
|
1353
|
+
const tmpPath = `${this.configPath}.tmp`;
|
|
1354
|
+
fs5.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
|
|
1355
|
+
fs5.renameSync(tmpPath, this.configPath);
|
|
1356
|
+
this.bootstrapConfig = validation.data;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Deep-set a value in a nested plain object using a dot-notation path.
|
|
1360
|
+
* Returns a new object (immutable).
|
|
1361
|
+
*/
|
|
1362
|
+
setNested(obj, path5, value) {
|
|
1363
|
+
const [head, ...rest] = path5.split(".");
|
|
1364
|
+
if (!head) return obj;
|
|
1365
|
+
if (rest.length === 0) {
|
|
1366
|
+
return { ...obj, [head]: value };
|
|
1367
|
+
}
|
|
1368
|
+
const child = obj[head] ?? {};
|
|
1369
|
+
return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Apply env var overrides onto the raw YAML object.
|
|
1373
|
+
* Only bootstrap-level env vars are applied.
|
|
1374
|
+
*/
|
|
1375
|
+
applyEnvOverrides(raw) {
|
|
1376
|
+
let result = { ...raw };
|
|
1377
|
+
for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
|
|
1378
|
+
const envValue = process.env[envKey];
|
|
1379
|
+
if (envValue === void 0 || envValue === "") continue;
|
|
1380
|
+
const coerced = configPath === "server.port" ? Number(envValue) : envValue;
|
|
1381
|
+
result = this.setNested(result, configPath, coerced);
|
|
1382
|
+
console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
|
|
1383
|
+
}
|
|
1384
|
+
return result;
|
|
1385
|
+
}
|
|
1386
|
+
loadYaml() {
|
|
1387
|
+
if (!fs5.existsSync(this.configPath)) {
|
|
1388
|
+
console.warn(
|
|
1389
|
+
`[ConfigManager] Config file not found at: ${this.configPath}
|
|
1634
1390
|
\u2192 Using built-in defaults. Set CONFIG_PATH env var or create the file.
|
|
1635
|
-
\u2192 Example path from project root: ./server/backend/data/config.yaml`
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
return current;
|
|
1391
|
+
\u2192 Example path from project root: ./server/backend/data/config.yaml`
|
|
1392
|
+
);
|
|
1393
|
+
return {};
|
|
1394
|
+
}
|
|
1395
|
+
const content = fs5.readFileSync(this.configPath, "utf-8");
|
|
1396
|
+
const parsed = yaml.load(content) ?? {};
|
|
1397
|
+
console.log(`[ConfigManager] Loaded config from: ${this.configPath}`);
|
|
1398
|
+
return parsed;
|
|
1399
|
+
}
|
|
1400
|
+
warnDefaultCredentials() {
|
|
1401
|
+
if (this.bootstrapConfig.auth.adminPassword === "changeme") {
|
|
1402
|
+
console.warn(
|
|
1403
|
+
`[ConfigManager] Warning: Using default admin password "changeme". Set auth.adminPassword in your config.yaml or the ADMIN_PASSWORD env var.`
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
getFromBootstrap(path5) {
|
|
1408
|
+
const keys = path5.split(".");
|
|
1409
|
+
let current = this.bootstrapConfig;
|
|
1410
|
+
for (const key of keys) {
|
|
1411
|
+
if (current === null || current === void 0 || typeof current !== "object") {
|
|
1412
|
+
return void 0;
|
|
1658
1413
|
}
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1414
|
+
current = current[key];
|
|
1415
|
+
}
|
|
1416
|
+
return current;
|
|
1417
|
+
}
|
|
1418
|
+
getFromRuntimeDefaults(path5) {
|
|
1419
|
+
const prefix = path5 + ".";
|
|
1420
|
+
const result = {};
|
|
1421
|
+
let found = false;
|
|
1422
|
+
for (const [key, value] of Object.entries(RUNTIME_DEFAULTS)) {
|
|
1423
|
+
if (key.startsWith(prefix)) {
|
|
1424
|
+
const subKey = key.slice(prefix.length);
|
|
1425
|
+
result[subKey] = value;
|
|
1426
|
+
found = true;
|
|
1671
1427
|
}
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
return found ? result : void 0;
|
|
1428
|
+
}
|
|
1429
|
+
return found ? result : void 0;
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Perform a prefix-based nested lookup against SQL system_settings.
|
|
1433
|
+
* e.g. path='features' matches keys 'features.streaming', 'features.notifications', etc.
|
|
1434
|
+
* Returns an object keyed by the sub-key, or undefined if nothing is found.
|
|
1435
|
+
*/
|
|
1436
|
+
getNestedFromSystemSettings(path5) {
|
|
1437
|
+
if (this.settingsStore === null) return void 0;
|
|
1438
|
+
const all = this.settingsStore.getAllSystem();
|
|
1439
|
+
const prefix = path5 + ".";
|
|
1440
|
+
const result = {};
|
|
1441
|
+
let found = false;
|
|
1442
|
+
for (const [key, value] of Object.entries(all)) {
|
|
1443
|
+
if (key.startsWith(prefix)) {
|
|
1444
|
+
result[key.slice(prefix.length)] = value;
|
|
1445
|
+
found = true;
|
|
1691
1446
|
}
|
|
1692
|
-
}
|
|
1693
|
-
|
|
1447
|
+
}
|
|
1448
|
+
return found ? result : void 0;
|
|
1694
1449
|
}
|
|
1695
|
-
}
|
|
1450
|
+
};
|
|
1696
1451
|
|
|
1697
|
-
// src/worker/addon-worker-host.
|
|
1698
|
-
var
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1452
|
+
// src/worker/addon-worker-host.ts
|
|
1453
|
+
var import_node_child_process3 = require("child_process");
|
|
1454
|
+
var INFRA_ADDON_IDS = /* @__PURE__ */ new Set([
|
|
1455
|
+
"filesystem-storage",
|
|
1456
|
+
"sqlite-settings",
|
|
1457
|
+
"winston-logging"
|
|
1458
|
+
]);
|
|
1459
|
+
var AddonWorkerHost = class {
|
|
1460
|
+
workers = /* @__PURE__ */ new Map();
|
|
1461
|
+
options;
|
|
1462
|
+
heartbeatTimer = null;
|
|
1463
|
+
/** Set of addons that failed to fork and fell back to in-process */
|
|
1464
|
+
fallbackInProcess = /* @__PURE__ */ new Set();
|
|
1465
|
+
constructor(options) {
|
|
1466
|
+
this.options = {
|
|
1467
|
+
workerEntryPath: options.workerEntryPath,
|
|
1468
|
+
devMode: options.devMode ?? false,
|
|
1469
|
+
forceInProcess: options.forceInProcess ?? process.env.CAMSTACK_FORCE_INPROCESS === "true",
|
|
1470
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? 5e3,
|
|
1471
|
+
heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 3e4,
|
|
1472
|
+
maxCrashesInWindow: options.maxCrashesInWindow ?? 3,
|
|
1473
|
+
crashWindowMs: options.crashWindowMs ?? 6e4,
|
|
1474
|
+
shutdownTimeoutMs: options.shutdownTimeoutMs ?? 1e4,
|
|
1475
|
+
onWorkerLog: options.onWorkerLog
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
/** Check if an addon is infrastructure (must stay in-process) */
|
|
1479
|
+
isInfraAddon(addonId) {
|
|
1480
|
+
return INFRA_ADDON_IDS.has(addonId);
|
|
1481
|
+
}
|
|
1482
|
+
/** Check if an addon fell back to in-process after fork failure */
|
|
1483
|
+
isFallbackInProcess(addonId) {
|
|
1484
|
+
return this.fallbackInProcess.has(addonId);
|
|
1485
|
+
}
|
|
1486
|
+
/** Mark an addon as fallen back to in-process */
|
|
1487
|
+
markFallbackInProcess(addonId) {
|
|
1488
|
+
this.fallbackInProcess.add(addonId);
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Determine if an addon should be forked.
|
|
1492
|
+
* Default: fork everything except infra addons.
|
|
1493
|
+
* Addons can opt out with `inProcess: true` in declaration.
|
|
1494
|
+
* Emergency fallback: CAMSTACK_FORCE_INPROCESS=true disables all forking.
|
|
1495
|
+
*/
|
|
1496
|
+
shouldFork(addonId, declaration) {
|
|
1497
|
+
if (this.options.forceInProcess) return false;
|
|
1498
|
+
if (this.options.devMode) return false;
|
|
1499
|
+
if (this.isInfraAddon(addonId)) return false;
|
|
1500
|
+
if (this.fallbackInProcess.has(addonId)) return false;
|
|
1501
|
+
if (declaration?.inProcess === true) return false;
|
|
1502
|
+
if (declaration?.forkable !== true) return false;
|
|
1503
|
+
return true;
|
|
1504
|
+
}
|
|
1505
|
+
/** Fork a worker for an addon */
|
|
1506
|
+
async forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1507
|
+
if (this.workers.has(addonId)) {
|
|
1508
|
+
throw new Error(`Worker for addon "${addonId}" already exists`);
|
|
1509
|
+
}
|
|
1510
|
+
const workerEnv = {
|
|
1511
|
+
PATH: process.env.PATH ?? "",
|
|
1512
|
+
HOME: process.env.HOME ?? "",
|
|
1513
|
+
NODE_ENV: process.env.NODE_ENV ?? "production",
|
|
1514
|
+
NODE_TLS_REJECT_UNAUTHORIZED: "0",
|
|
1515
|
+
// Accept self-signed cert
|
|
1516
|
+
CAMSTACK_WORKER_HUB_URL: `wss://localhost:${process.env.CAMSTACK_PORT ?? "4443"}/trpc`,
|
|
1517
|
+
CAMSTACK_WORKER_TOKEN: workerToken ?? "",
|
|
1518
|
+
CAMSTACK_ADDON_ID: addonId,
|
|
1519
|
+
CAMSTACK_ADDON_DIR: addonDir,
|
|
1520
|
+
CAMSTACK_ADDON_CONFIG: JSON.stringify(config),
|
|
1521
|
+
CAMSTACK_DATA_DIR: dataDir ?? `camstack-data/addons-data/${addonId}`,
|
|
1522
|
+
CAMSTACK_LOCATION_PATHS: JSON.stringify(locationPaths ?? storagePaths)
|
|
1523
|
+
};
|
|
1524
|
+
const forkOptions = {
|
|
1525
|
+
stdio: ["inherit", "inherit", "inherit", "ipc"],
|
|
1526
|
+
execArgv: [],
|
|
1527
|
+
env: workerEnv
|
|
1528
|
+
};
|
|
1529
|
+
const child = (0, import_node_child_process3.fork)(this.options.workerEntryPath, [], forkOptions);
|
|
1530
|
+
const worker = {
|
|
1531
|
+
addonId,
|
|
1532
|
+
process: child,
|
|
1533
|
+
state: "starting",
|
|
1534
|
+
startedAt: Date.now(),
|
|
1535
|
+
lastHeartbeat: Date.now(),
|
|
1536
|
+
restartCount: 0,
|
|
1537
|
+
crashTimestamps: [],
|
|
1538
|
+
cpuPercent: 0,
|
|
1539
|
+
memoryRss: 0,
|
|
1540
|
+
workerToken,
|
|
1541
|
+
forkConfig: { addonDir, config, storagePaths, dataDir, locationPaths, workerToken }
|
|
1542
|
+
};
|
|
1543
|
+
this.workers.set(addonId, worker);
|
|
1544
|
+
child.on("message", (msg) => {
|
|
1545
|
+
if (msg.type === "LOG" && this.options.onWorkerLog) {
|
|
1546
|
+
this.options.onWorkerLog({
|
|
1787
1547
|
addonId,
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
restartCount: 0,
|
|
1793
|
-
crashTimestamps: [],
|
|
1794
|
-
cpuPercent: 0,
|
|
1795
|
-
memoryRss: 0,
|
|
1796
|
-
workerToken
|
|
1797
|
-
};
|
|
1798
|
-
this.workers.set(addonId, worker);
|
|
1799
|
-
child.on("message", (msg) => {
|
|
1800
|
-
if (msg.type === "LOG" && this.options.onWorkerLog) {
|
|
1801
|
-
this.options.onWorkerLog({
|
|
1802
|
-
addonId,
|
|
1803
|
-
level: msg.level,
|
|
1804
|
-
message: msg.message,
|
|
1805
|
-
scope: ["hub", addonId],
|
|
1806
|
-
meta: msg.context
|
|
1807
|
-
});
|
|
1808
|
-
} else if (msg.type === "STATS") {
|
|
1809
|
-
worker.cpuPercent = msg.cpu;
|
|
1810
|
-
worker.memoryRss = msg.memory;
|
|
1811
|
-
}
|
|
1812
|
-
});
|
|
1813
|
-
child.stdout?.on("data", (chunk) => {
|
|
1814
|
-
const lines = chunk.toString().trim();
|
|
1815
|
-
if (!lines)
|
|
1816
|
-
return;
|
|
1817
|
-
if (this.options.onWorkerLog) {
|
|
1818
|
-
this.options.onWorkerLog({
|
|
1819
|
-
addonId,
|
|
1820
|
-
level: "info",
|
|
1821
|
-
message: lines,
|
|
1822
|
-
scope: ["hub", addonId, "__stdout"]
|
|
1823
|
-
});
|
|
1824
|
-
} else {
|
|
1825
|
-
console.log(`[Worker:${addonId}] ${lines}`);
|
|
1826
|
-
}
|
|
1827
|
-
});
|
|
1828
|
-
child.stderr?.on("data", (chunk) => {
|
|
1829
|
-
const lines = chunk.toString().trim();
|
|
1830
|
-
if (!lines)
|
|
1831
|
-
return;
|
|
1832
|
-
if (this.options.onWorkerLog) {
|
|
1833
|
-
this.options.onWorkerLog({
|
|
1834
|
-
addonId,
|
|
1835
|
-
level: "error",
|
|
1836
|
-
message: lines,
|
|
1837
|
-
scope: ["hub", addonId, "__stderr"]
|
|
1838
|
-
});
|
|
1839
|
-
} else {
|
|
1840
|
-
console.error(`[Worker:${addonId}:ERR] ${lines}`);
|
|
1841
|
-
}
|
|
1842
|
-
});
|
|
1843
|
-
child.on("exit", (code) => {
|
|
1844
|
-
this.handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken);
|
|
1845
|
-
});
|
|
1846
|
-
child.on("error", (err) => {
|
|
1847
|
-
console.error(`[WorkerHost] Worker ${addonId} error:`, err.message);
|
|
1848
|
-
});
|
|
1849
|
-
await new Promise((resolve, reject) => {
|
|
1850
|
-
const timeout = setTimeout(() => {
|
|
1851
|
-
reject(new Error(`Worker ${addonId} did not become ready within 30s`));
|
|
1852
|
-
}, 3e4);
|
|
1853
|
-
const readyCheck = (msg) => {
|
|
1854
|
-
if (msg.type === "READY") {
|
|
1855
|
-
clearTimeout(timeout);
|
|
1856
|
-
child.off("message", readyCheck);
|
|
1857
|
-
worker.state = "running";
|
|
1858
|
-
resolve();
|
|
1859
|
-
}
|
|
1860
|
-
};
|
|
1861
|
-
child.on("message", readyCheck);
|
|
1548
|
+
level: msg.level,
|
|
1549
|
+
message: msg.message,
|
|
1550
|
+
scope: ["hub", addonId],
|
|
1551
|
+
meta: msg.context
|
|
1862
1552
|
});
|
|
1553
|
+
} else if (msg.type === "STATS") {
|
|
1554
|
+
worker.cpuPercent = msg.cpu;
|
|
1555
|
+
worker.memoryRss = msg.memory;
|
|
1863
1556
|
}
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
/** Gracefully shutdown a single worker by addon ID */
|
|
1878
|
-
async shutdownWorkerById(addonId) {
|
|
1879
|
-
const worker = this.workers.get(addonId);
|
|
1880
|
-
if (!worker) {
|
|
1881
|
-
throw new Error(`No worker found for addon "${addonId}"`);
|
|
1882
|
-
}
|
|
1883
|
-
await this.shutdownWorker(addonId, worker);
|
|
1884
|
-
this.workers.delete(addonId);
|
|
1885
|
-
}
|
|
1886
|
-
/** Gracefully shutdown all workers */
|
|
1887
|
-
async shutdownAll() {
|
|
1888
|
-
if (this.heartbeatTimer) {
|
|
1889
|
-
clearInterval(this.heartbeatTimer);
|
|
1890
|
-
this.heartbeatTimer = null;
|
|
1891
|
-
}
|
|
1892
|
-
const shutdowns = [...this.workers.entries()].map(([addonId, worker]) => this.shutdownWorker(addonId, worker));
|
|
1893
|
-
await Promise.allSettled(shutdowns);
|
|
1894
|
-
this.workers.clear();
|
|
1895
|
-
}
|
|
1896
|
-
/** Start heartbeat monitoring — workers now report heartbeat via tRPC, not IPC PING */
|
|
1897
|
-
startHeartbeatMonitoring() {
|
|
1898
|
-
this.heartbeatTimer = setInterval(() => {
|
|
1899
|
-
const now = Date.now();
|
|
1900
|
-
for (const [addonId, worker] of this.workers) {
|
|
1901
|
-
if (worker.state !== "running")
|
|
1902
|
-
continue;
|
|
1903
|
-
if (now - worker.lastHeartbeat > this.options.heartbeatTimeoutMs) {
|
|
1904
|
-
console.warn(`[WorkerHost] Worker ${addonId} heartbeat timeout \u2014 marking unresponsive`);
|
|
1905
|
-
worker.state = "crashed";
|
|
1906
|
-
worker.process.kill("SIGKILL");
|
|
1907
|
-
}
|
|
1908
|
-
}
|
|
1909
|
-
}, this.options.heartbeatIntervalMs);
|
|
1557
|
+
});
|
|
1558
|
+
child.stdout?.on("data", (chunk) => {
|
|
1559
|
+
const lines = chunk.toString().trim();
|
|
1560
|
+
if (!lines) return;
|
|
1561
|
+
if (this.options.onWorkerLog) {
|
|
1562
|
+
this.options.onWorkerLog({
|
|
1563
|
+
addonId,
|
|
1564
|
+
level: "info",
|
|
1565
|
+
message: lines,
|
|
1566
|
+
scope: ["hub", addonId, "__stdout"]
|
|
1567
|
+
});
|
|
1568
|
+
} else {
|
|
1569
|
+
console.log(`[Worker:${addonId}] ${lines}`);
|
|
1910
1570
|
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1571
|
+
});
|
|
1572
|
+
child.stderr?.on("data", (chunk) => {
|
|
1573
|
+
const lines = chunk.toString().trim();
|
|
1574
|
+
if (!lines) return;
|
|
1575
|
+
if (this.options.onWorkerLog) {
|
|
1576
|
+
this.options.onWorkerLog({
|
|
1577
|
+
addonId,
|
|
1578
|
+
level: "error",
|
|
1579
|
+
message: lines,
|
|
1580
|
+
scope: ["hub", addonId, "__stderr"]
|
|
1581
|
+
});
|
|
1582
|
+
} else {
|
|
1583
|
+
console.error(`[Worker:${addonId}:ERR] ${lines}`);
|
|
1921
1584
|
}
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1585
|
+
});
|
|
1586
|
+
child.on("exit", (code) => {
|
|
1587
|
+
this.handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken);
|
|
1588
|
+
});
|
|
1589
|
+
child.on("error", (err) => {
|
|
1590
|
+
console.error(`[WorkerHost] Worker ${addonId} error:`, err.message);
|
|
1591
|
+
});
|
|
1592
|
+
await new Promise((resolve3, reject) => {
|
|
1593
|
+
const timeout = setTimeout(() => {
|
|
1594
|
+
reject(new Error(`Worker ${addonId} did not become ready within 30s`));
|
|
1595
|
+
}, 3e4);
|
|
1596
|
+
const readyCheck = (msg) => {
|
|
1597
|
+
if (msg.type === "READY") {
|
|
1598
|
+
clearTimeout(timeout);
|
|
1599
|
+
child.off("message", readyCheck);
|
|
1600
|
+
worker.state = "running";
|
|
1601
|
+
resolve3();
|
|
1939
1602
|
}
|
|
1940
|
-
|
|
1941
|
-
|
|
1603
|
+
};
|
|
1604
|
+
child.on("message", readyCheck);
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
/** List all workers with stats */
|
|
1608
|
+
listWorkers() {
|
|
1609
|
+
return [...this.workers.values()].map((w) => ({
|
|
1610
|
+
addonId: w.addonId,
|
|
1611
|
+
pid: w.process.pid ?? 0,
|
|
1612
|
+
state: w.state,
|
|
1613
|
+
cpuPercent: w.cpuPercent,
|
|
1614
|
+
memoryRss: w.memoryRss,
|
|
1615
|
+
uptimeSeconds: Math.round((Date.now() - w.startedAt) / 1e3),
|
|
1616
|
+
restartCount: w.restartCount,
|
|
1617
|
+
subProcesses: []
|
|
1618
|
+
}));
|
|
1619
|
+
}
|
|
1620
|
+
/** Gracefully shutdown a single worker by addon ID */
|
|
1621
|
+
async shutdownWorkerById(addonId) {
|
|
1622
|
+
const worker = this.workers.get(addonId);
|
|
1623
|
+
if (!worker) {
|
|
1624
|
+
throw new Error(`No worker found for addon "${addonId}"`);
|
|
1625
|
+
}
|
|
1626
|
+
await this.shutdownWorker(addonId, worker);
|
|
1627
|
+
this.workers.delete(addonId);
|
|
1628
|
+
}
|
|
1629
|
+
/** Gracefully restart a single worker by addon ID (stop then re-fork with same config) */
|
|
1630
|
+
async restartWorker(addonId) {
|
|
1631
|
+
const worker = this.workers.get(addonId);
|
|
1632
|
+
if (!worker) {
|
|
1633
|
+
throw new Error(`No worker found for addon "${addonId}"`);
|
|
1634
|
+
}
|
|
1635
|
+
const forkConfig = worker.forkConfig;
|
|
1636
|
+
if (!forkConfig) {
|
|
1637
|
+
throw new Error(`No fork config stored for addon "${addonId}" \u2014 cannot restart`);
|
|
1638
|
+
}
|
|
1639
|
+
await this.shutdownWorker(addonId, worker);
|
|
1640
|
+
this.workers.delete(addonId);
|
|
1641
|
+
await this.forkWorker(
|
|
1642
|
+
addonId,
|
|
1643
|
+
forkConfig.addonDir,
|
|
1644
|
+
forkConfig.config,
|
|
1645
|
+
forkConfig.storagePaths,
|
|
1646
|
+
forkConfig.dataDir,
|
|
1647
|
+
forkConfig.locationPaths,
|
|
1648
|
+
forkConfig.workerToken
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1651
|
+
/** Gracefully shutdown all workers */
|
|
1652
|
+
async shutdownAll() {
|
|
1653
|
+
if (this.heartbeatTimer) {
|
|
1654
|
+
clearInterval(this.heartbeatTimer);
|
|
1655
|
+
this.heartbeatTimer = null;
|
|
1656
|
+
}
|
|
1657
|
+
const shutdowns = [...this.workers.entries()].map(
|
|
1658
|
+
([addonId, worker]) => this.shutdownWorker(addonId, worker)
|
|
1659
|
+
);
|
|
1660
|
+
await Promise.allSettled(shutdowns);
|
|
1661
|
+
this.workers.clear();
|
|
1662
|
+
}
|
|
1663
|
+
/** Start heartbeat monitoring — workers now report heartbeat via tRPC, not IPC PING */
|
|
1664
|
+
startHeartbeatMonitoring() {
|
|
1665
|
+
this.heartbeatTimer = setInterval(() => {
|
|
1666
|
+
const now = Date.now();
|
|
1667
|
+
for (const [addonId, worker] of this.workers) {
|
|
1668
|
+
if (worker.state !== "running") continue;
|
|
1669
|
+
if (now - worker.lastHeartbeat > this.options.heartbeatTimeoutMs) {
|
|
1670
|
+
console.warn(`[WorkerHost] Worker ${addonId} heartbeat timeout \u2014 marking unresponsive`);
|
|
1671
|
+
worker.state = "crashed";
|
|
1672
|
+
worker.process.kill("SIGKILL");
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
}, this.options.heartbeatIntervalMs);
|
|
1676
|
+
}
|
|
1677
|
+
/** Update heartbeat timestamp for a worker (called when agent.heartbeat arrives) */
|
|
1678
|
+
updateWorkerHeartbeat(addonId, cpuPercent, memoryRss) {
|
|
1679
|
+
const worker = this.workers.get(addonId);
|
|
1680
|
+
if (!worker) return;
|
|
1681
|
+
worker.lastHeartbeat = Date.now();
|
|
1682
|
+
if (cpuPercent !== void 0) worker.cpuPercent = cpuPercent;
|
|
1683
|
+
if (memoryRss !== void 0) worker.memoryRss = memoryRss;
|
|
1684
|
+
}
|
|
1685
|
+
handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1686
|
+
const worker = this.workers.get(addonId);
|
|
1687
|
+
if (!worker) return;
|
|
1688
|
+
if (worker.state === "stopping") {
|
|
1689
|
+
worker.state = "stopped";
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
worker.state = "crashed";
|
|
1693
|
+
console.error(`[WorkerHost] Worker ${addonId} exited with code ${code}`);
|
|
1694
|
+
const now = Date.now();
|
|
1695
|
+
worker.crashTimestamps.push(now);
|
|
1696
|
+
const recentCrashes = worker.crashTimestamps.filter(
|
|
1697
|
+
(t) => now - t < this.options.crashWindowMs
|
|
1698
|
+
);
|
|
1699
|
+
worker.crashTimestamps = recentCrashes;
|
|
1700
|
+
if (recentCrashes.length >= this.options.maxCrashesInWindow) {
|
|
1701
|
+
console.error(`[WorkerHost] Worker ${addonId} crashed ${recentCrashes.length} times in ${this.options.crashWindowMs}ms \u2014 not restarting`);
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
const backoff = Math.min(2e3 * (worker.restartCount + 1), 3e4);
|
|
1705
|
+
console.log(`[WorkerHost] Restarting worker ${addonId} in ${backoff}ms`);
|
|
1706
|
+
setTimeout(() => {
|
|
1707
|
+
worker.restartCount++;
|
|
1708
|
+
this.workers.delete(addonId);
|
|
1709
|
+
this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
|
|
1710
|
+
console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
|
|
1711
|
+
});
|
|
1712
|
+
}, backoff);
|
|
1713
|
+
}
|
|
1714
|
+
async shutdownWorker(addonId, worker) {
|
|
1715
|
+
worker.state = "stopping";
|
|
1716
|
+
worker.process.kill("SIGTERM");
|
|
1717
|
+
await new Promise((resolve3) => {
|
|
1718
|
+
const timeout = setTimeout(() => {
|
|
1719
|
+
console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
|
|
1720
|
+
worker.process.kill("SIGKILL");
|
|
1721
|
+
resolve3();
|
|
1722
|
+
}, this.options.shutdownTimeoutMs);
|
|
1723
|
+
worker.process.on("exit", () => {
|
|
1724
|
+
clearTimeout(timeout);
|
|
1725
|
+
resolve3();
|
|
1726
|
+
});
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
};
|
|
1730
|
+
|
|
1731
|
+
// src/worker/worker-process-manager.ts
|
|
1732
|
+
var import_node_child_process4 = require("child_process");
|
|
1733
|
+
var WorkerProcessManager = class {
|
|
1734
|
+
constructor(sendToMain) {
|
|
1735
|
+
this.sendToMain = sendToMain;
|
|
1736
|
+
}
|
|
1737
|
+
processes = /* @__PURE__ */ new Map();
|
|
1738
|
+
async spawn(config) {
|
|
1739
|
+
const child = (0, import_node_child_process4.spawn)(config.command, [...config.args ?? []], {
|
|
1740
|
+
cwd: config.cwd,
|
|
1741
|
+
env: config.env ? { ...process.env, ...config.env } : void 0,
|
|
1742
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
1743
|
+
});
|
|
1744
|
+
const managed = new ManagedProcess(child, config, this.sendToMain);
|
|
1745
|
+
this.processes.set(child.pid, managed);
|
|
1746
|
+
this.sendToMain({
|
|
1747
|
+
type: "SUB_PROCESS_SPAWNED",
|
|
1748
|
+
pid: child.pid,
|
|
1749
|
+
name: config.name,
|
|
1750
|
+
command: config.command
|
|
1751
|
+
});
|
|
1752
|
+
child.on("exit", (code) => {
|
|
1753
|
+
this.sendToMain({
|
|
1754
|
+
type: "SUB_PROCESS_EXITED",
|
|
1755
|
+
pid: child.pid,
|
|
1756
|
+
code
|
|
1757
|
+
});
|
|
1758
|
+
if (config.autoRestart && managed.restartCount < (config.maxRestarts ?? 3)) {
|
|
1759
|
+
managed.restartCount++;
|
|
1942
1760
|
setTimeout(() => {
|
|
1943
|
-
|
|
1944
|
-
this.workers.delete(addonId);
|
|
1945
|
-
this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
|
|
1946
|
-
console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
|
|
1761
|
+
this.spawn(config).catch(() => {
|
|
1947
1762
|
});
|
|
1948
|
-
},
|
|
1949
|
-
}
|
|
1950
|
-
async shutdownWorker(addonId, worker) {
|
|
1951
|
-
worker.state = "stopping";
|
|
1952
|
-
worker.process.kill("SIGTERM");
|
|
1953
|
-
await new Promise((resolve) => {
|
|
1954
|
-
const timeout = setTimeout(() => {
|
|
1955
|
-
console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
|
|
1956
|
-
worker.process.kill("SIGKILL");
|
|
1957
|
-
resolve();
|
|
1958
|
-
}, this.options.shutdownTimeoutMs);
|
|
1959
|
-
worker.process.on("exit", () => {
|
|
1960
|
-
clearTimeout(timeout);
|
|
1961
|
-
resolve();
|
|
1962
|
-
});
|
|
1963
|
-
});
|
|
1763
|
+
}, 2e3);
|
|
1964
1764
|
}
|
|
1765
|
+
});
|
|
1766
|
+
return managed;
|
|
1767
|
+
}
|
|
1768
|
+
listProcesses() {
|
|
1769
|
+
return [...this.processes.values()].map((p) => p.toInfo());
|
|
1770
|
+
}
|
|
1771
|
+
getWorkerStats() {
|
|
1772
|
+
const mem = process.memoryUsage();
|
|
1773
|
+
const cpu = process.cpuUsage();
|
|
1774
|
+
return {
|
|
1775
|
+
pid: process.pid,
|
|
1776
|
+
cpuPercent: (cpu.user + cpu.system) / 1e6,
|
|
1777
|
+
memoryRss: mem.rss,
|
|
1778
|
+
heapUsed: mem.heapUsed,
|
|
1779
|
+
uptimeSeconds: Math.round(process.uptime()),
|
|
1780
|
+
restartCount: 0,
|
|
1781
|
+
state: "running"
|
|
1965
1782
|
};
|
|
1966
|
-
exports2.AddonWorkerHost = AddonWorkerHost2;
|
|
1967
1783
|
}
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
if (config.autoRestart && managed.restartCount < (config.maxRestarts ?? 3)) {
|
|
2004
|
-
managed.restartCount++;
|
|
2005
|
-
setTimeout(() => {
|
|
2006
|
-
this.spawn(config).catch(() => {
|
|
2007
|
-
});
|
|
2008
|
-
}, 2e3);
|
|
2009
|
-
}
|
|
2010
|
-
});
|
|
2011
|
-
return managed;
|
|
2012
|
-
}
|
|
2013
|
-
listProcesses() {
|
|
2014
|
-
return [...this.processes.values()].map((p) => p.toInfo());
|
|
2015
|
-
}
|
|
2016
|
-
getWorkerStats() {
|
|
2017
|
-
const mem = process.memoryUsage();
|
|
2018
|
-
const cpu = process.cpuUsage();
|
|
2019
|
-
return {
|
|
2020
|
-
pid: process.pid,
|
|
2021
|
-
cpuPercent: (cpu.user + cpu.system) / 1e6,
|
|
2022
|
-
memoryRss: mem.rss,
|
|
2023
|
-
heapUsed: mem.heapUsed,
|
|
2024
|
-
uptimeSeconds: Math.round(process.uptime()),
|
|
2025
|
-
restartCount: 0,
|
|
2026
|
-
state: "running"
|
|
2027
|
-
};
|
|
2028
|
-
}
|
|
2029
|
-
async killAll() {
|
|
2030
|
-
for (const [, proc] of this.processes) {
|
|
2031
|
-
proc.kill("SIGTERM");
|
|
2032
|
-
}
|
|
2033
|
-
this.processes.clear();
|
|
2034
|
-
}
|
|
1784
|
+
async killAll() {
|
|
1785
|
+
for (const [, proc] of this.processes) {
|
|
1786
|
+
proc.kill("SIGTERM");
|
|
1787
|
+
}
|
|
1788
|
+
this.processes.clear();
|
|
1789
|
+
}
|
|
1790
|
+
};
|
|
1791
|
+
var ManagedProcess = class {
|
|
1792
|
+
constructor(child, config, sendToMain) {
|
|
1793
|
+
this.child = child;
|
|
1794
|
+
this.config = config;
|
|
1795
|
+
this.sendToMain = sendToMain;
|
|
1796
|
+
this.pid = child.pid;
|
|
1797
|
+
this.name = config.name;
|
|
1798
|
+
child.on("exit", (code) => {
|
|
1799
|
+
for (const handler of this.exitHandlers) handler(code);
|
|
1800
|
+
});
|
|
1801
|
+
child.on("error", (err) => {
|
|
1802
|
+
for (const handler of this.errorHandlers) handler(err);
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1805
|
+
pid;
|
|
1806
|
+
name;
|
|
1807
|
+
restartCount = 0;
|
|
1808
|
+
startedAt = Date.now();
|
|
1809
|
+
exitHandlers = [];
|
|
1810
|
+
errorHandlers = [];
|
|
1811
|
+
getStats() {
|
|
1812
|
+
return {
|
|
1813
|
+
pid: this.pid,
|
|
1814
|
+
cpuPercent: 0,
|
|
1815
|
+
memoryRss: 0,
|
|
1816
|
+
uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1e3),
|
|
1817
|
+
restartCount: this.restartCount,
|
|
1818
|
+
state: this.child.exitCode !== null ? "stopped" : "running"
|
|
2035
1819
|
};
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
}
|
|
2075
|
-
get stdout() {
|
|
2076
|
-
return this.child.stdout;
|
|
2077
|
-
}
|
|
2078
|
-
get stderr() {
|
|
2079
|
-
return this.child.stderr;
|
|
2080
|
-
}
|
|
2081
|
-
kill(signal = "SIGTERM") {
|
|
2082
|
-
this.child.kill(signal);
|
|
2083
|
-
}
|
|
2084
|
-
wait() {
|
|
2085
|
-
if (this.child.exitCode !== null) {
|
|
2086
|
-
return Promise.resolve({ code: this.child.exitCode, signal: null });
|
|
2087
|
-
}
|
|
2088
|
-
return new Promise((resolve) => {
|
|
2089
|
-
this.child.on("exit", (code, signal) => {
|
|
2090
|
-
resolve({ code, signal });
|
|
2091
|
-
});
|
|
2092
|
-
});
|
|
2093
|
-
}
|
|
2094
|
-
onExit(handler) {
|
|
2095
|
-
this.exitHandlers.push(handler);
|
|
2096
|
-
}
|
|
2097
|
-
onError(handler) {
|
|
2098
|
-
this.errorHandlers.push(handler);
|
|
2099
|
-
}
|
|
2100
|
-
toInfo() {
|
|
2101
|
-
return {
|
|
2102
|
-
pid: this.pid,
|
|
2103
|
-
name: this.name,
|
|
2104
|
-
command: this.config.command,
|
|
2105
|
-
state: this.child.exitCode !== null ? "stopped" : "running",
|
|
2106
|
-
cpuPercent: 0,
|
|
2107
|
-
memoryRss: 0,
|
|
2108
|
-
uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1e3)
|
|
2109
|
-
};
|
|
2110
|
-
}
|
|
1820
|
+
}
|
|
1821
|
+
write(data) {
|
|
1822
|
+
this.child.stdin?.write(data);
|
|
1823
|
+
}
|
|
1824
|
+
get stdout() {
|
|
1825
|
+
return this.child.stdout;
|
|
1826
|
+
}
|
|
1827
|
+
get stderr() {
|
|
1828
|
+
return this.child.stderr;
|
|
1829
|
+
}
|
|
1830
|
+
kill(signal = "SIGTERM") {
|
|
1831
|
+
this.child.kill(signal);
|
|
1832
|
+
}
|
|
1833
|
+
wait() {
|
|
1834
|
+
if (this.child.exitCode !== null) {
|
|
1835
|
+
return Promise.resolve({ code: this.child.exitCode, signal: null });
|
|
1836
|
+
}
|
|
1837
|
+
return new Promise((resolve3) => {
|
|
1838
|
+
this.child.on("exit", (code, signal) => {
|
|
1839
|
+
resolve3({ code, signal });
|
|
1840
|
+
});
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
onExit(handler) {
|
|
1844
|
+
this.exitHandlers.push(handler);
|
|
1845
|
+
}
|
|
1846
|
+
onError(handler) {
|
|
1847
|
+
this.errorHandlers.push(handler);
|
|
1848
|
+
}
|
|
1849
|
+
toInfo() {
|
|
1850
|
+
return {
|
|
1851
|
+
pid: this.pid,
|
|
1852
|
+
name: this.name,
|
|
1853
|
+
command: this.config.command,
|
|
1854
|
+
state: this.child.exitCode !== null ? "stopped" : "running",
|
|
1855
|
+
cpuPercent: 0,
|
|
1856
|
+
memoryRss: 0,
|
|
1857
|
+
uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1e3)
|
|
2111
1858
|
};
|
|
2112
1859
|
}
|
|
2113
|
-
}
|
|
2114
|
-
|
|
2115
|
-
// src/index.ts
|
|
2116
|
-
var src_exports = {};
|
|
2117
|
-
__export(src_exports, {
|
|
2118
|
-
AddonEngineManager: () => import_addon_engine_manager.AddonEngineManager,
|
|
2119
|
-
AddonInstaller: () => import_addon_installer.AddonInstaller,
|
|
2120
|
-
AddonLoader: () => import_addon_loader.AddonLoader,
|
|
2121
|
-
AddonWorkerHost: () => import_addon_worker_host.AddonWorkerHost,
|
|
2122
|
-
CapabilityRegistry: () => import_capability_registry.CapabilityRegistry,
|
|
2123
|
-
ConfigManager: () => import_config_manager.ConfigManager,
|
|
2124
|
-
DEFAULT_DATA_PATH: () => import_config_schema.DEFAULT_DATA_PATH,
|
|
2125
|
-
INFRA_CAPABILITIES: () => import_infra_capabilities.INFRA_CAPABILITIES,
|
|
2126
|
-
RUNTIME_DEFAULTS: () => import_config_schema.RUNTIME_DEFAULTS,
|
|
2127
|
-
WorkerProcessManager: () => import_worker_process_manager.WorkerProcessManager,
|
|
2128
|
-
bootstrapSchema: () => import_config_schema.bootstrapSchema,
|
|
2129
|
-
copyDirRecursive: () => import_fs_utils.copyDirRecursive,
|
|
2130
|
-
copyExtraFileDirs: () => import_fs_utils.copyExtraFileDirs,
|
|
2131
|
-
detectWorkspacePackagesDir: () => import_workspace_detect.detectWorkspacePackagesDir,
|
|
2132
|
-
ensureDir: () => import_fs_utils.ensureDir,
|
|
2133
|
-
ensureLibraryBuilt: () => import_fs_utils.ensureLibraryBuilt,
|
|
2134
|
-
installPackageFromNpmSync: () => import_fs_utils.installPackageFromNpmSync,
|
|
2135
|
-
isInfraCapability: () => import_infra_capabilities.isInfraCapability,
|
|
2136
|
-
isSourceNewer: () => import_fs_utils.isSourceNewer,
|
|
2137
|
-
stripCamstackDeps: () => import_fs_utils.stripCamstackDeps,
|
|
2138
|
-
symlinkAddonsToNodeModules: () => import_fs_utils.symlinkAddonsToNodeModules
|
|
2139
|
-
});
|
|
2140
|
-
module.exports = __toCommonJS(src_exports);
|
|
2141
|
-
var import_addon_loader = __toESM(require_addon_loader());
|
|
2142
|
-
var import_addon_engine_manager = __toESM(require_addon_engine_manager());
|
|
2143
|
-
var import_addon_installer = __toESM(require_addon_installer());
|
|
2144
|
-
var import_fs_utils = __toESM(require_fs_utils());
|
|
2145
|
-
var import_workspace_detect = __toESM(require_workspace_detect());
|
|
2146
|
-
var import_capability_registry = __toESM(require_capability_registry());
|
|
2147
|
-
var import_infra_capabilities = __toESM(require_infra_capabilities());
|
|
2148
|
-
var import_config_manager = __toESM(require_config_manager());
|
|
2149
|
-
var import_config_schema = __toESM(require_config_schema());
|
|
2150
|
-
var import_addon_worker_host = __toESM(require_addon_worker_host());
|
|
2151
|
-
var import_worker_process_manager = __toESM(require_worker_process_manager());
|
|
1860
|
+
};
|
|
2152
1861
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2153
1862
|
0 && (module.exports = {
|
|
2154
1863
|
AddonEngineManager,
|