dsh-keys-manager 0.3.2 → 0.3.4

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,331 @@
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025-2026 Can Bölük
5
+ * Copyright (c) 2026 Stencil Labs, Inc.
6
+ *
7
+ * This file carries code from the `@oh-my-pi/pi-catalog` package's
8
+ * `src/model-catalog-format.ts` (MIT), ported to plain JavaScript. The notice
9
+ * above and this permission text are reproduced as the licence requires; the
10
+ * port itself is described in the module note below.
11
+ *
12
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ * of this software and associated documentation files (the "Software"), to deal
14
+ * in the Software without restriction, including without limitation the rights
15
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ * copies of the Software, and to permit persons to whom the Software is
17
+ * furnished to do so, subject to the following conditions:
18
+ *
19
+ * The above copyright notice and this permission notice shall be included in all
20
+ * copies or substantial portions of the Software.
21
+ *
22
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ * SOFTWARE.
29
+ */
30
+
31
+ /**
32
+ * The compact model-catalog format the pinned `@oh-my-pi/pi-catalog` ships.
33
+ *
34
+ * Ported from `@oh-my-pi/pi-catalog@18.18.8` `src/model-catalog-format.ts` (MIT,
35
+ * © oh-my-pi contributors): `encodeModelCatalog`, `openModelCatalog`,
36
+ * `getCatalogProviders`, `getCatalogProvider` and the decode helpers they use.
37
+ * The logic is kept line-for-line with upstream so a row decoded here is the row
38
+ * upstream would produce; only the TypeScript types are dropped, because this is
39
+ * plain Node ESM build tooling with no build step of its own.
40
+ *
41
+ * Why a copy: the pin's `exports` map points `import` at its `.ts` sources and
42
+ * ships no JS `dist` entry, and both generators run under plain `node`, so they
43
+ * cannot import the implementation. It is build tooling — no shipped module
44
+ * imports it at runtime and `@oh-my-pi/*` stays a build-time pin — but the root
45
+ * package publishes `scripts/`, so this file ships and carries the licence above.
46
+ *
47
+ * Shape (upstream's own encoding): a catalog is `{version: 1, keys,
48
+ * booleanShapes, nodes, compat, providers}`. Nested objects and arrays are
49
+ * interned into `nodes` and referenced by a one-element array `[id]`; `[-1]` is
50
+ * an explicitly present `undefined`; a provider row is `[name, constants,
51
+ * [[id, row, compatDelta?]]]`; and a row's `compat` is stored as a delta against
52
+ * the most common `compat` object for its `api`.
53
+ *
54
+ * @module dsh-keys-manager/model-catalog-format
55
+ */
56
+
57
+ /** `@oh-my-pi/pi-utils` `isRecord`, inlined: it is the only helper this port needs. */
58
+ function isRecord(value) {
59
+ return !!value && typeof value === 'object' && !Array.isArray(value)
60
+ }
61
+
62
+ // JSON serialization with sorted object keys gives both deterministic ordering
63
+ // and value-based interning, independent of the input objects' insertion order.
64
+ function canonical(value) {
65
+ if (value === undefined) return 'u'
66
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
67
+ if (isRecord(value)) {
68
+ return `{${Object.keys(value)
69
+ .sort()
70
+ .map(key => `${JSON.stringify(key)}:${canonical(value[key])}`)
71
+ .join(',')}}`
72
+ }
73
+ return JSON.stringify(value)
74
+ }
75
+
76
+ /**
77
+ * Encode a model catalog into a deterministic, compact JSON representation.
78
+ * @param {Record<string, Record<string, unknown>>} models - provider → model id → row.
79
+ * @returns {string} the catalog JSON text.
80
+ */
81
+ export function encodeModelCatalog(models) {
82
+ // Match JSON's treatment of undefined and non-finite numbers in generated rows.
83
+ models = JSON.parse(JSON.stringify(models))
84
+ const keys = []
85
+ const keyIds = new Map()
86
+ const booleanShapes = []
87
+ const shapeIds = new Map()
88
+ const nodes = []
89
+ const nodeIds = new Map()
90
+ const keyId = key => {
91
+ let id = keyIds.get(key)
92
+ if (id === undefined) {
93
+ id = keys.length
94
+ keys.push(key)
95
+ keyIds.set(key, id)
96
+ }
97
+ return id
98
+ }
99
+ const encode = value => {
100
+ if (value === undefined) return [-1]
101
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
102
+ return value
103
+ }
104
+ const signature = canonical(value)
105
+ const existing = nodeIds.get(signature)
106
+ if (existing !== undefined) return [existing]
107
+ let node
108
+ if (Array.isArray(value)) {
109
+ node = [1, value.map(encode)]
110
+ } else if (isRecord(value)) {
111
+ const properties = []
112
+ const boolKeys = []
113
+ const masks = []
114
+ for (const key of Object.keys(value).sort()) {
115
+ const entry = value[key]
116
+ if (typeof entry === 'boolean') {
117
+ const bit = boolKeys.length
118
+ boolKeys.push(keyId(key))
119
+ const word = Math.floor(bit / 32)
120
+ masks[word] ??= 0
121
+ if (entry) masks[word] = (masks[word] | (1 << (bit % 32))) >>> 0
122
+ } else {
123
+ properties.push(keyId(key), encode(entry))
124
+ }
125
+ }
126
+ const shape = boolKeys.join(',')
127
+ let shapeId = shapeIds.get(shape)
128
+ if (shapeId === undefined) {
129
+ shapeId = booleanShapes.length
130
+ booleanShapes.push(boolKeys)
131
+ shapeIds.set(shape, shapeId)
132
+ }
133
+ node = [0, properties, shapeId, masks]
134
+ } else {
135
+ throw new TypeError('Model catalog values must be JSON-compatible')
136
+ }
137
+ const id = nodes.length
138
+ nodes.push(node)
139
+ nodeIds.set(signature, id)
140
+ return [id]
141
+ }
142
+
143
+ // Select the most common complete compat object for each API. A row's
144
+ // delta records changed properties and explicitly removed base properties.
145
+ const compatCounts = new Map()
146
+ for (const provider of Object.keys(models).sort()) {
147
+ for (const id of Object.keys(models[provider]).sort()) {
148
+ const model = models[provider][id]
149
+ if (typeof model.api !== 'string' || !isRecord(model.compat)) continue
150
+ let counts = compatCounts.get(model.api)
151
+ if (!counts) compatCounts.set(model.api, (counts = new Map()))
152
+ const signature = canonical(model.compat)
153
+ const entry = counts.get(signature)
154
+ if (entry) entry.count++
155
+ else counts.set(signature, { value: model.compat, count: 1 })
156
+ }
157
+ }
158
+ const bases = new Map()
159
+ for (const api of [...compatCounts.keys()].sort()) {
160
+ const choices = [...compatCounts.get(api).entries()].sort(
161
+ (a, b) => b[1].count - a[1].count || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0),
162
+ )
163
+ bases.set(api, choices[0][1].value)
164
+ }
165
+ const compat = [...bases].map(([api, value]) => [api, encode(value)])
166
+ const providers = []
167
+ for (const provider of Object.keys(models).sort()) {
168
+ const entries = Object.entries(models[provider]).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
169
+ const constants = Object.create(null)
170
+ if (entries.length) {
171
+ const first = entries[0][1]
172
+ for (const key of Object.keys(first).sort()) {
173
+ const value = first[key]
174
+ if (key === 'id' || key === 'compat' || (value !== null && typeof value === 'object')) continue
175
+ if (entries.every(([, model]) => Object.hasOwn(model, key) && model[key] === value)) {
176
+ constants[key] = value
177
+ }
178
+ }
179
+ }
180
+ const encodedConstants = encode(constants)
181
+ const rows = []
182
+ for (const [id, model] of entries) {
183
+ const rest = Object.create(null)
184
+ const source = model
185
+ const base = typeof model.api === 'string' ? bases.get(model.api) : undefined
186
+ const useBase = base !== undefined && isRecord(model.compat)
187
+ for (const key of Object.keys(source).sort()) {
188
+ if (Object.hasOwn(constants, key) || (key === 'id' && source.id === id) || (key === 'compat' && useBase))
189
+ continue
190
+ rest[key] = source[key]
191
+ }
192
+ const row = [id, encode(rest)]
193
+ if (useBase) {
194
+ const value = model.compat
195
+ const removed = Object.keys(base)
196
+ .filter(key => !Object.hasOwn(value, key))
197
+ .sort()
198
+ .map(keyId)
199
+ const changed = Object.create(null)
200
+ for (const key of Object.keys(value).sort()) {
201
+ if (!Object.hasOwn(base, key) || canonical(value[key]) !== canonical(base[key])) changed[key] = value[key]
202
+ }
203
+ row.push([removed, encode(changed)])
204
+ }
205
+ rows.push(row)
206
+ }
207
+ providers.push([provider, encodedConstants, rows])
208
+ }
209
+ return JSON.stringify({ version: 1, keys, booleanShapes, nodes, compat, providers })
210
+ }
211
+
212
+ /**
213
+ * Open a parsed catalog without materializing its provider models.
214
+ * @param {unknown} value - the parsed `models.json`.
215
+ * @returns the catalog handle the accessors below take.
216
+ */
217
+ export function openModelCatalog(value) {
218
+ const data = value
219
+ if (data.version !== 1) throw new Error('Unsupported model catalog version')
220
+ return {
221
+ data,
222
+ values: [],
223
+ decoded: [],
224
+ providers: new Map(),
225
+ compatBases: new Map(data.compat),
226
+ compatValues: new Map(),
227
+ }
228
+ }
229
+
230
+ // Assignment is safe for ordinary keys, but __proto__ must remain an own key.
231
+ function setProperty(object, key, value) {
232
+ if (key === '__proto__') {
233
+ Object.defineProperty(object, key, { value, writable: true, enumerable: true, configurable: true })
234
+ } else {
235
+ object[key] = value
236
+ }
237
+ }
238
+
239
+ function decodeObject(catalog, object, node) {
240
+ for (let i = 0; i < node[1].length; i += 2) {
241
+ setProperty(object, catalog.data.keys[node[1][i]], decode(catalog, node[1][i + 1]))
242
+ }
243
+ const shape = catalog.data.booleanShapes[node[2]]
244
+ for (let i = 0; i < shape.length; i++) {
245
+ setProperty(object, catalog.data.keys[shape[i]], ((node[3][i >>> 5] >>> (i % 32)) & 1) !== 0)
246
+ }
247
+ }
248
+
249
+ function decode(catalog, value) {
250
+ if (!Array.isArray(value)) return value
251
+ const id = value[0]
252
+ if (id === -1) return undefined
253
+ if (catalog.decoded[id]) return catalog.values[id]
254
+ const node = catalog.data.nodes[id]
255
+ let result
256
+ if (node[0] === 1) {
257
+ result = node[1].map(entry => decode(catalog, entry))
258
+ } else {
259
+ const object = {}
260
+ decodeObject(catalog, object, node)
261
+ result = object
262
+ }
263
+ catalog.values[id] = result
264
+ catalog.decoded[id] = true
265
+ return result
266
+ }
267
+
268
+ /**
269
+ * List catalog provider keys in deterministic order.
270
+ * @param {object} catalog - an opened catalog.
271
+ */
272
+ export function getCatalogProviders(catalog) {
273
+ return catalog.data.providers.map(provider => provider[0])
274
+ }
275
+
276
+ /**
277
+ * Materialize and cache one provider, or return undefined if it is absent.
278
+ * @param {object} catalog - an opened catalog.
279
+ * @param {string} provider - the provider id.
280
+ */
281
+ export function getCatalogProvider(catalog, provider) {
282
+ const cached = catalog.providers.get(provider)
283
+ if (cached) return cached
284
+ const entry = catalog.data.providers.find(row => row[0] === provider)
285
+ if (!entry) return undefined
286
+ const constants = decode(catalog, entry[1])
287
+ const models = {}
288
+ for (const [id, encoded, delta] of entry[2]) {
289
+ if (!Array.isArray(encoded) || encoded[0] < 0) throw new Error('Invalid compact model row')
290
+ const row = catalog.data.nodes[encoded[0]]
291
+ if (!row || row[0] !== 0) throw new Error('Invalid compact model row')
292
+ const model = { id, ...constants }
293
+ decodeObject(catalog, model, row)
294
+ if (delta) {
295
+ const api = model.api
296
+ const changeId = delta[1][0]
297
+ const changeNode = catalog.data.nodes[changeId]
298
+ const base = decode(catalog, catalog.compatBases.get(api))
299
+ let compat
300
+ if (
301
+ delta[0].length === 0 &&
302
+ changeNode[1].length === 0 &&
303
+ catalog.data.booleanShapes[changeNode[2]].length === 0
304
+ ) {
305
+ compat = base
306
+ } else {
307
+ let byChange = catalog.compatValues.get(api)
308
+ if (!byChange) catalog.compatValues.set(api, (byChange = new Map()))
309
+ let byRemoved = byChange.get(changeId)
310
+ if (!byRemoved) byChange.set(changeId, (byRemoved = new Map()))
311
+ const removedKey = delta[0].join(',')
312
+ const cachedCompat = byRemoved.get(removedKey)
313
+ if (cachedCompat) {
314
+ compat = cachedCompat
315
+ } else {
316
+ compat = { ...base }
317
+ for (const key of delta[0]) delete compat[catalog.data.keys[key]]
318
+ const changes = decode(catalog, delta[1])
319
+ for (const key in changes) {
320
+ if (Object.hasOwn(changes, key)) setProperty(compat, key, changes[key])
321
+ }
322
+ byRemoved.set(removedKey, compat)
323
+ }
324
+ }
325
+ model.compat = compat
326
+ }
327
+ setProperty(models, id, model)
328
+ }
329
+ catalog.providers.set(provider, models)
330
+ return models
331
+ }