@marinoscar/platform-cli 0.1.0-next.24 → 0.1.0-next.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -3
  3. package/dist/engine/commands/node.d.ts.map +1 -1
  4. package/dist/engine/commands/node.js +65 -6
  5. package/dist/engine/commands/node.js.map +1 -1
  6. package/dist/engine/conformance.d.ts +3 -0
  7. package/dist/engine/conformance.d.ts.map +1 -1
  8. package/dist/engine/conformance.js +7 -0
  9. package/dist/engine/conformance.js.map +1 -1
  10. package/dist/engine/index.d.ts +8 -2
  11. package/dist/engine/index.d.ts.map +1 -1
  12. package/dist/engine/index.js +4 -1
  13. package/dist/engine/index.js.map +1 -1
  14. package/dist/engine/node/capabilities.d.ts +199 -4
  15. package/dist/engine/node/capabilities.d.ts.map +1 -1
  16. package/dist/engine/node/capabilities.js +292 -11
  17. package/dist/engine/node/capabilities.js.map +1 -1
  18. package/dist/engine/node/doctor.d.ts +2 -0
  19. package/dist/engine/node/doctor.d.ts.map +1 -1
  20. package/dist/engine/node/doctor.js +56 -3
  21. package/dist/engine/node/doctor.js.map +1 -1
  22. package/dist/engine/node/install-deps.d.ts +164 -6
  23. package/dist/engine/node/install-deps.d.ts.map +1 -1
  24. package/dist/engine/node/install-deps.js +251 -9
  25. package/dist/engine/node/install-deps.js.map +1 -1
  26. package/dist/engine/node/models.d.ts +195 -0
  27. package/dist/engine/node/models.d.ts.map +1 -0
  28. package/dist/engine/node/models.js +379 -0
  29. package/dist/engine/node/models.js.map +1 -0
  30. package/dist/engine/node/node-engine.d.ts +13 -1
  31. package/dist/engine/node/node-engine.d.ts.map +1 -1
  32. package/dist/engine/node/node-engine.js +18 -3
  33. package/dist/engine/node/node-engine.js.map +1 -1
  34. package/dist/engine/node/runtime-state.d.ts +1 -1
  35. package/dist/engine/node/start.d.ts.map +1 -1
  36. package/dist/engine/node/start.js +38 -2
  37. package/dist/engine/node/start.js.map +1 -1
  38. package/dist/engine/node/worker-env.d.ts +5 -0
  39. package/dist/engine/node/worker-env.d.ts.map +1 -1
  40. package/dist/engine/node/worker-env.js +5 -0
  41. package/dist/engine/node/worker-env.js.map +1 -1
  42. package/dist/engine/registries.d.ts.map +1 -1
  43. package/dist/engine/registries.js +2 -0
  44. package/dist/engine/registries.js.map +1 -1
  45. package/dist/engine/tui/conformance.d.ts +143 -0
  46. package/dist/engine/tui/conformance.d.ts.map +1 -0
  47. package/dist/engine/tui/conformance.js +423 -0
  48. package/dist/engine/tui/conformance.js.map +1 -0
  49. package/dist/engine/tui/testing/feeds.d.ts +58 -0
  50. package/dist/engine/tui/testing/feeds.d.ts.map +1 -0
  51. package/dist/engine/tui/testing/feeds.js +67 -0
  52. package/dist/engine/tui/testing/feeds.js.map +1 -0
  53. package/dist/engine/tui/testing/harness.d.ts +241 -0
  54. package/dist/engine/tui/testing/harness.d.ts.map +1 -0
  55. package/dist/engine/tui/testing/harness.js +332 -0
  56. package/dist/engine/tui/testing/harness.js.map +1 -0
  57. package/dist/node/index.d.ts +2 -2
  58. package/dist/node/index.d.ts.map +1 -1
  59. package/dist/node/index.js +1 -1
  60. package/dist/node/index.js.map +1 -1
  61. package/dist/testing/index.d.ts +2 -2
  62. package/dist/testing/index.d.ts.map +1 -1
  63. package/dist/testing/index.js +1 -1
  64. package/dist/testing/index.js.map +1 -1
  65. package/dist/tui/testing/index.d.ts +5 -0
  66. package/dist/tui/testing/index.d.ts.map +1 -0
  67. package/dist/tui/testing/index.js +12 -0
  68. package/dist/tui/testing/index.js.map +1 -0
  69. package/package.json +11 -3
@@ -100,8 +100,10 @@ export declare function registerProbedBinary(name: string, options?: ProbedBinar
100
100
  * Declares what a job type needs from the machine, for the startup self-test
101
101
  * and `node doctor`. A missing REQUIRED capability stops the node naming the
102
102
  * type; a missing degradable one only warns. Every `binary:<name>` capability
103
- * named here is registered as a probed binary (without a version command) so
104
- * the requirement can be satisfied at all.
103
+ * named here is registered as a probed binary (without a version command), and
104
+ * every `module:<name>` as a {@link moduleCapability} probe, so the requirement
105
+ * can be satisfied at all. A `service:<id>` key needs
106
+ * {@link registerCapabilityProbe}`(`{@link httpServiceCapability}`(...))`.
105
107
  *
106
108
  * @param type - the job type, as the server's handler declares it.
107
109
  * @param requirement - the required and degradable capability keys.
@@ -119,6 +121,173 @@ export declare function registerProbedBinary(name: string, options?: ProbedBinar
119
121
  * @stability experimental
120
122
  */
121
123
  export declare function registerJobRequirement(type: string, requirement: JobRequirementInput): void;
124
+ /**
125
+ * How well one non-binary capability works here.
126
+ *
127
+ * - `available`: present and working.
128
+ * - `installed`: present but not operational (resolves but fails its check; answers with an error).
129
+ * - `missing`: absent, unreachable, timed out or the probe threw.
130
+ *
131
+ * @stability experimental
132
+ */
133
+ export type CapabilityState = 'available' | 'installed' | 'missing';
134
+ /**
135
+ * What a capability probe reports.
136
+ *
137
+ * @stability experimental
138
+ */
139
+ export interface CapabilityProbeResult {
140
+ /** How well the capability works here. */
141
+ status: CapabilityState;
142
+ /** One line explaining the status. Cut to 200 printable characters. */
143
+ detail?: string | undefined;
144
+ /** A version string when the probe can read one. Cut to 80 printable characters. */
145
+ version?: string | undefined;
146
+ }
147
+ /**
148
+ * What a probe function receives.
149
+ *
150
+ * @stability experimental
151
+ */
152
+ export interface CapabilityProbeContext {
153
+ /** The environment the worker runs with. */
154
+ env: NodeJS.ProcessEnv;
155
+ /** Aborted when the probe's time budget is spent; honour it in any I/O. */
156
+ signal: AbortSignal;
157
+ }
158
+ /**
159
+ * A registered probe for one capability key.
160
+ *
161
+ * @stability experimental
162
+ */
163
+ export interface CapabilityProbeDefinition {
164
+ /** The capability key: `module:<name>`, `service:<id>` or any other `<kind>:<name>` an app invents. `binary:` is reserved. */
165
+ key: Capability;
166
+ /** Shown by `node doctor`. */
167
+ label: string;
168
+ /** Decides the status. Throwing or exceeding the budget means `missing`. */
169
+ probe(context: CapabilityProbeContext): CapabilityProbeResult | Promise<CapabilityProbeResult>;
170
+ /** Time budget in milliseconds. Default 5000. */
171
+ timeoutMs?: number | undefined;
172
+ /**
173
+ * How long a heartbeat refresh may reuse this probe's last result, in
174
+ * milliseconds. Default 0 (always probe). Startup and `node doctor` never use
175
+ * the cache.
176
+ */
177
+ cacheMs?: number | undefined;
178
+ }
179
+ /**
180
+ * One probe's outcome as recorded in {@link CapabilityProbe.probes}.
181
+ *
182
+ * @stability experimental
183
+ */
184
+ export interface CapabilityProbeEntry extends CapabilityProbeResult {
185
+ /** The probe's label, as `node doctor` shows it. */
186
+ label: string;
187
+ }
188
+ /**
189
+ * Declares a capability the platform cannot probe on its own (a native module,
190
+ * a sidecar service). Call it at module scope, before the node starts. The key
191
+ * can then be named in {@link registerJobRequirement}, and the result appears
192
+ * in the startup self-test, `node doctor` and the heartbeat capability summary.
193
+ *
194
+ * Each probe is bounded (default 5 s) and never throws into the caller: a probe
195
+ * that throws or times out reports `missing`.
196
+ *
197
+ * @param definition - the key, label and probe function.
198
+ * @throws Error when the key is malformed, uses the reserved `binary:` prefix, or is already registered.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * registerCapabilityProbe(moduleCapability('sharp'));
203
+ * registerCapabilityProbe(httpServiceCapability({ id: 'ocr', env: 'APP_OCR_URL', path: '/status' }));
204
+ * registerJobRequirement('app.ocr', { required: ['module:sharp', 'service:ocr'] });
205
+ * ```
206
+ *
207
+ * @extensionPoint registry
208
+ * @stability experimental
209
+ */
210
+ export declare function registerCapabilityProbe(definition: CapabilityProbeDefinition): void;
211
+ /** Removes one registered probe. Tests only. @internal */
212
+ export declare function unregisterCapabilityProbeForTests(key: Capability): void;
213
+ /**
214
+ * The registered non-binary probes, in registration order.
215
+ *
216
+ * @returns the definitions.
217
+ * @stability experimental
218
+ */
219
+ export declare function listCapabilityProbes(): CapabilityProbeDefinition[];
220
+ /**
221
+ * Options of {@link moduleCapability}.
222
+ *
223
+ * @stability experimental
224
+ */
225
+ export interface ModuleCapabilityOptions {
226
+ /** Shown by `node doctor`. Default `npm module <name>`. */
227
+ label?: string | undefined;
228
+ /**
229
+ * Proves the module WORKS, not just that it resolves (load it, run a tiny
230
+ * operation). Resolves normally or returns `true` for operational; returns
231
+ * `false`, a string (the reason) or throws for `installed`-but-not-operational.
232
+ * Absent: a resolvable module counts as available.
233
+ */
234
+ operational?: (() => unknown | Promise<unknown>) | undefined;
235
+ /** A path to resolve from, when the module is not reachable from the running script. */
236
+ resolveFrom?: string | undefined;
237
+ /** Time budget. Default 5000 ms (the module check may load a native binding). */
238
+ timeoutMs?: number | undefined;
239
+ /** Reuse window for heartbeat refreshes. Default 60000 ms: resolution and loading do not change while running. */
240
+ cacheMs?: number | undefined;
241
+ }
242
+ /**
243
+ * Builds the probe for an npm module under the key `module:<name>`. It decides
244
+ * with `require.resolve`, so probing never imports the module or runs its
245
+ * top-level code; only an explicit {@link ModuleCapabilityOptions.operational}
246
+ * check does, and then `installed` means "resolves, does not work".
247
+ *
248
+ * @param name - the npm package name (`sharp`, `@scope/pkg`).
249
+ * @param options - label and an optional operational check.
250
+ * @returns a definition for {@link registerCapabilityProbe}.
251
+ * @throws Error when the name is not an npm package name.
252
+ * @stability experimental
253
+ */
254
+ export declare function moduleCapability(name: string, options?: ModuleCapabilityOptions): CapabilityProbeDefinition;
255
+ /**
256
+ * Options of {@link httpServiceCapability}.
257
+ *
258
+ * @stability experimental
259
+ */
260
+ export interface HttpServiceCapabilityOptions {
261
+ /** The service id; the key is `service:<id>`. */
262
+ id: string;
263
+ /** Shown by `node doctor`. Default `service <id>`. */
264
+ label?: string | undefined;
265
+ /** The base URL. */
266
+ url?: string | undefined;
267
+ /** Or the NAME of an environment variable that holds the base URL (read at probe time). One of `url` / `env` is required. */
268
+ env?: string | undefined;
269
+ /** The path to request, default `/`. */
270
+ path?: string | undefined;
271
+ /** Time budget for the request, default 3000 ms. */
272
+ timeoutMs?: number | undefined;
273
+ /** Reuse window for heartbeat refreshes, default 15000 ms. */
274
+ cacheMs?: number | undefined;
275
+ /** Test seam. */
276
+ fetch?: typeof fetch | undefined;
277
+ }
278
+ /**
279
+ * Builds the probe for an HTTP sidecar under the key `service:<id>`: a `GET`
280
+ * to `<url><path>`. A 2xx answer is `available`; any other HTTP answer is
281
+ * `installed` (it is there but not healthy); a connection error or a timeout is
282
+ * `missing`. The detail shows the origin and path only, never credentials or a
283
+ * query string.
284
+ *
285
+ * @param options - the service id, its URL (or the env var naming it) and path.
286
+ * @returns a definition for {@link registerCapabilityProbe}.
287
+ * @throws Error when the id is malformed or neither `url` nor `env` is given.
288
+ * @stability experimental
289
+ */
290
+ export declare function httpServiceCapability(options: HttpServiceCapabilityOptions): CapabilityProbeDefinition;
122
291
  /**
123
292
  * What the capability probe found on this machine.
124
293
  *
@@ -144,6 +313,12 @@ export interface CapabilityProbe {
144
313
  * registered with `versionArgs`. Absent when none was captured.
145
314
  */
146
315
  versions?: Record<string, string> | undefined;
316
+ /**
317
+ * The outcome of every registered non-binary probe ({@link registerCapabilityProbe}),
318
+ * keyed by capability key. Absent when none is registered. Only `available`
319
+ * entries are in {@link CapabilityProbe.capabilities}.
320
+ */
321
+ probes?: Record<string, CapabilityProbeEntry> | undefined;
147
322
  /** Flat set of satisfied capability keys — what the self-test compares against. */
148
323
  capabilities: Capability[];
149
324
  }
@@ -162,7 +337,13 @@ export declare function probeCapabilities(options?: {
162
337
  hasBinary?: ((name: string) => boolean) | undefined;
163
338
  /** Reads a found binary's version banner. Defaults to running its registered `versionArgs`. */
164
339
  readVersion?: ((name: string) => string | undefined) | undefined;
165
- }): CapabilityProbe;
340
+ /** Environment handed to registered probes. Defaults to `process.env`. */
341
+ env?: NodeJS.ProcessEnv | undefined;
342
+ /** Reuse registered probes' cached results (`cacheMs`). For heartbeat refreshes; startup and `doctor` leave it off. */
343
+ useCache?: boolean | undefined;
344
+ /** Registered probes to run. Defaults to the registry; `[]` runs none. */
345
+ probes?: readonly CapabilityProbeDefinition[] | undefined;
346
+ }): Promise<CapabilityProbe>;
166
347
  /**
167
348
  * One capability a type needs and the machine lacks.
168
349
  *
@@ -173,6 +354,13 @@ export interface CapabilityGap {
173
354
  type: string;
174
355
  /** The missing capability key. */
175
356
  capability: Capability;
357
+ /**
358
+ * `installed` when the capability is present but not operational (a module
359
+ * that resolves and fails its check). Absent for a plainly missing one.
360
+ */
361
+ state?: 'installed' | undefined;
362
+ /** Why, when a probe said (or `no probe is registered for this capability`). */
363
+ detail?: string | undefined;
176
364
  }
177
365
  /**
178
366
  * The self-test's verdict.
@@ -225,9 +413,16 @@ export interface SelfTestOptions {
225
413
  * @returns the verdict; `ok` is false when a REQUIRED capability is missing.
226
414
  * @stability experimental
227
415
  */
228
- export declare function runStartupSelfTest(options: SelfTestOptions): SelfTestResult;
416
+ export declare function runStartupSelfTest(options: SelfTestOptions): Promise<SelfTestResult>;
229
417
  /** Is a path writable? Used by `doctor` and the install steps. */
230
418
  export declare function isWritable(path: string): boolean;
419
+ /**
420
+ * Lets a module that holds its own registry (the model artifacts) be emptied by
421
+ * {@link resetCapabilityRegistriesForTests} without `registries.ts` importing it.
422
+ *
423
+ * @internal
424
+ */
425
+ export declare function onCapabilityRegistryReset(hook: () => void): void;
231
426
  /**
232
427
  * Removes every requirement and probed binary an app registered, leaving the
233
428
  * platform's own. Tests only (`resetCliRegistriesForTests` calls it).
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.d.ts","sourceRoot":"","sources":["../../../src/engine/node/capabilities.ts"],"names":[],"mappings":"AAyCA;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC;AAEhC;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAEzD;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,wEAAwE;IACxE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACvB,yEAAyE;IACzE,UAAU,EAAE,UAAU,EAAE,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB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MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CAChD;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CAsB1F;AAED,kEAAkE;AAClE,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOhD;AAID;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,IAAI,GAAG,IAAI,CAEhE;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,IAAI,IAAI,CAWxD"}
@@ -1,6 +1,8 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { accessSync, constants } from 'node:fs';
2
+ import { accessSync, constants, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
3
4
  import { arch, cpus, freemem, platform, totalmem } from 'node:os';
5
+ import { join } from 'node:path';
4
6
  /**
5
7
  * Build the key for an executable, so no call site spells the prefix itself.
6
8
  *
@@ -104,8 +106,10 @@ export function registerProbedBinary(name, options = {}) {
104
106
  * Declares what a job type needs from the machine, for the startup self-test
105
107
  * and `node doctor`. A missing REQUIRED capability stops the node naming the
106
108
  * type; a missing degradable one only warns. Every `binary:<name>` capability
107
- * named here is registered as a probed binary (without a version command) so
108
- * the requirement can be satisfied at all.
109
+ * named here is registered as a probed binary (without a version command), and
110
+ * every `module:<name>` as a {@link moduleCapability} probe, so the requirement
111
+ * can be satisfied at all. A `service:<id>` key needs
112
+ * {@link registerCapabilityProbe}`(`{@link httpServiceCapability}`(...))`.
109
113
  *
110
114
  * @param type - the job type, as the server's handler declares it.
111
115
  * @param requirement - the required and degradable capability keys.
@@ -133,6 +137,9 @@ export function registerJobRequirement(type, requirement) {
133
137
  if (key.startsWith('binary:') && !BINARY_NAME_PATTERN.test(key.slice('binary:'.length))) {
134
138
  throw new Error(`registerJobRequirement("${type}"): "${key}" does not name a bare command.`);
135
139
  }
140
+ if (key.startsWith('module:') && !MODULE_NAME_PATTERN.test(key.slice('module:'.length))) {
141
+ throw new Error(`registerJobRequirement("${type}"): "${key}" does not name an npm package.`);
142
+ }
136
143
  }
137
144
  for (const key of [...required, ...degradable]) {
138
145
  if (key.startsWith('binary:')) {
@@ -140,9 +147,241 @@ export function registerJobRequirement(type, requirement) {
140
147
  if (!PROBED_BINARIES.includes(name))
141
148
  registerProbedBinary(name);
142
149
  }
150
+ // A `module:<name>` key is satisfiable without any further call: the module
151
+ // is resolved (never imported). A `service:<id>` key needs its URL, so the
152
+ // app registers `httpServiceCapability(...)` itself.
153
+ if (key.startsWith('module:') && !capabilityProbes.has(key)) {
154
+ registerCapabilityProbe(moduleCapability(key.slice('module:'.length)));
155
+ autoRegisteredProbes.add(key);
156
+ }
143
157
  }
144
158
  JOB_TYPE_REQUIREMENTS[type] = { required, degradable };
145
159
  }
160
+ const CAPABILITY_KEY_PATTERN = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9@][A-Za-z0-9@/._+-]{0,127}$/;
161
+ const MODULE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]{0,127}$/;
162
+ const SERVICE_ID_PATTERN = /^[a-z][a-z0-9._-]{0,63}$/;
163
+ const DEFAULT_PROBE_TIMEOUT_MS = 5000;
164
+ const MAX_PROBE_DETAIL_LENGTH = 200;
165
+ const capabilityProbes = new Map();
166
+ /** Keys `registerJobRequirement` registered on its own; an explicit registration replaces them. */
167
+ const autoRegisteredProbes = new Set();
168
+ const probeCache = new Map();
169
+ /**
170
+ * Declares a capability the platform cannot probe on its own (a native module,
171
+ * a sidecar service). Call it at module scope, before the node starts. The key
172
+ * can then be named in {@link registerJobRequirement}, and the result appears
173
+ * in the startup self-test, `node doctor` and the heartbeat capability summary.
174
+ *
175
+ * Each probe is bounded (default 5 s) and never throws into the caller: a probe
176
+ * that throws or times out reports `missing`.
177
+ *
178
+ * @param definition - the key, label and probe function.
179
+ * @throws Error when the key is malformed, uses the reserved `binary:` prefix, or is already registered.
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * registerCapabilityProbe(moduleCapability('sharp'));
184
+ * registerCapabilityProbe(httpServiceCapability({ id: 'ocr', env: 'APP_OCR_URL', path: '/status' }));
185
+ * registerJobRequirement('app.ocr', { required: ['module:sharp', 'service:ocr'] });
186
+ * ```
187
+ *
188
+ * @extensionPoint registry
189
+ * @stability experimental
190
+ */
191
+ export function registerCapabilityProbe(definition) {
192
+ const key = definition?.key;
193
+ if (typeof key !== 'string' || !CAPABILITY_KEY_PATTERN.test(key)) {
194
+ throw new Error(`registerCapabilityProbe: "${String(key)}" is not a capability key of the form <kind>:<name>.`);
195
+ }
196
+ if (key.startsWith('binary:')) {
197
+ throw new Error('registerCapabilityProbe: the "binary:" prefix is reserved for registerProbedBinary.');
198
+ }
199
+ if (typeof definition.label !== 'string' || definition.label.trim() === '')
200
+ throw new Error(`registerCapabilityProbe("${key}"): a label is required.`);
201
+ if (typeof definition.probe !== 'function')
202
+ throw new Error(`registerCapabilityProbe("${key}"): probe must be a function.`);
203
+ for (const field of ['timeoutMs', 'cacheMs']) {
204
+ const value = definition[field];
205
+ if (value !== undefined && (!Number.isFinite(value) || value < 0))
206
+ throw new Error(`registerCapabilityProbe("${key}"): ${field} must be a non-negative number.`);
207
+ }
208
+ if (capabilityProbes.has(key) && !autoRegisteredProbes.has(key))
209
+ throw new Error(`registerCapabilityProbe: "${key}" is already registered.`);
210
+ autoRegisteredProbes.delete(key);
211
+ capabilityProbes.set(key, definition);
212
+ }
213
+ /** Removes one registered probe. Tests only. @internal */
214
+ export function unregisterCapabilityProbeForTests(key) {
215
+ capabilityProbes.delete(key);
216
+ autoRegisteredProbes.delete(key);
217
+ probeCache.delete(key);
218
+ }
219
+ /**
220
+ * The registered non-binary probes, in registration order.
221
+ *
222
+ * @returns the definitions.
223
+ * @stability experimental
224
+ */
225
+ export function listCapabilityProbes() {
226
+ return [...capabilityProbes.values()];
227
+ }
228
+ /**
229
+ * Builds the probe for an npm module under the key `module:<name>`. It decides
230
+ * with `require.resolve`, so probing never imports the module or runs its
231
+ * top-level code; only an explicit {@link ModuleCapabilityOptions.operational}
232
+ * check does, and then `installed` means "resolves, does not work".
233
+ *
234
+ * @param name - the npm package name (`sharp`, `@scope/pkg`).
235
+ * @param options - label and an optional operational check.
236
+ * @returns a definition for {@link registerCapabilityProbe}.
237
+ * @throws Error when the name is not an npm package name.
238
+ * @stability experimental
239
+ */
240
+ export function moduleCapability(name, options = {}) {
241
+ if (typeof name !== 'string' || !MODULE_NAME_PATTERN.test(name)) {
242
+ throw new Error(`moduleCapability: "${String(name)}" is not an npm package name.`);
243
+ }
244
+ return {
245
+ key: `module:${name}`,
246
+ label: options.label ?? `npm module ${name}`,
247
+ timeoutMs: options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS,
248
+ cacheMs: options.cacheMs ?? 60_000,
249
+ async probe() {
250
+ const resolved = resolveModule(name, options.resolveFrom);
251
+ if (resolved === undefined)
252
+ return { status: 'missing', detail: `${name} is not installed` };
253
+ const version = readModuleVersion(name, resolved);
254
+ if (options.operational === undefined)
255
+ return { status: 'available', ...(version !== undefined ? { version } : {}) };
256
+ try {
257
+ const outcome = await options.operational();
258
+ if (outcome === false || typeof outcome === 'string') {
259
+ return { status: 'installed', detail: typeof outcome === 'string' ? outcome : `${name} is installed but failed its check`, ...(version !== undefined ? { version } : {}) };
260
+ }
261
+ return { status: 'available', ...(version !== undefined ? { version } : {}) };
262
+ }
263
+ catch (error) {
264
+ return { status: 'installed', detail: `${name} is installed but not operational: ${error instanceof Error ? error.message : String(error)}`, ...(version !== undefined ? { version } : {}) };
265
+ }
266
+ },
267
+ };
268
+ }
269
+ /** Resolves a module without loading it; returns the resolved path or undefined. */
270
+ function resolveModule(name, resolveFrom) {
271
+ const bases = [resolveFrom, process.argv[1], join(process.cwd(), 'noop.js')].filter((base) => typeof base === 'string' && base !== '');
272
+ for (const base of bases) {
273
+ try {
274
+ return createRequire(base).resolve(name);
275
+ }
276
+ catch {
277
+ // try the next base
278
+ }
279
+ }
280
+ return undefined;
281
+ }
282
+ /** The module's `package.json` version, found by walking up from its resolved entry. Never throws. */
283
+ function readModuleVersion(name, resolvedEntry) {
284
+ const marker = `node_modules/${name}/`;
285
+ const normalised = resolvedEntry.replace(/\\/g, '/');
286
+ const at = normalised.lastIndexOf(marker);
287
+ if (at === -1)
288
+ return undefined;
289
+ try {
290
+ const manifest = JSON.parse(readFileSync(`${normalised.slice(0, at + marker.length)}package.json`, 'utf8'));
291
+ return typeof manifest.version === 'string' ? manifest.version : undefined;
292
+ }
293
+ catch {
294
+ return undefined;
295
+ }
296
+ }
297
+ /**
298
+ * Builds the probe for an HTTP sidecar under the key `service:<id>`: a `GET`
299
+ * to `<url><path>`. A 2xx answer is `available`; any other HTTP answer is
300
+ * `installed` (it is there but not healthy); a connection error or a timeout is
301
+ * `missing`. The detail shows the origin and path only, never credentials or a
302
+ * query string.
303
+ *
304
+ * @param options - the service id, its URL (or the env var naming it) and path.
305
+ * @returns a definition for {@link registerCapabilityProbe}.
306
+ * @throws Error when the id is malformed or neither `url` nor `env` is given.
307
+ * @stability experimental
308
+ */
309
+ export function httpServiceCapability(options) {
310
+ if (typeof options?.id !== 'string' || !SERVICE_ID_PATTERN.test(options.id)) {
311
+ throw new Error(`httpServiceCapability: "${String(options?.id)}" is not a valid service id.`);
312
+ }
313
+ if (options.url === undefined && options.env === undefined) {
314
+ throw new Error(`httpServiceCapability("${options.id}"): give a url or the name of an env var that holds it.`);
315
+ }
316
+ const timeoutMs = options.timeoutMs ?? 3000;
317
+ return {
318
+ key: `service:${options.id}`,
319
+ label: options.label ?? `service ${options.id}`,
320
+ timeoutMs: timeoutMs + 500,
321
+ cacheMs: options.cacheMs ?? 15_000,
322
+ async probe({ env, signal }) {
323
+ const base = options.url ?? (options.env !== undefined ? env[options.env] : undefined);
324
+ if (base === undefined || base.trim() === '')
325
+ return { status: 'missing', detail: `${options.env ?? 'url'} is not set` };
326
+ let target;
327
+ try {
328
+ target = new URL(options.path ?? '/', base.endsWith('/') || (options.path ?? '/') === '/' ? base : `${base}/`);
329
+ }
330
+ catch {
331
+ return { status: 'missing', detail: 'the service URL is not a valid URL' };
332
+ }
333
+ const shown = `${target.origin}${target.pathname}`;
334
+ const timer = AbortSignal.timeout(timeoutMs);
335
+ try {
336
+ const response = await (options.fetch ?? fetch)(target, { method: 'GET', signal: AbortSignal.any([signal, timer]) });
337
+ return response.ok
338
+ ? { status: 'available', detail: `${shown} answered ${response.status}` }
339
+ : { status: 'installed', detail: `${shown} answered HTTP ${response.status}` };
340
+ }
341
+ catch (error) {
342
+ return { status: 'missing', detail: `${shown} is not reachable: ${timer.aborted ? `no answer within ${timeoutMs} ms` : error instanceof Error ? error.message : String(error)}` };
343
+ }
344
+ },
345
+ };
346
+ }
347
+ function printable(text, max) {
348
+ return text.replace(/[^\x20-\x7e]/g, ' ').trim().slice(0, max).trim();
349
+ }
350
+ /** Runs one registered probe with its budget, cache and fault isolation. Never throws. */
351
+ async function runCapabilityProbe(definition, env, useCache) {
352
+ const cacheMs = definition.cacheMs ?? 0;
353
+ const cached = probeCache.get(definition.key);
354
+ if (useCache && cacheMs > 0 && cached !== undefined && Date.now() - cached.at < cacheMs)
355
+ return cached.result;
356
+ const budget = definition.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
357
+ const controller = new AbortController();
358
+ let timer;
359
+ let result;
360
+ try {
361
+ const timeout = new Promise((resolve) => {
362
+ timer = setTimeout(() => {
363
+ controller.abort();
364
+ resolve({ status: 'missing', detail: `the probe did not answer within ${budget} ms` });
365
+ }, budget);
366
+ });
367
+ result = await Promise.race([Promise.resolve().then(() => definition.probe({ env, signal: controller.signal })), timeout]);
368
+ }
369
+ catch (error) {
370
+ result = { status: 'missing', detail: `the probe failed: ${error instanceof Error ? error.message : String(error)}` };
371
+ }
372
+ finally {
373
+ if (timer !== undefined)
374
+ clearTimeout(timer);
375
+ }
376
+ const status = result?.status === 'available' || result?.status === 'installed' ? result.status : 'missing';
377
+ const clean = {
378
+ status,
379
+ ...(typeof result?.detail === 'string' && result.detail !== '' ? { detail: printable(result.detail, MAX_PROBE_DETAIL_LENGTH) } : {}),
380
+ ...(typeof result?.version === 'string' && result.version !== '' ? { version: printable(result.version, 80) } : {}),
381
+ };
382
+ probeCache.set(definition.key, { at: Date.now(), result: clean });
383
+ return clean;
384
+ }
146
385
  /**
147
386
  * Probe this machine. NEVER THROWS, whatever the environment.
148
387
  *
@@ -153,7 +392,7 @@ export function registerJobRequirement(type, requirement) {
153
392
  * @returns what the machine has, including the satisfied capability keys.
154
393
  * @stability experimental
155
394
  */
156
- export function probeCapabilities(options) {
395
+ export async function probeCapabilities(options) {
157
396
  const names = options?.binaries ?? PROBED_BINARIES;
158
397
  const has = options?.hasBinary ?? isOnPath;
159
398
  const readVersion = options?.readVersion ?? readRegisteredVersion;
@@ -177,6 +416,17 @@ export function probeCapabilities(options) {
177
416
  if (found)
178
417
  capabilities.push(binaryCapability(name));
179
418
  }
419
+ // Registered non-binary probes run together; each is bounded and isolated.
420
+ const definitions = options?.probes ?? listCapabilityProbes();
421
+ const env = options?.env ?? process.env;
422
+ const settled = await Promise.all(definitions.map((definition) => runCapabilityProbe(definition, env, options?.useCache === true)));
423
+ const probes = {};
424
+ definitions.forEach((definition, index) => {
425
+ const result = settled[index];
426
+ probes[definition.key] = { label: definition.label, ...result };
427
+ if (result.status === 'available')
428
+ capabilities.push(definition.key);
429
+ });
180
430
  return {
181
431
  platform: safe(() => platform(), 'unknown'),
182
432
  arch: safe(() => arch(), 'unknown'),
@@ -186,6 +436,7 @@ export function probeCapabilities(options) {
186
436
  freeMemoryMb: safe(() => Math.round(freemem() / 1024 / 1024), 0),
187
437
  binaries,
188
438
  ...(Object.keys(versions).length > 0 ? { versions } : {}),
439
+ ...(definitions.length > 0 ? { probes } : {}),
189
440
  capabilities,
190
441
  };
191
442
  }
@@ -250,17 +501,32 @@ export function evaluateCapabilities(types, probe, requirements = JOB_TYPE_REQUI
250
501
  const satisfied = new Set(probe.capabilities);
251
502
  const missingRequired = [];
252
503
  const missingDegradable = [];
504
+ const gapOf = (type, capability) => {
505
+ const found = probe.probes?.[capability];
506
+ if (found !== undefined) {
507
+ return {
508
+ type,
509
+ capability,
510
+ ...(found.status === 'installed' ? { state: 'installed' } : {}),
511
+ ...(found.detail !== undefined ? { detail: found.detail } : {}),
512
+ };
513
+ }
514
+ // A binary is probed by name; anything else with no probe can never be satisfied.
515
+ return capability.startsWith('binary:')
516
+ ? { type, capability }
517
+ : { type, capability, detail: 'no probe is registered for this capability' };
518
+ };
253
519
  for (const type of types) {
254
520
  const need = requirements[type];
255
521
  if (need === undefined)
256
522
  continue;
257
523
  for (const capability of need.required) {
258
524
  if (!satisfied.has(capability))
259
- missingRequired.push({ type, capability });
525
+ missingRequired.push(gapOf(type, capability));
260
526
  }
261
527
  for (const capability of need.degradable) {
262
528
  if (!satisfied.has(capability))
263
- missingDegradable.push({ type, capability });
529
+ missingDegradable.push(gapOf(type, capability));
264
530
  }
265
531
  }
266
532
  return { ok: missingRequired.length === 0, missingRequired, missingDegradable };
@@ -276,15 +542,15 @@ export function evaluateCapabilities(types, probe, requirements = JOB_TYPE_REQUI
276
542
  * @returns the verdict; `ok` is false when a REQUIRED capability is missing.
277
543
  * @stability experimental
278
544
  */
279
- export function runStartupSelfTest(options) {
280
- const probe = options.probe ?? probeCapabilities();
545
+ export async function runStartupSelfTest(options) {
546
+ const probe = options.probe ?? (await probeCapabilities());
281
547
  const result = evaluateCapabilities(options.types, probe, options.requirements);
282
548
  for (const gap of result.missingDegradable) {
283
- options.warn?.(`Reduced function: job type "${gap.type}" would use "${gap.capability}", which is not available on this machine.`);
549
+ options.warn?.(`Reduced function: job type "${gap.type}" would use "${gap.capability}", which is ${gap.state === 'installed' ? 'installed but not operational' : 'not available'} on this machine${gap.detail !== undefined ? ` (${gap.detail})` : ''}.`);
284
550
  }
285
551
  for (const gap of result.missingRequired) {
286
- options.fail?.(`Cannot run job type "${gap.type}": required capability "${gap.capability}" is missing. ` +
287
- `Install it, or drop the type from this node's --types.`);
552
+ options.fail?.(`Cannot run job type "${gap.type}": required capability "${gap.capability}" is ${gap.state === 'installed' ? 'installed but not operational' : 'missing'}${gap.detail !== undefined ? ` (${gap.detail})` : ''}. ` +
553
+ `${gap.state === 'installed' ? 'Repair it' : 'Install it'}, or drop the type from this node's --types.`);
288
554
  }
289
555
  return result;
290
556
  }
@@ -298,6 +564,16 @@ export function isWritable(path) {
298
564
  return false;
299
565
  }
300
566
  }
567
+ const resetHooks = [];
568
+ /**
569
+ * Lets a module that holds its own registry (the model artifacts) be emptied by
570
+ * {@link resetCapabilityRegistriesForTests} without `registries.ts` importing it.
571
+ *
572
+ * @internal
573
+ */
574
+ export function onCapabilityRegistryReset(hook) {
575
+ resetHooks.push(hook);
576
+ }
301
577
  /**
302
578
  * Removes every requirement and probed binary an app registered, leaving the
303
579
  * platform's own. Tests only (`resetCliRegistriesForTests` calls it).
@@ -305,6 +581,8 @@ export function isWritable(path) {
305
581
  * @internal
306
582
  */
307
583
  export function resetCapabilityRegistriesForTests() {
584
+ for (const hook of resetHooks)
585
+ hook();
308
586
  for (const type of Object.keys(JOB_TYPE_REQUIREMENTS)) {
309
587
  if (!BUILTIN_REQUIREMENT_TYPES.has(type))
310
588
  delete JOB_TYPE_REQUIREMENTS[type];
@@ -312,5 +590,8 @@ export function resetCapabilityRegistriesForTests() {
312
590
  PROBED_BINARIES.length = 0;
313
591
  PROBED_BINARIES.push('pg_dump', 'psql');
314
592
  probedBinaryVersionArgs.clear();
593
+ capabilityProbes.clear();
594
+ autoRegisteredProbes.clear();
595
+ probeCache.clear();
315
596
  }
316
597
  //# sourceMappingURL=capabilities.js.map