@yaks/lens 0.0.0-stage → 0.2.36

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.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +228 -2
  3. package/_dist/compile.d.ts +30 -0
  4. package/_dist/compile.d.ts.map +1 -0
  5. package/_dist/described.d.ts +12 -0
  6. package/_dist/described.d.ts.map +1 -0
  7. package/_dist/document.d.ts +59 -0
  8. package/_dist/document.d.ts.map +1 -0
  9. package/_dist/graph.d.ts +3 -0
  10. package/_dist/graph.d.ts.map +1 -0
  11. package/_dist/mod.d.ts +7 -0
  12. package/_dist/mod.d.ts.map +1 -0
  13. package/_dist/plugin.d.ts +9 -0
  14. package/_dist/plugin.d.ts.map +1 -0
  15. package/_dist/steps.d.ts +10 -0
  16. package/_dist/steps.d.ts.map +1 -0
  17. package/_dist/view.d.ts +40 -0
  18. package/_dist/view.d.ts.map +1 -0
  19. package/_dist/vocab.d.ts +4 -0
  20. package/_dist/vocab.d.ts.map +1 -0
  21. package/compile.js +318 -0
  22. package/compile.js.map +1 -0
  23. package/compile.ts +290 -0
  24. package/deno.json +1 -0
  25. package/described.js +80 -0
  26. package/described.js.map +1 -0
  27. package/described.ts +85 -0
  28. package/document.js +268 -0
  29. package/document.js.map +1 -0
  30. package/document.ts +335 -0
  31. package/graph.js +5 -0
  32. package/graph.js.map +1 -0
  33. package/graph.ts +4 -0
  34. package/mod.js +7 -0
  35. package/mod.js.map +1 -0
  36. package/mod.ts +6 -0
  37. package/package.json +28 -4
  38. package/plugin.js +454 -0
  39. package/plugin.js.map +1 -0
  40. package/plugin.ts +597 -0
  41. package/schema.js +61 -0
  42. package/schema.js.map +1 -0
  43. package/schema.ts +53 -0
  44. package/steps.js +35 -0
  45. package/steps.js.map +1 -0
  46. package/steps.ts +47 -0
  47. package/tools.fixture.json +190 -0
  48. package/view.js +430 -0
  49. package/view.js.map +1 -0
  50. package/view.ts +448 -0
  51. package/vocab.js +11 -0
  52. package/vocab.js.map +1 -0
  53. package/vocab.json +34 -0
  54. package/vocab.ts +8 -0
package/document.ts ADDED
@@ -0,0 +1,335 @@
1
+ import { history } from './steps.js'
2
+
3
+ /** JSON documents have no graph vocabulary, storage or effects. */
4
+ export type Json = null | boolean | number | string | Json[] | {
5
+ [key: string]: Json
6
+ }
7
+ /** Dotted paths are convenient; arrays preserve keys containing dots. */
8
+ export type Path = string | readonly (string | number)[]
9
+ type Move = { from: Path; to: Path }
10
+ type Default = { path: Path; default: Json }
11
+ type Part = Path | { value: string }
12
+ export type Op =
13
+ | { rename: Move }
14
+ | { hoist: Move }
15
+ | { plunge: Move }
16
+ | { add: Default }
17
+ | { remove: Default }
18
+ | {
19
+ concat: {
20
+ from: readonly Part[]
21
+ to: Path
22
+ separator?: string
23
+ /** Append the joined string to a list; inverse consumes its last item. */
24
+ append?: boolean
25
+ }
26
+ }
27
+ | {
28
+ scatter: {
29
+ from: Path
30
+ to: Path
31
+ keyword: string
32
+ /** A short-name map keys its destination by the entry's value. */
33
+ key?: 'name' | 'value'
34
+ }
35
+ }
36
+ | { in: { path: Path; ops: readonly Op[] } }
37
+ export type DocumentLens = {
38
+ put: <T extends Json>(value: T) => Json
39
+ get: <T extends Json>(value: T) => Json
40
+ }
41
+
42
+ const absent = Symbol('absent')
43
+ type Value = Json | typeof absent
44
+ let object = (v: Value): v is { [key: string]: Json } =>
45
+ v !== absent && v !== null && typeof v == 'object' && !Array.isArray(v)
46
+ let fail: (why: string) => never = (why) => {
47
+ throw new Error(`Lens: ${why}`)
48
+ }
49
+ let same = (a: Value, b: Value): boolean => {
50
+ if (a === b) return true
51
+ if (a === absent || b === absent) return false
52
+ if (Array.isArray(a) && Array.isArray(b)) {
53
+ return a.length == b.length && a.every((v, i) => same(v, b[i]))
54
+ }
55
+ if (!object(a) || !object(b)) return false
56
+ let keys = Object.keys(a)
57
+ return keys.length == Object.keys(b).length &&
58
+ keys.every((k) => Object.hasOwn(b, k) && same(a[k], b[k]))
59
+ }
60
+ let path = (p: Path): string[] => {
61
+ let parts = typeof p == 'string' ? p.split('.') : [...p].map(String)
62
+ if (!parts.length || parts.some((k) => !k)) fail('a path needs nonempty keys')
63
+ return parts
64
+ }
65
+ let read = (doc: Value, p: readonly string[]): Value => {
66
+ let out = doc
67
+ for (let key of p) {
68
+ if (out === absent || out === null || typeof out != 'object') return absent
69
+ if (!Object.hasOwn(out, key)) return absent
70
+ out = (out as { [key: string]: Json })[key]
71
+ }
72
+ return out
73
+ }
74
+ // Copy only changed ancestors. No operation can mutate a caller's document or
75
+ // an authored default, including a later operation using that default.
76
+ let write = (
77
+ doc: Value,
78
+ p: readonly string[],
79
+ value: Value,
80
+ at = 0,
81
+ ): Value => {
82
+ if (at == p.length) return same(doc, value) ? doc : value
83
+ let key = p[at]
84
+ if (doc !== absent && (doc === null || typeof doc != 'object')) {
85
+ fail(`cannot descend into ${key}`)
86
+ }
87
+ let held = doc === absent ? {} : doc as Json[] | { [key: string]: Json }
88
+ let before = Object.hasOwn(held, key)
89
+ ? (held as { [key: string]: Json })[key]
90
+ : absent
91
+ let after = write(before, p, value, at + 1)
92
+ // A leaf keeps its identity when unchanged; ancestors need no second walk.
93
+ if (before === after) return doc
94
+ if (Array.isArray(held)) {
95
+ let n = Number(key)
96
+ if (!Number.isInteger(n) || n < 0 || n > held.length || String(n) != key) {
97
+ fail(`invalid array index ${key}`)
98
+ }
99
+ let out = [...held]
100
+ if (after === absent) out.splice(n, 1)
101
+ else out[n] = after
102
+ return out
103
+ }
104
+ if (after !== absent) return { ...held, [key]: after }
105
+ let out = { ...held }
106
+ delete out[key]
107
+ return out
108
+ }
109
+ let set = (doc: Json, p: string[], value: Json): Json => {
110
+ let held = read(doc, p)
111
+ if (held !== absent && !same(held, value)) {
112
+ fail(`conflicting writes to ${p.join('.')}`)
113
+ }
114
+ return write(doc, p, value) as Json
115
+ }
116
+ let drop = (doc: Json, p: string[]): Json => write(doc, p, absent) as Json
117
+ let move = (doc: Json, from: string[], to: string[]): Json => {
118
+ let value = read(doc, from)
119
+ if (value === absent) return doc
120
+ // Array moves consume before assigning, so indexes address the resulting
121
+ // document. Object moves retain their now-empty source containers.
122
+ return set(drop(doc, from), to, value)
123
+ }
124
+ let constant = (part: Part): part is { value: string } =>
125
+ typeof part == 'object' && !Array.isArray(part) && 'value' in part
126
+ let escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
127
+ type Run = (doc: Json, backwards: boolean) => Json
128
+
129
+ let operation = (op: Op): Run => {
130
+ if (!op || typeof op != 'object' || Object.keys(op).length != 1) {
131
+ return fail('an operation needs exactly one name')
132
+ }
133
+ if ('rename' in op || 'hoist' in op || 'plunge' in op) {
134
+ let spec = 'rename' in op ? op.rename : 'hoist' in op ? op.hoist : op.plunge
135
+ let from = path(spec.from), to = path(spec.to)
136
+ if (from.join('\0') == to.join('\0')) fail('a move must change its path')
137
+ if (from.every((k, i) => to[i] == k) || to.every((k, i) => from[i] == k)) {
138
+ fail('a move cannot contain its own source')
139
+ }
140
+ if ('hoist' in op && from.length <= to.length) {
141
+ fail('hoist needs a shallower destination')
142
+ }
143
+ if ('plunge' in op && from.length >= to.length) {
144
+ fail('plunge needs a deeper destination')
145
+ }
146
+ return (doc, backwards) =>
147
+ backwards ? move(doc, to, from) : move(doc, from, to)
148
+ }
149
+ if ('add' in op || 'remove' in op) {
150
+ let spec = 'add' in op ? op.add : op.remove
151
+ let p = path(spec.path),
152
+ value = structuredClone(spec.default),
153
+ add = 'add' in op
154
+ return (doc, backwards) => {
155
+ let adding = add ? !backwards : backwards
156
+ let held = read(doc, p)
157
+ if (adding) {
158
+ return held === absent ? set(doc, p, structuredClone(value)) : doc
159
+ }
160
+ if (held === absent) return doc
161
+ if (!same(held, value)) {
162
+ fail(`removing ${p.join('.')} would lose a nondefault value`)
163
+ }
164
+ return drop(doc, p)
165
+ }
166
+ }
167
+ if ('concat' in op) {
168
+ let spec = op.concat,
169
+ to = path(spec.to),
170
+ separator = spec.separator ?? '',
171
+ append = spec.append
172
+ if (!spec.from.length) fail('concat needs parts')
173
+ let parts = spec.from.map((p) =>
174
+ constant(p) ? { value: p.value } : { path: path(p) }
175
+ )
176
+ let variables = parts.filter((p) => 'path' in p)
177
+ if (!variables.length || variables.length > 1 && !separator) {
178
+ fail('concat with multiple variable parts needs a separator')
179
+ }
180
+ let pattern = new RegExp(
181
+ '^' + parts.map((p) =>
182
+ 'value' in p ? escape(p.value!) : '(.*?)'
183
+ ).join(escape(separator)) + '$',
184
+ 's',
185
+ )
186
+ return (doc, backwards) => {
187
+ if (!backwards) {
188
+ let values = parts.map((p) =>
189
+ 'value' in p ? p.value : read(doc, p.path!)
190
+ )
191
+ if (
192
+ values.some((v) =>
193
+ v === absent
194
+ )
195
+ ) return doc
196
+ if (values.some((v) => typeof v != 'string')) {
197
+ fail('concat parts must be strings')
198
+ }
199
+ if (
200
+ variables.length > 1 && values.some((v, i) =>
201
+ 'path' in parts[i] && String(v).includes(separator)
202
+ )
203
+ ) {
204
+ fail('concat value contains its separator')
205
+ }
206
+ let joined = values.join(separator), out = doc
207
+ for (let p of variables) out = drop(out, p.path!)
208
+ if (!append) return set(out, to, joined)
209
+ let held = read(out, to)
210
+ if (held !== absent && !Array.isArray(held)) {
211
+ fail('concat append needs an array')
212
+ }
213
+ return write(out, to, [
214
+ ...(held === absent ? [] : held as Json[]),
215
+ joined,
216
+ ]) as Json
217
+ }
218
+ let held = read(doc, to)
219
+ if (held === absent) return doc
220
+ let value: Value = held
221
+ if (append) {
222
+ if (!Array.isArray(held)) fail('concat append needs an array')
223
+ if (!held.length) return doc
224
+ value = held.at(-1)!
225
+ }
226
+ if (typeof value != 'string') fail('concat inverse needs a string')
227
+ let matched = pattern.exec(value)
228
+ // An array may end in an ordinary positional, with no rest argument.
229
+ if (!matched && append) return doc
230
+ if (!matched) fail('concat inverse does not match its literals')
231
+ if (
232
+ variables.length > 1 &&
233
+ matched.slice(1).some((v) => v.includes(separator))
234
+ ) {
235
+ fail('concat inverse contains an ambiguous separator')
236
+ }
237
+ let out = append
238
+ ? held instanceof Array && held.length > 1
239
+ ? write(doc, to, held.slice(0, -1)) as Json
240
+ : drop(doc, to)
241
+ : drop(doc, to)
242
+ for (let i = 0; i < variables.length; i++) {
243
+ out = set(out, variables[i].path!, matched![i + 1])
244
+ }
245
+ return out
246
+ }
247
+ }
248
+ if ('scatter' in op) {
249
+ let spec = op.scatter,
250
+ from = path(spec.from),
251
+ to = path(spec.to),
252
+ keyword = spec.keyword,
253
+ byValue = spec.key == 'value'
254
+ if (!keyword) fail('scatter needs a keyword')
255
+ if (spec.key && spec.key != 'name' && !byValue) {
256
+ fail('unknown scatter key')
257
+ }
258
+ return (doc, backwards) => {
259
+ let source = read(doc, backwards ? to : from)
260
+ if (source === absent) return doc
261
+ if (!object(source)) fail('scatter needs an object')
262
+ let out = doc
263
+ if (!backwards) {
264
+ for (let [name, value] of Object.entries(source)) {
265
+ let key = byValue ? value : name
266
+ if (typeof key != 'string') {
267
+ fail('scatter destination keys must be strings')
268
+ }
269
+ let target = [...to, key]
270
+ if (!object(read(out, target))) {
271
+ fail(`scatter destination ${target.join('.')} must exist`)
272
+ }
273
+ out = set(
274
+ out,
275
+ [...target, keyword],
276
+ byValue ? name : value,
277
+ )
278
+ }
279
+ return drop(out, from)
280
+ }
281
+ let gathered: { [key: string]: Json } = {}
282
+ for (let [name, entry] of Object.entries(source)) {
283
+ if (!object(entry) || !Object.hasOwn(entry, keyword)) continue
284
+ let value = entry[keyword], key = byValue ? value : name
285
+ if (typeof key != 'string') fail('gathered keys must be strings')
286
+ if (Object.hasOwn(gathered, key)) fail(`duplicate gathered key ${key}`)
287
+ Object.defineProperty(gathered, key, {
288
+ value: byValue ? name : value,
289
+ enumerable: true,
290
+ })
291
+ out = drop(out, [...to, name, keyword])
292
+ }
293
+ return Object.keys(gathered).length ? set(out, from, gathered) : out
294
+ }
295
+ }
296
+ if ('in' in op) {
297
+ let parts = path(op.in.path), child = document(op.in.ops)
298
+ let visit = (doc: Json, rest: string[], backwards: boolean): Json => {
299
+ if (!rest.length) return backwards ? child.get(doc) : child.put(doc)
300
+ let [head, ...tail] = rest
301
+ if (doc === null || typeof doc != 'object') return doc
302
+ let keys = head == '*' ? Object.keys(doc) : [head]
303
+ let out: Json = doc
304
+ for (let key of keys) {
305
+ let value = read(out, [key])
306
+ if (value !== absent) {
307
+ out = write(out, [key], visit(value, tail, backwards)) as Json
308
+ }
309
+ }
310
+ return out
311
+ }
312
+ return (doc, backwards) => visit(doc, parts, backwards)
313
+ }
314
+ return fail('unknown operation')
315
+ }
316
+
317
+ /** Compile a reversible JSON document change once. Omitted paths stay omitted;
318
+ * null is data. Add/remove invert within their declared default, concat within
319
+ * its delimiter, and scatter within the map's unique keys. Empty containers
320
+ * survive moves; defaults and empty maps/lists have a canonical inverse. */
321
+ export let document = (ops: readonly Op[]): DocumentLens => {
322
+ let runs = ops.map(operation), reverse = runs.toReversed()
323
+ return {
324
+ put: (value) => runs.reduce((out, run) => run(out, false), value as Json),
325
+ get: (value) => reverse.reduce((out, run) => run(out, true), value as Json),
326
+ }
327
+ }
328
+
329
+ /** Compile the timestamp suffix of a JSON format's declared changes. Zero
330
+ * speaks before all changes, including when the argument is omitted. */
331
+ export let documentChain = (
332
+ steps: readonly { step: number; ops: readonly Op[] }[],
333
+ speaks = 0,
334
+ ): DocumentLens =>
335
+ document(history(steps, speaks).remaining.flatMap(({ ops }) => [...ops]))
package/graph.js ADDED
@@ -0,0 +1,5 @@
1
+ import { lenses } from "./plugin.js";
2
+ /** The rename vocabulary and translation hooks. */ export let plugins = ()=>[
3
+ lenses()
4
+ ];
5
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AACA,SAAS,MAAM,sBAAqB;AACpC,iDAAiD,GACjD,OAAO,IAAI,UAAU,IAAgB;IAAC;GAAS,CAAA"}
package/graph.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
2
+ import { lenses } from './plugin.js'
3
+ /** The rename vocabulary and translation hooks. */
4
+ export let plugins = (): Plugin[] => [lenses()]
package/mod.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./document.js";
2
+ export * from "./compile.js";
3
+ export * from "./described.js";
4
+ export * from "./plugin.js";
5
+ export * from "./steps.js";
6
+ export * from "./view.js";
7
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,8BAA6B;AAC7B,6BAA4B;AAC5B,+BAA8B;AAC9B,4BAA2B;AAC3B,2BAA0B;AAC1B,0BAAyB"}
package/mod.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './document.js'
2
+ export * from './compile.js'
3
+ export * from './described.js'
4
+ export * from './plugin.js'
5
+ export * from './steps.js'
6
+ export * from './view.js'
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@yaks/lens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/lens",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./vocab": {
12
+ "types": "./_dist/vocab.d.ts",
13
+ "default": "./vocab.js"
14
+ },
15
+ "./graph": {
16
+ "types": "./_dist/graph.d.ts",
17
+ "default": "./graph.js"
18
+ }
19
+ },
20
+ "license": "Apache-2.0",
21
+ "dependencies": {
22
+ "@yaks/fp": "0.2.36",
23
+ "@yaks/graph": "0.2.36",
24
+ "@yaks/match": "0.2.36",
25
+ "@yaks/query": "0.2.36",
26
+ "@yaks/vocab": "0.2.36"
27
+ },
28
+ "description": "Compiles reversible JSON document changes, with graph bundle, query, and migration adapters.",
29
+ "repository": "https://github.com/yak-sh/yak.git"
30
+ }