@terreno/admin-backend 57.3.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 (44) hide show
  1. package/bunfig.toml +9 -1
  2. package/dist/adminApp.d.ts +20 -2
  3. package/dist/adminApp.js +468 -363
  4. package/dist/adminConfigIdentity.d.ts +1 -0
  5. package/dist/adminConfigIdentity.js +1 -0
  6. package/dist/adminMigrations.d.ts +10 -0
  7. package/dist/adminMigrations.js +205 -0
  8. package/dist/adminScriptJob.d.ts +32 -0
  9. package/dist/adminScriptJob.js +360 -0
  10. package/dist/adminTextSearch.d.ts +1 -0
  11. package/dist/adminTextSearch.js +1 -0
  12. package/dist/adminUiV2.d.ts +2 -0
  13. package/dist/aggregateAdmin.js +2 -0
  14. package/dist/enrichAdminListFilters.d.ts +7 -0
  15. package/dist/enrichAdminListFilters.js +37 -0
  16. package/dist/filterParser.js +139 -12
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +4 -1
  19. package/dist/legacy.js +4 -2
  20. package/dist/resolvedAdminModel.js +2 -1
  21. package/package.json +7 -7
  22. package/src/adminApp.migrations.test.ts +232 -0
  23. package/src/adminApp.models.test.ts +645 -1
  24. package/src/adminApp.syncMeta.test.ts +237 -0
  25. package/src/adminApp.test.ts +92 -0
  26. package/src/adminApp.ts +344 -124
  27. package/src/adminConfigIdentity.ts +1 -0
  28. package/src/adminHttpGoldens.test.ts +337 -0
  29. package/src/adminMigrations.ts +157 -0
  30. package/src/adminScriptJob.test.ts +297 -0
  31. package/src/adminScriptJob.ts +271 -0
  32. package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
  33. package/src/adminTextSearch.test.ts +28 -0
  34. package/src/adminTextSearch.ts +1 -0
  35. package/src/adminUiV2.ts +2 -0
  36. package/src/aggregateAdmin.test.ts +125 -0
  37. package/src/aggregateAdmin.ts +2 -0
  38. package/src/enrichAdminListFilters.test.ts +44 -0
  39. package/src/enrichAdminListFilters.ts +29 -0
  40. package/src/filterParser.test.ts +95 -0
  41. package/src/filterParser.ts +156 -10
  42. package/src/index.ts +2 -0
  43. package/src/legacy.ts +5 -1
  44. 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") {
@@ -388,12 +424,29 @@ var AdminApp = /** @class */ (function () {
388
424
  function AdminApp(options) {
389
425
  this.options = options;
390
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
+ };
391
438
  AdminApp.prototype.adminAccessPermissions = function () {
392
439
  if (this.options.accessControl) {
393
440
  return [this.options.accessControl.permission({ admin: [api_1.ADMIN_PAGE_ACTION] })];
394
441
  }
395
442
  return [api_1.Permissions.IsAdmin];
396
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
+ };
397
450
  AdminApp.prototype.hasScriptPermission = function (user, action) {
398
451
  return __awaiter(this, void 0, void 0, function () {
399
452
  var result;
@@ -436,8 +489,8 @@ var AdminApp = /** @class */ (function () {
436
489
  };
437
490
  AdminApp.prototype.canAnyResourceAction = function (user, resource, actions, instance) {
438
491
  return __awaiter(this, void 0, void 0, function () {
439
- var accessControl, actions_1, actions_1_1, action, result, e_5_1;
440
- var e_5, _a, _b;
492
+ var accessControl, actions_1, actions_1_1, action, result, e_6_1;
493
+ var e_6, _a, _b;
441
494
  return __generator(this, function (_c) {
442
495
  switch (_c.label) {
443
496
  case 0:
@@ -469,14 +522,14 @@ var AdminApp = /** @class */ (function () {
469
522
  return [3 /*break*/, 2];
470
523
  case 5: return [3 /*break*/, 8];
471
524
  case 6:
472
- e_5_1 = _c.sent();
473
- e_5 = { error: e_5_1 };
525
+ e_6_1 = _c.sent();
526
+ e_6 = { error: e_6_1 };
474
527
  return [3 /*break*/, 8];
475
528
  case 7:
476
529
  try {
477
530
  if (actions_1_1 && !actions_1_1.done && (_a = actions_1.return)) _a.call(actions_1);
478
531
  }
479
- finally { if (e_5) throw e_5.error; }
532
+ finally { if (e_6) throw e_6.error; }
480
533
  return [7 /*endfinally*/];
481
534
  case 8: return [2 /*return*/, false];
482
535
  }
@@ -583,9 +636,9 @@ var AdminApp = /** @class */ (function () {
583
636
  * @param app - The Express application instance to register with
584
637
  */
585
638
  AdminApp.prototype.register = function (app, openApi, terrenoApp) {
586
- var e_6, _a, e_7, _b;
639
+ var e_7, _a, e_8, _b;
587
640
  var _this = this;
588
- 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;
589
642
  var basePath = (_c = this.options.basePath) !== null && _c !== void 0 ? _c : "/admin";
590
643
  var openApiMw = openApi;
591
644
  var aggregated = (0, aggregateAdmin_1.aggregateFromTerrenoApp)({
@@ -620,6 +673,24 @@ var AdminApp = /** @class */ (function () {
620
673
  }
621
674
  });
622
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
+ }); };
623
694
  // Build config response with field metadata from Mongoose schemas
624
695
  var configNames = (0, adminConfigIdentity_1.assignUniqueAdminConfigNames)(modelConfigs.map(function (config) { return ({
625
696
  modelName: config.model.modelName,
@@ -627,7 +698,7 @@ var AdminApp = /** @class */ (function () {
627
698
  source: config.source,
628
699
  }); }));
629
700
  var configModels = modelConfigs.map(function (config, configIndex) {
630
- var e_8, _a;
701
+ var e_9, _a;
631
702
  var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
632
703
  var hiddenFieldSet = new Set((_b = config.hiddenFields) !== null && _b !== void 0 ? _b : []);
633
704
  var fields = extractFieldMetaFromDescription(config.model, __spreadArray([], __read(hiddenFieldSet), false));
@@ -641,12 +712,12 @@ var AdminApp = /** @class */ (function () {
641
712
  }
642
713
  }
643
714
  }
644
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
715
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
645
716
  finally {
646
717
  try {
647
718
  if (_s && !_s.done && (_a = _r.return)) _a.call(_r);
648
719
  }
649
- finally { if (e_8) throw e_8.error; }
720
+ finally { if (e_9) throw e_9.error; }
650
721
  }
651
722
  }
652
723
  var readonlyFields = (_c = config.readonlyFields) !== null && _c !== void 0 ? _c : [];
@@ -666,34 +737,13 @@ var AdminApp = /** @class */ (function () {
666
737
  readonlyFields: readonlyFields,
667
738
  schemaPaths: schemaPathKeys,
668
739
  });
669
- return {
670
- actions: (_g = config.actions) !== null && _g !== void 0 ? _g : [],
671
- bulkPatchAllowlist: bulkPatchAllowlist,
672
- defaultSort: (_h = config.defaultSort) !== null && _h !== void 0 ? _h : "-created",
673
- displayName: config.displayName,
674
- fieldOrder: config.fieldOrder,
675
- fields: fields,
676
- fieldsets: config.fieldsets,
677
- filters: (_j = config.filters) !== null && _j !== void 0 ? _j : [],
678
- group: config.group,
679
- hiddenFields: __spreadArray([], __read(hiddenFieldSet), false),
680
- listDisplay: listDisplay,
681
- listDisplayLinks: (_k = config.listDisplayLinks) !== null && _k !== void 0 ? _k : [],
682
- listFields: listFields,
683
- name: (_l = configNames[configIndex]) !== null && _l !== void 0 ? _l : config.model.modelName,
684
- pageSize: config.pageSize,
685
- permissions: {
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: {
686
743
  create: ((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create) !== false,
687
744
  delete: ((_o = config.permissions) === null || _o === void 0 ? void 0 : _o.delete) !== false,
688
745
  update: ((_p = config.permissions) === null || _p === void 0 ? void 0 : _p.update) !== false,
689
- },
690
- readonlyFields: readonlyFields,
691
- realtime: (_q = config.realtime) !== null && _q !== void 0 ? _q : false,
692
- recordTitleField: config.recordTitleField,
693
- routePath: "".concat(basePath).concat(config.routePath),
694
- searchFields: searchFields,
695
- sortableFields: sortableFields,
696
- };
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 } : {}));
697
747
  });
698
748
  // Build script metadata for config response
699
749
  var scriptConfigs = __spreadArray(__spreadArray([], __read(((_e = this.options.scripts) !== null && _e !== void 0 ? _e : [])), false), __read(aggregated.scripts), false);
@@ -731,8 +781,9 @@ var AdminApp = /** @class */ (function () {
731
781
  var buildAuthorizedConfig = function (user) { return __awaiter(_this, void 0, void 0, function () {
732
782
  var authorizedModels, authorizedScreens, canReadConfiguration, canReadRoles, canRunScripts, canViewScripts, canUseScripts;
733
783
  var _this = this;
734
- return __generator(this, function (_a) {
735
- switch (_a.label) {
784
+ var _a;
785
+ return __generator(this, function (_b) {
786
+ switch (_b.label) {
736
787
  case 0: return [4 /*yield*/, Promise.all(configModels.map(function (modelMeta, index) { return __awaiter(_this, void 0, void 0, function () {
737
788
  var config, canRead, canCreate, _a, canDelete, _b, canUpdate, _c;
738
789
  return __generator(this, function (_d) {
@@ -777,7 +828,7 @@ var AdminApp = /** @class */ (function () {
777
828
  });
778
829
  }); }))];
779
830
  case 1:
780
- authorizedModels = (_a.sent()).filter(function (model) { return model !== null; });
831
+ authorizedModels = (_b.sent()).filter(function (model) { return model !== null; });
781
832
  return [4 /*yield*/, Promise.all(mergedScreens.map(function (screen) { return __awaiter(_this, void 0, void 0, function () {
782
833
  var allowed_1, allowed;
783
834
  var _a, _b;
@@ -809,24 +860,24 @@ var AdminApp = /** @class */ (function () {
809
860
  });
810
861
  }); }))];
811
862
  case 2:
812
- authorizedScreens = (_a.sent()).filter(function (screen) { return screen !== null; });
863
+ authorizedScreens = (_b.sent()).filter(function (screen) { return screen !== null; });
813
864
  return [4 /*yield*/, this.hasConfigurationPermission(user, "read")];
814
865
  case 3:
815
- canReadConfiguration = _a.sent();
866
+ canReadConfiguration = _b.sent();
816
867
  return [4 /*yield*/, this.canAnyResourceAction(user, "rbac", ["read"])];
817
868
  case 4:
818
- canReadRoles = _a.sent();
869
+ canReadRoles = _b.sent();
819
870
  return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
820
871
  case 5:
821
- canRunScripts = _a.sent();
872
+ canRunScripts = _b.sent();
822
873
  return [4 /*yield*/, this.hasScriptPermission(user, "viewBackgroundTasks")];
823
874
  case 6:
824
- canViewScripts = _a.sent();
875
+ canViewScripts = _b.sent();
825
876
  canUseScripts = canRunScripts || canViewScripts;
826
877
  return [2 /*return*/, __assign(__assign({}, baseConfigResponse), { customScreens: authorizedScreens.map(function (_a) {
827
878
  var _adminAccess = _a.adminAccess, screen = __rest(_a, ["adminAccess"]);
828
879
  return screen;
829
- }), models: authorizedModels, platformTools: {
880
+ }), migrations: { enabled: Boolean((_a = this.options.migrations) === null || _a === void 0 ? void 0 : _a.dir) }, models: authorizedModels, platformTools: {
830
881
  configuration: canReadConfiguration,
831
882
  roles: canReadRoles,
832
883
  runScripts: canRunScripts,
@@ -856,6 +907,8 @@ var AdminApp = /** @class */ (function () {
856
907
  properties: {
857
908
  description: { type: "string" },
858
909
  displayName: { type: "string" },
910
+ group: { type: "string" },
911
+ icon: { type: "string" },
859
912
  name: { type: "string" },
860
913
  },
861
914
  type: "object",
@@ -1023,7 +1076,7 @@ var AdminApp = /** @class */ (function () {
1023
1076
  }); }));
1024
1077
  app.put(versionConfigPath, (0, api_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1025
1078
  var raw, allowedFields, setFields, unsetFields, allowedFields_1, allowedFields_1_1, field, updateOp, doc;
1026
- var e_9, _a;
1079
+ var e_10, _a;
1027
1080
  return __generator(this, function (_b) {
1028
1081
  switch (_b.label) {
1029
1082
  case 0: return [4 /*yield*/, this.hasConfigurationPermission(req.user, "update")];
@@ -1054,12 +1107,12 @@ var AdminApp = /** @class */ (function () {
1054
1107
  }
1055
1108
  }
1056
1109
  }
1057
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
1110
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
1058
1111
  finally {
1059
1112
  try {
1060
1113
  if (allowedFields_1_1 && !allowedFields_1_1.done && (_a = allowedFields_1.return)) _a.call(allowedFields_1);
1061
1114
  }
1062
- finally { if (e_9) throw e_9.error; }
1115
+ finally { if (e_10) throw e_10.error; }
1063
1116
  }
1064
1117
  updateOp = {};
1065
1118
  if (Object.keys(setFields).length > 0) {
@@ -1081,7 +1134,8 @@ var AdminApp = /** @class */ (function () {
1081
1134
  });
1082
1135
  }); }));
1083
1136
  var _loop_1 = function (config) {
1084
- var e_10, _t;
1137
+ var e_11, _2;
1138
+ var isOrganizationScoped = this_1.isOrganizationScoped(config);
1085
1139
  // Determine searchable fields from the actual Mongoose schema type,
1086
1140
  // not the OpenAPI type (which reports ObjectId as "string")
1087
1141
  var searchableFields = [];
@@ -1089,8 +1143,8 @@ var AdminApp = /** @class */ (function () {
1089
1143
  var modelMeta = (0, adminConfigIdentity_1.findAdminModelMetaByRoutePath)(configModels, "".concat(basePath).concat(config.routePath));
1090
1144
  if (modelMeta) {
1091
1145
  try {
1092
- for (var _u = (e_10 = void 0, __values(Object.keys(modelMeta.fields))), _v = _u.next(); !_v.done; _v = _u.next()) {
1093
- 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;
1094
1148
  var schemaPath = config.model.schema.path(key);
1095
1149
  if (schemaPath && schemaPath.instance === "String" && !modelMeta.fields[key].enum) {
1096
1150
  searchableFields.push(key);
@@ -1100,84 +1154,85 @@ var AdminApp = /** @class */ (function () {
1100
1154
  }
1101
1155
  }
1102
1156
  }
1103
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
1157
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
1104
1158
  finally {
1105
1159
  try {
1106
- if (_v && !_v.done && (_t = _u.return)) _t.call(_u);
1160
+ if (_4 && !_4.done && (_2 = _3.return)) _2.call(_3);
1107
1161
  }
1108
- finally { if (e_10) throw e_10.error; }
1162
+ finally { if (e_11) throw e_11.error; }
1109
1163
  }
1110
1164
  }
1111
- 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 () {
1112
- var q, fields, searchClause, scoped, results, err_3;
1113
- var _a;
1114
- return __generator(this, function (_b) {
1115
- switch (_b.label) {
1116
- case 0: return [4 /*yield*/, (0, api_1.checkPermissions)("list", this.resourceActionPermissions(config, "list"), req.user)];
1117
- case 1:
1118
- if (!(_b.sent())) {
1119
- throw new api_1.APIError({
1120
- disableExternalErrorTracking: true,
1121
- status: 403,
1122
- 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,
1123
1191
  });
1124
- }
1125
- q = String((_a = req.query.q) !== null && _a !== void 0 ? _a : "");
1126
- if (!q) {
1127
- return [2 /*return*/, res.json({ data: [] })];
1128
- }
1129
- fields = typeof req.query.fields === "string"
1130
- ? req.query.fields.split(",").filter(function (f) { return searchableFields.includes(f); })
1131
- : searchableFields;
1132
- searchClause = (0, adminTextSearch_1.buildAdminPartialSearchFilter)({
1133
- extraObjectIdFields: objectIdFields,
1134
- model: config.model,
1135
- q: q,
1136
- searchFields: fields,
1137
- });
1138
- if (!searchClause) {
1139
- return [2 /*return*/, res.json({ data: [] })];
1140
- }
1141
- api_1.logger.debug("Admin search query", {
1142
- fields: fields,
1143
- model: config.model.modelName,
1144
- q: q,
1145
- });
1146
- _b.label = 2;
1147
- case 2:
1148
- _b.trys.push([2, 5, , 6]);
1149
- return [4 /*yield*/, buildAdminListQueryFilter(config, modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields)(req.user, {})];
1150
- case 3:
1151
- scoped = _b.sent();
1152
- if (scoped === null) {
1153
- return [2 /*return*/, res.json({ data: [] })];
1154
- }
1155
- return [4 /*yield*/, config.model
1156
- .find({ $and: [scoped, searchClause] })
1157
- .limit(20)
1158
- .lean()];
1159
- case 4:
1160
- results = _b.sent();
1161
- api_1.logger.debug("Admin search results", {
1162
- count: results.length,
1163
- model: config.model.modelName,
1164
- });
1165
- return [2 /*return*/, res.json({
1166
- data: results.map(function (doc) { return scrubAdminResponse(doc, config, allModelAdmins); }),
1167
- })];
1168
- case 5:
1169
- err_3 = _b.sent();
1170
- api_1.logger.error("Admin search failed", {
1171
- error: err_3,
1172
- fields: fields,
1173
- model: config.model.modelName,
1174
- });
1175
- throw err_3;
1176
- case 6: return [2 /*return*/];
1177
- }
1178
- });
1179
- }); }));
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));
1180
1234
  };
1235
+ var this_1 = this;
1181
1236
  try {
1182
1237
  // Mount search endpoint for each model
1183
1238
  for (var modelConfigs_1 = __values(modelConfigs), modelConfigs_1_1 = modelConfigs_1.next(); !modelConfigs_1_1.done; modelConfigs_1_1 = modelConfigs_1.next()) {
@@ -1185,14 +1240,15 @@ var AdminApp = /** @class */ (function () {
1185
1240
  _loop_1(config);
1186
1241
  }
1187
1242
  }
1188
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
1243
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
1189
1244
  finally {
1190
1245
  try {
1191
1246
  if (modelConfigs_1_1 && !modelConfigs_1_1.done && (_a = modelConfigs_1.return)) _a.call(modelConfigs_1);
1192
1247
  }
1193
- finally { if (e_6) throw e_6.error; }
1248
+ finally { if (e_7) throw e_7.error; }
1194
1249
  }
1195
1250
  var _loop_2 = function (config) {
1251
+ var isOrganizationScoped = this_2.isOrganizationScoped(config);
1196
1252
  var hiddenFieldSet = new Set((_g = config.hiddenFields) !== null && _g !== void 0 ? _g : []);
1197
1253
  var readonlySet = new Set((_h = config.readonlyFields) !== null && _h !== void 0 ? _h : []);
1198
1254
  var excludeFieldSet = new Set((_j = config.excludeFields) !== null && _j !== void 0 ? _j : []);
@@ -1202,66 +1258,70 @@ var AdminApp = /** @class */ (function () {
1202
1258
  if (allowed === false) {
1203
1259
  return [];
1204
1260
  }
1205
- 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;
1206
1266
  };
1207
- var updatePermissions = this_1.resourceActionPermissions(config, "update");
1267
+ var updatePermissions = adminPermission((_l = config.permissions) === null || _l === void 0 ? void 0 : _l.update, "update");
1208
1268
  var stripProtectedFromBody = function (body) {
1209
- var e_11, _a, e_12, _b, e_13, _c, e_14, _d;
1269
+ var e_12, _a, e_13, _b, e_14, _c, e_15, _d;
1210
1270
  if (!body || typeof body !== "object" || Array.isArray(body)) {
1211
1271
  return {};
1212
1272
  }
1213
1273
  var next = __assign({}, body);
1214
1274
  try {
1215
- for (var readonlySet_1 = (e_11 = 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()) {
1216
1276
  var key = readonlySet_1_1.value;
1217
1277
  delete next[key];
1218
1278
  }
1219
1279
  }
1220
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
1280
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
1221
1281
  finally {
1222
1282
  try {
1223
1283
  if (readonlySet_1_1 && !readonlySet_1_1.done && (_a = readonlySet_1.return)) _a.call(readonlySet_1);
1224
1284
  }
1225
- finally { if (e_11) throw e_11.error; }
1285
+ finally { if (e_12) throw e_12.error; }
1226
1286
  }
1227
1287
  try {
1228
- for (var hiddenFieldSet_1 = (e_12 = 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()) {
1229
1289
  var key = hiddenFieldSet_1_1.value;
1230
1290
  delete next[key];
1231
1291
  }
1232
1292
  }
1233
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
1293
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
1234
1294
  finally {
1235
1295
  try {
1236
1296
  if (hiddenFieldSet_1_1 && !hiddenFieldSet_1_1.done && (_b = hiddenFieldSet_1.return)) _b.call(hiddenFieldSet_1);
1237
1297
  }
1238
- finally { if (e_12) throw e_12.error; }
1298
+ finally { if (e_13) throw e_13.error; }
1239
1299
  }
1240
1300
  try {
1241
- for (var excludeFieldSet_1 = (e_13 = 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()) {
1242
1302
  var key = excludeFieldSet_1_1.value;
1243
1303
  delete next[key];
1244
1304
  }
1245
1305
  }
1246
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
1306
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
1247
1307
  finally {
1248
1308
  try {
1249
1309
  if (excludeFieldSet_1_1 && !excludeFieldSet_1_1.done && (_c = excludeFieldSet_1.return)) _c.call(excludeFieldSet_1);
1250
1310
  }
1251
- finally { if (e_13) throw e_13.error; }
1311
+ finally { if (e_14) throw e_14.error; }
1252
1312
  }
1253
1313
  try {
1254
- for (var SYSTEM_ADMIN_FIELDS_1 = (e_14 = 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()) {
1255
1315
  var key = SYSTEM_ADMIN_FIELDS_1_1.value;
1256
1316
  delete next[key];
1257
1317
  }
1258
1318
  }
1259
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
1319
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
1260
1320
  finally {
1261
1321
  try {
1262
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);
1263
1323
  }
1264
- finally { if (e_14) throw e_14.error; }
1324
+ finally { if (e_15) throw e_15.error; }
1265
1325
  }
1266
1326
  // Self-service never writes these fields. Admin CRUD may set `admin`.
1267
1327
  // When RBAC is enabled, `roles` must go through RoleManager.assign and
@@ -1352,7 +1412,7 @@ var AdminApp = /** @class */ (function () {
1352
1412
  };
1353
1413
  var restoreUserFieldsAfterFailedRoleAssign = function (value, prev, cleanedBody) { return __awaiter(_this, void 0, void 0, function () {
1354
1414
  var record, prevRecord, body, restore, _a, _b, key;
1355
- var e_15, _c;
1415
+ var e_16, _c;
1356
1416
  return __generator(this, function (_d) {
1357
1417
  switch (_d.label) {
1358
1418
  case 0:
@@ -1378,12 +1438,12 @@ var AdminApp = /** @class */ (function () {
1378
1438
  }
1379
1439
  }
1380
1440
  }
1381
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
1441
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
1382
1442
  finally {
1383
1443
  try {
1384
1444
  if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1385
1445
  }
1386
- finally { if (e_15) throw e_15.error; }
1446
+ finally { if (e_16) throw e_16.error; }
1387
1447
  }
1388
1448
  if (Object.keys(restore).length === 0) {
1389
1449
  return [2 /*return*/];
@@ -1426,71 +1486,112 @@ var AdminApp = /** @class */ (function () {
1426
1486
  })
1427
1487
  .build()
1428
1488
  : undefined;
1429
- var auditEligible = Boolean(onAdminAudit) && config.model.modelName !== "AdminAuditLog";
1430
- var auditHooks = auditEligible
1431
- ? {
1432
- postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1433
- var doc, rid;
1434
- return __generator(this, function (_a) {
1435
- switch (_a.label) {
1436
- case 0:
1437
- doc = auditDocumentToPlain(value);
1438
- rid = doc._id;
1439
- return [4 /*yield*/, safeOnAdminAudit(request, {
1440
- actorId: auditActorId(request),
1441
- modelName: config.model.modelName,
1442
- recordId: rid != null ? String(rid) : undefined,
1443
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1444
- verb: "created",
1445
- })];
1446
- case 1:
1447
- _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) {
1448
1510
  return [2 /*return*/];
1449
- }
1450
- });
1451
- }); },
1452
- postDelete: function (request, value) { return __awaiter(_this, void 0, void 0, function () {
1453
- var doc, rid;
1454
- return __generator(this, function (_a) {
1455
- switch (_a.label) {
1456
- case 0:
1457
- doc = auditDocumentToPlain(value);
1458
- rid = doc._id;
1459
- return [4 /*yield*/, safeOnAdminAudit(request, {
1460
- actorId: auditActorId(request),
1461
- modelName: config.model.modelName,
1462
- recordId: rid != null ? String(rid) : undefined,
1463
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1464
- verb: "deleted",
1465
- })];
1466
- case 1:
1467
- _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) {
1468
1544
  return [2 /*return*/];
1469
- }
1470
- });
1471
- }); },
1472
- postUpdate: function (value, _cleanedBody, request, _prev) { return __awaiter(_this, void 0, void 0, function () {
1473
- var doc, rid;
1474
- return __generator(this, function (_a) {
1475
- switch (_a.label) {
1476
- case 0:
1477
- doc = auditDocumentToPlain(value);
1478
- rid = doc._id;
1479
- return [4 /*yield*/, safeOnAdminAudit(request, {
1480
- actorId: auditActorId(request),
1481
- modelName: config.model.modelName,
1482
- recordId: rid != null ? String(rid) : undefined,
1483
- recordLabel: auditLabelFromListFields(doc, config.listFields),
1484
- verb: "updated",
1485
- })];
1486
- case 1:
1487
- _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) {
1488
1579
  return [2 /*return*/];
1489
- }
1490
- });
1491
- }); },
1492
- }
1493
- : {};
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
+ };
1494
1595
  var assertCanWriteUserAdminFlag = function (body_1, request_1) {
1495
1596
  var args_1 = [];
1496
1597
  for (var _i = 2; _i < arguments.length; _i++) {
@@ -1625,12 +1726,12 @@ var AdminApp = /** @class */ (function () {
1625
1726
  }); };
1626
1727
  // noExplicitAny: matches the Model<any> from AdminModelConfig above.
1627
1728
  // biome-ignore lint/suspicious/noExplicitAny: matches the Model<any> from AdminModelConfig above.
1628
- 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: {
1629
- create: adminPermission((_m = config.permissions) === null || _m === void 0 ? void 0 : _m.create, "create"),
1630
- 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"),
1631
1732
  list: adminPermission(true, "list"),
1632
1733
  read: adminPermission(true, "read"),
1633
- 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"),
1634
1735
  }, postCreate: function (value, request) { return __awaiter(_this, void 0, void 0, function () {
1635
1736
  var _a;
1636
1737
  return __generator(this, function (_b) {
@@ -1669,22 +1770,26 @@ var AdminApp = /** @class */ (function () {
1669
1770
  });
1670
1771
  }); }, preCreate: function (body, req) { return __awaiter(_this, void 0, void 0, function () {
1671
1772
  var record;
1672
- return __generator(this, function (_a) {
1673
- switch (_a.label) {
1773
+ var _a, _b;
1774
+ return __generator(this, function (_c) {
1775
+ switch (_c.label) {
1674
1776
  case 0:
1675
1777
  if (!body || typeof body !== "object") {
1676
1778
  return [2 /*return*/, body];
1677
1779
  }
1678
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
+ }
1679
1784
  return [4 /*yield*/, (0, api_1.checkPermissions)("create", this.resourceActionPermissions(config, "create"), req.user, record)];
1680
1785
  case 1:
1681
- if (!(_a.sent())) {
1786
+ if (!(_c.sent())) {
1682
1787
  throw new api_1.APIError({ status: 403, title: "Admin create access denied" });
1683
1788
  }
1684
1789
  takePendingUserRoles(record, req);
1685
1790
  return [4 /*yield*/, assertCanWriteUserAdminFlag(record, req)];
1686
1791
  case 2:
1687
- _a.sent();
1792
+ _c.sent();
1688
1793
  markAuthorizedUserAdminWrite(record, req);
1689
1794
  return [2 /*return*/, stripProtectedFromBody(body)];
1690
1795
  }
@@ -1713,16 +1818,49 @@ var AdminApp = /** @class */ (function () {
1713
1818
  filters: config.filters,
1714
1819
  listDisplay: config.listDisplay,
1715
1820
  listFields: config.listFields,
1716
- searchFields: (_q = modelMeta === null || modelMeta === void 0 ? void 0 : modelMeta.searchFields) !== null && _q !== void 0 ? _q : config.searchFields,
1717
- }), 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) {
1718
1823
  return [2 /*return*/, addRecordCapabilities(value, request)];
1719
- }); }); }, 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
+ }
1720
1855
  var modelBase = express_1.default.Router();
1721
- 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 : []));
1722
1860
  modelBase.post.apply(modelBase, __spreadArray(__spreadArray(["/bulk-patch",
1723
1861
  (0, api_1.authenticateMiddleware)()], __read(asMiddlewareList(bulkPatchOpenApi)), false), [(0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1724
- 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_16_1;
1725
- var e_16, _c, e_17, _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;
1726
1864
  var _e, _f;
1727
1865
  return __generator(this, function (_g) {
1728
1866
  switch (_g.label) {
@@ -1808,17 +1946,17 @@ var AdminApp = /** @class */ (function () {
1808
1946
  _g.sent();
1809
1947
  previousPatch = {};
1810
1948
  try {
1811
- for (_a = (e_17 = 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()) {
1812
1950
  key = _b.value;
1813
1951
  previousPatch[key] = doc[key];
1814
1952
  }
1815
1953
  }
1816
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
1954
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
1817
1955
  finally {
1818
1956
  try {
1819
1957
  if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1820
1958
  }
1821
- finally { if (e_17) throw e_17.error; }
1959
+ finally { if (e_18) throw e_18.error; }
1822
1960
  }
1823
1961
  if (!(Object.keys(patch).length > 0)) return [3 /*break*/, 9];
1824
1962
  return [4 /*yield*/, doc.updateOne({ $set: patch })];
@@ -1862,14 +2000,14 @@ var AdminApp = /** @class */ (function () {
1862
2000
  return [3 /*break*/, 3];
1863
2001
  case 18: return [3 /*break*/, 21];
1864
2002
  case 19:
1865
- e_16_1 = _g.sent();
1866
- e_16 = { error: e_16_1 };
2003
+ e_17_1 = _g.sent();
2004
+ e_17 = { error: e_17_1 };
1867
2005
  return [3 /*break*/, 21];
1868
2006
  case 20:
1869
2007
  try {
1870
2008
  if (ids_1_1 && !ids_1_1.done && (_c = ids_1.return)) _c.call(ids_1);
1871
2009
  }
1872
- finally { if (e_16) throw e_16.error; }
2010
+ finally { if (e_17) throw e_17.error; }
1873
2011
  return [7 /*endfinally*/];
1874
2012
  case 21: return [2 /*return*/, res.json({ failures: failures.length > 0 ? failures : undefined, updated: updated })];
1875
2013
  }
@@ -1878,7 +2016,7 @@ var AdminApp = /** @class */ (function () {
1878
2016
  modelBase.use((0, api_1.modelRouter)(config.model, routerOptions));
1879
2017
  app.use("".concat(basePath).concat(config.routePath), modelBase);
1880
2018
  };
1881
- var this_1 = this;
2019
+ var this_2 = this;
1882
2020
  try {
1883
2021
  // Mount modelRouter for each model with IsAdmin permissions
1884
2022
  for (var modelConfigs_2 = __values(modelConfigs), modelConfigs_2_1 = modelConfigs_2.next(); !modelConfigs_2_1.done; modelConfigs_2_1 = modelConfigs_2.next()) {
@@ -1886,25 +2024,30 @@ var AdminApp = /** @class */ (function () {
1886
2024
  _loop_2(config);
1887
2025
  }
1888
2026
  }
1889
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
2027
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
1890
2028
  finally {
1891
2029
  try {
1892
2030
  if (modelConfigs_2_1 && !modelConfigs_2_1.done && (_b = modelConfigs_2.return)) _b.call(modelConfigs_2);
1893
2031
  }
1894
- finally { if (e_7) throw e_7.error; }
2032
+ finally { if (e_8) throw e_8.error; }
1895
2033
  }
1896
2034
  // Mount script routes
1897
- if (scriptConfigs.length > 0) {
2035
+ if (scriptConfigs.length > 0 || ((_0 = this.options.migrations) === null || _0 === void 0 ? void 0 : _0.dir)) {
1898
2036
  var scriptsRouter = express_1.default.Router();
1899
2037
  scriptsRouter.use((0, api_1.authenticateMiddleware)());
1900
2038
  this.mountScriptRoutes(scriptsRouter, scriptConfigs);
1901
2039
  app.use("".concat(basePath, "/scripts"), scriptsRouter);
1902
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() }));
1903
2042
  };
1904
2043
  AdminApp.prototype.mountScriptRoutes = function (router, scripts) {
1905
2044
  var _this = this;
1906
2045
  var scriptsByName = new Map(scripts.map(function (s) { return [s.name, s]; }));
1907
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
+ }
1908
2051
  // GET /admin/scripts/runs — Paginated history of script runs (BackgroundTasks)
1909
2052
  router.get("/runs", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1910
2053
  var user, _a, limit, page, skip, requestedName, taskTypeFilter, query, _b, tasks, total, data;
@@ -1962,20 +2105,19 @@ var AdminApp = /** @class */ (function () {
1962
2105
  }); }));
1963
2106
  // POST /admin/scripts/:name/run — Execute a script
1964
2107
  router.post("/:name/run", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
1965
- 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;
1966
- var e_18, _j, e_19, _k;
1967
- var _this = this;
1968
- var _l, _m;
1969
- return __generator(this, function (_o) {
1970
- 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) {
1971
2113
  case 0:
1972
2114
  user = req.user;
1973
2115
  _a = !user;
1974
2116
  if (_a) return [3 /*break*/, 2];
1975
2117
  return [4 /*yield*/, this.hasScriptPermission(user, "runScripts")];
1976
2118
  case 1:
1977
- _a = !(_o.sent());
1978
- _o.label = 2;
2119
+ _a = !(_p.sent());
2120
+ _p.label = 2;
1979
2121
  case 2:
1980
2122
  if (_a) {
1981
2123
  throw new api_1.APIError({ status: 403, title: "Only admins can run scripts" });
@@ -1995,12 +2137,12 @@ var AdminApp = /** @class */ (function () {
1995
2137
  argValues[key] = value;
1996
2138
  }
1997
2139
  }
1998
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
2140
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
1999
2141
  finally {
2000
2142
  try {
2001
2143
  if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
2002
2144
  }
2003
- finally { if (e_18) throw e_18.error; }
2145
+ finally { if (e_19) throw e_19.error; }
2004
2146
  }
2005
2147
  rawBody = req.body && typeof req.body === "object" && !Array.isArray(req.body)
2006
2148
  ? req.body
@@ -2017,12 +2159,12 @@ var AdminApp = /** @class */ (function () {
2017
2159
  argValues[key] = value;
2018
2160
  }
2019
2161
  }
2020
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
2162
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
2021
2163
  finally {
2022
2164
  try {
2023
2165
  if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
2024
2166
  }
2025
- finally { if (e_19) throw e_19.error; }
2167
+ finally { if (e_20) throw e_20.error; }
2026
2168
  }
2027
2169
  _h = (0, api_1.createScriptArgs)({
2028
2170
  defs: (_l = script.args) !== null && _l !== void 0 ? _l : [],
@@ -2036,25 +2178,30 @@ var AdminApp = /** @class */ (function () {
2036
2178
  });
2037
2179
  }
2038
2180
  now = luxon_1.DateTime.now().toJSDate();
2039
- _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;
2040
2183
  case 3:
2041
- _o.trys.push([3, 5, , 6]);
2184
+ _p.trys.push([3, 5, , 6]);
2042
2185
  return [4 /*yield*/, api_1.BackgroundTask.create({
2043
2186
  createdBy: user._id,
2044
2187
  isDryRun: !isWetRun,
2045
2188
  logs: [
2046
- { 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 },
2047
2190
  ],
2048
- progress: { message: "Starting...", percentage: 0, stage: "Queued" },
2049
- startedAt: now,
2050
- 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",
2051
2198
  taskType: script.name,
2052
2199
  })];
2053
2200
  case 4:
2054
- task = (_o.sent());
2201
+ task = (_p.sent());
2055
2202
  return [3 /*break*/, 6];
2056
2203
  case 5:
2057
- err_5 = _o.sent();
2204
+ err_5 = _p.sent();
2058
2205
  detail = err_5 instanceof Error ? err_5.message : String(err_5);
2059
2206
  api_1.logger.error("Failed to create background task for ".concat(script.name, ": ").concat(detail));
2060
2207
  throw new api_1.APIError({
@@ -2063,100 +2210,55 @@ var AdminApp = /** @class */ (function () {
2063
2210
  title: "Failed to create background task for script: ".concat(script.name),
2064
2211
  });
2065
2212
  case 6:
2066
- ctx = {
2067
- addLog: function (level, message) { return __awaiter(_this, void 0, void 0, function () {
2068
- var current;
2069
- return __generator(this, function (_a) {
2070
- switch (_a.label) {
2071
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2072
- case 1:
2073
- current = _a.sent();
2074
- if (!current) return [3 /*break*/, 3];
2075
- return [4 /*yield*/, current.addLog(level, message)];
2076
- case 2:
2077
- _a.sent();
2078
- _a.label = 3;
2079
- case 3: return [2 /*return*/];
2080
- }
2081
- });
2082
- }); },
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)({
2083
2256
  args: args,
2084
- checkCancellation: function () { return __awaiter(_this, void 0, void 0, function () {
2085
- return __generator(this, function (_a) {
2086
- switch (_a.label) {
2087
- case 0: return [4 /*yield*/, api_1.BackgroundTask.checkCancellation(task._id.toString())];
2088
- case 1:
2089
- _a.sent();
2090
- return [2 /*return*/];
2091
- }
2092
- });
2093
- }); },
2094
- updateProgress: function (percentage, stage, message) { return __awaiter(_this, void 0, void 0, function () {
2095
- var current;
2096
- return __generator(this, function (_a) {
2097
- switch (_a.label) {
2098
- case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
2099
- case 1:
2100
- current = _a.sent();
2101
- if (!current) return [3 /*break*/, 3];
2102
- return [4 /*yield*/, current.updateProgress(percentage, stage, message)];
2103
- case 2:
2104
- _a.sent();
2105
- _a.label = 3;
2106
- case 3: return [2 /*return*/];
2107
- }
2108
- });
2109
- }); },
2110
- };
2111
- // Run the script asynchronously — use atomic updates to avoid overwriting
2112
- // cancellation or other intermediate state changes.
2113
- void (function () { return __awaiter(_this, void 0, void 0, function () {
2114
- var result, err_6, message;
2115
- return __generator(this, function (_a) {
2116
- switch (_a.label) {
2117
- case 0:
2118
- _a.trys.push([0, 3, , 5]);
2119
- return [4 /*yield*/, script.runner(isWetRun, ctx)];
2120
- case 1:
2121
- result = _a.sent();
2122
- // Atomically update only if still running (don't overwrite cancellation)
2123
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2124
- $set: {
2125
- completedAt: luxon_1.DateTime.now().toJSDate(),
2126
- progress: { message: "Done", percentage: 100, stage: "Complete" },
2127
- result: result.results,
2128
- status: result.success ? "completed" : "failed",
2129
- },
2130
- })];
2131
- case 2:
2132
- // Atomically update only if still running (don't overwrite cancellation)
2133
- _a.sent();
2134
- return [3 /*break*/, 5];
2135
- case 3:
2136
- err_6 = _a.sent();
2137
- if (err_6 instanceof api_1.TaskCancelledError) {
2138
- return [2 /*return*/];
2139
- }
2140
- message = err_6 instanceof Error ? err_6.message : String(err_6);
2141
- api_1.logger.error("Script ".concat(script.name, " failed: ").concat(message));
2142
- // Atomically update only if still running
2143
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
2144
- $set: {
2145
- completedAt: luxon_1.DateTime.now().toJSDate(),
2146
- error: message,
2147
- result: [message],
2148
- status: "failed",
2149
- },
2150
- })];
2151
- case 4:
2152
- // Atomically update only if still running
2153
- _a.sent();
2154
- return [3 /*break*/, 5];
2155
- case 5: return [2 /*return*/];
2156
- }
2157
- });
2158
- }); })();
2159
- 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 })];
2160
2262
  }
2161
2263
  });
2162
2264
  }); }));
@@ -2256,6 +2358,9 @@ var AdminApp = /** @class */ (function () {
2256
2358
  title: "Task already completed or cancelled",
2257
2359
  });
2258
2360
  }
2361
+ return [4 /*yield*/, (0, adminScriptJob_1.tryCancelAdminScriptJob)(task._id.toString())];
2362
+ case 8:
2363
+ _c.sent();
2259
2364
  return [2 /*return*/, res.json({ message: "Task cancelled", task: cancelled.toObject() })];
2260
2365
  }
2261
2366
  });