Line data Source code
1 : import { toNodeId } from './nodeId'
2 : import type { NodeId } from './nodeId'
3 : type UUID = string
4 :
5 : /**
6 : * A widget's canonical identity: `graphId:nodeId:name`.
7 : * Duplicate widget names must be normalized before deriving this ID.
8 : * See ADR-ECS-0008's "Widget identity keys on name" section.
9 : */
10 : export type WidgetId = string & { readonly __brand: 'WidgetId' }
11 :
12 2356 : const SEPARATOR = ':'
13 2356 : const WIDGET_ID_PATTERN = /^(?<graphId>[^:]+):(?<nodeId>[^:]+):(?<name>[^:]+)$/u
14 :
15 311536 : export function widgetId(
16 : graphId: UUID,
17 : localNodeId: NodeId,
18 : name: string
19 : ): WidgetId {
20 311536 : return [
21 : graphId,
22 : encodeURIComponent(String(localNodeId)),
23 : encodeURIComponent(name)
24 : ].join(SEPARATOR) as WidgetId
25 : }
26 :
27 7 : function nameIsWritable(widget: object): boolean {
28 7 : try {
29 7 : for (
30 : let target: object | null = widget;
31 : target;
32 : target = Reflect.getPrototypeOf(target)
33 : ) {
34 7 : const descriptor = Object.getOwnPropertyDescriptor(target, 'name')
35 7 : if (!descriptor) continue
36 7 : return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set
37 : }
38 0 : return Object.isExtensible(widget)
39 : } catch {
40 0 : return false
41 : }
42 : }
43 :
44 198616 : export function ensureUniqueWidgetNames(
45 : widgets: readonly { name: string }[]
46 : ): boolean {
47 198616 : try {
48 198616 : const reserved = new Set(widgets.map(({ name }) => name))
49 198616 : const used = new Set<string>()
50 198616 : const seen = new Set<unknown>()
51 198616 : const renames: { widget: { name: string }; name: string }[] = []
52 :
53 198616 : for (const widget of widgets) {
54 : // The same widget object may transiently occupy multiple array slots
55 : // (e.g. during an index-assignment reorder). Identity duplicates are
56 : // one widget, not a name collision — never rename them.
57 996561 : if (seen.has(widget)) continue
58 995371 : seen.add(widget)
59 995371 : if (!used.has(widget.name)) {
60 995371 : used.add(widget.name)
61 995371 : continue
62 : }
63 :
64 0 : let index = 1
65 996561 : while (
66 : used.has(`${widget.name}#${index}`) ||
67 : reserved.has(`${widget.name}#${index}`)
68 : ) {
69 0 : index++
70 : }
71 0 : const name = `${widget.name}#${index}`
72 0 : used.add(name)
73 0 : renames.push({ widget, name })
74 : }
75 :
76 198616 : if (renames.some(({ widget }) => !nameIsWritable(widget))) {
77 0 : console.warn('Cannot safely rename duplicate widgets')
78 0 : return false
79 : }
80 :
81 198616 : let unique = true
82 198616 : for (const { widget, name } of renames) {
83 0 : try {
84 0 : widget.name = name
85 0 : if (widget.name !== name) unique = false
86 : } catch {
87 0 : unique = false
88 : }
89 : }
90 198616 : return unique
91 : } catch (error) {
92 0 : console.warn('Failed to rename duplicate widgets', error)
93 0 : return false
94 : }
95 : }
96 :
97 2356 : const UNREADABLE_NAME = Symbol('unreadable widget name')
98 :
99 : export type RefusedWidget<T> =
100 : | { widget: T; cause: 'unreadable-name'; name: undefined }
101 : | { widget: T; cause: 'duplicate-name'; name: string }
102 : | { widget: T; cause: 'unresolved-duplicate'; name: string }
103 :
104 306010 : function readName(widget: { name: unknown }): string | typeof UNREADABLE_NAME {
105 306010 : try {
106 306010 : const raw = widget.name
107 306010 : if (typeof raw === 'symbol') return UNREADABLE_NAME
108 : const key = String(raw)
109 : encodeURIComponent(key)
110 306010 : return key
111 : } catch {
112 0 : return UNREADABLE_NAME
113 : }
114 : }
115 :
116 17 : function tryRename(widget: { name: unknown }, name: string): boolean {
117 17 : try {
118 17 : widget.name = name
119 17 : return widget.name === name
120 : } catch {
121 7 : return false
122 : }
123 : }
124 :
125 191251 : export function isWidgetNameUnreadable(widget: { name: unknown }): boolean {
126 191251 : return readName(widget) === UNREADABLE_NAME
127 : }
128 :
129 20805 : function readableNames(widgets: readonly { name: unknown }[]): Set<string> {
130 20805 : const names = new Set<string>()
131 20805 : for (const widget of widgets) {
132 57418 : const name = readName(widget)
133 57418 : if (name !== UNREADABLE_NAME) names.add(name)
134 : }
135 20805 : return names
136 : }
137 :
138 17 : function freeSuffixedName(
139 : name: string,
140 : isTaken: (candidate: string) => boolean
141 : ): string {
142 17 : let index = 1
143 17 : while (isTaken(`${name}#${index}`)) index++
144 17 : return `${name}#${index}`
145 : }
146 :
147 17 : function resolveCollision(
148 : widget: { name: unknown },
149 : key: string,
150 : used: Set<string>,
151 : reserved: Set<string>,
152 : isNameTaken: (name: string) => boolean
153 : ): 'renamed' | 'unresolved-duplicate' | 'duplicate-name' {
154 17 : const candidate = freeSuffixedName(
155 : key,
156 : (name) => used.has(name) || reserved.has(name) || isNameTaken(name)
157 : )
158 17 : if (tryRename(widget, candidate)) {
159 10 : used.add(candidate)
160 10 : reserved.add(candidate)
161 10 : return 'renamed'
162 : }
163 17 : return nameIsWritable(widget) ? 'unresolved-duplicate' : 'duplicate-name'
164 : }
165 :
166 20805 : export function dropUnrenamableDuplicateWidgets<T extends { name: unknown }>(
167 : widgets: T[],
168 : isNameTaken: (name: string) => boolean = () => false
169 : ): RefusedWidget<T>[] {
170 20805 : const kept: T[] = []
171 20805 : const refused: RefusedWidget<T>[] = []
172 20805 : const used = new Set<string>()
173 20805 : const reserved = readableNames(widgets)
174 20805 : const verdicts = new Map<T, boolean>()
175 :
176 20805 : for (const widget of widgets) {
177 57418 : const previous = verdicts.get(widget)
178 57418 : if (previous !== undefined) {
179 77 : if (previous) kept.push(widget)
180 77 : continue
181 : }
182 :
183 57341 : const key = readName(widget)
184 57418 : if (key === UNREADABLE_NAME) {
185 0 : verdicts.set(widget, false)
186 0 : refused.push({ widget, cause: 'unreadable-name', name: undefined })
187 0 : continue
188 : }
189 :
190 57345 : if (!used.has(key)) {
191 57324 : used.add(key)
192 57324 : verdicts.set(widget, true)
193 57324 : kept.push(widget)
194 57324 : continue
195 : }
196 :
197 17 : const outcome = resolveCollision(widget, key, used, reserved, isNameTaken)
198 17 : const keep = outcome !== 'duplicate-name'
199 17 : verdicts.set(widget, keep)
200 112 : if (keep) kept.push(widget)
201 324 : if (outcome !== 'renamed')
202 7 : refused.push({ widget, cause: outcome, name: key })
203 : }
204 :
205 20805 : if (refused.length) widgets.splice(0, widgets.length, ...kept)
206 20805 : return refused
207 : }
208 :
209 1033618 : function decodeWidgetIdSegment(segment: string): string {
210 1033618 : try {
211 1033618 : return decodeURIComponent(segment)
212 : } catch (error) {
213 0 : if (error instanceof URIError) return segment
214 0 : throw error
215 : }
216 : }
217 :
218 516809 : export function parseWidgetId(id: WidgetId): {
219 : graphId: UUID
220 : nodeId: NodeId
221 : name: string
222 : } {
223 516809 : const groups = WIDGET_ID_PATTERN.exec(id)?.groups
224 516809 : if (!groups) throw new Error('Invalid widget id')
225 :
226 516809 : return {
227 : graphId: groups.graphId,
228 : nodeId: toNodeId(decodeWidgetIdSegment(groups.nodeId)),
229 : name: decodeWidgetIdSegment(groups.name)
230 : }
231 : }
232 :
233 457191 : export function isWidgetId(value: unknown): value is WidgetId {
234 457191 : if (typeof value !== 'string') return false
235 457191 : return WIDGET_ID_PATTERN.test(value)
236 : }
|