glassbrain 0.2.0-alpha.5 → 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.
package/README.md CHANGED
@@ -22,10 +22,12 @@ lets you read one at a glance, and when the agent learns something, shows you ex
22
22
  ```json
23
23
  {
24
24
  "nodes": [
25
- { "id": "src", "label": "src", "kind": "folder", "parent": null },
26
- { "id": "src/auth", "label": "auth", "kind": "folder", "parent": "src@1" },
27
- { "id": "src/auth/login.ts", "label": "login.ts", "kind": "file", "parent": "src/auth@-1" },
28
- { "id": "src/db.ts", "label": "db.ts", "kind": "file", "parent": "src@2" }
25
+ { "id": "src", "label": "src", "kind": "folder", "children": [
26
+ { "id": "src/auth", "label": "auth", "kind": "folder", "children": [
27
+ { "id": "src/auth/login.ts", "label": "login.ts", "kind": "file" }
28
+ ] },
29
+ { "id": "src/db.ts", "label": "db.ts", "kind": "file" }
30
+ ] }
29
31
  ],
30
32
  "edges": [{ "source": "src/auth/login.ts", "target": "src/db.ts", "kind": "uses" }]
31
33
  }
@@ -39,13 +41,17 @@ it as an error (forty kinds without colours look exactly like one kind):
39
41
  "edgePalette": { "uses": "#2563eb" } }
40
42
  ```
41
43
 
42
- `parent` is required on every node (null for the one root) and says what sits inside what **and where
43
- it sits**: `id@order`, or `id@-1` for an explicitly unordered set. The layout reads the numbers
44
- clockwise when seeding recursive sectors: the outer circle has `n+1` equal sectors for `n` children, with
45
- sector 0 empty and centered at the top. Descendants subdivide their parent’s angular interval around the same
46
- origin, without adding further empty sectors. Each child samples a small normal angular offset; unordered siblings also
47
- shuffle sector order. Re-layout discards saved coordinates and samples a new seed. The force solver relaxes it
48
- without a final rotation. A root whose children are numbered *is* the 2.5D layer view. There is no layer field.
44
+ Only `id` is required. Nest nodes in `children`; array order is reading order. `kind` is recommended.
45
+ Within one pass, fragments with the same id fill absent fields. Equal values are accepted; conflicting values
46
+ are errors. Repeated `children` declarations must have the same direct child ids in the same order;
47
+ child details compose independently. An omitted list is unspecified; `[]` explicitly declares no children.
48
+ Top-level fragments attach wherever their id appears in another node's children. Unattached nodes are roots.
49
+ Each node has at most one parent, and cycles are errors. Each pass is a complete snapshot.
50
+
51
+ The layout reads children clockwise when seeding recursive sectors: the outer circle reserves an empty
52
+ sector at the top, and descendants subdivide their parent's angular interval. Re-layout samples again;
53
+ the force solver can change the final angular order. The layer view uses the root's children, or the forest's
54
+ roots, in reading order. No parent, order or layer field is written. See [tree composition](https://github.com/voidixyn/glassbrain/blob/main/docs/cli.md#tree-fragments-and-composition).
49
55
  A [JSON Schema](https://github.com/voidixyn/glassbrain/blob/main/schema/graph.schema.json) describes every field, and the CLI answers in a form an
50
56
  agent can act on — findings identify the problem and structural advice suggests a next step:
51
57
 
@@ -100,7 +106,7 @@ That makes change the main event:
100
106
 
101
107
  Search ranks by how well a node matches, the detail panel renders the node's markdown, labels
102
108
  make room for each other instead of piling up, and [dark mode is computed](https://github.com/voidixyn/glassbrain/blob/main/docs/guide.md#color-hue-is-configured-everything-else-is-computed)
103
- from the light palette. A root whose children carry `order` opens as floors in 2.5D:
109
+ from the light palette. The root’s children can be read as floors in 2.5D:
104
110
 
105
111
  ![Protocols, building blocks and products of the agent ecosystem, stacked in 2.5D](https://raw.githubusercontent.com/voidixyn/glassbrain/main/docs/media/layers.png)
106
112
 
package/dist/adapters.js CHANGED
@@ -481,12 +481,36 @@ function adapt(files, only) {
481
481
  const out = pick.convert(files);
482
482
  const skipped = pick === MARKDOWN ? [] : files.filter((f) => /\.jsonl?$/i.test(f.path) && !pick.detect([f])).map((f) => f.path);
483
483
  return {
484
- sources: out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify(s.graph) })),
484
+ sources: treeSources(out),
485
485
  profile: out.profile,
486
486
  adapter: pick,
487
487
  skipped
488
488
  };
489
489
  }
490
+ function treeSources(out) {
491
+ const children = /* @__PURE__ */ new Map();
492
+ for (const s of out.sources) for (const n of s.graph.nodes) {
493
+ if (!n.parent) continue;
494
+ const kids = children.get(n.parent) ?? /* @__PURE__ */ new Map();
495
+ kids.set(n.id, typeof n.order === "number" ? n.order : void 0);
496
+ children.set(n.parent, kids);
497
+ }
498
+ const written = /* @__PURE__ */ new Set();
499
+ return out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify({
500
+ ...s.graph,
501
+ nodes: s.graph.nodes.map((n) => {
502
+ const { parent: _parent, order: _order, layer: _layer, ...fields } = n;
503
+ const kids = children.get(n.id);
504
+ if (!kids || written.has(n.id)) return fields;
505
+ written.add(n.id);
506
+ return {
507
+ ...fields,
508
+ ...fields.unordered === void 0 && [...kids.values()].every((v) => v === void 0) ? { unordered: true } : {},
509
+ children: [...kids].sort((a, b) => (a[1] ?? Infinity) - (b[1] ?? Infinity)).map(([id]) => ({ id }))
510
+ };
511
+ })
512
+ }) }));
513
+ }
490
514
  var isNativeGraph = (f) => {
491
515
  if (!/\.json$/i.test(f.path)) return false;
492
516
  try {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  EN
3
- } from "./chunk-ISWKAU5G.js";
3
+ } from "./chunk-5DEN6HXJ.js";
4
4
 
5
5
  // src/react/i18n.ts
6
6
  import { createContext, useContext } from "react";
@@ -175,6 +175,7 @@ function DetailPanel({ node, spec, kindLabels, onClose, renderText, onEdit, colo
175
175
  "label",
176
176
  "parent",
177
177
  "order",
178
+ "children",
178
179
  "layer",
179
180
  "flags"
180
181
  ]);
@@ -201,8 +202,8 @@ function DetailPanel({ node, spec, kindLabels, onClose, renderText, onEdit, colo
201
202
  /* @__PURE__ */ jsx3("span", { children: node.parent ?? "Root" })
202
203
  ] }),
203
204
  node.parent && /* @__PURE__ */ jsxs("div", { className: "gb-line", children: [
204
- /* @__PURE__ */ jsx3("span", { className: "gb-k", children: "Order" }),
205
- /* @__PURE__ */ jsx3("span", { children: node.order ?? "Unordered" })
205
+ /* @__PURE__ */ jsx3("span", { className: "gb-k", children: "Position" }),
206
+ /* @__PURE__ */ jsx3("span", { children: node.order ?? "\u2014" })
206
207
  ] }),
207
208
  node.flags.map((f) => {
208
209
  const note = spec.flagNotes?.[f];
@@ -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 = [];
@@ -617,7 +782,7 @@ function buildElements(model, profile, opts = {}) {
617
782
  kind: n.kind ?? "",
618
783
  layer,
619
784
  origin: n.origin ?? null,
620
- order: n.order ?? null,
785
+ order: n.parent && model.index.get(n.parent)?.data?.unordered === true ? null : n.order ?? null,
621
786
  // Parentage for the layout's order pass. A separate key, not `parent`: cytoscape treats `data.parent` as a compound.
622
787
  parentId: effParent ?? null,
623
788
  share: shareOf(n.id),
@@ -1656,8 +1821,12 @@ function checkEdit(model, op) {
1656
1821
  if (order != null && (!Number.isFinite(order) || order <= 0)) return "order-invalid";
1657
1822
  const current = model.index.get(op.id);
1658
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
+ }
1659
1828
  const value = order === null ? void 0 : order ?? current?.order;
1660
- 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";
1661
1830
  }
1662
1831
  switch (op.op) {
1663
1832
  case "addNode":
@@ -1689,7 +1858,7 @@ function applyEdit(model, op, profile) {
1689
1858
  function apply(model, op, profile) {
1690
1859
  const layerOf = (n) => profile ? profile.layerOf(n) : n.layer;
1691
1860
  const fields = (n, set) => {
1692
- const { parent, order, ...rest } = set;
1861
+ const { parent, order, before: _before, ...rest } = set;
1693
1862
  const next = { ...n, ...rest };
1694
1863
  if (parent !== void 0) {
1695
1864
  if (parent) {
@@ -1702,6 +1871,18 @@ function apply(model, op, profile) {
1702
1871
  next.layer = layerOf(next);
1703
1872
  return next;
1704
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
+ };
1705
1886
  switch (op.op) {
1706
1887
  case "addNode": {
1707
1888
  const dad = op.set.parent ? model.index.get(op.set.parent) : void 0;
@@ -1712,11 +1893,11 @@ function apply(model, op, profile) {
1712
1893
  layer: dad?.layer,
1713
1894
  ...origin ? { origin, origins: [origin] } : {}
1714
1895
  };
1715
- 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);
1716
1897
  }
1717
1898
  case "updateNode":
1718
1899
  return buildModel(
1719
- 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)),
1720
1901
  model.edges,
1721
1902
  model.errors
1722
1903
  );
@@ -1753,25 +1934,7 @@ function applyEdits(model, ops, profile) {
1753
1934
  }
1754
1935
  return { model: m, skipped };
1755
1936
  }
1756
- function checkNativeEdit(model, op) {
1757
- if (op.op === "addNode" && !/^[^\s@]{1,80}$/.test(op.id)) return "id-format";
1758
- const basic = checkEdit(model, op);
1759
- if (basic) return basic;
1760
- const next = apply(model, op);
1761
- const oldRoots = model.nodes.filter((n) => !n.parent).length;
1762
- if (next.nodes.filter((n) => !n.parent).length > Math.max(1, oldRoots)) return "multiple-roots";
1763
- const siblings = /* @__PURE__ */ new Map();
1764
- for (const n of next.nodes) if (n.parent) {
1765
- const xs = siblings.get(n.parent) ?? [];
1766
- xs.push(n);
1767
- siblings.set(n.parent, xs);
1768
- }
1769
- for (const xs of siblings.values()) {
1770
- const count = xs.filter((n) => n.order !== void 0).length;
1771
- if (count && count !== xs.length) return "order-mixed";
1772
- }
1773
- return null;
1774
- }
1937
+ var checkNativeEdit = checkEdit;
1775
1938
 
1776
1939
  // src/animate.ts
1777
1940
  var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
@@ -2332,9 +2495,9 @@ export {
2332
2495
  originsOfNode,
2333
2496
  indexModel,
2334
2497
  originsOf,
2335
- encodeParent,
2336
2498
  parsePhysical,
2337
2499
  toPhysical,
2500
+ toBundle,
2338
2501
  validateStructure,
2339
2502
  defineProfile,
2340
2503
  defaultProfile,
@@ -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",