Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions src/mint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,18 +228,18 @@ export function importedLinkState(raw: unknown, workflow: WorkflowJSON): Importe
}

/**
* The `links` map key for one interior link of a definition: the tuple's
* `[0]` for the litegraph array form, `id` for the frontend's object form, and
* the link's mint position for anything else (so an id-less entry still
* occupies its own key rather than colliding on `"undefined"`).
* The explicit `links` map key for one interior link of a definition: the
* tuple's `[0]` for the litegraph array form or `id` for the frontend's object
* form. ID-less links receive a collision-free positional key in
* `mintDefinition` after all explicit keys have been reserved.
*/
function definitionLinkKey(ln: unknown, index: number): string {
function definitionLinkKey(ln: unknown): string | undefined {
if (Array.isArray(ln) && ln[0] !== undefined) return String(ln[0]);
if (typeof ln === "object" && ln !== null && !Array.isArray(ln)) {
const id = (ln as { id?: unknown }).id;
if (id !== undefined && id !== null) return String(id);
}
return `#${String(index)}`;
return undefined;
}

export function mintDefinition(sg: SubgraphDef, catalog: WidgetCatalog): Y.Map<unknown> {
Expand All @@ -263,14 +263,27 @@ export function mintDefinition(sg: SubgraphDef, catalog: WidgetCatalog): Y.Map<u
} else if (k === "links" && Array.isArray(v)) {
const lm = new Y.Map<unknown>();
const order: string[] = [];
const usedKeys = new Set<string>();
for (const link of v) {
const key = definitionLinkKey(link);
if (key === undefined) continue;
if (usedKeys.has(key)) throw new TypeError(`mint: duplicate definition link id '${key}'`);
usedKeys.add(key);
}
v.forEach((ln, i) => {
// A definition's interior links are serialized by the frontend as
// OBJECTS (`{id, origin_id, origin_slot, target_id, target_slot,
// type}`), not top-level tuples. Keying every shape by `ln[0]` read
// `undefined` off each object, so every interior link of a real
// template collapsed onto one key and the round trip emitted the last
// one N times (found by the z-image turbo fixture, Amendment A15).
const key = definitionLinkKey(ln, i);
const explicitKey = definitionLinkKey(ln);
let key = explicitKey ?? `#${String(i)}`;
if (explicitKey === undefined) {
const base = key;
for (let suffix = 1; usedKeys.has(key); suffix += 1) key = `${base}~${String(suffix)}`;
usedKeys.add(key);
}
order.push(key);
lm.set(key, cloneForMap(ln, `mint: definition link ${key}`));
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down
72 changes: 72 additions & 0 deletions test/definition-links-roundtrip.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* The 18 links below are the template's, verbatim and in authored order.
*/
import { describe, expect, it } from "vitest";
import * as Y from "yjs";
import { mint, project, type WidgetCatalog, type WorkflowJSON } from "../src/index.js";
import { loadCatalog } from "./helpers.js";

Expand Down Expand Up @@ -92,6 +93,21 @@ const catalog: WidgetCatalog = loadCatalog();
const interiorLinks = (wf: WorkflowJSON) =>
(wf["definitions"] as { subgraphs: { links: unknown[] }[] }).subgraphs[0]!.links;

function withInteriorLinks(links: unknown[]): WorkflowJSON {
const wf = zImageTemplate();
(wf["definitions"] as { subgraphs: { links: unknown[] }[] }).subgraphs[0]!.links = links;
return wf;
}

function interiorLinkStorage(doc: Y.Doc): { keys: string[]; order: string[] } {
const definition = doc.getMap<Y.Map<unknown>>("definitions").get(DEF)!;
const links = definition.get("links") as Y.Map<unknown>;
return {
keys: [...links.keys()],
order: definition.get("link_order") as string[],
};
}

describe("mint → project keeps a definition's interior links distinct (frontend object form)", () => {
it("round-trips all 18 links of the z-image turbo definition with exact ids, origins, targets and slots, in authored order", () => {
const out = project(mint(zImageTemplate(), catalog), catalog);
Expand Down Expand Up @@ -122,4 +138,60 @@ describe("mint → project keeps a definition's interior links distinct (fronten
const out = project(mint(wf, catalog), catalog);
expect(interiorLinks(out)).toEqual(sg.links);
});

it("reserves a later explicit '#0' before allocating the id-less link at position zero", () => {
const idless = { origin_id: 101, origin_slot: 1, target_id: 102, target_slot: 2, type: "IDLESS" };
const explicit = { id: "#0", origin_id: 201, origin_slot: 3, target_id: 202, target_slot: 4, type: "EXPLICIT" };
const doc = mint(withInteriorLinks([idless, explicit]), catalog);

expect(interiorLinks(project(doc, catalog))).toEqual([idless, explicit]);
expect(interiorLinkStorage(doc)).toEqual({ keys: ["#0~1", "#0"], order: ["#0~1", "#0"] });
});

it("preserves reverse-order noncollision keys and exact asymmetric projected values", () => {
const explicit = { id: "#0", origin_id: 301, origin_slot: 5, target_id: 302, target_slot: 6, type: "EXPLICIT-FIRST" };
const idless = { origin_id: 401, origin_slot: 7, target_id: 402, target_slot: 8, type: "IDLESS-SECOND" };
const doc = mint(withInteriorLinks([explicit, idless]), catalog);

expect(interiorLinks(project(doc, catalog))).toEqual([explicit, idless]);
expect(interiorLinkStorage(doc)).toEqual({ keys: ["#0", "#1"], order: ["#0", "#1"] });
});

it("loops past explicit suffix adversaries while keeping every internal key and order entry unique", () => {
const idless = { origin_id: 501, origin_slot: 9, target_id: 502, target_slot: 10, type: "IDLESS" };
const explicitBase = { id: "#0", origin_id: 601, origin_slot: 11, target_id: 602, target_slot: 12, type: "BASE" };
const explicitSuffix = { id: "#0~1", origin_id: 701, origin_slot: 13, target_id: 702, target_slot: 14, type: "SUFFIX" };
const doc = mint(withInteriorLinks([idless, explicitBase, explicitSuffix]), catalog);
const storage = interiorLinkStorage(doc);

expect(interiorLinks(project(doc, catalog))).toEqual([idless, explicitBase, explicitSuffix]);
expect(storage).toEqual({ keys: ["#0~2", "#0", "#0~1"], order: ["#0~2", "#0", "#0~1"] });
expect(new Set(storage.keys).size).toBe(3);
expect(new Set(storage.order).size).toBe(3);
});

it("reserves normalized tuple IDs before allocating synthetic keys", () => {
const idless = { origin_id: 801, origin_slot: 15, target_id: 802, target_slot: 16, type: "IDLESS" };
const tuple = ["#0", 901, 17, 902, 18, "TUPLE"];
const doc = mint(withInteriorLinks([idless, tuple]), catalog);

expect(interiorLinks(project(doc, catalog))).toEqual([idless, tuple]);
expect(interiorLinkStorage(doc)).toEqual({ keys: ["#0~1", "#0"], order: ["#0~1", "#0"] });
});

it.each([
["tuple then object", [[1, 1001, 19, 1002, 20, "TUPLE-FIRST"], { id: "1", origin_id: 1101, origin_slot: 21, target_id: 1102, target_slot: 22, type: "OBJECT-SECOND" }]],
["object then tuple", [{ id: "1", origin_id: 1201, origin_slot: 23, target_id: 1202, target_slot: 24, type: "OBJECT-FIRST" }, [1, 1301, 25, 1302, 26, "TUPLE-SECOND"]]],
])("refuses duplicate explicit normalized link IDs in %s order", (_name, links) => {
expect(() => mint(withInteriorLinks(links), catalog)).toThrow(new TypeError("mint: duplicate definition link id '1'"));
});

it("accepts distinct normalized tuple and object IDs with exact asymmetric payloads", () => {
const tuple = [1, 1401, 27, 1402, 28, "TUPLE"];
const object = { id: "2", origin_id: 1501, origin_slot: 29, target_id: 1502, target_slot: 30, type: "OBJECT" };
const doc = mint(withInteriorLinks([tuple, object]), catalog);

expect(interiorLinks(project(doc, catalog))).toEqual([tuple, object]);
expect(interiorLinkStorage(doc)).toEqual({ keys: ["1", "2"], order: ["1", "2"] });
});
});
Loading