glassbrain 0.2.0-alpha.4 → 0.2.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,175 @@
1
+ // src/tree.ts
2
+ var object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
3
+ var ref = (x) => typeof x === "string" || typeof x === "number" ? String(x) : void 0;
4
+ var stable = (x) => JSON.stringify(x, function(_key, value) {
5
+ return object(value) ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]])) : value;
6
+ });
7
+ function treeDeclarations(raw, origin) {
8
+ const declarations = [];
9
+ const rootIds = [];
10
+ const problems = [];
11
+ const stack = (Array.isArray(raw) ? raw : []).map((node, i) => ({ node, path: `nodes[${i}]`, top: true })).reverse();
12
+ if (raw !== void 0 && !Array.isArray(raw)) problems.push("nodes must be an array");
13
+ while (stack.length) {
14
+ const { node, path, top } = stack.pop();
15
+ if (!object(node) || ref(node.id) === void 0) {
16
+ problems.push(`${path}: expected a node with id`);
17
+ continue;
18
+ }
19
+ const id = ref(node.id);
20
+ if (!id.trim()) problems.push(`${path}.id: expected a non-empty identity`);
21
+ if (top) rootIds.push(id);
22
+ const { children, ...fields } = node;
23
+ if ("parent" in node || "order" in node) problems.push(`${path}: parent/order are not supported; nest nodes in children`);
24
+ if ("unordered" in node && typeof node.unordered !== "boolean") problems.push(`${path}.unordered must be a boolean`);
25
+ const declaration = { id, fields: { ...fields, id }, path: `${origin}:${path}` };
26
+ if ("children" in node) {
27
+ if (!Array.isArray(children)) problems.push(`${path}.children must be an array`);
28
+ else {
29
+ declaration.children = children.filter(object).map((n) => ref(n.id)).filter((id2) => id2 !== void 0);
30
+ for (let i = children.length - 1; i >= 0; i--) stack.push({ node: children[i], path: `${path}.children[${i}]`, top: false });
31
+ }
32
+ }
33
+ declarations.push(declaration);
34
+ }
35
+ return { declarations, rootIds, ...problems.length ? { error: problems.slice(0, 20).join("; ") } : {} };
36
+ }
37
+ function treeNodes(declarations = []) {
38
+ const placements = /* @__PURE__ */ new Map();
39
+ for (const d of declarations) d.children?.forEach((id, i) => placements.set(id, { parent: d.id, order: i + 1 }));
40
+ return declarations.map(({ id, fields }) => ({
41
+ id,
42
+ ...placements.get(id),
43
+ label: String(fields.label ?? fields.name ?? id),
44
+ ...typeof fields.kind === "string" ? { kind: fields.kind } : {},
45
+ ...Array.isArray(fields.flags) ? { flags: fields.flags.filter((f) => typeof f === "string") } : {},
46
+ data: fields
47
+ }));
48
+ }
49
+ function composeTrees(input) {
50
+ const slices = [...input].sort((a, b) => a.origin < b.origin ? -1 : a.origin > b.origin ? 1 : 0);
51
+ const errors = [];
52
+ const records = /* @__PURE__ */ new Map();
53
+ const roots = [];
54
+ for (const slice of slices) {
55
+ if (slice.error) errors.push({ origin: slice.origin, code: "schema", message: slice.error });
56
+ if (!slice.declarations && slice.nodes.length) {
57
+ errors.push({ origin: slice.origin, code: "schema", message: "Cannot compose flat runtime slices with native children fragments." });
58
+ continue;
59
+ }
60
+ roots.push(...slice.rootIds ?? []);
61
+ for (const d of slice.declarations ?? []) {
62
+ let r = records.get(d.id);
63
+ if (!r) {
64
+ r = { fields: /* @__PURE__ */ Object.create(null), locations: /* @__PURE__ */ new Map(), origins: [] };
65
+ records.set(d.id, r);
66
+ }
67
+ if (!r.origins.includes(slice.origin)) r.origins.push(slice.origin);
68
+ for (const [field, value] of [...Object.entries(d.fields), ...d.children === void 0 ? [] : [["children", d.children]]]) {
69
+ const previous = field === "children" ? r.children : r.fields[field];
70
+ if (r.locations.has(field) && stable(previous) !== stable(value)) {
71
+ errors.push({
72
+ origin: slice.origin,
73
+ node: d.id,
74
+ code: field === "children" ? "children-conflict" : "field-conflict",
75
+ message: `"${d.id}".${field}: ${r.locations.get(field)} = ${stable(previous)} conflicts with ${d.path} = ${stable(value)}; provide one consistent value (lists are not combined).`
76
+ });
77
+ } else if (!r.locations.has(field)) {
78
+ if (field === "children") r.children = value;
79
+ else r.fields[field] = value;
80
+ r.locations.set(field, d.path);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ const parents = /* @__PURE__ */ new Map();
86
+ const positions = /* @__PURE__ */ new Map();
87
+ for (const [id, r] of records) {
88
+ const seen = /* @__PURE__ */ new Set();
89
+ for (const [i, child] of (r.children ?? []).entries()) {
90
+ if (seen.has(child)) errors.push({ origin: r.origins[0], node: id, code: "children-conflict", message: `${r.locations.get("children")}: "${child}" occurs twice in children of "${id}".` });
91
+ seen.add(child);
92
+ const old = parents.get(child);
93
+ if (old !== void 0 && old !== id) {
94
+ errors.push({ origin: r.origins[0], node: child, code: "parent-error", message: `"${child}" has two parents: "${old}" (${records.get(old).locations.get("children")}) and "${id}" (${r.locations.get("children")}). Keep one placement.` });
95
+ } else {
96
+ parents.set(child, id);
97
+ positions.set(child, i + 1);
98
+ }
99
+ }
100
+ }
101
+ const done = /* @__PURE__ */ new Set();
102
+ for (const id of records.keys()) {
103
+ const chain = [], at = /* @__PURE__ */ new Map();
104
+ let cur = id;
105
+ while (cur !== void 0 && !done.has(cur)) {
106
+ if (at.has(cur)) {
107
+ const loop = [...chain.slice(at.get(cur)), cur];
108
+ errors.push({ origin: records.get(cur).origins[0], node: cur, code: "parent-error", message: `parent cycle: ${loop.join(" \u2192 ")}. Remove one children placement.` });
109
+ parents.delete(cur);
110
+ positions.delete(cur);
111
+ break;
112
+ }
113
+ at.set(cur, chain.length);
114
+ chain.push(cur);
115
+ cur = parents.get(cur);
116
+ }
117
+ chain.forEach((x) => done.add(x));
118
+ }
119
+ const orderedRoots = [.../* @__PURE__ */ new Set([...roots, ...records.keys()])].filter((id) => !parents.has(id));
120
+ const ordered = [], visited = /* @__PURE__ */ new Set(), stack = [...orderedRoots].reverse();
121
+ while (stack.length) {
122
+ const id = stack.pop();
123
+ if (visited.has(id) || !records.has(id)) continue;
124
+ visited.add(id);
125
+ ordered.push(id);
126
+ const kids = records.get(id).children ?? [];
127
+ for (let i = kids.length - 1; i >= 0; i--) if (parents.get(kids[i]) === id) stack.push(kids[i]);
128
+ }
129
+ const rootRanks = new Map(orderedRoots.map((id, i) => [id, i + 1]));
130
+ const nodes = ordered.map((id) => {
131
+ const r = records.get(id);
132
+ const n = treeNodes([{ id, fields: r.fields, path: "" }])[0];
133
+ return { ...n, parent: parents.get(id), order: positions.get(id) ?? rootRanks.get(id), origin: r.origins[0], origins: r.origins };
134
+ });
135
+ return buildModel(nodes, slices.flatMap((s) => s.edges), errors);
136
+ }
137
+ function serializeTree(model) {
138
+ if (model.errors.length || model.duplicateIds?.length) throw new Error("Cannot export a graph with unresolved input conflicts");
139
+ const records = /* @__PURE__ */ new Map();
140
+ const groups = /* @__PURE__ */ new Map();
141
+ for (const n of model.nodes) {
142
+ if (records.has(n.id)) throw new Error(`Duplicate id: ${n.id}`);
143
+ if (n.parent && !model.index.has(n.parent)) throw new Error(`Missing parent: ${n.parent}`);
144
+ const { parent: _parent, order: _order, layer: _layer, children: _children, ...data } = n.data ?? {};
145
+ records.set(n.id, Object.fromEntries(Object.entries({ ...data, id: n.id, label: n.label, kind: n.kind }).filter(([, v]) => v !== void 0)));
146
+ const group = groups.get(n.parent) ?? [];
147
+ group.push(n);
148
+ groups.set(n.parent, group);
149
+ }
150
+ for (const list of groups.values()) list.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
151
+ const roots = groups.get(void 0) ?? [];
152
+ const visited = /* @__PURE__ */ new Set(), stack = [...roots];
153
+ while (stack.length) {
154
+ const n = stack.pop();
155
+ if (visited.has(n.id)) throw new Error(`Parent cycle: ${n.id}`);
156
+ visited.add(n.id);
157
+ const kids = groups.get(n.id);
158
+ if (kids?.length) {
159
+ const record = records.get(n.id);
160
+ if (!("unordered" in record) && kids.every((k) => k.order === void 0)) record.unordered = true;
161
+ record.children = kids.map((k) => records.get(k.id));
162
+ stack.push(...kids);
163
+ }
164
+ }
165
+ if (visited.size !== model.nodes.length) throw new Error("Parent cycle: no rooted forest can be exported");
166
+ for (const e of model.edges) if (!records.has(e.source) || !records.has(e.target)) throw new Error(`Dangling edge: ${e.source} \u2192 ${e.target}`);
167
+ return {
168
+ nodes: roots.map((n) => records.get(n.id)),
169
+ edges: model.edges.map((e) => Object.fromEntries(Object.entries({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }).filter(([, v]) => v !== void 0)))
170
+ };
171
+ }
172
+
1
173
  // src/model.ts
2
174
  var EMPTY_MODEL = { nodes: [], edges: [], errors: [], index: /* @__PURE__ */ new Map() };
3
175
  function buildModel(nodes, edges, errors = []) {
@@ -6,6 +178,10 @@ function buildModel(nodes, edges, errors = []) {
6
178
  return { nodes, edges, errors, index };
7
179
  }
8
180
  function mergeSlices(slices) {
181
+ if (slices.some((s) => s.declarations?.length) || slices.every((s) => !s.nodes.length)) return composeTrees(slices);
182
+ return mergeRuntimeSlices(slices);
183
+ }
184
+ function mergeRuntimeSlices(slices) {
9
185
  const byId = /* @__PURE__ */ new Map();
10
186
  const edges = [];
11
187
  const errors = [];
@@ -90,19 +266,6 @@ function originsOf(model) {
90
266
  for (const n of model.nodes) for (const o of originsOfNode(n)) seen.add(o);
91
267
  return [...seen].sort();
92
268
  }
93
- function encodeParent(parent, order) {
94
- if (!parent) return null;
95
- if (order === void 0) return `${parent}@-1`;
96
- if (!Number.isFinite(order) || order <= 0) throw new Error("order must be finite and positive");
97
- const text = String(order);
98
- if (!/[eE]/.test(text)) return `${parent}@${text}`;
99
- const [mantissa, exponent] = text.toLowerCase().split("e");
100
- const [whole, fraction = ""] = mantissa.split(".");
101
- const digits = whole + fraction;
102
- const at = whole.length + Number(exponent);
103
- const decimal = at <= 0 ? `0.${"0".repeat(-at)}${digits}` : at >= digits.length ? digits + "0".repeat(at - digits.length) : `${digits.slice(0, at)}.${digits.slice(at)}`;
104
- return `${parent}@${decimal}`;
105
- }
106
269
 
107
270
  // src/profile.ts
108
271
  function parsePhysical(origin, text) {
@@ -113,30 +276,6 @@ function parsePhysical(origin, text) {
113
276
  return { origin, title: origin, nodes: [], edges: [], error: e instanceof Error ? e.message : String(e) };
114
277
  }
115
278
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
116
- const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
117
- const parentOf = (v) => {
118
- const rawParent = ref(v);
119
- const at = rawParent?.lastIndexOf("@") ?? -1;
120
- const tail = at > 0 ? rawParent.slice(at + 1) : "";
121
- if (!/^(-1|\d+(\.\d+)?)$/.test(tail)) return { parent: rawParent, order: void 0 };
122
- const order = tail === "-1" ? void 0 : Number(tail);
123
- return { parent: rawParent.slice(0, at), order: order !== void 0 && order > 0 ? order : void 0 };
124
- };
125
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => {
126
- const { parent, order } = parentOf(n.parent);
127
- return {
128
- id: String(n.id),
129
- label: String(n.label ?? n.name ?? n.id),
130
- kind: typeof n.kind === "string" ? n.kind : void 0,
131
- parent,
132
- order,
133
- layer: typeof n.layer === "string" ? n.layer : void 0,
134
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
135
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
136
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
137
- data: n
138
- };
139
- });
140
279
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
141
280
  source: String(e.source ?? e.from),
142
281
  target: String(e.target ?? e.to),
@@ -146,23 +285,22 @@ function parsePhysical(origin, text) {
146
285
  // The whole record, like nodes' `data`: fields the library does not know survive a round trip (convert, toPhysical).
147
286
  data: e
148
287
  }));
149
- return { origin, title: String(raw.name ?? raw.title ?? origin), nodes, edges };
288
+ const parsed = treeDeclarations(raw.nodes, origin);
289
+ return { origin, title: String(raw.name ?? raw.title ?? origin), nodes: treeNodes(parsed.declarations), edges, ...parsed };
150
290
  }
151
291
  function toPhysical(model) {
152
- const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
153
- return {
154
- // `layer` is derived, never written: a file that gains it would freeze a view decision into the data.
155
- // `parent` is always written, `null` for a root, and carries the order: `"<id>@<order|-1>"`. `order` is never a field of its own.
156
- nodes: model.nodes.map((n) => {
157
- const { order: _order, layer: _layer, ...data } = n.data ?? {};
158
- return clean({ ...data, id: n.id, label: n.label, kind: n.kind, parent: encodeParent(n.parent, n.order) });
159
- }),
160
- edges: model.edges.map((e) => clean({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
161
- };
292
+ return serializeTree(model);
293
+ }
294
+ function toBundle(model, profile = null) {
295
+ const palette = Object.assign(/* @__PURE__ */ Object.create(null), profile?.nodePalette ?? {});
296
+ const wheel = ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6", "#06b6d4", "#ec4899", "#84cc16"];
297
+ const kinds = [...new Set(model.nodes.map((n) => n.kind).filter((k) => !!k))];
298
+ for (const [i, kind] of kinds.entries()) if (!Object.hasOwn(palette, kind)) palette[kind] = wheel[i % wheel.length];
299
+ return { profile: { ...profile, nodePalette: palette }, ...toPhysical(model) };
162
300
  }
163
301
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
164
302
  function validateStructure(model) {
165
- const out = [];
303
+ const out = model.errors.map((e) => ({ kind: e.code ?? "schema", group: "Invalid graph", level: "error", nodeId: e.node, message: `${e.origin}: ${e.message}` }));
166
304
  const seen = /* @__PURE__ */ new Set();
167
305
  const dup = /* @__PURE__ */ new Set();
168
306
  for (const n of model.nodes) {
@@ -254,7 +392,7 @@ var DIFF_FLAG = {
254
392
  merged: "gb-merged"
255
393
  };
256
394
  var KEPT_FLAG = "gb-kept";
257
- var stable = (v, ignore) => {
395
+ var stable2 = (v, ignore) => {
258
396
  const walk = (x) => {
259
397
  if (Array.isArray(x)) return x.map(walk);
260
398
  if (x && typeof x === "object") {
@@ -272,7 +410,7 @@ function changedFields(a, b, ignore) {
272
410
  const ob = b ?? {};
273
411
  const keys = new Set([...Object.keys(oa), ...Object.keys(ob)].filter((k) => !ignore.has(k)));
274
412
  const out = [];
275
- for (const k of keys) if (stable(oa[k], ignore) !== stable(ob[k], ignore)) out.push(k);
413
+ for (const k of keys) if (stable2(oa[k], ignore) !== stable2(ob[k], ignore)) out.push(k);
276
414
  return out.sort();
277
415
  }
278
416
  var EDIT_CAP = 512;
@@ -307,7 +445,7 @@ function editDistance(a, b) {
307
445
  return prev[m] + over;
308
446
  }
309
447
  function changeAmount(a, b, fields, ignore) {
310
- const pick = (n) => fields.map((k) => stable((n.data ?? {})[k], ignore)).join("\0");
448
+ const pick = (n) => fields.map((k) => stable2((n.data ?? {})[k], ignore)).join("\0");
311
449
  return editDistance(pick(a), pick(b)) + editDistance(a.label ?? "", b.label ?? "");
312
450
  }
313
451
  var edgeKey = (e) => `${e.source} ${e.target} ${e.kind ?? ""}`;
@@ -330,8 +468,30 @@ function diffModels(before, after, opts = {}) {
330
468
  const b = afterByKey.get(k);
331
469
  if (b) resolve.set(list[0].id, b.id);
332
470
  }
333
- const ref = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
471
+ const ref2 = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
334
472
  const consumed = new Set(resolve.keys());
473
+ const reordered = /* @__PURE__ */ new Set();
474
+ if (!ignore.has("position")) {
475
+ const groups = /* @__PURE__ */ new Map();
476
+ for (const a of before.nodes) {
477
+ const id = resolve.get(a.id), b = id ? after.index.get(id) : void 0;
478
+ if (!b || ref2(a.parent) !== b.parent) continue;
479
+ if (a.parent && before.index.get(a.parent)?.data?.unordered === true || b.parent && after.index.get(b.parent)?.data?.unordered === true) continue;
480
+ const p = b.parent;
481
+ const g = groups.get(p) ?? { old: [], next: [] };
482
+ g.old.push(a);
483
+ g.next.push(b);
484
+ groups.set(p, g);
485
+ }
486
+ for (const g of groups.values()) {
487
+ g.old.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
488
+ const ranks = new Map(after.nodes.map((n, i) => [n.id, i]));
489
+ g.next.sort((a, b) => (a.order ?? ranks.get(a.id)) - (b.order ?? ranks.get(b.id)));
490
+ g.old.forEach((a, i) => {
491
+ if (resolve.get(a.id) !== g.next[i].id) reordered.add(g.next[i].id);
492
+ });
493
+ }
494
+ }
335
495
  const changes = [];
336
496
  const prevData = /* @__PURE__ */ new Map();
337
497
  const moved = /* @__PURE__ */ new Map();
@@ -343,8 +503,13 @@ function diffModels(before, after, opts = {}) {
343
503
  flag = DIFF_FLAG.added;
344
504
  changes.push({ kind: "added", id: b.id });
345
505
  } else {
346
- const fields = changedFields(a.data, b.data, ignore);
347
- const aParent = ref(a.parent) ?? null;
506
+ const own = (n) => {
507
+ const { children: _children, parent: _parent, order: _order, ...data } = n.data ?? {};
508
+ return { ...data, kind: n.kind };
509
+ };
510
+ const fields = changedFields(own(a), own(b), ignore);
511
+ if (reordered.has(b.id)) fields.push("position");
512
+ const aParent = ref2(a.parent) ?? null;
348
513
  if (aParent !== (b.parent ?? null)) {
349
514
  flag = DIFF_FLAG.moved;
350
515
  changes.push({
@@ -381,7 +546,7 @@ function diffModels(before, after, opts = {}) {
381
546
  const merged = !!to && after.index.has(to);
382
547
  const kind = merged ? "merged" : "removed";
383
548
  changes.push({ kind, id: a.id, pairId: merged ? to : void 0 });
384
- const parent = ref(a.parent);
549
+ const parent = ref2(a.parent);
385
550
  nodes.push({
386
551
  ...withFlag(a, DIFF_FLAG[kind]),
387
552
  parent: parent && (unionIds.has(parent) || !consumed.has(a.parent)) ? parent : void 0
@@ -391,7 +556,7 @@ function diffModels(before, after, opts = {}) {
391
556
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
392
557
  const beforeEdges = new Map(
393
558
  before.edges.map((e) => {
394
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
559
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
395
560
  return [edgeKey(r), r];
396
561
  })
397
562
  );
@@ -435,22 +600,22 @@ function unionSides(d) {
435
600
  const afterEdges = d.model.edges.filter(
436
601
  (e) => !has(e, DIFF_FLAG.removed) && aIds.has(e.source) && aIds.has(e.target)
437
602
  );
438
- const ref = (id) => id === void 0 ? void 0 : d.resolved.get(id) ?? id;
603
+ const ref2 = (id) => id === void 0 ? void 0 : d.resolved.get(id) ?? id;
439
604
  const beforeNodes = d.before.nodes.map((n) => {
440
- const id = ref(n.id);
605
+ const id = ref2(n.id);
441
606
  const now = d.model.index.get(id);
442
- const relinked = now && (now.parent ?? null) !== (ref(n.parent) ?? null);
607
+ const relinked = now && (now.parent ?? null) !== (ref2(n.parent) ?? null);
443
608
  return {
444
609
  ...n,
445
610
  id,
446
- parent: ref(n.parent),
611
+ parent: ref2(n.parent),
447
612
  flags: now?.flags ?? n.flags,
448
613
  ...relinked ? { prevParent: now.parent ?? null } : {}
449
614
  };
450
615
  });
451
616
  const bIds = new Set(beforeNodes.map((n) => n.id));
452
617
  const afterKeys = new Set(afterEdges.map(edgeKey));
453
- const beforeEdges = d.before.edges.map((e) => ({ ...e, source: ref(e.source), target: ref(e.target) })).filter((e) => bIds.has(e.source) && bIds.has(e.target)).map((e) => withFlag(e, afterKeys.has(edgeKey(e)) ? KEPT_FLAG : DIFF_FLAG.removed));
618
+ const beforeEdges = d.before.edges.map((e) => ({ ...e, source: ref2(e.source), target: ref2(e.target) })).filter((e) => bIds.has(e.source) && bIds.has(e.target)).map((e) => withFlag(e, afterKeys.has(edgeKey(e)) ? KEPT_FLAG : DIFF_FLAG.removed));
454
619
  return { before: buildModel(beforeNodes, beforeEdges), after: buildModel(afterNodes, afterEdges) };
455
620
  }
456
621
  var STEP_FLAG = { added: "gb-step-added", removed: "gb-step-removed" };
@@ -463,7 +628,7 @@ function stepUnion(before, after, key = (n) => n.id) {
463
628
  const b = afterByKey.get(key(a));
464
629
  if (b) resolved.set(a.id, b.id);
465
630
  }
466
- const ref = (id) => id === void 0 ? void 0 : resolved.get(id) ?? id;
631
+ const ref2 = (id) => id === void 0 ? void 0 : resolved.get(id) ?? id;
467
632
  const paired = new Set(resolved.values());
468
633
  const changes = [];
469
634
  const nodes = [];
@@ -475,12 +640,12 @@ function stepUnion(before, after, key = (n) => n.id) {
475
640
  for (const a of before.nodes) {
476
641
  if (resolved.has(a.id)) continue;
477
642
  changes.push({ kind: "removed", id: a.id });
478
- nodes.push(withFlag({ ...a, parent: ref(a.parent) }, STEP_FLAG.removed));
643
+ nodes.push(withFlag({ ...a, parent: ref2(a.parent) }, STEP_FLAG.removed));
479
644
  }
480
645
  const ids = new Set(nodes.map((n) => n.id));
481
646
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
482
647
  const beforeEdges = new Map(before.edges.map((e) => {
483
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
648
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
484
649
  return [edgeKey(r), r];
485
650
  }));
486
651
  const edges = [];
@@ -526,6 +691,7 @@ function changedSubset(d) {
526
691
  var VIRTUAL_ROOT = "__gk_root__";
527
692
  var RESERVED_CLASSES = ["container", "crosslayer", "contains", "root", "gb-node"];
528
693
  var cls = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_");
694
+ var edgeKindClass = (kind) => kind === "contains" ? "gb-relation-contains" : cls(kind);
529
695
  function nodeClasses(n, profile, o) {
530
696
  return [
531
697
  "gb-node",
@@ -616,7 +782,7 @@ function buildElements(model, profile, opts = {}) {
616
782
  kind: n.kind ?? "",
617
783
  layer,
618
784
  origin: n.origin ?? null,
619
- order: n.order ?? null,
785
+ order: n.parent && model.index.get(n.parent)?.data?.unordered === true ? null : n.order ?? null,
620
786
  // Parentage for the layout's order pass. A separate key, not `parent`: cytoscape treats `data.parent` as a compound.
621
787
  parentId: effParent ?? null,
622
788
  share: shareOf(n.id),
@@ -655,7 +821,7 @@ function buildElements(model, profile, opts = {}) {
655
821
  const { source, target } = e;
656
822
  if (source === target) continue;
657
823
  if (!nodeIds.has(source) || !nodeIds.has(target)) continue;
658
- const id = e.id ?? `${e.kind ?? "e"}:${source}->${target}`;
824
+ const id = e.id ?? `${e.kind === "contains" ? "relation:contains" : e.kind ?? "e"}:${source}->${target}`;
659
825
  if (seen.has(id)) continue;
660
826
  seen.add(id);
661
827
  const cross = layerOf.get(source) !== layerOf.get(target);
@@ -672,7 +838,7 @@ function buildElements(model, profile, opts = {}) {
672
838
  _force: profile.layoutEdge(e)
673
839
  },
674
840
  classes: [
675
- profile.edgeClass(e) || "plain",
841
+ (profile.edgeClass(e) || "plain").split(/\s+/).map(edgeKindClass).join(" "),
676
842
  ...(e.flags ?? []).map(cls),
677
843
  cross ? "crosslayer" : ""
678
844
  ].filter(Boolean).join(" ")
@@ -1065,7 +1231,7 @@ function paletteStyle(profile, theme = LIGHT_THEME, nodeScale = 1) {
1065
1231
  for (const [kind, raw] of Object.entries(profile.edgePalette ?? {})) {
1066
1232
  const color = themeColor(theme, raw);
1067
1233
  out.push({
1068
- selector: `edge.${cls(kind)}`,
1234
+ selector: `edge.${edgeKindClass(kind)}`,
1069
1235
  style: { "line-color": color, "target-arrow-color": color, "source-arrow-color": color }
1070
1236
  });
1071
1237
  }
@@ -1076,7 +1242,7 @@ function paletteStyle(profile, theme = LIGHT_THEME, nodeScale = 1) {
1076
1242
  out.push({ selector: `node.${cls(kind)}`, style: { width: size, height: size } });
1077
1243
  }
1078
1244
  for (const [kind, k] of Object.entries(profile.edgeWidth ?? {})) {
1079
- if (k !== 1) out.push({ selector: `edge.${cls(kind)}`, style: { width: (el) => edgeWidthOf(el) * k } });
1245
+ if (k !== 1) out.push({ selector: `edge.${edgeKindClass(kind)}`, style: { width: (el) => edgeWidthOf(el) * k } });
1080
1246
  }
1081
1247
  for (const flag of profile.placeholderFlags ?? []) {
1082
1248
  out.push({
@@ -1655,8 +1821,12 @@ function checkEdit(model, op) {
1655
1821
  if (order != null && (!Number.isFinite(order) || order <= 0)) return "order-invalid";
1656
1822
  const current = model.index.get(op.id);
1657
1823
  const parent = op.set.parent !== void 0 ? op.set.parent : current?.parent;
1824
+ if (op.set.before != null) {
1825
+ const sibling = model.index.get(op.set.before);
1826
+ if (!sibling || sibling.id === op.id || (sibling.parent ?? null) !== (parent ?? null)) return "invalid-position";
1827
+ }
1658
1828
  const value = order === null ? void 0 : order ?? current?.order;
1659
- if (parent && value !== void 0 && model.nodes.some((n) => n.id !== op.id && n.parent === parent && n.order === value)) return "order-invalid";
1829
+ if (op.set.before === void 0 && (op.set.parent === void 0 || order !== void 0) && parent && value !== void 0 && model.nodes.some((n) => n.id !== op.id && n.parent === parent && n.order === value)) return "order-invalid";
1660
1830
  }
1661
1831
  switch (op.op) {
1662
1832
  case "addNode":
@@ -1688,7 +1858,7 @@ function applyEdit(model, op, profile) {
1688
1858
  function apply(model, op, profile) {
1689
1859
  const layerOf = (n) => profile ? profile.layerOf(n) : n.layer;
1690
1860
  const fields = (n, set) => {
1691
- const { parent, order, ...rest } = set;
1861
+ const { parent, order, before: _before, ...rest } = set;
1692
1862
  const next = { ...n, ...rest };
1693
1863
  if (parent !== void 0) {
1694
1864
  if (parent) {
@@ -1701,6 +1871,18 @@ function apply(model, op, profile) {
1701
1871
  next.layer = layerOf(next);
1702
1872
  return next;
1703
1873
  };
1874
+ const place = (nodes) => {
1875
+ if (op.op !== "addNode" && op.op !== "updateNode") return nodes;
1876
+ const old = model.index.get(op.id);
1877
+ const changedParent = op.op === "addNode" || "parent" in op.set && (old?.parent ?? null) !== op.set.parent;
1878
+ if (!("before" in op.set) && (!changedParent || typeof op.set.order === "number")) return nodes;
1879
+ const moved = nodes.find((n) => n.id === op.id);
1880
+ const siblings = nodes.filter((n) => n.id !== moved.id && n.parent === moved.parent).sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
1881
+ const at = op.set.before ? siblings.findIndex((n) => n.id === op.set.before) : siblings.length;
1882
+ siblings.splice(at < 0 ? siblings.length : at, 0, moved);
1883
+ const ranks = new Map(siblings.map((n, i) => [n.id, i + 1]));
1884
+ return nodes.map((n) => ranks.has(n.id) ? { ...n, order: ranks.get(n.id) } : n);
1885
+ };
1704
1886
  switch (op.op) {
1705
1887
  case "addNode": {
1706
1888
  const dad = op.set.parent ? model.index.get(op.set.parent) : void 0;
@@ -1711,11 +1893,11 @@ function apply(model, op, profile) {
1711
1893
  layer: dad?.layer,
1712
1894
  ...origin ? { origin, origins: [origin] } : {}
1713
1895
  };
1714
- return buildModel([...model.nodes, fields(seed, op.set)], model.edges, model.errors);
1896
+ return buildModel(place([...model.nodes, fields(seed, op.set)]), model.edges, model.errors);
1715
1897
  }
1716
1898
  case "updateNode":
1717
1899
  return buildModel(
1718
- model.nodes.map((n) => n.id === op.id ? fields(n, op.set) : n),
1900
+ place(model.nodes.map((n) => n.id === op.id ? fields(n, op.set) : n)),
1719
1901
  model.edges,
1720
1902
  model.errors
1721
1903
  );
@@ -1752,25 +1934,7 @@ function applyEdits(model, ops, profile) {
1752
1934
  }
1753
1935
  return { model: m, skipped };
1754
1936
  }
1755
- function checkNativeEdit(model, op) {
1756
- if (op.op === "addNode" && !/^[^\s@]{1,80}$/.test(op.id)) return "id-format";
1757
- const basic = checkEdit(model, op);
1758
- if (basic) return basic;
1759
- const next = apply(model, op);
1760
- const oldRoots = model.nodes.filter((n) => !n.parent).length;
1761
- if (next.nodes.filter((n) => !n.parent).length > Math.max(1, oldRoots)) return "multiple-roots";
1762
- const siblings = /* @__PURE__ */ new Map();
1763
- for (const n of next.nodes) if (n.parent) {
1764
- const xs = siblings.get(n.parent) ?? [];
1765
- xs.push(n);
1766
- siblings.set(n.parent, xs);
1767
- }
1768
- for (const xs of siblings.values()) {
1769
- const count = xs.filter((n) => n.order !== void 0).length;
1770
- if (count && count !== xs.length) return "order-mixed";
1771
- }
1772
- return null;
1773
- }
1937
+ var checkNativeEdit = checkEdit;
1774
1938
 
1775
1939
  // src/animate.ts
1776
1940
  var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
@@ -2331,9 +2495,9 @@ export {
2331
2495
  originsOfNode,
2332
2496
  indexModel,
2333
2497
  originsOf,
2334
- encodeParent,
2335
2498
  parsePhysical,
2336
2499
  toPhysical,
2500
+ toBundle,
2337
2501
  validateStructure,
2338
2502
  defineProfile,
2339
2503
  defaultProfile,
@@ -2351,6 +2515,7 @@ export {
2351
2515
  VIRTUAL_ROOT,
2352
2516
  RESERVED_CLASSES,
2353
2517
  cls,
2518
+ edgeKindClass,
2354
2519
  nodeClasses,
2355
2520
  buildElements,
2356
2521
  isNodeEl,
@@ -84,9 +84,7 @@ var EN = {
84
84
  "no-node": "Node not found",
85
85
  "no-parent": "Parent not found",
86
86
  cycle: "Cannot be placed inside itself",
87
- "id-format": "Use 1\u201380 characters without spaces or @",
88
- "multiple-roots": "Keep one root: choose an existing parent",
89
- "order-mixed": "Siblings must all be numbered or all unordered",
87
+ "invalid-position": "Choose a different node in the same children list",
90
88
  "order-invalid": "Order must be positive and unique among siblings (blank = unordered)",
91
89
  "has-children": "Has children \u2014 delete or move them first",
92
90
  "no-endpoint": "Pick both ends",