clyops-jobs 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dan VerWeire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -6,9 +6,13 @@ artifacts, and each run gets a job record. A small in-memory queue runs jobs wit
6
6
  limit, for servers that hand out job ids. Built on [clyops-tools](../tools).
7
7
 
8
8
  ```sh
9
- npm install clyops-jobs
9
+ pnpm add clyops-jobs
10
10
  ```
11
11
 
12
+ **Single file.** `clyops-jobs.cjs` (in this package, and on npm) is the whole library as one dependency-free
13
+ CommonJS file: copy or link it into a project and `require()` it on Node 20+, with no build step
14
+ and no `node_modules`. It includes clyops-tools. `require('clyops-jobs')` loads it; `import` loads the ESM build. It is generated from the sources and checked in CI.
15
+
12
16
  ## Function config
13
17
 
14
18
  ```json
@@ -27,6 +31,7 @@ npm install clyops-jobs
27
31
  - `key` names the options block (default: the function name). Options are
28
32
  `deepMerge(defaults[key], config[key])`, keyed like the tool's options (`out_dir`, `out-dir`)
29
33
  and mapped onto its command line through `--help-json-schema` ([spec §13](../../spec/SPEC.md#13-json-input-toargv)).
34
+ - `positionals_order` (optional) is `first` (default) or `last`, for wrappers needing a specific order. `--` is only emitted for positional values starting with `-`.
30
35
  - `positionals` (optional) lists the tool's positional arguments explicitly; otherwise they're
31
36
  options keyed by argument name.
32
37
  - String values may use `${dot.path}` or `{{dot.path}}` templates against a context you build
@@ -84,3 +89,7 @@ queue.get(job.record.job_id)?.cancel();
84
89
  ```
85
90
 
86
91
  ESM only, Node 20+.
92
+
93
+ A missing or unreadable configured stdin file rejects `runScriptFunction()`
94
+ with its input-file error. It fails that job and stops its tool; the host worker
95
+ stays alive.
@@ -0,0 +1,835 @@
1
+ // Generated by tools/bundle-js.mjs from packages/jobs/src/index.ts. Do not edit.
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // packages/jobs/src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ JobQueue: () => JobQueue,
25
+ artifactIncludePatterns: () => artifactIncludePatterns,
26
+ artifactRequirement: () => artifactRequirement,
27
+ buildFunctionCommand: () => buildFunctionCommand,
28
+ buildResultRecord: () => buildResultRecord,
29
+ configureLogging: () => configureLogging,
30
+ copyConfiguredArtifacts: () => copyConfiguredArtifacts,
31
+ copyFileEnsuringDir: () => copyFileEnsuringDir,
32
+ deepMerge: () => deepMerge,
33
+ ensureDir: () => ensureDir,
34
+ findFilesByArtifactPattern: () => findFilesByArtifactPattern,
35
+ globToRegex: () => globToRegex,
36
+ isDirectoryPath: () => isDirectoryPath,
37
+ isEnabled: () => isEnabled,
38
+ isFilePath: () => isFilePath,
39
+ listFilesRecursive: () => listFilesRecursive,
40
+ lookupTemplateValue: () => lookupTemplateValue,
41
+ newJobId: () => newJobId,
42
+ newJobRecord: () => newJobRecord,
43
+ objectValue: () => objectValue,
44
+ pathParts: () => pathParts,
45
+ readJson: () => readJson,
46
+ renderConfigValue: () => renderConfigValue,
47
+ renderResultMap: () => renderResultMap,
48
+ renderResultValue: () => renderResultValue,
49
+ renderTemplateString: () => renderTemplateString,
50
+ resolveConfigPath: () => resolveConfigPath,
51
+ resolveFunctionConfig: () => resolveFunctionConfig,
52
+ resolveScriptPath: () => resolveScriptPath,
53
+ runScriptFunction: () => runScriptFunction,
54
+ shellQuote: () => shellQuote,
55
+ statFollowingSymlinks: () => statFollowingSymlinks,
56
+ timestampIso: () => timestampIso,
57
+ transitionJobRecord: () => transitionJobRecord,
58
+ truthy: () => truthy,
59
+ writeJson: () => writeJson
60
+ });
61
+ module.exports = __toCommonJS(index_exports);
62
+
63
+ // packages/jobs/src/util.ts
64
+ var import_node_fs = require("node:fs");
65
+ var import_node_path = require("node:path");
66
+ function timestampIso() {
67
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
68
+ }
69
+ function isEnabled(value) {
70
+ return value !== "" && value !== "disabled" && value !== "false";
71
+ }
72
+ function truthy(value) {
73
+ return /^(true|1|yes|on)$/i.test(String(value));
74
+ }
75
+ function ensureDir(dir) {
76
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
77
+ }
78
+ function readJson(file) {
79
+ return JSON.parse((0, import_node_fs.readFileSync)(file, "utf8"));
80
+ }
81
+ function writeJson(file, value) {
82
+ (0, import_node_fs.writeFileSync)(file, `${JSON.stringify(value, null, 2)}
83
+ `, "utf8");
84
+ }
85
+ function statFollowingSymlinks(file) {
86
+ try {
87
+ return (0, import_node_fs.statSync)(file);
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+ function isDirectoryPath(file) {
93
+ return Boolean(statFollowingSymlinks(file)?.isDirectory());
94
+ }
95
+ function isFilePath(file) {
96
+ return Boolean(statFollowingSymlinks(file)?.isFile());
97
+ }
98
+ function copyFileEnsuringDir(source, destination) {
99
+ ensureDir((0, import_node_path.dirname)(destination));
100
+ (0, import_node_fs.copyFileSync)(source, destination);
101
+ }
102
+ function pathParts(file) {
103
+ const name = (0, import_node_path.basename)(file);
104
+ const ext = (0, import_node_path.extname)(name);
105
+ return { path: file, dir: (0, import_node_path.dirname)(file), name, basename: ext ? name.slice(0, -ext.length) : name, ext: ext.replace(/^\./, "") };
106
+ }
107
+ function objectValue(value) {
108
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
109
+ }
110
+ function deepMerge(base, override) {
111
+ if (!base || typeof base !== "object" || Array.isArray(base)) return override;
112
+ if (!override || typeof override !== "object" || Array.isArray(override)) return override;
113
+ const out = { ...base };
114
+ for (const [key, value] of Object.entries(override)) out[key] = key in out ? deepMerge(out[key], value) : value;
115
+ return out;
116
+ }
117
+ function resolveConfigPath(root, value) {
118
+ if (!value || value === "disabled" || value === "false" || value === "-") return value || "";
119
+ if ((0, import_node_path.isAbsolute)(value) || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value;
120
+ return (0, import_node_path.resolve)(root, value);
121
+ }
122
+ var resolveScriptPath = resolveConfigPath;
123
+
124
+ // packages/jobs/src/template.ts
125
+ function lookupTemplateValue(context, expression) {
126
+ let current = context;
127
+ for (const part of String(expression).split(".").filter(Boolean)) {
128
+ if (!current || typeof current !== "object" || !Object.prototype.hasOwnProperty.call(current, part)) {
129
+ throw new Error(`unknown template value: ${expression}`);
130
+ }
131
+ current = current[part];
132
+ }
133
+ if (current === void 0 || current === null) return "";
134
+ return typeof current === "object" ? JSON.stringify(current) : String(current);
135
+ }
136
+ function renderTemplateString(value, context) {
137
+ return String(value).replace(
138
+ /\$\{\s*([A-Za-z0-9_.-]+)\s*\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g,
139
+ (_, dollar, brace) => lookupTemplateValue(context, dollar || brace)
140
+ );
141
+ }
142
+ function renderConfigValue(value, context) {
143
+ if (!context) return value;
144
+ if (typeof value === "string") return renderTemplateString(value, context);
145
+ if (Array.isArray(value)) return value.map((item) => renderConfigValue(item, context));
146
+ return value;
147
+ }
148
+ function renderResultValue(value, context) {
149
+ if (typeof value === "string") return renderTemplateString(value, context);
150
+ if (Array.isArray(value)) return value.map((item) => renderResultValue(item, context));
151
+ if (value && typeof value === "object") {
152
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, renderResultValue(v, context)]));
153
+ }
154
+ return value;
155
+ }
156
+ function renderResultMap(resultMap, context) {
157
+ if (!resultMap || typeof resultMap !== "object" || Array.isArray(resultMap)) return {};
158
+ return renderResultValue(resultMap, context);
159
+ }
160
+
161
+ // packages/tools/src/schema.ts
162
+ var import_node_child_process = require("node:child_process");
163
+ var import_node_fs2 = require("node:fs");
164
+ function stamp(file) {
165
+ const s = (0, import_node_fs2.statSync)(file);
166
+ return `${s.mtimeMs}:${s.size}`;
167
+ }
168
+ var cache = /* @__PURE__ */ new Map();
169
+ function loadSchema(file, opts = {}) {
170
+ const key = stamp(file);
171
+ const hit = cache.get(file);
172
+ if (hit && hit.stamp === key) return hit.schema;
173
+ const schema = new Promise((resolve5, reject) => {
174
+ (0, import_node_child_process.execFile)(file, ["--help-json-schema"], { cwd: opts.cwd, timeout: opts.timeoutMs ?? 5e3, maxBuffer: 16 << 20 }, (err, stdout) => {
175
+ if (err) return reject(new Error(`${file} does not provide --help-json-schema: ${err.message}`));
176
+ const start2 = stdout.indexOf("{");
177
+ const end = stdout.lastIndexOf("}");
178
+ if (start2 < 0 || end < start2) return reject(new Error(`${file} produced no JSON schema`));
179
+ try {
180
+ const parsed = JSON.parse(stdout.slice(start2, end + 1));
181
+ if (parsed.clyops !== 1 || !Array.isArray(parsed.options) || !Array.isArray(parsed.arguments) || typeof parsed.description !== "string") {
182
+ throw new Error("expected a clyops: 1 schema with description, options and arguments");
183
+ }
184
+ resolve5(parsed);
185
+ } catch (e) {
186
+ reject(new Error(`${file}: invalid JSON schema: ${e.message}`));
187
+ }
188
+ });
189
+ });
190
+ schema.catch(() => cache.delete(file));
191
+ cache.set(file, { stamp: key, schema });
192
+ return schema;
193
+ }
194
+
195
+ // packages/tools/src/argv.ts
196
+ var import_node_fs3 = require("node:fs");
197
+ var import_node_path2 = require("node:path");
198
+ var InputError = class extends Error {
199
+ status = 400;
200
+ };
201
+ function inputKey(name) {
202
+ return name.replace(/-/g, "_");
203
+ }
204
+ function inputKeys(item) {
205
+ const variable = "variableName" in item ? item.variableName : item.name;
206
+ return [.../* @__PURE__ */ new Set([inputKey(item.name), item.name, variable.toLowerCase()])].filter(Boolean);
207
+ }
208
+ function isBareFlag(option) {
209
+ const choices = [...option.choices].sort().join(",");
210
+ return option.isFlag && choices !== "false,true";
211
+ }
212
+ function isPathValued(validation, type) {
213
+ return type === "path" || validation === "path" || validation.startsWith("file:") || validation.startsWith("dir:");
214
+ }
215
+ var TRUE = /^(true|1|yes|on)$/i;
216
+ var FALSE = /^(false|0|no|off)$/i;
217
+ function toArgv(schema, input, opts = {}) {
218
+ const used = /* @__PURE__ */ new Set();
219
+ const out = { argv: [], env: {}, unknown: [], controlled: [] };
220
+ const pick = (item) => {
221
+ for (const key of inputKeys(item)) {
222
+ if (Object.prototype.hasOwnProperty.call(input, key)) {
223
+ used.add(key);
224
+ return { key, value: input[key] };
225
+ }
226
+ }
227
+ return void 0;
228
+ };
229
+ const text = (value, pathValued, name = "") => {
230
+ let s = typeof value === "object" ? JSON.stringify(value) : String(value);
231
+ if (opts.render) s = opts.render(s);
232
+ if (pathValued && opts.base && !["", "-", "disabled", "false"].includes(s) && !(0, import_node_path2.isAbsolute)(s) && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
233
+ s = (0, import_node_path2.resolve)(opts.base, s);
234
+ }
235
+ if (pathValued && opts.within) checkWithin(name, s, opts.within, opts.base ?? opts.cwd ?? process.cwd());
236
+ return s;
237
+ };
238
+ for (const option of schema.options) {
239
+ const found = pick(option);
240
+ if (!found) continue;
241
+ if (opts.controlled?.includes(option.name)) {
242
+ out.controlled.push(found.key);
243
+ continue;
244
+ }
245
+ if (found.value === null || found.value === void 0) continue;
246
+ if (isBareFlag(option)) {
247
+ if (!["boolean", "string", "number"].includes(typeof found.value)) {
248
+ throw new InputError(`--${option.name} must be a boolean (true/false, yes/no, 1/0, on/off)`);
249
+ }
250
+ const value = text(found.value, false);
251
+ if (!TRUE.test(value) && !FALSE.test(value)) {
252
+ throw new InputError(`--${option.name} must be a boolean (true/false, yes/no, 1/0, on/off), got '${value}'`);
253
+ }
254
+ out.argv.push(TRUE.test(value) ? `--${option.name}` : `--no-${option.name}`);
255
+ continue;
256
+ }
257
+ if (opts.secretEnv && option.secret && !option.isArray) {
258
+ out.env[option.variableName] = text(found.value, isPathValued(option.validation, option.type), `--${option.name}`);
259
+ continue;
260
+ }
261
+ for (const item of Array.isArray(found.value) ? found.value : [found.value]) {
262
+ out.argv.push(`--${option.name}`, text(item, isPathValued(option.validation, option.type), `--${option.name}`));
263
+ }
264
+ }
265
+ const explicit = Array.isArray(opts.positionals) ? opts.positionals : void 0;
266
+ const order = typeof opts.positionals === "string" ? opts.positionals : opts.positionalsOrder ?? "first";
267
+ if (order !== "first" && order !== "last") throw new InputError("positionals order must be first or last");
268
+ const positionals = [...explicit ?? []];
269
+ if (!explicit) {
270
+ let skipped = [];
271
+ for (const argument of schema.arguments) {
272
+ const found = pick(argument);
273
+ if (!found || found.value === null || found.value === void 0) {
274
+ skipped.push(argument);
275
+ continue;
276
+ }
277
+ for (const gap of skipped) {
278
+ if (!gap.default) throw new Error(`${argument.name} is given, so ${gap.name} must be too`);
279
+ positionals.push(text(gap.default, false));
280
+ }
281
+ skipped = [];
282
+ const values = Array.isArray(found.value) ? found.value : [found.value];
283
+ positionals.push(...values.map((v) => text(v, isPathValued(argument.validation), argument.name)));
284
+ }
285
+ }
286
+ if (positionals.some((p) => p.startsWith("-"))) out.argv.push("--", ...positionals);
287
+ else if (order === "last") out.argv.push(...positionals);
288
+ else out.argv.unshift(...positionals);
289
+ out.unknown = Object.keys(input).filter((k) => !used.has(k));
290
+ return out;
291
+ }
292
+ function realish(p) {
293
+ let head = p;
294
+ const tail2 = [];
295
+ while (!(0, import_node_fs3.existsSync)(head) && (0, import_node_path2.dirname)(head) !== head) {
296
+ tail2.unshift(head.slice((0, import_node_path2.dirname)(head).length).replace(/^[\\/]/, ""));
297
+ head = (0, import_node_path2.dirname)(head);
298
+ }
299
+ return (0, import_node_path2.resolve)((0, import_node_fs3.existsSync)(head) ? (0, import_node_fs3.realpathSync)(head) : head, ...tail2);
300
+ }
301
+ function checkWithin(name, value, dirs, base) {
302
+ if (["", "-", "disabled", "false"].includes(value)) return;
303
+ if (/^[a-z][a-z0-9+.-]+:/i.test(value) && !(0, import_node_path2.isAbsolute)(value)) {
304
+ throw new InputError(`${name}: ${value} is not a path inside the allowed directories`);
305
+ }
306
+ const target = realish((0, import_node_path2.resolve)(base, value));
307
+ const inside = dirs.some((dir) => {
308
+ const rel = (0, import_node_path2.relative)(realish((0, import_node_path2.resolve)(dir)), target);
309
+ return rel === "" || !rel.startsWith("..") && !(0, import_node_path2.isAbsolute)(rel);
310
+ });
311
+ if (!inside) throw new InputError(`${name}: ${value} is outside the allowed directories`);
312
+ }
313
+ function redactArgv(schema, argv) {
314
+ const secret = new Set(schema.options.filter((o) => o.secret).map((o) => `--${o.name}`));
315
+ const out = [...argv];
316
+ for (let i = 0; i < out.length; i++) {
317
+ if (out[i] === "--") break;
318
+ const eq = out[i].indexOf("=");
319
+ if (eq > 0 && secret.has(out[i].slice(0, eq))) out[i] = `${out[i].slice(0, eq)}=***`;
320
+ else if (secret.has(out[i]) && i + 1 < out.length) out[++i] = "***";
321
+ }
322
+ return out;
323
+ }
324
+
325
+ // packages/tools/src/run.ts
326
+ var import_node_child_process2 = require("node:child_process");
327
+ var import_node_stream = require("node:stream");
328
+ var import_node_string_decoder = require("node:string_decoder");
329
+ var ABORT_GRACE_MS = 200;
330
+ var STOP_WAIT_MS = 1e3;
331
+ function terminateTree(child, signal) {
332
+ const pid = child.pid;
333
+ if (!pid || pid <= 0) return Promise.resolve();
334
+ if (process.platform === "win32") {
335
+ return new Promise((resolve5) => {
336
+ (0, import_node_child_process2.execFile)("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 500 }, (err) => {
337
+ if (err && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
338
+ resolve5();
339
+ });
340
+ });
341
+ }
342
+ try {
343
+ process.kill(-pid, signal);
344
+ } catch (err) {
345
+ if (err.code !== "ESRCH") child.kill(signal);
346
+ }
347
+ return Promise.resolve();
348
+ }
349
+ function start(file, argv, opts = {}) {
350
+ const started = Date.now();
351
+ const child = (0, import_node_child_process2.spawn)(file, argv, {
352
+ cwd: opts.cwd,
353
+ env: opts.env ?? process.env,
354
+ stdio: [opts.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"],
355
+ // POSIX detached children lead a new session/group, still with owned pipes.
356
+ detached: process.platform !== "win32",
357
+ windowsHide: true
358
+ });
359
+ const limit = opts.maxOutput || Infinity;
360
+ let truncated = false;
361
+ const collect = (stream, onChunk) => {
362
+ const chunks = [];
363
+ const decoder = new import_node_string_decoder.StringDecoder("utf8");
364
+ let size = 0;
365
+ stream.on("data", (chunk) => {
366
+ if (onChunk) onChunk(decoder.write(chunk));
367
+ if (size >= limit) return void (truncated = true);
368
+ if (size + chunk.length > limit) {
369
+ chunk = chunk.subarray(0, limit - size);
370
+ truncated = true;
371
+ }
372
+ chunks.push(chunk);
373
+ size += chunk.length;
374
+ });
375
+ return () => Buffer.concat(chunks);
376
+ };
377
+ const [childOut, childErr] = [child.stdout, child.stderr];
378
+ const mode = opts.stdout ?? "text";
379
+ const stdout = mode === "stream" ? () => Buffer.alloc(0) : collect(childOut, opts.onStdout);
380
+ const stderr = collect(childErr, opts.onStderr);
381
+ const result = new Promise((resolve5, reject) => {
382
+ let timedOut = false;
383
+ let failure;
384
+ let exited = false;
385
+ let settled = false;
386
+ let stopping;
387
+ let timer;
388
+ let escalation;
389
+ let deadline;
390
+ let treeStopped;
391
+ let inputClosed = false;
392
+ const source = opts.stdin instanceof import_node_stream.Readable ? opts.stdin : void 0;
393
+ const forgetSource = () => {
394
+ source?.removeListener("error", inputError);
395
+ source?.removeListener("close", forgetSource);
396
+ };
397
+ const closeInput = () => {
398
+ if (inputClosed) return;
399
+ inputClosed = true;
400
+ if (source) {
401
+ source.unpipe(child.stdin ?? void 0);
402
+ if (source.closed) forgetSource();
403
+ else {
404
+ source.once("close", forgetSource);
405
+ source.destroy();
406
+ }
407
+ }
408
+ child.stdin?.destroy();
409
+ };
410
+ const finish = async (exitCode, signal) => {
411
+ if (settled) return;
412
+ settled = true;
413
+ clearTimeout(timer);
414
+ clearTimeout(escalation);
415
+ clearTimeout(deadline);
416
+ opts.signal?.removeEventListener("abort", abort);
417
+ closeInput();
418
+ if (stopping && process.platform !== "win32") treeStopped = terminateTree(child, "SIGKILL");
419
+ await treeStopped;
420
+ if (failure) {
421
+ reject(failure);
422
+ return;
423
+ }
424
+ const out = stdout();
425
+ resolve5({
426
+ command: [file, ...argv],
427
+ exitCode,
428
+ signal: signal ?? stopping ?? null,
429
+ timedOut,
430
+ stdout: mode === "text" ? out.toString("utf8") : "",
431
+ ...mode === "buffer" ? { stdoutBuffer: out } : {},
432
+ stderr: stderr().toString("utf8"),
433
+ ...truncated ? { truncated } : {},
434
+ durationMs: Date.now() - started
435
+ });
436
+ };
437
+ const stop = (signal) => {
438
+ if (settled || stopping) return;
439
+ stopping = signal;
440
+ clearTimeout(timer);
441
+ treeStopped = terminateTree(child, signal);
442
+ closeInput();
443
+ if (signal === "SIGTERM") {
444
+ escalation = setTimeout(() => {
445
+ treeStopped = terminateTree(child, "SIGKILL");
446
+ }, ABORT_GRACE_MS);
447
+ }
448
+ deadline = setTimeout(() => {
449
+ treeStopped = terminateTree(child, "SIGKILL");
450
+ for (const stream of [childOut, childErr]) {
451
+ if (!stream.destroyed) {
452
+ stream.once("end", () => stream.destroy());
453
+ stream.push(null);
454
+ stream.resume();
455
+ }
456
+ }
457
+ void finish(child.exitCode, child.signalCode);
458
+ }, STOP_WAIT_MS);
459
+ };
460
+ const abort = () => stop("SIGTERM");
461
+ const inputError = (err) => {
462
+ if (exited || failure || settled || stopping) return;
463
+ failure = err;
464
+ stop("SIGKILL");
465
+ };
466
+ child.on("error", (err) => {
467
+ failure ??= err;
468
+ stop("SIGKILL");
469
+ });
470
+ child.once("exit", () => {
471
+ exited = true;
472
+ closeInput();
473
+ });
474
+ child.once("close", (exitCode, signal) => {
475
+ void finish(exitCode, signal);
476
+ });
477
+ timer = opts.timeoutMs ? setTimeout(() => {
478
+ timedOut = true;
479
+ stop("SIGKILL");
480
+ }, opts.timeoutMs) : void 0;
481
+ opts.signal?.addEventListener("abort", abort, { once: true });
482
+ if (opts.stdin !== void 0 && child.stdin) {
483
+ child.stdin.on("error", closeInput);
484
+ child.stdin.once("close", () => child.stdin?.removeListener("error", closeInput));
485
+ if (source) {
486
+ source.on("error", inputError);
487
+ if (source.errored) inputError(source.errored);
488
+ else source.pipe(child.stdin);
489
+ } else child.stdin.end(opts.stdin);
490
+ }
491
+ if (opts.signal?.aborted) abort();
492
+ });
493
+ return { child, stdout: childOut, result };
494
+ }
495
+ function tail(text, lines = 40) {
496
+ return text.replace(/\x1b\[[0-9;]*m/g, "").split("\n").filter((l, i, all) => l || i < all.length - 1).slice(-lines);
497
+ }
498
+ function shellQuote(args) {
499
+ return args.map((a) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`).join(" ");
500
+ }
501
+
502
+ // packages/jobs/src/functions.ts
503
+ var import_node_fs4 = require("node:fs");
504
+ var import_promises = require("node:stream/promises");
505
+ var import_node_path3 = require("node:path");
506
+ var LOGGER = {
507
+ module: "clyops-jobs",
508
+ warn: (..._args) => {
509
+ },
510
+ verbose: (..._args) => {
511
+ }
512
+ };
513
+ function configureLogging(opts) {
514
+ Object.assign(LOGGER, Object.fromEntries(Object.entries(opts).filter(([, v]) => v)));
515
+ }
516
+ function resolveFunctionConfig(scriptRoot, routeConfig, functionName) {
517
+ const definition = objectValue(objectValue(routeConfig.functions)[functionName]);
518
+ if (Object.keys(definition).length === 0) return null;
519
+ const key = String(definition.key || functionName);
520
+ const script = String(definition.script || "");
521
+ if (!script) throw new Error(`function ${functionName} does not define a script`);
522
+ const config = deepMerge(objectValue(objectValue(routeConfig.defaults)[key]), objectValue(routeConfig[key]));
523
+ return { functionName, key, script: resolveScriptPath(scriptRoot, script), config, definition };
524
+ }
525
+ function explicitPositionals(fn, context) {
526
+ if (!Array.isArray(fn.definition.positionals)) return void 0;
527
+ return fn.definition.positionals.map((item) => String(renderConfigValue(item, context))).filter(Boolean);
528
+ }
529
+ async function buildFunctionCommand(fn, opts, schema) {
530
+ schema ??= await loadSchema(fn.script);
531
+ const config = { ...fn.config };
532
+ const first = schema.arguments[0];
533
+ if (opts.defaultPositional && first && !Array.isArray(fn.definition.positionals) && !inputKeys(first).some((k) => k in config)) {
534
+ config[inputKeys(first)[0]] = opts.defaultPositional;
535
+ }
536
+ const context = opts.context;
537
+ const { argv, unknown, controlled } = toArgv(schema, config, {
538
+ base: opts.configRoot,
539
+ controlled: opts.controlled ?? ["help"],
540
+ render: context ? (s) => renderTemplateString(s, context) : void 0,
541
+ positionals: explicitPositionals(fn, context),
542
+ positionalsOrder: fn.definition.positionals_order
543
+ });
544
+ const name = (0, import_node_path3.basename)(fn.script);
545
+ for (const key of controlled) LOGGER.warn("[%s] ignoring config key %s; it is controlled by %s", name, key, LOGGER.module);
546
+ for (const key of unknown) LOGGER.warn("[%s] ignoring config key %s; no matching CLI option in schema", name, key);
547
+ return [fn.script, ...argv];
548
+ }
549
+ function streamPath(template, opts, base) {
550
+ if (!template) return void 0;
551
+ const rendered = opts.context ? renderTemplateString(template, opts.context) : template;
552
+ return (0, import_node_path3.isAbsolute)(rendered) ? rendered : (0, import_node_path3.resolve)(base, rendered);
553
+ }
554
+ async function runScriptFunction(fn, opts) {
555
+ const schema = await loadSchema(fn.script);
556
+ const [file, ...argv] = await buildFunctionCommand(fn, opts, schema);
557
+ const command = [file, ...redactArgv(schema, argv)];
558
+ LOGGER.verbose("command: %s", shellQuote(command));
559
+ const workDir = opts.context?.paths?.work_dir;
560
+ const stdinPath = streamPath(fn.definition.stdin, opts, opts.configRoot);
561
+ const stdoutPath = streamPath(fn.definition.stdout, opts, workDir ?? opts.configRoot);
562
+ const started = start(file, argv, {
563
+ cwd: opts.cwd,
564
+ env: opts.env,
565
+ timeoutMs: opts.timeoutMs,
566
+ signal: opts.signal,
567
+ onStderr: opts.onStderr,
568
+ stdin: stdinPath ? (0, import_node_fs4.createReadStream)(stdinPath) : void 0,
569
+ stdout: stdoutPath ? "stream" : "text"
570
+ });
571
+ let written;
572
+ if (stdoutPath) {
573
+ ensureDir((0, import_node_path3.dirname)(stdoutPath));
574
+ written = (0, import_promises.finished)(started.stdout.pipe((0, import_node_fs4.createWriteStream)(stdoutPath)));
575
+ }
576
+ const [result] = await Promise.all([started.result, written]);
577
+ return { ...result, command, stderrTail: tail(result.stderr) };
578
+ }
579
+ function buildResultRecord(p) {
580
+ return {
581
+ job_id: p.jobId,
582
+ ...p.fields,
583
+ function: p.fn.functionName,
584
+ function_key: p.fn.key,
585
+ script: p.fn.script,
586
+ artifact_keys: p.artifactKeys,
587
+ completed_at: p.now,
588
+ config: p.fn.config,
589
+ ...renderResultMap(p.fn.definition.result, p.context)
590
+ };
591
+ }
592
+
593
+ // packages/jobs/src/artifacts.ts
594
+ var import_node_fs5 = require("node:fs");
595
+ var import_node_path4 = require("node:path");
596
+ function globToRegex(pattern) {
597
+ const source = String(pattern).replace(/\\/g, "/");
598
+ let out = "^";
599
+ for (let i = 0; i < source.length; i += 1) {
600
+ const char = source[i];
601
+ if (char === "*") {
602
+ if (source[i + 1] === "*" && source[i + 2] === "/") {
603
+ out += "(?:.*/)?";
604
+ i += 2;
605
+ } else if (source[i + 1] === "*") {
606
+ out += ".*";
607
+ i += 1;
608
+ } else out += "[^/]*";
609
+ } else if (char === "?") out += "[^/]";
610
+ else out += char.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
611
+ }
612
+ return new RegExp(`${out}$`);
613
+ }
614
+ function globSearchRoot(pattern) {
615
+ const normalized = String(pattern).replace(/\\/g, "/");
616
+ const wildcard = normalized.search(/[*?]/);
617
+ if (wildcard < 0) return (0, import_node_path4.dirname)(pattern);
618
+ const prefix = normalized.slice(0, wildcard);
619
+ return (0, import_node_path4.normalize)(prefix.slice(0, prefix.lastIndexOf("/")) || (0, import_node_path4.parse)(pattern).root || ".");
620
+ }
621
+ function listFilesRecursive(dir, visited = /* @__PURE__ */ new Set()) {
622
+ if (!isDirectoryPath(dir)) return [];
623
+ const real = (0, import_node_fs5.realpathSync)(dir);
624
+ if (visited.has(real)) return [];
625
+ visited.add(real);
626
+ const files = [];
627
+ for (const name of (0, import_node_fs5.readdirSync)(dir)) {
628
+ const full = (0, import_node_path4.join)(dir, name);
629
+ const stat = statFollowingSymlinks(full);
630
+ if (stat?.isDirectory()) files.push(...listFilesRecursive(full, visited));
631
+ else if (stat?.isFile()) files.push(full);
632
+ }
633
+ return files;
634
+ }
635
+ function findFilesByArtifactPattern(pattern, context) {
636
+ const rendered = renderTemplateString(pattern, context);
637
+ const absolute = (0, import_node_path4.isAbsolute)(rendered) ? rendered : (0, import_node_path4.resolve)(context.paths.work_dir, rendered);
638
+ if (!/[*?]/.test(absolute)) return isFilePath(absolute) ? [absolute] : [];
639
+ const regex = globToRegex(absolute);
640
+ return listFilesRecursive(globSearchRoot(absolute)).filter((file) => regex.test(file.replace(/\\/g, "/"))).sort();
641
+ }
642
+ function artifactIncludePatterns(fn) {
643
+ const stdout = fn.definition.stdout ? [String(fn.definition.stdout)] : [];
644
+ const artifacts = fn.definition.artifacts;
645
+ if (!artifacts) return stdout;
646
+ if (typeof artifacts === "string") return [artifacts, ...stdout];
647
+ if (Array.isArray(artifacts)) return [...artifacts.map(String), ...stdout];
648
+ if (typeof artifacts === "object") {
649
+ const a = artifacts;
650
+ const include = a.include || a.includes || a.patterns;
651
+ if (typeof include === "string") return [include, ...stdout];
652
+ if (Array.isArray(include)) return [...include.map(String), ...stdout];
653
+ }
654
+ return stdout;
655
+ }
656
+ function artifactRequirement(fn) {
657
+ const artifacts = fn.definition.artifacts;
658
+ if (!artifacts || typeof artifacts !== "object" || Array.isArray(artifacts)) return 0;
659
+ const min = Number(artifacts.min);
660
+ if (Number.isFinite(min) && min > 0) return Math.floor(min);
661
+ return artifacts.required === true || truthy(artifacts.required) ? 1 : 0;
662
+ }
663
+ function copyConfiguredArtifacts(fn, context, opts = {}) {
664
+ const patterns = artifactIncludePatterns(fn);
665
+ const min = artifactRequirement(fn);
666
+ if (patterns.length === 0) {
667
+ if (min > 0) throw new Error(`artifacts require at least ${min} file(s) but no include patterns are configured`);
668
+ return [];
669
+ }
670
+ const dir = context.paths.artifacts_dir;
671
+ if ((0, import_node_fs5.existsSync)(dir)) throw new Error(`artifact directory already exists: ${dir}`);
672
+ const seen = /* @__PURE__ */ new Set();
673
+ const copied = [];
674
+ for (const pattern of patterns) {
675
+ for (const source of findFilesByArtifactPattern(pattern, context)) {
676
+ if (seen.has(source)) continue;
677
+ seen.add(source);
678
+ const destination = (0, import_node_path4.join)(dir, (0, import_node_path4.basename)(source));
679
+ if ((0, import_node_fs5.existsSync)(destination)) throw new Error(`duplicate artifact filename: ${(0, import_node_path4.basename)(source)}`);
680
+ copyFileEnsuringDir(source, destination);
681
+ copied.push({ source, key: `${opts.keyPrefix ?? ""}${(0, import_node_path4.basename)(dir)}/${(0, import_node_path4.basename)(destination)}` });
682
+ }
683
+ }
684
+ if (copied.length < min) throw new Error(`expected at least ${min} artifact file(s) but matched ${copied.length}`);
685
+ return copied;
686
+ }
687
+
688
+ // packages/jobs/src/records.ts
689
+ var import_node_crypto = require("node:crypto");
690
+ function newJobId(seed, prefix = "job") {
691
+ const material = `${seed}/${Date.now()}/${process.pid}/${Math.random()}`;
692
+ return `${prefix}-${(0, import_node_crypto.createHash)("md5").update(material).digest("hex").slice(0, 12)}`;
693
+ }
694
+ function newJobRecord(p) {
695
+ const now = p.now ?? timestampIso();
696
+ return {
697
+ job_id: p.jobId,
698
+ ...p.fields,
699
+ function: p.functionName,
700
+ status: "pending",
701
+ stage: null,
702
+ started_at: now,
703
+ updated_at: now,
704
+ completed_at: null,
705
+ error: null,
706
+ result_key: null,
707
+ history: []
708
+ };
709
+ }
710
+ function transitionJobRecord(record, change) {
711
+ return {
712
+ ...record,
713
+ ...change.extra,
714
+ history: [{ status: record.status, stage: record.stage, updated_at: record.updated_at }, ...record.history || []],
715
+ status: change.status,
716
+ stage: change.stage ?? null,
717
+ updated_at: change.now ?? timestampIso(),
718
+ completed_at: change.completedAt || null,
719
+ error: change.error || null,
720
+ result_key: change.resultKey || null
721
+ };
722
+ }
723
+
724
+ // packages/jobs/src/queue.ts
725
+ var import_node_os = require("node:os");
726
+ var JobQueue = class {
727
+ constructor(opts = {}) {
728
+ this.opts = opts;
729
+ }
730
+ opts;
731
+ jobs = /* @__PURE__ */ new Map();
732
+ waiting = [];
733
+ running = 0;
734
+ finished = [];
735
+ /**
736
+ * Queue `task` as a job of `functionName`. The task gets an AbortSignal and
737
+ * a `stage` setter for progress; its return value is the job's result.
738
+ */
739
+ add(functionName, task, fields = {}) {
740
+ const id = newJobId(functionName, this.opts.prefix ?? "job");
741
+ const abort = new AbortController();
742
+ const job = { record: newJobRecord({ jobId: id, functionName, fields }) };
743
+ const update = (change) => {
744
+ job.record = transitionJobRecord(job.record, change);
745
+ this.opts.onChange?.(job.record);
746
+ };
747
+ job.cancel = () => abort.abort();
748
+ job.done = (async () => {
749
+ await this.slot();
750
+ try {
751
+ abort.signal.throwIfAborted();
752
+ update({ status: "processing" });
753
+ const result = await task({ signal: abort.signal, stage: (stage) => update({ status: "processing", stage }) });
754
+ job.result = result;
755
+ abort.signal.throwIfAborted();
756
+ update({ status: "done", completedAt: timestampIso() });
757
+ return result;
758
+ } catch (err) {
759
+ update({ status: "error", error: abort.signal.aborted ? "cancelled" : err.message, completedAt: timestampIso() });
760
+ throw err;
761
+ } finally {
762
+ this.release(id);
763
+ }
764
+ })();
765
+ job.done.catch(() => {
766
+ });
767
+ this.jobs.set(id, job);
768
+ this.opts.onChange?.(job.record);
769
+ return job;
770
+ }
771
+ get(id) {
772
+ return this.jobs.get(id);
773
+ }
774
+ list() {
775
+ return [...this.jobs.values()].map((j) => j.record);
776
+ }
777
+ slot() {
778
+ if (this.running < (this.opts.concurrency ?? (0, import_node_os.availableParallelism)())) {
779
+ this.running += 1;
780
+ return Promise.resolve();
781
+ }
782
+ return new Promise((resolve5) => this.waiting.push(resolve5));
783
+ }
784
+ release(id) {
785
+ const next = this.waiting.shift();
786
+ if (next) next();
787
+ else this.running -= 1;
788
+ this.finished.push(id);
789
+ while (this.finished.length > (this.opts.keep ?? 1e3)) {
790
+ const dropped = this.finished.shift();
791
+ const job = this.jobs.get(dropped);
792
+ this.jobs.delete(dropped);
793
+ if (job) this.opts.onDrop?.(job.record);
794
+ }
795
+ }
796
+ };
797
+ // Annotate the CommonJS export names for ESM import in node:
798
+ 0 && (module.exports = {
799
+ JobQueue,
800
+ artifactIncludePatterns,
801
+ artifactRequirement,
802
+ buildFunctionCommand,
803
+ buildResultRecord,
804
+ configureLogging,
805
+ copyConfiguredArtifacts,
806
+ copyFileEnsuringDir,
807
+ deepMerge,
808
+ ensureDir,
809
+ findFilesByArtifactPattern,
810
+ globToRegex,
811
+ isDirectoryPath,
812
+ isEnabled,
813
+ isFilePath,
814
+ listFilesRecursive,
815
+ lookupTemplateValue,
816
+ newJobId,
817
+ newJobRecord,
818
+ objectValue,
819
+ pathParts,
820
+ readJson,
821
+ renderConfigValue,
822
+ renderResultMap,
823
+ renderResultValue,
824
+ renderTemplateString,
825
+ resolveConfigPath,
826
+ resolveFunctionConfig,
827
+ resolveScriptPath,
828
+ runScriptFunction,
829
+ shellQuote,
830
+ statFollowingSymlinks,
831
+ timestampIso,
832
+ transitionJobRecord,
833
+ truthy,
834
+ writeJson
835
+ });
@@ -15,6 +15,8 @@ export interface FunctionDefinition {
15
15
  key?: string;
16
16
  script?: string;
17
17
  positionals?: unknown[];
18
+ /** Positionals before or after options (default: first). */
19
+ positionals_order?: 'first' | 'last';
18
20
  /** A template for a file fed to the tool's stdin, e.g. '${media.path}'. */
19
21
  stdin?: string;
20
22
  /** A template for the file the tool's stdout is written to; it also counts as an artifact. */
package/dist/functions.js CHANGED
@@ -66,6 +66,7 @@ export async function buildFunctionCommand(fn, opts, schema) {
66
66
  controlled: opts.controlled ?? ['help'],
67
67
  render: context ? (s) => renderTemplateString(s, context) : undefined,
68
68
  positionals: explicitPositionals(fn, context),
69
+ positionalsOrder: fn.definition.positionals_order,
69
70
  });
70
71
  const name = basename(fn.script);
71
72
  for (const key of controlled)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clyops-jobs",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Run clyops tools as jobs: config-bound functions, templated invocation, artifacts, job records and a queue.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,24 +24,25 @@
24
24
  "exports": {
25
25
  ".": {
26
26
  "types": "./dist/index.d.ts",
27
- "default": "./dist/index.js"
27
+ "import": "./dist/index.js",
28
+ "require": "./clyops-jobs.cjs"
28
29
  }
29
30
  },
30
31
  "files": [
31
32
  "dist",
32
- "src"
33
+ "src",
34
+ "clyops-jobs.cjs"
33
35
  ],
34
- "scripts": {
35
- "build": "tsc -p tsconfig.json",
36
- "typecheck": "tsc -p tsconfig.json --noEmit",
37
- "test": "node --test test/*.test.mjs",
38
- "prepublishOnly": "npm run build && npm test"
39
- },
40
36
  "devDependencies": {
41
37
  "@types/node": "^22.0.0",
42
38
  "typescript": "^5.6.0"
43
39
  },
44
40
  "dependencies": {
45
- "clyops-tools": "0.2.0"
41
+ "clyops-tools": "0.3.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "node --test test/*.test.mjs"
46
47
  }
47
- }
48
+ }
package/src/functions.ts CHANGED
@@ -34,6 +34,8 @@ export interface FunctionDefinition {
34
34
  key?: string;
35
35
  script?: string;
36
36
  positionals?: unknown[];
37
+ /** Positionals before or after options (default: first). */
38
+ positionals_order?: 'first' | 'last';
37
39
  /** A template for a file fed to the tool's stdin, e.g. '${media.path}'. */
38
40
  stdin?: string;
39
41
  /** A template for the file the tool's stdout is written to; it also counts as an artifact. */
@@ -105,6 +107,7 @@ export async function buildFunctionCommand(fn: ResolvedFunction, opts: CommandOp
105
107
  controlled: opts.controlled ?? ['help'],
106
108
  render: context ? (s) => renderTemplateString(s, context) : undefined,
107
109
  positionals: explicitPositionals(fn, context),
110
+ positionalsOrder: fn.definition.positionals_order,
108
111
  });
109
112
  const name = basename(fn.script);
110
113
  for (const key of controlled) LOGGER.warn('[%s] ignoring config key %s; it is controlled by %s', name, key, LOGGER.module);