@terreno/admin-backend 57.3.0 → 57.6.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.
- package/README.md +3 -3
- package/bunfig.toml +9 -1
- package/dist/adminApp.d.ts +20 -2
- package/dist/adminApp.js +1261 -1873
- package/dist/adminConfigIdentity.d.ts +1 -0
- package/dist/adminConfigIdentity.js +27 -50
- package/dist/adminMigrations.d.ts +10 -0
- package/dist/adminMigrations.js +120 -0
- package/dist/adminScriptJob.d.ts +32 -0
- package/dist/adminScriptJob.js +202 -0
- package/dist/adminTextSearch.d.ts +1 -0
- package/dist/adminTextSearch.js +22 -78
- package/dist/adminUiV2.d.ts +2 -0
- package/dist/adminUiV2.js +49 -146
- package/dist/aggregateAdmin.js +104 -227
- package/dist/documentStorageApp.js +184 -325
- package/dist/enrichAdminListFilters.d.ts +7 -0
- package/dist/enrichAdminListFilters.js +26 -0
- package/dist/filterParser.js +230 -183
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -1
- package/dist/legacy.js +21 -23
- package/dist/resolvedAdminModel.js +23 -78
- package/dist/routePath.js +3 -3
- package/dist/scriptCli.js +161 -307
- package/dist/tests/bunSetup.js +1 -1
- package/package.json +10 -10
- package/src/adminApp.migrations.test.ts +232 -0
- package/src/adminApp.models.test.ts +731 -1
- package/src/adminApp.syncMeta.test.ts +237 -0
- package/src/adminApp.test.ts +92 -0
- package/src/adminApp.ts +373 -130
- package/src/adminConfigIdentity.ts +1 -0
- package/src/adminHttpGoldens.test.ts +337 -0
- package/src/adminMigrations.ts +157 -0
- package/src/adminScriptJob.test.ts +297 -0
- package/src/adminScriptJob.ts +271 -0
- package/src/adminSyncMutationAuthMismatch.test.ts +650 -0
- package/src/adminTextSearch.test.ts +28 -0
- package/src/adminTextSearch.ts +1 -0
- package/src/adminUiV2.ts +2 -0
- package/src/aggregateAdmin.test.ts +125 -0
- package/src/aggregateAdmin.ts +2 -0
- package/src/enrichAdminListFilters.test.ts +44 -0
- package/src/enrichAdminListFilters.ts +29 -0
- package/src/filterParser.test.ts +95 -0
- package/src/filterParser.ts +156 -10
- package/src/index.ts +2 -0
- package/src/legacy.ts +5 -1
- package/src/resolvedAdminModel.ts +2 -1
- package/tsconfig.json +6 -21
|
@@ -4,6 +4,7 @@ export interface AdminConfigNameInput {
|
|
|
4
4
|
routePath: string;
|
|
5
5
|
source?: AdminModelSource;
|
|
6
6
|
}
|
|
7
|
+
/** @internal */
|
|
7
8
|
export declare const slugFromAdminRoutePath: (routePath: string) => string;
|
|
8
9
|
/**
|
|
9
10
|
* UI route keys must be unique even when the same Mongoose model is mounted at
|
|
@@ -1,31 +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
|
-
|
|
4
|
+
const SOURCE_RANK = {
|
|
16
5
|
legacy: 0,
|
|
17
6
|
plugin: 1,
|
|
18
7
|
registered: 2,
|
|
19
8
|
};
|
|
20
|
-
|
|
21
|
-
|
|
9
|
+
/** @internal */
|
|
10
|
+
const slugFromAdminRoutePath = (routePath) => {
|
|
11
|
+
const trimmed = routePath.replace(/^\/+|\/+$/g, "").replace(/\//g, "-");
|
|
22
12
|
if (!trimmed) {
|
|
23
13
|
return "model";
|
|
24
14
|
}
|
|
25
15
|
return trimmed;
|
|
26
16
|
};
|
|
27
17
|
exports.slugFromAdminRoutePath = slugFromAdminRoutePath;
|
|
28
|
-
|
|
18
|
+
const sourceRank = (source) => {
|
|
29
19
|
if (!source) {
|
|
30
20
|
return 0;
|
|
31
21
|
}
|
|
@@ -36,35 +26,23 @@ var sourceRank = function (source) {
|
|
|
36
26
|
* two `routePath`s. Keep `modelName` for a singleton (and for the highest-precedence
|
|
37
27
|
* duplicate). Suffix the rest with the route slug.
|
|
38
28
|
*/
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
try {
|
|
44
|
-
for (var entries_1 = __values(entries), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
|
|
45
|
-
var entry = entries_1_1.value;
|
|
46
|
-
counts.set(entry.modelName, ((_b = counts.get(entry.modelName)) !== null && _b !== void 0 ? _b : 0) + 1);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
50
|
-
finally {
|
|
51
|
-
try {
|
|
52
|
-
if (entries_1_1 && !entries_1_1.done && (_a = entries_1.return)) _a.call(entries_1);
|
|
53
|
-
}
|
|
54
|
-
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);
|
|
55
33
|
}
|
|
56
|
-
|
|
57
|
-
for (
|
|
58
|
-
|
|
59
|
-
if (!entry || (
|
|
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) {
|
|
60
38
|
continue;
|
|
61
39
|
}
|
|
62
|
-
|
|
40
|
+
const existing = preferredIndex.get(entry.modelName);
|
|
63
41
|
if (existing === undefined) {
|
|
64
42
|
preferredIndex.set(entry.modelName, index);
|
|
65
43
|
continue;
|
|
66
44
|
}
|
|
67
|
-
|
|
45
|
+
const current = entries[existing];
|
|
68
46
|
if (!current) {
|
|
69
47
|
preferredIndex.set(entry.modelName, index);
|
|
70
48
|
continue;
|
|
@@ -73,28 +51,27 @@ var assignUniqueAdminConfigNames = function (entries) {
|
|
|
73
51
|
preferredIndex.set(entry.modelName, index);
|
|
74
52
|
}
|
|
75
53
|
}
|
|
76
|
-
|
|
77
|
-
return entries.map(
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
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
|
|
82
59
|
? entry.modelName
|
|
83
|
-
:
|
|
60
|
+
: `${entry.modelName}-${(0, exports.slugFromAdminRoutePath)(entry.routePath)}`;
|
|
84
61
|
if (used.has(candidate)) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
while (used.has(
|
|
62
|
+
const base = candidate;
|
|
63
|
+
let suffix = 2;
|
|
64
|
+
while (used.has(`${base}-${suffix}`)) {
|
|
88
65
|
suffix += 1;
|
|
89
66
|
}
|
|
90
|
-
candidate =
|
|
67
|
+
candidate = `${base}-${suffix}`;
|
|
91
68
|
}
|
|
92
69
|
used.add(candidate);
|
|
93
70
|
return candidate;
|
|
94
71
|
});
|
|
95
72
|
};
|
|
96
73
|
exports.assignUniqueAdminConfigNames = assignUniqueAdminConfigNames;
|
|
97
|
-
|
|
98
|
-
return models.find(
|
|
74
|
+
const findAdminModelMetaByRoutePath = (models, mountedRoutePath) => {
|
|
75
|
+
return models.find((model) => model.routePath === mountedRoutePath);
|
|
99
76
|
};
|
|
100
77
|
exports.findAdminModelMetaByRoutePath = findAdminModelMetaByRoutePath;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type OpenApiMiddleware, type PermissionMethod } from "@terreno/api";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
export declare const mountAdminMigrationRoutes: ({ app, basePath, dir, openApi, runPermissions, statusPermissions, }: {
|
|
4
|
+
app: express.Application;
|
|
5
|
+
basePath: string;
|
|
6
|
+
dir: string | undefined;
|
|
7
|
+
openApi?: OpenApiMiddleware;
|
|
8
|
+
runPermissions: PermissionMethod<unknown>[];
|
|
9
|
+
statusPermissions: PermissionMethod<unknown>[];
|
|
10
|
+
}) => void;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.mountAdminMigrationRoutes = void 0;
|
|
7
|
+
const api_1 = require("@terreno/api");
|
|
8
|
+
const luxon_1 = require("luxon");
|
|
9
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
10
|
+
const DISABLED_CRUD = {
|
|
11
|
+
create: [],
|
|
12
|
+
delete: [],
|
|
13
|
+
list: [],
|
|
14
|
+
read: [],
|
|
15
|
+
update: [],
|
|
16
|
+
};
|
|
17
|
+
const runQuerySchema = api_1.z.object({
|
|
18
|
+
wetRun: api_1.z.enum(["true", "false"]).optional(),
|
|
19
|
+
});
|
|
20
|
+
const mountAdminMigrationRoutes = ({ app, basePath, dir, openApi, runPermissions, statusPermissions, }) => {
|
|
21
|
+
const requireDir = () => {
|
|
22
|
+
if (!dir) {
|
|
23
|
+
throw new api_1.APIError({ status: 404, title: "Migrations are not configured" });
|
|
24
|
+
}
|
|
25
|
+
return dir;
|
|
26
|
+
};
|
|
27
|
+
app.use(`${basePath}/migrations`, (0, api_1.modelRouter)(api_1.BackgroundTask, {
|
|
28
|
+
...(openApi ? { openApi } : {}),
|
|
29
|
+
collectionActions: {
|
|
30
|
+
run: {
|
|
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",
|
|
43
|
+
});
|
|
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
|
+
},
|
|
95
|
+
method: "POST",
|
|
96
|
+
permissions: runPermissions,
|
|
97
|
+
query: runQuerySchema,
|
|
98
|
+
status: 201,
|
|
99
|
+
summary: "Dry-run or apply pending MongoDB migrations",
|
|
100
|
+
tag: "adminMigrations",
|
|
101
|
+
},
|
|
102
|
+
status: {
|
|
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,
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
method: "GET",
|
|
112
|
+
permissions: statusPermissions,
|
|
113
|
+
summary: "List applied and pending MongoDB migrations",
|
|
114
|
+
tag: "adminMigrations",
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
permissions: DISABLED_CRUD,
|
|
118
|
+
}));
|
|
119
|
+
};
|
|
120
|
+
exports.mountAdminMigrationRoutes = mountAdminMigrationRoutes;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ScriptArgDef, type ScriptArgs, type ScriptArgValue, type ScriptRunner } from "@terreno/api";
|
|
2
|
+
import { type JobDefinition } from "@terreno/jobs";
|
|
3
|
+
export interface AdminScriptJobTarget {
|
|
4
|
+
args?: ScriptArgDef[];
|
|
5
|
+
name: string;
|
|
6
|
+
runner: ScriptRunner;
|
|
7
|
+
}
|
|
8
|
+
/** Durable job name for admin panel script runs. */
|
|
9
|
+
export declare const ADMIN_SCRIPT_JOB_NAME = "admin/script";
|
|
10
|
+
export interface AdminScriptJobPayload {
|
|
11
|
+
args: Record<string, ScriptArgValue>;
|
|
12
|
+
createdByName?: string;
|
|
13
|
+
scriptName: string;
|
|
14
|
+
taskId: string;
|
|
15
|
+
wetRun: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface JobsDefineHost {
|
|
18
|
+
define: (name: string, definition: JobDefinition) => unknown;
|
|
19
|
+
}
|
|
20
|
+
export declare const runRegisteredScriptTask: ({ args, script, signal, taskId, wetRun, }: {
|
|
21
|
+
args: ScriptArgs;
|
|
22
|
+
script: AdminScriptJobTarget;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
taskId: string;
|
|
25
|
+
wetRun: boolean;
|
|
26
|
+
}) => Promise<void>;
|
|
27
|
+
/** Register the shared `admin/script` handler (maxAttempts 1 — scripts are not assumed idempotent). */
|
|
28
|
+
export declare const defineAdminScriptJob: (jobs: JobsDefineHost, getScript: (name: string) => AdminScriptJobTarget | undefined) => void;
|
|
29
|
+
export declare const tryEnqueueAdminScriptJob: (payload: AdminScriptJobPayload) => Promise<{
|
|
30
|
+
id: string;
|
|
31
|
+
} | undefined>;
|
|
32
|
+
export declare const tryCancelAdminScriptJob: (taskId: string) => Promise<void>;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.tryCancelAdminScriptJob = exports.tryEnqueueAdminScriptJob = exports.defineAdminScriptJob = exports.runRegisteredScriptTask = exports.ADMIN_SCRIPT_JOB_NAME = void 0;
|
|
4
|
+
const api_1 = require("@terreno/api");
|
|
5
|
+
const jobs_1 = require("@terreno/jobs");
|
|
6
|
+
const luxon_1 = require("luxon");
|
|
7
|
+
/** Durable job name for admin panel script runs. */
|
|
8
|
+
exports.ADMIN_SCRIPT_JOB_NAME = "admin/script";
|
|
9
|
+
const isScriptArgValue = (value) => {
|
|
10
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
if (!Array.isArray(value)) {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
return value.every((entry) => typeof entry === "string");
|
|
17
|
+
};
|
|
18
|
+
const parseAdminScriptJobPayload = (payload) => {
|
|
19
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
const record = payload;
|
|
23
|
+
if (typeof record.scriptName !== "string" || record.scriptName.length === 0) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
if (typeof record.taskId !== "string" || record.taskId.length === 0) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
if (typeof record.wetRun !== "boolean") {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
const args = {};
|
|
33
|
+
if (record.args !== undefined) {
|
|
34
|
+
if (!record.args || typeof record.args !== "object" || Array.isArray(record.args)) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
for (const [key, value] of Object.entries(record.args)) {
|
|
38
|
+
if (!isScriptArgValue(value)) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
args[key] = value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const createdByName = typeof record.createdByName === "string" ? record.createdByName : undefined;
|
|
45
|
+
return {
|
|
46
|
+
args,
|
|
47
|
+
createdByName,
|
|
48
|
+
scriptName: record.scriptName,
|
|
49
|
+
taskId: record.taskId,
|
|
50
|
+
wetRun: record.wetRun,
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
const isAbortLike = (error) => {
|
|
54
|
+
if (error instanceof api_1.TaskCancelledError) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
if (!(error instanceof Error)) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return error.name === "AbortError" || error.name === "TaskCancelledError";
|
|
61
|
+
};
|
|
62
|
+
const runRegisteredScriptTask = async ({ args, script, signal, taskId, wetRun, }) => {
|
|
63
|
+
const now = luxon_1.DateTime.now().toJSDate();
|
|
64
|
+
await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: { $in: ["pending", "running"] } }, {
|
|
65
|
+
$set: {
|
|
66
|
+
progress: { message: "Starting...", percentage: 0, stage: "Running" },
|
|
67
|
+
startedAt: now,
|
|
68
|
+
status: "running",
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
const ctx = {
|
|
72
|
+
addLog: async (level, message) => {
|
|
73
|
+
const current = await api_1.BackgroundTask.findById(taskId);
|
|
74
|
+
if (current) {
|
|
75
|
+
await current.addLog(level, message);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
args,
|
|
79
|
+
checkCancellation: async () => {
|
|
80
|
+
if (signal?.aborted) {
|
|
81
|
+
throw new api_1.TaskCancelledError(taskId);
|
|
82
|
+
}
|
|
83
|
+
await api_1.BackgroundTask.checkCancellation(taskId);
|
|
84
|
+
},
|
|
85
|
+
updateProgress: async (percentage, stage, message) => {
|
|
86
|
+
const current = await api_1.BackgroundTask.findById(taskId);
|
|
87
|
+
if (current) {
|
|
88
|
+
await current.updateProgress(percentage, stage, message);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
try {
|
|
93
|
+
await ctx.checkCancellation();
|
|
94
|
+
const result = await script.runner(wetRun, ctx);
|
|
95
|
+
await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: "running" }, {
|
|
96
|
+
$set: {
|
|
97
|
+
completedAt: luxon_1.DateTime.now().toJSDate(),
|
|
98
|
+
progress: { message: "Done", percentage: 100, stage: "Complete" },
|
|
99
|
+
result: result.results,
|
|
100
|
+
status: result.success ? "completed" : "failed",
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
if (isAbortLike(err)) {
|
|
106
|
+
await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: { $in: ["pending", "running"] } }, {
|
|
107
|
+
$set: {
|
|
108
|
+
completedAt: luxon_1.DateTime.now().toJSDate(),
|
|
109
|
+
status: "cancelled",
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
+
api_1.logger.error(`Script ${script.name} failed: ${message}`);
|
|
116
|
+
await api_1.BackgroundTask.findOneAndUpdate({ _id: taskId, status: "running" }, {
|
|
117
|
+
$set: {
|
|
118
|
+
completedAt: luxon_1.DateTime.now().toJSDate(),
|
|
119
|
+
error: message,
|
|
120
|
+
result: [message],
|
|
121
|
+
status: "failed",
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
exports.runRegisteredScriptTask = runRegisteredScriptTask;
|
|
127
|
+
const createAdminScriptHandler = (getScript) => {
|
|
128
|
+
return async (payload, ctx) => {
|
|
129
|
+
const parsed = parseAdminScriptJobPayload(payload);
|
|
130
|
+
if (!parsed) {
|
|
131
|
+
throw new api_1.APIError({ status: 400, title: "Invalid admin/script job payload" });
|
|
132
|
+
}
|
|
133
|
+
const script = getScript(parsed.scriptName);
|
|
134
|
+
if (!script) {
|
|
135
|
+
const message = `Script not found: ${parsed.scriptName}`;
|
|
136
|
+
await api_1.BackgroundTask.findOneAndUpdate({ _id: parsed.taskId, status: { $in: ["pending", "running"] } }, {
|
|
137
|
+
$set: {
|
|
138
|
+
completedAt: luxon_1.DateTime.now().toJSDate(),
|
|
139
|
+
error: message,
|
|
140
|
+
result: [message],
|
|
141
|
+
status: "failed",
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
throw new api_1.APIError({ status: 404, title: message });
|
|
145
|
+
}
|
|
146
|
+
const { args, errors } = (0, api_1.createScriptArgs)({
|
|
147
|
+
defs: script.args ?? [],
|
|
148
|
+
values: parsed.args,
|
|
149
|
+
});
|
|
150
|
+
if (errors.length > 0) {
|
|
151
|
+
throw new api_1.APIError({ status: 400, title: errors.join("; ") });
|
|
152
|
+
}
|
|
153
|
+
await (0, exports.runRegisteredScriptTask)({
|
|
154
|
+
args,
|
|
155
|
+
script,
|
|
156
|
+
signal: ctx.signal,
|
|
157
|
+
taskId: parsed.taskId,
|
|
158
|
+
wetRun: parsed.wetRun,
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
/** Register the shared `admin/script` handler (maxAttempts 1 — scripts are not assumed idempotent). */
|
|
163
|
+
const defineAdminScriptJob = (jobs, getScript) => {
|
|
164
|
+
jobs.define(exports.ADMIN_SCRIPT_JOB_NAME, {
|
|
165
|
+
handler: createAdminScriptHandler(getScript),
|
|
166
|
+
retry: { maxAttempts: 1 },
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
exports.defineAdminScriptJob = defineAdminScriptJob;
|
|
170
|
+
const tryEnqueueAdminScriptJob = async (payload) => {
|
|
171
|
+
const jobs = (0, jobs_1.tryGetJobsService)();
|
|
172
|
+
if (!jobs?.getDefinition(exports.ADMIN_SCRIPT_JOB_NAME)) {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
const job = await jobs.enqueue({
|
|
176
|
+
idempotencyKey: `admin-script:${payload.taskId}`,
|
|
177
|
+
name: exports.ADMIN_SCRIPT_JOB_NAME,
|
|
178
|
+
payload,
|
|
179
|
+
});
|
|
180
|
+
return { id: String(job._id) };
|
|
181
|
+
};
|
|
182
|
+
exports.tryEnqueueAdminScriptJob = tryEnqueueAdminScriptJob;
|
|
183
|
+
const tryCancelAdminScriptJob = async (taskId) => {
|
|
184
|
+
const jobs = (0, jobs_1.tryGetJobsService)();
|
|
185
|
+
if (!jobs) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const job = await jobs_1.Job.findOneOrNone({
|
|
189
|
+
name: exports.ADMIN_SCRIPT_JOB_NAME,
|
|
190
|
+
"payload.taskId": taskId,
|
|
191
|
+
});
|
|
192
|
+
if (!job) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
await jobs.adminCancelJob(String(job._id));
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// Job may already be terminal; BackgroundTask cancel is the operator contract.
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
exports.tryCancelAdminScriptJob = tryCancelAdminScriptJob;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import mongoose from "mongoose";
|
|
2
2
|
/** List-query param for the admin table search box. */
|
|
3
3
|
export declare const ADMIN_LIST_SEARCH_PARAM = "q";
|
|
4
|
+
/** @internal */
|
|
4
5
|
export declare const escapeRegexLiteral: (value: string) => string;
|
|
5
6
|
/**
|
|
6
7
|
* Case-insensitive partial match across string `searchFields`, plus ObjectId equality
|
package/dist/adminTextSearch.js
CHANGED
|
@@ -1,49 +1,14 @@
|
|
|
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
|
-
var __read = (this && this.__read) || function (o, n) {
|
|
14
|
-
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
15
|
-
if (!m) return o;
|
|
16
|
-
var i = m.call(o), r, ar = [], e;
|
|
17
|
-
try {
|
|
18
|
-
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
19
|
-
}
|
|
20
|
-
catch (error) { e = { error: error }; }
|
|
21
|
-
finally {
|
|
22
|
-
try {
|
|
23
|
-
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
24
|
-
}
|
|
25
|
-
finally { if (e) throw e.error; }
|
|
26
|
-
}
|
|
27
|
-
return ar;
|
|
28
|
-
};
|
|
29
|
-
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
30
|
-
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
31
|
-
if (ar || !(i in from)) {
|
|
32
|
-
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
33
|
-
ar[i] = from[i];
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
return to.concat(ar || Array.prototype.slice.call(from));
|
|
37
|
-
};
|
|
38
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
39
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40
4
|
};
|
|
41
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
6
|
exports.andMongoFilters = exports.buildAdminPartialSearchFilter = exports.escapeRegexLiteral = exports.ADMIN_LIST_SEARCH_PARAM = void 0;
|
|
43
|
-
|
|
7
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
44
8
|
/** List-query param for the admin table search box. */
|
|
45
9
|
exports.ADMIN_LIST_SEARCH_PARAM = "q";
|
|
46
|
-
|
|
10
|
+
/** @internal */
|
|
11
|
+
const escapeRegexLiteral = (value) => {
|
|
47
12
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
48
13
|
};
|
|
49
14
|
exports.escapeRegexLiteral = escapeRegexLiteral;
|
|
@@ -51,52 +16,31 @@ exports.escapeRegexLiteral = escapeRegexLiteral;
|
|
|
51
16
|
* Case-insensitive partial match across string `searchFields`, plus ObjectId equality
|
|
52
17
|
* when `q` is a valid id.
|
|
53
18
|
*/
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
var extraObjectIdFields = _a.extraObjectIdFields, model = _a.model, q = _a.q, searchFields = _a.searchFields;
|
|
57
|
-
var trimmed = q.trim();
|
|
19
|
+
const buildAdminPartialSearchFilter = ({ extraObjectIdFields, model, q, searchFields, }) => {
|
|
20
|
+
const trimmed = q.trim();
|
|
58
21
|
if (!trimmed) {
|
|
59
22
|
return undefined;
|
|
60
23
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
if (seenFields.has(field)) {
|
|
68
|
-
continue;
|
|
69
|
-
}
|
|
70
|
-
seenFields.add(field);
|
|
71
|
-
var schemaPath = model.schema.path(field);
|
|
72
|
-
if (schemaPath && schemaPath.instance !== "String") {
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
orConditions.push((_c = {}, _c[field] = { $regex: regex }, _c));
|
|
24
|
+
const regex = new RegExp((0, exports.escapeRegexLiteral)(trimmed), "i");
|
|
25
|
+
const orConditions = [];
|
|
26
|
+
const seenFields = new Set();
|
|
27
|
+
for (const field of searchFields) {
|
|
28
|
+
if (seenFields.has(field)) {
|
|
29
|
+
continue;
|
|
76
30
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if (searchFields_1_1 && !searchFields_1_1.done && (_b = searchFields_1.return)) _b.call(searchFields_1);
|
|
31
|
+
seenFields.add(field);
|
|
32
|
+
const schemaPath = model.schema.path(field);
|
|
33
|
+
if (schemaPath && schemaPath.instance !== "String") {
|
|
34
|
+
continue;
|
|
82
35
|
}
|
|
83
|
-
|
|
36
|
+
orConditions.push({ [field]: { $regex: regex } });
|
|
84
37
|
}
|
|
85
38
|
if (mongoose_1.default.isValidObjectId(trimmed)) {
|
|
86
|
-
|
|
87
|
-
?
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
orConditions.push((_e = {}, _e[field] = new mongoose_1.default.Types.ObjectId(trimmed), _e));
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
95
|
-
finally {
|
|
96
|
-
try {
|
|
97
|
-
if (objectIdFields_1_1 && !objectIdFields_1_1.done && (_d = objectIdFields_1.return)) _d.call(objectIdFields_1);
|
|
98
|
-
}
|
|
99
|
-
finally { if (e_2) throw e_2.error; }
|
|
39
|
+
const objectIdFields = extraObjectIdFields
|
|
40
|
+
? [...extraObjectIdFields]
|
|
41
|
+
: Object.keys(model.schema.paths).filter((key) => model.schema.path(key)?.instance === "ObjectID");
|
|
42
|
+
for (const field of objectIdFields) {
|
|
43
|
+
orConditions.push({ [field]: new mongoose_1.default.Types.ObjectId(trimmed) });
|
|
100
44
|
}
|
|
101
45
|
}
|
|
102
46
|
if (orConditions.length === 0) {
|
|
@@ -105,7 +49,7 @@ var buildAdminPartialSearchFilter = function (_a) {
|
|
|
105
49
|
return { $or: orConditions };
|
|
106
50
|
};
|
|
107
51
|
exports.buildAdminPartialSearchFilter = buildAdminPartialSearchFilter;
|
|
108
|
-
|
|
52
|
+
const andMongoFilters = (base, extra) => {
|
|
109
53
|
if (!extra) {
|
|
110
54
|
return base;
|
|
111
55
|
}
|
package/dist/adminUiV2.d.ts
CHANGED