@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.d.ts","sources":["../vocab.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,2BAAgC;AAItD,wDAAwD,GACxD,OAAO,YAAI,MAAM,WAA8B;AAC/C,mDAAmD,GACnD,OAAO,YAAI,aAAa,MAAM,CAAuB"}
package/compile.js ADDED
@@ -0,0 +1,318 @@
1
+ import { getViews, stageViews, validateView, viewDependencies } from "./view.js";
2
+ import { schema } from "./schema.js";
3
+ import { history } from "./steps.js";
4
+ import { document } from "./document.js";
5
+ import { and, every, map, never, or, present, want } from "@yaks/query";
6
+ let own = (o, k)=>Object.hasOwn(o, k);
7
+ let same = (a, b)=>JSON.stringify(a) == JSON.stringify(b);
8
+ let fail = (why)=>{
9
+ throw new Error(`Lens: ${why}`);
10
+ };
11
+ let path = (p)=>{
12
+ if (typeof p != 'string' || !/^[_a-zA-Z]\w*\.[_a-zA-Z]\w*$/.test(p)) {
13
+ return fail(`expected comp.prop, got ${JSON.stringify(p)}`);
14
+ }
15
+ return p.split('.');
16
+ };
17
+ // A rename consumes only the property the patch says. Null clears that
18
+ // property; omission never becomes a clear. A component deletion clears the
19
+ // moved property too, without deleting unrelated destination properties.
20
+ let put = (b, pairs)=>{
21
+ let out = b;
22
+ for (let { from: [fc, fp], to: [tc], change } of pairs){
23
+ let source = out[fc];
24
+ if (source === undefined || source !== null && !own(source, fp)) continue;
25
+ let dest = out[tc];
26
+ if (source === null && fc == tc) continue;
27
+ if (dest === null && source !== null && source[fp] !== null) {
28
+ fail(`conflicting writes to ${fc}.${fp} and removed ${tc}`);
29
+ }
30
+ // Component null is a patch instruction, rather than JSON null data.
31
+ // Expose its property clear to the shared document operation, then retain
32
+ // the component removals on the translated patch.
33
+ let patch = source === null ? {
34
+ ...out,
35
+ [fc]: {
36
+ [fp]: null
37
+ }
38
+ } : out;
39
+ if (dest === null) patch = {
40
+ ...patch,
41
+ [tc]: {}
42
+ };
43
+ out = change.put(patch);
44
+ if (source === null) out = {
45
+ ...out,
46
+ [fc]: null
47
+ };
48
+ if (dest === null) out = {
49
+ ...out,
50
+ [tc]: null
51
+ };
52
+ }
53
+ if (b.$was) {
54
+ let guard = put({
55
+ entity: b.entity,
56
+ ...b.$was
57
+ }, pairs);
58
+ let { entity: _, ...was } = guard;
59
+ if (!same(was, b.$was)) out = {
60
+ ...out,
61
+ $was: was
62
+ };
63
+ }
64
+ return out;
65
+ };
66
+ // Keep the target: it was already a word in the old vocabulary, too. A
67
+ // snapshot supplies its own membership. A feed patch may consult a held row
68
+ // for membership, but never copies that row's unrelated properties.
69
+ let get = (b, pairs, held)=>{
70
+ let out = b;
71
+ for (let { from: [fc, fp], to: [tc, tp] } of pairs.toReversed()){
72
+ let src = out[fc];
73
+ let dst = out[tc];
74
+ if (fc != tc) {
75
+ if (src === null || !(src === undefined ? held?.[fc] : src)) continue;
76
+ if (dst === null) {
77
+ out = {
78
+ ...out,
79
+ [fc]: {
80
+ ...src ?? {},
81
+ [fp]: null
82
+ }
83
+ };
84
+ continue;
85
+ }
86
+ }
87
+ if (!dst || !own(dst, tp)) continue;
88
+ out = {
89
+ ...out,
90
+ [fc]: {
91
+ ...src ?? {},
92
+ [fp]: dst[tp]
93
+ }
94
+ };
95
+ if (fc == tc) {
96
+ let c = out[fc];
97
+ delete c[tp];
98
+ }
99
+ }
100
+ return out;
101
+ };
102
+ let identity = {
103
+ put: (b)=>b,
104
+ get: (b)=>b,
105
+ renames: [],
106
+ views: [],
107
+ dependencies: [],
108
+ ask: (q)=>q,
109
+ sources: [],
110
+ find: ()=>and(never()),
111
+ schema: (docs)=>docs
112
+ };
113
+ let cache = new Map();
114
+ /** Compile stored `_lens` rows once. Missing `speaks` means before all steps
115
+ * for moving stored rows; a plugin bypasses compilation for current callers.
116
+ * Each package's immutable timestamp steps run in order. */ export let compile = (rows, speaks)=>{
117
+ let groups = new Map();
118
+ for (let row of rows){
119
+ if (!row._lens) continue;
120
+ let s = row._lens;
121
+ if (typeof s.package != 'string' || !s.package) {
122
+ fail('a step needs its package eid');
123
+ }
124
+ let pkg = String(s.package);
125
+ let steps = groups.get(pkg) ?? [];
126
+ steps.push(s);
127
+ groups.set(pkg, steps);
128
+ }
129
+ let ordered = [
130
+ ...groups
131
+ ].toSorted(([a], [b])=>a.localeCompare(b)).map(([pkg, steps])=>[
132
+ pkg,
133
+ history(steps, speaks ? speaks[pkg] : 0)
134
+ ]);
135
+ for (let [pkg, version] of Object.entries(speaks ?? {})){
136
+ if (typeof version != 'number') {
137
+ fail(`unknown version ${version} for ${pkg}`);
138
+ }
139
+ if (!groups.has(pkg)) history([], version);
140
+ }
141
+ let key = JSON.stringify([
142
+ ordered.map(([pkg, h])=>[
143
+ pkg,
144
+ h.steps
145
+ ]),
146
+ speaks
147
+ ]);
148
+ let hit = cache.get(key);
149
+ if (hit) return hit;
150
+ let pairs = [];
151
+ let views = [];
152
+ for (let [, { steps, remaining }] of ordered){
153
+ let selected = new Set(remaining);
154
+ for (let s of steps){
155
+ if (!Array.isArray(s.ops)) fail(`step ${s.step} ops must be an array`);
156
+ for (let op of s.ops){
157
+ if (op && 'view' in op && Object.keys(op).length == 1) {
158
+ validateView(op.view);
159
+ if (selected.has(s)) views.push(structuredClone(op.view));
160
+ continue;
161
+ }
162
+ if (!op || !('rename' in op) || Object.keys(op).length != 1) {
163
+ return fail('expected rename or component view');
164
+ }
165
+ let from = path(op.rename.from), to = path(op.rename.to);
166
+ if (from.join('.') == to.join('.')) {
167
+ fail('a rename must change its path');
168
+ }
169
+ if (selected.has(s)) {
170
+ pairs.push({
171
+ from,
172
+ to,
173
+ change: document([
174
+ {
175
+ rename: {
176
+ from,
177
+ to
178
+ }
179
+ }
180
+ ])
181
+ });
182
+ }
183
+ }
184
+ }
185
+ }
186
+ let consumed = new Set();
187
+ for (let pair of pairs){
188
+ consumed.delete(pair.to.join('.'));
189
+ consumed.add(pair.from.join('.'));
190
+ }
191
+ let sources = [
192
+ ...consumed,
193
+ ...views.map((v)=>v.from)
194
+ ];
195
+ let lens = !pairs.length && !views.length ? identity : {
196
+ renames: pairs.map(({ from, to })=>({
197
+ rename: {
198
+ from: from.join('.'),
199
+ to: to.join('.')
200
+ }
201
+ })),
202
+ views,
203
+ dependencies: [
204
+ ...new Set(views.flatMap(viewDependencies))
205
+ ],
206
+ sources,
207
+ put: (b, ctx)=>stageViews(b.map((row)=>put(row, pairs)), views, ctx),
208
+ get: (b, ctx)=>{
209
+ let held = new Map(ctx?.facts?.map((r)=>[
210
+ r.entity.eid,
211
+ r
212
+ ]));
213
+ return getViews(b, views, ctx).map((row)=>get(row, pairs, held.get(row.entity.eid)));
214
+ },
215
+ ask: (q)=>{
216
+ let extra = new Map();
217
+ let rewrite = (p)=>{
218
+ let out = p;
219
+ for (let { from, to } of pairs){
220
+ for(let i = 0; i < out.length - 1; i++){
221
+ if (out[i] == from[0] && out[i + 1] == from[1]) {
222
+ if (i == 0 && from[0] != to[0]) {
223
+ extra.set(`want:${from[0]}`, want(from[0]));
224
+ }
225
+ out = [
226
+ ...out.slice(0, i),
227
+ ...to,
228
+ ...out.slice(i + 2)
229
+ ];
230
+ i++;
231
+ }
232
+ }
233
+ }
234
+ return out;
235
+ };
236
+ let out = map(q, (c)=>{
237
+ if (c.kind == 'pred' && c.path.length == 1) {
238
+ for (let { from, to } of pairs){
239
+ if (c.path[0] == from[0] && from[0] != to[0] && c.op != '=') {
240
+ extra.set(`want:${to[0]}`, want(to[0]));
241
+ }
242
+ }
243
+ }
244
+ if ('path' in c) {
245
+ let p = rewrite(c.path);
246
+ if (p === c.path) return c;
247
+ let changed = {
248
+ ...c,
249
+ path: p
250
+ };
251
+ if (c.kind == 'pred' && c.path.length == 2 && p[0] != c.path[0] && c.op != '?' && !(c.op == '=' && c.value?.kind == 'scalar' && c.value.raw == '')) return and(present(c.path[0]), changed);
252
+ return changed;
253
+ }
254
+ if (c.kind == 'fields') {
255
+ return {
256
+ ...c,
257
+ fields: c.fields.map((f)=>({
258
+ ...f,
259
+ path: rewrite(f.path)
260
+ }))
261
+ };
262
+ }
263
+ if (c.kind == 'order') {
264
+ let sign = c.value.startsWith('-') ? '-' : '';
265
+ return {
266
+ ...c,
267
+ value: sign + rewrite(c.value.slice(sign.length).split('.')).join('.')
268
+ };
269
+ }
270
+ if ((c.kind == 'ensure' || c.kind == 'mutable') && c.prop) {
271
+ let [comp, prop] = rewrite([
272
+ c.comp,
273
+ c.prop
274
+ ]);
275
+ return {
276
+ ...c,
277
+ comp,
278
+ prop
279
+ };
280
+ }
281
+ return c;
282
+ });
283
+ return extra.size ? and(...out.clauses, ...extra.values()) : out;
284
+ },
285
+ find: (admits = ()=>true)=>{
286
+ let source = sources.filter(admits);
287
+ return source.length ? and(or(...source.map(present)), every()) : and(never());
288
+ },
289
+ schema: (docs)=>{
290
+ let out = schema(docs, pairs);
291
+ for (let v of views.toReversed()){
292
+ let found = out.findIndex((d)=>d.$defs?.[v.from]);
293
+ if (found < 0) out = [
294
+ ...out,
295
+ {
296
+ $defs: {
297
+ [v.from]: v.declaration
298
+ }
299
+ }
300
+ ];
301
+ else {
302
+ out = out.map((d, i)=>i == found ? {
303
+ ...d,
304
+ $defs: {
305
+ ...d.$defs,
306
+ [v.from]: v.declaration
307
+ }
308
+ } : d);
309
+ }
310
+ }
311
+ return out;
312
+ }
313
+ };
314
+ if (cache.size >= 64) cache.delete(cache.keys().next().value);
315
+ cache.set(key, lens);
316
+ return lens;
317
+ };
318
+ //# sourceMappingURL=compile.js.map
package/compile.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.js","sources":["./compile.ts"],"names":[],"mappings":"AAEA,SAGE,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,gBAAgB,oBACA;AAClB,SAAS,MAAM,sBAAqB;AACpC,SAAS,OAAO,qBAAoB;AACpC,SAAS,QAAQ,wBAAqD;AACtE,SACE,GAAG,EACH,KAAK,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AAE,IAAI,CAAC,EAAE,EAAE,WAAW;cAAC;YAAE,IACvD;QACL;MACL;MACA,OAAO;IACT;EACF;EACA,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,MAAM,CAAC,MAAM,IAAI,GAAG,IAAI,GAAG,KAAK;EAC5D,MAAM,GAAG,CAAC,KAAK;EACf,OAAO;AACT,EAAC"}
package/compile.ts ADDED
@@ -0,0 +1,290 @@
1
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
2
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
3
+ import {
4
+ type ComponentView,
5
+ type Facts,
6
+ getViews,
7
+ stageViews,
8
+ validateView,
9
+ viewDependencies,
10
+ } from './view.js'
11
+ import { schema } from './schema.js'
12
+ import { history } from './steps.js'
13
+ import { document, type DocumentLens, type Json } from './document.js'
14
+ import {
15
+ and,
16
+ every,
17
+ map,
18
+ never,
19
+ or,
20
+ present,
21
+ type Query,
22
+ want,
23
+ } from '@yaks/query'
24
+
25
+ /** A caller's latest step timestamp, keyed by the declaring package's eid. */
26
+ export type Speaks = Record<string, number>
27
+ /** The pilot's single operation. Paths name a component and one property. */
28
+ export type Rename = { rename: { from: string; to: string } }
29
+ export type ViewOp = { view: ComponentView }
30
+ export type GraphOp = Rename | ViewOp
31
+ /** The pure directions of a compiled vocabulary change. */
32
+ export type Lens = {
33
+ put: (bundles: Bundle[], ctx?: Facts) => Bundle[]
34
+ get: (bundles: Bundle[], ctx?: Facts) => Bundle[]
35
+ renames: readonly Rename[]
36
+ views: readonly ComponentView[]
37
+ dependencies: readonly string[]
38
+ ask: (query: Query) => Query
39
+ /** Consumed source properties, excluding names a later step restores. */
40
+ sources: readonly string[]
41
+ /** Stored sources still admitted after earlier migrations contracted. */
42
+ find: (admits?: (path: string) => boolean) => Query
43
+ /** The property declarations an old caller's local graph admits. */
44
+ schema: (docs: VocabDoc[]) => VocabDoc[]
45
+ }
46
+
47
+ type Pair = {
48
+ from: [string, string]
49
+ to: [string, string]
50
+ change: DocumentLens
51
+ }
52
+ let own = (o: object, k: string) => Object.hasOwn(o, k)
53
+ let same = (a: unknown, b: unknown) => JSON.stringify(a) == JSON.stringify(b)
54
+ let fail = (why: string): never => {
55
+ throw new Error(`Lens: ${why}`)
56
+ }
57
+ let path = (p: unknown): [string, string] => {
58
+ if (typeof p != 'string' || !/^[_a-zA-Z]\w*\.[_a-zA-Z]\w*$/.test(p)) {
59
+ return fail(`expected comp.prop, got ${JSON.stringify(p)}`)
60
+ }
61
+ return p.split('.') as [string, string]
62
+ }
63
+
64
+ // A rename consumes only the property the patch says. Null clears that
65
+ // property; omission never becomes a clear. A component deletion clears the
66
+ // moved property too, without deleting unrelated destination properties.
67
+ let put = (b: Bundle, pairs: Pair[]): Bundle => {
68
+ let out = b
69
+ for (let { from: [fc, fp], to: [tc], change } of pairs) {
70
+ let source = out[fc] as Comp | null | undefined
71
+ if (source === undefined || source !== null && !own(source, fp)) continue
72
+ let dest = out[tc] as Comp | null | undefined
73
+ if (source === null && fc == tc) continue
74
+ if (dest === null && source !== null && source[fp] !== null) {
75
+ fail(`conflicting writes to ${fc}.${fp} and removed ${tc}`)
76
+ }
77
+ // Component null is a patch instruction, rather than JSON null data.
78
+ // Expose its property clear to the shared document operation, then retain
79
+ // the component removals on the translated patch.
80
+ let patch = source === null ? { ...out, [fc]: { [fp]: null } } : out
81
+ if (dest === null) patch = { ...patch, [tc]: {} }
82
+ out = change.put(patch as Json) as Bundle
83
+ if (source === null) out = { ...out, [fc]: null }
84
+ if (dest === null) out = { ...out, [tc]: null }
85
+ }
86
+ if (b.$was) {
87
+ let guard = put({ entity: b.entity, ...b.$was }, pairs)
88
+ let { entity: _, ...was } = guard
89
+ if (!same(was, b.$was)) out = { ...out, $was: was as Bundle['$was'] }
90
+ }
91
+ return out
92
+ }
93
+
94
+ // Keep the target: it was already a word in the old vocabulary, too. A
95
+ // snapshot supplies its own membership. A feed patch may consult a held row
96
+ // for membership, but never copies that row's unrelated properties.
97
+ let get = (b: Bundle, pairs: Pair[], held?: Bundle): Bundle => {
98
+ let out = b
99
+ for (let { from: [fc, fp], to: [tc, tp] } of pairs.toReversed()) {
100
+ let src = out[fc] as Comp | null | undefined
101
+ let dst = out[tc] as Comp | null | undefined
102
+ if (fc != tc) {
103
+ if (src === null || !(src === undefined ? held?.[fc] : src)) continue
104
+ if (dst === null) {
105
+ out = { ...out, [fc]: { ...(src ?? {}), [fp]: null } }
106
+ continue
107
+ }
108
+ }
109
+ if (!dst || !own(dst, tp)) continue
110
+ out = { ...out, [fc]: { ...(src ?? {}), [fp]: dst[tp] } }
111
+ if (fc == tc) {
112
+ let c = out[fc] as Comp
113
+ delete c[tp]
114
+ }
115
+ }
116
+ return out
117
+ }
118
+
119
+ let identity: Lens = {
120
+ put: (b) => b,
121
+ get: (b) => b,
122
+ renames: [],
123
+ views: [],
124
+ dependencies: [],
125
+ ask: (q) => q,
126
+ sources: [],
127
+ find: () => and(never()),
128
+ schema: (docs) => docs,
129
+ }
130
+ let cache = new Map<string, Lens>()
131
+
132
+ /** Compile stored `_lens` rows once. Missing `speaks` means before all steps
133
+ * for moving stored rows; a plugin bypasses compilation for current callers.
134
+ * Each package's immutable timestamp steps run in order. */
135
+ export let compile = (rows: Bundle[], speaks?: Speaks): Lens => {
136
+ let groups = new Map<string, (Comp & { step: number })[]>()
137
+ for (let row of rows) {
138
+ if (!row._lens) continue
139
+ let s = row._lens as Comp & { step: number }
140
+ if (typeof s.package != 'string' || !s.package) {
141
+ fail('a step needs its package eid')
142
+ }
143
+ let pkg = String(s.package)
144
+ let steps = groups.get(pkg) ?? []
145
+ steps.push(s)
146
+ groups.set(pkg, steps)
147
+ }
148
+ let ordered = [...groups].toSorted(([a], [b]) => a.localeCompare(b)).map(
149
+ ([pkg, steps]) => [pkg, history(steps, speaks ? speaks[pkg] : 0)] as const,
150
+ )
151
+ for (let [pkg, version] of Object.entries(speaks ?? {})) {
152
+ if (typeof version != 'number') {
153
+ fail(`unknown version ${version} for ${pkg}`)
154
+ }
155
+ if (!groups.has(pkg)) history([], version)
156
+ }
157
+ let key = JSON.stringify([ordered.map(([pkg, h]) => [pkg, h.steps]), speaks])
158
+ let hit = cache.get(key)
159
+ if (hit) return hit
160
+ let pairs: Pair[] = []
161
+ let views: ComponentView[] = []
162
+ for (let [, { steps, remaining }] of ordered) {
163
+ let selected = new Set(remaining)
164
+ for (let s of steps) {
165
+ if (!Array.isArray(s.ops)) fail(`step ${s.step} ops must be an array`)
166
+ for (let op of s.ops as GraphOp[]) {
167
+ if (op && 'view' in op && Object.keys(op).length == 1) {
168
+ validateView(op.view)
169
+ if (selected.has(s)) views.push(structuredClone(op.view))
170
+ continue
171
+ }
172
+ if (!op || !('rename' in op) || Object.keys(op).length != 1) {
173
+ return fail('expected rename or component view')
174
+ }
175
+ let from = path(op.rename.from), to = path(op.rename.to)
176
+ if (from.join('.') == to.join('.')) {
177
+ fail('a rename must change its path')
178
+ }
179
+ if (selected.has(s)) {
180
+ pairs.push({
181
+ from,
182
+ to,
183
+ change: document([{ rename: { from, to } }]),
184
+ })
185
+ }
186
+ }
187
+ }
188
+ }
189
+ let consumed = new Set<string>()
190
+ for (let pair of pairs) {
191
+ consumed.delete(pair.to.join('.'))
192
+ consumed.add(pair.from.join('.'))
193
+ }
194
+ let sources = [...consumed, ...views.map((v) => v.from)]
195
+ let lens: Lens = !pairs.length && !views.length ? identity : {
196
+ renames: pairs.map(({ from, to }) => ({
197
+ rename: { from: from.join('.'), to: to.join('.') },
198
+ })),
199
+ views,
200
+ dependencies: [...new Set(views.flatMap(viewDependencies))],
201
+ sources,
202
+ put: (b, ctx) => stageViews(b.map((row) => put(row, pairs)), views, ctx),
203
+ get: (b, ctx) => {
204
+ let held = new Map(ctx?.facts?.map((r) => [r.entity.eid, r]))
205
+ return getViews(b, views, ctx).map((row) =>
206
+ get(row, pairs, held.get(row.entity.eid))
207
+ )
208
+ },
209
+ ask: (q) => {
210
+ let extra = new Map<string, ReturnType<typeof want>>()
211
+ let rewrite = (p: string[]): string[] => {
212
+ let out = p
213
+ for (let { from, to } of pairs) {
214
+ for (let i = 0; i < out.length - 1; i++) {
215
+ if (out[i] == from[0] && out[i + 1] == from[1]) {
216
+ if (i == 0 && from[0] != to[0]) {
217
+ extra.set(`want:${from[0]}`, want(from[0]))
218
+ }
219
+ out = [...out.slice(0, i), ...to, ...out.slice(i + 2)]
220
+ i++
221
+ }
222
+ }
223
+ }
224
+ return out
225
+ }
226
+ let out = map(q, (c) => {
227
+ if (c.kind == 'pred' && c.path.length == 1) {
228
+ for (let { from, to } of pairs) {
229
+ if (c.path[0] == from[0] && from[0] != to[0] && c.op != '=') {
230
+ extra.set(`want:${to[0]}`, want(to[0]))
231
+ }
232
+ }
233
+ }
234
+ if ('path' in c) {
235
+ let p = rewrite(c.path)
236
+ if (p === c.path) return c
237
+ let changed = { ...c, path: p }
238
+ if (
239
+ c.kind == 'pred' && c.path.length == 2 && p[0] != c.path[0] &&
240
+ c.op != '?' &&
241
+ !(c.op == '=' && c.value?.kind == 'scalar' && c.value.raw == '')
242
+ ) return and(present(c.path[0]), changed)
243
+ return changed
244
+ }
245
+ if (c.kind == 'fields') {
246
+ return {
247
+ ...c,
248
+ fields: c.fields.map((f) => ({ ...f, path: rewrite(f.path) })),
249
+ }
250
+ }
251
+ if (c.kind == 'order') {
252
+ let sign = c.value.startsWith('-') ? '-' : ''
253
+ return {
254
+ ...c,
255
+ value: sign +
256
+ rewrite(c.value.slice(sign.length).split('.')).join('.'),
257
+ }
258
+ }
259
+ if ((c.kind == 'ensure' || c.kind == 'mutable') && c.prop) {
260
+ let [comp, prop] = rewrite([c.comp, c.prop])
261
+ return { ...c, comp, prop }
262
+ }
263
+ return c
264
+ }) as Query
265
+ return extra.size ? and(...out.clauses, ...extra.values()) : out
266
+ },
267
+ find: (admits = () => true) => {
268
+ let source = sources.filter(admits)
269
+ return source.length
270
+ ? and(or(...source.map(present)), every())
271
+ : and(never())
272
+ },
273
+ schema: (docs) => {
274
+ let out = schema(docs, pairs)
275
+ for (let v of views.toReversed()) {
276
+ let found = out.findIndex((d) => d.$defs?.[v.from])
277
+ if (found < 0) out = [...out, { $defs: { [v.from]: v.declaration } }]
278
+ else {out = out.map((d, i) =>
279
+ i == found
280
+ ? { ...d, $defs: { ...d.$defs, [v.from]: v.declaration } }
281
+ : d
282
+ )}
283
+ }
284
+ return out
285
+ },
286
+ }
287
+ if (cache.size >= 64) cache.delete(cache.keys().next().value!)
288
+ cache.set(key, lens)
289
+ return lens
290
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/lens","version":"0.2.36","license":"Apache-2.0","description":"Compiles reversible JSON document changes, with graph bundle, query, and migration adapters.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./graph":"./graph.ts"},"imports":{"@yaks/lens":"./mod.ts","@yaks/lens/vocab":"./vocab.ts","@yaks/lens/graph":"./graph.ts"}}