@terreno/api 0.22.2 → 0.23.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/dist/consentApp.d.ts +3 -0
- package/dist/consentApp.js +13 -7
- package/dist/consentApp.test.js +35 -0
- package/dist/scriptRunner.d.ts +77 -0
- package/dist/scriptRunner.js +258 -1
- package/dist/scriptRunner.test.d.ts +1 -0
- package/dist/scriptRunner.test.js +151 -0
- package/package.json +2 -2
- package/src/consentApp.test.ts +26 -0
- package/src/consentApp.ts +14 -6
- package/src/scriptRunner.test.ts +175 -0
- package/src/scriptRunner.ts +249 -0
package/dist/consentApp.d.ts
CHANGED
|
@@ -8,7 +8,10 @@
|
|
|
8
8
|
import { type Application } from "express";
|
|
9
9
|
import type { User } from "./auth";
|
|
10
10
|
import type { TerrenoPlugin } from "./terrenoPlugin";
|
|
11
|
+
import type { PopulatePath } from "./populate";
|
|
11
12
|
import type { ConsentFormDocument } from "./types/consentForm";
|
|
13
|
+
/** Shared populate config for consent response list/read endpoints. */
|
|
14
|
+
export declare const consentResponsePopulatePaths: PopulatePath[];
|
|
12
15
|
export interface ConsentAppOptions {
|
|
13
16
|
auditTrail?: boolean;
|
|
14
17
|
aiConfig?: {
|
package/dist/consentApp.js
CHANGED
|
@@ -54,7 +54,7 @@ var __values = (this && this.__values) || function(o) {
|
|
|
54
54
|
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
55
55
|
};
|
|
56
56
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
57
|
-
exports.ConsentApp = void 0;
|
|
57
|
+
exports.ConsentApp = exports.consentResponsePopulatePaths = void 0;
|
|
58
58
|
var express_1 = require("express");
|
|
59
59
|
var luxon_1 = require("luxon");
|
|
60
60
|
var api_1 = require("./api");
|
|
@@ -64,6 +64,17 @@ var logger_1 = require("./logger");
|
|
|
64
64
|
var consentForm_1 = require("./models/consentForm");
|
|
65
65
|
var consentResponse_1 = require("./models/consentResponse");
|
|
66
66
|
var permissions_1 = require("./permissions");
|
|
67
|
+
/** Shared populate config for consent response list/read endpoints. */
|
|
68
|
+
exports.consentResponsePopulatePaths = [
|
|
69
|
+
{
|
|
70
|
+
fields: ["title", "slug", "version", "type"],
|
|
71
|
+
path: "consentFormId",
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
fields: ["name", "email"],
|
|
75
|
+
path: "userId",
|
|
76
|
+
},
|
|
77
|
+
];
|
|
67
78
|
var requireAdmin = function (user) {
|
|
68
79
|
if (!(user === null || user === void 0 ? void 0 : user.admin)) {
|
|
69
80
|
throw new errors_1.APIError({ status: 403, title: "Admin access required" });
|
|
@@ -217,12 +228,7 @@ var ConsentApp = /** @class */ (function () {
|
|
|
217
228
|
read: [permissions_1.Permissions.IsAdmin],
|
|
218
229
|
update: [],
|
|
219
230
|
},
|
|
220
|
-
populatePaths:
|
|
221
|
-
{
|
|
222
|
-
fields: ["title", "slug", "version", "type"],
|
|
223
|
-
path: "consentFormId",
|
|
224
|
-
},
|
|
225
|
-
],
|
|
231
|
+
populatePaths: exports.consentResponsePopulatePaths,
|
|
226
232
|
}));
|
|
227
233
|
// User-facing consent endpoints
|
|
228
234
|
var router = (0, express_1.Router)();
|
package/dist/consentApp.test.js
CHANGED
|
@@ -331,6 +331,41 @@ var buildApp = function (consentAppOptions) {
|
|
|
331
331
|
}
|
|
332
332
|
});
|
|
333
333
|
}); });
|
|
334
|
+
(0, bun_test_1.it)("populates consentFormId and userId on read", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
335
|
+
var form, response, res;
|
|
336
|
+
return __generator(this, function (_a) {
|
|
337
|
+
switch (_a.label) {
|
|
338
|
+
case 0: return [4 /*yield*/, consentForm_1.ConsentForm.create({
|
|
339
|
+
active: true,
|
|
340
|
+
content: new Map([["en", "# Terms"]]),
|
|
341
|
+
order: 1,
|
|
342
|
+
slug: "terms-populated",
|
|
343
|
+
title: "Terms Populated",
|
|
344
|
+
type: "terms",
|
|
345
|
+
version: 1,
|
|
346
|
+
})];
|
|
347
|
+
case 1:
|
|
348
|
+
form = _a.sent();
|
|
349
|
+
return [4 /*yield*/, consentResponse_1.ConsentResponse.create({
|
|
350
|
+
agreed: true,
|
|
351
|
+
agreedAt: new Date(),
|
|
352
|
+
consentFormId: form._id,
|
|
353
|
+
formVersionSnapshot: 1,
|
|
354
|
+
locale: "en",
|
|
355
|
+
userId: notAdmin._id,
|
|
356
|
+
})];
|
|
357
|
+
case 2:
|
|
358
|
+
response = _a.sent();
|
|
359
|
+
return [4 /*yield*/, adminAgent.get("/consent-responses/".concat(response._id)).expect(200)];
|
|
360
|
+
case 3:
|
|
361
|
+
res = _a.sent();
|
|
362
|
+
(0, bun_test_1.expect)(res.body.data.consentFormId.title).toBe("Terms Populated");
|
|
363
|
+
(0, bun_test_1.expect)(res.body.data.userId.email).toBe(notAdmin.email);
|
|
364
|
+
(0, bun_test_1.expect)(res.body.data.userId.name).toBe(notAdmin.name);
|
|
365
|
+
return [2 /*return*/];
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}); });
|
|
334
369
|
(0, bun_test_1.it)("blocks non-admins from listing responses", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
335
370
|
return __generator(this, function (_a) {
|
|
336
371
|
switch (_a.label) {
|
package/dist/scriptRunner.d.ts
CHANGED
|
@@ -3,6 +3,51 @@ export interface ScriptResult {
|
|
|
3
3
|
success: boolean;
|
|
4
4
|
results: string[];
|
|
5
5
|
}
|
|
6
|
+
/** A single parsed argument value. Repeated flags collapse into a string array. */
|
|
7
|
+
export type ScriptArgValue = string | number | boolean | string[];
|
|
8
|
+
/**
|
|
9
|
+
* Optional declaration for a single script argument. Declarations are purely
|
|
10
|
+
* advisory: they drive validation, type coercion, default values, and help text
|
|
11
|
+
* but a script can still read any argument the caller supplied. This keeps
|
|
12
|
+
* argument handling flexible — declare the args you care about, ignore the rest.
|
|
13
|
+
*/
|
|
14
|
+
export interface ScriptArgDef {
|
|
15
|
+
/** Canonical name (used as `--name` on the CLI and as the key in the args map). */
|
|
16
|
+
name: string;
|
|
17
|
+
/** Human-readable description shown in CLI help and the admin UI. */
|
|
18
|
+
description: string;
|
|
19
|
+
/** Type used for coercion and validation. Defaults to "string". */
|
|
20
|
+
type?: "string" | "number" | "boolean";
|
|
21
|
+
/** When true, parsing fails if the argument is missing. */
|
|
22
|
+
required?: boolean;
|
|
23
|
+
/** Default applied when the argument is not provided. */
|
|
24
|
+
default?: ScriptArgValue;
|
|
25
|
+
/** Alternate names accepted on the CLI (e.g. ["l"] enables `-l`). */
|
|
26
|
+
aliases?: string[];
|
|
27
|
+
/** Example value shown in help text. */
|
|
28
|
+
example?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Typed, ergonomic accessor over the parsed arguments passed to a script. Scripts
|
|
32
|
+
* read values via the typed getters; `raw` and `positional` expose everything for
|
|
33
|
+
* advanced cases.
|
|
34
|
+
*/
|
|
35
|
+
export interface ScriptArgs {
|
|
36
|
+
/** All named values keyed by canonical name. */
|
|
37
|
+
raw: Record<string, ScriptArgValue>;
|
|
38
|
+
/** Positional (non-flag) arguments, in order. */
|
|
39
|
+
positional: string[];
|
|
40
|
+
/** Whether a named argument was supplied (or has a default). */
|
|
41
|
+
has: (name: string) => boolean;
|
|
42
|
+
/** Read a string value (coerces numbers/booleans; first element of arrays). */
|
|
43
|
+
getString: (name: string, fallback?: string) => string | undefined;
|
|
44
|
+
/** Read a numeric value (coerces strings; returns fallback when missing/NaN). */
|
|
45
|
+
getNumber: (name: string, fallback?: number) => number | undefined;
|
|
46
|
+
/** Read a boolean value ("true"/"1"/"yes"/"on" are truthy). */
|
|
47
|
+
getBoolean: (name: string, fallback?: boolean) => boolean;
|
|
48
|
+
/** Read a string array (single values become a one-element array). */
|
|
49
|
+
getStringArray: (name: string) => string[];
|
|
50
|
+
}
|
|
6
51
|
export interface ScriptContext {
|
|
7
52
|
/** Check if the task has been cancelled. Throws TaskCancelledError if so. */
|
|
8
53
|
checkCancellation: () => Promise<void>;
|
|
@@ -10,8 +55,40 @@ export interface ScriptContext {
|
|
|
10
55
|
addLog: (level: "info" | "warn" | "error", message: string) => Promise<void>;
|
|
11
56
|
/** Update progress on the task. */
|
|
12
57
|
updateProgress: (percentage: number, stage?: string, message?: string) => Promise<void>;
|
|
58
|
+
/** Arguments supplied to this run (from the CLI, HTTP body, or admin UI). */
|
|
59
|
+
args: ScriptArgs;
|
|
13
60
|
}
|
|
14
61
|
export type ScriptRunner = (wetRun: boolean, ctx?: ScriptContext) => Promise<ScriptResult>;
|
|
62
|
+
/**
|
|
63
|
+
* Build a {@link ScriptArgs} accessor from a raw values map and optional declarations.
|
|
64
|
+
* Applies declared defaults, coerces declared types, and validates required args.
|
|
65
|
+
* Returns the accessor plus any validation errors (callers decide how to surface them).
|
|
66
|
+
*/
|
|
67
|
+
export declare const createScriptArgs: ({ values, positional, defs, }: {
|
|
68
|
+
values: Record<string, ScriptArgValue>;
|
|
69
|
+
positional?: string[];
|
|
70
|
+
defs?: ScriptArgDef[];
|
|
71
|
+
}) => {
|
|
72
|
+
args: ScriptArgs;
|
|
73
|
+
errors: string[];
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Parse CLI-style tokens into a {@link ScriptArgs} accessor. Supports a flexible set
|
|
77
|
+
* of conventions so callers and scripts do not need to agree on a rigid format:
|
|
78
|
+
*
|
|
79
|
+
* - `--name=value` and `--name value`
|
|
80
|
+
* - `--flag` (boolean true) and `--no-flag` (boolean false)
|
|
81
|
+
* - short aliases `-x` (treated like `--x`)
|
|
82
|
+
* - repeated flags collapse into a string array
|
|
83
|
+
* - bare tokens become positional arguments
|
|
84
|
+
*
|
|
85
|
+
* When {@link ScriptArgDef declarations} are supplied, values are coerced to the
|
|
86
|
+
* declared type, defaults are applied, and required args are validated.
|
|
87
|
+
*/
|
|
88
|
+
export declare const parseScriptArgs: (tokens: string[], defs?: ScriptArgDef[]) => {
|
|
89
|
+
args: ScriptArgs;
|
|
90
|
+
errors: string[];
|
|
91
|
+
};
|
|
15
92
|
export declare class TaskCancelledError extends Error {
|
|
16
93
|
constructor(taskId: string);
|
|
17
94
|
}
|
package/dist/scriptRunner.js
CHANGED
|
@@ -14,6 +14,17 @@ var __extends = (this && this.__extends) || (function () {
|
|
|
14
14
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
15
15
|
};
|
|
16
16
|
})();
|
|
17
|
+
var __assign = (this && this.__assign) || function () {
|
|
18
|
+
__assign = Object.assign || function(t) {
|
|
19
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
20
|
+
s = arguments[i];
|
|
21
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
22
|
+
t[p] = s[p];
|
|
23
|
+
}
|
|
24
|
+
return t;
|
|
25
|
+
};
|
|
26
|
+
return __assign.apply(this, arguments);
|
|
27
|
+
};
|
|
17
28
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
18
29
|
if (k2 === undefined) k2 = k;
|
|
19
30
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -83,11 +94,257 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
83
94
|
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
84
95
|
}
|
|
85
96
|
};
|
|
97
|
+
var __values = (this && this.__values) || function(o) {
|
|
98
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
99
|
+
if (m) return m.call(o);
|
|
100
|
+
if (o && typeof o.length === "number") return {
|
|
101
|
+
next: function () {
|
|
102
|
+
if (o && i >= o.length) o = void 0;
|
|
103
|
+
return { value: o && o[i++], done: !o };
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
107
|
+
};
|
|
108
|
+
var __read = (this && this.__read) || function (o, n) {
|
|
109
|
+
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
110
|
+
if (!m) return o;
|
|
111
|
+
var i = m.call(o), r, ar = [], e;
|
|
112
|
+
try {
|
|
113
|
+
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
114
|
+
}
|
|
115
|
+
catch (error) { e = { error: error }; }
|
|
116
|
+
finally {
|
|
117
|
+
try {
|
|
118
|
+
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
119
|
+
}
|
|
120
|
+
finally { if (e) throw e.error; }
|
|
121
|
+
}
|
|
122
|
+
return ar;
|
|
123
|
+
};
|
|
124
|
+
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
125
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
126
|
+
if (ar || !(i in from)) {
|
|
127
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
128
|
+
ar[i] = from[i];
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
132
|
+
};
|
|
86
133
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
87
|
-
exports.BackgroundTask = exports.TaskCancelledError = void 0;
|
|
134
|
+
exports.BackgroundTask = exports.TaskCancelledError = exports.parseScriptArgs = exports.createScriptArgs = void 0;
|
|
88
135
|
var luxon_1 = require("luxon");
|
|
89
136
|
var mongoose_1 = __importStar(require("mongoose"));
|
|
90
137
|
var plugins_1 = require("./plugins");
|
|
138
|
+
var coerceArgValue = function (value, type) {
|
|
139
|
+
if (type === "number") {
|
|
140
|
+
var num = typeof value === "number" ? value : Number(Array.isArray(value) ? value[0] : value);
|
|
141
|
+
if (Number.isNaN(num)) {
|
|
142
|
+
return { error: "expected a number but received \"".concat(String(value), "\""), value: value };
|
|
143
|
+
}
|
|
144
|
+
return { value: num };
|
|
145
|
+
}
|
|
146
|
+
if (type === "boolean") {
|
|
147
|
+
if (typeof value === "boolean") {
|
|
148
|
+
return { value: value };
|
|
149
|
+
}
|
|
150
|
+
var normalized = String(Array.isArray(value) ? value[0] : value).toLowerCase();
|
|
151
|
+
if (["true", "1", "yes", "on"].includes(normalized)) {
|
|
152
|
+
return { value: true };
|
|
153
|
+
}
|
|
154
|
+
if (["false", "0", "no", "off"].includes(normalized)) {
|
|
155
|
+
return { value: false };
|
|
156
|
+
}
|
|
157
|
+
return { error: "expected a boolean but received \"".concat(String(value), "\""), value: value };
|
|
158
|
+
}
|
|
159
|
+
return { value: value };
|
|
160
|
+
};
|
|
161
|
+
var toStringValue = function (value) {
|
|
162
|
+
if (value === undefined) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
if (Array.isArray(value)) {
|
|
166
|
+
return value[0];
|
|
167
|
+
}
|
|
168
|
+
return String(value);
|
|
169
|
+
};
|
|
170
|
+
/**
|
|
171
|
+
* Build a {@link ScriptArgs} accessor from a raw values map and optional declarations.
|
|
172
|
+
* Applies declared defaults, coerces declared types, and validates required args.
|
|
173
|
+
* Returns the accessor plus any validation errors (callers decide how to surface them).
|
|
174
|
+
*/
|
|
175
|
+
var createScriptArgs = function (_a) {
|
|
176
|
+
var e_1, _b;
|
|
177
|
+
var values = _a.values, _c = _a.positional, positional = _c === void 0 ? [] : _c, _d = _a.defs, defs = _d === void 0 ? [] : _d;
|
|
178
|
+
var errors = [];
|
|
179
|
+
var raw = __assign({}, values);
|
|
180
|
+
try {
|
|
181
|
+
for (var defs_1 = __values(defs), defs_1_1 = defs_1.next(); !defs_1_1.done; defs_1_1 = defs_1.next()) {
|
|
182
|
+
var def = defs_1_1.value;
|
|
183
|
+
if (raw[def.name] === undefined) {
|
|
184
|
+
if (def.default !== undefined) {
|
|
185
|
+
raw[def.name] = def.default;
|
|
186
|
+
}
|
|
187
|
+
else if (def.required) {
|
|
188
|
+
errors.push("Missing required argument: --".concat(def.name, " (").concat(def.description, ")"));
|
|
189
|
+
}
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
var coerced = coerceArgValue(raw[def.name], def.type);
|
|
193
|
+
if (coerced.error) {
|
|
194
|
+
errors.push("Invalid argument --".concat(def.name, ": ").concat(coerced.error));
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
raw[def.name] = coerced.value;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
201
|
+
finally {
|
|
202
|
+
try {
|
|
203
|
+
if (defs_1_1 && !defs_1_1.done && (_b = defs_1.return)) _b.call(defs_1);
|
|
204
|
+
}
|
|
205
|
+
finally { if (e_1) throw e_1.error; }
|
|
206
|
+
}
|
|
207
|
+
var args = {
|
|
208
|
+
getBoolean: function (name, fallback) {
|
|
209
|
+
var _a;
|
|
210
|
+
if (fallback === void 0) { fallback = false; }
|
|
211
|
+
var value = raw[name];
|
|
212
|
+
if (value === undefined) {
|
|
213
|
+
return fallback;
|
|
214
|
+
}
|
|
215
|
+
if (typeof value === "boolean") {
|
|
216
|
+
return value;
|
|
217
|
+
}
|
|
218
|
+
var normalized = (_a = toStringValue(value)) === null || _a === void 0 ? void 0 : _a.toLowerCase();
|
|
219
|
+
return normalized !== undefined && ["true", "1", "yes", "on"].includes(normalized);
|
|
220
|
+
},
|
|
221
|
+
getNumber: function (name, fallback) {
|
|
222
|
+
var value = raw[name];
|
|
223
|
+
if (value === undefined) {
|
|
224
|
+
return fallback;
|
|
225
|
+
}
|
|
226
|
+
var num = typeof value === "number" ? value : Number(toStringValue(value));
|
|
227
|
+
return Number.isNaN(num) ? fallback : num;
|
|
228
|
+
},
|
|
229
|
+
getString: function (name, fallback) { var _a; return (_a = toStringValue(raw[name])) !== null && _a !== void 0 ? _a : fallback; },
|
|
230
|
+
getStringArray: function (name) {
|
|
231
|
+
var value = raw[name];
|
|
232
|
+
if (value === undefined) {
|
|
233
|
+
return [];
|
|
234
|
+
}
|
|
235
|
+
if (Array.isArray(value)) {
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
return [String(value)];
|
|
239
|
+
},
|
|
240
|
+
has: function (name) { return raw[name] !== undefined; },
|
|
241
|
+
positional: positional,
|
|
242
|
+
raw: raw,
|
|
243
|
+
};
|
|
244
|
+
return { args: args, errors: errors };
|
|
245
|
+
};
|
|
246
|
+
exports.createScriptArgs = createScriptArgs;
|
|
247
|
+
/**
|
|
248
|
+
* Parse CLI-style tokens into a {@link ScriptArgs} accessor. Supports a flexible set
|
|
249
|
+
* of conventions so callers and scripts do not need to agree on a rigid format:
|
|
250
|
+
*
|
|
251
|
+
* - `--name=value` and `--name value`
|
|
252
|
+
* - `--flag` (boolean true) and `--no-flag` (boolean false)
|
|
253
|
+
* - short aliases `-x` (treated like `--x`)
|
|
254
|
+
* - repeated flags collapse into a string array
|
|
255
|
+
* - bare tokens become positional arguments
|
|
256
|
+
*
|
|
257
|
+
* When {@link ScriptArgDef declarations} are supplied, values are coerced to the
|
|
258
|
+
* declared type, defaults are applied, and required args are validated.
|
|
259
|
+
*/
|
|
260
|
+
var parseScriptArgs = function (tokens, defs) {
|
|
261
|
+
var e_2, _a, e_3, _b;
|
|
262
|
+
var _c, _d, _e;
|
|
263
|
+
if (defs === void 0) { defs = []; }
|
|
264
|
+
var aliasToName = new Map();
|
|
265
|
+
var defByName = new Map();
|
|
266
|
+
try {
|
|
267
|
+
for (var defs_2 = __values(defs), defs_2_1 = defs_2.next(); !defs_2_1.done; defs_2_1 = defs_2.next()) {
|
|
268
|
+
var def = defs_2_1.value;
|
|
269
|
+
defByName.set(def.name, def);
|
|
270
|
+
try {
|
|
271
|
+
for (var _f = (e_3 = void 0, __values((_c = def.aliases) !== null && _c !== void 0 ? _c : [])), _g = _f.next(); !_g.done; _g = _f.next()) {
|
|
272
|
+
var alias = _g.value;
|
|
273
|
+
aliasToName.set(alias, def.name);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch (e_3_1) { e_3 = { error: e_3_1 }; }
|
|
277
|
+
finally {
|
|
278
|
+
try {
|
|
279
|
+
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
|
|
280
|
+
}
|
|
281
|
+
finally { if (e_3) throw e_3.error; }
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
286
|
+
finally {
|
|
287
|
+
try {
|
|
288
|
+
if (defs_2_1 && !defs_2_1.done && (_a = defs_2.return)) _a.call(defs_2);
|
|
289
|
+
}
|
|
290
|
+
finally { if (e_2) throw e_2.error; }
|
|
291
|
+
}
|
|
292
|
+
var values = {};
|
|
293
|
+
var positional = [];
|
|
294
|
+
var missingValueErrors = [];
|
|
295
|
+
var assign = function (key, value) {
|
|
296
|
+
var _a;
|
|
297
|
+
var name = (_a = aliasToName.get(key)) !== null && _a !== void 0 ? _a : key;
|
|
298
|
+
var existing = values[name];
|
|
299
|
+
if (existing === undefined) {
|
|
300
|
+
values[name] = value;
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
// Repeated flag: collapse into an array of strings.
|
|
304
|
+
var asArray = Array.isArray(existing) ? existing : [String(existing)];
|
|
305
|
+
values[name] = __spreadArray(__spreadArray([], __read(asArray), false), [String(value)], false);
|
|
306
|
+
};
|
|
307
|
+
for (var i = 0; i < tokens.length; i++) {
|
|
308
|
+
var token = tokens[i];
|
|
309
|
+
if (!token.startsWith("-") || token === "-") {
|
|
310
|
+
positional.push(token);
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
var flag = token.replace(/^-+/, "");
|
|
314
|
+
if (flag.startsWith("no-") && !flag.includes("=")) {
|
|
315
|
+
assign(flag.slice(3), false);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
var eqIndex = flag.indexOf("=");
|
|
319
|
+
if (eqIndex !== -1) {
|
|
320
|
+
assign(flag.slice(0, eqIndex), flag.slice(eqIndex + 1));
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
var canonical = (_d = aliasToName.get(flag)) !== null && _d !== void 0 ? _d : flag;
|
|
324
|
+
var def = defByName.get(canonical);
|
|
325
|
+
var next = tokens[i + 1];
|
|
326
|
+
var nextIsValue = next !== undefined && (next === "-" || !next.startsWith("-"));
|
|
327
|
+
if ((def === null || def === void 0 ? void 0 : def.type) === "boolean") {
|
|
328
|
+
assign(flag, true);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (!nextIsValue) {
|
|
332
|
+
// A declared string/number flag was given without a value. Record an error
|
|
333
|
+
// instead of silently storing `true` (which would coerce to 1 / "true").
|
|
334
|
+
if (def) {
|
|
335
|
+
missingValueErrors.push("Argument --".concat(canonical, " expects a ").concat((_e = def.type) !== null && _e !== void 0 ? _e : "string", " value"));
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
assign(flag, true);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
assign(flag, next);
|
|
342
|
+
i++;
|
|
343
|
+
}
|
|
344
|
+
var _h = (0, exports.createScriptArgs)({ defs: defs, positional: positional, values: values }), args = _h.args, errors = _h.errors;
|
|
345
|
+
return { args: args, errors: __spreadArray(__spreadArray([], __read(missingValueErrors), false), __read(errors), false) };
|
|
346
|
+
};
|
|
347
|
+
exports.parseScriptArgs = parseScriptArgs;
|
|
91
348
|
var TaskCancelledError = /** @class */ (function (_super) {
|
|
92
349
|
__extends(TaskCancelledError, _super);
|
|
93
350
|
function TaskCancelledError(taskId) {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
var bun_test_1 = require("bun:test");
|
|
4
|
+
var scriptRunner_1 = require("./scriptRunner");
|
|
5
|
+
(0, bun_test_1.describe)("parseScriptArgs", function () {
|
|
6
|
+
(0, bun_test_1.it)("parses --name=value form", function () {
|
|
7
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--model=todos"]).args;
|
|
8
|
+
(0, bun_test_1.expect)(args.getString("model")).toBe("todos");
|
|
9
|
+
(0, bun_test_1.expect)(args.has("model")).toBe(true);
|
|
10
|
+
});
|
|
11
|
+
(0, bun_test_1.it)("parses --name value form", function () {
|
|
12
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--model", "todos"]).args;
|
|
13
|
+
(0, bun_test_1.expect)(args.getString("model")).toBe("todos");
|
|
14
|
+
});
|
|
15
|
+
(0, bun_test_1.it)("treats a lone --flag as boolean true", function () {
|
|
16
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--wet"]).args;
|
|
17
|
+
(0, bun_test_1.expect)(args.getBoolean("wet")).toBe(true);
|
|
18
|
+
});
|
|
19
|
+
(0, bun_test_1.it)("parses --no-flag as boolean false", function () {
|
|
20
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--no-cache"]).args;
|
|
21
|
+
(0, bun_test_1.expect)(args.getBoolean("cache")).toBe(false);
|
|
22
|
+
});
|
|
23
|
+
(0, bun_test_1.it)("treats short -x like --x", function () {
|
|
24
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["-v"]).args;
|
|
25
|
+
(0, bun_test_1.expect)(args.getBoolean("v")).toBe(true);
|
|
26
|
+
});
|
|
27
|
+
(0, bun_test_1.it)("collects positional arguments", function () {
|
|
28
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["one", "two", "-"]).args;
|
|
29
|
+
(0, bun_test_1.expect)(args.positional).toEqual(["one", "two", "-"]);
|
|
30
|
+
});
|
|
31
|
+
(0, bun_test_1.it)("collapses repeated flags into an array", function () {
|
|
32
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--tag", "a", "--tag", "b", "--tag=c"]).args;
|
|
33
|
+
(0, bun_test_1.expect)(args.getStringArray("tag")).toEqual(["a", "b", "c"]);
|
|
34
|
+
});
|
|
35
|
+
(0, bun_test_1.it)("does not consume the next token for declared boolean flags", function () {
|
|
36
|
+
var defs = [{ description: "verbose", name: "verbose", type: "boolean" }];
|
|
37
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--verbose", "leftover"], defs).args;
|
|
38
|
+
(0, bun_test_1.expect)(args.getBoolean("verbose")).toBe(true);
|
|
39
|
+
(0, bun_test_1.expect)(args.positional).toEqual(["leftover"]);
|
|
40
|
+
});
|
|
41
|
+
(0, bun_test_1.it)("resolves aliases to the canonical name", function () {
|
|
42
|
+
var defs = [
|
|
43
|
+
{ aliases: ["m"], description: "model", name: "model", type: "string" },
|
|
44
|
+
];
|
|
45
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["-m", "users"], defs).args;
|
|
46
|
+
(0, bun_test_1.expect)(args.getString("model")).toBe("users");
|
|
47
|
+
});
|
|
48
|
+
(0, bun_test_1.it)("treats a trailing flag with no value as boolean true", function () {
|
|
49
|
+
var args = (0, scriptRunner_1.parseScriptArgs)(["--model", "todos", "--wet"]).args;
|
|
50
|
+
(0, bun_test_1.expect)(args.getString("model")).toBe("todos");
|
|
51
|
+
(0, bun_test_1.expect)(args.getBoolean("wet")).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
(0, bun_test_1.it)("errors when a declared string flag is missing its value", function () {
|
|
54
|
+
var defs = [{ description: "model", name: "model", type: "string" }];
|
|
55
|
+
var errors = (0, scriptRunner_1.parseScriptArgs)(["--model"], defs).errors;
|
|
56
|
+
(0, bun_test_1.expect)(errors).toHaveLength(1);
|
|
57
|
+
(0, bun_test_1.expect)(errors[0]).toInclude("--model expects a string value");
|
|
58
|
+
});
|
|
59
|
+
(0, bun_test_1.it)("errors when a declared number flag is followed by another flag", function () {
|
|
60
|
+
var defs = [{ description: "limit", name: "limit", type: "number" }];
|
|
61
|
+
var errors = (0, scriptRunner_1.parseScriptArgs)(["--limit", "--wet"], defs).errors;
|
|
62
|
+
(0, bun_test_1.expect)(errors.some(function (e) { return e.includes("--limit expects a number value"); })).toBe(true);
|
|
63
|
+
});
|
|
64
|
+
(0, bun_test_1.it)("still treats an undeclared value-less flag as boolean true", function () {
|
|
65
|
+
var _a = (0, scriptRunner_1.parseScriptArgs)(["--unknown"]), args = _a.args, errors = _a.errors;
|
|
66
|
+
(0, bun_test_1.expect)(errors).toHaveLength(0);
|
|
67
|
+
(0, bun_test_1.expect)(args.getBoolean("unknown")).toBe(true);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
(0, bun_test_1.describe)("createScriptArgs", function () {
|
|
71
|
+
(0, bun_test_1.it)("applies declared defaults when missing", function () {
|
|
72
|
+
var defs = [{ default: "all", description: "model", name: "model" }];
|
|
73
|
+
var _a = (0, scriptRunner_1.createScriptArgs)({ defs: defs, values: {} }), args = _a.args, errors = _a.errors;
|
|
74
|
+
(0, bun_test_1.expect)(errors).toHaveLength(0);
|
|
75
|
+
(0, bun_test_1.expect)(args.getString("model")).toBe("all");
|
|
76
|
+
});
|
|
77
|
+
(0, bun_test_1.it)("reports an error for missing required args", function () {
|
|
78
|
+
var defs = [{ description: "model", name: "model", required: true }];
|
|
79
|
+
var errors = (0, scriptRunner_1.createScriptArgs)({ defs: defs, values: {} }).errors;
|
|
80
|
+
(0, bun_test_1.expect)(errors).toHaveLength(1);
|
|
81
|
+
(0, bun_test_1.expect)(errors[0]).toInclude("Missing required argument: --model");
|
|
82
|
+
});
|
|
83
|
+
(0, bun_test_1.it)("coerces declared number args and reports invalid numbers", function () {
|
|
84
|
+
var defs = [{ description: "limit", name: "limit", type: "number" }];
|
|
85
|
+
var ok = (0, scriptRunner_1.createScriptArgs)({ defs: defs, values: { limit: "10" } });
|
|
86
|
+
(0, bun_test_1.expect)(ok.errors).toHaveLength(0);
|
|
87
|
+
(0, bun_test_1.expect)(ok.args.getNumber("limit")).toBe(10);
|
|
88
|
+
var bad = (0, scriptRunner_1.createScriptArgs)({ defs: defs, values: { limit: "nope" } });
|
|
89
|
+
(0, bun_test_1.expect)(bad.errors).toHaveLength(1);
|
|
90
|
+
(0, bun_test_1.expect)(bad.errors[0]).toInclude("expected a number");
|
|
91
|
+
});
|
|
92
|
+
(0, bun_test_1.it)("coerces declared boolean args", function () {
|
|
93
|
+
var defs = [{ description: "force", name: "force", type: "boolean" }];
|
|
94
|
+
(0, bun_test_1.expect)((0, scriptRunner_1.createScriptArgs)({ defs: defs, values: { force: "yes" } }).args.getBoolean("force")).toBe(true);
|
|
95
|
+
(0, bun_test_1.expect)((0, scriptRunner_1.createScriptArgs)({ defs: defs, values: { force: "off" } }).args.getBoolean("force")).toBe(false);
|
|
96
|
+
var bad = (0, scriptRunner_1.createScriptArgs)({ defs: defs, values: { force: "maybe" } });
|
|
97
|
+
(0, bun_test_1.expect)(bad.errors[0]).toInclude("expected a boolean");
|
|
98
|
+
});
|
|
99
|
+
(0, bun_test_1.it)("coerces booleans and numbers from array values (first element)", function () {
|
|
100
|
+
var defs = [
|
|
101
|
+
{ description: "force", name: "force", type: "boolean" },
|
|
102
|
+
{ description: "limit", name: "limit", type: "number" },
|
|
103
|
+
];
|
|
104
|
+
var args = (0, scriptRunner_1.createScriptArgs)({
|
|
105
|
+
defs: defs,
|
|
106
|
+
values: { force: ["true", "false"], limit: ["5", "6"] },
|
|
107
|
+
}).args;
|
|
108
|
+
(0, bun_test_1.expect)(args.getBoolean("force")).toBe(true);
|
|
109
|
+
(0, bun_test_1.expect)(args.getNumber("limit")).toBe(5);
|
|
110
|
+
});
|
|
111
|
+
(0, bun_test_1.describe)("getters", function () {
|
|
112
|
+
(0, bun_test_1.it)("getString returns fallback when missing and stringifies non-strings", function () {
|
|
113
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ values: { count: 3, flag: true } }).args;
|
|
114
|
+
(0, bun_test_1.expect)(args.getString("missing", "fallback")).toBe("fallback");
|
|
115
|
+
(0, bun_test_1.expect)(args.getString("count")).toBe("3");
|
|
116
|
+
(0, bun_test_1.expect)(args.getString("flag")).toBe("true");
|
|
117
|
+
});
|
|
118
|
+
(0, bun_test_1.it)("getNumber handles native numbers, strings, NaN, and missing", function () {
|
|
119
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ values: { a: 7, b: "8", c: "x" } }).args;
|
|
120
|
+
(0, bun_test_1.expect)(args.getNumber("a")).toBe(7);
|
|
121
|
+
(0, bun_test_1.expect)(args.getNumber("b")).toBe(8);
|
|
122
|
+
(0, bun_test_1.expect)(args.getNumber("c", 1)).toBe(1);
|
|
123
|
+
(0, bun_test_1.expect)(args.getNumber("missing", 99)).toBe(99);
|
|
124
|
+
(0, bun_test_1.expect)(args.getNumber("missing")).toBeUndefined();
|
|
125
|
+
});
|
|
126
|
+
(0, bun_test_1.it)("getBoolean honors native booleans, string truthiness, and fallback", function () {
|
|
127
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ values: { a: true, b: "on", c: "nope" } }).args;
|
|
128
|
+
(0, bun_test_1.expect)(args.getBoolean("a")).toBe(true);
|
|
129
|
+
(0, bun_test_1.expect)(args.getBoolean("b")).toBe(true);
|
|
130
|
+
(0, bun_test_1.expect)(args.getBoolean("c")).toBe(false);
|
|
131
|
+
(0, bun_test_1.expect)(args.getBoolean("missing")).toBe(false);
|
|
132
|
+
(0, bun_test_1.expect)(args.getBoolean("missing", true)).toBe(true);
|
|
133
|
+
});
|
|
134
|
+
(0, bun_test_1.it)("reads undeclared array values via getString/getNumber (first element)", function () {
|
|
135
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ values: { nums: ["3", "4"], tags: ["x", "y"] } }).args;
|
|
136
|
+
(0, bun_test_1.expect)(args.getString("tags")).toBe("x");
|
|
137
|
+
(0, bun_test_1.expect)(args.getNumber("nums")).toBe(3);
|
|
138
|
+
});
|
|
139
|
+
(0, bun_test_1.it)("getStringArray normalizes single values and missing keys", function () {
|
|
140
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ values: { many: ["a", "b"], one: "x" } }).args;
|
|
141
|
+
(0, bun_test_1.expect)(args.getStringArray("one")).toEqual(["x"]);
|
|
142
|
+
(0, bun_test_1.expect)(args.getStringArray("many")).toEqual(["a", "b"]);
|
|
143
|
+
(0, bun_test_1.expect)(args.getStringArray("missing")).toEqual([]);
|
|
144
|
+
});
|
|
145
|
+
(0, bun_test_1.it)("exposes raw values and positional list", function () {
|
|
146
|
+
var args = (0, scriptRunner_1.createScriptArgs)({ positional: ["p"], values: { x: "1" } }).args;
|
|
147
|
+
(0, bun_test_1.expect)(args.raw.x).toBe("1");
|
|
148
|
+
(0, bun_test_1.expect)(args.positional).toEqual(["p"]);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
});
|
package/package.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
|
8
8
|
"@sentry/bun": "^10.25.0",
|
|
9
9
|
"@sentry/profiling-node": "^10.25.0",
|
|
10
|
-
"@terreno/test": "0.
|
|
10
|
+
"@terreno/test": "0.23.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.18.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -123,5 +123,5 @@
|
|
|
123
123
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
124
|
},
|
|
125
125
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "0.
|
|
126
|
+
"version": "0.23.0"
|
|
127
127
|
}
|
package/src/consentApp.test.ts
CHANGED
|
@@ -185,6 +185,32 @@ describe("ConsentApp", () => {
|
|
|
185
185
|
expect(res.body.data[0].agreed).toBe(true);
|
|
186
186
|
});
|
|
187
187
|
|
|
188
|
+
it("populates consentFormId and userId on read", async () => {
|
|
189
|
+
const form = await ConsentForm.create({
|
|
190
|
+
active: true,
|
|
191
|
+
content: new Map([["en", "# Terms"]]),
|
|
192
|
+
order: 1,
|
|
193
|
+
slug: "terms-populated",
|
|
194
|
+
title: "Terms Populated",
|
|
195
|
+
type: "terms",
|
|
196
|
+
version: 1,
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const response = await ConsentResponse.create({
|
|
200
|
+
agreed: true,
|
|
201
|
+
agreedAt: new Date(),
|
|
202
|
+
consentFormId: form._id,
|
|
203
|
+
formVersionSnapshot: 1,
|
|
204
|
+
locale: "en",
|
|
205
|
+
userId: notAdmin._id,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const res = await adminAgent.get(`/consent-responses/${response._id}`).expect(200);
|
|
209
|
+
expect(res.body.data.consentFormId.title).toBe("Terms Populated");
|
|
210
|
+
expect(res.body.data.userId.email).toBe(notAdmin.email);
|
|
211
|
+
expect(res.body.data.userId.name).toBe(notAdmin.name);
|
|
212
|
+
});
|
|
213
|
+
|
|
188
214
|
it("blocks non-admins from listing responses", async () => {
|
|
189
215
|
await userAgent.get("/consent-responses").expect(405);
|
|
190
216
|
});
|
package/src/consentApp.ts
CHANGED
|
@@ -18,8 +18,21 @@ import {ConsentForm} from "./models/consentForm";
|
|
|
18
18
|
import {ConsentResponse} from "./models/consentResponse";
|
|
19
19
|
import {Permissions} from "./permissions";
|
|
20
20
|
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
21
|
+
import type {PopulatePath} from "./populate";
|
|
21
22
|
import type {ConsentFormDocument} from "./types/consentForm";
|
|
22
23
|
|
|
24
|
+
/** Shared populate config for consent response list/read endpoints. */
|
|
25
|
+
export const consentResponsePopulatePaths: PopulatePath[] = [
|
|
26
|
+
{
|
|
27
|
+
fields: ["title", "slug", "version", "type"],
|
|
28
|
+
path: "consentFormId",
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
fields: ["name", "email"],
|
|
32
|
+
path: "userId",
|
|
33
|
+
},
|
|
34
|
+
];
|
|
35
|
+
|
|
23
36
|
export interface ConsentAppOptions {
|
|
24
37
|
auditTrail?: boolean;
|
|
25
38
|
aiConfig?: {
|
|
@@ -188,12 +201,7 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
188
201
|
read: [Permissions.IsAdmin],
|
|
189
202
|
update: [],
|
|
190
203
|
},
|
|
191
|
-
populatePaths:
|
|
192
|
-
{
|
|
193
|
-
fields: ["title", "slug", "version", "type"],
|
|
194
|
-
path: "consentFormId",
|
|
195
|
-
},
|
|
196
|
-
],
|
|
204
|
+
populatePaths: consentResponsePopulatePaths,
|
|
197
205
|
})
|
|
198
206
|
);
|
|
199
207
|
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
|
|
3
|
+
import {createScriptArgs, parseScriptArgs, type ScriptArgDef} from "./scriptRunner";
|
|
4
|
+
|
|
5
|
+
describe("parseScriptArgs", () => {
|
|
6
|
+
it("parses --name=value form", () => {
|
|
7
|
+
const {args} = parseScriptArgs(["--model=todos"]);
|
|
8
|
+
expect(args.getString("model")).toBe("todos");
|
|
9
|
+
expect(args.has("model")).toBe(true);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("parses --name value form", () => {
|
|
13
|
+
const {args} = parseScriptArgs(["--model", "todos"]);
|
|
14
|
+
expect(args.getString("model")).toBe("todos");
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it("treats a lone --flag as boolean true", () => {
|
|
18
|
+
const {args} = parseScriptArgs(["--wet"]);
|
|
19
|
+
expect(args.getBoolean("wet")).toBe(true);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("parses --no-flag as boolean false", () => {
|
|
23
|
+
const {args} = parseScriptArgs(["--no-cache"]);
|
|
24
|
+
expect(args.getBoolean("cache")).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("treats short -x like --x", () => {
|
|
28
|
+
const {args} = parseScriptArgs(["-v"]);
|
|
29
|
+
expect(args.getBoolean("v")).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("collects positional arguments", () => {
|
|
33
|
+
const {args} = parseScriptArgs(["one", "two", "-"]);
|
|
34
|
+
expect(args.positional).toEqual(["one", "two", "-"]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("collapses repeated flags into an array", () => {
|
|
38
|
+
const {args} = parseScriptArgs(["--tag", "a", "--tag", "b", "--tag=c"]);
|
|
39
|
+
expect(args.getStringArray("tag")).toEqual(["a", "b", "c"]);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("does not consume the next token for declared boolean flags", () => {
|
|
43
|
+
const defs: ScriptArgDef[] = [{description: "verbose", name: "verbose", type: "boolean"}];
|
|
44
|
+
const {args} = parseScriptArgs(["--verbose", "leftover"], defs);
|
|
45
|
+
expect(args.getBoolean("verbose")).toBe(true);
|
|
46
|
+
expect(args.positional).toEqual(["leftover"]);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("resolves aliases to the canonical name", () => {
|
|
50
|
+
const defs: ScriptArgDef[] = [
|
|
51
|
+
{aliases: ["m"], description: "model", name: "model", type: "string"},
|
|
52
|
+
];
|
|
53
|
+
const {args} = parseScriptArgs(["-m", "users"], defs);
|
|
54
|
+
expect(args.getString("model")).toBe("users");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("treats a trailing flag with no value as boolean true", () => {
|
|
58
|
+
const {args} = parseScriptArgs(["--model", "todos", "--wet"]);
|
|
59
|
+
expect(args.getString("model")).toBe("todos");
|
|
60
|
+
expect(args.getBoolean("wet")).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("errors when a declared string flag is missing its value", () => {
|
|
64
|
+
const defs: ScriptArgDef[] = [{description: "model", name: "model", type: "string"}];
|
|
65
|
+
const {errors} = parseScriptArgs(["--model"], defs);
|
|
66
|
+
expect(errors).toHaveLength(1);
|
|
67
|
+
expect(errors[0]).toInclude("--model expects a string value");
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("errors when a declared number flag is followed by another flag", () => {
|
|
71
|
+
const defs: ScriptArgDef[] = [{description: "limit", name: "limit", type: "number"}];
|
|
72
|
+
const {errors} = parseScriptArgs(["--limit", "--wet"], defs);
|
|
73
|
+
expect(errors.some((e) => e.includes("--limit expects a number value"))).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("still treats an undeclared value-less flag as boolean true", () => {
|
|
77
|
+
const {args, errors} = parseScriptArgs(["--unknown"]);
|
|
78
|
+
expect(errors).toHaveLength(0);
|
|
79
|
+
expect(args.getBoolean("unknown")).toBe(true);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("createScriptArgs", () => {
|
|
84
|
+
it("applies declared defaults when missing", () => {
|
|
85
|
+
const defs: ScriptArgDef[] = [{default: "all", description: "model", name: "model"}];
|
|
86
|
+
const {args, errors} = createScriptArgs({defs, values: {}});
|
|
87
|
+
expect(errors).toHaveLength(0);
|
|
88
|
+
expect(args.getString("model")).toBe("all");
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("reports an error for missing required args", () => {
|
|
92
|
+
const defs: ScriptArgDef[] = [{description: "model", name: "model", required: true}];
|
|
93
|
+
const {errors} = createScriptArgs({defs, values: {}});
|
|
94
|
+
expect(errors).toHaveLength(1);
|
|
95
|
+
expect(errors[0]).toInclude("Missing required argument: --model");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("coerces declared number args and reports invalid numbers", () => {
|
|
99
|
+
const defs: ScriptArgDef[] = [{description: "limit", name: "limit", type: "number"}];
|
|
100
|
+
const ok = createScriptArgs({defs, values: {limit: "10"}});
|
|
101
|
+
expect(ok.errors).toHaveLength(0);
|
|
102
|
+
expect(ok.args.getNumber("limit")).toBe(10);
|
|
103
|
+
|
|
104
|
+
const bad = createScriptArgs({defs, values: {limit: "nope"}});
|
|
105
|
+
expect(bad.errors).toHaveLength(1);
|
|
106
|
+
expect(bad.errors[0]).toInclude("expected a number");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("coerces declared boolean args", () => {
|
|
110
|
+
const defs: ScriptArgDef[] = [{description: "force", name: "force", type: "boolean"}];
|
|
111
|
+
expect(createScriptArgs({defs, values: {force: "yes"}}).args.getBoolean("force")).toBe(true);
|
|
112
|
+
expect(createScriptArgs({defs, values: {force: "off"}}).args.getBoolean("force")).toBe(false);
|
|
113
|
+
const bad = createScriptArgs({defs, values: {force: "maybe"}});
|
|
114
|
+
expect(bad.errors[0]).toInclude("expected a boolean");
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("coerces booleans and numbers from array values (first element)", () => {
|
|
118
|
+
const defs: ScriptArgDef[] = [
|
|
119
|
+
{description: "force", name: "force", type: "boolean"},
|
|
120
|
+
{description: "limit", name: "limit", type: "number"},
|
|
121
|
+
];
|
|
122
|
+
const {args} = createScriptArgs({
|
|
123
|
+
defs,
|
|
124
|
+
values: {force: ["true", "false"], limit: ["5", "6"]},
|
|
125
|
+
});
|
|
126
|
+
expect(args.getBoolean("force")).toBe(true);
|
|
127
|
+
expect(args.getNumber("limit")).toBe(5);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("getters", () => {
|
|
131
|
+
it("getString returns fallback when missing and stringifies non-strings", () => {
|
|
132
|
+
const {args} = createScriptArgs({values: {count: 3, flag: true}});
|
|
133
|
+
expect(args.getString("missing", "fallback")).toBe("fallback");
|
|
134
|
+
expect(args.getString("count")).toBe("3");
|
|
135
|
+
expect(args.getString("flag")).toBe("true");
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("getNumber handles native numbers, strings, NaN, and missing", () => {
|
|
139
|
+
const {args} = createScriptArgs({values: {a: 7, b: "8", c: "x"}});
|
|
140
|
+
expect(args.getNumber("a")).toBe(7);
|
|
141
|
+
expect(args.getNumber("b")).toBe(8);
|
|
142
|
+
expect(args.getNumber("c", 1)).toBe(1);
|
|
143
|
+
expect(args.getNumber("missing", 99)).toBe(99);
|
|
144
|
+
expect(args.getNumber("missing")).toBeUndefined();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("getBoolean honors native booleans, string truthiness, and fallback", () => {
|
|
148
|
+
const {args} = createScriptArgs({values: {a: true, b: "on", c: "nope"}});
|
|
149
|
+
expect(args.getBoolean("a")).toBe(true);
|
|
150
|
+
expect(args.getBoolean("b")).toBe(true);
|
|
151
|
+
expect(args.getBoolean("c")).toBe(false);
|
|
152
|
+
expect(args.getBoolean("missing")).toBe(false);
|
|
153
|
+
expect(args.getBoolean("missing", true)).toBe(true);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("reads undeclared array values via getString/getNumber (first element)", () => {
|
|
157
|
+
const {args} = createScriptArgs({values: {nums: ["3", "4"], tags: ["x", "y"]}});
|
|
158
|
+
expect(args.getString("tags")).toBe("x");
|
|
159
|
+
expect(args.getNumber("nums")).toBe(3);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("getStringArray normalizes single values and missing keys", () => {
|
|
163
|
+
const {args} = createScriptArgs({values: {many: ["a", "b"], one: "x"}});
|
|
164
|
+
expect(args.getStringArray("one")).toEqual(["x"]);
|
|
165
|
+
expect(args.getStringArray("many")).toEqual(["a", "b"]);
|
|
166
|
+
expect(args.getStringArray("missing")).toEqual([]);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("exposes raw values and positional list", () => {
|
|
170
|
+
const {args} = createScriptArgs({positional: ["p"], values: {x: "1"}});
|
|
171
|
+
expect(args.raw.x).toBe("1");
|
|
172
|
+
expect(args.positional).toEqual(["p"]);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
});
|
package/src/scriptRunner.ts
CHANGED
|
@@ -10,6 +10,56 @@ export interface ScriptResult {
|
|
|
10
10
|
results: string[];
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
// --- Flexible Script Arguments ---
|
|
14
|
+
|
|
15
|
+
/** A single parsed argument value. Repeated flags collapse into a string array. */
|
|
16
|
+
export type ScriptArgValue = string | number | boolean | string[];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Optional declaration for a single script argument. Declarations are purely
|
|
20
|
+
* advisory: they drive validation, type coercion, default values, and help text
|
|
21
|
+
* but a script can still read any argument the caller supplied. This keeps
|
|
22
|
+
* argument handling flexible — declare the args you care about, ignore the rest.
|
|
23
|
+
*/
|
|
24
|
+
export interface ScriptArgDef {
|
|
25
|
+
/** Canonical name (used as `--name` on the CLI and as the key in the args map). */
|
|
26
|
+
name: string;
|
|
27
|
+
/** Human-readable description shown in CLI help and the admin UI. */
|
|
28
|
+
description: string;
|
|
29
|
+
/** Type used for coercion and validation. Defaults to "string". */
|
|
30
|
+
type?: "string" | "number" | "boolean";
|
|
31
|
+
/** When true, parsing fails if the argument is missing. */
|
|
32
|
+
required?: boolean;
|
|
33
|
+
/** Default applied when the argument is not provided. */
|
|
34
|
+
default?: ScriptArgValue;
|
|
35
|
+
/** Alternate names accepted on the CLI (e.g. ["l"] enables `-l`). */
|
|
36
|
+
aliases?: string[];
|
|
37
|
+
/** Example value shown in help text. */
|
|
38
|
+
example?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Typed, ergonomic accessor over the parsed arguments passed to a script. Scripts
|
|
43
|
+
* read values via the typed getters; `raw` and `positional` expose everything for
|
|
44
|
+
* advanced cases.
|
|
45
|
+
*/
|
|
46
|
+
export interface ScriptArgs {
|
|
47
|
+
/** All named values keyed by canonical name. */
|
|
48
|
+
raw: Record<string, ScriptArgValue>;
|
|
49
|
+
/** Positional (non-flag) arguments, in order. */
|
|
50
|
+
positional: string[];
|
|
51
|
+
/** Whether a named argument was supplied (or has a default). */
|
|
52
|
+
has: (name: string) => boolean;
|
|
53
|
+
/** Read a string value (coerces numbers/booleans; first element of arrays). */
|
|
54
|
+
getString: (name: string, fallback?: string) => string | undefined;
|
|
55
|
+
/** Read a numeric value (coerces strings; returns fallback when missing/NaN). */
|
|
56
|
+
getNumber: (name: string, fallback?: number) => number | undefined;
|
|
57
|
+
/** Read a boolean value ("true"/"1"/"yes"/"on" are truthy). */
|
|
58
|
+
getBoolean: (name: string, fallback?: boolean) => boolean;
|
|
59
|
+
/** Read a string array (single values become a one-element array). */
|
|
60
|
+
getStringArray: (name: string) => string[];
|
|
61
|
+
}
|
|
62
|
+
|
|
13
63
|
export interface ScriptContext {
|
|
14
64
|
/** Check if the task has been cancelled. Throws TaskCancelledError if so. */
|
|
15
65
|
checkCancellation: () => Promise<void>;
|
|
@@ -17,10 +67,209 @@ export interface ScriptContext {
|
|
|
17
67
|
addLog: (level: "info" | "warn" | "error", message: string) => Promise<void>;
|
|
18
68
|
/** Update progress on the task. */
|
|
19
69
|
updateProgress: (percentage: number, stage?: string, message?: string) => Promise<void>;
|
|
70
|
+
/** Arguments supplied to this run (from the CLI, HTTP body, or admin UI). */
|
|
71
|
+
args: ScriptArgs;
|
|
20
72
|
}
|
|
21
73
|
|
|
22
74
|
export type ScriptRunner = (wetRun: boolean, ctx?: ScriptContext) => Promise<ScriptResult>;
|
|
23
75
|
|
|
76
|
+
const coerceArgValue = (
|
|
77
|
+
value: ScriptArgValue,
|
|
78
|
+
type: ScriptArgDef["type"]
|
|
79
|
+
): {value: ScriptArgValue; error?: string} => {
|
|
80
|
+
if (type === "number") {
|
|
81
|
+
const num = typeof value === "number" ? value : Number(Array.isArray(value) ? value[0] : value);
|
|
82
|
+
if (Number.isNaN(num)) {
|
|
83
|
+
return {error: `expected a number but received "${String(value)}"`, value};
|
|
84
|
+
}
|
|
85
|
+
return {value: num};
|
|
86
|
+
}
|
|
87
|
+
if (type === "boolean") {
|
|
88
|
+
if (typeof value === "boolean") {
|
|
89
|
+
return {value};
|
|
90
|
+
}
|
|
91
|
+
const normalized = String(Array.isArray(value) ? value[0] : value).toLowerCase();
|
|
92
|
+
if (["true", "1", "yes", "on"].includes(normalized)) {
|
|
93
|
+
return {value: true};
|
|
94
|
+
}
|
|
95
|
+
if (["false", "0", "no", "off"].includes(normalized)) {
|
|
96
|
+
return {value: false};
|
|
97
|
+
}
|
|
98
|
+
return {error: `expected a boolean but received "${String(value)}"`, value};
|
|
99
|
+
}
|
|
100
|
+
return {value};
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const toStringValue = (value: ScriptArgValue | undefined): string | undefined => {
|
|
104
|
+
if (value === undefined) {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
if (Array.isArray(value)) {
|
|
108
|
+
return value[0];
|
|
109
|
+
}
|
|
110
|
+
return String(value);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Build a {@link ScriptArgs} accessor from a raw values map and optional declarations.
|
|
115
|
+
* Applies declared defaults, coerces declared types, and validates required args.
|
|
116
|
+
* Returns the accessor plus any validation errors (callers decide how to surface them).
|
|
117
|
+
*/
|
|
118
|
+
export const createScriptArgs = ({
|
|
119
|
+
values,
|
|
120
|
+
positional = [],
|
|
121
|
+
defs = [],
|
|
122
|
+
}: {
|
|
123
|
+
values: Record<string, ScriptArgValue>;
|
|
124
|
+
positional?: string[];
|
|
125
|
+
defs?: ScriptArgDef[];
|
|
126
|
+
}): {args: ScriptArgs; errors: string[]} => {
|
|
127
|
+
const errors: string[] = [];
|
|
128
|
+
const raw: Record<string, ScriptArgValue> = {...values};
|
|
129
|
+
|
|
130
|
+
for (const def of defs) {
|
|
131
|
+
if (raw[def.name] === undefined) {
|
|
132
|
+
if (def.default !== undefined) {
|
|
133
|
+
raw[def.name] = def.default;
|
|
134
|
+
} else if (def.required) {
|
|
135
|
+
errors.push(`Missing required argument: --${def.name} (${def.description})`);
|
|
136
|
+
}
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const coerced = coerceArgValue(raw[def.name], def.type);
|
|
140
|
+
if (coerced.error) {
|
|
141
|
+
errors.push(`Invalid argument --${def.name}: ${coerced.error}`);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
raw[def.name] = coerced.value;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const args: ScriptArgs = {
|
|
148
|
+
getBoolean: (name, fallback = false) => {
|
|
149
|
+
const value = raw[name];
|
|
150
|
+
if (value === undefined) {
|
|
151
|
+
return fallback;
|
|
152
|
+
}
|
|
153
|
+
if (typeof value === "boolean") {
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
const normalized = toStringValue(value)?.toLowerCase();
|
|
157
|
+
return normalized !== undefined && ["true", "1", "yes", "on"].includes(normalized);
|
|
158
|
+
},
|
|
159
|
+
getNumber: (name, fallback) => {
|
|
160
|
+
const value = raw[name];
|
|
161
|
+
if (value === undefined) {
|
|
162
|
+
return fallback;
|
|
163
|
+
}
|
|
164
|
+
const num = typeof value === "number" ? value : Number(toStringValue(value));
|
|
165
|
+
return Number.isNaN(num) ? fallback : num;
|
|
166
|
+
},
|
|
167
|
+
getString: (name, fallback) => toStringValue(raw[name]) ?? fallback,
|
|
168
|
+
getStringArray: (name) => {
|
|
169
|
+
const value = raw[name];
|
|
170
|
+
if (value === undefined) {
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
if (Array.isArray(value)) {
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
return [String(value)];
|
|
177
|
+
},
|
|
178
|
+
has: (name) => raw[name] !== undefined,
|
|
179
|
+
positional,
|
|
180
|
+
raw,
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
return {args, errors};
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Parse CLI-style tokens into a {@link ScriptArgs} accessor. Supports a flexible set
|
|
188
|
+
* of conventions so callers and scripts do not need to agree on a rigid format:
|
|
189
|
+
*
|
|
190
|
+
* - `--name=value` and `--name value`
|
|
191
|
+
* - `--flag` (boolean true) and `--no-flag` (boolean false)
|
|
192
|
+
* - short aliases `-x` (treated like `--x`)
|
|
193
|
+
* - repeated flags collapse into a string array
|
|
194
|
+
* - bare tokens become positional arguments
|
|
195
|
+
*
|
|
196
|
+
* When {@link ScriptArgDef declarations} are supplied, values are coerced to the
|
|
197
|
+
* declared type, defaults are applied, and required args are validated.
|
|
198
|
+
*/
|
|
199
|
+
export const parseScriptArgs = (
|
|
200
|
+
tokens: string[],
|
|
201
|
+
defs: ScriptArgDef[] = []
|
|
202
|
+
): {args: ScriptArgs; errors: string[]} => {
|
|
203
|
+
const aliasToName = new Map<string, string>();
|
|
204
|
+
const defByName = new Map<string, ScriptArgDef>();
|
|
205
|
+
for (const def of defs) {
|
|
206
|
+
defByName.set(def.name, def);
|
|
207
|
+
for (const alias of def.aliases ?? []) {
|
|
208
|
+
aliasToName.set(alias, def.name);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const values: Record<string, ScriptArgValue> = {};
|
|
213
|
+
const positional: string[] = [];
|
|
214
|
+
const missingValueErrors: string[] = [];
|
|
215
|
+
|
|
216
|
+
const assign = (key: string, value: ScriptArgValue): void => {
|
|
217
|
+
const name = aliasToName.get(key) ?? key;
|
|
218
|
+
const existing = values[name];
|
|
219
|
+
if (existing === undefined) {
|
|
220
|
+
values[name] = value;
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
// Repeated flag: collapse into an array of strings.
|
|
224
|
+
const asArray = Array.isArray(existing) ? existing : [String(existing)];
|
|
225
|
+
values[name] = [...asArray, String(value)];
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
229
|
+
const token = tokens[i];
|
|
230
|
+
if (!token.startsWith("-") || token === "-") {
|
|
231
|
+
positional.push(token);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const flag = token.replace(/^-+/, "");
|
|
236
|
+
if (flag.startsWith("no-") && !flag.includes("=")) {
|
|
237
|
+
assign(flag.slice(3), false);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const eqIndex = flag.indexOf("=");
|
|
242
|
+
if (eqIndex !== -1) {
|
|
243
|
+
assign(flag.slice(0, eqIndex), flag.slice(eqIndex + 1));
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const canonical = aliasToName.get(flag) ?? flag;
|
|
248
|
+
const def = defByName.get(canonical);
|
|
249
|
+
const next = tokens[i + 1];
|
|
250
|
+
const nextIsValue = next !== undefined && (next === "-" || !next.startsWith("-"));
|
|
251
|
+
if (def?.type === "boolean") {
|
|
252
|
+
assign(flag, true);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (!nextIsValue) {
|
|
256
|
+
// A declared string/number flag was given without a value. Record an error
|
|
257
|
+
// instead of silently storing `true` (which would coerce to 1 / "true").
|
|
258
|
+
if (def) {
|
|
259
|
+
missingValueErrors.push(`Argument --${canonical} expects a ${def.type ?? "string"} value`);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
assign(flag, true);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
assign(flag, next);
|
|
266
|
+
i++;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const {args, errors} = createScriptArgs({defs, positional, values});
|
|
270
|
+
return {args, errors: [...missingValueErrors, ...errors]};
|
|
271
|
+
};
|
|
272
|
+
|
|
24
273
|
export class TaskCancelledError extends Error {
|
|
25
274
|
constructor(taskId: string) {
|
|
26
275
|
super(`Task ${taskId} was cancelled`);
|