@terreno/admin-backend 57.2.0 → 57.4.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.
Files changed (53) hide show
  1. package/.ai/guidelines/core.md +12 -4
  2. package/.claude/CLAUDE.local.md +17 -2
  3. package/.cursor/rules/00-root.mdc +17 -2
  4. package/.github/copilot-instructions.md +17 -2
  5. package/AGENTS.md +17 -2
  6. package/README.md +3 -1
  7. package/bunfig.toml +9 -1
  8. package/dist/adminApp.d.ts +20 -2
  9. package/dist/adminApp.js +480 -474
  10. package/dist/adminConfigIdentity.d.ts +1 -0
  11. package/dist/adminConfigIdentity.js +1 -0
  12. package/dist/adminMigrations.d.ts +10 -0
  13. package/dist/adminMigrations.js +205 -0
  14. package/dist/adminScriptJob.d.ts +32 -0
  15. package/dist/adminScriptJob.js +360 -0
  16. package/dist/adminTextSearch.d.ts +1 -0
  17. package/dist/adminTextSearch.js +1 -0
  18. package/dist/adminUiV2.d.ts +2 -0
  19. package/dist/aggregateAdmin.js +6 -1
  20. package/dist/documentStorageApp.js +1 -4
  21. package/dist/enrichAdminListFilters.d.ts +7 -0
  22. package/dist/enrichAdminListFilters.js +37 -0
  23. package/dist/filterParser.js +139 -12
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +4 -1
  26. package/dist/legacy.js +4 -2
  27. package/dist/resolvedAdminModel.js +2 -1
  28. package/package.json +8 -8
  29. package/src/adminApp.migrations.test.ts +232 -0
  30. package/src/adminApp.models.test.ts +647 -5
  31. package/src/adminApp.syncMeta.test.ts +237 -0
  32. package/src/adminApp.test.ts +92 -0
  33. package/src/adminApp.ts +354 -240
  34. package/src/adminConfigIdentity.ts +1 -0
  35. package/src/adminHttpGoldens.test.ts +337 -0
  36. package/src/adminMigrations.ts +157 -0
  37. package/src/adminScriptJob.test.ts +297 -0
  38. package/src/adminScriptJob.ts +271 -0
  39. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  40. package/src/adminTextSearch.test.ts +28 -0
  41. package/src/adminTextSearch.ts +1 -0
  42. package/src/adminUiV2.test.ts +71 -1
  43. package/src/adminUiV2.ts +2 -0
  44. package/src/aggregateAdmin.test.ts +125 -0
  45. package/src/aggregateAdmin.ts +7 -4
  46. package/src/documentStorageApp.ts +1 -3
  47. package/src/enrichAdminListFilters.test.ts +44 -0
  48. package/src/enrichAdminListFilters.ts +29 -0
  49. package/src/filterParser.test.ts +95 -0
  50. package/src/filterParser.ts +156 -10
  51. package/src/index.ts +2 -0
  52. package/src/legacy.ts +5 -1
  53. package/src/resolvedAdminModel.ts +2 -1
@@ -53,6 +53,8 @@ var contributionScriptToConfig = function (script) { return ({
53
53
  var contributionScreenToConfig = function (screen) { return ({
54
54
  adminAccess: screen.adminAccess,
55
55
  displayName: screen.displayName,
56
+ group: screen.group,
57
+ icon: screen.icon,
56
58
  name: screen.name,
57
59
  }); };
58
60
  var mergeUniqueByName = function (existing, incoming) {
@@ -181,7 +183,10 @@ var aggregateAdminContributions = function (_a) {
181
183
  var path = registered.routePath;
182
184
  var existingRegistered = registeredByPath.get(path);
183
185
  if (existingRegistered) {
184
- throw new Error("Duplicate admin modelRouter routePath \"".concat(path, "\" (").concat(existingRegistered.sourceLabel, " and ").concat(registered.sourceLabel, ")"));
186
+ throw new api_1.APIError({
187
+ status: 500,
188
+ title: "Duplicate admin modelRouter routePath \"".concat(path, "\" (").concat(existingRegistered.sourceLabel, " and ").concat(registered.sourceLabel, ")"),
189
+ });
185
190
  }
186
191
  registeredByPath.set(path, registered);
187
192
  var existing = modelsByPath.get(path);
@@ -223,10 +223,7 @@ var DocumentStorageApp = /** @class */ (function () {
223
223
  });
224
224
  }); })], false));
225
225
  // POST basePath/ — Upload a file
226
- app.post.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/")], __read(adminGuard), false), [
227
- // noExplicitAny: multer's RequestHandler type is incompatible with Express 5's middleware signature.
228
- // biome-ignore lint/suspicious/noExplicitAny: multer's RequestHandler type is incompatible with Express 5's middleware signature.
229
- upload.single("file"),
226
+ app.post.apply(app, __spreadArray(__spreadArray(["".concat(basePath, "/")], __read(adminGuard), false), [upload.single("file"),
230
227
  (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
231
228
  var file, targetPrefix, sanitizedFilename, gcsPath, gcsFile, documentFile;
232
229
  var _a;
@@ -0,0 +1,7 @@
1
+ import type { Model } from "mongoose";
2
+ import type { AdminListFilter } from "./adminUiV2";
3
+ /**
4
+ * Derives `allowEmpty` for optional choice filters from the Mongoose schema when not
5
+ * set explicitly on admin config.
6
+ */
7
+ export declare const enrichAdminListFilters: (filters: AdminListFilter[] | undefined, model: Model<unknown>) => AdminListFilter[] | undefined;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.enrichAdminListFilters = void 0;
15
+ /**
16
+ * Derives `allowEmpty` for optional choice filters from the Mongoose schema when not
17
+ * set explicitly on admin config.
18
+ */
19
+ var enrichAdminListFilters = function (filters, model) {
20
+ if (!filters) {
21
+ return filters;
22
+ }
23
+ return filters.map(function (filter) {
24
+ if (filter.kind !== "choice") {
25
+ return filter;
26
+ }
27
+ if (filter.allowEmpty !== undefined) {
28
+ return filter;
29
+ }
30
+ var path = model.schema.path(filter.field);
31
+ if (!path || path.isRequired) {
32
+ return filter;
33
+ }
34
+ return __assign(__assign({}, filter), { allowEmpty: true });
35
+ });
36
+ };
37
+ exports.enrichAdminListFilters = enrichAdminListFilters;
@@ -44,6 +44,22 @@ var api_1 = require("@terreno/api");
44
44
  var luxon_1 = require("luxon");
45
45
  var mongoose_1 = __importDefault(require("mongoose"));
46
46
  var POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
47
+ var REGEX_META_CHARACTERS = new Set([
48
+ "\\",
49
+ ".",
50
+ "*",
51
+ "+",
52
+ "?",
53
+ "^",
54
+ "$",
55
+ "{",
56
+ "}",
57
+ "(",
58
+ ")",
59
+ "|",
60
+ "[",
61
+ "]",
62
+ ]);
47
63
  var isOperatorKey = function (key) {
48
64
  return key.startsWith("$");
49
65
  };
@@ -78,6 +94,27 @@ var scalarString = function (value) {
78
94
  }
79
95
  return undefined;
80
96
  };
97
+ var hasOnlyKeys = function (record, allowedKeys) {
98
+ var allowed = new Set(allowedKeys);
99
+ return Object.keys(record).every(function (key) { return allowed.has(key); });
100
+ };
101
+ var isEscapedRegexLiteral = function (value) {
102
+ for (var index = 0; index < value.length; index += 1) {
103
+ var character = value[index];
104
+ if (character === "\\") {
105
+ var escapedCharacter = value[index + 1];
106
+ if (!escapedCharacter || !REGEX_META_CHARACTERS.has(escapedCharacter)) {
107
+ return false;
108
+ }
109
+ index += 1;
110
+ continue;
111
+ }
112
+ if (REGEX_META_CHARACTERS.has(character)) {
113
+ return false;
114
+ }
115
+ }
116
+ return true;
117
+ };
81
118
  var parseBooleanFilter = function (field, value) {
82
119
  var scalar = scalarString(value);
83
120
  if (scalar === "true") {
@@ -97,16 +134,94 @@ var parseTextFilter = function (field, value) {
97
134
  }
98
135
  return { ok: true, value: scalar };
99
136
  };
100
- var parseChoiceFilter = function (field, value, choices) {
137
+ var parseTextRegexFilter = function (field, value) {
138
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
139
+ return { error: "".concat(field, " must be a case-insensitive regex filter"), ok: false };
140
+ }
141
+ var record = value;
142
+ if (!hasOnlyKeys(record, ["$options", "$regex"])) {
143
+ return { error: "".concat(field, " contains an unsupported regex operator"), ok: false };
144
+ }
145
+ if (record.$options !== "i") {
146
+ return { error: "".concat(field, " must use $options \"i\""), ok: false };
147
+ }
148
+ var regex = scalarString(record.$regex);
149
+ if (!regex || !isEscapedRegexLiteral(regex)) {
150
+ return { error: "".concat(field, " must include an escaped literal $regex pattern"), ok: false };
151
+ }
152
+ return { ok: true, value: { $options: "i", $regex: regex } };
153
+ };
154
+ var normalizeChoiceMongoValue = function (values) {
155
+ if (values.length === 1) {
156
+ return values[0];
157
+ }
158
+ return { $in: values };
159
+ };
160
+ var parseChoiceWireValue = function (field, wireValue, choices, allowEmpty) {
161
+ if (wireValue === api_1.ADMIN_LIST_CHOICE_EMPTY_VALUE) {
162
+ if (!allowEmpty) {
163
+ return {
164
+ error: "".concat(field, " must be one of: ").concat(choices.map(function (choice) { return choice.value; }).join(", ")),
165
+ ok: false,
166
+ };
167
+ }
168
+ return { ok: true, value: null };
169
+ }
170
+ var allowed = new Set(choices.map(function (choice) { return choice.value; }));
171
+ if (!allowed.has(wireValue)) {
172
+ return { error: "".concat(field, " must be one of: ").concat(__spreadArray([], __read(allowed), false).join(", ")), ok: false };
173
+ }
174
+ return { ok: true, value: wireValue };
175
+ };
176
+ var parseChoiceFilter = function (field, value, declared) {
101
177
  var parsed = parseTextFilter(field, value);
102
178
  if (!parsed.ok) {
103
179
  return parsed;
104
180
  }
105
- var allowed = new Set(choices.map(function (choice) { return choice.value; }));
106
- if (!allowed.has(parsed.value)) {
107
- return { error: "".concat(field, " must be one of: ").concat(__spreadArray([], __read(allowed), false).join(", ")), ok: false };
181
+ var wire = parseChoiceWireValue(field, parsed.value, declared.choices, declared.allowEmpty === true);
182
+ if (!wire.ok) {
183
+ return wire;
108
184
  }
109
- return parsed;
185
+ return { ok: true, value: wire.value };
186
+ };
187
+ var parseChoiceInFilter = function (field, value, declared) {
188
+ var e_2, _a;
189
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
190
+ return { error: "".concat(field, " must be a multi-value choice filter"), ok: false };
191
+ }
192
+ var record = value;
193
+ if (!hasOnlyKeys(record, ["$in"])) {
194
+ return { error: "".concat(field, " contains an unsupported choice operator"), ok: false };
195
+ }
196
+ if (!Array.isArray(record.$in)) {
197
+ return { error: "".concat(field, " must use $in with string values"), ok: false };
198
+ }
199
+ var mongoValues = [];
200
+ try {
201
+ for (var _b = __values(record.$in), _c = _b.next(); !_c.done; _c = _b.next()) {
202
+ var entry = _c.value;
203
+ var scalar = scalarString(entry);
204
+ if (!scalar) {
205
+ return { error: "".concat(field, " must use $in with string values"), ok: false };
206
+ }
207
+ var wire = parseChoiceWireValue(field, scalar, declared.choices, declared.allowEmpty === true);
208
+ if (!wire.ok) {
209
+ return wire;
210
+ }
211
+ mongoValues.push(wire.value);
212
+ }
213
+ }
214
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
215
+ finally {
216
+ try {
217
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
218
+ }
219
+ finally { if (e_2) throw e_2.error; }
220
+ }
221
+ if (mongoValues.length === 0) {
222
+ return { error: "".concat(field, " must include at least one choice"), ok: false };
223
+ }
224
+ return { ok: true, value: normalizeChoiceMongoValue(mongoValues) };
110
225
  };
111
226
  var parseRefFilter = function (field, value) {
112
227
  var parsed = parseTextFilter(field, value);
@@ -136,7 +251,7 @@ var parseIsoDate = function (field, value) {
136
251
  * Undeclared keys are ignored; Mongo operator keys are rejected.
137
252
  */
138
253
  var parseAdminListFilters = function (query, filters) {
139
- var e_2, _a, e_3, _b;
254
+ var e_3, _a, e_4, _b;
140
255
  if (filters === void 0) { filters = []; }
141
256
  var safeQuery = dropPollutionKeys(query);
142
257
  var errors = {};
@@ -164,7 +279,13 @@ var parseAdminListFilters = function (query, filters) {
164
279
  continue;
165
280
  }
166
281
  consumedKeys.add(field);
167
- var parsed = parseTextFilter(field, safeQuery[field]);
282
+ var raw = safeQuery[field];
283
+ var regexParsed = parseTextRegexFilter(field, raw);
284
+ if (regexParsed.ok) {
285
+ filter[field] = regexParsed.value;
286
+ continue;
287
+ }
288
+ var parsed = parseTextFilter(field, raw);
168
289
  if (!parsed.ok) {
169
290
  errors[field] = parsed.error;
170
291
  continue;
@@ -177,7 +298,13 @@ var parseAdminListFilters = function (query, filters) {
177
298
  continue;
178
299
  }
179
300
  consumedKeys.add(field);
180
- var parsed = parseChoiceFilter(field, safeQuery[field], declared.choices);
301
+ var raw = safeQuery[field];
302
+ var inParsed = parseChoiceInFilter(field, raw, declared);
303
+ if (inParsed.ok) {
304
+ filter[field] = inParsed.value;
305
+ continue;
306
+ }
307
+ var parsed = parseChoiceFilter(field, raw, declared);
181
308
  if (!parsed.ok) {
182
309
  errors[field] = parsed.error;
183
310
  continue;
@@ -233,12 +360,12 @@ var parseAdminListFilters = function (query, filters) {
233
360
  }
234
361
  }
235
362
  }
236
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
363
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
237
364
  finally {
238
365
  try {
239
366
  if (filters_1_1 && !filters_1_1.done && (_a = filters_1.return)) _a.call(filters_1);
240
367
  }
241
- finally { if (e_2) throw e_2.error; }
368
+ finally { if (e_3) throw e_3.error; }
242
369
  }
243
370
  try {
244
371
  for (var _c = __values(Object.keys(safeQuery)), _d = _c.next(); !_d.done; _d = _c.next()) {
@@ -248,12 +375,12 @@ var parseAdminListFilters = function (query, filters) {
248
375
  }
249
376
  }
250
377
  }
251
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
378
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
252
379
  finally {
253
380
  try {
254
381
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
255
382
  }
256
- finally { if (e_3) throw e_3.error; }
383
+ finally { if (e_4) throw e_4.error; }
257
384
  }
258
385
  return { consumedKeys: consumedKeys, errors: errors, filter: filter };
259
386
  };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export type { AdminChangeEvent, AdminChangeType, AdminConfig, AdminContribution, AdminCustomScreen, AdminFieldset, AdminFilter, AdminFilterBoolean, AdminFilterChoice, AdminFilterDateRange, AdminFilterKind, AdminFilterRef, AdminFilterText, AdminHomeConfig, AdminHomeSlots, AdminHomeWidgetContribution, AdminModelContribution, AdminModelPermissions, AdminScriptContribution, TerrenoAppAdminEvent, } from "@terreno/api";
2
2
  export type { AdminAuditEvent, AdminCustomScreenConfig, AdminFieldOverride, AdminModelConfig, AdminOptions, AdminScriptConfig, } from "./adminApp";
3
3
  export { AdminApp, adminOwnedBy } from "./adminApp";
4
+ export type { AdminScriptJobPayload, AdminScriptJobTarget } from "./adminScriptJob";
5
+ export { ADMIN_SCRIPT_JOB_NAME, defineAdminScriptJob } from "./adminScriptJob";
4
6
  export * from "./adminUiV2";
5
7
  export type { AggregatedAdminContributions } from "./aggregateAdmin";
6
8
  export { aggregateAdminContributions, aggregateFromTerrenoApp, collectPluginAdminContributions, collectRegisteredAdminModels, } from "./aggregateAdmin";
package/dist/index.js CHANGED
@@ -14,10 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.adminOwnedBy = exports.AdminApp = void 0;
17
+ exports.runScriptCli = exports.normalizeAdminRoutePath = exports.resolvedModelFromAdminConfig = exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = exports.parseAdminListFilters = exports.DocumentStorageApp = exports.collectRegisteredAdminModels = exports.collectPluginAdminContributions = exports.aggregateFromTerrenoApp = exports.aggregateAdminContributions = exports.defineAdminScriptJob = exports.ADMIN_SCRIPT_JOB_NAME = exports.adminOwnedBy = exports.AdminApp = void 0;
18
18
  var adminApp_1 = require("./adminApp");
19
19
  Object.defineProperty(exports, "AdminApp", { enumerable: true, get: function () { return adminApp_1.AdminApp; } });
20
20
  Object.defineProperty(exports, "adminOwnedBy", { enumerable: true, get: function () { return adminApp_1.adminOwnedBy; } });
21
+ var adminScriptJob_1 = require("./adminScriptJob");
22
+ Object.defineProperty(exports, "ADMIN_SCRIPT_JOB_NAME", { enumerable: true, get: function () { return adminScriptJob_1.ADMIN_SCRIPT_JOB_NAME; } });
23
+ Object.defineProperty(exports, "defineAdminScriptJob", { enumerable: true, get: function () { return adminScriptJob_1.defineAdminScriptJob; } });
21
24
  __exportStar(require("./adminUiV2"), exports);
22
25
  var aggregateAdmin_1 = require("./aggregateAdmin");
23
26
  Object.defineProperty(exports, "aggregateAdminContributions", { enumerable: true, get: function () { return aggregateAdmin_1.aggregateAdminContributions; } });
package/dist/legacy.js CHANGED
@@ -13,6 +13,7 @@ var __assign = (this && this.__assign) || function () {
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.resetLegacyDeprecationWarningsForTests = exports.convertLegacyModelConfig = void 0;
15
15
  var api_1 = require("@terreno/api");
16
+ var enrichAdminListFilters_1 = require("./enrichAdminListFilters");
16
17
  var routePath_1 = require("./routePath");
17
18
  var warnedLegacyKeys = new Set();
18
19
  var legacyWarningKey = function (config) {
@@ -28,6 +29,7 @@ var convertLegacyModelConfig = function (config) {
28
29
  warnedLegacyKeys.add(key);
29
30
  api_1.logger.warn("[admin] AdminApp.models entry \"".concat(config.displayName, "\" uses the legacy shape (model=").concat(config.model.modelName, ", routePath=").concat(config.routePath, "). Migrate to modelRouter({admin: {...}}) \u2014 see docs/how-to/admin-add-model.md"));
30
31
  }
32
+ var filters = (0, enrichAdminListFilters_1.enrichAdminListFilters)(config.filters, config.model);
31
33
  var admin = {
32
34
  actions: config.actions,
33
35
  autocompleteFields: undefined,
@@ -38,7 +40,7 @@ var convertLegacyModelConfig = function (config) {
38
40
  fieldOrder: config.fieldOrder,
39
41
  fieldOverrides: config.fieldOverrides,
40
42
  fieldsets: config.fieldsets,
41
- filters: config.filters,
43
+ filters: filters,
42
44
  group: config.group,
43
45
  hiddenFields: config.hiddenFields,
44
46
  listDisplay: config.listDisplay,
@@ -51,7 +53,7 @@ var convertLegacyModelConfig = function (config) {
51
53
  searchFields: config.searchFields,
52
54
  sortableFields: config.sortableFields,
53
55
  };
54
- return __assign(__assign({}, config), { admin: admin, routePath: (0, routePath_1.normalizeAdminRoutePath)(config.routePath), source: "legacy", sourceLabel: config.displayName });
56
+ return __assign(__assign({}, config), { admin: admin, filters: filters, routePath: (0, routePath_1.normalizeAdminRoutePath)(config.routePath), source: "legacy", sourceLabel: config.displayName });
55
57
  };
56
58
  exports.convertLegacyModelConfig = convertLegacyModelConfig;
57
59
  /** @internal Test helper — clears one-time legacy deprecation warnings. */
@@ -48,6 +48,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
50
  exports.resolvedModelFromAdminConfig = void 0;
51
+ var enrichAdminListFilters_1 = require("./enrichAdminListFilters");
51
52
  var routePath_1 = require("./routePath");
52
53
  var adminPermissionsToModelPermissions = function (permissions) {
53
54
  if (!permissions) {
@@ -105,7 +106,7 @@ var resolvedModelFromAdminConfig = function (_a) {
105
106
  fieldOrder: admin.fieldOrder,
106
107
  fieldOverrides: admin.fieldOverrides,
107
108
  fieldsets: admin.fieldsets,
108
- filters: admin.filters,
109
+ filters: (0, enrichAdminListFilters_1.enrichAdminListFilters)(admin.filters, model),
109
110
  group: admin.group,
110
111
  hiddenFields: admin.hiddenFields,
111
112
  icon: admin.icon,
package/package.json CHANGED
@@ -5,21 +5,21 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@google-cloud/storage": "^7.15.0",
8
- "@terreno/api": "57.2.0",
8
+ "@terreno/api": "57.4.0",
9
+ "@terreno/jobs": "57.4.0",
9
10
  "express": "^5.2.1",
10
11
  "luxon": "^3.7.2",
11
12
  "multer": "2.2.0"
12
13
  },
13
- "description": "Admin panel backend plugin for @terreno/api",
14
+ "description": "Admin panel backend plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
14
15
  "devDependencies": {
15
16
  "@biomejs/biome": "^2.3.6",
16
- "@terreno/test": "57.2.0",
17
+ "@terreno/test": "57.4.0",
17
18
  "@types/bun": "^1.4.0",
18
19
  "@types/express": "^5.0.6",
19
20
  "@types/luxon": "^3.7.1",
20
21
  "@types/multer": "^1.4.12",
21
22
  "@types/supertest": "^7.2.0",
22
- "passport-local-mongoose": "^9.0.1",
23
23
  "supertest": "^7.2.2",
24
24
  "typescript": "~6.0.3"
25
25
  },
@@ -31,11 +31,11 @@
31
31
  "terreno"
32
32
  ],
33
33
  "license": "MIT",
34
+ "main": "dist/index.js",
35
+ "name": "@terreno/admin-backend",
34
36
  "peerDependencies": {
35
37
  "mongoose": "^8.0.0 || ^9.0.0"
36
38
  },
37
- "main": "dist/index.js",
38
- "name": "@terreno/admin-backend",
39
39
  "publishConfig": {
40
40
  "access": "public"
41
41
  },
@@ -44,7 +44,7 @@
44
44
  "url": "git+ssh://git@github.com/FlourishHealth/terreno.git"
45
45
  },
46
46
  "scripts": {
47
- "compile": "bun tsc",
47
+ "compile": "node ../.github/scripts/compile-workspace-deps.js && bun tsc",
48
48
  "compile:watch": "bun tsc -w",
49
49
  "dev": "bun tsc -w",
50
50
  "lint": "biome check ./src",
@@ -55,5 +55,5 @@
55
55
  "test:coverage": "bun run ../scripts/check-coverage.ts"
56
56
  },
57
57
  "types": "dist/index.d.ts",
58
- "version": "57.2.0"
58
+ "version": "57.4.0"
59
59
  }
@@ -0,0 +1,232 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
+ import {mkdtemp, rm, writeFile} from "node:fs/promises";
3
+ import {tmpdir} from "node:os";
4
+ import {join} from "node:path";
5
+ import {
6
+ type AnyTerrenoAccess,
7
+ addAuthRoutes,
8
+ apiErrorMiddleware,
9
+ apiUnauthorizedMiddleware,
10
+ BackgroundTask,
11
+ createAccess,
12
+ MIGRATION_LOCK_ID,
13
+ MIGRATIONS_COLLECTION,
14
+ setupAuth,
15
+ terrenoStatements,
16
+ type UserModel as UserModelType,
17
+ } from "@terreno/api";
18
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
19
+ import type express from "express";
20
+ import mongoose from "mongoose";
21
+ import type TestAgent from "supertest/lib/agent";
22
+
23
+ import {AdminApp} from "./adminApp";
24
+
25
+ const fixturesDir = join(import.meta.dir, "../../api/src/migrations/fixtures/valid");
26
+
27
+ const buildApp = ({
28
+ accessControl,
29
+ migrationsDir,
30
+ }: {
31
+ accessControl?: AnyTerrenoAccess;
32
+ migrationsDir?: string;
33
+ } = {}): express.Application => {
34
+ const app = getBaseServer();
35
+ setupAuth(app, UserModel as unknown as UserModelType);
36
+ addAuthRoutes(app, UserModel as unknown as UserModelType);
37
+ const admin = new AdminApp({
38
+ accessControl,
39
+ basePath: "/admin",
40
+ migrations: migrationsDir ? {dir: migrationsDir} : undefined,
41
+ models: [],
42
+ });
43
+ admin.register(app);
44
+ app.use(apiUnauthorizedMiddleware);
45
+ app.use(apiErrorMiddleware);
46
+ return app;
47
+ };
48
+
49
+ const waitForTask = (): Promise<void> => {
50
+ return new Promise((resolve) => setTimeout(resolve, 500));
51
+ };
52
+
53
+ const appliedIds = async (): Promise<string[]> => {
54
+ const docs = await mongoose.connection
55
+ .collection(MIGRATIONS_COLLECTION)
56
+ .find({_id: {$ne: MIGRATION_LOCK_ID}})
57
+ .project({id: 1})
58
+ .toArray();
59
+ return docs.map((doc) => String(doc.id)).sort();
60
+ };
61
+
62
+ describe("AdminApp migrations routes", () => {
63
+ let app: express.Application;
64
+ let adminAgent: TestAgent;
65
+ let notAdminAgent: TestAgent;
66
+
67
+ afterEach(async () => {
68
+ await waitForTask();
69
+ await BackgroundTask.deleteMany({});
70
+ });
71
+
72
+ describe("when migrations are not configured", () => {
73
+ beforeEach(async () => {
74
+ await setupDb();
75
+ await mongoose.connection.collection(MIGRATIONS_COLLECTION).deleteMany({});
76
+ app = buildApp();
77
+ adminAgent = await authAsUser(app, "admin");
78
+ });
79
+
80
+ it("returns 404 for GET /admin/migrations/status", async () => {
81
+ await adminAgent.get("/admin/migrations/status").expect(404);
82
+ });
83
+
84
+ it("returns 404 for POST /admin/migrations/run", async () => {
85
+ await adminAgent.post("/admin/migrations/run").expect(404);
86
+ });
87
+
88
+ it("omits enabled migrations from config", async () => {
89
+ const res = await adminAgent.get("/admin/config").expect(200);
90
+ expect(res.body.migrations?.enabled).toBe(false);
91
+ });
92
+ });
93
+
94
+ describe("when migrations are configured", () => {
95
+ beforeEach(async () => {
96
+ await setupDb();
97
+ await mongoose.connection.collection(MIGRATIONS_COLLECTION).deleteMany({});
98
+ app = buildApp({migrationsDir: fixturesDir});
99
+ adminAgent = await authAsUser(app, "admin");
100
+ notAdminAgent = await authAsUser(app, "notAdmin");
101
+ });
102
+
103
+ it("returns 404 when the configured directory is missing", async () => {
104
+ const missingApp = buildApp({
105
+ migrationsDir: join(tmpdir(), "terreno-admin-migrations-missing"),
106
+ });
107
+ const agent = await authAsUser(missingApp, "admin");
108
+ const res = await agent.get("/admin/migrations/status").expect(404);
109
+ expect(res.body.title).toBe("Migration directory not found");
110
+ });
111
+
112
+ it("returns pending status for admins", async () => {
113
+ const res = await adminAgent.get("/admin/migrations/status").expect(200);
114
+ expect(res.body.data.pending.map((row: {id: string}) => row.id)).toEqual([
115
+ "20260910120000-alpha",
116
+ "20260910120001-beta",
117
+ ]);
118
+ });
119
+
120
+ it("disables CRUD on the migrations mount", async () => {
121
+ await adminAgent.get("/admin/migrations").expect(405);
122
+ });
123
+
124
+ it("forbids non-admins", async () => {
125
+ await notAdminAgent.get("/admin/migrations/status").expect(405);
126
+ await notAdminAgent.post("/admin/migrations/run").expect(405);
127
+ });
128
+
129
+ it("requires admin:runScripts to start a run when accessControl is configured", async () => {
130
+ const accessControl = createAccess({
131
+ connection: mongoose.connection,
132
+ resolvePermissions: async () => ({admin: ["access"]}),
133
+ statements: terrenoStatements,
134
+ });
135
+ const rbacApp = buildApp({accessControl, migrationsDir: fixturesDir});
136
+ const accessOnly = await authAsUser(rbacApp, "admin");
137
+
138
+ await accessOnly.get("/admin/migrations/status").expect(200);
139
+ await accessOnly.post("/admin/migrations/run").expect(405);
140
+ await accessOnly.post("/admin/migrations/run?wetRun=true").expect(405);
141
+ expect(await appliedIds()).toEqual([]);
142
+ });
143
+
144
+ it("allows admin:runScripts to start a dry-run", async () => {
145
+ const accessControl = createAccess({
146
+ connection: mongoose.connection,
147
+ resolvePermissions: async () => ({
148
+ admin: ["access", "runScripts", "viewBackgroundTasks"],
149
+ }),
150
+ statements: terrenoStatements,
151
+ });
152
+ const rbacApp = buildApp({accessControl, migrationsDir: fixturesDir});
153
+ const runner = await authAsUser(rbacApp, "admin");
154
+
155
+ const res = await runner.post("/admin/migrations/run").expect(201);
156
+ expect(res.body.data.taskId).toBeDefined();
157
+ await waitForTask();
158
+ expect(await appliedIds()).toEqual([]);
159
+ });
160
+
161
+ it("sets migrations.enabled on config", async () => {
162
+ const res = await adminAgent.get("/admin/config").expect(200);
163
+ expect(res.body.migrations.enabled).toBe(true);
164
+ });
165
+
166
+ it("dry-run does not persist applied ids", async () => {
167
+ const res = await adminAgent.post("/admin/migrations/run").expect(201);
168
+ expect(res.body.data.taskId).toBeDefined();
169
+ await waitForTask();
170
+ expect(await appliedIds()).toEqual([]);
171
+ const task = await BackgroundTask.findById(res.body.data.taskId);
172
+ expect(task?.isDryRun).toBe(true);
173
+ expect(task?.taskType).toBe("migrations:up");
174
+ const polled = await adminAgent
175
+ .get(`/admin/scripts/tasks/${res.body.data.taskId}`)
176
+ .expect(200);
177
+ expect(polled.body.task.status).toBe("completed");
178
+ });
179
+
180
+ it("applies pending on wet run", async () => {
181
+ const res = await adminAgent.post("/admin/migrations/run?wetRun=true").expect(201);
182
+ await waitForTask();
183
+ expect(await appliedIds()).toEqual(["20260910120000-alpha", "20260910120001-beta"]);
184
+ const task = await BackgroundTask.findById(res.body.data.taskId);
185
+ expect(task?.isDryRun).toBe(false);
186
+ });
187
+
188
+ it("returns 403 for production wet apply without ALLOW_MIGRATIONS", async () => {
189
+ const previousNodeEnv = process.env.NODE_ENV;
190
+ process.env.NODE_ENV = "production";
191
+ Reflect.deleteProperty(process.env, "ALLOW_MIGRATIONS");
192
+ try {
193
+ await adminAgent.post("/admin/migrations/run?wetRun=true").expect(403);
194
+ expect(await appliedIds()).toEqual([]);
195
+ } finally {
196
+ process.env.NODE_ENV = previousNodeEnv;
197
+ }
198
+ });
199
+ });
200
+
201
+ describe("when a migration up throws", () => {
202
+ let dir: string;
203
+
204
+ beforeEach(async () => {
205
+ await setupDb();
206
+ await mongoose.connection.collection(MIGRATIONS_COLLECTION).deleteMany({});
207
+ dir = await mkdtemp(join(tmpdir(), "admin-mig-fail-"));
208
+ await writeFile(
209
+ join(dir, "20260910120000-boom.ts"),
210
+ `export const id = "20260910120000-boom";
211
+ export const up = async () => {
212
+ throw new Error("boom");
213
+ };
214
+ `
215
+ );
216
+ app = buildApp({migrationsDir: dir});
217
+ adminAgent = await authAsUser(app, "admin");
218
+ });
219
+
220
+ afterEach(async () => {
221
+ await rm(dir, {force: true, recursive: true});
222
+ });
223
+
224
+ it("marks the background task failed", async () => {
225
+ const res = await adminAgent.post("/admin/migrations/run").expect(201);
226
+ await waitForTask();
227
+ const task = await BackgroundTask.findById(res.body.data.taskId);
228
+ expect(task?.status).toBe("failed");
229
+ expect(task?.error).toContain("boom");
230
+ });
231
+ });
232
+ });