@terreno/admin-backend 0.22.1 → 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.
@@ -171,6 +171,108 @@ describe("AdminApp script routes", () => {
171
171
  });
172
172
  });
173
173
 
174
+ describe("POST /admin/scripts/:name/run with arguments", () => {
175
+ const createArgScript = () => ({
176
+ args: [
177
+ {default: "all", description: "Which model", name: "model", type: "string" as const},
178
+ {description: "Limit", name: "limit", required: true, type: "number" as const},
179
+ ],
180
+ description: "Echoes its arguments",
181
+ name: "argScript",
182
+ runner: async (
183
+ _wetRun: boolean,
184
+ ctx?: {
185
+ args: {
186
+ getString: (n: string, f?: string) => string | undefined;
187
+ getNumber: (n: string) => number | undefined;
188
+ };
189
+ }
190
+ ) => ({
191
+ results: [`model=${ctx?.args.getString("model")}`, `limit=${ctx?.args.getNumber("limit")}`],
192
+ success: true,
193
+ }),
194
+ });
195
+
196
+ beforeEach(async () => {
197
+ await setupDb();
198
+ app = buildApp([createArgScript()]);
199
+ adminAgent = await authAsUser(app, "admin");
200
+ });
201
+
202
+ it("passes JSON body args to the runner", async () => {
203
+ const res = await adminAgent
204
+ .post("/admin/scripts/argScript/run")
205
+ .send({args: {limit: 5, model: "todos"}})
206
+ .expect(201);
207
+
208
+ await new Promise((resolve) => setTimeout(resolve, 100));
209
+ const task = await BackgroundTask.findById(res.body.taskId);
210
+ expect(task?.status).toBe("completed");
211
+ expect(task?.result).toContain("model=todos");
212
+ expect(task?.result).toContain("limit=5");
213
+ });
214
+
215
+ it("passes query params as args", async () => {
216
+ const res = await adminAgent
217
+ .post("/admin/scripts/argScript/run?model=users&limit=9")
218
+ .expect(201);
219
+
220
+ await new Promise((resolve) => setTimeout(resolve, 100));
221
+ const task = await BackgroundTask.findById(res.body.taskId);
222
+ expect(task?.result).toContain("model=users");
223
+ expect(task?.result).toContain("limit=9");
224
+ });
225
+
226
+ it("applies declared defaults when an arg is omitted", async () => {
227
+ const res = await adminAgent
228
+ .post("/admin/scripts/argScript/run")
229
+ .send({args: {limit: 1}})
230
+ .expect(201);
231
+
232
+ await new Promise((resolve) => setTimeout(resolve, 100));
233
+ const task = await BackgroundTask.findById(res.body.taskId);
234
+ expect(task?.result).toContain("model=all");
235
+ });
236
+
237
+ it("returns 400 when a required arg is missing", async () => {
238
+ const res = await adminAgent.post("/admin/scripts/argScript/run").expect(400);
239
+ expect(res.body.title).toInclude("Invalid arguments for script: argScript");
240
+ expect(res.body.detail).toInclude("Missing required argument: --limit");
241
+ });
242
+
243
+ it("returns 400 when an arg fails type coercion", async () => {
244
+ const res = await adminAgent
245
+ .post("/admin/scripts/argScript/run")
246
+ .send({args: {limit: "not-a-number"}})
247
+ .expect(400);
248
+ expect(res.body.detail).toInclude("expected a number");
249
+ });
250
+
251
+ it("strips reserved runner flags from ctx.args over HTTP", async () => {
252
+ const echoScript = {
253
+ description: "Echoes arg keys",
254
+ name: "echoArgs",
255
+ runner: async (_wetRun: boolean, ctx?: {args: {raw: Record<string, unknown>}}) => ({
256
+ results: [
257
+ Object.keys(ctx?.args.raw ?? {})
258
+ .sort()
259
+ .join(","),
260
+ ],
261
+ success: true,
262
+ }),
263
+ };
264
+ app = buildApp([echoScript]);
265
+ const agent = await authAsUser(app, "admin");
266
+ const res = await agent
267
+ .post("/admin/scripts/echoArgs/run?wetRun=true&json=true&keep=yes")
268
+ .expect(201);
269
+
270
+ await new Promise((resolve) => setTimeout(resolve, 100));
271
+ const task = await BackgroundTask.findById(res.body.taskId);
272
+ expect(task?.result?.[0]).toBe("keep");
273
+ });
274
+ });
275
+
174
276
  describe("GET /admin/scripts/tasks/:id", () => {
175
277
  let taskId: string;
176
278
 
@@ -402,6 +504,23 @@ describe("AdminApp script routes", () => {
402
504
  expect(res.body.scripts[0].description).toBe("Migrate old data");
403
505
  expect(res.body.scripts[1].name).toBe("cleanup");
404
506
  expect(res.body.scripts[1].description).toBe("Clean up orphans");
507
+ expect(res.body.scripts[0].args).toEqual([]);
508
+ });
509
+
510
+ it("exposes declared script args in the config response", async () => {
511
+ app = buildApp([
512
+ {
513
+ args: [{description: "Which model", name: "model", type: "string"}],
514
+ description: "Echoes args",
515
+ name: "argScript",
516
+ runner: async () => ({results: [], success: true}),
517
+ },
518
+ ]);
519
+ const freshAdmin = await authAsUser(app, "admin");
520
+ const res = await freshAdmin.get("/admin/config").expect(200);
521
+
522
+ expect(res.body.scripts[0].args).toHaveLength(1);
523
+ expect(res.body.scripts[0].args[0].name).toBe("model");
405
524
  });
406
525
 
407
526
  it("returns empty scripts array when no scripts configured", async () => {
package/src/adminApp.ts CHANGED
@@ -6,13 +6,17 @@ import {
6
6
  type BackgroundTaskDocument,
7
7
  checkPermissions,
8
8
  createOpenApiBuilder,
9
+ createScriptArgs,
9
10
  getOpenApiSpecForModel,
10
11
  type JSONValue,
11
12
  logger,
12
13
  type ModelRouterOptions,
13
14
  modelRouter,
15
+ type PopulatePath,
14
16
  type OpenApiMiddleware,
15
17
  Permissions,
18
+ type ScriptArgDef,
19
+ type ScriptArgValue,
16
20
  type ScriptContext,
17
21
  type ScriptResult,
18
22
  type ScriptRunner,
@@ -38,6 +42,7 @@ import {
38
42
  normalizeAdminHome,
39
43
  SYSTEM_ADMIN_FIELDS,
40
44
  } from "./adminUiV2";
45
+ import {RESERVED_SCRIPT_FLAGS} from "./scriptCli";
41
46
 
42
47
  /**
43
48
  * Configuration for a single model in the admin panel.
@@ -87,6 +92,8 @@ export interface AdminModelConfig {
87
92
  permissions?: AdminModelPermissionsInput;
88
93
  /** Suggested page size for the changelist */
89
94
  pageSize?: number;
95
+ /** Mongoose populate paths for list/read responses (e.g. populated refs on consent responses). */
96
+ populatePaths?: PopulatePath[];
90
97
  /** UI-only hint that live updates may be available */
91
98
  realtime?: boolean;
92
99
  /**
@@ -117,6 +124,12 @@ export interface AdminScriptConfig {
117
124
  name: string;
118
125
  /** Human-readable description shown in the admin UI */
119
126
  description: string;
127
+ /**
128
+ * Optional declarations for the arguments this script accepts. Drives CLI help,
129
+ * type coercion, defaults, and validation. Scripts may still read undeclared
130
+ * arguments via `ctx.args`.
131
+ */
132
+ args?: ScriptArgDef[];
120
133
  /** The function that executes the script. Must return string[] results. */
121
134
  runner: ScriptRunner;
122
135
  }
@@ -213,6 +226,7 @@ interface AdminModelMeta {
213
226
  interface AdminScriptMeta {
214
227
  name: string;
215
228
  description: string;
229
+ args: ScriptArgDef[];
216
230
  }
217
231
 
218
232
  interface AdminConfigResponse {
@@ -568,6 +582,7 @@ export class AdminApp {
568
582
  // Build script metadata for config response
569
583
  const scriptConfigs = this.options.scripts ?? [];
570
584
  const configScripts: AdminScriptMeta[] = scriptConfigs.map((script) => ({
585
+ args: script.args ?? [],
571
586
  description: script.description,
572
587
  name: script.name,
573
588
  }));
@@ -605,6 +620,7 @@ export class AdminApp {
605
620
  scripts: {
606
621
  items: {
607
622
  properties: {
623
+ args: {type: "array"},
608
624
  description: {type: "string"},
609
625
  name: {type: "string"},
610
626
  },
@@ -1004,6 +1020,7 @@ export class AdminApp {
1004
1020
  removeHiddenFields(value, hiddenFieldSet) as JSONValue
1005
1021
  : undefined,
1006
1022
  sort: config.defaultSort ?? "-created",
1023
+ ...(config.populatePaths ? {populatePaths: config.populatePaths} : {}),
1007
1024
  ...auditHooks,
1008
1025
  };
1009
1026
 
@@ -1169,6 +1186,45 @@ export class AdminApp {
1169
1186
  }
1170
1187
 
1171
1188
  const isWetRun = req.query.wetRun === "true";
1189
+
1190
+ // Collect flexible arguments from the request. Query params and a JSON body
1191
+ // are both accepted; an explicit `args` object in the body takes precedence.
1192
+ // Reserved runner flags (wetRun, wet, dry, json, ...) are stripped so scripts
1193
+ // read args identically over HTTP and via the CLI.
1194
+ const argValues: Record<string, ScriptArgValue> = {};
1195
+ for (const [key, value] of Object.entries(req.query)) {
1196
+ if (RESERVED_SCRIPT_FLAGS.includes(key) || value === undefined) {
1197
+ continue;
1198
+ }
1199
+ argValues[key] = value as ScriptArgValue;
1200
+ }
1201
+ const rawBody =
1202
+ req.body && typeof req.body === "object" && !Array.isArray(req.body)
1203
+ ? (req.body as Record<string, unknown>)
1204
+ : {};
1205
+ const bodyValues =
1206
+ rawBody.args && typeof rawBody.args === "object" && !Array.isArray(rawBody.args)
1207
+ ? (rawBody.args as Record<string, ScriptArgValue>)
1208
+ : (rawBody as Record<string, ScriptArgValue>);
1209
+ for (const [key, value] of Object.entries(bodyValues)) {
1210
+ if (RESERVED_SCRIPT_FLAGS.includes(key)) {
1211
+ continue;
1212
+ }
1213
+ argValues[key] = value;
1214
+ }
1215
+
1216
+ const {args, errors: argErrors} = createScriptArgs({
1217
+ defs: script.args ?? [],
1218
+ values: argValues,
1219
+ });
1220
+ if (argErrors.length > 0) {
1221
+ throw new APIError({
1222
+ detail: argErrors.join("; "),
1223
+ status: 400,
1224
+ title: `Invalid arguments for script: ${script.name}`,
1225
+ });
1226
+ }
1227
+
1172
1228
  const now = DateTime.now().toJSDate();
1173
1229
 
1174
1230
  let task: BackgroundTaskDocument;
@@ -1194,7 +1250,7 @@ export class AdminApp {
1194
1250
  });
1195
1251
  }
1196
1252
 
1197
- // Build context for cancellation and progress reporting
1253
+ // Build context for cancellation, progress reporting, and arguments
1198
1254
  const ctx: ScriptContext = {
1199
1255
  addLog: async (level, message) => {
1200
1256
  const current = await BackgroundTask.findById(task._id);
@@ -1202,6 +1258,7 @@ export class AdminApp {
1202
1258
  await current.addLog(level, message);
1203
1259
  }
1204
1260
  },
1261
+ args,
1205
1262
  checkCancellation: async () => {
1206
1263
  await BackgroundTask.checkCancellation(task._id.toString());
1207
1264
  },
package/src/index.ts CHANGED
@@ -14,3 +14,5 @@ export type {
14
14
  DocumentStorageOptions,
15
15
  } from "./documentStorageApp";
16
16
  export {DocumentStorageApp} from "./documentStorageApp";
17
+ export type {RunScriptCliOptions, RunScriptCliResult} from "./scriptCli";
18
+ export {runScriptCli} from "./scriptCli";
@@ -0,0 +1,246 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import type {ScriptContext} from "@terreno/api";
3
+
4
+ import type {AdminScriptConfig} from "./adminApp";
5
+ import {runScriptCli} from "./scriptCli";
6
+
7
+ const countScript: AdminScriptConfig = {
8
+ args: [{default: "all", description: "Which collection to count", name: "model", type: "string"}],
9
+ description: "Count records",
10
+ name: "countRecords",
11
+ runner: async (wetRun, ctx) => {
12
+ const model = ctx?.args.getString("model", "all") ?? "all";
13
+ return {results: [`mode=${wetRun ? "wet" : "dry"}`, `model=${model}`], success: true};
14
+ },
15
+ };
16
+
17
+ const requiredArgScript: AdminScriptConfig = {
18
+ args: [{description: "Email to target", name: "email", required: true}],
19
+ description: "Needs an email",
20
+ name: "needsEmail",
21
+ runner: async (_wetRun, ctx) => ({
22
+ results: [`email=${ctx?.args.getString("email") ?? ""}`],
23
+ success: true,
24
+ }),
25
+ };
26
+
27
+ const failingScript: AdminScriptConfig = {
28
+ description: "Always throws",
29
+ name: "boom",
30
+ runner: async () => {
31
+ throw new Error("kaboom");
32
+ },
33
+ };
34
+
35
+ const unsuccessfulScript: AdminScriptConfig = {
36
+ description: "Reports failure",
37
+ name: "sad",
38
+ runner: async () => ({results: ["nope"], success: false}),
39
+ };
40
+
41
+ const loggingScript: AdminScriptConfig = {
42
+ description: "Logs via context",
43
+ name: "logger",
44
+ runner: async (_wetRun, ctx?: ScriptContext) => {
45
+ await ctx?.checkCancellation();
46
+ await ctx?.addLog("info", "hello");
47
+ await ctx?.updateProgress(50, "halfway", "still going");
48
+ return {results: ["logged"], success: true};
49
+ },
50
+ };
51
+
52
+ const richArgsScript: AdminScriptConfig = {
53
+ args: [
54
+ {
55
+ aliases: ["m"],
56
+ default: "all",
57
+ description: "Which model",
58
+ example: "todos",
59
+ name: "model",
60
+ type: "string",
61
+ },
62
+ ],
63
+ description: "Has a rich arg",
64
+ name: "rich",
65
+ runner: async (_wetRun, ctx) => ({
66
+ results: [`model=${ctx?.args.getString("model")}`],
67
+ success: true,
68
+ }),
69
+ };
70
+
71
+ const allScripts = [
72
+ countScript,
73
+ requiredArgScript,
74
+ failingScript,
75
+ unsuccessfulScript,
76
+ loggingScript,
77
+ richArgsScript,
78
+ ];
79
+
80
+ /** Runs the CLI capturing output, never exiting the process. */
81
+ const run = async (argv: string[], scripts = allScripts) => {
82
+ const lines: string[] = [];
83
+ const result = await runScriptCli({
84
+ argv,
85
+ exit: false,
86
+ scripts,
87
+ write: (line) => lines.push(line),
88
+ });
89
+ return {lines, output: lines.join("\n"), result};
90
+ };
91
+
92
+ describe("runScriptCli", () => {
93
+ it("prints general help and lists scripts when no script is given", async () => {
94
+ const {output, result} = await run([]);
95
+ expect(result.exitCode).toBe(0);
96
+ expect(output).toInclude("Available scripts:");
97
+ expect(output).toInclude("countRecords");
98
+ });
99
+
100
+ it("lists scripts with --list", async () => {
101
+ const {output, result} = await run(["--list"]);
102
+ expect(result.exitCode).toBe(0);
103
+ expect(output).toInclude("countRecords");
104
+ });
105
+
106
+ it("prints general help with --help and no script", async () => {
107
+ const {output, result} = await run(["--help"]);
108
+ expect(result.exitCode).toBe(0);
109
+ expect(output).toInclude("Available scripts:");
110
+ });
111
+
112
+ it("shows aliases and examples in per-script help", async () => {
113
+ const {output, result} = await run(["rich", "--help"]);
114
+ expect(result.exitCode).toBe(0);
115
+ expect(output).toInclude("(-m)");
116
+ expect(output).toInclude("(e.g. todos)");
117
+ expect(output).toInclude("(default: all)");
118
+ });
119
+
120
+ it("notes when no scripts are registered", async () => {
121
+ const {output} = await run(["--list"], []);
122
+ expect(output).toInclude("No scripts are registered.");
123
+ });
124
+
125
+ it("returns an error for an unknown script", async () => {
126
+ const {output, result} = await run(["doesNotExist"]);
127
+ expect(result.exitCode).toBe(1);
128
+ expect(result.success).toBe(false);
129
+ expect(output).toInclude("Unknown script: doesNotExist");
130
+ });
131
+
132
+ it("prints per-script help including declared args", async () => {
133
+ const {output, result} = await run(["countRecords", "--help"]);
134
+ expect(result.exitCode).toBe(0);
135
+ expect(output).toInclude("--model");
136
+ expect(output).toInclude("Which collection to count");
137
+ });
138
+
139
+ it("runs as a dry run by default", async () => {
140
+ const {result} = await run(["countRecords"]);
141
+ expect(result.success).toBe(true);
142
+ expect(result.wetRun).toBe(false);
143
+ expect(result.results).toContain("mode=dry");
144
+ expect(result.results).toContain("model=all");
145
+ });
146
+
147
+ it("runs in wet mode with --wet", async () => {
148
+ const {result} = await run(["countRecords", "--wet"]);
149
+ expect(result.wetRun).toBe(true);
150
+ expect(result.results).toContain("mode=wet");
151
+ });
152
+
153
+ it("lets --dry override --wet", async () => {
154
+ const {result} = await run(["countRecords", "--wet", "--dry"]);
155
+ expect(result.wetRun).toBe(false);
156
+ expect(result.results).toContain("mode=dry");
157
+ });
158
+
159
+ it("forwards declared args to the runner", async () => {
160
+ const {result} = await run(["countRecords", "--model", "todos"]);
161
+ expect(result.results).toContain("model=todos");
162
+ });
163
+
164
+ it("does not leak reserved flags into script args", async () => {
165
+ const seen: Record<string, unknown> = {};
166
+ const spyScript: AdminScriptConfig = {
167
+ description: "spy",
168
+ name: "spy",
169
+ runner: async (_wetRun, ctx) => {
170
+ Object.assign(seen, ctx?.args.raw);
171
+ return {results: ["ok"], success: true};
172
+ },
173
+ };
174
+ await run(["spy", "--wet", "--json", "--keep=yes"], [spyScript]);
175
+ expect(seen.wet).toBeUndefined();
176
+ expect(seen.json).toBeUndefined();
177
+ expect(seen.keep).toBe("yes");
178
+ });
179
+
180
+ it("errors when a declared value flag is missing its value", async () => {
181
+ const {output, result} = await run(["countRecords", "--model"]);
182
+ expect(result.exitCode).toBe(1);
183
+ expect(result.success).toBe(false);
184
+ expect(output).toInclude("--model expects a string value");
185
+ });
186
+
187
+ it("fails when a required argument is missing", async () => {
188
+ const {output, result} = await run(["needsEmail"]);
189
+ expect(result.exitCode).toBe(1);
190
+ expect(result.success).toBe(false);
191
+ expect(output).toInclude("Missing required argument: --email");
192
+ expect(output).toInclude("Usage:");
193
+ });
194
+
195
+ it("accepts a provided required argument", async () => {
196
+ const {result} = await run(["needsEmail", "--email", "a@b.com"]);
197
+ expect(result.success).toBe(true);
198
+ expect(result.results).toContain("email=a@b.com");
199
+ });
200
+
201
+ it("returns a non-zero exit when the script throws", async () => {
202
+ const {output, result} = await run(["boom"]);
203
+ expect(result.exitCode).toBe(1);
204
+ expect(result.errors).toContain("kaboom");
205
+ expect(output).toInclude("Error: kaboom");
206
+ });
207
+
208
+ it("returns a non-zero exit when the script reports failure", async () => {
209
+ const {output, result} = await run(["sad"]);
210
+ expect(result.exitCode).toBe(1);
211
+ expect(result.success).toBe(false);
212
+ expect(output).toInclude("Script reported failure.");
213
+ });
214
+
215
+ it("emits a JSON line in --json mode", async () => {
216
+ const {lines, result} = await run(["countRecords", "--json", "--model", "users"]);
217
+ expect(result.success).toBe(true);
218
+ const jsonLine = lines.find((line) => line.startsWith("{"));
219
+ expect(jsonLine).toBeDefined();
220
+ const parsed = JSON.parse(jsonLine as string);
221
+ expect(parsed.script).toBe("countRecords");
222
+ expect(parsed.results).toContain("model=users");
223
+ });
224
+
225
+ it("emits JSON on error in --json mode", async () => {
226
+ const {lines, result} = await run(["boom", "--json"]);
227
+ expect(result.exitCode).toBe(1);
228
+ const jsonLine = lines.find((line) => line.startsWith("{"));
229
+ const parsed = JSON.parse(jsonLine as string);
230
+ expect(parsed.success).toBe(false);
231
+ expect(parsed.error).toBe("kaboom");
232
+ });
233
+
234
+ it("routes context logs and progress to output (non-json)", async () => {
235
+ const {output} = await run(["logger"]);
236
+ expect(output).toInclude("[info] hello");
237
+ expect(output).toInclude("[progress] 50%");
238
+ expect(output).toInclude("halfway");
239
+ });
240
+
241
+ it("suppresses context logs in --json mode", async () => {
242
+ const {output} = await run(["logger", "--json"]);
243
+ expect(output).not.toInclude("[info] hello");
244
+ expect(output).not.toInclude("[progress]");
245
+ });
246
+ });