suppa-mcp-2 1.1.3 → 1.2.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.
@@ -94,9 +94,99 @@ export function _setV1Request(fn) {
94
94
  export function _resetV1Request() {
95
95
  v1RequestImpl = _v1RequestReal;
96
96
  }
97
+ /** POST request against the Suppa 1.0 API (used for instance-existence probes). */
98
+ async function _v1PostReal(path, body, timeout = 60) {
99
+ if (!config.V1_API_KEY && !config.V1_ACCESS_TOKEN) {
100
+ throw new Error("Suppa 1.0 credentials missing: set SUPPA_V1_API_KEY or SUPPA_V1_ACCESS_TOKEN");
101
+ }
102
+ const url = `${config.V1_BASE_URL}/${path.replace(/^\/+/, "")}`;
103
+ const controller = new AbortController();
104
+ const timer = setTimeout(() => controller.abort(), timeout * 1000);
105
+ let res;
106
+ try {
107
+ res = await fetch(url, {
108
+ method: "POST",
109
+ headers: _v1Headers(),
110
+ body: JSON.stringify(body ?? {}),
111
+ signal: controller.signal,
112
+ });
113
+ }
114
+ catch (e) {
115
+ const reason = e instanceof Error ? e.message : String(e);
116
+ throw new Error(`Suppa 1.0 connection error: ${reason}`);
117
+ }
118
+ finally {
119
+ clearTimeout(timer);
120
+ }
121
+ if (res.status >= 400) {
122
+ let text = "";
123
+ try {
124
+ text = await res.text();
125
+ }
126
+ catch {
127
+ // ignore
128
+ }
129
+ throw new Error(`Suppa 1.0 HTTP ${res.status} ${res.statusText}: ${text}`);
130
+ }
131
+ const raw = await res.text();
132
+ return raw.trim() ? JSON.parse(raw) : null;
133
+ }
134
+ // Swappable v1 POST implementation (see the GET seam above). Tests replace it
135
+ // via `_setV1Post`; production uses `_v1PostReal`.
136
+ let v1PostImpl = _v1PostReal;
137
+ async function _v1Post(path, body, timeout = 60) {
138
+ return v1PostImpl(path, body, timeout);
139
+ }
140
+ /** TEST HOOK: swap the v1 POST client. */
141
+ export function _setV1Post(fn) {
142
+ v1PostImpl = fn;
143
+ }
144
+ /** TEST HOOK: restore the production v1 POST client. */
145
+ export function _resetV1Post() {
146
+ v1PostImpl = _v1PostReal;
147
+ }
97
148
  function _isDict(v) {
98
149
  return v !== null && typeof v === "object" && !Array.isArray(v);
99
150
  }
151
+ /**
152
+ * Does at least one v1 record of `searchAlias` populate `v1FieldName`?
153
+ *
154
+ * Probes `POST /api/search/{alias}` with an "is not null" filter and limit 1.
155
+ * Returns true (a populated row exists), false (definitively none), or null
156
+ * when the check couldn't run (no v1 creds, endpoint error, unexpected shape).
157
+ * Callers treat null as "unknown" and never drop a field on it.
158
+ */
159
+ async function _v1RelationPopulated(searchAlias, v1FieldName) {
160
+ if (!searchAlias || !v1FieldName) {
161
+ return null;
162
+ }
163
+ let rows;
164
+ try {
165
+ rows = await _v1Post(`api/search/${searchAlias}`, {
166
+ filters: [{ field: v1FieldName, comparator: "is not null" }],
167
+ limit: 1,
168
+ });
169
+ }
170
+ catch {
171
+ return null; // fail-safe: unknown, never prune on a probe error
172
+ }
173
+ if (Array.isArray(rows)) {
174
+ return rows.length > 0;
175
+ }
176
+ if (_isDict(rows)) {
177
+ for (const k of ["data", "rows", "items", "result"]) {
178
+ const v = rows[k];
179
+ if (Array.isArray(v)) {
180
+ return v.length > 0;
181
+ }
182
+ }
183
+ const total = rows.total;
184
+ if (typeof total === "number") {
185
+ return total > 0;
186
+ }
187
+ }
188
+ return null;
189
+ }
100
190
  /**
101
191
  * Resolve an enum field's option labels from a 1.0 property.
102
192
  *
@@ -343,19 +433,21 @@ export async function readV1EntityProps(entity, expand = true, resolveEnums = tr
343
433
  multiple: p.multiple === true,
344
434
  sub_type: p.sub_type,
345
435
  });
346
- // A tabular part ("Табличні частини") is a MULTI-valued relation
347
- // (`multiple: true` — an embedded child collection) into a custom
348
- // (non-builtin), non-self entity. Single-valued relations (multiple:false)
349
- // are plain lookups, not child tables. Expand only the real tabular parts
350
- // to reveal their sub-fields; lookups just show their target name.
351
- const isTabular = p.multiple === true && target != null && !isSelf && !isBuiltin;
352
- if (isTabular) {
353
- tabularParts.push(String(p.name));
354
- if (expand) {
355
- const cf = await childFields(targetKey);
356
- if (cf) {
436
+ // A tabular part ("Табличні частини") is an OWNED child: the target entity
437
+ // carries an `owner` relation pointing back to THIS entity. (Multi-valued
438
+ // many-to-many fields like `skills`/`vacancies` are shared lookups, NOT
439
+ // child tables — `multiple` is not the marker.) Only owned children are
440
+ // expanded, with the platform-managed owner field(s) hidden.
441
+ if (target && !isSelf && !isBuiltin) {
442
+ const cf = await childFields(targetKey);
443
+ const ownsBack = cf != null &&
444
+ cf.some((f) => f.name === "owner" &&
445
+ [String(ent.name).toLowerCase(), String(ent.alias).toLowerCase()].includes(String(f.relation_target ?? "").toLowerCase()));
446
+ if (ownsBack) {
447
+ tabularParts.push(String(p.name));
448
+ if (expand && cf) {
357
449
  s.child_entity = targetKey;
358
- s.child_fields = cf;
450
+ s.child_fields = cf.filter((f) => f.name !== "owner" && f.name !== "owner_id");
359
451
  }
360
452
  }
361
453
  }
@@ -461,11 +553,137 @@ export async function readV1Enum(enumInput) {
461
553
  function _enumNameFor(entityName, fieldName) {
462
554
  return `${entityName}_${fieldName}`;
463
555
  }
556
+ /**
557
+ * Classify one 1.0 entity's props into scalar/enum/relation buckets and choose a
558
+ * title field. `dropNames` skips specific field names (used to drop a tabular
559
+ * part's `owner` field, which the platform auto-creates). Shared by top-level
560
+ * entities and their tabular-part children.
561
+ */
562
+ async function _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, dropNames = new Set(), searchAlias = "", checkInstances = false, skipEmptyRelations = false) {
563
+ const scalarFields = [];
564
+ const enumFields = [];
565
+ const relationFields = [];
566
+ for (const p of props) {
567
+ if (!_isDict(p) || p.system) {
568
+ continue; // system/built-in fields are auto-created in 2.0
569
+ }
570
+ const fname = String(p.name ?? "");
571
+ if (dropNames.has(fname)) {
572
+ continue; // e.g. a tabular part's `owner` (auto-created by the platform)
573
+ }
574
+ const v2Fname = normalizeFieldName(fname);
575
+ // Preserve a v1 multilingual title object ({en, uk, ...}) as-is so each
576
+ // language survives into 2.0; collapse only plain/absent titles to a string.
577
+ // (String(object) would otherwise store the literal "[object Object]".)
578
+ const ftitle = _isDict(p.title)
579
+ ? p.title
580
+ : String(p.title ?? "") || fname;
581
+ const ftype = String(p.type ?? "");
582
+ const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
583
+ const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
584
+ const rawLen = p.max_length;
585
+ const maxLength = typeof rawLen === "number" && Number.isInteger(rawLen) && rawLen > 0 ? rawLen : null;
586
+ const rawPrec = p.precision;
587
+ const decimalPlaces = typeof rawPrec === "number" && Number.isInteger(rawPrec) && rawPrec > 0 ? rawPrec : null;
588
+ const cls = classifyV1Field(ftype, fsub, { isSystem: Boolean(p.system) });
589
+ if (cls.kind === KIND_SKIP) {
590
+ warnings.push(`${entName}.${fname}: ${cls.note || `unsupported type ${ftype}/${fsub}`} — skipped`);
591
+ continue;
592
+ }
593
+ if (cls.kind === KIND_RELATION) {
594
+ const rel = _isDict(p.relation) ? p.relation : {};
595
+ const target = String(rel.relation_target_entity_name ?? "");
596
+ const v2Target = targetResolver[target.toLowerCase()];
597
+ const inSet = v2Target !== undefined;
598
+ if (target && !inSet) {
599
+ warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
600
+ }
601
+ const relField = {
602
+ v1_name: fname,
603
+ name: v2Fname,
604
+ title: ftitle,
605
+ type: cls.v2Type,
606
+ required,
607
+ relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
608
+ target_in_set: inSet,
609
+ };
610
+ // Analyze whether this relation actually carries data in v1 before deciding
611
+ // the field is needed. `create:false` fields are reported but not created.
612
+ if (checkInstances) {
613
+ const populated = await _v1RelationPopulated(searchAlias, fname);
614
+ relField.v1_populated = populated;
615
+ const create = !(skipEmptyRelations && populated === false);
616
+ relField.create = create;
617
+ if (populated === false) {
618
+ warnings.push(`${entName}.${fname}: relation has no populated instances in v1 — ` +
619
+ (create ? "kept for review" : "excluded (skip_empty_relations)"));
620
+ }
621
+ }
622
+ relationFields.push(relField);
623
+ continue;
624
+ }
625
+ if (cls.kind === KIND_ENUM) {
626
+ const values = await _v1EnumValues(p);
627
+ enumFields.push({
628
+ v1_name: fname,
629
+ name: v2Fname,
630
+ title: ftitle,
631
+ type: cls.v2Type,
632
+ required,
633
+ enum_name: _enumNameFor(v2EntName, v2Fname),
634
+ values,
635
+ });
636
+ continue;
637
+ }
638
+ if (cls.kind === KIND_SCALAR || cls.kind === KIND_FILE) {
639
+ const field = {
640
+ v1_name: fname,
641
+ name: v2Fname,
642
+ title: ftitle,
643
+ type: cls.v2Type,
644
+ required,
645
+ sub_type: cls.v2SubType,
646
+ max_length: cls.v2Type === "text" ? maxLength : null,
647
+ decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
648
+ multilingual: cls.multilingual,
649
+ };
650
+ if (cls.note) {
651
+ field.note = cls.note;
652
+ }
653
+ scalarFields.push(field);
654
+ continue;
655
+ }
656
+ warnings.push(`${entName}.${fname}: unclassified field '${ftype}/${fsub}' — skipped`);
657
+ }
658
+ const scalarNames = scalarFields.map((f) => f.name);
659
+ const textLike = scalarFields
660
+ .filter((f) => f.type === "text" || f.type === "multi-language")
661
+ .map((f) => f.name);
662
+ let titleFieldName;
663
+ if (scalarNames.includes("name")) {
664
+ titleFieldName = "name";
665
+ }
666
+ else if (scalarNames.includes("title")) {
667
+ titleFieldName = "title";
668
+ }
669
+ else if (textLike.length > 0) {
670
+ titleFieldName = textLike[0];
671
+ }
672
+ else {
673
+ titleFieldName = scalarNames.length > 0 ? scalarNames[0] : "name";
674
+ }
675
+ const allV1FieldNames = [
676
+ ...scalarFields.map((f) => f.v1_name),
677
+ ...enumFields.map((f) => f.v1_name),
678
+ ...relationFields.map((f) => f.v1_name),
679
+ ];
680
+ return { scalarFields, enumFields, relationFields, allV1FieldNames, titleFieldName };
681
+ }
464
682
  // ---------------------------------------------------------------------------
465
683
  // Planning
466
684
  // ---------------------------------------------------------------------------
467
685
  /** Fetch the 1.0 schema and build a structured migration plan. */
468
- export async function _buildPlan(entityNames = "", includeBuiltin = false, skipRelations = false) {
686
+ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipRelations = false, checkRelationInstances = false, skipEmptyRelations = false) {
469
687
  const allEntities = await _v1Request("api/all_entities");
470
688
  if (!Array.isArray(allEntities)) {
471
689
  throw new Error("Unexpected response from api/all_entities (expected a list)");
@@ -501,16 +719,40 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
501
719
  }
502
720
  }
503
721
  }
504
- const planEntities = [];
722
+ // Index ALL 1.0 entities (not just selected) so relation/tabular targets can
723
+ // be resolved and their `builtin` flag checked even when outside the selection.
724
+ const entIndex = new Map();
725
+ for (const e of allEntities) {
726
+ if (!_isDict(e)) {
727
+ continue;
728
+ }
729
+ const v1Name = String(e.name ?? "");
730
+ const alias = String(e.alias ?? "");
731
+ const info = {
732
+ v1Name,
733
+ alias: alias || v1Name,
734
+ builtin: Boolean(e.builtin),
735
+ id: String(e.id ?? ""),
736
+ };
737
+ if (v1Name) {
738
+ entIndex.set(v1Name.toLowerCase(), info);
739
+ }
740
+ if (alias) {
741
+ entIndex.set(alias.toLowerCase(), info);
742
+ }
743
+ }
505
744
  const warnings = [];
506
- for (const e of selected) {
507
- const entName = String(e.name ?? "");
508
- const entTitle = String(e.alias ?? "") || entName;
509
- const entId = e.id;
510
- const v2EntName = normalizeEntityName(entName);
745
+ // Fetch + cache each entity's props once (children may be fetched on demand).
746
+ const propsCache = new Map();
747
+ const fetchProps = async (id, entName) => {
748
+ const key = entName.toLowerCase();
749
+ const cached = propsCache.get(key);
750
+ if (cached) {
751
+ return cached;
752
+ }
511
753
  let props;
512
754
  try {
513
- props = await _v1Request(`api/entity_props/${entId}`);
755
+ props = await _v1Request(`api/entity_props/${id}`);
514
756
  }
515
757
  catch (ex) {
516
758
  if (!(ex instanceof Error)) {
@@ -519,136 +761,101 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
519
761
  warnings.push(`${entName}: failed to read props (${ex.message})`);
520
762
  props = [];
521
763
  }
522
- if (!Array.isArray(props)) {
523
- props = [];
764
+ const arr = Array.isArray(props) ? props : [];
765
+ propsCache.set(key, arr);
766
+ return arr;
767
+ };
768
+ // Phase A: detect tabular-part children. The reliable v1 marker is CHILD-side:
769
+ // a tabular part carries an `owner` relation pointing back to its parent.
770
+ // (Multi-valued many-to-many fields like `skills`/`vacancies` are shared
771
+ // lookups, NOT owned child tables — they stay normal relations.) A child is
772
+ // only nested when its parent is also in the migration set.
773
+ const selectedLower = new Set();
774
+ for (const e of selected) {
775
+ selectedLower.add(String(e.name ?? "").toLowerCase());
776
+ if (e.alias) {
777
+ selectedLower.add(String(e.alias).toLowerCase());
524
778
  }
525
- const scalarFields = [];
526
- const enumFields = [];
527
- const relationFields = [];
528
- for (const p of props) {
529
- if (!_isDict(p)) {
530
- continue;
531
- }
532
- if (p.system) {
533
- // System/built-in fields (id, createdAt, *_id, ...) are auto-created in 2.0.
534
- continue;
535
- }
536
- const fname = String(p.name ?? "");
537
- const v2Fname = normalizeFieldName(fname);
538
- const ftitle = String(p.title ?? "") || fname;
539
- const ftype = String(p.type ?? "");
540
- const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
541
- const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
542
- // max_length: 0 (or None) means "unlimited" in 1.0 -> omit in 2.0.
543
- const rawLen = p.max_length;
544
- const maxLength = typeof rawLen === "number" && Number.isInteger(rawLen) && rawLen > 0 ? rawLen : null;
545
- const rawPrec = p.precision;
546
- const decimalPlaces = typeof rawPrec === "number" && Number.isInteger(rawPrec) && rawPrec > 0 ? rawPrec : null;
547
- // Classify against the hardcoded 1.0 field catalog (v1Fields.ts).
548
- const cls = classifyV1Field(ftype, fsub, { isSystem: Boolean(p.system) });
549
- if (cls.kind === KIND_SKIP) {
550
- warnings.push(`${entName}.${fname}: ${cls.note || `unsupported type ${ftype}/${fsub}`} — skipped`);
551
- continue;
779
+ }
780
+ const ownerOf = new Map(); // childV1(lower) -> parentV1 (canonical)
781
+ for (const e of selected) {
782
+ const entName = String(e.name ?? "");
783
+ const props = await fetchProps(String(e.id ?? ""), entName);
784
+ const ownerField = props.find((p) => _isDict(p) && p.name === "owner" && p.type === "relation");
785
+ if (!ownerField) {
786
+ continue;
787
+ }
788
+ const rel = _isDict(ownerField.relation) ? ownerField.relation : {};
789
+ const parentInfo = entIndex.get(String(rel.relation_target_entity_name ?? "").toLowerCase());
790
+ if (parentInfo && selectedLower.has(parentInfo.v1Name.toLowerCase())) {
791
+ ownerOf.set(entName.toLowerCase(), parentInfo.v1Name);
792
+ }
793
+ else if (parentInfo) {
794
+ warnings.push(`${entName}: is a tabular part of '${parentInfo.v1Name}', which is not in the migration set — migrating standalone`);
795
+ }
796
+ }
797
+ const isChild = (nameLower) => ownerOf.has(nameLower);
798
+ // Phase B: emit top-level entities; nest each parent's tabular-part children
799
+ // (dropping their platform-managed `owner` field).
800
+ const planEntities = [];
801
+ let tabularCount = 0;
802
+ for (const e of selected) {
803
+ const entName = String(e.name ?? "");
804
+ const entLower = entName.toLowerCase();
805
+ if (isChild(entLower)) {
806
+ const parent = ownerOf.get(entLower);
807
+ if (!isChild(parent.toLowerCase())) {
808
+ continue; // nested under its parent below (v2 supports one level)
552
809
  }
553
- // Relations (FK / many-to-many) — second pass, once targets exist.
554
- if (cls.kind === KIND_RELATION) {
555
- if (skipRelations) {
556
- continue;
557
- }
558
- const rel = _isDict(p.relation) ? p.relation : {};
559
- const target = _isDict(rel) ? String(rel.relation_target_entity_name ?? "") : "";
560
- const v2Target = targetResolver[target.toLowerCase()];
561
- const inSet = v2Target !== undefined;
562
- if (target && !inSet) {
563
- warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
810
+ warnings.push(`${entName}: nested tabular part (parent '${parent}' is itself a tabular part) — migrating standalone`);
811
+ }
812
+ const entTitle = String(e.alias ?? "") || entName;
813
+ const v2EntName = normalizeEntityName(entName);
814
+ const searchAlias = String(e.alias ?? "") || entName;
815
+ const props = await fetchProps(String(e.id ?? ""), entName);
816
+ const pf = await _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, new Set(), searchAlias, checkRelationInstances, skipEmptyRelations);
817
+ const tabularParts = [];
818
+ if (!isChild(entLower)) {
819
+ for (const c of selected) {
820
+ const cName = String(c.name ?? "");
821
+ if (ownerOf.get(cName.toLowerCase()) !== entName) {
822
+ continue; // not a tabular part of this entity
564
823
  }
565
- relationFields.push({
566
- v1_name: fname,
567
- name: v2Fname,
568
- title: ftitle,
569
- type: cls.v2Type,
570
- required,
571
- relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
572
- target_in_set: inSet,
573
- });
574
- continue;
575
- }
576
- // Enums (single 'enum' / 'multi-enum') — values seeded before the field.
577
- if (cls.kind === KIND_ENUM) {
578
- const values = await _v1EnumValues(p);
579
- enumFields.push({
580
- v1_name: fname,
581
- name: v2Fname,
582
- title: ftitle,
583
- type: cls.v2Type,
584
- required,
585
- enum_name: _enumNameFor(v2EntName, v2Fname),
586
- values,
824
+ const cprops = await fetchProps(String(c.id ?? ""), cName);
825
+ const cv2 = normalizeEntityName(cName);
826
+ const cSearchAlias = String(c.alias ?? "") || cName;
827
+ const cf = await _planFields(cprops, cName, cv2, targetResolver, entIndex, warnings, new Set(["owner", "owner_id"]), // auto-created by create_tabular_part
828
+ cSearchAlias, checkRelationInstances, skipEmptyRelations);
829
+ tabularParts.push({
830
+ v1_name: cName,
831
+ name: cv2,
832
+ title: String(c.alias ?? "") || cName,
833
+ title_field_name: cf.titleFieldName,
834
+ scalar_fields: cf.scalarFields,
835
+ enum_fields: cf.enumFields,
836
+ relation_fields: skipRelations ? [] : cf.relationFields,
837
+ name_map: buildNameMap(cName, cf.allV1FieldNames),
587
838
  });
588
- continue;
589
- }
590
- // Scalars + file attachments (file / multi-file are added like scalars).
591
- if (cls.kind === KIND_SCALAR || cls.kind === KIND_FILE) {
592
- const field = {
593
- v1_name: fname,
594
- name: v2Fname,
595
- title: ftitle,
596
- type: cls.v2Type,
597
- required,
598
- sub_type: cls.v2SubType,
599
- max_length: cls.v2Type === "text" ? maxLength : null,
600
- decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
601
- multilingual: cls.multilingual,
602
- };
603
- if (cls.note) {
604
- field.note = cls.note;
605
- }
606
- scalarFields.push(field);
607
- continue;
839
+ tabularCount++;
608
840
  }
609
- // Defensive: an unclassified kind should never reach here.
610
- warnings.push(`${entName}.${fname}: unclassified field '${ftype}/${fsub}' — skipped`);
611
- }
612
- // Choose the entity title field: prefer 'name', then 'title', then the first
613
- // text-like scalar (a number/date/boolean/icon makes a poor display title),
614
- // then any scalar, else 'name'.
615
- const scalarNames = scalarFields.map((f) => f.name);
616
- const textLike = scalarFields
617
- .filter((f) => f.type === "text" || f.type === "multi-language")
618
- .map((f) => f.name);
619
- let titleField;
620
- if (scalarNames.includes("name")) {
621
- titleField = "name";
622
- }
623
- else if (scalarNames.includes("title")) {
624
- titleField = "title";
625
- }
626
- else if (textLike.length > 0) {
627
- titleField = textLike[0];
628
841
  }
629
- else {
630
- titleField = scalarNames.length > 0 ? scalarNames[0] : "name";
631
- }
632
- const allV1FieldNames = [
633
- ...scalarFields.map((f) => f.v1_name),
634
- ...enumFields.map((f) => f.v1_name),
635
- ...relationFields.map((f) => f.v1_name),
636
- ];
637
842
  planEntities.push({
638
843
  v1_name: entName,
639
844
  name: v2EntName,
640
845
  title: entTitle,
641
- title_field_name: titleField,
642
- scalar_fields: scalarFields,
643
- enum_fields: enumFields,
644
- relation_fields: relationFields,
645
- name_map: buildNameMap(entName, allV1FieldNames),
846
+ title_field_name: pf.titleFieldName,
847
+ scalar_fields: pf.scalarFields,
848
+ enum_fields: pf.enumFields,
849
+ relation_fields: skipRelations ? [] : pf.relationFields,
850
+ tabular_parts: tabularParts,
851
+ name_map: buildNameMap(entName, pf.allV1FieldNames),
646
852
  });
647
853
  }
648
854
  return {
649
855
  source: config.V1_BASE_URL,
650
856
  target: tenants.current().baseUrl,
651
857
  entity_count: planEntities.length,
858
+ tabular_part_count: tabularCount,
652
859
  entities: planEntities,
653
860
  warnings,
654
861
  };
@@ -857,6 +1064,52 @@ export async function _execute(plan, mode = "create") {
857
1064
  details.push(step);
858
1065
  }
859
1066
  void live;
1067
+ // Tabular parts: create each owned child sub-table (type="tabular-part",
1068
+ // auto owner FK back to the parent), then add its scalar + enum fields.
1069
+ for (const tp of (ent.tabular_parts ?? [])) {
1070
+ const tpName = tp.name;
1071
+ const tpStep = await _runWrite(`create_tabular_part:${tpName}`, () => entityTools.createTabularPart(name, // parent entity
1072
+ tpName, tp.title, tp.title_field_name, false, // add the real fields ourselves
1073
+ "text", tpName));
1074
+ tpStep.entity = name;
1075
+ tpStep.tabular_part = tpName;
1076
+ details.push(tpStep);
1077
+ const tlive = await _liveFields(tpName);
1078
+ for (const f of tp.scalar_fields) {
1079
+ if (f.name in tlive) {
1080
+ details.push({ entity: tpName, action: `add_field:${f.name}`, status: "skipped", reason: "exists" });
1081
+ continue;
1082
+ }
1083
+ const step = await _runWrite(`add_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type, f.title, {
1084
+ required: f.required ?? false,
1085
+ subType: f.sub_type ?? null,
1086
+ maxLength: f.max_length ?? null,
1087
+ decimalPlaces: f.decimal_places ?? null,
1088
+ }));
1089
+ step.entity = tpName;
1090
+ details.push(step);
1091
+ }
1092
+ for (const f of tp.enum_fields) {
1093
+ if (f.name in tlive) {
1094
+ details.push({ entity: tpName, action: `add_enum_field:${f.name}`, status: "skipped", reason: "exists" });
1095
+ continue;
1096
+ }
1097
+ if (f.values && f.values.length) {
1098
+ try {
1099
+ await entityTools.addEnumValues(f.enum_name, f.values.join(","));
1100
+ }
1101
+ catch {
1102
+ // enum-values failure is reported via the field add below
1103
+ }
1104
+ }
1105
+ const step = await _runWrite(`add_enum_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type ?? "enum", f.title, {
1106
+ required: f.required ?? false,
1107
+ enumName: f.enum_name,
1108
+ }));
1109
+ step.entity = tpName;
1110
+ details.push(step);
1111
+ }
1112
+ }
860
1113
  }
861
1114
  // Pass 2: relations (targets now exist).
862
1115
  for (const ent of plan.entities) {
@@ -875,6 +1128,15 @@ export async function _execute(plan, mode = "create") {
875
1128
  });
876
1129
  continue;
877
1130
  }
1131
+ if (f.create === false) {
1132
+ details.push({
1133
+ entity: name,
1134
+ action: `add_relation:${f.name}`,
1135
+ status: "skipped",
1136
+ reason: "no populated instances in v1 (skip_empty_relations)",
1137
+ });
1138
+ continue;
1139
+ }
878
1140
  if (!f.relation_entity || !(f.target_in_set ?? true)) {
879
1141
  details.push({
880
1142
  entity: name,
@@ -892,15 +1154,54 @@ export async function _execute(plan, mode = "create") {
892
1154
  details.push(step);
893
1155
  }
894
1156
  }
895
- // Verify: re-read each entity and confirm every planned field is present.
896
- const verify = {};
1157
+ // Pass 2b: relations declared on tabular parts (targets now exist).
897
1158
  for (const ent of plan.entities) {
898
- const name = ent.name;
1159
+ for (const tp of (ent.tabular_parts ?? [])) {
1160
+ if (!tp.relation_fields || tp.relation_fields.length === 0) {
1161
+ continue;
1162
+ }
1163
+ const tlive = await _liveFields(tp.name);
1164
+ for (const f of tp.relation_fields) {
1165
+ if (f.name in tlive) {
1166
+ details.push({ entity: tp.name, action: `add_relation:${f.name}`, status: "skipped", reason: "exists" });
1167
+ continue;
1168
+ }
1169
+ if (f.create === false) {
1170
+ details.push({
1171
+ entity: tp.name,
1172
+ action: `add_relation:${f.name}`,
1173
+ status: "skipped",
1174
+ reason: "no populated instances in v1 (skip_empty_relations)",
1175
+ });
1176
+ continue;
1177
+ }
1178
+ if (!f.relation_entity || !(f.target_in_set ?? true)) {
1179
+ details.push({
1180
+ entity: tp.name,
1181
+ action: `add_relation:${f.name}`,
1182
+ status: "skipped",
1183
+ reason: `relation target not in migration set (${f.relation_entity})`,
1184
+ });
1185
+ continue;
1186
+ }
1187
+ const step = await _runWrite(`add_relation:${f.name}`, () => entityTools.addField(tp.name, f.name, f.type, f.title, {
1188
+ required: f.required ?? false,
1189
+ relationEntity: f.relation_entity,
1190
+ }));
1191
+ step.entity = tp.name;
1192
+ details.push(step);
1193
+ }
1194
+ }
1195
+ }
1196
+ // Verify: re-read each entity (and each tabular part) and confirm every
1197
+ // planned field is present.
1198
+ const verify = {};
1199
+ const verifyOne = async (name, spec) => {
899
1200
  const planned = [
900
- ...ent.scalar_fields.map((f) => f.name),
901
- ...ent.enum_fields.map((f) => f.name),
902
- ...ent.relation_fields
903
- .filter((f) => f.relation_entity && (f.target_in_set ?? true))
1201
+ ...spec.scalar_fields.map((f) => f.name),
1202
+ ...spec.enum_fields.map((f) => f.name),
1203
+ ...(spec.relation_fields ?? [])
1204
+ .filter((f) => f.relation_entity && (f.target_in_set ?? true) && f.create !== false)
904
1205
  .map((f) => f.name),
905
1206
  ];
906
1207
  const present = new Set(Object.keys(await _liveFields(name)));
@@ -909,6 +1210,12 @@ export async function _execute(plan, mode = "create") {
909
1210
  present: planned.filter((p) => present.has(p)).sort(),
910
1211
  missing: planned.filter((p) => !present.has(p)).sort(),
911
1212
  };
1213
+ };
1214
+ for (const ent of plan.entities) {
1215
+ await verifyOne(ent.name, ent);
1216
+ for (const tp of (ent.tabular_parts ?? [])) {
1217
+ await verifyOne(tp.name, tp);
1218
+ }
912
1219
  }
913
1220
  return {
914
1221
  executed: true,
@@ -965,7 +1272,9 @@ export async function _reconcile(plan) {
965
1272
  const plannedFields = [
966
1273
  ...ent.scalar_fields.map((f) => [f.name, f.type]),
967
1274
  ...ent.enum_fields.map((f) => [f.name, f.type ?? "enum"]),
968
- ...ent.relation_fields.map((f) => [f.name, f.type]),
1275
+ ...ent.relation_fields
1276
+ .filter((f) => f.create !== false)
1277
+ .map((f) => [f.name, f.type]),
969
1278
  ];
970
1279
  const present = [];
971
1280
  const missing = [];
@@ -1034,14 +1343,20 @@ function _validatePlan(plan) {
1034
1343
  * plan_file: when set, load the plan from this JSON file instead of reading from Suppa 1.0.
1035
1344
  * mode: 'create' (default) and 'gap-fill' both skip existing entities/fields (idempotent);
1036
1345
  * 'reconcile' is a read-only diff of the plan vs. the live 2.0 tenant (writes nothing).
1346
+ * check_relation_instances: probe Suppa 1.0 (POST /api/search/{alias}) to see whether each
1347
+ * relation candidate is actually populated in the source; annotates the plan with
1348
+ * v1_populated + create flags (default true).
1349
+ * skip_empty_relations: when a probed relation has no populated instances in v1, exclude it
1350
+ * from creation (create:false) — the tool's decision that the field isn't needed. Probe
1351
+ * errors leave the field as create:true. Default true; set false to keep every relation.
1037
1352
  */
1038
- export async function migrateEntities(dryRun = true, entityNames = "", includeBuiltin = false, skipRelations = false, outputFile = "", planFile = "", mode = "create") {
1353
+ export async function migrateEntities(dryRun = true, entityNames = "", includeBuiltin = false, skipRelations = false, outputFile = "", planFile = "", mode = "create", checkRelationInstances = true, skipEmptyRelations = true) {
1039
1354
  let plan;
1040
1355
  if (planFile) {
1041
1356
  plan = _validatePlan(JSON.parse(readFileSync(planFile, { encoding: "utf-8" })));
1042
1357
  }
1043
1358
  else {
1044
- plan = await _buildPlan(entityNames, includeBuiltin, skipRelations);
1359
+ plan = await _buildPlan(entityNames, includeBuiltin, skipRelations, checkRelationInstances, skipEmptyRelations);
1045
1360
  }
1046
1361
  let writtenTo = null;
1047
1362
  if (outputFile) {