suppa-mcp-2 1.0.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/LICENSE +21 -0
- package/README.md +59 -0
- package/dist/auth.js +612 -0
- package/dist/bin.js +11 -0
- package/dist/config.js +168 -0
- package/dist/httpClient.js +269 -0
- package/dist/registry.js +111 -0
- package/dist/server.js +1533 -0
- package/dist/store.js +120 -0
- package/dist/tenants.js +408 -0
- package/dist/tools/automation.js +776 -0
- package/dist/tools/docs.js +534 -0
- package/dist/tools/entity.js +831 -0
- package/dist/tools/forms.js +550 -0
- package/dist/tools/migrate.js +936 -0
- package/dist/tools/nameMap.js +134 -0
- package/dist/tools/tasks.js +423 -0
- package/dist/tools/v1Fields.js +0 -0
- package/dist/tools/workspace.js +121 -0
- package/dist/utils.js +391 -0
- package/package.json +26 -0
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration connector: copy entity schemas from Suppa 1.0 into Suppa 2.0.
|
|
3
|
+
*
|
|
4
|
+
* Faithful 1:1 port of the Python `suppa_mcp/tools/migrate.py`.
|
|
5
|
+
*
|
|
6
|
+
* Reads entities and their fields from a Suppa 1.0 backend (source) and recreates
|
|
7
|
+
* them on the active Suppa 2.0 tenant (target) using the entity-builder helpers.
|
|
8
|
+
* Names are normalized (entities PascalCase, fields camelCase, semantic renames),
|
|
9
|
+
* types are mapped to the real 2.0 type system, and relations are created in a
|
|
10
|
+
* second pass once their targets exist.
|
|
11
|
+
*
|
|
12
|
+
* Source (1.0) endpoints:
|
|
13
|
+
* GET api/all_entities -> list of entities (tables)
|
|
14
|
+
* GET api/entity_props/:id -> list of fields (properties) for one entity
|
|
15
|
+
*
|
|
16
|
+
* Target (2.0) is written via the entity helpers (active tenant).
|
|
17
|
+
*
|
|
18
|
+
* PORT NOTE — mockable seams: the Python offline tests monkeypatch
|
|
19
|
+
* `migrate._v1_request` (the 1.0 read client) and the entity tools on the
|
|
20
|
+
* `entity` module. In ESM an intra-module call can't be rebound, so:
|
|
21
|
+
* - all v1 reads route through a module-level `v1RequestImpl` that tests swap
|
|
22
|
+
* via `_setV1Request` / `_resetV1Request` (the ESM equivalent of the
|
|
23
|
+
* `migrate._v1_request = fake` monkeypatch);
|
|
24
|
+
* - the entity tools are reached via `import * as entityTools`, which tests
|
|
25
|
+
* replace with `vi.mock("../src/tools/entity.js", ...)`.
|
|
26
|
+
*/
|
|
27
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { config } from "../config.js";
|
|
29
|
+
import * as tenants from "../tenants.js";
|
|
30
|
+
import * as entityTools from "./entity.js";
|
|
31
|
+
import { normalizeEntityName, normalizeFieldName, buildNameMap } from "./nameMap.js";
|
|
32
|
+
import { classifyV1Field, KIND_ENUM, KIND_FILE, KIND_RELATION, KIND_SCALAR, KIND_SKIP, } from "./v1Fields.js";
|
|
33
|
+
import { jsonResponse } from "../utils.js";
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// Suppa 1.0 (source) HTTP client
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
function _v1Headers() {
|
|
38
|
+
const h = {
|
|
39
|
+
Accept: "application/json, text/plain, */*",
|
|
40
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
41
|
+
};
|
|
42
|
+
// Access token takes priority over API key (mirrors the 1.0 MCP server).
|
|
43
|
+
if (config.V1_ACCESS_TOKEN) {
|
|
44
|
+
h["X-Access-Token"] = config.V1_ACCESS_TOKEN;
|
|
45
|
+
}
|
|
46
|
+
else if (config.V1_API_KEY) {
|
|
47
|
+
h["Authorization"] = `Bearer ${config.V1_API_KEY}`;
|
|
48
|
+
}
|
|
49
|
+
return h;
|
|
50
|
+
}
|
|
51
|
+
/** GET request against the Suppa 1.0 API. Returns parsed JSON. */
|
|
52
|
+
async function _v1RequestReal(path, timeout = 60) {
|
|
53
|
+
if (!config.V1_API_KEY && !config.V1_ACCESS_TOKEN) {
|
|
54
|
+
throw new Error("Suppa 1.0 credentials missing: set SUPPA_V1_API_KEY or SUPPA_V1_ACCESS_TOKEN");
|
|
55
|
+
}
|
|
56
|
+
const url = `${config.V1_BASE_URL}/${path.replace(/^\/+/, "")}`;
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
const timer = setTimeout(() => controller.abort(), timeout * 1000);
|
|
59
|
+
let res;
|
|
60
|
+
try {
|
|
61
|
+
res = await fetch(url, { method: "GET", headers: _v1Headers(), signal: controller.signal });
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
65
|
+
throw new Error(`Suppa 1.0 connection error: ${reason}`);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
}
|
|
70
|
+
if (res.status >= 400) {
|
|
71
|
+
let body = "";
|
|
72
|
+
try {
|
|
73
|
+
body = await res.text();
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// ignore
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`Suppa 1.0 HTTP ${res.status} ${res.statusText}: ${body}`);
|
|
79
|
+
}
|
|
80
|
+
const raw = await res.text();
|
|
81
|
+
return raw.trim() ? JSON.parse(raw) : null;
|
|
82
|
+
}
|
|
83
|
+
// Swappable v1 request implementation (see PORT NOTE). Tests replace it via
|
|
84
|
+
// `_setV1Request`; production uses `_v1RequestReal`.
|
|
85
|
+
let v1RequestImpl = _v1RequestReal;
|
|
86
|
+
async function _v1Request(path, timeout = 60) {
|
|
87
|
+
return v1RequestImpl(path, timeout);
|
|
88
|
+
}
|
|
89
|
+
/** TEST HOOK: swap the v1 read client (ESM equivalent of `migrate._v1_request = fake`). */
|
|
90
|
+
export function _setV1Request(fn) {
|
|
91
|
+
v1RequestImpl = fn;
|
|
92
|
+
}
|
|
93
|
+
/** TEST HOOK: restore the production v1 read client. */
|
|
94
|
+
export function _resetV1Request() {
|
|
95
|
+
v1RequestImpl = _v1RequestReal;
|
|
96
|
+
}
|
|
97
|
+
function _isDict(v) {
|
|
98
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Resolve an enum field's option labels from a 1.0 property.
|
|
102
|
+
*
|
|
103
|
+
* Current Suppa 1.0 (``custom_enum``) returns NO inline values in
|
|
104
|
+
* ``entity_props`` (``items`` is null); the options live at
|
|
105
|
+
* ``api/custom_enums/values/{enum_id}`` (enum_id from the field's
|
|
106
|
+
* ``custom_enum`` block). Legacy ``enum`` fields may carry them inline under
|
|
107
|
+
* ``items``. Prefer inline, then fall back to the dedicated endpoint. Skips
|
|
108
|
+
* soft-deleted rows. Returns order-preserving, de-duplicated labels.
|
|
109
|
+
*/
|
|
110
|
+
async function _v1EnumValues(prop) {
|
|
111
|
+
const seen = new Set();
|
|
112
|
+
const out = [];
|
|
113
|
+
const _add = (label) => {
|
|
114
|
+
label = (label || "").trim();
|
|
115
|
+
if (label && !seen.has(label)) {
|
|
116
|
+
seen.add(label);
|
|
117
|
+
out.push(label);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const items = prop.items;
|
|
121
|
+
if (Array.isArray(items)) {
|
|
122
|
+
for (const it of items) {
|
|
123
|
+
if (_isDict(it)) {
|
|
124
|
+
_add(String(it.name || it.id || ""));
|
|
125
|
+
}
|
|
126
|
+
else if (typeof it === "string") {
|
|
127
|
+
_add(it);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (out.length === 0) {
|
|
132
|
+
const ce = _isDict(prop.custom_enum) ? prop.custom_enum : {};
|
|
133
|
+
const enumId = ce.enum_id;
|
|
134
|
+
if (enumId) {
|
|
135
|
+
let rows = null;
|
|
136
|
+
try {
|
|
137
|
+
rows = await _v1Request(`api/custom_enums/values/${enumId}`);
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
if (e instanceof Error) {
|
|
141
|
+
rows = null;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
throw e;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
for (const r of (Array.isArray(rows) ? rows : [])) {
|
|
148
|
+
if (_isDict(r) && !r.deleted) {
|
|
149
|
+
_add(String(r.name || r.value || r.id || ""));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
/** Find one 1.0 entity by name or alias (case-insensitive). */
|
|
157
|
+
async function _resolveV1Entity(nameOrAlias) {
|
|
158
|
+
const key = (nameOrAlias || "").trim().toLowerCase();
|
|
159
|
+
if (!key) {
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
const allEntities = await _v1Request("api/all_entities");
|
|
163
|
+
if (!Array.isArray(allEntities)) {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
for (const e of allEntities) {
|
|
167
|
+
if (!_isDict(e)) {
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (String(e.name ?? "").toLowerCase() === key ||
|
|
171
|
+
String(e.alias ?? "").toLowerCase() === key) {
|
|
172
|
+
return e;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* List entities (tables) on the configured Suppa 1.0 backend.
|
|
179
|
+
*
|
|
180
|
+
* Read-only. Optional case-insensitive substring filter on name/alias.
|
|
181
|
+
*/
|
|
182
|
+
export async function readV1Entities(search = "") {
|
|
183
|
+
const allEntities = await _v1Request("api/all_entities");
|
|
184
|
+
if (!Array.isArray(allEntities)) {
|
|
185
|
+
return jsonResponse({ error: "Unexpected response from api/all_entities" });
|
|
186
|
+
}
|
|
187
|
+
const s = (search || "").trim().toLowerCase();
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const e of allEntities) {
|
|
190
|
+
if (!_isDict(e)) {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const name = String(e.name ?? "");
|
|
194
|
+
const alias = String(e.alias ?? "");
|
|
195
|
+
if (s && !name.toLowerCase().includes(s) && !alias.toLowerCase().includes(s)) {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
out.push({
|
|
199
|
+
id: e.id,
|
|
200
|
+
name,
|
|
201
|
+
alias,
|
|
202
|
+
builtin: Boolean(e.builtin),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
return jsonResponse({ count: out.length, entities: out });
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* List the fields (properties) of one Suppa 1.0 entity (read-only).
|
|
209
|
+
*
|
|
210
|
+
* entity: 1.0 entity name or alias.
|
|
211
|
+
*/
|
|
212
|
+
export async function readV1EntityProps(entity) {
|
|
213
|
+
const ent = await _resolveV1Entity(entity);
|
|
214
|
+
if (!ent) {
|
|
215
|
+
return jsonResponse({ error: `No Suppa 1.0 entity named/aliased '${entity}'.` });
|
|
216
|
+
}
|
|
217
|
+
let props = await _v1Request(`api/entity_props/${ent.id}`);
|
|
218
|
+
if (!Array.isArray(props)) {
|
|
219
|
+
props = [];
|
|
220
|
+
}
|
|
221
|
+
return jsonResponse({
|
|
222
|
+
entity: ent.name,
|
|
223
|
+
alias: ent.alias,
|
|
224
|
+
field_count: props.length,
|
|
225
|
+
fields: props,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Fetch + clean a custom-enum's labels from api/custom_enums/values/{id}.
|
|
230
|
+
*
|
|
231
|
+
* Suppa 1.0 enum_ids are UUIDs (not numeric); this endpoint accepts the id
|
|
232
|
+
* verbatim. Raises RuntimeError if the id isn't usable. Skips soft-deleted rows.
|
|
233
|
+
*/
|
|
234
|
+
async function _v1EnumValuesById(enumId) {
|
|
235
|
+
const rows = await _v1Request(`api/custom_enums/values/${enumId}`);
|
|
236
|
+
const out = [];
|
|
237
|
+
for (const r of (Array.isArray(rows) ? rows : [])) {
|
|
238
|
+
if (_isDict(r) && !r.deleted) {
|
|
239
|
+
out.push(String(r.name ?? r.value ?? r.id));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Read a Suppa 1.0 custom-enum's values (read-only).
|
|
246
|
+
*
|
|
247
|
+
* enum: the enum_id (a UUID — what ``entity_props`` reports under a field's
|
|
248
|
+
* ``custom_enum.enum_id`` — or a legacy numeric id) OR an enum name. The id
|
|
249
|
+
* path is tried first because that is what the values endpoint actually
|
|
250
|
+
* accepts; a plain name is resolved via the ``api/custom_enums`` listing.
|
|
251
|
+
*/
|
|
252
|
+
export async function readV1Enum(enumInput) {
|
|
253
|
+
const raw = (enumInput || "").trim();
|
|
254
|
+
if (!raw) {
|
|
255
|
+
return jsonResponse({ error: "Pass an enum_id (UUID/number) or enum name." });
|
|
256
|
+
}
|
|
257
|
+
// Try the input directly as an enum_id (UUID or numeric — both are valid ids).
|
|
258
|
+
try {
|
|
259
|
+
const values = await _v1EnumValuesById(raw);
|
|
260
|
+
return jsonResponse({ enum_id: raw, value_count: values.length, values });
|
|
261
|
+
}
|
|
262
|
+
catch (e) {
|
|
263
|
+
if (!(e instanceof Error)) {
|
|
264
|
+
throw e;
|
|
265
|
+
}
|
|
266
|
+
// not a usable id — fall through to name resolution
|
|
267
|
+
}
|
|
268
|
+
// Resolve a plain name via the listing, then read by the resolved id.
|
|
269
|
+
let listing = null;
|
|
270
|
+
try {
|
|
271
|
+
listing = await _v1Request("api/custom_enums");
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
if (!(e instanceof Error)) {
|
|
275
|
+
throw e;
|
|
276
|
+
}
|
|
277
|
+
listing = null;
|
|
278
|
+
}
|
|
279
|
+
for (const row of (Array.isArray(listing) ? listing : [])) {
|
|
280
|
+
if (_isDict(row) && String(row.name ?? "").toLowerCase() === raw.toLowerCase()) {
|
|
281
|
+
const enumId = String(row.id ?? row.enum_id ?? "");
|
|
282
|
+
if (enumId) {
|
|
283
|
+
let values;
|
|
284
|
+
try {
|
|
285
|
+
values = await _v1EnumValuesById(enumId);
|
|
286
|
+
}
|
|
287
|
+
catch (e) {
|
|
288
|
+
if (!(e instanceof Error)) {
|
|
289
|
+
throw e;
|
|
290
|
+
}
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
return jsonResponse({ enum_id: enumId, value_count: values.length, values });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return jsonResponse({
|
|
298
|
+
error: `Could not read enum '${enumInput}'. Pass the enum_id from ` +
|
|
299
|
+
"read_v1_entity_props → field.custom_enum.enum_id.",
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
// Field-type mapping: Suppa 1.0 -> Suppa 2.0
|
|
304
|
+
// ---------------------------------------------------------------------------
|
|
305
|
+
//
|
|
306
|
+
// The precise, hardcoded 1.0 field-format catalog + classifier lives in
|
|
307
|
+
// ``v1Fields.ts`` (a mirror of the 1.0 builder's fieldCatalog, verified live).
|
|
308
|
+
// ``classifyV1Field(type, subType)`` returns the target 2.0 type and the build
|
|
309
|
+
// path (scalar / enum / relation / file / skip), covering every 1.0 field type:
|
|
310
|
+
// all primitives, localized text/json, custom fields, enums (single + multi),
|
|
311
|
+
// relations (FK + many-to-many), file attachments (single + multi), and legacy
|
|
312
|
+
// shapes (Number, polymorphic relations, TSVector/Object/List system columns).
|
|
313
|
+
/** Stable enum bucket name for a migrated enum field (avoids cross-entity clashes). */
|
|
314
|
+
function _enumNameFor(entityName, fieldName) {
|
|
315
|
+
return `${entityName}_${fieldName}`;
|
|
316
|
+
}
|
|
317
|
+
// ---------------------------------------------------------------------------
|
|
318
|
+
// Planning
|
|
319
|
+
// ---------------------------------------------------------------------------
|
|
320
|
+
/** Fetch the 1.0 schema and build a structured migration plan. */
|
|
321
|
+
export async function _buildPlan(entityNames = "", includeBuiltin = false, skipRelations = false) {
|
|
322
|
+
const allEntities = await _v1Request("api/all_entities");
|
|
323
|
+
if (!Array.isArray(allEntities)) {
|
|
324
|
+
throw new Error("Unexpected response from api/all_entities (expected a list)");
|
|
325
|
+
}
|
|
326
|
+
const wanted = new Set(entityNames
|
|
327
|
+
.split(",")
|
|
328
|
+
.map((n) => n.trim())
|
|
329
|
+
.filter((n) => n)
|
|
330
|
+
.map((n) => n.toLowerCase()));
|
|
331
|
+
const selected = [];
|
|
332
|
+
for (const e of allEntities) {
|
|
333
|
+
if (!_isDict(e)) {
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (e.builtin && !includeBuiltin) {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const name = String(e.name ?? "");
|
|
340
|
+
const alias = String(e.alias ?? name);
|
|
341
|
+
if (wanted.size > 0 && !wanted.has(name.toLowerCase()) && !wanted.has(alias.toLowerCase())) {
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
selected.push(e);
|
|
345
|
+
}
|
|
346
|
+
// Relation targets in 1.0 may reference an entity by its *alias* rather than
|
|
347
|
+
// its canonical name. Build a resolver from both name and alias -> v2 name.
|
|
348
|
+
const targetResolver = {};
|
|
349
|
+
for (const e of selected) {
|
|
350
|
+
const v2 = normalizeEntityName(String(e.name ?? ""));
|
|
351
|
+
for (const key of [String(e.name ?? ""), String(e.alias ?? "")]) {
|
|
352
|
+
if (key) {
|
|
353
|
+
targetResolver[key.toLowerCase()] = v2;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const planEntities = [];
|
|
358
|
+
const warnings = [];
|
|
359
|
+
for (const e of selected) {
|
|
360
|
+
const entName = String(e.name ?? "");
|
|
361
|
+
const entTitle = String(e.alias ?? "") || entName;
|
|
362
|
+
const entId = e.id;
|
|
363
|
+
const v2EntName = normalizeEntityName(entName);
|
|
364
|
+
let props;
|
|
365
|
+
try {
|
|
366
|
+
props = await _v1Request(`api/entity_props/${entId}`);
|
|
367
|
+
}
|
|
368
|
+
catch (ex) {
|
|
369
|
+
if (!(ex instanceof Error)) {
|
|
370
|
+
throw ex;
|
|
371
|
+
}
|
|
372
|
+
warnings.push(`${entName}: failed to read props (${ex.message})`);
|
|
373
|
+
props = [];
|
|
374
|
+
}
|
|
375
|
+
if (!Array.isArray(props)) {
|
|
376
|
+
props = [];
|
|
377
|
+
}
|
|
378
|
+
const scalarFields = [];
|
|
379
|
+
const enumFields = [];
|
|
380
|
+
const relationFields = [];
|
|
381
|
+
for (const p of props) {
|
|
382
|
+
if (!_isDict(p)) {
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (p.system) {
|
|
386
|
+
// System/built-in fields (id, createdAt, *_id, ...) are auto-created in 2.0.
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const fname = String(p.name ?? "");
|
|
390
|
+
const v2Fname = normalizeFieldName(fname);
|
|
391
|
+
const ftitle = String(p.title ?? "") || fname;
|
|
392
|
+
const ftype = String(p.type ?? "");
|
|
393
|
+
const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
|
|
394
|
+
const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
|
|
395
|
+
// max_length: 0 (or None) means "unlimited" in 1.0 -> omit in 2.0.
|
|
396
|
+
const rawLen = p.max_length;
|
|
397
|
+
const maxLength = typeof rawLen === "number" && Number.isInteger(rawLen) && rawLen > 0 ? rawLen : null;
|
|
398
|
+
const rawPrec = p.precision;
|
|
399
|
+
const decimalPlaces = typeof rawPrec === "number" && Number.isInteger(rawPrec) && rawPrec > 0 ? rawPrec : null;
|
|
400
|
+
// Classify against the hardcoded 1.0 field catalog (v1Fields.ts).
|
|
401
|
+
const cls = classifyV1Field(ftype, fsub, { isSystem: Boolean(p.system) });
|
|
402
|
+
if (cls.kind === KIND_SKIP) {
|
|
403
|
+
warnings.push(`${entName}.${fname}: ${cls.note || `unsupported type ${ftype}/${fsub}`} — skipped`);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
// Relations (FK / many-to-many) — second pass, once targets exist.
|
|
407
|
+
if (cls.kind === KIND_RELATION) {
|
|
408
|
+
if (skipRelations) {
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const rel = _isDict(p.relation) ? p.relation : {};
|
|
412
|
+
const target = _isDict(rel) ? String(rel.relation_target_entity_name ?? "") : "";
|
|
413
|
+
const v2Target = targetResolver[target.toLowerCase()];
|
|
414
|
+
const inSet = v2Target !== undefined;
|
|
415
|
+
if (target && !inSet) {
|
|
416
|
+
warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
|
|
417
|
+
}
|
|
418
|
+
relationFields.push({
|
|
419
|
+
v1_name: fname,
|
|
420
|
+
name: v2Fname,
|
|
421
|
+
title: ftitle,
|
|
422
|
+
type: cls.v2Type,
|
|
423
|
+
required,
|
|
424
|
+
relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
|
|
425
|
+
target_in_set: inSet,
|
|
426
|
+
});
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
// Enums (single 'enum' / 'multi-enum') — values seeded before the field.
|
|
430
|
+
if (cls.kind === KIND_ENUM) {
|
|
431
|
+
const values = await _v1EnumValues(p);
|
|
432
|
+
enumFields.push({
|
|
433
|
+
v1_name: fname,
|
|
434
|
+
name: v2Fname,
|
|
435
|
+
title: ftitle,
|
|
436
|
+
type: cls.v2Type,
|
|
437
|
+
required,
|
|
438
|
+
enum_name: _enumNameFor(v2EntName, v2Fname),
|
|
439
|
+
values,
|
|
440
|
+
});
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
// Scalars + file attachments (file / multi-file are added like scalars).
|
|
444
|
+
if (cls.kind === KIND_SCALAR || cls.kind === KIND_FILE) {
|
|
445
|
+
const field = {
|
|
446
|
+
v1_name: fname,
|
|
447
|
+
name: v2Fname,
|
|
448
|
+
title: ftitle,
|
|
449
|
+
type: cls.v2Type,
|
|
450
|
+
required,
|
|
451
|
+
sub_type: cls.v2SubType,
|
|
452
|
+
max_length: cls.v2Type === "text" ? maxLength : null,
|
|
453
|
+
decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
|
|
454
|
+
multilingual: cls.multilingual,
|
|
455
|
+
};
|
|
456
|
+
if (cls.note) {
|
|
457
|
+
field.note = cls.note;
|
|
458
|
+
}
|
|
459
|
+
scalarFields.push(field);
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
// Defensive: an unclassified kind should never reach here.
|
|
463
|
+
warnings.push(`${entName}.${fname}: unclassified field '${ftype}/${fsub}' — skipped`);
|
|
464
|
+
}
|
|
465
|
+
// Choose the entity title field: prefer 'name', then 'title', then the first
|
|
466
|
+
// text-like scalar (a number/date/boolean/icon makes a poor display title),
|
|
467
|
+
// then any scalar, else 'name'.
|
|
468
|
+
const scalarNames = scalarFields.map((f) => f.name);
|
|
469
|
+
const textLike = scalarFields
|
|
470
|
+
.filter((f) => f.type === "text" || f.type === "multi-language")
|
|
471
|
+
.map((f) => f.name);
|
|
472
|
+
let titleField;
|
|
473
|
+
if (scalarNames.includes("name")) {
|
|
474
|
+
titleField = "name";
|
|
475
|
+
}
|
|
476
|
+
else if (scalarNames.includes("title")) {
|
|
477
|
+
titleField = "title";
|
|
478
|
+
}
|
|
479
|
+
else if (textLike.length > 0) {
|
|
480
|
+
titleField = textLike[0];
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
titleField = scalarNames.length > 0 ? scalarNames[0] : "name";
|
|
484
|
+
}
|
|
485
|
+
const allV1FieldNames = [
|
|
486
|
+
...scalarFields.map((f) => f.v1_name),
|
|
487
|
+
...enumFields.map((f) => f.v1_name),
|
|
488
|
+
...relationFields.map((f) => f.v1_name),
|
|
489
|
+
];
|
|
490
|
+
planEntities.push({
|
|
491
|
+
v1_name: entName,
|
|
492
|
+
name: v2EntName,
|
|
493
|
+
title: entTitle,
|
|
494
|
+
title_field_name: titleField,
|
|
495
|
+
scalar_fields: scalarFields,
|
|
496
|
+
enum_fields: enumFields,
|
|
497
|
+
relation_fields: relationFields,
|
|
498
|
+
name_map: buildNameMap(entName, allV1FieldNames),
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
return {
|
|
502
|
+
source: config.V1_BASE_URL,
|
|
503
|
+
target: tenants.current().baseUrl,
|
|
504
|
+
entity_count: planEntities.length,
|
|
505
|
+
entities: planEntities,
|
|
506
|
+
warnings,
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
// Execution
|
|
511
|
+
// ---------------------------------------------------------------------------
|
|
512
|
+
function _parse(result) {
|
|
513
|
+
if (typeof result !== "string") {
|
|
514
|
+
return result;
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
return JSON.parse(result);
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
return result;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
/** Normalize a field type for comparison (lowercase, '_'→'-'). */
|
|
524
|
+
function _normType(t) {
|
|
525
|
+
return String(t ?? "").trim().toLowerCase().replace(/_/g, "-");
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Pull the field list out of an entity schema, tolerant of response shape.
|
|
529
|
+
*
|
|
530
|
+
* (Local copy of entity.ts's private `_extractFields`, since it isn't exported;
|
|
531
|
+
* this is the port of the Python `from ...entity import _extract_fields`.)
|
|
532
|
+
*/
|
|
533
|
+
function _extractFields(schema) {
|
|
534
|
+
if (Array.isArray(schema)) {
|
|
535
|
+
return schema.filter((f) => _isDict(f));
|
|
536
|
+
}
|
|
537
|
+
if (_isDict(schema)) {
|
|
538
|
+
for (const key of ["fields", "properties", "columns"]) {
|
|
539
|
+
const val = schema[key];
|
|
540
|
+
if (Array.isArray(val)) {
|
|
541
|
+
return val.filter((f) => _isDict(f));
|
|
542
|
+
}
|
|
543
|
+
if (_isDict(val)) {
|
|
544
|
+
const out = [];
|
|
545
|
+
for (const [name, fdef] of Object.entries(val)) {
|
|
546
|
+
if (_isDict(fdef)) {
|
|
547
|
+
out.push({ ...fdef, name: fdef.name ?? name });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return [];
|
|
555
|
+
}
|
|
556
|
+
/** Lowercased names of entities that already exist on the active 2.0 tenant. */
|
|
557
|
+
async function _liveEntityNames() {
|
|
558
|
+
const data = _parse(await entityTools.listEntities());
|
|
559
|
+
if (!Array.isArray(data)) {
|
|
560
|
+
return new Set();
|
|
561
|
+
}
|
|
562
|
+
const out = new Set();
|
|
563
|
+
for (const e of data) {
|
|
564
|
+
if (_isDict(e) && e.name) {
|
|
565
|
+
out.add(String(e.name).toLowerCase());
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
return out;
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Map of existing 2.0 field name -> normalized type for one entity ({} if absent).
|
|
572
|
+
*
|
|
573
|
+
* Re-read fresh on every pass: fields added by an earlier pass must be visible
|
|
574
|
+
* to the next, so this is deliberately not cached. A transient/HTTP read error
|
|
575
|
+
* (``describe_entity`` raises on 4xx/5xx) is treated as "no known fields" rather
|
|
576
|
+
* than aborting the whole run — consistent with the report-and-continue handling
|
|
577
|
+
* in ``_runWrite``; the verify-after pass will still surface anything missing.
|
|
578
|
+
*/
|
|
579
|
+
async function _liveFields(entityName) {
|
|
580
|
+
let schema;
|
|
581
|
+
try {
|
|
582
|
+
schema = _parse(await entityTools.describeEntity(entityName));
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
// unreadable schema → treat as no known fields
|
|
586
|
+
return {};
|
|
587
|
+
}
|
|
588
|
+
const out = {};
|
|
589
|
+
for (const f of _extractFields(schema)) {
|
|
590
|
+
const name = f.name;
|
|
591
|
+
if (name) {
|
|
592
|
+
out[String(name)] = _normType(f.type ?? "");
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
const _EXISTS_MARKERS = [
|
|
598
|
+
"already exist",
|
|
599
|
+
"already exists",
|
|
600
|
+
"23505",
|
|
601
|
+
"duplicate key",
|
|
602
|
+
"duplicate",
|
|
603
|
+
" exists",
|
|
604
|
+
];
|
|
605
|
+
function _isExistsError(text) {
|
|
606
|
+
const t = (text || "").toLowerCase();
|
|
607
|
+
return _EXISTS_MARKERS.some((m) => t.includes(m));
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Run one write, classifying the outcome as created / skipped / failed.
|
|
611
|
+
*
|
|
612
|
+
* 'skipped' covers already-exists (idempotency belt-and-suspenders); the
|
|
613
|
+
* planner also pre-checks existence so this rarely fires on a clean run.
|
|
614
|
+
*/
|
|
615
|
+
async function _runWrite(action, fn) {
|
|
616
|
+
let res;
|
|
617
|
+
try {
|
|
618
|
+
res = await fn();
|
|
619
|
+
}
|
|
620
|
+
catch (ex) {
|
|
621
|
+
const msg = ex instanceof Error ? ex.message : String(ex);
|
|
622
|
+
if (_isExistsError(msg)) {
|
|
623
|
+
return { action, status: "skipped", reason: "exists" };
|
|
624
|
+
}
|
|
625
|
+
return { action, status: "failed", error: msg };
|
|
626
|
+
}
|
|
627
|
+
const parsed = _parse(res);
|
|
628
|
+
const err = _isDict(parsed) ? parsed.error : null;
|
|
629
|
+
if (err) {
|
|
630
|
+
if (_isExistsError(String(err))) {
|
|
631
|
+
return { action, status: "skipped", reason: "exists" };
|
|
632
|
+
}
|
|
633
|
+
return { action, status: "failed", error: String(err) };
|
|
634
|
+
}
|
|
635
|
+
return { action, status: "created", result: parsed };
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Apply the plan to the active Suppa 2.0 tenant, idempotently. Two-pass for relations.
|
|
639
|
+
*
|
|
640
|
+
* mode 'create' or 'gap-fill': both skip entities/fields that already exist
|
|
641
|
+
* (so re-runs never duplicate). They differ only in intent/reporting; the
|
|
642
|
+
* skip-if-exists behaviour is identical, which is what makes the tool safe to
|
|
643
|
+
* re-run after a partial failure.
|
|
644
|
+
*/
|
|
645
|
+
export async function _execute(plan, mode = "create") {
|
|
646
|
+
const details = [];
|
|
647
|
+
const existingEntities = await _liveEntityNames();
|
|
648
|
+
// Pass 1: entities + scalar + enum fields.
|
|
649
|
+
for (const ent of plan.entities) {
|
|
650
|
+
const name = ent.name;
|
|
651
|
+
if (existingEntities.has(name.toLowerCase())) {
|
|
652
|
+
details.push({
|
|
653
|
+
entity: name,
|
|
654
|
+
action: "create_entity",
|
|
655
|
+
status: "skipped",
|
|
656
|
+
reason: "exists",
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
else {
|
|
660
|
+
const step = await _runWrite("create_entity", () => entityTools.createEntity(name, ent.title, ent.title_field_name, false));
|
|
661
|
+
step.entity = name;
|
|
662
|
+
details.push(step);
|
|
663
|
+
if (step.status !== "failed") {
|
|
664
|
+
existingEntities.add(name.toLowerCase());
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
let live = await _liveFields(name); // fields already present on this entity
|
|
668
|
+
for (const f of ent.scalar_fields) {
|
|
669
|
+
if (f.name in live) {
|
|
670
|
+
details.push({
|
|
671
|
+
entity: name,
|
|
672
|
+
action: `add_field:${f.name}`,
|
|
673
|
+
status: "skipped",
|
|
674
|
+
reason: "exists",
|
|
675
|
+
});
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const step = await _runWrite(`add_field:${f.name}`, () => entityTools.addField(name, f.name, f.type, f.title, {
|
|
679
|
+
required: f.required ?? false,
|
|
680
|
+
subType: f.sub_type ?? null,
|
|
681
|
+
maxLength: f.max_length ?? null,
|
|
682
|
+
decimalPlaces: f.decimal_places ?? null,
|
|
683
|
+
}));
|
|
684
|
+
step.entity = name;
|
|
685
|
+
details.push(step);
|
|
686
|
+
}
|
|
687
|
+
for (const f of ent.enum_fields) {
|
|
688
|
+
if (f.name in live) {
|
|
689
|
+
details.push({
|
|
690
|
+
entity: name,
|
|
691
|
+
action: `add_enum_field:${f.name}`,
|
|
692
|
+
status: "skipped",
|
|
693
|
+
reason: "exists",
|
|
694
|
+
});
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
if (f.values && f.values.length) {
|
|
698
|
+
try {
|
|
699
|
+
await entityTools.addEnumValues(f.enum_name, f.values.join(","));
|
|
700
|
+
}
|
|
701
|
+
catch {
|
|
702
|
+
// enum-values failure is reported via field add
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const step = await _runWrite(`add_enum_field:${f.name}`, () => entityTools.addField(name, f.name, f.type ?? "enum", f.title, {
|
|
706
|
+
required: f.required ?? false,
|
|
707
|
+
enumName: f.enum_name,
|
|
708
|
+
}));
|
|
709
|
+
step.entity = name;
|
|
710
|
+
details.push(step);
|
|
711
|
+
}
|
|
712
|
+
void live;
|
|
713
|
+
}
|
|
714
|
+
// Pass 2: relations (targets now exist).
|
|
715
|
+
for (const ent of plan.entities) {
|
|
716
|
+
const name = ent.name;
|
|
717
|
+
if (!ent.relation_fields || ent.relation_fields.length === 0) {
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
const live = await _liveFields(name);
|
|
721
|
+
for (const f of ent.relation_fields) {
|
|
722
|
+
if (f.name in live) {
|
|
723
|
+
details.push({
|
|
724
|
+
entity: name,
|
|
725
|
+
action: `add_relation:${f.name}`,
|
|
726
|
+
status: "skipped",
|
|
727
|
+
reason: "exists",
|
|
728
|
+
});
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (!f.relation_entity || !(f.target_in_set ?? true)) {
|
|
732
|
+
details.push({
|
|
733
|
+
entity: name,
|
|
734
|
+
action: `add_relation:${f.name}`,
|
|
735
|
+
status: "skipped",
|
|
736
|
+
reason: `relation target not in migration set (${f.relation_entity})`,
|
|
737
|
+
});
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const step = await _runWrite(`add_relation:${f.name}`, () => entityTools.addField(name, f.name, f.type, f.title, {
|
|
741
|
+
required: f.required ?? false,
|
|
742
|
+
relationEntity: f.relation_entity,
|
|
743
|
+
}));
|
|
744
|
+
step.entity = name;
|
|
745
|
+
details.push(step);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
// Verify: re-read each entity and confirm every planned field is present.
|
|
749
|
+
const verify = {};
|
|
750
|
+
for (const ent of plan.entities) {
|
|
751
|
+
const name = ent.name;
|
|
752
|
+
const planned = [
|
|
753
|
+
...ent.scalar_fields.map((f) => f.name),
|
|
754
|
+
...ent.enum_fields.map((f) => f.name),
|
|
755
|
+
...ent.relation_fields
|
|
756
|
+
.filter((f) => f.relation_entity && (f.target_in_set ?? true))
|
|
757
|
+
.map((f) => f.name),
|
|
758
|
+
];
|
|
759
|
+
const present = new Set(Object.keys(await _liveFields(name)));
|
|
760
|
+
verify[name] = {
|
|
761
|
+
expected: planned.length,
|
|
762
|
+
present: planned.filter((p) => present.has(p)).sort(),
|
|
763
|
+
missing: planned.filter((p) => !present.has(p)).sort(),
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
return {
|
|
767
|
+
executed: true,
|
|
768
|
+
mode,
|
|
769
|
+
summary: _summarize(details),
|
|
770
|
+
verify,
|
|
771
|
+
details,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Aggregate per-action steps into created/skipped/failed rollups.
|
|
776
|
+
*
|
|
777
|
+
* 'created' means the write call returned without a recognizable error — not a
|
|
778
|
+
* re-confirmed presence. The ``verify`` block in :func:`_execute` (which re-reads
|
|
779
|
+
* live state) is the source of truth for what actually landed.
|
|
780
|
+
*/
|
|
781
|
+
function _summarize(details) {
|
|
782
|
+
const ent = {
|
|
783
|
+
created: [],
|
|
784
|
+
skipped: [],
|
|
785
|
+
failed: [],
|
|
786
|
+
};
|
|
787
|
+
const fld = {
|
|
788
|
+
created: 0,
|
|
789
|
+
skipped: 0,
|
|
790
|
+
failed: 0,
|
|
791
|
+
};
|
|
792
|
+
for (const d of details) {
|
|
793
|
+
const isEntity = d.action === "create_entity";
|
|
794
|
+
const status = d.status;
|
|
795
|
+
const key = status === "created" ? "created" : status === "skipped" ? "skipped" : "failed";
|
|
796
|
+
if (isEntity) {
|
|
797
|
+
ent[key].push(d.entity);
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
fld[key] += 1;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return { entities: ent, fields: fld };
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Read-only diff of the plan against the live 2.0 tenant. Writes nothing.
|
|
807
|
+
*
|
|
808
|
+
* For each planned entity: whether it exists, and per planned field whether it
|
|
809
|
+
* is present, missing, or a type-mismatch (planned 2.0 type vs. live type).
|
|
810
|
+
*/
|
|
811
|
+
export async function _reconcile(plan) {
|
|
812
|
+
const existingEntities = await _liveEntityNames();
|
|
813
|
+
const diff = {};
|
|
814
|
+
for (const ent of plan.entities) {
|
|
815
|
+
const name = ent.name;
|
|
816
|
+
const exists = existingEntities.has(name.toLowerCase());
|
|
817
|
+
const live = exists ? await _liveFields(name) : {};
|
|
818
|
+
const plannedFields = [
|
|
819
|
+
...ent.scalar_fields.map((f) => [f.name, f.type]),
|
|
820
|
+
...ent.enum_fields.map((f) => [f.name, f.type ?? "enum"]),
|
|
821
|
+
...ent.relation_fields.map((f) => [f.name, f.type]),
|
|
822
|
+
];
|
|
823
|
+
const present = [];
|
|
824
|
+
const missing = [];
|
|
825
|
+
const mismatched = [];
|
|
826
|
+
for (const [fname, ptype] of plannedFields) {
|
|
827
|
+
if (!(fname in live)) {
|
|
828
|
+
missing.push(fname);
|
|
829
|
+
}
|
|
830
|
+
else if (live[fname] && _normType(ptype) && live[fname] !== _normType(ptype)) {
|
|
831
|
+
mismatched.push({ name: fname, planned: _normType(ptype), live: live[fname] });
|
|
832
|
+
}
|
|
833
|
+
else {
|
|
834
|
+
present.push(fname);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
diff[name] = {
|
|
838
|
+
exists,
|
|
839
|
+
fields: { present, missing, mismatched },
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
return { reconciled: true, mode: "reconcile", diff };
|
|
843
|
+
}
|
|
844
|
+
// ---------------------------------------------------------------------------
|
|
845
|
+
// Public tool entry point
|
|
846
|
+
// ---------------------------------------------------------------------------
|
|
847
|
+
const _REQUIRED_ENTITY_KEYS = [
|
|
848
|
+
"name",
|
|
849
|
+
"title",
|
|
850
|
+
"title_field_name",
|
|
851
|
+
"scalar_fields",
|
|
852
|
+
"enum_fields",
|
|
853
|
+
"relation_fields",
|
|
854
|
+
];
|
|
855
|
+
/** Validate the shape of a (possibly hand-edited) plan loaded from a file. */
|
|
856
|
+
function _validatePlan(plan) {
|
|
857
|
+
if (!_isDict(plan) || !Array.isArray(plan.entities)) {
|
|
858
|
+
throw new Error("Invalid plan: expected an object with an 'entities' array");
|
|
859
|
+
}
|
|
860
|
+
plan.entities.forEach((ent, i) => {
|
|
861
|
+
if (!_isDict(ent)) {
|
|
862
|
+
throw new Error(`Invalid plan: entity #${i} is not an object`);
|
|
863
|
+
}
|
|
864
|
+
const missing = _REQUIRED_ENTITY_KEYS.filter((k) => !(k in ent));
|
|
865
|
+
if (missing.length > 0) {
|
|
866
|
+
throw new Error(`Invalid plan: entity '${ent.name ?? i}' is missing keys: [${missing
|
|
867
|
+
.map((m) => `'${m}'`)
|
|
868
|
+
.join(", ")}]`);
|
|
869
|
+
}
|
|
870
|
+
});
|
|
871
|
+
if (!("entity_count" in plan)) {
|
|
872
|
+
plan.entity_count = plan.entities.length;
|
|
873
|
+
}
|
|
874
|
+
if (!("warnings" in plan)) {
|
|
875
|
+
plan.warnings = [];
|
|
876
|
+
}
|
|
877
|
+
return plan;
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Migrate entity schemas from Suppa 1.0 into the active Suppa 2.0 tenant.
|
|
881
|
+
*
|
|
882
|
+
* dry_run: when True (default), only returns the plan without writing to 2.0.
|
|
883
|
+
* entity_names: comma-separated list of 1.0 entity names/aliases to migrate (empty = all).
|
|
884
|
+
* include_builtin: include builtin/system entities (default: custom only).
|
|
885
|
+
* skip_relations: skip relation/foreign-key fields entirely.
|
|
886
|
+
* output_file: when set, write the migration plan as JSON to this path (for review/editing).
|
|
887
|
+
* plan_file: when set, load the plan from this JSON file instead of reading from Suppa 1.0.
|
|
888
|
+
* mode: 'create' (default) and 'gap-fill' both skip existing entities/fields (idempotent);
|
|
889
|
+
* 'reconcile' is a read-only diff of the plan vs. the live 2.0 tenant (writes nothing).
|
|
890
|
+
*/
|
|
891
|
+
export async function migrateEntities(dryRun = true, entityNames = "", includeBuiltin = false, skipRelations = false, outputFile = "", planFile = "", mode = "create") {
|
|
892
|
+
let plan;
|
|
893
|
+
if (planFile) {
|
|
894
|
+
plan = _validatePlan(JSON.parse(readFileSync(planFile, { encoding: "utf-8" })));
|
|
895
|
+
}
|
|
896
|
+
else {
|
|
897
|
+
plan = await _buildPlan(entityNames, includeBuiltin, skipRelations);
|
|
898
|
+
}
|
|
899
|
+
let writtenTo = null;
|
|
900
|
+
if (outputFile) {
|
|
901
|
+
writeFileSync(outputFile, JSON.stringify(plan, null, 2), { encoding: "utf-8" });
|
|
902
|
+
writtenTo = outputFile;
|
|
903
|
+
}
|
|
904
|
+
mode = (mode || "create").trim().toLowerCase();
|
|
905
|
+
if (!["create", "gap-fill", "reconcile"].includes(mode)) {
|
|
906
|
+
return jsonResponse({
|
|
907
|
+
error: `Unknown mode '${mode}'. Use 'create', 'gap-fill', or 'reconcile'.`,
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
// Reconcile is a read-only live diff — it ignores dry_run (never writes).
|
|
911
|
+
if (mode === "reconcile") {
|
|
912
|
+
return jsonResponse({
|
|
913
|
+
mode: "reconcile",
|
|
914
|
+
plan_written_to: writtenTo,
|
|
915
|
+
...(await _reconcile(plan)),
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
if (dryRun) {
|
|
919
|
+
return jsonResponse({
|
|
920
|
+
dry_run: true,
|
|
921
|
+
mode,
|
|
922
|
+
plan_written_to: writtenTo,
|
|
923
|
+
plan,
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
const result = await _execute(plan, mode);
|
|
927
|
+
return jsonResponse({
|
|
928
|
+
dry_run: false,
|
|
929
|
+
plan_written_to: writtenTo,
|
|
930
|
+
plan_summary: {
|
|
931
|
+
entity_count: plan.entity_count,
|
|
932
|
+
warnings: plan.warnings ?? [],
|
|
933
|
+
},
|
|
934
|
+
...result,
|
|
935
|
+
});
|
|
936
|
+
}
|