@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
package/dist/adminApp.js CHANGED
@@ -99,10 +99,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
99
99
  Object.defineProperty(exports, "__esModule", { value: true });
100
100
  exports.AdminApp = exports.getArrayEmbeddedSchemaType = exports.adminOwnedBy = void 0;
101
101
  var api_1 = require("@terreno/api");
102
+ var jobs_1 = require("@terreno/jobs");
102
103
  var express_1 = __importDefault(require("express"));
103
104
  var luxon_1 = require("luxon");
104
105
  var mongoose_1 = __importDefault(require("mongoose"));
105
106
  var adminConfigIdentity_1 = require("./adminConfigIdentity");
107
+ var adminMigrations_1 = require("./adminMigrations");
108
+ var adminScriptJob_1 = require("./adminScriptJob");
106
109
  var adminTextSearch_1 = require("./adminTextSearch");
107
110
  var adminUiV2_1 = require("./adminUiV2");
108
111
  var aggregateAdmin_1 = require("./aggregateAdmin");
@@ -122,6 +125,24 @@ var adminOwnedBy = function (field) {
122
125
  };
123
126
  };
124
127
  exports.adminOwnedBy = adminOwnedBy;
128
+ var syncMetaForAdminModel = function (modelName, isOrganizationScoped) {
129
+ if (isOrganizationScoped === void 0) { isOrganizationScoped = false; }
130
+ if (isOrganizationScoped) {
131
+ return { adminBroadcast: false };
132
+ }
133
+ var entry = (0, api_1.findSyncEntryByModelName)(modelName);
134
+ if ((entry === null || entry === void 0 ? void 0 : entry.config.adminBroadcast) !== true) {
135
+ return { adminBroadcast: false };
136
+ }
137
+ return { adminBroadcast: true, syncCollection: entry.collectionTag };
138
+ };
139
+ var disableOrgScopedAdminBroadcastSync = function (modelName) {
140
+ var syncEntry = (0, api_1.findSyncEntryByModelName)(modelName);
141
+ if ((syncEntry === null || syncEntry === void 0 ? void 0 : syncEntry.config.adminBroadcast) !== true) {
142
+ return;
143
+ }
144
+ (0, api_1.updateSyncRegistryOptions)(syncEntry.routePath, __assign(__assign({}, syncEntry.options), { sync: __assign(__assign({}, syncEntry.config), { adminBroadcast: false }) }));
145
+ };
125
146
  var buildAllModelAdminsMap = function (models) {
126
147
  var e_1, _a;
127
148
  var map = {};
@@ -149,19 +170,20 @@ var scrubAdminResponse = function (value, config, allModelAdmins) {
149
170
  };
150
171
  var buildAdminListQueryFilter = function (config,
151
172
  /** Resolved (possibly derived) search fields from `/admin/config`, not just explicit config. */
152
- resolvedSearchFields) {
173
+ resolvedSearchFields, isOrganizationScoped) {
153
174
  var _a;
175
+ if (isOrganizationScoped === void 0) { isOrganizationScoped = false; }
154
176
  var base = config.queryFilter;
155
177
  var searchFields = (_a = resolvedSearchFields !== null && resolvedSearchFields !== void 0 ? resolvedSearchFields : config.searchFields) !== null && _a !== void 0 ? _a : [];
156
178
  return function (user, query) { return __awaiter(void 0, void 0, void 0, function () {
157
- var clientQuery, _a, consumedKeys, errors, filter, consumedKeys_1, consumedKeys_1_1, key, rawSearch, searchClause, merged, baseResult, result;
158
- var e_2, _b, _c;
159
- var _d;
160
- return __generator(this, function (_e) {
161
- switch (_e.label) {
179
+ var clientQuery, _a, consumedKeys, errors, filter, consumedKeys_1, consumedKeys_1_1, key, rawSearch, searchClause, merged, baseResult, result, overrides, consumedKeys_2, consumedKeys_2_1, key;
180
+ var e_2, _b, e_3, _c, _d;
181
+ var _e;
182
+ return __generator(this, function (_f) {
183
+ switch (_f.label) {
162
184
  case 0:
163
185
  clientQuery = __assign({}, (query !== null && query !== void 0 ? query : {}));
164
- _a = (0, filterParser_1.parseAdminListFilters)(clientQuery, (_d = config.filters) !== null && _d !== void 0 ? _d : []), consumedKeys = _a.consumedKeys, errors = _a.errors, filter = _a.filter;
186
+ _a = (0, filterParser_1.parseAdminListFilters)(clientQuery, (_e = config.filters) !== null && _e !== void 0 ? _e : []), consumedKeys = _a.consumedKeys, errors = _a.errors, filter = _a.filter;
165
187
  if (Object.keys(errors).length > 0) {
166
188
  throw new api_1.APIError({
167
189
  detail: JSON.stringify(errors),
@@ -195,15 +217,34 @@ resolvedSearchFields) {
195
217
  if (!base) return [3 /*break*/, 2];
196
218
  return [4 /*yield*/, base(user, merged)];
197
219
  case 1:
198
- baseResult = _e.sent();
220
+ baseResult = _f.sent();
199
221
  if (baseResult === null) {
200
222
  return [2 /*return*/, null];
201
223
  }
202
224
  merged = __assign(__assign({}, merged), baseResult);
203
- _e.label = 2;
225
+ _f.label = 2;
204
226
  case 2:
227
+ if (isOrganizationScoped) {
228
+ merged = __assign(__assign({}, merged), (0, api_1.OrgQueryFilter)(user, merged));
229
+ }
205
230
  result = (0, adminTextSearch_1.andMongoFilters)(merged, searchClause);
206
- return [2 /*return*/, __assign(__assign({}, result), (_c = {}, _c[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM] = undefined, _c))];
231
+ overrides = __assign({}, filter);
232
+ try {
233
+ for (consumedKeys_2 = __values(consumedKeys), consumedKeys_2_1 = consumedKeys_2.next(); !consumedKeys_2_1.done; consumedKeys_2_1 = consumedKeys_2.next()) {
234
+ key = consumedKeys_2_1.value;
235
+ if (!(key in overrides)) {
236
+ overrides[key] = undefined;
237
+ }
238
+ }
239
+ }
240
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
241
+ finally {
242
+ try {
243
+ if (consumedKeys_2_1 && !consumedKeys_2_1.done && (_c = consumedKeys_2.return)) _c.call(consumedKeys_2);
244
+ }
245
+ finally { if (e_3) throw e_3.error; }
246
+ }
247
+ return [2 /*return*/, __assign(__assign(__assign({}, result), overrides), (_d = {}, _d[adminTextSearch_1.ADMIN_LIST_SEARCH_PARAM] = undefined, _d))];
207
248
  }
208
249
  });
209
250
  }); };
@@ -228,7 +269,7 @@ var resolveAdminSortableFields = function (_a) {
228
269
  };
229
270
  var validateAdminSortParam = function (sortableFields) {
230
271
  return function (req, _res, next) {
231
- var e_3, _a;
272
+ var e_4, _a;
232
273
  var sort = req.query.sort;
233
274
  if (typeof sort !== "string" || !sort.trim()) {
234
275
  next();
@@ -248,12 +289,12 @@ var validateAdminSortParam = function (sortableFields) {
248
289
  }
249
290
  }
250
291
  }
251
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
292
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
252
293
  finally {
253
294
  try {
254
295
  if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
255
296
  }
256
- finally { if (e_3) throw e_3.error; }
297
+ finally { if (e_4) throw e_4.error; }
257
298
  }
258
299
  next();
259
300
  };
@@ -268,7 +309,7 @@ var auditDocumentToPlain = function (value) {
268
309
  return value;
269
310
  };
270
311
  var auditLabelFromListFields = function (doc, listFields) {
271
- var e_4, _a;
312
+ var e_5, _a;
272
313
  try {
273
314
  for (var listFields_1 = __values(listFields), listFields_1_1 = listFields_1.next(); !listFields_1_1.done; listFields_1_1 = listFields_1.next()) {
274
315
  var key = listFields_1_1.value;
@@ -279,12 +320,12 @@ var auditLabelFromListFields = function (doc, listFields) {
279
320
  return String(fieldValue);
280
321
  }
281
322
  }
282
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
323
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
283
324
  finally {
284
325
  try {
285
326
  if (listFields_1_1 && !listFields_1_1.done && (_a = listFields_1.return)) _a.call(listFields_1);
286
327
  }
287
- finally { if (e_4) throw e_4.error; }
328
+ finally { if (e_5) throw e_5.error; }
288
329
  }
289
330
  var id = doc._id;
290
331
  return id != null ? String(id) : undefined;
@@ -304,13 +345,8 @@ var coerceAdminFlag = function (value) {
304
345
  }
305
346
  throw new api_1.APIError({ status: 400, title: "admin must be a boolean" });
306
347
  };
307
- var auditActorId = function (request) {
308
- var user = request.user;
309
- if (!user || user._id == null) {
310
- return undefined;
311
- }
312
- return String(user._id);
313
- };
348
+ var auditActorId = api_1.auditActorIdFromRequest;
349
+ /** @internal */
314
350
  var getArrayEmbeddedSchemaType = function (schemaPath) {
315
351
  var compatiblePath = schemaPath;
316
352
  if (typeof compatiblePath.getEmbeddedSchemaType === "function") {
@@ -319,52 +355,14 @@ var getArrayEmbeddedSchemaType = function (schemaPath) {
319
355
  return compatiblePath.caster;
320
356
  };
321
357
  exports.getArrayEmbeddedSchemaType = getArrayEmbeddedSchemaType;
322
- var extractFieldMeta = function (properties, required) {
323
- var e_5, _a;
324
- var _b, _c, _d;
325
- var fields = {};
326
- try {
327
- for (var _e = __values(Object.entries(properties)), _f = _e.next(); !_f.done; _f = _e.next()) {
328
- var _g = __read(_f.value, 2), key = _g[0], prop = _g[1];
329
- var fieldType = (_b = prop.type) !== null && _b !== void 0 ? _b : "string";
330
- fields[key] = {
331
- default: prop.default,
332
- description: prop.description,
333
- enum: prop.enum,
334
- ref: prop.$ref ? prop.$ref.replace("#/components/schemas/", "") : undefined,
335
- required: required.includes(key),
336
- searchable: fieldType === "string" && !prop.enum,
337
- type: fieldType,
338
- };
339
- // For array fields, extract item sub-field metadata
340
- if (prop.type === "array" && ((_c = prop.items) === null || _c === void 0 ? void 0 : _c.properties)) {
341
- var itemRequired = (_d = prop.items.required) !== null && _d !== void 0 ? _d : [];
342
- fields[key].items = extractFieldMeta(prop.items.properties, itemRequired);
343
- }
344
- // For array fields of primitives, capture the item type and enum
345
- if (prop.type === "array" && prop.items && !prop.items.properties) {
346
- var itemProp = prop.items;
347
- if (itemProp.type) {
348
- fields[key].itemType = itemProp.type;
349
- }
350
- if (itemProp.enum) {
351
- fields[key].itemEnum = itemProp.enum;
352
- }
353
- }
354
- // Check for ObjectId references in the raw property
355
- if (!fields[key].ref && prop.type === "string" && prop.format === "objectid") {
356
- // mongoose-to-swagger may not preserve ref directly; we'll handle this in register()
357
- }
358
- }
359
- }
360
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
361
- finally {
362
- try {
363
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
364
- }
365
- finally { if (e_5) throw e_5.error; }
366
- }
367
- return fields;
358
+ var extractFieldMetaFromDescription = function (model, hiddenFields) {
359
+ var hiddenFieldSet = new Set(hiddenFields);
360
+ var description = (0, api_1.describeModel)(model);
361
+ var fields = (0, api_1.modelDescriptionToAdminFields)(description);
362
+ return Object.fromEntries(Object.entries(fields).filter(function (_a) {
363
+ var _b = __read(_a, 1), key = _b[0];
364
+ return !hiddenFieldSet.has(key);
365
+ }));
368
366
  };
369
367
  var asMiddlewareList = function (middleware) {
370
368
  if (middleware === undefined) {
@@ -426,12 +424,29 @@ var AdminApp = /** @class */ (function () {
426
424
  function AdminApp(options) {
427
425
  this.options = options;
428
426
  }
427
+ AdminApp.prototype.isOrganizationScoped = function (config) {
428
+ if (!this.options.organizations) {
429
+ return false;
430
+ }
431
+ // Platform audit rows may omit organizationId. Requiring a selected org hides
432
+ // those events and skips Recent Activity / the AuditEvent changelist.
433
+ if (config.model.modelName === "AuditEvent") {
434
+ return false;
435
+ }
436
+ return Boolean(config.model.schema.path("organizationId"));
437
+ };
429
438
  AdminApp.prototype.adminAccessPermissions = function () {
430
439
  if (this.options.accessControl) {
431
440
  return [this.options.accessControl.permission({ admin: [api_1.ADMIN_PAGE_ACTION] })];
432
441
  }
433
442
  return [api_1.Permissions.IsAdmin];
434
443
  };
444
+ AdminApp.prototype.adminRunScriptsPermissions = function () {
445
+ if (this.options.accessControl) {
446
+ return [this.options.accessControl.permission({ admin: ["runScripts"] })];
447
+ }
448
+ return [api_1.Permissions.IsAdmin];
449
+ };
435
450
  AdminApp.prototype.hasScriptPermission = function (user, action) {
436
451
  return __awaiter(this, void 0, void 0, function () {
437
452
  var result;
@@ -623,7 +638,7 @@ var AdminApp = /** @class */ (function () {
623
638
  AdminApp.prototype.register = function (app, openApi, terrenoApp) {
624
639
  var e_7, _a, e_8, _b;
625
640
  var _this = this;
626
- var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
641
+ var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
627
642
  var basePath = (_c = this.options.basePath) !== null && _c !== void 0 ? _c : "/admin";
628
643
  var openApiMw = openApi;
629
644
  var aggregated = (0, aggregateAdmin_1.aggregateFromTerrenoApp)({
@@ -658,6 +673,24 @@ var AdminApp = /** @class */ (function () {
658
673
  }
659
674
  });
660
675
  }); };
676
+ var safeFrameworkAdminAudit = function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
677
+ var after = _b.after, before = _b.before, extraRedact = _b.extraRedact, modelName = _b.modelName, recordLabel = _b.recordLabel, request = _b.request, verb = _b.verb;
678
+ return __generator(this, function (_c) {
679
+ if (modelName === "AuditEvent") {
680
+ return [2 /*return*/];
681
+ }
682
+ void (0, api_1.maybeRecordAdminAudit)({
683
+ after: after,
684
+ before: before,
685
+ extraRedact: extraRedact,
686
+ modelName: modelName,
687
+ recordLabel: recordLabel,
688
+ req: request,
689
+ verb: verb,
690
+ });
691
+ return [2 /*return*/];
692
+ });
693
+ }); };
661
694
  // Build config response with field metadata from Mongoose schemas
662
695
  var configNames = (0, adminConfigIdentity_1.assignUniqueAdminConfigNames)(modelConfigs.map(function (config) { return ({
663
696
  modelName: config.model.modelName,
@@ -665,127 +698,52 @@ var AdminApp = /** @class */ (function () {
665
698
  source: config.source,
666
699
  }); }));
667
700
  var configModels = modelConfigs.map(function (config, configIndex) {
668
- var e_9, _a, e_10, _b;
669
- var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
670
- var _v = (0, api_1.getOpenApiSpecForModel)(config.model), properties = _v.properties, required = _v.required;
671
- var hiddenFieldSet = new Set((_c = config.hiddenFields) !== null && _c !== void 0 ? _c : []);
672
- var filteredProperties = Object.fromEntries(Object.entries(properties).filter(function (_a) {
673
- var _b = __read(_a, 1), key = _b[0];
674
- return !hiddenFieldSet.has(key);
675
- }));
676
- var filteredRequired = required.filter(function (key) { return !hiddenFieldSet.has(key); });
677
- // Extract ref information directly from the Mongoose schema
678
- var fields = extractFieldMeta(filteredProperties, filteredRequired);
679
- try {
680
- for (var _w = __values(Object.entries(fields)), _x = _w.next(); !_x.done; _x = _w.next()) {
681
- var _y = __read(_x.value, 2), key = _y[0], field = _y[1];
682
- var schemaPath = config.model.schema.path(key);
683
- if (schemaPath) {
684
- var pathOptions = schemaPath.options;
685
- if (pathOptions === null || pathOptions === void 0 ? void 0 : pathOptions.ref) {
686
- field.ref = pathOptions.ref;
687
- }
688
- // Handle array of refs (legacy: also set ref for back-compat)
689
- if (Array.isArray(pathOptions === null || pathOptions === void 0 ? void 0 : pathOptions.type) && ((_d = pathOptions.type[0]) === null || _d === void 0 ? void 0 : _d.ref)) {
690
- field.ref = pathOptions.type[0].ref;
691
- }
692
- // For arrays, use the public embedded schema type to infer the primitive item type/ref.
693
- if (schemaPath.instance === "Array") {
694
- var embeddedSchemaType = (0, exports.getArrayEmbeddedSchemaType)(schemaPath);
695
- if ((embeddedSchemaType === null || embeddedSchemaType === void 0 ? void 0 : embeddedSchemaType.instance) && !field.items) {
696
- var instanceToType = {
697
- Boolean: "boolean",
698
- Number: "number",
699
- ObjectID: "objectid",
700
- ObjectId: "objectid",
701
- SchemaObjectId: "objectid",
702
- String: "string",
703
- };
704
- var mapped = instanceToType[embeddedSchemaType.instance];
705
- if (mapped) {
706
- field.itemType = mapped;
707
- }
708
- if ((_e = embeddedSchemaType.options) === null || _e === void 0 ? void 0 : _e.ref) {
709
- field.itemRef = embeddedSchemaType.options.ref;
710
- }
711
- if (Array.isArray((_f = embeddedSchemaType.options) === null || _f === void 0 ? void 0 : _f.enum)) {
712
- field.itemEnum = embeddedSchemaType.options.enum;
713
- }
714
- }
715
- }
716
- }
717
- }
718
- }
719
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
720
- finally {
721
- try {
722
- if (_x && !_x.done && (_a = _w.return)) _a.call(_w);
723
- }
724
- finally { if (e_9) throw e_9.error; }
725
- }
701
+ var e_9, _a;
702
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
703
+ var hiddenFieldSet = new Set((_b = config.hiddenFields) !== null && _b !== void 0 ? _b : []);
704
+ var fields = extractFieldMetaFromDescription(config.model, __spreadArray([], __read(hiddenFieldSet), false));
726
705
  // Apply field overrides (e.g., widget: "markdown")
727
706
  if (config.fieldOverrides) {
728
707
  try {
729
- for (var _z = __values(Object.entries(config.fieldOverrides)), _0 = _z.next(); !_0.done; _0 = _z.next()) {
730
- var _1 = __read(_0.value, 2), key = _1[0], override = _1[1];
708
+ for (var _r = __values(Object.entries(config.fieldOverrides)), _s = _r.next(); !_s.done; _s = _r.next()) {
709
+ var _t = __read(_s.value, 2), key = _t[0], override = _t[1];
731
710
  if (fields[key] && override.widget) {
732
711
  fields[key].widget = override.widget;
733
712
  }
734
713
  }
735
714
  }
736
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
715
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
737
716
  finally {
738
717
  try {
739
- if (_0 && !_0.done && (_b = _z.return)) _b.call(_z);
718
+ if (_s && !_s.done && (_a = _r.return)) _a.call(_r);
740
719
  }
741
- finally { if (e_10) throw e_10.error; }
720
+ finally { if (e_9) throw e_9.error; }
742
721
  }
743
722
  }
744
- var readonlyFields = (_g = config.readonlyFields) !== null && _g !== void 0 ? _g : [];
723
+ var readonlyFields = (_c = config.readonlyFields) !== null && _c !== void 0 ? _c : [];
745
724
  var listFields = config.listFields.filter(function (field) { return !hiddenFieldSet.has(field); });
746
- var listDisplay = (_h = config.listDisplay) !== null && _h !== void 0 ? _h : listFields;
725
+ var listDisplay = (_d = config.listDisplay) !== null && _d !== void 0 ? _d : listFields;
747
726
  var derivedSearchFields = listFields.filter(function (field) { var _a; return (_a = fields[field]) === null || _a === void 0 ? void 0 : _a.searchable; });
748
- var searchFields = (_j = config.searchFields) !== null && _j !== void 0 ? _j : derivedSearchFields;
727
+ var searchFields = (_e = config.searchFields) !== null && _e !== void 0 ? _e : derivedSearchFields;
749
728
  var sortableFields = resolveAdminSortableFields({
750
729
  defaultSort: config.defaultSort,
751
730
  listDisplay: listDisplay,
752
731
  sortableFields: config.sortableFields,
753
732
  });
754
733
  var schemaPathKeys = new Set(Object.keys(config.model.schema.paths));
755
- var bulkPatchAllowlist = (_k = config.bulkPatchAllowlist) !== null && _k !== void 0 ? _k : (0, adminUiV2_1.defaultBulkPatchAllowlistFrom)({
734
+ var bulkPatchAllowlist = (_f = config.bulkPatchAllowlist) !== null && _f !== void 0 ? _f : (0, adminUiV2_1.defaultBulkPatchAllowlistFrom)({
756
735
  hiddenFieldSet: hiddenFieldSet,
757
736
  listFields: listFields,
758
737
  readonlyFields: readonlyFields,
759
738
  schemaPaths: schemaPathKeys,
760
739
  });
761
- return {
762
- actions: (_l = config.actions) !== null && _l !== void 0 ? _l : [],
763
- bulkPatchAllowlist: bulkPatchAllowlist,
764
- defaultSort: (_m = config.defaultSort) !== null && _m !== void 0 ? _m : "-created",
765
- displayName: config.displayName,
766
- fieldOrder: config.fieldOrder,
767
- fields: fields,
768
- fieldsets: config.fieldsets,
769
- filters: (_o = config.filters) !== null && _o !== void 0 ? _o : [],
770
- group: config.group,
771
- hiddenFields: __spreadArray([], __read(hiddenFieldSet), false),
772
- listDisplay: listDisplay,
773
- listDisplayLinks: (_p = config.listDisplayLinks) !== null && _p !== void 0 ? _p : [],
774
- listFields: listFields,
775
- name: (_q = configNames[configIndex]) !== null && _q !== void 0 ? _q : config.model.modelName,
776
- pageSize: config.pageSize,
777
- permissions: {
778
- create: ((_r = config.permissions) === null || _r === void 0 ? void 0 : _r.create) !== false,
779
- delete: ((_s = config.permissions) === null || _s === void 0 ? void 0 : _s.delete) !== false,
780
- update: ((_t = config.permissions) === null || _t === void 0 ? void 0 : _t.update) !== false,
781
- },
782
- readonlyFields: readonlyFields,
783
- realtime: (_u = config.realtime) !== null && _u !== void 0 ? _u : false,
784
- recordTitleField: config.recordTitleField,
785
- routePath: "".concat(basePath).concat(config.routePath),
786
- searchFields: searchFields,
787
- sortableFields: sortableFields,
788
- };
740
+ var isOrgScopedModel = _this.isOrganizationScoped(config);
741
+ var syncMeta = syncMetaForAdminModel(config.model.modelName, isOrgScopedModel);
742
+ return __assign({ actions: (_g = config.actions) !== null && _g !== void 0 ? _g : [], adminBroadcast: syncMeta.adminBroadcast, bulkPatchAllowlist: bulkPatchAllowlist, defaultSort: (_h = config.defaultSort) !== null && _h !== void 0 ? _h : "-created", displayName: config.displayName, fieldOrder: config.fieldOrder, fields: fields, fieldsets: config.fieldsets, filters: (_j = config.filters) !== null && _j !== void 0 ? _j : [], group: config.group, hiddenFields: __spreadArray([], __read(hiddenFieldSet), false), listDisplay: listDisplay, listDisplayLinks: (_k = config.listDisplayLinks) !== null && _k !== void 0 ? _k : [], listFields: listFields, name: (_l = configNames[configIndex]) !== null && _l !== void 0 ? _l : config.model.modelName, organizationScoped: isOrgScopedModel, pageSize: config.pageSize, permissions: {
743
+ create: ((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create) !== false,
744
+ delete: ((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.delete) !== false,
745
+ update: ((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.update) !== false,
746
+ }, readonlyFields: readonlyFields, realtime: (_q = config.realtime) !== null && _q !== void 0 ? _q : false, recordTitleField: config.recordTitleField, routePath: "".concat(basePath).concat(config.routePath), searchFields: searchFields, sortableFields: sortableFields }, (syncMeta.syncCollection ? { syncCollection: syncMeta.syncCollection } : {}));
789
747
  });
790
748
  // Build script metadata for config response
791
749
  var scriptConfigs = __spreadArray(__spreadArray([], __read(((_e = this.options.scripts) !== null && _e !== void 0 ? _e : [])), false), __read(aggregated.scripts), false);
@@ -797,14 +755,7 @@ var AdminApp = /** @class */ (function () {
797
755
  name: script.name,
798
756
  });
799
757
  });
800
- var defaultScreens = [
801
- {
802
- adminAccess: { action: "read", resource: "configuration" },
803
- displayName: "Version Config",
804
- name: "version-config",
805
- },
806
- ];
807
- var mergedScreens = __spreadArray(__spreadArray(__spreadArray([], __read(defaultScreens), false), __read(aggregated.customScreens), false), __read(((_f = this.options.customScreens) !== null && _f !== void 0 ? _f : [])), false);
758
+ var mergedScreens = __spreadArray(__spreadArray([], __read(aggregated.customScreens), false), __read(((_f = this.options.customScreens) !== null && _f !== void 0 ? _f : [])), false);
808
759
  var baseConfigResponse = {
809
760
  capabilities: {
810
761
  actions: true,
@@ -830,8 +781,9 @@ var AdminApp = /** @class */ (function () {
830
781
  var buildAuthorizedConfig = function (user) { return __awaiter(_this, void 0, void 0, function () {
831
782
  var authorizedModels, authorizedScreens, canReadConfiguration, canReadRoles, canRunScripts, canViewScripts, canUseScripts;
832
783
  var _this = this;
833
- return __generator(this, function (_a) {
834
- switch (_a.label) {
784
+ var _a;
785
+ return __generator(this, function (_b) {
786
+ switch (_b.label) {
835
787
  case 0: return [4 /*yield*/, Promise.all(configModels.map(function (modelMeta, index) { return __awaiter(_this, void 0, void 0, function () {
836
788
  var config, canRead, canCreate, _a, canDelete, _b, canUpdate, _c;
837
789
  return __generator(this, function (_d) {
@@ -876,7 +828,7 @@ var AdminApp = /** @class */ (function () {
876
828
  });
877
829
  }); }))];
878
830
  case 1:
879
- authorizedModels = (_a.sent()).filter(function (model) { return model !== null; });
831
+ authorizedModels = (_b.sent()).filter(function (model) { return model !== null; });
880
832
  return [4 /*yield*/, Promise.all(mergedScreens.map(function (screen) { return __awaiter(_this, void 0, void 0, function () {
881
833
  var allowed_1, allowed;
882
834
  var _a, _b;
@@ -908,24 +860,24 @@ var AdminApp = /** @class */ (function () {
908
860
  });
909
861
  }); }))];
910
862
  case 2:
911
- authorizedScreens = (_a.sent()).filter(function (screen) { return screen !== null; });
863
+ authorizedScreens = (_b.sent()).filter(function (screen) { return screen !== null; });
912
864
  return [4 /*yield*/, this.hasConfigurationPermission(user, "read")];
913
865
  case 3:
914
- canReadConfiguration = _a.sent();
866
+ canReadConfiguration = _b.sent();
915
867
  return [4 /*yield*/, this.canAnyResourceAction(user, "rbac", ["read"])];
916
868
  case 4:
917
- canReadRoles = _a.sent();
869
+ canReadRoles = _b.sent();
918
870
  return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
919
871
  case 5:
920
- canRunScripts = _a.sent();
872
+ canRunScripts = _b.sent();
921
873
  return [4 /*yield*/, this.hasScriptPermission(user, "viewBackgroundTasks")];
922
874
  case 6:
923
- canViewScripts = _a.sent();
875
+ canViewScripts = _b.sent();
924
876
  canUseScripts = canRunScripts || canViewScripts;
925
877
  return [2 /*return*/, __assign(__assign({}, baseConfigResponse), { customScreens: authorizedScreens.map(function (_a) {
926
878
  var _adminAccess = _a.adminAccess, screen = __rest(_a, ["adminAccess"]);
927
879
  return screen;
928
- }), models: authorizedModels, platformTools: {
880
+ }), migrations: { enabled: Boolean((_a = this.options.migrations) === null || _a === void 0 ? void 0 : _a.dir) }, models: authorizedModels, platformTools: {
929
881
  configuration: canReadConfiguration,
930
882
  roles: canReadRoles,
931
883
  runScripts: canRunScripts,
@@ -955,6 +907,8 @@ var AdminApp = /** @class */ (function () {
955
907
  properties: {
956
908
  description: { type: "string" },
957
909
  displayName: { type: "string" },
910
+ group: { type: "string" },
911
+ icon: { type: "string" },
958
912
  name: { type: "string" },
959
913
  },
960
914
  type: "object",
@@ -1122,7 +1076,7 @@ var AdminApp = /** @class */ (function () {
1122
1076
  }); }));
1123
1077
  app.put(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1124
1078
  var raw, allowedFields, setFields, unsetFields, allowedFields_1, allowedFields_1_1, field, updateOp, doc;
1125
- var e_11, _a;
1079
+ var e_10, _a;
1126
1080
  return __generator(this, function (_b) {
1127
1081
  switch (_b.label) {
1128
1082
  case 0: return [4 /*yield*/, this.hasConfigurationPermission(req.user, "update")];
@@ -1153,12 +1107,12 @@ var AdminApp = /** @class */ (function () {
1153
1107
  }
1154
1108
  }
1155
1109
  }
1156
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
1110
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
1157
1111
  finally {
1158
1112
  try {
1159
1113
  if (allowedFields_1_1 && !allowedFields_1_1.done && (_a = allowedFields_1.return)) _a.call(allowedFields_1);
1160
1114
  }
1161
- finally { if (e_11) throw e_11.error; }
1115
+ finally { if (e_10) throw e_10.error; }
1162
1116
  }
1163
1117
  updateOp = {};
1164
1118
  if (Object.keys(setFields).length > 0) {
@@ -1180,7 +1134,8 @@ var AdminApp = /** @class */ (function () {
1180
1134
  });
1181
1135
  }); }));
1182
1136
  var _loop_1 = function (config) {
1183
- var e_12, _t;
1137
+ var e_11, _2;
1138
+ var isOrganizationScoped = this_1.isOrganizationScoped(config);
1184
1139
  // Determine searchable fields from the actual Mongoose schema type,
1185
1140
  // not the OpenAPI type (which reports ObjectId as "string")
1186
1141
  var searchableFields = [];
@@ -1188,8 +1143,8 @@ var AdminApp = /** @class */ (function () {
1188
1143
  var modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, "".concat(basePath).concat(config.routePath));
1189
1144
  if (modelMeta) {
1190
1145
  try {
1191
- for (var _u = (e_12 = void 0, __values(Object.keys(modelMeta.fields))), _v = _u.next(); !_v.done; _v = _u.next()) {
1192
- var key = _v.value;
1146
+ for (var _3 = (e_11 = void 0, __values(Object.keys(modelMeta.fields))), _4 = _3.next(); !_4.done; _4 = _3.next()) {
1147
+ var key = _4.value;
1193
1148
  var schemaPath = config.model.schema.path(key);
1194
1149
  if (schemaPath && schemaPath.instance === "String" && !modelMeta.fields[key].enum) {
1195
1150
  searchableFields.push(key);
@@ -1199,84 +1154,85 @@ var AdminApp = /** @class */ (function () {
1199
1154
  }
1200
1155
  }
1201
1156
  }
1202
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
1157
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
1203
1158
  finally {
1204
1159
  try {
1205
- if (_v && !_v.done && (_t = _u.return)) _t.call(_u);
1160
+ if (_4 && !_4.done && (_2 = _3.return)) _2.call(_3);
1206
1161
  }
1207
- finally { if (e_12) throw e_12.error; }
1162
+ finally { if (e_11) throw e_11.error; }
1208
1163
  }
1209
1164
  }
1210
- app.get("".concat(basePath).concat(config.routePath, "/search"), (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1211
- var q, fields, searchClause, scoped, results, err_3;
1212
- var _a;
1213
- return __generator(this, function (_b) {
1214
- switch (_b.label) {
1215
- case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), req.user)];
1216
- case 1:
1217
- if (!(_b.sent())) {
1218
- throw new api_1.APIError({
1219
- disableExternalErrorTracking: true,
1220
- status: 403,
1221
- title: "Forbidden",
1165
+ app.get.apply(app, __spreadArray(__spreadArray(["".concat(basePath).concat(config.routePath, "/search"), (0, api_1.authenticateMiddleware)()], __read((isOrganizationScoped ? [(0, api_1.orgContextMiddleware)({ required: true })] : [])), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1166
+ var q, fields, searchClause, scoped, results, err_3;
1167
+ var _a;
1168
+ return __generator(this, function (_b) {
1169
+ switch (_b.label) {
1170
+ case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), req.user)];
1171
+ case 1:
1172
+ if (!(_b.sent())) {
1173
+ throw new api_1.APIError({
1174
+ disableExternalErrorTracking: true,
1175
+ status: 403,
1176
+ title: "Forbidden",
1177
+ });
1178
+ }
1179
+ q = String((_a = req.query.q) !== null && _a !== void 0 ? _a : "");
1180
+ if (!q) {
1181
+ return [2 /*return*/, res.json({ data: [] })];
1182
+ }
1183
+ fields = typeof req.query.fields === "string"
1184
+ ? req.query.fields.split(",").filter(function (f) { return searchableFields.includes(f); })
1185
+ : searchableFields;
1186
+ searchClause = (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
1187
+ extraObjectIdFields: objectIdFields,
1188
+ model: config.model,
1189
+ q: q,
1190
+ searchFields: fields,
1222
1191
  });
1223
- }
1224
- q = String((_a = req.query.q) !== null && _a !== void 0 ? _a : "");
1225
- if (!q) {
1226
- return [2 /*return*/, res.json({ data: [] })];
1227
- }
1228
- fields = typeof req.query.fields === "string"
1229
- ? req.query.fields.split(",").filter(function (f) { return searchableFields.includes(f); })
1230
- : searchableFields;
1231
- searchClause = (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
1232
- extraObjectIdFields: objectIdFields,
1233
- model: config.model,
1234
- q: q,
1235
- searchFields: fields,
1236
- });
1237
- if (!searchClause) {
1238
- return [2 /*return*/, res.json({ data: [] })];
1239
- }
1240
- api_1.logger.debug("Admin search query", {
1241
- fields: fields,
1242
- model: config.model.modelName,
1243
- q: q,
1244
- });
1245
- _b.label = 2;
1246
- case 2:
1247
- _b.trys.push([2, 5, , 6]);
1248
- return [4 /*yield*/, buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields)(req.user, {})];
1249
- case 3:
1250
- scoped = _b.sent();
1251
- if (scoped === null) {
1252
- return [2 /*return*/, res.json({ data: [] })];
1253
- }
1254
- return [4 /*yield*/, config.model
1255
- .find({ $and: [scoped, searchClause] })
1256
- .limit(20)
1257
- .lean()];
1258
- case 4:
1259
- results = _b.sent();
1260
- api_1.logger.debug("Admin search results", {
1261
- count: results.length,
1262
- model: config.model.modelName,
1263
- });
1264
- return [2 /*return*/, res.json({
1265
- data: results.map(function (doc) { return scrubAdminResponse(doc, config, allModelAdmins); }),
1266
- })];
1267
- case 5:
1268
- err_3 = _b.sent();
1269
- api_1.logger.error("Admin search failed", {
1270
- error: err_3,
1271
- fields: fields,
1272
- model: config.model.modelName,
1273
- });
1274
- throw err_3;
1275
- case 6: return [2 /*return*/];
1276
- }
1277
- });
1278
- }); }));
1192
+ if (!searchClause) {
1193
+ return [2 /*return*/, res.json({ data: [] })];
1194
+ }
1195
+ api_1.logger.debug("Admin search query", {
1196
+ fields: fields,
1197
+ model: config.model.modelName,
1198
+ q: q,
1199
+ });
1200
+ _b.label = 2;
1201
+ case 2:
1202
+ _b.trys.push([2, 5, , 6]);
1203
+ return [4 /*yield*/, buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields, isOrganizationScoped)(req.user, {})];
1204
+ case 3:
1205
+ scoped = _b.sent();
1206
+ if (scoped === null) {
1207
+ return [2 /*return*/, res.json({ data: [] })];
1208
+ }
1209
+ return [4 /*yield*/, config.model
1210
+ .find({ $and: [scoped, searchClause] })
1211
+ .limit(20)
1212
+ .lean()];
1213
+ case 4:
1214
+ results = _b.sent();
1215
+ api_1.logger.debug("Admin search results", {
1216
+ count: results.length,
1217
+ model: config.model.modelName,
1218
+ });
1219
+ return [2 /*return*/, res.json({
1220
+ data: results.map(function (doc) { return scrubAdminResponse(doc, config, allModelAdmins); }),
1221
+ })];
1222
+ case 5:
1223
+ err_3 = _b.sent();
1224
+ api_1.logger.error("Admin search failed", {
1225
+ error: err_3,
1226
+ fields: fields,
1227
+ model: config.model.modelName,
1228
+ });
1229
+ throw err_3;
1230
+ case 6: return [2 /*return*/];
1231
+ }
1232
+ });
1233
+ }); })], false));
1279
1234
  };
1235
+ var this_1 = this;
1280
1236
  try {
1281
1237
  // Mount search endpoint for each model
1282
1238
  for (var modelConfigs_1 = __values(modelConfigs), modelConfigs_1_1 = modelConfigs_1.next(); !modelConfigs_1_1.done; modelConfigs_1_1 = modelConfigs_1.next()) {
@@ -1292,6 +1248,7 @@ var AdminApp = /** @class */ (function () {
1292
1248
  finally { if (e_7) throw e_7.error; }
1293
1249
  }
1294
1250
  var _loop_2 = function (config) {
1251
+ var isOrganizationScoped = this_2.isOrganizationScoped(config);
1295
1252
  var hiddenFieldSet = new Set((_g = config.hiddenFields) !== null && _g !== void 0 ? _g : []);
1296
1253
  var readonlySet = new Set((_h = config.readonlyFields) !== null && _h !== void 0 ? _h : []);
1297
1254
  var excludeFieldSet = new Set((_j = config.excludeFields) !== null && _j !== void 0 ? _j : []);
@@ -1301,66 +1258,70 @@ var AdminApp = /** @class */ (function () {
1301
1258
  if (allowed === false) {
1302
1259
  return [];
1303
1260
  }
1304
- return _this.resourceActionPermissions(config, action);
1261
+ var permissions = _this.resourceActionPermissions(config, action);
1262
+ if (isOrganizationScoped && action !== "create") {
1263
+ return __spreadArray(__spreadArray([], __read(permissions), false), [api_1.Permissions.IsOrganizationMember], false);
1264
+ }
1265
+ return permissions;
1305
1266
  };
1306
- var updatePermissions = this_1.resourceActionPermissions(config, "update");
1267
+ var updatePermissions = adminPermission((_l = config.permissions) === null || _l === void 0 ? void 0 : _l.update, "update");
1307
1268
  var stripProtectedFromBody = function (body) {
1308
- var e_13, _a, e_14, _b, e_15, _c, e_16, _d;
1269
+ var e_12, _a, e_13, _b, e_14, _c, e_15, _d;
1309
1270
  if (!body || typeof body !== "object" || Array.isArray(body)) {
1310
1271
  return {};
1311
1272
  }
1312
1273
  var next = __assign({}, body);
1313
1274
  try {
1314
- for (var readonlySet_1 = (e_13 = void 0, __values(readonlySet)), readonlySet_1_1 = readonlySet_1.next(); !readonlySet_1_1.done; readonlySet_1_1 = readonlySet_1.next()) {
1275
+ for (var readonlySet_1 = (e_12 = void 0, __values(readonlySet)), readonlySet_1_1 = readonlySet_1.next(); !readonlySet_1_1.done; readonlySet_1_1 = readonlySet_1.next()) {
1315
1276
  var key = readonlySet_1_1.value;
1316
1277
  delete next[key];
1317
1278
  }
1318
1279
  }
1319
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1280
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
1320
1281
  finally {
1321
1282
  try {
1322
1283
  if (readonlySet_1_1 && !readonlySet_1_1.done && (_a = readonlySet_1.return)) _a.call(readonlySet_1);
1323
1284
  }
1324
- finally { if (e_13) throw e_13.error; }
1285
+ finally { if (e_12) throw e_12.error; }
1325
1286
  }
1326
1287
  try {
1327
- for (var hiddenFieldSet_1 = (e_14 = void 0, __values(hiddenFieldSet)), hiddenFieldSet_1_1 = hiddenFieldSet_1.next(); !hiddenFieldSet_1_1.done; hiddenFieldSet_1_1 = hiddenFieldSet_1.next()) {
1288
+ for (var hiddenFieldSet_1 = (e_13 = void 0, __values(hiddenFieldSet)), hiddenFieldSet_1_1 = hiddenFieldSet_1.next(); !hiddenFieldSet_1_1.done; hiddenFieldSet_1_1 = hiddenFieldSet_1.next()) {
1328
1289
  var key = hiddenFieldSet_1_1.value;
1329
1290
  delete next[key];
1330
1291
  }
1331
1292
  }
1332
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
1293
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
1333
1294
  finally {
1334
1295
  try {
1335
1296
  if (hiddenFieldSet_1_1 && !hiddenFieldSet_1_1.done && (_b = hiddenFieldSet_1.return)) _b.call(hiddenFieldSet_1);
1336
1297
  }
1337
- finally { if (e_14) throw e_14.error; }
1298
+ finally { if (e_13) throw e_13.error; }
1338
1299
  }
1339
1300
  try {
1340
- for (var excludeFieldSet_1 = (e_15 = void 0, __values(excludeFieldSet)), excludeFieldSet_1_1 = excludeFieldSet_1.next(); !excludeFieldSet_1_1.done; excludeFieldSet_1_1 = excludeFieldSet_1.next()) {
1301
+ for (var excludeFieldSet_1 = (e_14 = void 0, __values(excludeFieldSet)), excludeFieldSet_1_1 = excludeFieldSet_1.next(); !excludeFieldSet_1_1.done; excludeFieldSet_1_1 = excludeFieldSet_1.next()) {
1341
1302
  var key = excludeFieldSet_1_1.value;
1342
1303
  delete next[key];
1343
1304
  }
1344
1305
  }
1345
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
1306
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
1346
1307
  finally {
1347
1308
  try {
1348
1309
  if (excludeFieldSet_1_1 && !excludeFieldSet_1_1.done && (_c = excludeFieldSet_1.return)) _c.call(excludeFieldSet_1);
1349
1310
  }
1350
- finally { if (e_15) throw e_15.error; }
1311
+ finally { if (e_14) throw e_14.error; }
1351
1312
  }
1352
1313
  try {
1353
- for (var SYSTEM_ADMIN_FIELDS_1 = (e_16 = void 0, __values(adminUiV2_1.SYSTEM_ADMIN_FIELDS)), SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next(); !SYSTEM_ADMIN_FIELDS_1_1.done; SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next()) {
1314
+ for (var SYSTEM_ADMIN_FIELDS_1 = (e_15 = void 0, __values(adminUiV2_1.SYSTEM_ADMIN_FIELDS)), SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next(); !SYSTEM_ADMIN_FIELDS_1_1.done; SYSTEM_ADMIN_FIELDS_1_1 = SYSTEM_ADMIN_FIELDS_1.next()) {
1354
1315
  var key = SYSTEM_ADMIN_FIELDS_1_1.value;
1355
1316
  delete next[key];
1356
1317
  }
1357
1318
  }
1358
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
1319
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
1359
1320
  finally {
1360
1321
  try {
1361
1322
  if (SYSTEM_ADMIN_FIELDS_1_1 && !SYSTEM_ADMIN_FIELDS_1_1.done && (_d = SYSTEM_ADMIN_FIELDS_1.return)) _d.call(SYSTEM_ADMIN_FIELDS_1);
1362
1323
  }
1363
- finally { if (e_16) throw e_16.error; }
1324
+ finally { if (e_15) throw e_15.error; }
1364
1325
  }
1365
1326
  // Self-service never writes these fields. Admin CRUD may set `admin`.
1366
1327
  // When RBAC is enabled, `roles` must go through RoleManager.assign and
@@ -1451,7 +1412,7 @@ var AdminApp = /** @class */ (function () {
1451
1412
  };
1452
1413
  var restoreUserFieldsAfterFailedRoleAssign = function (value, prev, cleanedBody) { return __awaiter(_this, void 0, void 0, function () {
1453
1414
  var record, prevRecord, body, restore, _a, _b, key;
1454
- var e_17, _c;
1415
+ var e_16, _c;
1455
1416
  return __generator(this, function (_d) {
1456
1417
  switch (_d.label) {
1457
1418
  case 0:
@@ -1477,12 +1438,12 @@ var AdminApp = /** @class */ (function () {
1477
1438
  }
1478
1439
  }
1479
1440
  }
1480
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
1441
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
1481
1442
  finally {
1482
1443
  try {
1483
1444
  if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1484
1445
  }
1485
- finally { if (e_17) throw e_17.error; }
1446
+ finally { if (e_16) throw e_16.error; }
1486
1447
  }
1487
1448
  if (Object.keys(restore).length === 0) {
1488
1449
  return [2 /*return*/];
@@ -1525,71 +1486,112 @@ var AdminApp = /** @class */ (function () {
1525
1486
  })
1526
1487
  .build()
1527
1488
  : undefined;
1528
- var auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
1529
- var auditHooks = auditEligible
1530
- ? {
1531
- postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1532
- var doc, rid;
1533
- return __generator(this, function (_a) {
1534
- switch (_a.label) {
1535
- case 0:
1536
- doc = auditDocumentToPlain(value);
1537
- rid = doc._id;
1538
- return [4 /*yield*/, safeOnAdminAudit(request, {
1539
- actorId: auditActorId(request),
1540
- modelName: config.model.modelName,
1541
- recordId: rid != null ? String(rid) : undefined,
1542
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1543
- verb: "created",
1544
- })];
1545
- case 1:
1546
- _a.sent();
1489
+ var skipOnAdminAuditHook = config.model.modelName === "AdminAuditLog";
1490
+ var auditHooks = {
1491
+ postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1492
+ var doc, rid, recordLabel;
1493
+ return __generator(this, function (_a) {
1494
+ switch (_a.label) {
1495
+ case 0:
1496
+ doc = auditDocumentToPlain(value);
1497
+ rid = doc._id;
1498
+ recordLabel = auditLabelFromListFields(doc, config.listFields);
1499
+ return [4 /*yield*/, safeFrameworkAdminAudit({
1500
+ after: value,
1501
+ extraRedact: __spreadArray(__spreadArray([], __read(hiddenFieldSet), false), __read(excludeFieldSet), false),
1502
+ modelName: config.model.modelName,
1503
+ recordLabel: recordLabel,
1504
+ request: request,
1505
+ verb: "created",
1506
+ })];
1507
+ case 1:
1508
+ _a.sent();
1509
+ if (skipOnAdminAuditHook) {
1547
1510
  return [2 /*return*/];
1548
- }
1549
- });
1550
- }); },
1551
- postDelete: function (request, value) { return __awaiter(_this, void 0, void 0, function () {
1552
- var doc, rid;
1553
- return __generator(this, function (_a) {
1554
- switch (_a.label) {
1555
- case 0:
1556
- doc = auditDocumentToPlain(value);
1557
- rid = doc._id;
1558
- return [4 /*yield*/, safeOnAdminAudit(request, {
1559
- actorId: auditActorId(request),
1560
- modelName: config.model.modelName,
1561
- recordId: rid != null ? String(rid) : undefined,
1562
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1563
- verb: "deleted",
1564
- })];
1565
- case 1:
1566
- _a.sent();
1511
+ }
1512
+ return [4 /*yield*/, safeOnAdminAudit(request, {
1513
+ actorId: auditActorId(request),
1514
+ modelName: config.model.modelName,
1515
+ recordId: rid != null ? String(rid) : undefined,
1516
+ recordLabel: recordLabel,
1517
+ verb: "created",
1518
+ })];
1519
+ case 2:
1520
+ _a.sent();
1521
+ return [2 /*return*/];
1522
+ }
1523
+ });
1524
+ }); },
1525
+ postDelete: function (request, value) { return __awaiter(_this, void 0, void 0, function () {
1526
+ var doc, rid, recordLabel;
1527
+ return __generator(this, function (_a) {
1528
+ switch (_a.label) {
1529
+ case 0:
1530
+ doc = auditDocumentToPlain(value);
1531
+ rid = doc._id;
1532
+ recordLabel = auditLabelFromListFields(doc, config.listFields);
1533
+ return [4 /*yield*/, safeFrameworkAdminAudit({
1534
+ before: value,
1535
+ extraRedact: __spreadArray(__spreadArray([], __read(hiddenFieldSet), false), __read(excludeFieldSet), false),
1536
+ modelName: config.model.modelName,
1537
+ recordLabel: recordLabel,
1538
+ request: request,
1539
+ verb: "deleted",
1540
+ })];
1541
+ case 1:
1542
+ _a.sent();
1543
+ if (skipOnAdminAuditHook) {
1567
1544
  return [2 /*return*/];
1568
- }
1569
- });
1570
- }); },
1571
- postUpdate: function (value, _cleanedBody, request, _prev) { return __awaiter(_this, void 0, void 0, function () {
1572
- var doc, rid;
1573
- return __generator(this, function (_a) {
1574
- switch (_a.label) {
1575
- case 0:
1576
- doc = auditDocumentToPlain(value);
1577
- rid = doc._id;
1578
- return [4 /*yield*/, safeOnAdminAudit(request, {
1579
- actorId: auditActorId(request),
1580
- modelName: config.model.modelName,
1581
- recordId: rid != null ? String(rid) : undefined,
1582
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1583
- verb: "updated",
1584
- })];
1585
- case 1:
1586
- _a.sent();
1545
+ }
1546
+ return [4 /*yield*/, safeOnAdminAudit(request, {
1547
+ actorId: auditActorId(request),
1548
+ modelName: config.model.modelName,
1549
+ recordId: rid != null ? String(rid) : undefined,
1550
+ recordLabel: recordLabel,
1551
+ verb: "deleted",
1552
+ })];
1553
+ case 2:
1554
+ _a.sent();
1555
+ return [2 /*return*/];
1556
+ }
1557
+ });
1558
+ }); },
1559
+ postUpdate: function (value, _cleanedBody, request, prev) { return __awaiter(_this, void 0, void 0, function () {
1560
+ var doc, rid, recordLabel;
1561
+ return __generator(this, function (_a) {
1562
+ switch (_a.label) {
1563
+ case 0:
1564
+ doc = auditDocumentToPlain(value);
1565
+ rid = doc._id;
1566
+ recordLabel = auditLabelFromListFields(doc, config.listFields);
1567
+ return [4 /*yield*/, safeFrameworkAdminAudit({
1568
+ after: value,
1569
+ before: prev,
1570
+ extraRedact: __spreadArray(__spreadArray([], __read(hiddenFieldSet), false), __read(excludeFieldSet), false),
1571
+ modelName: config.model.modelName,
1572
+ recordLabel: recordLabel,
1573
+ request: request,
1574
+ verb: "updated",
1575
+ })];
1576
+ case 1:
1577
+ _a.sent();
1578
+ if (skipOnAdminAuditHook) {
1587
1579
  return [2 /*return*/];
1588
- }
1589
- });
1590
- }); },
1591
- }
1592
- : {};
1580
+ }
1581
+ return [4 /*yield*/, safeOnAdminAudit(request, {
1582
+ actorId: auditActorId(request),
1583
+ modelName: config.model.modelName,
1584
+ recordId: rid != null ? String(rid) : undefined,
1585
+ recordLabel: recordLabel,
1586
+ verb: "updated",
1587
+ })];
1588
+ case 2:
1589
+ _a.sent();
1590
+ return [2 /*return*/];
1591
+ }
1592
+ });
1593
+ }); },
1594
+ };
1593
1595
  var assertCanWriteUserAdminFlag = function (body_1, request_1) {
1594
1596
  var args_1 = [];
1595
1597
  for (var _i = 2; _i < arguments.length; _i++) {
@@ -1724,12 +1726,12 @@ var AdminApp = /** @class */ (function () {
1724
1726
  }); };
1725
1727
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
1726
1728
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
1727
- var routerOptions = __assign(__assign(__assign(__assign(__assign({}, (openApiMw ? { openApi: openApiMw } : {})), (this_1.options.accessControl ? { accessControl: this_1.options.accessControl } : {})), { defaultLimit: (_l = config.pageSize) !== null && _l !== void 0 ? _l : 100, maxLimit: 500, permissions: {
1728
- create: adminPermission((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create, "create"),
1729
- delete: adminPermission((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.delete, "delete"),
1729
+ var routerOptions = __assign(__assign(__assign(__assign(__assign({}, (openApiMw ? { openApi: openApiMw } : {})), (this_2.options.accessControl ? { accessControl: this_2.options.accessControl } : {})), { defaultLimit: (_m = config.pageSize) !== null && _m !== void 0 ? _m : 100, maxLimit: 500, permissions: {
1730
+ create: adminPermission((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.create, "create"),
1731
+ delete: adminPermission((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.delete, "delete"),
1730
1732
  list: adminPermission(true, "list"),
1731
1733
  read: adminPermission(true, "read"),
1732
- update: adminPermission((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.update, "update"),
1734
+ update: adminPermission((_q = config.permissions) === null || _q === void 0 ? void 0 : _q.update, "update"),
1733
1735
  }, postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1734
1736
  var _a;
1735
1737
  return __generator(this, function (_b) {
@@ -1768,22 +1770,26 @@ var AdminApp = /** @class */ (function () {
1768
1770
  });
1769
1771
  }); }, preCreate: function (body, req) { return __awaiter(_this, void 0, void 0, function () {
1770
1772
  var record;
1771
- return __generator(this, function (_a) {
1772
- switch (_a.label) {
1773
+ var _a, _b;
1774
+ return __generator(this, function (_c) {
1775
+ switch (_c.label) {
1773
1776
  case 0:
1774
1777
  if (!body || typeof body !== "object") {
1775
1778
  return [2 /*return*/, body];
1776
1779
  }
1777
1780
  record = body;
1781
+ if (isOrganizationScoped) {
1782
+ record.organizationId = (_b = (_a = (0, api_1.getOrgContext)()) === null || _a === void 0 ? void 0 : _a.organization) === null || _b === void 0 ? void 0 : _b._id;
1783
+ }
1778
1784
  return [4 /*yield*/, (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), req.user, record)];
1779
1785
  case 1:
1780
- if (!(_a.sent())) {
1786
+ if (!(_c.sent())) {
1781
1787
  throw new api_1.APIError({ status: 403, title: "Admin create access denied" });
1782
1788
  }
1783
1789
  takePendingUserRoles(record, req);
1784
1790
  return [4 /*yield*/, assertCanWriteUserAdminFlag(record, req)];
1785
1791
  case 2:
1786
- _a.sent();
1792
+ _c.sent();
1787
1793
  markAuthorizedUserAdminWrite(record, req);
1788
1794
  return [2 /*return*/, stripProtectedFromBody(body)];
1789
1795
  }
@@ -1812,16 +1818,49 @@ var AdminApp = /** @class */ (function () {
1812
1818
  filters: config.filters,
1813
1819
  listDisplay: config.listDisplay,
1814
1820
  listFields: config.listFields,
1815
- searchFields: (_q = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields) !== null && _q !== void 0 ? _q : config.searchFields,
1816
- }), queryFilter: buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields), responseHandler: function (value, _method, request) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
1821
+ searchFields: (_r = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields) !== null && _r !== void 0 ? _r : config.searchFields,
1822
+ }), queryFilter: buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields, isOrganizationScoped), responseHandler: function (value, _method, request) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
1817
1823
  return [2 /*return*/, addRecordCapabilities(value, request)];
1818
- }); }); }, sort: (_r = config.defaultSort) !== null && _r !== void 0 ? _r : "-created" }), (config.populatePaths ? { populatePaths: config.populatePaths } : {})), (auditHooks.postDelete ? { postDelete: auditHooks.postDelete } : {}));
1824
+ }); }); }, sort: (_s = config.defaultSort) !== null && _s !== void 0 ? _s : "-created" }), (config.populatePaths ? { populatePaths: config.populatePaths } : {})), (auditHooks.postDelete ? { postDelete: auditHooks.postDelete } : {}));
1825
+ if (isOrganizationScoped) {
1826
+ disableOrgScopedAdminBroadcastSync(config.model.modelName);
1827
+ }
1828
+ var syncEntry = (0, api_1.findSyncEntryByModelName)(config.model.modelName);
1829
+ var adminBroadcastEnabled = (syncEntry === null || syncEntry === void 0 ? void 0 : syncEntry.config.adminBroadcast) === true;
1830
+ if (adminBroadcastEnabled) {
1831
+ (0, api_1.registerAdminBroadcastScope)(config.model.modelName, {
1832
+ listPermissions: adminPermission(true, "list"),
1833
+ queryFilter: routerOptions.queryFilter,
1834
+ readPermissions: adminPermission(true, "read"),
1835
+ });
1836
+ (0, api_1.registerAdminWindowMutationScope)(config.model.modelName, {
1837
+ accessControl: this_2.options.accessControl,
1838
+ createPermissions: adminPermission((_t = config.permissions) === null || _t === void 0 ? void 0 : _t.create, "create"),
1839
+ deletePermissions: adminPermission((_u = config.permissions) === null || _u === void 0 ? void 0 : _u.delete, "delete"),
1840
+ modelName: config.model.modelName,
1841
+ permissions: {
1842
+ create: ((_v = config.permissions) === null || _v === void 0 ? void 0 : _v.create) !== false,
1843
+ delete: ((_w = config.permissions) === null || _w === void 0 ? void 0 : _w.delete) !== false,
1844
+ update: ((_x = config.permissions) === null || _x === void 0 ? void 0 : _x.update) !== false,
1845
+ },
1846
+ postCreate: routerOptions.postCreate,
1847
+ postDelete: routerOptions.postDelete,
1848
+ postUpdate: routerOptions.postUpdate,
1849
+ preCreate: routerOptions.preCreate,
1850
+ preUpdate: routerOptions.preUpdate,
1851
+ stripMutationData: function (data) { return stripProtectedFromBody(data); },
1852
+ updatePermissions: adminPermission((_y = config.permissions) === null || _y === void 0 ? void 0 : _y.update, "update"),
1853
+ });
1854
+ }
1819
1855
  var modelBase = express_1.default.Router();
1820
- modelBase.use(validateAdminSortParam((_s = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.sortableFields) !== null && _s !== void 0 ? _s : []));
1856
+ if (isOrganizationScoped) {
1857
+ modelBase.use((0, api_1.authenticateMiddleware)(), (0, api_1.orgContextMiddleware)({ required: true }));
1858
+ }
1859
+ modelBase.use(validateAdminSortParam((_z = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.sortableFields) !== null && _z !== void 0 ? _z : []));
1821
1860
  modelBase.post.apply(modelBase, __spreadArray(__spreadArray(["/bulk-patch",
1822
1861
  (0, api_1.authenticateMiddleware)()], __read(asMiddlewareList(bulkPatchOpenApi)), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1823
- var body, ids, rawPatch, unknownKeys, patch, pendingRoles, updated, failures, actor, ids_1, ids_1_1, id, doc, previousPatch, _a, _b, key, roleError_1, err_4, message, e_18_1;
1824
- var e_18, _c, e_19, _d;
1862
+ var body, ids, rawPatch, unknownKeys, patch, pendingRoles, updated, failures, actor, ids_1, ids_1_1, id, doc, previousPatch, _a, _b, key, roleError_1, err_4, message, e_17_1;
1863
+ var e_17, _c, e_18, _d;
1825
1864
  var _e, _f;
1826
1865
  return __generator(this, function (_g) {
1827
1866
  switch (_g.label) {
@@ -1907,17 +1946,17 @@ var AdminApp = /** @class */ (function () {
1907
1946
  _g.sent();
1908
1947
  previousPatch = {};
1909
1948
  try {
1910
- for (_a = (e_19 = void 0, __values(Object.keys(patch))), _b = _a.next(); !_b.done; _b = _a.next()) {
1949
+ for (_a = (e_18 = void 0, __values(Object.keys(patch))), _b = _a.next(); !_b.done; _b = _a.next()) {
1911
1950
  key = _b.value;
1912
1951
  previousPatch[key] = doc[key];
1913
1952
  }
1914
1953
  }
1915
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
1954
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
1916
1955
  finally {
1917
1956
  try {
1918
1957
  if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1919
1958
  }
1920
- finally { if (e_19) throw e_19.error; }
1959
+ finally { if (e_18) throw e_18.error; }
1921
1960
  }
1922
1961
  if (!(Object.keys(patch).length > 0)) return [3 /*break*/, 9];
1923
1962
  return [4 /*yield*/, doc.updateOne({ $set: patch })];
@@ -1961,14 +2000,14 @@ var AdminApp = /** @class */ (function () {
1961
2000
  return [3 /*break*/, 3];
1962
2001
  case 18: return [3 /*break*/, 21];
1963
2002
  case 19:
1964
- e_18_1 = _g.sent();
1965
- e_18 = { error: e_18_1 };
2003
+ e_17_1 = _g.sent();
2004
+ e_17 = { error: e_17_1 };
1966
2005
  return [3 /*break*/, 21];
1967
2006
  case 20:
1968
2007
  try {
1969
2008
  if (ids_1_1 && !ids_1_1.done && (_c = ids_1.return)) _c.call(ids_1);
1970
2009
  }
1971
- finally { if (e_18) throw e_18.error; }
2010
+ finally { if (e_17) throw e_17.error; }
1972
2011
  return [7 /*endfinally*/];
1973
2012
  case 21: return [2 /*return*/, res.json({ failures: failures.length > 0 ? failures : undefined, updated: updated })];
1974
2013
  }
@@ -1977,7 +2016,7 @@ var AdminApp = /** @class */ (function () {
1977
2016
  modelBase.use((0, api_1.modelRouter)(config.model, routerOptions));
1978
2017
  app.use("".concat(basePath).concat(config.routePath), modelBase);
1979
2018
  };
1980
- var this_1 = this;
2019
+ var this_2 = this;
1981
2020
  try {
1982
2021
  // Mount modelRouter for each model with IsAdmin permissions
1983
2022
  for (var modelConfigs_2 = __values(modelConfigs), modelConfigs_2_1 = modelConfigs_2.next(); !modelConfigs_2_1.done; modelConfigs_2_1 = modelConfigs_2.next()) {
@@ -1993,17 +2032,22 @@ var AdminApp = /** @class */ (function () {
1993
2032
  finally { if (e_8) throw e_8.error; }
1994
2033
  }
1995
2034
  // Mount script routes
1996
- if (scriptConfigs.length > 0) {
2035
+ if (scriptConfigs.length > 0 || ((_0 = this.options.migrations) === null || _0 === void 0 ? void 0 : _0.dir)) {
1997
2036
  var scriptsRouter = express_1.default.Router();
1998
2037
  scriptsRouter.use((0, api_1.authenticateMiddleware)());
1999
2038
  this.mountScriptRoutes(scriptsRouter, scriptConfigs);
2000
2039
  app.use("".concat(basePath, "/scripts"), scriptsRouter);
2001
2040
  }
2041
+ (0, adminMigrations_1.mountAdminMigrationRoutes)(__assign(__assign({ app: app, basePath: basePath, dir: (_1 = this.options.migrations) === null || _1 === void 0 ? void 0 : _1.dir }, (openApiMw ? { openApi: openApiMw } : {})), { runPermissions: this.adminRunScriptsPermissions(), statusPermissions: this.adminAccessPermissions() }));
2002
2042
  };
2003
2043
  AdminApp.prototype.mountScriptRoutes = function (router, scripts) {
2004
2044
  var _this = this;
2005
2045
  var scriptsByName = new Map(scripts.map(function (s) { return [s.name, s]; }));
2006
2046
  var scriptNames = scripts.map(function (s) { return s.name; });
2047
+ var jobs = (0, jobs_1.tryGetJobsService)();
2048
+ if (jobs) {
2049
+ (0, adminScriptJob_1.defineAdminScriptJob)(jobs, function (name) { return scriptsByName.get(name); });
2050
+ }
2007
2051
  // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
2008
2052
  router.get("/runs", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
2009
2053
  var user, _a, limit, page, skip, requestedName, taskTypeFilter, query, _b, tasks, total, data;
@@ -2061,20 +2105,19 @@ var AdminApp = /** @class */ (function () {
2061
2105
  }); }));
2062
2106
  // POST /admin/scripts/:name/run — Execute a script
2063
2107
  router.post("/:name/run", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
2064
- var user, _a, script, isWetRun, argValues, _b, _c, _d, key, value, rawBody, bodyValues, _e, _f, _g, key, value, _h, args, argErrors, now, task, err_5, detail, ctx;
2065
- var e_20, _j, e_21, _k;
2066
- var _this = this;
2067
- var _l, _m;
2068
- return __generator(this, function (_o) {
2069
- switch (_o.label) {
2108
+ var user, _a, script, isWetRun, argValues, _b, _c, _d, key, value, rawBody, bodyValues, _e, _f, _g, key, value, _h, args, argErrors, now, queuedViaJobs, task, err_5, detail, taskId, enqueued, err_6, detail, failedAt;
2109
+ var e_19, _j, e_20, _k;
2110
+ var _l, _m, _o;
2111
+ return __generator(this, function (_p) {
2112
+ switch (_p.label) {
2070
2113
  case 0:
2071
2114
  user = req.user;
2072
2115
  _a = !user;
2073
2116
  if (_a) return [3 /*break*/, 2];
2074
2117
  return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
2075
2118
  case 1:
2076
- _a = !(_o.sent());
2077
- _o.label = 2;
2119
+ _a = !(_p.sent());
2120
+ _p.label = 2;
2078
2121
  case 2:
2079
2122
  if (_a) {
2080
2123
  throw new api_1.APIError({ status: 403, title: "Only admins can run scripts" });
@@ -2094,12 +2137,12 @@ var AdminApp = /** @class */ (function () {
2094
2137
  argValues[key] = value;
2095
2138
  }
2096
2139
  }
2097
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
2140
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
2098
2141
  finally {
2099
2142
  try {
2100
2143
  if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
2101
2144
  }
2102
- finally { if (e_20) throw e_20.error; }
2145
+ finally { if (e_19) throw e_19.error; }
2103
2146
  }
2104
2147
  rawBody = req.body && typeof req.body === "object" && !Array.isArray(req.body)
2105
2148
  ? req.body
@@ -2116,12 +2159,12 @@ var AdminApp = /** @class */ (function () {
2116
2159
  argValues[key] = value;
2117
2160
  }
2118
2161
  }
2119
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
2162
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
2120
2163
  finally {
2121
2164
  try {
2122
2165
  if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
2123
2166
  }
2124
- finally { if (e_21) throw e_21.error; }
2167
+ finally { if (e_20) throw e_20.error; }
2125
2168
  }
2126
2169
  _h = (0, api_1.createScriptArgs)({
2127
2170
  defs: (_l = script.args) !== null && _l !== void 0 ? _l : [],
@@ -2135,25 +2178,30 @@ var AdminApp = /** @class */ (function () {
2135
2178
  });
2136
2179
  }
2137
2180
  now = luxon_1.DateTime.now().toJSDate();
2138
- _o.label = 3;
2181
+ queuedViaJobs = Boolean((_m = (0, jobs_1.tryGetJobsService)()) === null || _m === void 0 ? void 0 : _m.getDefinition(adminScriptJob_1.ADMIN_SCRIPT_JOB_NAME));
2182
+ _p.label = 3;
2139
2183
  case 3:
2140
- _o.trys.push([3, 5, , 6]);
2184
+ _p.trys.push([3, 5, , 6]);
2141
2185
  return [4 /*yield*/, api_1.BackgroundTask.create({
2142
2186
  createdBy: user._id,
2143
2187
  isDryRun: !isWetRun,
2144
2188
  logs: [
2145
- { level: "info", message: "Script started by ".concat((_m = user.name) !== null && _m !== void 0 ? _m : "admin"), timestamp: now },
2189
+ { level: "info", message: "Script started by ".concat((_o = user.name) !== null && _o !== void 0 ? _o : "admin"), timestamp: now },
2146
2190
  ],
2147
- progress: { message: "Starting...", percentage: 0, stage: "Queued" },
2148
- startedAt: now,
2149
- status: "running",
2191
+ progress: {
2192
+ message: queuedViaJobs ? "Queued" : "Starting...",
2193
+ percentage: 0,
2194
+ stage: queuedViaJobs ? "Queued" : "Queued",
2195
+ },
2196
+ startedAt: queuedViaJobs ? undefined : now,
2197
+ status: queuedViaJobs ? "pending" : "running",
2150
2198
  taskType: script.name,
2151
2199
  })];
2152
2200
  case 4:
2153
- task = (_o.sent());
2201
+ task = (_p.sent());
2154
2202
  return [3 /*break*/, 6];
2155
2203
  case 5:
2156
- err_5 = _o.sent();
2204
+ err_5 = _p.sent();
2157
2205
  detail = err_5 instanceof Error ? err_5.message : String(err_5);
2158
2206
  api_1.logger.error("Failed to create background task for ".concat(script.name, ": ").concat(detail));
2159
2207
  throw new api_1.APIError({
@@ -2162,100 +2210,55 @@ var AdminApp = /** @class */ (function () {
2162
2210
  title: "Failed to create background task for script: ".concat(script.name),
2163
2211
  });
2164
2212
  case 6:
2165
- ctx = {
2166
- addLog: function (level, message) { return __awaiter(_this, void 0, void 0, function () {
2167
- var current;
2168
- return __generator(this, function (_a) {
2169
- switch (_a.label) {
2170
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2171
- case 1:
2172
- current = _a.sent();
2173
- if (!current) return [3 /*break*/, 3];
2174
- return [4 /*yield*/, current.addLog(level, message)];
2175
- case 2:
2176
- _a.sent();
2177
- _a.label = 3;
2178
- case 3: return [2 /*return*/];
2179
- }
2180
- });
2181
- }); },
2213
+ taskId = task._id.toString();
2214
+ _p.label = 7;
2215
+ case 7:
2216
+ _p.trys.push([7, 9, , 11]);
2217
+ return [4 /*yield*/, (0, adminScriptJob_1.tryEnqueueAdminScriptJob)({
2218
+ args: args.raw,
2219
+ createdByName: user.name,
2220
+ scriptName: script.name,
2221
+ taskId: taskId,
2222
+ wetRun: isWetRun,
2223
+ })];
2224
+ case 8:
2225
+ enqueued = _p.sent();
2226
+ return [3 /*break*/, 11];
2227
+ case 9:
2228
+ err_6 = _p.sent();
2229
+ detail = err_6 instanceof Error ? err_6.message : String(err_6);
2230
+ api_1.logger.error("Failed to enqueue durable job for ".concat(script.name, ": ").concat(detail));
2231
+ failedAt = luxon_1.DateTime.now().toJSDate();
2232
+ return [4 /*yield*/, api_1.BackgroundTask.updateOne({ _id: task._id }, {
2233
+ $set: {
2234
+ completedAt: failedAt,
2235
+ error: detail,
2236
+ progress: {
2237
+ message: "Failed to enqueue",
2238
+ percentage: 100,
2239
+ stage: "Failed",
2240
+ },
2241
+ status: "failed",
2242
+ },
2243
+ })];
2244
+ case 10:
2245
+ _p.sent();
2246
+ throw new api_1.APIError({
2247
+ detail: detail,
2248
+ status: 500,
2249
+ title: "Failed to enqueue script: ".concat(script.name),
2250
+ });
2251
+ case 11:
2252
+ if (enqueued) {
2253
+ return [2 /*return*/, res.status(201).json({ taskId: taskId })];
2254
+ }
2255
+ void (0, adminScriptJob_1.runRegisteredScriptTask)({
2182
2256
  args: args,
2183
- checkCancellation: function () { return __awaiter(_this, void 0, void 0, function () {
2184
- return __generator(this, function (_a) {
2185
- switch (_a.label) {
2186
- case 0: return [4 /*yield*/, api_1.BackgroundTask.checkCancellation(task._id.toString())];
2187
- case 1:
2188
- _a.sent();
2189
- return [2 /*return*/];
2190
- }
2191
- });
2192
- }); },
2193
- updateProgress: function (percentage, stage, message) { return __awaiter(_this, void 0, void 0, function () {
2194
- var current;
2195
- return __generator(this, function (_a) {
2196
- switch (_a.label) {
2197
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2198
- case 1:
2199
- current = _a.sent();
2200
- if (!current) return [3 /*break*/, 3];
2201
- return [4 /*yield*/, current.updateProgress(percentage, stage, message)];
2202
- case 2:
2203
- _a.sent();
2204
- _a.label = 3;
2205
- case 3: return [2 /*return*/];
2206
- }
2207
- });
2208
- }); },
2209
- };
2210
- // Run the script asynchronously — use atomic updates to avoid overwriting
2211
- // cancellation or other intermediate state changes.
2212
- void (function () { return __awaiter(_this, void 0, void 0, function () {
2213
- var result, err_6, message;
2214
- return __generator(this, function (_a) {
2215
- switch (_a.label) {
2216
- case 0:
2217
- _a.trys.push([0, 3, , 5]);
2218
- return [4 /*yield*/, script.runner(isWetRun, ctx)];
2219
- case 1:
2220
- result = _a.sent();
2221
- // Atomically update only if still running (don't overwrite cancellation)
2222
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2223
- $set: {
2224
- completedAt: luxon_1.DateTime.now().toJSDate(),
2225
- progress: { message: "Done", percentage: 100, stage: "Complete" },
2226
- result: result.results,
2227
- status: result.success ? "completed" : "failed",
2228
- },
2229
- })];
2230
- case 2:
2231
- // Atomically update only if still running (don't overwrite cancellation)
2232
- _a.sent();
2233
- return [3 /*break*/, 5];
2234
- case 3:
2235
- err_6 = _a.sent();
2236
- if (err_6 instanceof api_1.TaskCancelledError) {
2237
- return [2 /*return*/];
2238
- }
2239
- message = err_6 instanceof Error ? err_6.message : String(err_6);
2240
- api_1.logger.error("Script ".concat(script.name, " failed: ").concat(message));
2241
- // Atomically update only if still running
2242
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2243
- $set: {
2244
- completedAt: luxon_1.DateTime.now().toJSDate(),
2245
- error: message,
2246
- result: [message],
2247
- status: "failed",
2248
- },
2249
- })];
2250
- case 4:
2251
- // Atomically update only if still running
2252
- _a.sent();
2253
- return [3 /*break*/, 5];
2254
- case 5: return [2 /*return*/];
2255
- }
2256
- });
2257
- }); })();
2258
- return [2 /*return*/, res.status(201).json({ taskId: task._id.toString() })];
2257
+ script: script,
2258
+ taskId: taskId,
2259
+ wetRun: isWetRun,
2260
+ });
2261
+ return [2 /*return*/, res.status(201).json({ taskId: taskId })];
2259
2262
  }
2260
2263
  });
2261
2264
  }); }));
@@ -2355,6 +2358,9 @@ var AdminApp = /** @class */ (function () {
2355
2358
  title: "Task already completed or cancelled",
2356
2359
  });
2357
2360
  }
2361
+ return [4 /*yield*/, (0, adminScriptJob_1.tryCancelAdminScriptJob)(task._id.toString())];
2362
+ case 8:
2363
+ _c.sent();
2358
2364
  return [2 /*return*/, res.json({ message: "Task cancelled", task: cancelled.toObject() })];
2359
2365
  }
2360
2366
  });