@needle-tools/addressing 0.3.1 → 0.3.2

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.
@@ -0,0 +1,30 @@
1
+ import { type GraphNode, type NeedleAddress } from "./address.js";
2
+ import { type GltfJson } from "./gltf.js";
3
+ export type GltfResolveResult = {
4
+ type: string;
5
+ index: number;
6
+ element: Record<string, unknown>;
7
+ };
8
+ /**
9
+ * Resolve an address inside glTF JSON. Tries id → anchor → namePath (nodes), in that
10
+ * order; returns null when nothing matches exactly (reconciliation is a separate,
11
+ * explicit step — resolution never guesses).
12
+ */
13
+ export declare function resolveInGltf(address: NeedleAddress, json: GltfJson): GltfResolveResult | null;
14
+ /**
15
+ * Resolve an address inside a live scene graph (duck-typed — any three.js).
16
+ * Same order as glTF resolution: id → anchor → namePath.
17
+ */
18
+ export declare function resolveInGraph(address: NeedleAddress, root: GraphNode): GraphNode | null;
19
+ export type ReconcileCandidate = {
20
+ object: GraphNode;
21
+ /** 0..1 — heuristic, for ranking and thresholds; 1.0 is reserved for exact resolution */
22
+ confidence: number;
23
+ reasons: string[];
24
+ };
25
+ /**
26
+ * When exact resolution fails (the asset changed), propose candidates instead of
27
+ * guessing: nodes matching the address's name, ranked by how much of the recorded
28
+ * namePath still matches. Callers decide thresholds and whether to re-anchor.
29
+ */
30
+ export declare function reconcileInGraph(address: NeedleAddress, root: GraphNode): ReconcileCandidate[];
@@ -0,0 +1,168 @@
1
+ import { parseAnchorValue } from "./anchor.js";
2
+ import { collectionKeyForType } from "./address.js";
3
+ import { NEEDLE_ID_KEY, STAMPED_COLLECTIONS } from "./gltf.js";
4
+ /**
5
+ * Resolve an address inside glTF JSON. Tries id → anchor → namePath (nodes), in that
6
+ * order; returns null when nothing matches exactly (reconciliation is a separate,
7
+ * explicit step — resolution never guesses).
8
+ */
9
+ export function resolveInGltf(address, json) {
10
+ const searched = address.type
11
+ ? [[address.type, collectionKeyForType(address.type)]]
12
+ : [...STAMPED_COLLECTIONS];
13
+ if (address.id) {
14
+ for (const [type, key] of searched) {
15
+ const found = findInCollection(json, key, el => el.extras?.[NEEDLE_ID_KEY] === address.id);
16
+ if (found)
17
+ return { type, index: found.index, element: found.element };
18
+ }
19
+ }
20
+ if (address.anchor) {
21
+ for (const [type, key] of searched) {
22
+ const found = findInCollection(json, key, el => parseAnchorValue(el.name) === address.anchor);
23
+ if (found)
24
+ return { type, index: found.index, element: found.element };
25
+ }
26
+ }
27
+ if (address.namePath?.length && (!address.type || address.type === "node")) {
28
+ const index = walkGltfNamePath(json, address.namePath);
29
+ if (index !== null) {
30
+ const nodes = json["nodes"];
31
+ return { type: "node", index, element: nodes[index] };
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+ /**
37
+ * Resolve an address inside a live scene graph (duck-typed — any three.js).
38
+ * Same order as glTF resolution: id → anchor → namePath.
39
+ */
40
+ export function resolveInGraph(address, root) {
41
+ if (address.id) {
42
+ const byId = findInGraph(root, n => n.userData?.[NEEDLE_ID_KEY] === address.id);
43
+ if (byId)
44
+ return byId;
45
+ }
46
+ if (address.anchor) {
47
+ const byAnchor = findInGraph(root, n => parseAnchorValue(n.name) === address.anchor);
48
+ if (byAnchor)
49
+ return byAnchor;
50
+ }
51
+ if (address.namePath?.length) {
52
+ let current = root;
53
+ for (const segment of address.namePath) {
54
+ current = current.children?.find(c => (c.name ?? "") === segment) ?? null;
55
+ if (!current)
56
+ break;
57
+ }
58
+ if (current && current !== root)
59
+ return current;
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * When exact resolution fails (the asset changed), propose candidates instead of
65
+ * guessing: nodes matching the address's name, ranked by how much of the recorded
66
+ * namePath still matches. Callers decide thresholds and whether to re-anchor.
67
+ */
68
+ export function reconcileInGraph(address, root) {
69
+ if (!address.name && !address.namePath?.length)
70
+ return [];
71
+ const targetName = address.name ?? address.namePath[address.namePath.length - 1];
72
+ const candidates = [];
73
+ collectDescendants(root, (node, namePath) => {
74
+ if ((node.name ?? "") !== targetName)
75
+ return;
76
+ const reasons = [`name matches "${targetName}"`];
77
+ let confidence = 0.5;
78
+ if (address.namePath?.length) {
79
+ const similarity = pathSuffixSimilarity(address.namePath, namePath);
80
+ confidence += 0.4 * similarity;
81
+ if (similarity > 0)
82
+ reasons.push(`path suffix similarity ${(similarity * 100).toFixed(0)}%`);
83
+ }
84
+ candidates.push({ object: node, confidence, reasons });
85
+ });
86
+ if (candidates.length === 1) {
87
+ candidates[0].confidence = Math.min(0.95, candidates[0].confidence + 0.1);
88
+ candidates[0].reasons.push("only candidate with this name");
89
+ }
90
+ return candidates.sort((a, b) => b.confidence - a.confidence);
91
+ }
92
+ function findInCollection(json, key, predicate) {
93
+ const collection = json[key];
94
+ if (!Array.isArray(collection))
95
+ return null;
96
+ for (let i = 0; i < collection.length; i++) {
97
+ const element = collection[i];
98
+ if (element != null && typeof element === "object" && predicate(element)) {
99
+ return { index: i, element };
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ function walkGltfNamePath(json, namePath) {
105
+ const nodes = json["nodes"];
106
+ const scenes = json["scenes"];
107
+ if (!Array.isArray(nodes) || !Array.isArray(scenes))
108
+ return null;
109
+ // roots: the union of all scenes' root nodes
110
+ let candidates = scenes.flatMap(s => (Array.isArray(s?.nodes) ? s.nodes : []));
111
+ let match = null;
112
+ for (const segment of namePath) {
113
+ match = candidates.find(i => ((nodes[i]?.name ?? "") === segment)) ?? null;
114
+ if (match === null)
115
+ return null;
116
+ const children = nodes[match]?.children;
117
+ candidates = Array.isArray(children) ? children : [];
118
+ }
119
+ return match;
120
+ }
121
+ function findInGraph(root, predicate, visited = new Set()) {
122
+ if (visited.has(root))
123
+ return null;
124
+ visited.add(root);
125
+ if (predicate(root))
126
+ return root;
127
+ if (!root.children)
128
+ return null;
129
+ for (let i = 0; i < root.children.length; i++) {
130
+ const child = root.children[i];
131
+ if (child == null)
132
+ continue;
133
+ const found = findInGraph(child, predicate, visited);
134
+ if (found)
135
+ return found;
136
+ }
137
+ return null;
138
+ }
139
+ /** visit every descendant of root with its root-exclusive name path (including own name) */
140
+ function collectDescendants(root, visit) {
141
+ const visited = new Set();
142
+ const walk = (node, namePath) => {
143
+ if (visited.has(node))
144
+ return;
145
+ visited.add(node);
146
+ if (node !== root)
147
+ visit(node, namePath);
148
+ if (!node.children)
149
+ return;
150
+ for (let i = 0; i < node.children.length; i++) {
151
+ const child = node.children[i];
152
+ if (child == null)
153
+ continue;
154
+ walk(child, [...namePath, child.name ?? ""]);
155
+ }
156
+ };
157
+ walk(root, []);
158
+ }
159
+ /** how much of the expected path's tail matches the actual path's tail (0..1) */
160
+ function pathSuffixSimilarity(expected, actual) {
161
+ let shared = 0;
162
+ while (shared < expected.length &&
163
+ shared < actual.length &&
164
+ expected[expected.length - 1 - shared] === actual[actual.length - 1 - shared]) {
165
+ shared++;
166
+ }
167
+ return shared / Math.max(expected.length, actual.length);
168
+ }
package/dist/uuid.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** RFC 4122 URL namespace — the namespace needle-cloud's `ensureUUID` uses (`uuidv5.URL`). */
2
+ export declare const UUID_NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
3
+ /**
4
+ * RFC 4122 version-5 (SHA-1, name-based) UUID. Byte-identical to the `uuid` npm
5
+ * package's `v5(name, namespace)`.
6
+ */
7
+ export declare function uuidv5(name: string, namespace?: string): string;
8
+ /**
9
+ * Random UUID for content that has no source file to be deterministic against
10
+ * (scratch content created in an editor). Uses the platform's crypto when available.
11
+ */
12
+ export declare function randomUuid(): string;
package/dist/uuid.js ADDED
@@ -0,0 +1,49 @@
1
+ import { sha1, toHex } from "./hash.js";
2
+ /** RFC 4122 URL namespace — the namespace needle-cloud's `ensureUUID` uses (`uuidv5.URL`). */
3
+ export const UUID_NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
4
+ /**
5
+ * RFC 4122 version-5 (SHA-1, name-based) UUID. Byte-identical to the `uuid` npm
6
+ * package's `v5(name, namespace)`.
7
+ */
8
+ export function uuidv5(name, namespace = UUID_NAMESPACE_URL) {
9
+ const ns = parseUuidBytes(namespace);
10
+ const nameBytes = new TextEncoder().encode(name);
11
+ const input = new Uint8Array(ns.length + nameBytes.length);
12
+ input.set(ns);
13
+ input.set(nameBytes, ns.length);
14
+ const hash = sha1(input).slice(0, 16);
15
+ hash[6] = (hash[6] & 0x0f) | 0x50; // version 5
16
+ hash[8] = (hash[8] & 0x3f) | 0x80; // RFC 4122 variant
17
+ return formatUuid(hash);
18
+ }
19
+ /**
20
+ * Random UUID for content that has no source file to be deterministic against
21
+ * (scratch content created in an editor). Uses the platform's crypto when available.
22
+ */
23
+ export function randomUuid() {
24
+ const cryptoObj = globalThis.crypto;
25
+ if (cryptoObj?.randomUUID)
26
+ return cryptoObj.randomUUID();
27
+ const bytes = new Uint8Array(16);
28
+ if (cryptoObj?.getRandomValues)
29
+ cryptoObj.getRandomValues(bytes);
30
+ else
31
+ for (let i = 0; i < 16; i++)
32
+ bytes[i] = Math.floor(Math.random() * 256);
33
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
34
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
35
+ return formatUuid(bytes);
36
+ }
37
+ function parseUuidBytes(uuid) {
38
+ const hex = uuid.replace(/-/g, "");
39
+ if (hex.length !== 32)
40
+ throw new Error(`Invalid UUID: ${uuid}`);
41
+ const bytes = new Uint8Array(16);
42
+ for (let i = 0; i < 16; i++)
43
+ bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
44
+ return bytes;
45
+ }
46
+ function formatUuid(bytes) {
47
+ const hex = toHex(bytes);
48
+ return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}`;
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/addressing",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Persistent addressing for Needle assets: deterministic needle-id computation, #needle anchors, and address resolution over glTF JSON and live scene graphs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -8,16 +8,19 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./src/index.ts",
11
+ "node": "./dist/index.js",
11
12
  "default": "./src/index.ts"
12
13
  }
13
14
  },
14
15
  "files": [
16
+ "dist",
15
17
  "src",
16
18
  "Readme.md"
17
19
  ],
18
20
  "scripts": {
19
21
  "build": "tsc -p tsconfig.json",
20
- "test": "vitest run"
22
+ "test": "vitest run",
23
+ "prepack": "npm run build"
21
24
  },
22
25
  "author": {
23
26
  "name": "Needle",
package/src/address.ts CHANGED
@@ -1,106 +1,106 @@
1
- import { parseAnchorValue } from "./anchor.js";
2
- import { getElementId, NEEDLE_ID_KEY, type GltfJson, type StampedElementType } from "./gltf.js";
3
-
4
- /**
5
- * A persistent pointer to an element inside an asset — the "fat address": every
6
- * fallback the resolver may need is captured at CREATION time, while the target is
7
- * known, instead of being reconstructed later.
8
- *
9
- * Resolution order: `id` (exact) → `anchor` (survives asset updates) → `namePath`
10
- * (best-effort) → reconciliation (candidates + confidence, never a silent guess).
11
- */
12
- export type NeedleAddress = {
13
- /** the element's needle-id (deterministic for file-backed content, random for scratch) */
14
- id?: string;
15
- /** `#needle` anchor value, when the target's name carries one */
16
- anchor?: string;
17
- /** element type (`node`, `material`, …) — narrows resolution and validates matches */
18
- type?: StampedElementType | (string & {});
19
- /** the target's name at address-creation time */
20
- name?: string;
21
- /** node names from the asset root (exclusive) down to the target (inclusive); nodes only */
22
- namePath?: string[];
23
- };
24
-
25
- /** Structural (duck-typed) view of a live scene-graph node — works with any three.js. */
26
- export type GraphNode = {
27
- name?: string;
28
- children?: readonly GraphNode[];
29
- userData?: Record<string, unknown>;
30
- };
31
-
32
- /** Build an address for a glTF root-collection element. `namePath` only applies to nodes. */
33
- export function createGltfElementAddress(json: GltfJson, type: StampedElementType | string, index: number): NeedleAddress | null {
34
- const collection = json[collectionKeyForType(type)];
35
- if (!Array.isArray(collection)) return null;
36
- const element = collection[index];
37
- if (element == null || typeof element !== "object") return null;
38
-
39
- const name = typeof element.name === "string" ? element.name : undefined;
40
- const address: NeedleAddress = { type };
41
- const id = getElementId(element);
42
- if (id) address.id = id;
43
- const anchor = parseAnchorValue(name);
44
- if (anchor) address.anchor = anchor;
45
- if (name !== undefined) address.name = name;
46
- if (type === "node") {
47
- const path = gltfNodeNamePath(json, index);
48
- if (path) address.namePath = path;
49
- }
50
- return address;
51
- }
52
-
53
- /** Build an address for a live scene-graph object under `root`. */
54
- export function createObjectAddress(root: GraphNode, target: GraphNode): NeedleAddress | null {
55
- const path = findPath(root, target);
56
- if (!path) return null;
57
-
58
- const address: NeedleAddress = { type: "node" };
59
- const id = target.userData?.[NEEDLE_ID_KEY];
60
- if (typeof id === "string") address.id = id;
61
- const anchor = parseAnchorValue(target.name);
62
- if (anchor) address.anchor = anchor;
63
- if (typeof target.name === "string") address.name = target.name;
64
- address.namePath = path.map(n => n.name ?? "");
65
- return address;
66
- }
67
-
68
- export function collectionKeyForType(type: string): string {
69
- // glTF collection keys are the pluralized type names; only "mesh" is irregular
70
- return type === "mesh" ? "meshes" : `${type}s`;
71
- }
72
-
73
- /** names from root (exclusive) to the node at `nodeIndex` (inclusive), via the scene tree */
74
- function gltfNodeNamePath(json: GltfJson, nodeIndex: number): string[] | null {
75
- const nodes = json["nodes"];
76
- if (!Array.isArray(nodes)) return null;
77
- const parents = new Map<number, number>();
78
- for (let i = 0; i < nodes.length; i++) {
79
- const children = nodes[i]?.children;
80
- if (Array.isArray(children)) for (const c of children) parents.set(c, i);
81
- }
82
- const path: string[] = [];
83
- let current: number | undefined = nodeIndex;
84
- const seen = new Set<number>();
85
- while (current !== undefined) {
86
- if (seen.has(current)) return null; // malformed (cyclic) input
87
- seen.add(current);
88
- path.unshift(typeof nodes[current]?.name === "string" ? nodes[current].name : "");
89
- current = parents.get(current);
90
- }
91
- return path;
92
- }
93
-
94
- /** path from root (exclusive) to target (inclusive), or null if target is not under root */
95
- export function findPath(root: GraphNode, target: GraphNode): GraphNode[] | null {
96
- if (root === target) return [];
97
- const children = root.children;
98
- if (!children) return null;
99
- for (let i = 0; i < children.length; i++) {
100
- const child = children[i];
101
- if (child == null) continue;
102
- const sub = findPath(child, target);
103
- if (sub) return [child, ...sub];
104
- }
105
- return null;
106
- }
1
+ import { parseAnchorValue } from "./anchor.js";
2
+ import { getElementId, NEEDLE_ID_KEY, type GltfJson, type StampedElementType } from "./gltf.js";
3
+
4
+ /**
5
+ * A persistent pointer to an element inside an asset — the "fat address": every
6
+ * fallback the resolver may need is captured at CREATION time, while the target is
7
+ * known, instead of being reconstructed later.
8
+ *
9
+ * Resolution order: `id` (exact) → `anchor` (survives asset updates) → `namePath`
10
+ * (best-effort) → reconciliation (candidates + confidence, never a silent guess).
11
+ */
12
+ export type NeedleAddress = {
13
+ /** the element's needle-id (deterministic for file-backed content, random for scratch) */
14
+ id?: string;
15
+ /** `#needle` anchor value, when the target's name carries one */
16
+ anchor?: string;
17
+ /** element type (`node`, `material`, …) — narrows resolution and validates matches */
18
+ type?: StampedElementType | (string & {});
19
+ /** the target's name at address-creation time */
20
+ name?: string;
21
+ /** node names from the asset root (exclusive) down to the target (inclusive); nodes only */
22
+ namePath?: string[];
23
+ };
24
+
25
+ /** Structural (duck-typed) view of a live scene-graph node — works with any three.js. */
26
+ export type GraphNode = {
27
+ name?: string;
28
+ children?: readonly GraphNode[];
29
+ userData?: Record<string, unknown>;
30
+ };
31
+
32
+ /** Build an address for a glTF root-collection element. `namePath` only applies to nodes. */
33
+ export function createGltfElementAddress(json: GltfJson, type: StampedElementType | string, index: number): NeedleAddress | null {
34
+ const collection = json[collectionKeyForType(type)];
35
+ if (!Array.isArray(collection)) return null;
36
+ const element = collection[index];
37
+ if (element == null || typeof element !== "object") return null;
38
+
39
+ const name = typeof element.name === "string" ? element.name : undefined;
40
+ const address: NeedleAddress = { type };
41
+ const id = getElementId(element);
42
+ if (id) address.id = id;
43
+ const anchor = parseAnchorValue(name);
44
+ if (anchor) address.anchor = anchor;
45
+ if (name !== undefined) address.name = name;
46
+ if (type === "node") {
47
+ const path = gltfNodeNamePath(json, index);
48
+ if (path) address.namePath = path;
49
+ }
50
+ return address;
51
+ }
52
+
53
+ /** Build an address for a live scene-graph object under `root`. */
54
+ export function createObjectAddress(root: GraphNode, target: GraphNode): NeedleAddress | null {
55
+ const path = findPath(root, target);
56
+ if (!path) return null;
57
+
58
+ const address: NeedleAddress = { type: "node" };
59
+ const id = target.userData?.[NEEDLE_ID_KEY];
60
+ if (typeof id === "string") address.id = id;
61
+ const anchor = parseAnchorValue(target.name);
62
+ if (anchor) address.anchor = anchor;
63
+ if (typeof target.name === "string") address.name = target.name;
64
+ address.namePath = path.map(n => n.name ?? "");
65
+ return address;
66
+ }
67
+
68
+ export function collectionKeyForType(type: string): string {
69
+ // glTF collection keys are the pluralized type names; only "mesh" is irregular
70
+ return type === "mesh" ? "meshes" : `${type}s`;
71
+ }
72
+
73
+ /** names from root (exclusive) to the node at `nodeIndex` (inclusive), via the scene tree */
74
+ function gltfNodeNamePath(json: GltfJson, nodeIndex: number): string[] | null {
75
+ const nodes = json["nodes"];
76
+ if (!Array.isArray(nodes)) return null;
77
+ const parents = new Map<number, number>();
78
+ for (let i = 0; i < nodes.length; i++) {
79
+ const children = nodes[i]?.children;
80
+ if (Array.isArray(children)) for (const c of children) parents.set(c, i);
81
+ }
82
+ const path: string[] = [];
83
+ let current: number | undefined = nodeIndex;
84
+ const seen = new Set<number>();
85
+ while (current !== undefined) {
86
+ if (seen.has(current)) return null; // malformed (cyclic) input
87
+ seen.add(current);
88
+ path.unshift(typeof nodes[current]?.name === "string" ? nodes[current].name : "");
89
+ current = parents.get(current);
90
+ }
91
+ return path;
92
+ }
93
+
94
+ /** path from root (exclusive) to target (inclusive), or null if target is not under root */
95
+ export function findPath(root: GraphNode, target: GraphNode): GraphNode[] | null {
96
+ if (root === target) return [];
97
+ const children = root.children;
98
+ if (!children) return null;
99
+ for (let i = 0; i < children.length; i++) {
100
+ const child = children[i];
101
+ if (child == null) continue;
102
+ const sub = findPath(child, target);
103
+ if (sub) return [child, ...sub];
104
+ }
105
+ return null;
106
+ }
package/src/anchor.ts CHANGED
@@ -1,56 +1,68 @@
1
- /**
2
- * The name-anchor scheme: an element named `Door #needle` derives its deterministic id
3
- * from the text before the marker instead of (name, index, file hash) — so the id
4
- * survives content changes and asset re-uploads as long as the name stays.
5
- *
6
- * CONTRACT NOTE — the marker set is part of the id contract. Markers may be ADDED (new
7
- * names start anchoring), but never removed or re-prioritized, and every WRITER of ids
8
- * (this package's consumers: cloud upload, editors, CLI) must agree on the set before a
9
- * new marker ships — a writer that anchors on a marker another writer doesn't know mints
10
- * DIFFERENT ids for the same file. The anchored id only hashes the VALUE (not the
11
- * marker), so all markers are aliases into the same id space.
12
- */
13
-
14
- /** the original marker — kept as a named export for existing consumers */
15
- export const ANCHOR_MARKER = "#needle";
16
-
17
- /**
18
- * All recognized markers, matched longest-first so overlapping suffixes resolve
19
- * deterministically. Currently one entry; see the contract note before adding more.
20
- */
21
- export const ANCHOR_MARKERS: readonly string[] = [ANCHOR_MARKER];
22
-
23
- export type ParsedAnchor = {
24
- /** the marker that matched (one of {@link ANCHOR_MARKERS}) */
25
- marker: string;
26
- /** the anchor value — the deterministic-id input */
27
- value: string;
28
- };
29
-
30
- /**
31
- * Parse an element name against all recognized markers (case-insensitive suffix match).
32
- * Returns null when no marker matches or the anchor value is empty.
33
- */
34
- export function parseAnchor(rawName: string | null | undefined): ParsedAnchor | null {
35
- if (rawName == null) return null;
36
- const trimmed = rawName.trim();
37
- const lower = trimmed.toLowerCase();
38
- for (const marker of byLengthDescending(ANCHOR_MARKERS)) {
39
- if (!lower.endsWith(marker)) continue;
40
- const value = trimmed.substring(0, trimmed.length - marker.length).trim();
41
- return value.length > 0 ? { marker, value } : null;
42
- }
43
- return null;
44
- }
45
-
46
- /**
47
- * Extract the anchor value from an element name, or null when the name carries no anchor.
48
- * Convenience over {@link parseAnchor} for callers that only need the id input.
49
- */
50
- export function parseAnchorValue(rawName: string | null | undefined): string | null {
51
- return parseAnchor(rawName)?.value ?? null;
52
- }
53
-
54
- function byLengthDescending(markers: readonly string[]): readonly string[] {
55
- return markers.length > 1 ? [...markers].sort((a, b) => b.length - a.length) : markers;
56
- }
1
+ /**
2
+ * The name-anchor scheme: an element named `Door #needle` derives its deterministic id
3
+ * from the text before the marker instead of (name, index, file hash) — so the id
4
+ * survives content changes and asset re-uploads as long as the name stays.
5
+ *
6
+ * CONTRACT NOTE — the marker set is part of the id contract. Markers may be ADDED (new
7
+ * names start anchoring), but never removed or re-prioritized, and every WRITER of ids
8
+ * (this package's consumers: cloud upload, editors, CLI) must agree on the set before a
9
+ * new marker ships — a writer that anchors on a marker another writer doesn't know mints
10
+ * DIFFERENT ids for the same file. The anchored id only hashes the VALUE (not the
11
+ * marker), so all markers are aliases into the same id space.
12
+ */
13
+
14
+ /** the original marker — kept as a named export for existing consumers */
15
+ export const ANCHOR_MARKER = "#needle";
16
+
17
+ /**
18
+ * All recognized markers, matched longest-first so overlapping suffixes resolve
19
+ * deterministically. Currently one entry; see the contract note before adding more.
20
+ */
21
+ export const ANCHOR_MARKERS: readonly string[] = [ANCHOR_MARKER];
22
+
23
+ export type ParsedAnchor = {
24
+ /** the marker that matched (one of {@link ANCHOR_MARKERS}) */
25
+ marker: string;
26
+ /** the anchor value — the deterministic-id input */
27
+ value: string;
28
+ };
29
+
30
+ /**
31
+ * Parse an element name against all recognized markers (case-insensitive suffix match).
32
+ * Returns null when no marker matches or the anchor value is empty.
33
+ */
34
+ export function parseAnchor(rawName: string | null | undefined): ParsedAnchor | null {
35
+ if (rawName == null) return null;
36
+ const trimmed = rawName.trim();
37
+ const lower = trimmed.toLowerCase();
38
+ for (const marker of byLengthDescending(ANCHOR_MARKERS)) {
39
+ if (!lower.endsWith(marker)) continue;
40
+ const value = normalizeAnchorValue(trimmed.substring(0, trimmed.length - marker.length));
41
+ return value.length > 0 ? { marker, value } : null;
42
+ }
43
+ return null;
44
+ }
45
+
46
+ /**
47
+ * Anchor values treat SPACES and UNDERSCORES as the same character (runs collapse to
48
+ * one space): three's GLTFLoader sanitizes node names on load (whitespace becomes
49
+ * "_"), so "Door Frame #needle" appears live as "Door_Frame_#needle" — without
50
+ * normalization the stamped anchor and the live anchor would never match. Applied at
51
+ * PARSE time, so id computation and resolution agree from one change point. Accepted
52
+ * trade: names differing only by space-vs-underscore share one anchor.
53
+ */
54
+ function normalizeAnchorValue(value: string): string {
55
+ return value.replace(/[\s_]+/g, " ").trim();
56
+ }
57
+
58
+ /**
59
+ * Extract the anchor value from an element name, or null when the name carries no anchor.
60
+ * Convenience over {@link parseAnchor} for callers that only need the id input.
61
+ */
62
+ export function parseAnchorValue(rawName: string | null | undefined): string | null {
63
+ return parseAnchor(rawName)?.value ?? null;
64
+ }
65
+
66
+ function byLengthDescending(markers: readonly string[]): readonly string[] {
67
+ return markers.length > 1 ? [...markers].sort((a, b) => b.length - a.length) : markers;
68
+ }