@terreno/admin-backend 57.4.0 → 57.6.1

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.
@@ -1,32 +1,21 @@
1
1
  "use strict";
2
- var __values = (this && this.__values) || function(o) {
3
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
- if (m) return m.call(o);
5
- if (o && typeof o.length === "number") return {
6
- next: function () {
7
- if (o && i >= o.length) o = void 0;
8
- return { value: o && o[i++], done: !o };
9
- }
10
- };
11
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.findAdminModelMetaByRoutePath = exports.assignUniqueAdminConfigNames = exports.slugFromAdminRoutePath = void 0;
15
- var SOURCE_RANK = {
4
+ const SOURCE_RANK = {
16
5
  legacy: 0,
17
6
  plugin: 1,
18
7
  registered: 2,
19
8
  };
20
9
  /** @internal */
21
- var slugFromAdminRoutePath = function (routePath) {
22
- var trimmed = routePath.replace(/^\/+|\/+$/g, "").replace(/\//g, "-");
10
+ const slugFromAdminRoutePath = (routePath) => {
11
+ const trimmed = routePath.replace(/^\/+|\/+$/g, "").replace(/\//g, "-");
23
12
  if (!trimmed) {
24
13
  return "model";
25
14
  }
26
15
  return trimmed;
27
16
  };
28
17
  exports.slugFromAdminRoutePath = slugFromAdminRoutePath;
29
- var sourceRank = function (source) {
18
+ const sourceRank = (source) => {
30
19
  if (!source) {
31
20
  return 0;
32
21
  }
@@ -37,35 +26,23 @@ var sourceRank = function (source) {
37
26
  * two `routePath`s. Keep `modelName` for a singleton (and for the highest-precedence
38
27
  * duplicate). Suffix the rest with the route slug.
39
28
  */
40
- var assignUniqueAdminConfigNames = function (entries) {
41
- var e_1, _a;
42
- var _b, _c;
43
- var counts = new Map();
44
- try {
45
- for (var entries_1 = __values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
46
- var entry = entries_1_1.value;
47
- counts.set(entry.modelName, ((_b = counts.get(entry.modelName)) !== null && _b !== void 0 ? _b : 0) + 1);
48
- }
49
- }
50
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
51
- finally {
52
- try {
53
- if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
54
- }
55
- finally { if (e_1) throw e_1.error; }
29
+ const assignUniqueAdminConfigNames = (entries) => {
30
+ const counts = new Map();
31
+ for (const entry of entries) {
32
+ counts.set(entry.modelName, (counts.get(entry.modelName) ?? 0) + 1);
56
33
  }
57
- var preferredIndex = new Map();
58
- for (var index = 0; index < entries.length; index += 1) {
59
- var entry = entries[index];
60
- if (!entry || ((_c = counts.get(entry.modelName)) !== null && _c !== void 0 ? _c : 0) <= 1) {
34
+ const preferredIndex = new Map();
35
+ for (let index = 0; index < entries.length; index += 1) {
36
+ const entry = entries[index];
37
+ if (!entry || (counts.get(entry.modelName) ?? 0) <= 1) {
61
38
  continue;
62
39
  }
63
- var existing = preferredIndex.get(entry.modelName);
40
+ const existing = preferredIndex.get(entry.modelName);
64
41
  if (existing === undefined) {
65
42
  preferredIndex.set(entry.modelName, index);
66
43
  continue;
67
44
  }
68
- var current = entries[existing];
45
+ const current = entries[existing];
69
46
  if (!current) {
70
47
  preferredIndex.set(entry.modelName, index);
71
48
  continue;
@@ -74,28 +51,27 @@ var assignUniqueAdminConfigNames = function (entries) {
74
51
  preferredIndex.set(entry.modelName, index);
75
52
  }
76
53
  }
77
- var used = new Set();
78
- return entries.map(function (entry, index) {
79
- var _a;
80
- var isDuplicate = ((_a = counts.get(entry.modelName)) !== null && _a !== void 0 ? _a : 0) > 1;
81
- var keepBare = !isDuplicate || preferredIndex.get(entry.modelName) === index;
82
- var candidate = keepBare
54
+ const used = new Set();
55
+ return entries.map((entry, index) => {
56
+ const isDuplicate = (counts.get(entry.modelName) ?? 0) > 1;
57
+ const keepBare = !isDuplicate || preferredIndex.get(entry.modelName) === index;
58
+ let candidate = keepBare
83
59
  ? entry.modelName
84
- : "".concat(entry.modelName, "-").concat((0, exports.slugFromAdminRoutePath)(entry.routePath));
60
+ : `${entry.modelName}-${(0, exports.slugFromAdminRoutePath)(entry.routePath)}`;
85
61
  if (used.has(candidate)) {
86
- var base = candidate;
87
- var suffix = 2;
88
- while (used.has("".concat(base, "-").concat(suffix))) {
62
+ const base = candidate;
63
+ let suffix = 2;
64
+ while (used.has(`${base}-${suffix}`)) {
89
65
  suffix += 1;
90
66
  }
91
- candidate = "".concat(base, "-").concat(suffix);
67
+ candidate = `${base}-${suffix}`;
92
68
  }
93
69
  used.add(candidate);
94
70
  return candidate;
95
71
  });
96
72
  };
97
73
  exports.assignUniqueAdminConfigNames = assignUniqueAdminConfigNames;
98
- var findAdminModelMetaByRoutePath = function (models, mountedRoutePath) {
99
- return models.find(function (model) { return model.routePath === mountedRoutePath; });
74
+ const findAdminModelMetaByRoutePath = (models, mountedRoutePath) => {
75
+ return models.find((model) => model.routePath === mountedRoutePath);
100
76
  };
101
77
  exports.findAdminModelMetaByRoutePath = findAdminModelMetaByRoutePath;
@@ -1,176 +1,97 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
50
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
4
  };
52
5
  Object.defineProperty(exports, "__esModule", { value: true });
53
6
  exports.mountAdminMigrationRoutes = void 0;
54
- var api_1 = require("@terreno/api");
55
- var luxon_1 = require("luxon");
56
- var mongoose_1 = __importDefault(require("mongoose"));
57
- var DISABLED_CRUD = {
7
+ const api_1 = require("@terreno/api");
8
+ const luxon_1 = require("luxon");
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ const DISABLED_CRUD = {
58
11
  create: [],
59
12
  delete: [],
60
13
  list: [],
61
14
  read: [],
62
15
  update: [],
63
16
  };
64
- var runQuerySchema = api_1.z.object({
17
+ const runQuerySchema = api_1.z.object({
65
18
  wetRun: api_1.z.enum(["true", "false"]).optional(),
66
19
  });
67
- var mountAdminMigrationRoutes = function (_a) {
68
- var app = _a.app, basePath = _a.basePath, dir = _a.dir, openApi = _a.openApi, runPermissions = _a.runPermissions, statusPermissions = _a.statusPermissions;
69
- var requireDir = function () {
20
+ const mountAdminMigrationRoutes = ({ app, basePath, dir, openApi, runPermissions, statusPermissions, }) => {
21
+ const requireDir = () => {
70
22
  if (!dir) {
71
23
  throw new api_1.APIError({ status: 404, title: "Migrations are not configured" });
72
24
  }
73
25
  return dir;
74
26
  };
75
- app.use("".concat(basePath, "/migrations"), (0, api_1.modelRouter)(api_1.BackgroundTask, __assign(__assign({}, (openApi ? { openApi: openApi } : {})), { collectionActions: {
27
+ app.use(`${basePath}/migrations`, (0, api_1.modelRouter)(api_1.BackgroundTask, {
28
+ ...(openApi ? { openApi } : {}),
29
+ collectionActions: {
76
30
  run: {
77
- handler: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
78
- var actor, migrationsDir, isWetRun, now, task;
79
- var _c;
80
- var query = _b.query, user = _b.user;
81
- return __generator(this, function (_d) {
82
- switch (_d.label) {
83
- case 0:
84
- actor = user;
85
- if (!actor) {
86
- throw new api_1.APIError({ status: 403, title: "Admin access required" });
87
- }
88
- migrationsDir = requireDir();
89
- isWetRun = query.wetRun === "true";
90
- (0, api_1.assertMigrationsAllowed)({
91
- allowEnv: process.env.ALLOW_MIGRATIONS === "true",
92
- dryRun: !isWetRun,
93
- force: true,
94
- isProduction: process.env.NODE_ENV === "production",
95
- });
96
- now = luxon_1.DateTime.now().toJSDate();
97
- return [4 /*yield*/, api_1.BackgroundTask.create({
98
- createdBy: actor._id,
99
- isDryRun: !isWetRun,
100
- logs: [
101
- {
102
- level: "info",
103
- message: "Migrations ".concat(isWetRun ? "apply" : "dry-run", " started by ").concat((_c = actor.name) !== null && _c !== void 0 ? _c : "admin"),
104
- timestamp: now,
105
- },
106
- ],
107
- progress: { message: "Starting...", percentage: 0, stage: "Queued" },
108
- startedAt: now,
109
- status: "running",
110
- taskType: "migrations:up",
111
- })];
112
- case 1:
113
- task = (_d.sent());
114
- void (function () { return __awaiter(void 0, void 0, void 0, function () {
115
- var migrations, result, error_1, detail;
116
- return __generator(this, function (_a) {
117
- switch (_a.label) {
118
- case 0:
119
- _a.trys.push([0, 4, , 6]);
120
- return [4 /*yield*/, (0, api_1.checkMigrationFiles)({ dir: migrationsDir })];
121
- case 1:
122
- migrations = _a.sent();
123
- return [4 /*yield*/, (0, api_1.runMigrations)({
124
- checkCancellation: function () { return __awaiter(void 0, void 0, void 0, function () {
125
- return __generator(this, function (_a) {
126
- switch (_a.label) {
127
- case 0: return [4 /*yield*/, api_1.BackgroundTask.checkCancellation(task._id.toString())];
128
- case 1:
129
- _a.sent();
130
- return [2 /*return*/];
131
- }
132
- });
133
- }); },
134
- connection: mongoose_1.default.connection,
135
- dryRun: !isWetRun,
136
- migrations: migrations,
137
- mongoose: mongoose_1.default,
138
- })];
139
- case 2:
140
- result = _a.sent();
141
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
142
- $set: {
143
- completedAt: luxon_1.DateTime.now().toJSDate(),
144
- progress: { message: "Done", percentage: 100, stage: "Complete" },
145
- result: result.applied,
146
- status: "completed",
147
- },
148
- })];
149
- case 3:
150
- _a.sent();
151
- return [3 /*break*/, 6];
152
- case 4:
153
- error_1 = _a.sent();
154
- detail = error_1 instanceof Error ? error_1.message : String(error_1);
155
- api_1.logger.error("Admin migrations run failed: ".concat(detail));
156
- return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
157
- $set: {
158
- completedAt: luxon_1.DateTime.now().toJSDate(),
159
- error: detail,
160
- status: "failed",
161
- },
162
- })];
163
- case 5:
164
- _a.sent();
165
- return [3 /*break*/, 6];
166
- case 6: return [2 /*return*/];
167
- }
168
- });
169
- }); })();
170
- return [2 /*return*/, { taskId: task._id.toString() }];
171
- }
31
+ handler: async ({ query, user }) => {
32
+ const actor = user;
33
+ if (!actor) {
34
+ throw new api_1.APIError({ status: 403, title: "Admin access required" });
35
+ }
36
+ const migrationsDir = requireDir();
37
+ const isWetRun = query.wetRun === "true";
38
+ (0, api_1.assertMigrationsAllowed)({
39
+ allowEnv: process.env.ALLOW_MIGRATIONS === "true",
40
+ dryRun: !isWetRun,
41
+ force: true,
42
+ isProduction: process.env.NODE_ENV === "production",
172
43
  });
173
- }); },
44
+ const now = luxon_1.DateTime.now().toJSDate();
45
+ const task = (await api_1.BackgroundTask.create({
46
+ createdBy: actor._id,
47
+ isDryRun: !isWetRun,
48
+ logs: [
49
+ {
50
+ level: "info",
51
+ message: `Migrations ${isWetRun ? "apply" : "dry-run"} started by ${actor.name ?? "admin"}`,
52
+ timestamp: now,
53
+ },
54
+ ],
55
+ progress: { message: "Starting...", percentage: 0, stage: "Queued" },
56
+ startedAt: now,
57
+ status: "running",
58
+ taskType: "migrations:up",
59
+ }));
60
+ void (async () => {
61
+ try {
62
+ const migrations = await (0, api_1.checkMigrationFiles)({ dir: migrationsDir });
63
+ const result = await (0, api_1.runMigrations)({
64
+ checkCancellation: async () => {
65
+ await api_1.BackgroundTask.checkCancellation(task._id.toString());
66
+ },
67
+ connection: mongoose_1.default.connection,
68
+ dryRun: !isWetRun,
69
+ migrations,
70
+ mongoose: mongoose_1.default,
71
+ });
72
+ await api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
73
+ $set: {
74
+ completedAt: luxon_1.DateTime.now().toJSDate(),
75
+ progress: { message: "Done", percentage: 100, stage: "Complete" },
76
+ result: result.applied,
77
+ status: "completed",
78
+ },
79
+ });
80
+ }
81
+ catch (error) {
82
+ const detail = error instanceof Error ? error.message : String(error);
83
+ api_1.logger.error(`Admin migrations run failed: ${detail}`);
84
+ await api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
85
+ $set: {
86
+ completedAt: luxon_1.DateTime.now().toJSDate(),
87
+ error: detail,
88
+ status: "failed",
89
+ },
90
+ });
91
+ }
92
+ })();
93
+ return { taskId: task._id.toString() };
94
+ },
174
95
  method: "POST",
175
96
  permissions: runPermissions,
176
97
  query: runQuerySchema,
@@ -179,27 +100,21 @@ var mountAdminMigrationRoutes = function (_a) {
179
100
  tag: "adminMigrations",
180
101
  },
181
102
  status: {
182
- handler: function () { return __awaiter(void 0, void 0, void 0, function () {
183
- var migrationsDir, migrations;
184
- return __generator(this, function (_a) {
185
- switch (_a.label) {
186
- case 0:
187
- migrationsDir = requireDir();
188
- return [4 /*yield*/, (0, api_1.checkMigrationFiles)({ dir: migrationsDir })];
189
- case 1:
190
- migrations = _a.sent();
191
- return [2 /*return*/, (0, api_1.getMigrationStatus)({
192
- connection: mongoose_1.default.connection,
193
- migrations: migrations,
194
- })];
195
- }
103
+ handler: async () => {
104
+ const migrationsDir = requireDir();
105
+ const migrations = await (0, api_1.checkMigrationFiles)({ dir: migrationsDir });
106
+ return (0, api_1.getMigrationStatus)({
107
+ connection: mongoose_1.default.connection,
108
+ migrations,
196
109
  });
197
- }); },
110
+ },
198
111
  method: "GET",
199
112
  permissions: statusPermissions,
200
113
  summary: "List applied and pending MongoDB migrations",
201
114
  tag: "adminMigrations",
202
115
  },
203
- }, permissions: DISABLED_CRUD })));
116
+ },
117
+ permissions: DISABLED_CRUD,
118
+ }));
204
119
  };
205
120
  exports.mountAdminMigrationRoutes = mountAdminMigrationRoutes;