@tanstack/db-ivm 0.1.19 → 0.1.22

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 (63) hide show
  1. package/dist/cjs/hashing/hash.cjs +114 -45
  2. package/dist/cjs/hashing/hash.cjs.map +1 -1
  3. package/dist/cjs/hashing/hash.d.cts +7 -0
  4. package/dist/cjs/hashing/murmur.cjs +32 -9
  5. package/dist/cjs/hashing/murmur.cjs.map +1 -1
  6. package/dist/cjs/hashing/murmur.d.cts +1 -0
  7. package/dist/cjs/index.cjs +2 -0
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/index.d.cts +1 -0
  10. package/dist/cjs/operators/distinct.cjs.map +1 -1
  11. package/dist/cjs/operators/distinct.d.cts +1 -1
  12. package/dist/cjs/operators/groupBy.cjs +1 -1
  13. package/dist/cjs/operators/groupBy.cjs.map +1 -1
  14. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs +4 -5
  15. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs.map +1 -1
  16. package/dist/cjs/operators/topKArray.cjs +2 -0
  17. package/dist/cjs/operators/topKArray.cjs.map +1 -1
  18. package/dist/cjs/operators/topKState.cjs +30 -0
  19. package/dist/cjs/operators/topKState.cjs.map +1 -1
  20. package/dist/cjs/operators/topKState.d.cts +9 -0
  21. package/dist/cjs/operators/topKWithFractionalIndex.cjs +4 -5
  22. package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
  23. package/dist/cjs/utils.cjs +8 -0
  24. package/dist/cjs/utils.cjs.map +1 -1
  25. package/dist/esm/hashing/hash.d.ts +7 -0
  26. package/dist/esm/hashing/hash.js +116 -47
  27. package/dist/esm/hashing/hash.js.map +1 -1
  28. package/dist/esm/hashing/murmur.d.ts +1 -0
  29. package/dist/esm/hashing/murmur.js +32 -9
  30. package/dist/esm/hashing/murmur.js.map +1 -1
  31. package/dist/esm/index.d.ts +1 -0
  32. package/dist/esm/index.js +2 -0
  33. package/dist/esm/index.js.map +1 -1
  34. package/dist/esm/operators/distinct.d.ts +1 -1
  35. package/dist/esm/operators/distinct.js.map +1 -1
  36. package/dist/esm/operators/groupBy.js +1 -1
  37. package/dist/esm/operators/groupBy.js.map +1 -1
  38. package/dist/esm/operators/groupedTopKWithFractionalIndex.js +5 -6
  39. package/dist/esm/operators/groupedTopKWithFractionalIndex.js.map +1 -1
  40. package/dist/esm/operators/topKArray.js +2 -0
  41. package/dist/esm/operators/topKArray.js.map +1 -1
  42. package/dist/esm/operators/topKState.d.ts +9 -0
  43. package/dist/esm/operators/topKState.js +31 -1
  44. package/dist/esm/operators/topKState.js.map +1 -1
  45. package/dist/esm/operators/topKWithFractionalIndex.js +5 -6
  46. package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
  47. package/dist/esm/utils.js +8 -0
  48. package/dist/esm/utils.js.map +1 -1
  49. package/package.json +5 -2
  50. package/src/hashing/hash.ts +189 -57
  51. package/src/hashing/murmur.ts +44 -10
  52. package/src/index.ts +1 -0
  53. package/src/operators/distinct.ts +5 -3
  54. package/src/operators/groupBy.ts +7 -4
  55. package/src/operators/groupedTopKWithFractionalIndex.ts +10 -6
  56. package/src/operators/topKArray.ts +4 -0
  57. package/src/operators/topKState.ts +42 -0
  58. package/src/operators/topKWithFractionalIndex.ts +10 -6
  59. package/src/operators/topKWithFractionalIndexBTree.ts +7 -8
  60. package/src/utils.ts +8 -0
  61. package/dist/cjs/operators/orderByBTree.d.cts +0 -3
  62. package/dist/esm/operators/orderByBTree.d.ts +0 -3
  63. package/src/operators/orderByBTree.ts +0 -20
@@ -8,12 +8,16 @@ const UNDEFINED = murmur.randomHash();
8
8
  const KEY = murmur.randomHash();
9
9
  const FUNCTIONS = murmur.randomHash();
10
10
  const DATE_MARKER = murmur.randomHash();
11
- const OBJECT_MARKER = murmur.randomHash();
12
- const ARRAY_MARKER = murmur.randomHash();
13
- const MAP_MARKER = murmur.randomHash();
14
- const SET_MARKER = murmur.randomHash();
11
+ const STRUCTURAL_MARKERS = {
12
+ object: murmur.randomHash(),
13
+ array: murmur.randomHash(),
14
+ map: murmur.randomHash(),
15
+ set: murmur.randomHash()
16
+ };
15
17
  const UINT8ARRAY_MARKER = murmur.randomHash();
16
18
  const TEMPORAL_MARKER = murmur.randomHash();
19
+ const MAX_STRUCTURAL_HASH_WORK = 1e6;
20
+ const MAX_STRUCTURAL_HASH_DEPTH = 768;
17
21
  const temporalTypes = /* @__PURE__ */ new Set([
18
22
  `Temporal.Duration`,
19
23
  `Temporal.Instant`,
@@ -30,49 +34,42 @@ function isTemporal(input) {
30
34
  }
31
35
  const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128;
32
36
  const hashCache = /* @__PURE__ */ new WeakMap();
37
+ const referenceValues = /* @__PURE__ */ new WeakSet();
38
+ function registerOpaqueHash(value) {
39
+ cachedReferenceHash(value);
40
+ }
33
41
  function hash(input) {
34
42
  const hasher = new murmur.MurmurHashStream();
35
43
  updateHasher(hasher, input);
36
44
  return hasher.digest();
37
45
  }
38
- function hashObject(input) {
39
- const cachedHash = hashCache.get(input);
40
- if (cachedHash !== void 0) {
41
- return cachedHash;
46
+ function hashObject(input, context) {
47
+ if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {
48
+ throw new RangeError(
49
+ `Value is too complex to hash safely: structural depth`
50
+ );
42
51
  }
52
+ context.activeObjects.add(input);
43
53
  let valueHash;
44
- if (input instanceof Date) {
45
- valueHash = hashDate(input);
46
- } else if (
47
- // Check if input is a Uint8Array or Buffer
48
- typeof Buffer !== `undefined` && input instanceof Buffer || input instanceof Uint8Array
49
- ) {
50
- if (input.byteLength <= UINT8ARRAY_CONTENT_HASH_THRESHOLD) {
54
+ try {
55
+ if (input instanceof Date) {
56
+ valueHash = hashDate(input);
57
+ } else if (isBinaryValue(input)) {
51
58
  valueHash = hashUint8Array(input);
59
+ } else if (isTemporal(input)) {
60
+ valueHash = hashTemporal(input);
52
61
  } else {
53
- return cachedReferenceHash(input);
54
- }
55
- } else if (input instanceof File) {
56
- return cachedReferenceHash(input);
57
- } else if (isTemporal(input)) {
58
- valueHash = hashTemporal(input);
59
- } else {
60
- let plainObjectInput = input;
61
- let marker = OBJECT_MARKER;
62
- if (input instanceof Array) {
63
- marker = ARRAY_MARKER;
64
- }
65
- if (input instanceof Map) {
66
- marker = MAP_MARKER;
67
- plainObjectInput = [...input.entries()];
68
- }
69
- if (input instanceof Set) {
70
- marker = SET_MARKER;
71
- plainObjectInput = [...input.entries()];
62
+ const [kind, plainObjectInput] = structuralShape(input);
63
+ valueHash = hashPlainObject(
64
+ plainObjectInput,
65
+ STRUCTURAL_MARKERS[kind],
66
+ context
67
+ );
72
68
  }
73
- valueHash = hashPlainObject(plainObjectInput, marker);
69
+ } finally {
70
+ context.activeObjects.delete(input);
74
71
  }
75
- hashCache.set(input, valueHash);
72
+ context.pendingHashes.set(input, valueHash);
76
73
  return valueHash;
77
74
  }
78
75
  function hashDate(input) {
@@ -97,7 +94,7 @@ function hashTemporal(input) {
97
94
  hasher.update(input.toString());
98
95
  return hasher.digest();
99
96
  }
100
- function hashPlainObject(input, marker) {
97
+ function hashPlainObject(input, marker, context) {
101
98
  const hasher = new murmur.MurmurHashStream();
102
99
  hasher.update(marker);
103
100
  const keys = Object.keys(input);
@@ -105,11 +102,20 @@ function hashPlainObject(input, marker) {
105
102
  for (const key of keys) {
106
103
  hasher.update(KEY);
107
104
  hasher.update(key);
108
- updateHasher(hasher, input[key]);
105
+ updateHasher(hasher, input[key], context);
106
+ }
107
+ const symbolKeys = Object.getOwnPropertySymbols(input).filter((key) => Object.prototype.propertyIsEnumerable.call(input, key)).sort((left, right) => murmur.getSymbolIdentity(left) - murmur.getSymbolIdentity(right));
108
+ for (const key of symbolKeys) {
109
+ hasher.update(KEY);
110
+ hasher.update(key);
111
+ updateHasher(hasher, input[key], context);
109
112
  }
110
113
  return hasher.digest();
111
114
  }
112
- function updateHasher(hasher, input) {
115
+ function updateHasher(hasher, input, context) {
116
+ if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {
117
+ throw new RangeError(`Value is too complex to hash safely: structural work`);
118
+ }
113
119
  if (input === null) {
114
120
  hasher.update(NULL);
115
121
  return;
@@ -130,7 +136,7 @@ function updateHasher(hasher, input) {
130
136
  hasher.update(input);
131
137
  return;
132
138
  case `object`:
133
- hasher.update(getCachedHash(input));
139
+ hasher.update(getCachedHash(input, context));
134
140
  return;
135
141
  case `function`:
136
142
  hasher.update(cachedReferenceHash(input));
@@ -141,12 +147,72 @@ function updateHasher(hasher, input) {
141
147
  );
142
148
  }
143
149
  }
144
- function getCachedHash(input) {
145
- let valueHash = hashCache.get(input);
146
- if (valueHash === void 0) {
147
- valueHash = hashObject(input);
150
+ function getCachedHash(input, context) {
151
+ if (!context) {
152
+ const cached = hashCache.get(input);
153
+ if (cached !== void 0) return cached;
154
+ if (isReferenceHashedObject(input)) return cachedReferenceHash(input);
155
+ context = {
156
+ activeObjects: /* @__PURE__ */ new Set(),
157
+ work: 0,
158
+ pendingHashes: /* @__PURE__ */ new Map()
159
+ };
160
+ const result = hashObject(input, context);
161
+ for (const [object, valueHash2] of context.pendingHashes) {
162
+ hashCache.set(object, valueHash2);
163
+ }
164
+ return result;
148
165
  }
149
- return valueHash;
166
+ if (context.activeObjects.has(input)) {
167
+ throw new TypeError(`Cannot hash cyclic structural values`);
168
+ }
169
+ if (isReferenceHashedObject(input)) return cachedReferenceHash(input);
170
+ const valueHash = hashCache.get(input) ?? context.pendingHashes.get(input);
171
+ if (valueHash !== void 0) return valueHash;
172
+ return hashObject(input, context);
173
+ }
174
+ function isReferenceHashedObject(input) {
175
+ return input instanceof File || isBinaryValue(input) && input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD;
176
+ }
177
+ function isBinaryValue(input) {
178
+ return typeof Buffer !== `undefined` && input instanceof Buffer || input instanceof Uint8Array;
179
+ }
180
+ function structuralShape(input) {
181
+ if (input instanceof Map) return [`map`, [...input.entries()]];
182
+ if (input instanceof Set) return [`set`, [...input.values()]];
183
+ return [input instanceof Array ? `array` : `object`, input];
184
+ }
185
+ function equalHashValues(left, right) {
186
+ const compared = /* @__PURE__ */ new Map();
187
+ function equal(a, b) {
188
+ if (a === b || Number.isNaN(a) && Number.isNaN(b)) return true;
189
+ if (a === null || b === null || typeof a !== `object` || typeof b !== `object`)
190
+ return false;
191
+ if (referenceValues.has(a) || referenceValues.has(b) || isReferenceHashedObject(a) || isReferenceHashedObject(b))
192
+ return false;
193
+ if (a instanceof Date || b instanceof Date)
194
+ return a instanceof Date && b instanceof Date && equal(a.getTime(), b.getTime());
195
+ if (isBinaryValue(a) || isBinaryValue(b))
196
+ return isBinaryValue(a) && isBinaryValue(b) && a.byteLength === b.byteLength && a.every((value, index) => value === b[index]);
197
+ if (isTemporal(a) || isTemporal(b))
198
+ return isTemporal(a) && isTemporal(b) && a[Symbol.toStringTag] === b[Symbol.toStringTag] && a.toString() === b.toString();
199
+ const peers = compared.get(a);
200
+ if (peers?.has(b)) return true;
201
+ if (peers) peers.add(b);
202
+ else compared.set(a, /* @__PURE__ */ new Set([b]));
203
+ const [aKind, aShape] = structuralShape(a);
204
+ const [bKind, bShape] = structuralShape(b);
205
+ if (aKind !== bKind) return false;
206
+ const keys = (value) => Reflect.ownKeys(value).filter(
207
+ (key) => Object.prototype.propertyIsEnumerable.call(value, key)
208
+ );
209
+ const aKeys = keys(aShape);
210
+ if (aKeys.length !== keys(bShape).length) return false;
211
+ return aKeys.every(
212
+ (key) => Object.prototype.propertyIsEnumerable.call(bShape, key) && equal(aShape[key], bShape[key])
213
+ );
214
+ }
215
+ return equal(left, right);
150
216
  }
151
217
  let nextRefId = 1;
152
218
  function cachedReferenceHash(fn) {
@@ -155,11 +221,14 @@ function cachedReferenceHash(fn) {
155
221
  valueHash = nextRefId ^ FUNCTIONS;
156
222
  nextRefId++;
157
223
  hashCache.set(fn, valueHash);
224
+ referenceValues.add(fn);
158
225
  }
159
226
  return valueHash;
160
227
  }
161
228
  function keySort(a, b) {
162
229
  return a.localeCompare(b);
163
230
  }
231
+ exports.equalHashValues = equalHashValues;
164
232
  exports.hash = hash;
233
+ exports.registerOpaqueHash = registerOpaqueHash;
165
234
  //# sourceMappingURL=hash.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.cjs","sources":["../../../src/hashing/hash.ts"],"sourcesContent":["import { MurmurHashStream, randomHash } from './murmur.js'\nimport type { Hasher } from './murmur.js'\n\n/*\n * Implementation of structural hashing based on the Composites polyfill implementation:\n * https://github.com/tc39/proposal-composites\n */\n\nconst TRUE = randomHash()\nconst FALSE = randomHash()\nconst NULL = randomHash()\nconst UNDEFINED = randomHash()\nconst KEY = randomHash()\nconst FUNCTIONS = randomHash()\nconst DATE_MARKER = randomHash()\nconst OBJECT_MARKER = randomHash()\nconst ARRAY_MARKER = randomHash()\nconst MAP_MARKER = randomHash()\nconst SET_MARKER = randomHash()\nconst UINT8ARRAY_MARKER = randomHash()\nconst TEMPORAL_MARKER = randomHash()\n\nconst temporalTypes = new Set([\n `Temporal.Duration`,\n `Temporal.Instant`,\n `Temporal.PlainDate`,\n `Temporal.PlainDateTime`,\n `Temporal.PlainMonthDay`,\n `Temporal.PlainTime`,\n `Temporal.PlainYearMonth`,\n `Temporal.ZonedDateTime`,\n])\n\ninterface TemporalLike {\n [Symbol.toStringTag]: string\n toString: () => string\n}\n\nfunction isTemporal(input: object): input is TemporalLike {\n const tag = (input as Record<symbol, unknown>)[Symbol.toStringTag]\n return typeof tag === `string` && temporalTypes.has(tag)\n}\n\n// Maximum byte length for Uint8Arrays to hash by content instead of reference\n// Arrays smaller than this will be hashed by content, allowing proper equality comparisons\n// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays\nconst UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128\n\nconst hashCache = new WeakMap<object, number>()\n\nexport function hash(input: any): number {\n const hasher = new MurmurHashStream()\n updateHasher(hasher, input)\n return hasher.digest()\n}\n\nfunction hashObject(input: object): number {\n const cachedHash = hashCache.get(input)\n if (cachedHash !== undefined) {\n return cachedHash\n }\n\n let valueHash: number | undefined\n if (input instanceof Date) {\n valueHash = hashDate(input)\n } else if (\n // Check if input is a Uint8Array or Buffer\n (typeof Buffer !== `undefined` && input instanceof Buffer) ||\n input instanceof Uint8Array\n ) {\n // For small Uint8Arrays/Buffers (e.g., ULIDs, UUIDs), hash by content\n // to enable proper equality comparisons. For large arrays, hash by reference\n // to avoid performance costs.\n if (input.byteLength <= UINT8ARRAY_CONTENT_HASH_THRESHOLD) {\n valueHash = hashUint8Array(input)\n } else {\n // Deeply hashing large arrays would be too costly\n // so we track them by reference and cache them in a weak map\n return cachedReferenceHash(input)\n }\n } else if (input instanceof File) {\n // Files are always hashed by reference due to their potentially large size\n return cachedReferenceHash(input)\n } else if (isTemporal(input)) {\n valueHash = hashTemporal(input)\n } else {\n let plainObjectInput = input\n let marker = OBJECT_MARKER\n\n if (input instanceof Array) {\n marker = ARRAY_MARKER\n }\n\n if (input instanceof Map) {\n marker = MAP_MARKER\n plainObjectInput = [...input.entries()]\n }\n\n if (input instanceof Set) {\n marker = SET_MARKER\n plainObjectInput = [...input.entries()]\n }\n\n valueHash = hashPlainObject(plainObjectInput, marker)\n }\n\n hashCache.set(input, valueHash)\n return valueHash\n}\n\nfunction hashDate(input: Date): number {\n const hasher = new MurmurHashStream()\n hasher.update(DATE_MARKER)\n hasher.update(input.getTime())\n return hasher.digest()\n}\n\nfunction hashUint8Array(input: Uint8Array): number {\n const hasher = new MurmurHashStream()\n hasher.update(UINT8ARRAY_MARKER)\n // Hash the byte length first to differentiate arrays of different sizes\n hasher.update(input.byteLength)\n // Hash each byte in the array\n for (let i = 0; i < input.byteLength; i++) {\n hasher.writeByte(input[i]!)\n }\n return hasher.digest()\n}\n\nfunction hashTemporal(input: TemporalLike): number {\n const hasher = new MurmurHashStream()\n hasher.update(TEMPORAL_MARKER)\n hasher.update(input[Symbol.toStringTag])\n hasher.update(input.toString())\n return hasher.digest()\n}\n\nfunction hashPlainObject(input: object, marker: number): number {\n const hasher = new MurmurHashStream()\n\n // Mark the type of the input\n hasher.update(marker)\n const keys = Object.keys(input)\n keys.sort(keySort)\n for (const key of keys) {\n hasher.update(KEY)\n hasher.update(key)\n updateHasher(hasher, input[key as keyof typeof input])\n }\n\n return hasher.digest()\n}\n\nfunction updateHasher(hasher: Hasher, input: unknown): void {\n if (input === null) {\n hasher.update(NULL)\n return\n }\n switch (typeof input) {\n case `undefined`:\n hasher.update(UNDEFINED)\n return\n case `boolean`:\n hasher.update(input ? TRUE : FALSE)\n return\n case `number`:\n // Normalize NaNs and -0\n hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)\n return\n case `bigint`:\n case `string`:\n case `symbol`:\n hasher.update(input)\n return\n case `object`:\n hasher.update(getCachedHash(input))\n return\n case `function`:\n // Functions are assigned a globally unique ID\n // and that ID is cached in the weak map\n hasher.update(cachedReferenceHash(input))\n return\n default:\n console.warn(\n `Ignored input during hashing because it is of type ${typeof input} which is not supported`,\n )\n }\n}\n\nfunction getCachedHash(input: object): number {\n let valueHash = hashCache.get(input)\n if (valueHash === undefined) {\n valueHash = hashObject(input)\n }\n return valueHash\n}\n\nlet nextRefId = 1\nfunction cachedReferenceHash(fn: object): number {\n let valueHash = hashCache.get(fn)\n if (valueHash === undefined) {\n valueHash = nextRefId ^ FUNCTIONS\n nextRefId++\n hashCache.set(fn, valueHash)\n }\n return valueHash\n}\n\n/**\n * Strings sorted lexicographically.\n */\nfunction keySort(a: string, b: string): number {\n return a.localeCompare(b)\n}\n"],"names":["randomHash","MurmurHashStream"],"mappings":";;;AAQA,MAAM,OAAOA,OAAAA,WAAA;AACb,MAAM,QAAQA,OAAAA,WAAA;AACd,MAAM,OAAOA,OAAAA,WAAA;AACb,MAAM,YAAYA,OAAAA,WAAA;AAClB,MAAM,MAAMA,OAAAA,WAAA;AACZ,MAAM,YAAYA,OAAAA,WAAA;AAClB,MAAM,cAAcA,OAAAA,WAAA;AACp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AQ,OAAO,OAAA;AAAA,IACb,KAAK;AACH,aAAO,OAAO,SAAS;AACvB;AAAA,IACF,KAAK;AACH,aAAO,OAAO,QAAQ,OAAO,KAAK;AAClC;AAAA,IACF,KAAK;AAEH,aAAO,OAAO,MAAM,KAAK,IAAI,MAAM,UAAU,IAAI,IAAI,KAAK;AAC1D;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,OAAO,KAAK;AACnB;AAAA,IACF,KAAK;AACH,aAAO,OAAO,cAAc,KAAK,CAAC;AAClC;AAAA,IACF,KAAK;AAGH,aAAO,OAAO,oBAAoB,KAAK,CAAC;AACxC;AAAA,IACF;AACE,cAAQ;AAAA,QACN,sDAAsD,OAAO,KAAK;AAAA,MAAA;AAAA,EACpE;AAEN;AAEA,SAAS,cAAc,OAAuB;AAC5C,MAAI,YAAY,UAAU,IAAI,KAAK;AACnC,MAAI,cAAc,QAAW;AAC3B,gBAAY,WAAW,KAAK;AAAA,EAC9B;AACA,SAAO;AACT;AAEA,IAAI,YAAY;AAChB,SAAS,oBAAoB,IAAoB;AAC/C,MAAI,YAAY,UAAU,IAAI,EAAE;AAChC,MAAI,cAAc,QAAW;AAC3B,gBAAY,YAAY;AACxB;AACA,cAAU,IAAI,IAAI,SAAS;AAAA,EAC7B;AACA,SAAO;AACT;AAKA,SAAS,QAAQ,GAAW,GAAmB;AAC7C,SAAO,EAAE,cAAc,CAAC;AAC1B;;"}
1
+ {"version":3,"file":"hash.cjs","sources":["../../../src/hashing/hash.ts"],"sourcesContent":["import { MurmurHashStream, getSymbolIdentity, randomHash } from './murmur.js'\nimport type { Hasher } from './murmur.js'\n\n/*\n * Implementation of structural hashing based on the Composites polyfill implementation:\n * https://github.com/tc39/proposal-composites\n */\n\nconst TRUE = randomHash()\nconst FALSE = randomHash()\nconst NULL = randomHash()\nconst UNDEFINED = randomHash()\nconst KEY = randomHash()\nconst FUNCTIONS = randomHash()\nconst DATE_MARKER = randomHash()\nconst STRUCTURAL_MARKERS = {\n object: randomHash(),\n array: randomHash(),\n map: randomHash(),\n set: randomHash(),\n}\nconst UINT8ARRAY_MARKER = randomHash()\nconst TEMPORAL_MARKER = randomHash()\n// Bound structural recursion and value visits. Shared acyclic subtrees are\n// cached; cycles are rejected rather than given context-dependent hashes.\nconst MAX_STRUCTURAL_HASH_WORK = 1_000_000\nconst MAX_STRUCTURAL_HASH_DEPTH = 768\n\nconst temporalTypes = new Set([\n `Temporal.Duration`,\n `Temporal.Instant`,\n `Temporal.PlainDate`,\n `Temporal.PlainDateTime`,\n `Temporal.PlainMonthDay`,\n `Temporal.PlainTime`,\n `Temporal.PlainYearMonth`,\n `Temporal.ZonedDateTime`,\n])\n\ninterface TemporalLike {\n [Symbol.toStringTag]: string\n toString: () => string\n}\n\nfunction isTemporal(input: object): input is TemporalLike {\n const tag = (input as Record<symbol, unknown>)[Symbol.toStringTag]\n return typeof tag === `string` && temporalTypes.has(tag)\n}\n\n// Maximum byte length for Uint8Arrays to hash by content instead of reference\n// Arrays smaller than this will be hashed by content, allowing proper equality comparisons\n// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays\nconst UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128\n\nconst hashCache = new WeakMap<object, number>()\nconst referenceValues = new WeakSet<object>()\n\n/** @internal Register a mutable handle before it enters a structural value. */\nexport function registerOpaqueHash(value: object): void {\n cachedReferenceHash(value)\n}\n\ntype HashContext = {\n activeObjects: Set<object>\n work: number\n pendingHashes: Map<object, number>\n}\n\nexport function hash(input: any): number {\n const hasher = new MurmurHashStream()\n updateHasher(hasher, input)\n return hasher.digest()\n}\n\nfunction hashObject(input: object, context: HashContext): number {\n if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {\n throw new RangeError(\n `Value is too complex to hash safely: structural depth`,\n )\n }\n\n context.activeObjects.add(input)\n\n let valueHash: number | undefined\n try {\n if (input instanceof Date) {\n valueHash = hashDate(input)\n } else if (isBinaryValue(input)) {\n valueHash = hashUint8Array(input)\n } else if (isTemporal(input)) {\n valueHash = hashTemporal(input)\n } else {\n const [kind, plainObjectInput] = structuralShape(input)\n valueHash = hashPlainObject(\n plainObjectInput,\n STRUCTURAL_MARKERS[kind],\n context,\n )\n }\n } finally {\n context.activeObjects.delete(input)\n }\n\n context.pendingHashes.set(input, valueHash)\n return valueHash\n}\n\nfunction hashDate(input: Date): number {\n const hasher = new MurmurHashStream()\n hasher.update(DATE_MARKER)\n hasher.update(input.getTime())\n return hasher.digest()\n}\n\nfunction hashUint8Array(input: Uint8Array): number {\n const hasher = new MurmurHashStream()\n hasher.update(UINT8ARRAY_MARKER)\n // Hash the byte length first to differentiate arrays of different sizes\n hasher.update(input.byteLength)\n // Hash each byte in the array\n for (let i = 0; i < input.byteLength; i++) {\n hasher.writeByte(input[i]!)\n }\n return hasher.digest()\n}\n\nfunction hashTemporal(input: TemporalLike): number {\n const hasher = new MurmurHashStream()\n hasher.update(TEMPORAL_MARKER)\n hasher.update(input[Symbol.toStringTag])\n hasher.update(input.toString())\n return hasher.digest()\n}\n\nfunction hashPlainObject(\n input: object,\n marker: number,\n context: HashContext,\n): number {\n const hasher = new MurmurHashStream()\n\n // Mark the type of the input\n hasher.update(marker)\n const keys = Object.keys(input)\n keys.sort(keySort)\n for (const key of keys) {\n hasher.update(KEY)\n hasher.update(key)\n updateHasher(hasher, input[key as keyof typeof input], context)\n }\n const symbolKeys = Object.getOwnPropertySymbols(input)\n .filter((key) => Object.prototype.propertyIsEnumerable.call(input, key))\n .sort((left, right) => getSymbolIdentity(left) - getSymbolIdentity(right))\n for (const key of symbolKeys) {\n hasher.update(KEY)\n hasher.update(key)\n updateHasher(hasher, input[key as keyof typeof input], context)\n }\n\n return hasher.digest()\n}\n\nfunction updateHasher(\n hasher: Hasher,\n input: unknown,\n context?: HashContext,\n): void {\n if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {\n throw new RangeError(`Value is too complex to hash safely: structural work`)\n }\n if (input === null) {\n hasher.update(NULL)\n return\n }\n switch (typeof input) {\n case `undefined`:\n hasher.update(UNDEFINED)\n return\n case `boolean`:\n hasher.update(input ? TRUE : FALSE)\n return\n case `number`:\n // Normalize NaNs and -0\n hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)\n return\n case `bigint`:\n case `string`:\n case `symbol`:\n hasher.update(input)\n return\n case `object`:\n hasher.update(getCachedHash(input, context))\n return\n case `function`:\n // Functions are assigned a globally unique ID\n // and that ID is cached in the weak map\n hasher.update(cachedReferenceHash(input))\n return\n default:\n console.warn(\n `Ignored input during hashing because it is of type ${typeof input} which is not supported`,\n )\n }\n}\n\nfunction getCachedHash(input: object, context?: HashContext): number {\n if (!context) {\n const cached = hashCache.get(input)\n if (cached !== undefined) return cached\n if (isReferenceHashedObject(input)) return cachedReferenceHash(input)\n\n // Only an uncached structural root needs graph traversal state. Commit its\n // cache entries after success so a failed traversal cannot poison retries.\n context = {\n activeObjects: new Set(),\n work: 0,\n pendingHashes: new Map(),\n }\n const result = hashObject(input, context)\n for (const [object, valueHash] of context.pendingHashes) {\n hashCache.set(object, valueHash)\n }\n return result\n }\n\n if (context.activeObjects.has(input)) {\n throw new TypeError(`Cannot hash cyclic structural values`)\n }\n\n // Opaque leaves cannot contain structural back-references. Resolve them\n // before entering structural recursion, even when they have user properties.\n if (isReferenceHashedObject(input)) return cachedReferenceHash(input)\n\n const valueHash = hashCache.get(input) ?? context.pendingHashes.get(input)\n if (valueHash !== undefined) return valueHash\n\n return hashObject(input, context)\n}\n\nfunction isReferenceHashedObject(input: object): boolean {\n return (\n input instanceof File ||\n (isBinaryValue(input) &&\n input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD)\n )\n}\n\nfunction isBinaryValue(input: object): input is Uint8Array {\n return (\n (typeof Buffer !== `undefined` && input instanceof Buffer) ||\n input instanceof Uint8Array\n )\n}\n\nfunction structuralShape(\n input: object,\n): [keyof typeof STRUCTURAL_MARKERS, object] {\n if (input instanceof Map) return [`map`, [...input.entries()]]\n if (input instanceof Set) return [`set`, [...input.values()]]\n return [input instanceof Array ? `array` : `object`, input]\n}\n\n/** @internal Compare immutable structural values without computing a digest.\n * Pair memoization also permits cyclic values that structural hashing rejects.\n * Reference-valued leaves remain opaque, including registered mutable handles.\n */\nexport function equalHashValues(left: unknown, right: unknown): boolean {\n const compared = new Map<object, Set<object>>()\n function equal(a: unknown, b: unknown): boolean {\n if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true\n if (\n a === null ||\n b === null ||\n typeof a !== `object` ||\n typeof b !== `object`\n )\n return false\n if (\n referenceValues.has(a) ||\n referenceValues.has(b) ||\n isReferenceHashedObject(a) ||\n isReferenceHashedObject(b)\n )\n return false\n if (a instanceof Date || b instanceof Date)\n return (\n a instanceof Date &&\n b instanceof Date &&\n equal(a.getTime(), b.getTime())\n )\n if (isBinaryValue(a) || isBinaryValue(b))\n return (\n isBinaryValue(a) &&\n isBinaryValue(b) &&\n a.byteLength === b.byteLength &&\n a.every((value, index) => value === b[index])\n )\n if (isTemporal(a) || isTemporal(b))\n return (\n isTemporal(a) &&\n isTemporal(b) &&\n a[Symbol.toStringTag] === b[Symbol.toStringTag] &&\n a.toString() === b.toString()\n )\n\n // Revisited pairs close cycles and avoid expanding shared subtrees.\n const peers = compared.get(a)\n if (peers?.has(b)) return true\n if (peers) peers.add(b)\n else compared.set(a, new Set([b]))\n const [aKind, aShape] = structuralShape(a)\n const [bKind, bShape] = structuralShape(b)\n if (aKind !== bKind) return false\n const keys = (value: object) =>\n Reflect.ownKeys(value).filter((key) =>\n Object.prototype.propertyIsEnumerable.call(value, key),\n )\n const aKeys = keys(aShape)\n if (aKeys.length !== keys(bShape).length) return false\n return aKeys.every(\n (key) =>\n Object.prototype.propertyIsEnumerable.call(bShape, key) &&\n equal(aShape[key as keyof object], bShape[key as keyof object]),\n )\n }\n return equal(left, right)\n}\n\nlet nextRefId = 1\nfunction cachedReferenceHash(fn: object): number {\n let valueHash = hashCache.get(fn)\n if (valueHash === undefined) {\n valueHash = nextRefId ^ FUNCTIONS\n nextRefId++\n hashCache.set(fn, valueHash)\n referenceValues.add(fn)\n }\n return valueHash\n}\n\n/**\n * Strings sorted lexicographically.\n */\nfunction keySort(a: string, b: string): number {\n return a.localeCompare(b)\n}\n"],"names":["randomHash","MurmurHashStream","getSymbolIdentity","valueHash"],"mappings":";;;AAQA,MAAM,OAAOA,OAAAA,WAAA;AACb,MAAM,QAAQA,OAAAA,WAAA;AACd,MAAM,OAAOA,OAAAA,WAAA;AACb,MAAM,YAAYA,OAAAA,WAAA;AAClB,MAAM,MAAMA,OAAAA,WAAA;AACZ,MAAM,YAAYA,OAAAA,WAAA;AAClB,MAAM,cAAcA,OAAAA,WAAA;AACpB,MAAM,qBAAqB;AAAA,EACzB,QAAQA,OAAAA,WAAA;AAAA,EACR,OAAOA,OAAAA,WAAA;AAAA,EACP,KAAKA,OAAAA,WAAA;AAAA,EACL,KAAKA,OAAAA,WAAA;AACP;AACA,MAAM,oBAAoBA,OAAAA,WAAA;AAC1B,MAAM,kBAAkBA,OAAAA,WAAA;AAGxB,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAElC,MAAM,oCAAoB,IAAI;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,SAAS,WAAW,OAAsC;AACxD,QAAM,MAAO,MAAkC,OAAO,WAAW;AACjE,SAAO,OAAO,QAAQ,YAAY,cAAc,IAAI,GAAG;AACzD;AAKA,MAAM,oCAAoC;AAE1C,MAAM,gCAAgB,QAAA;AACtB,MAAM,sCAAsB,QAAA;AAGrB,SAAS,mBAAmB,OAAqB;AACtD,sBAAoB,KAAK;AAC3B;AAQO,SAAS,KAAK,OAAoB;AACvC,QAAM,SAAS,IAAIC,wBAAA;AACnB,eAAa,QAAQ,KAAK;AAC1B,SAAO,OAAO,OAAA;AAChB;AAEA,SAAS,WAAW,OAAe,SAA8B;AAC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K,MAAM,EAAE,OAAQ,QAAO;AACjD,WAAO,MAAM;AAAA,MACX,CAAC,QACC,OAAO,UAAU,qBAAqB,KAAK,QAAQ,GAAG,KACtD,MAAM,OAAO,GAAmB,GAAG,OAAO,GAAmB,CAAC;AAAA,IAAA;AAAA,EAEpE;AACA,SAAO,MAAM,MAAM,KAAK;AAC1B;AAEA,IAAI,YAAY;AAChB,SAAS,oBAAoB,IAAoB;AAC/C,MAAI,YAAY,UAAU,IAAI,EAAE;AAChC,MAAI,cAAc,QAAW;AAC3B,gBAAY,YAAY;AACxB;AACA,cAAU,IAAI,IAAI,SAAS;AAC3B,oBAAgB,IAAI,EAAE;AAAA,EACxB;AACA,SAAO;AACT;AAKA,SAAS,QAAQ,GAAW,GAAmB;AAC7C,SAAO,EAAE,cAAc,CAAC;AAC1B;;;;"}
@@ -1 +1,8 @@
1
+ /** @internal Register a mutable handle before it enters a structural value. */
2
+ export declare function registerOpaqueHash(value: object): void;
1
3
  export declare function hash(input: any): number;
4
+ /** @internal Compare immutable structural values without computing a digest.
5
+ * Pair memoization also permits cyclic values that structural hashing rejects.
6
+ * Reference-valued leaves remain opaque, including registered mutable handles.
7
+ */
8
+ export declare function equalHashValues(left: unknown, right: unknown): boolean;
@@ -5,6 +5,36 @@ const STRING_MARKER = randomHash();
5
5
  const BIG_INT_MARKER = randomHash();
6
6
  const NEG_BIG_INT_MARKER = randomHash();
7
7
  const SYMBOL_MARKER = randomHash();
8
+ const symbolIds = createSymbolIdStore();
9
+ const registeredSymbolIds = /* @__PURE__ */ new Map();
10
+ let nextSymbolId = 0;
11
+ function getSymbolIdentity(symbol) {
12
+ const registeredKey = Symbol.keyFor(symbol);
13
+ if (registeredKey !== void 0) {
14
+ let id2 = registeredSymbolIds.get(registeredKey);
15
+ if (id2 === void 0) {
16
+ id2 = ++nextSymbolId;
17
+ registeredSymbolIds.set(registeredKey, id2);
18
+ }
19
+ return id2;
20
+ }
21
+ let id = symbolIds.get(symbol);
22
+ if (id === void 0) {
23
+ id = ++nextSymbolId;
24
+ symbolIds.set(symbol, id);
25
+ }
26
+ return id;
27
+ }
28
+ function createSymbolIdStore() {
29
+ const weakIds = /* @__PURE__ */ new WeakMap();
30
+ const probe = /* @__PURE__ */ Symbol();
31
+ try {
32
+ weakIds.set(probe, 0);
33
+ if (weakIds.get(probe) === 0) return weakIds;
34
+ } catch {
35
+ }
36
+ return /* @__PURE__ */ new Map();
37
+ }
8
38
  function randomHash() {
9
39
  return Math.random() * (2 ** 31 - 1) >>> 0;
10
40
  }
@@ -40,15 +70,7 @@ class MurmurHashStream {
40
70
  switch (typeof chunk) {
41
71
  case `symbol`: {
42
72
  this.update(SYMBOL_MARKER);
43
- const description = chunk.description;
44
- if (!description) {
45
- return;
46
- }
47
- for (let i = 0; i < description.length; i++) {
48
- const code = description.charCodeAt(i);
49
- this.writeByte(code & 255);
50
- this.writeByte(code >>> 8 & 255);
51
- }
73
+ this.update(getSymbolIdentity(chunk));
52
74
  return;
53
75
  }
54
76
  case `string`:
@@ -107,5 +129,6 @@ class MurmurHashStream {
107
129
  }
108
130
  }
109
131
  exports.MurmurHashStream = MurmurHashStream;
132
+ exports.getSymbolIdentity = getSymbolIdentity;
110
133
  exports.randomHash = randomHash;
111
134
  //# sourceMappingURL=murmur.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"murmur.cjs","sources":["../../../src/hashing/murmur.ts"],"sourcesContent":["/*\n * Implementation of murmur hash based on the Composites polyfill implementation:\n * https://github.com/tc39/proposal-composites\n */\n\nconst RANDOM_SEED = randomHash()\nconst STRING_MARKER = randomHash()\nconst BIG_INT_MARKER = randomHash()\nconst NEG_BIG_INT_MARKER = randomHash()\nconst SYMBOL_MARKER = randomHash()\n\nexport type Hash = number\n\nexport function randomHash() {\n return (Math.random() * (2 ** 31 - 1)) >>> 0\n}\n\nexport interface Hasher {\n update: (val: symbol | string | number | bigint) => void\n digest: () => number\n}\n\n// Allocate these once, outside the hot path\nconst buf = new ArrayBuffer(8)\n// dv and u8 are 2 different views on the same buffer `buf`\nconst dv = new DataView(buf)\nconst u8 = new Uint8Array(buf)\n\n/**\n * This implementation of Murmur hash uses a random initial seed and random markers.\n * This means that hashes aren't deterministic across app restarts.\n * This is intentional in the composites polyfill to be resistent to hash-flooding attacks\n * where malicious users would precompute lots of different objects whose hashes collide with each other.\n *\n * Currently, for ts/db-ivm this is fine because we don't persist client state.\n * However, when we will introduce persistence we will either need to store the seeds or remove the randomness\n * to ensure deterministic hashes across app restarts.\n */\nexport class MurmurHashStream implements Hasher {\n private hash: number = RANDOM_SEED\n private length = 0\n private carry = 0\n private carryBytes = 0\n\n private _mix(k1: number): void {\n k1 = Math.imul(k1, 0xcc9e2d51)\n k1 = (k1 << 15) | (k1 >>> 17)\n k1 = Math.imul(k1, 0x1b873593)\n this.hash ^= k1\n this.hash = (this.hash << 13) | (this.hash >>> 19)\n this.hash = Math.imul(this.hash, 5) + 0xe6546b64\n }\n\n writeByte(byte: number): void {\n this.carry |= (byte & 0xff) << (8 * this.carryBytes)\n this.carryBytes++\n this.length++\n\n if (this.carryBytes === 4) {\n this._mix(this.carry >>> 0)\n this.carry = 0\n this.carryBytes = 0\n }\n }\n\n update(chunk: symbol | string | number | bigint): void {\n switch (typeof chunk) {\n case `symbol`: {\n this.update(SYMBOL_MARKER)\n const description = chunk.description\n if (!description) {\n return\n }\n\n for (let i = 0; i < description.length; i++) {\n const code = description.charCodeAt(i)\n this.writeByte(code & 0xff)\n this.writeByte((code >>> 8) & 0xff)\n }\n return\n }\n case `string`:\n this.update(STRING_MARKER)\n for (let i = 0; i < chunk.length; i++) {\n const code = chunk.charCodeAt(i)\n this.writeByte(code & 0xff)\n this.writeByte((code >>> 8) & 0xff)\n }\n return\n case `number`:\n dv.setFloat64(0, chunk, true) // fixed little-endian\n this.writeByte(u8[0]!)\n this.writeByte(u8[1]!)\n this.writeByte(u8[2]!)\n this.writeByte(u8[3]!)\n this.writeByte(u8[4]!)\n this.writeByte(u8[5]!)\n this.writeByte(u8[6]!)\n this.writeByte(u8[7]!)\n return\n case `bigint`: {\n let value = chunk\n if (value < 0n) {\n value = -value\n this.update(NEG_BIG_INT_MARKER)\n } else {\n this.update(BIG_INT_MARKER)\n }\n while (value > 0n) {\n this.writeByte(Number(value & 0xffn))\n value >>= 8n\n }\n if (chunk === 0n) this.writeByte(0)\n return\n }\n default:\n throw new TypeError(`Unsupported input type: ${typeof chunk}`)\n }\n }\n\n digest(): number {\n if (this.carryBytes > 0) {\n let k1 = this.carry >>> 0\n k1 = Math.imul(k1, 0xcc9e2d51)\n k1 = (k1 << 15) | (k1 >>> 17)\n k1 = Math.imul(k1, 0x1b873593)\n this.hash ^= k1\n }\n\n this.hash ^= this.length\n this.hash ^= this.hash >>> 16\n this.hash = Math.imul(this.hash, 0x85ebca6b)\n this.hash ^= this.hash >>> 13\n this.hash = Math.imul(this.hash, 0xc2b2ae35)\n this.hash ^= this.hash >>> 16\n\n return this.hash >>> 0\n }\n}\n"],"names":[],"mappings":";;AAKA,MAAM,cAAc,WAAA;AACpB,MAAM,gBAAgB,WAAA;AACtB,MAAM,iBAAiB,WAAA;AACvB,MAAM,qBAAqB,WAAA;AAC3B,MAAM,gBAAgB,WAAA;AAIf,SAAS,aAAa;AAC3B,SAAQ,KAAK,OAAA,KAAY,KAAK,KAAK,OAAQ;AAC7C;AAQA,MAAM,MAAM,IAAI,YAAY,CAAC;AAE7B,MAAM,KAAK,IAAI,SAAS,GAAG;AAC3B,MAAM,KAAK,IAAI,WAAW,GAAG;AAYtB,MAAM,iBAAmC;AAAA,EAAzC,cAAA;AACL,SAAQ,OAAe;AACvB,SAAQ,SAAS;AACjB,SAAQ,QAAQ;AAChB,SAAQ,aAAa;AAAA,EAAA;AAAA,EAEb,KAAK,IAAkB;AAC7B,SAAK,KAAK,KAAK,IAAI,UAAU;AAC7B,SAAM,MAAM,KAAO,OAAO;AAC1B,SAAK,KAAK,KAAK,IAAI,SAAU;AAC7B,SAAK,QAAQ;AACb,SAAK,OAAQ,K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,KAAK,UAAU;AACb,YAAI,QAAQ;AACZ,YAAI,QAAQ,IAAI;AACd,kBAAQ,CAAC;AACT,eAAK,OAAO,kBAAkB;AAAA,QAChC,OAAO;AACL,eAAK,OAAO,cAAc;AAAA,QAC5B;AACA,eAAO,QAAQ,IAAI;AACjB,eAAK,UAAU,OAAO,QAAQ,KAAK,CAAC;AACpC,oBAAU;AAAA,QACZ;AACA,YAAI,UAAU,GAAI,MAAK,UAAU,CAAC;AAClC;AAAA,MACF;AAAA,MACA;AACE,cAAM,IAAI,UAAU,2BAA2B,OAAO,KAAK,EAAE;AAAA,IAAA;AAAA,EAEnE;AAAA,EAEA,SAAiB;AACf,QAAI,KAAK,aAAa,GAAG;AACvB,UAAI,KAAK,KAAK,UAAU;AACxB,WAAK,KAAK,KAAK,IAAI,UAAU;AAC7B,WAAM,MAAM,KAAO,OAAO;AAC1B,WAAK,KAAK,KAAK,IAAI,SAAU;AAC7B,WAAK,QAAQ;AAAA,IACf;AAEA,SAAK,QAAQ,KAAK;AAClB,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,KAAK,KAAK,MAAM,UAAU;AAC3C,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,KAAK,KAAK,MAAM,UAAU;AAC3C,SAAK,QAAQ,KAAK,SAAS;AAE3B,WAAO,KAAK,SAAS;AAAA,EACvB;AACF;;;"}
1
+ {"version":3,"file":"murmur.cjs","sources":["../../../src/hashing/murmur.ts"],"sourcesContent":["/*\n * Implementation of murmur hash based on the Composites polyfill implementation:\n * https://github.com/tc39/proposal-composites\n */\n\nconst RANDOM_SEED = randomHash()\nconst STRING_MARKER = randomHash()\nconst BIG_INT_MARKER = randomHash()\nconst NEG_BIG_INT_MARKER = randomHash()\nconst SYMBOL_MARKER = randomHash()\n\ntype SymbolIdStore = {\n get: (key: symbol) => number | undefined\n set: (key: symbol, value: number) => unknown\n}\n\nconst symbolIds = createSymbolIdStore()\nconst registeredSymbolIds = new Map<string, number>()\nlet nextSymbolId = 0\n\nexport function getSymbolIdentity(symbol: symbol): number {\n const registeredKey = Symbol.keyFor(symbol)\n if (registeredKey !== undefined) {\n let id = registeredSymbolIds.get(registeredKey)\n if (id === undefined) {\n id = ++nextSymbolId\n registeredSymbolIds.set(registeredKey, id)\n }\n return id\n }\n\n let id = symbolIds.get(symbol)\n if (id === undefined) {\n id = ++nextSymbolId\n symbolIds.set(symbol, id)\n }\n return id\n}\n\nfunction createSymbolIdStore(): SymbolIdStore {\n const weakIds = new WeakMap<object, number>() as unknown as SymbolIdStore\n const probe = Symbol()\n\n try {\n weakIds.set(probe, 0)\n if (weakIds.get(probe) === 0) return weakIds\n } catch {\n // Older runtimes reject symbols as weak keys. Retain them rather than\n // merge distinct symbols and corrupt differential state.\n }\n\n return new Map<symbol, number>()\n}\n\nexport type Hash = number\n\nexport function randomHash() {\n return (Math.random() * (2 ** 31 - 1)) >>> 0\n}\n\nexport interface Hasher {\n update: (val: symbol | string | number | bigint) => void\n digest: () => number\n}\n\n// Allocate these once, outside the hot path\nconst buf = new ArrayBuffer(8)\n// dv and u8 are 2 different views on the same buffer `buf`\nconst dv = new DataView(buf)\nconst u8 = new Uint8Array(buf)\n\n/**\n * This implementation of Murmur hash uses a random initial seed and random markers.\n * This means that hashes aren't deterministic across app restarts.\n * This is intentional in the composites polyfill to be resistent to hash-flooding attacks\n * where malicious users would precompute lots of different objects whose hashes collide with each other.\n *\n * Currently, for ts/db-ivm this is fine because we don't persist client state.\n * However, when we will introduce persistence we will either need to store the seeds or remove the randomness\n * to ensure deterministic hashes across app restarts.\n */\nexport class MurmurHashStream implements Hasher {\n private hash: number = RANDOM_SEED\n private length = 0\n private carry = 0\n private carryBytes = 0\n\n private _mix(k1: number): void {\n k1 = Math.imul(k1, 0xcc9e2d51)\n k1 = (k1 << 15) | (k1 >>> 17)\n k1 = Math.imul(k1, 0x1b873593)\n this.hash ^= k1\n this.hash = (this.hash << 13) | (this.hash >>> 19)\n this.hash = Math.imul(this.hash, 5) + 0xe6546b64\n }\n\n writeByte(byte: number): void {\n this.carry |= (byte & 0xff) << (8 * this.carryBytes)\n this.carryBytes++\n this.length++\n\n if (this.carryBytes === 4) {\n this._mix(this.carry >>> 0)\n this.carry = 0\n this.carryBytes = 0\n }\n }\n\n update(chunk: symbol | string | number | bigint): void {\n switch (typeof chunk) {\n case `symbol`: {\n this.update(SYMBOL_MARKER)\n this.update(getSymbolIdentity(chunk))\n return\n }\n case `string`:\n this.update(STRING_MARKER)\n for (let i = 0; i < chunk.length; i++) {\n const code = chunk.charCodeAt(i)\n this.writeByte(code & 0xff)\n this.writeByte((code >>> 8) & 0xff)\n }\n return\n case `number`:\n dv.setFloat64(0, chunk, true) // fixed little-endian\n this.writeByte(u8[0]!)\n this.writeByte(u8[1]!)\n this.writeByte(u8[2]!)\n this.writeByte(u8[3]!)\n this.writeByte(u8[4]!)\n this.writeByte(u8[5]!)\n this.writeByte(u8[6]!)\n this.writeByte(u8[7]!)\n return\n case `bigint`: {\n let value = chunk\n if (value < 0n) {\n value = -value\n this.update(NEG_BIG_INT_MARKER)\n } else {\n this.update(BIG_INT_MARKER)\n }\n while (value > 0n) {\n this.writeByte(Number(value & 0xffn))\n value >>= 8n\n }\n if (chunk === 0n) this.writeByte(0)\n return\n }\n default:\n throw new TypeError(`Unsupported input type: ${typeof chunk}`)\n }\n }\n\n digest(): number {\n if (this.carryBytes > 0) {\n let k1 = this.carry >>> 0\n k1 = Math.imul(k1, 0xcc9e2d51)\n k1 = (k1 << 15) | (k1 >>> 17)\n k1 = Math.imul(k1, 0x1b873593)\n this.hash ^= k1\n }\n\n this.hash ^= this.length\n this.hash ^= this.hash >>> 16\n this.hash = Math.imul(this.hash, 0x85ebca6b)\n this.hash ^= this.hash >>> 13\n this.hash = Math.imul(this.hash, 0xc2b2ae35)\n this.hash ^= this.hash >>> 16\n\n return this.hash >>> 0\n }\n}\n"],"names":["id"],"mappings":";;AAKA,MAAM,cAAc,WAAA;AACpB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AACA,eAAO,QAAQ,IAAI;AACjB,eAAK,UAAU,OAAO,QAAQ,KAAK,CAAC;AACpC,oBAAU;AAAA,QACZ;AACA,YAAI,UAAU,GAAI,MAAK,UAAU,CAAC;AAClC;AAAA,MACF;AAAA,MACA;AACE,cAAM,IAAI,UAAU,2BAA2B,OAAO,KAAK,EAAE;AAAA,IAAA;AAAA,EAEnE;AAAA,EAEA,SAAiB;AACf,QAAI,KAAK,aAAa,GAAG;AACvB,UAAI,KAAK,KAAK,UAAU;AACxB,WAAK,KAAK,KAAK,IAAI,UAAU;AAC7B,WAAM,MAAM,KAAO,OAAO;AAC1B,WAAK,KAAK,KAAK,IAAI,SAAU;AAC7B,WAAK,QAAQ;AAAA,IACf;AAEA,SAAK,QAAQ,KAAK;AAClB,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,KAAK,KAAK,MAAM,UAAU;AAC3C,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,KAAK,KAAK,MAAM,UAAU;AAC3C,SAAK,QAAQ,KAAK,SAAS;AAE3B,WAAO,KAAK,SAAS;AAAA,EACvB;AACF;;;;"}
@@ -1,3 +1,4 @@
1
+ export declare function getSymbolIdentity(symbol: symbol): number;
1
2
  export type Hash = number;
2
3
  export declare function randomHash(): number;
3
4
  export interface Hasher {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const d2 = require("./d2.cjs");
4
4
  const multiset = require("./multiset.cjs");
5
5
  const utils = require("./utils.cjs");
6
+ const hash = require("./hashing/hash.cjs");
6
7
  const groupBy = require("./operators/groupBy.cjs");
7
8
  const pipe = require("./operators/pipe.cjs");
8
9
  const map = require("./operators/map.cjs");
@@ -30,6 +31,7 @@ exports.StreamBuilder = d2.StreamBuilder;
30
31
  exports.MultiSet = multiset.MultiSet;
31
32
  exports.compareKeys = utils.compareKeys;
32
33
  exports.serializeValue = utils.serializeValue;
34
+ exports.registerOpaqueHash = hash.registerOpaqueHash;
33
35
  exports.groupBy = groupBy.groupBy;
34
36
  exports.groupByOperators = groupBy.groupByOperators;
35
37
  exports.pipe = pipe.pipe;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -3,3 +3,4 @@ export * from './multiset.js';
3
3
  export * from './operators/index.js';
4
4
  export * from './types.js';
5
5
  export { compareKeys, serializeValue } from './utils.js';
6
+ export { registerOpaqueHash } from './hashing/hash.js';
@@ -1 +1 @@
1
- {"version":3,"file":"distinct.cjs","sources":["../../../src/operators/distinct.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { hash } from '../hashing/index.js'\nimport { MultiSet } from '../multiset.js'\nimport type { Hash } from '../hashing/index.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\ntype Multiplicity = number\n\ntype GetValue<T> = T extends KeyValue<any, infer V> ? V : never\n\n/**\n * Operator that removes duplicates\n */\nexport class DistinctOperator<\n T extends KeyValue<any, any>,\n> extends UnaryOperator<T, KeyValue<number, GetValue<T>>> {\n #by: (value: T) => any\n #values: Map<Hash, Multiplicity> // keeps track of the number of times each value has been seen\n\n constructor(\n id: number,\n input: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<KeyValue<number, GetValue<T>>>,\n by: (value: T) => any = (value: T) => value,\n ) {\n super(id, input, output)\n this.#by = by\n this.#values = new Map()\n }\n\n run(): void {\n const updatedValues = new Map<Hash, [Multiplicity, T]>()\n\n // Compute the new multiplicity for each value\n for (const message of this.inputMessages()) {\n for (const [value, diff] of message.getInner()) {\n const hashedValue = hash(this.#by(value))\n\n const oldMultiplicity =\n updatedValues.get(hashedValue)?.[0] ??\n this.#values.get(hashedValue) ??\n 0\n const newMultiplicity = oldMultiplicity + diff\n updatedValues.set(hashedValue, [newMultiplicity, value])\n }\n }\n\n const result: Array<[KeyValue<number, GetValue<T>>, number]> = []\n\n // Check which values became visible or disappeared\n for (const [\n hashedValue,\n [newMultiplicity, value],\n ] of updatedValues.entries()) {\n const oldMultiplicity = this.#values.get(hashedValue) ?? 0\n\n if (newMultiplicity === 0) {\n this.#values.delete(hashedValue)\n } else {\n this.#values.set(hashedValue, newMultiplicity)\n }\n\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value wasn't present in the stream\n // but with this change it is now present in the stream\n result.push([[hash(this.#by(value)), value[1]], 1])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was present in the stream\n // but with this change it is no longer present in the stream\n result.push([[hash(this.#by(value)), value[1]], -1])\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n}\n\n/**\n * Removes duplicate values\n */\nexport function distinct<T extends KeyValue<any, any>>(\n by: (value: T) => any = (value: T) => value,\n) {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>(),\n )\n const operator = new DistinctOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n by,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","hash","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;AAeO,MAAM,yBAEHA,MAAAA,cAAgD;AAAA,EACxD;AAAA,EACA;AAAA;AAAA,EAEA,YACE,IACA,OACA,QACA,KAAwB,CAAC,UAAa,OACtC;AACA,UAAM,IAAI,OAAO,MAAM;AACv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AACvD,UAAM,SAAS,IAAIC,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
1
+ {"version":3,"file":"distinct.cjs","sources":["../../../src/operators/distinct.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { hash } from '../hashing/index.js'\nimport { MultiSet } from '../multiset.js'\nimport type { Hash } from '../hashing/index.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\ntype Multiplicity = number\n\ntype GetValue<T> = T extends KeyValue<any, infer V> ? V : never\n\n/**\n * Operator that removes duplicates\n */\nexport class DistinctOperator<\n T extends KeyValue<any, any>,\n> extends UnaryOperator<T, KeyValue<number, GetValue<T>>> {\n #by: (value: T) => any\n #values: Map<Hash, Multiplicity> // keeps track of the number of times each value has been seen\n\n constructor(\n id: number,\n input: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<KeyValue<number, GetValue<T>>>,\n by: (value: T) => any = (value: T) => value,\n ) {\n super(id, input, output)\n this.#by = by\n this.#values = new Map()\n }\n\n run(): void {\n const updatedValues = new Map<Hash, [Multiplicity, T]>()\n\n // Compute the new multiplicity for each value\n for (const message of this.inputMessages()) {\n for (const [value, diff] of message.getInner()) {\n const hashedValue = hash(this.#by(value))\n\n const oldMultiplicity =\n updatedValues.get(hashedValue)?.[0] ??\n this.#values.get(hashedValue) ??\n 0\n const newMultiplicity = oldMultiplicity + diff\n updatedValues.set(hashedValue, [newMultiplicity, value])\n }\n }\n\n const result: Array<[KeyValue<number, GetValue<T>>, number]> = []\n\n // Check which values became visible or disappeared\n for (const [\n hashedValue,\n [newMultiplicity, value],\n ] of updatedValues.entries()) {\n const oldMultiplicity = this.#values.get(hashedValue) ?? 0\n\n if (newMultiplicity === 0) {\n this.#values.delete(hashedValue)\n } else {\n this.#values.set(hashedValue, newMultiplicity)\n }\n\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value wasn't present in the stream\n // but with this change it is now present in the stream\n result.push([[hash(this.#by(value)), value[1]], 1])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was present in the stream\n // but with this change it is no longer present in the stream\n result.push([[hash(this.#by(value)), value[1]], -1])\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n}\n\n/**\n * Removes duplicate values\n */\nexport function distinct<T extends KeyValue<any, any>>(\n by: (value: T) => any = (value: T) => value,\n) {\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<KeyValue<number, GetValue<T>>> => {\n const output = new StreamBuilder<KeyValue<number, GetValue<T>>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<number, GetValue<T>>>(),\n )\n const operator = new DistinctOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n by,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","hash","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;AAeO,MAAM,yBAEHA,MAAAA,cAAgD;AAAA,EACxD;AAAA,EACA;AAAA;AAAA,EAEA,YACE,IACA,OACA,QACA,KAAwB,CAAC,UAAa,OACtC;AACA,UAAM,IAAI,OAAO,MAAM;AACvB,SAAK,MAAM;AACX,SAAK,8BAAc,IAAA;AAAA,EACrB;AAAA,EAEA,MAAY;AACV,UAAM,oCAAoB,IAAA;AAG1B,eAAW,WAAW,KAAK,iBAAiB;AAC1C,iBAAW,CAAC,OAAO,IAAI,KAAK,QAAQ,YAAY;AAC9C,cAAM,cAAcC,KAAAA,KAAK,KAAK,IAAI,KAAK,CA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AAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
@@ -12,5 +12,5 @@ export declare class DistinctOperator<T extends KeyValue<any, any>> extends Unar
12
12
  /**
13
13
  * Removes duplicate values
14
14
  */
15
- export declare function distinct<T extends KeyValue<any, any>>(by?: (value: T) => any): (stream: IStreamBuilder<T>) => IStreamBuilder<T>;
15
+ export declare function distinct<T extends KeyValue<any, any>>(by?: (value: T) => any): (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<number, GetValue<T>>>;
16
16
  export {};
@@ -18,7 +18,7 @@ function groupBy(keyExtractor, aggregates = {}) {
18
18
  )
19
19
  );
20
20
  return (stream) => {
21
- const KEY_SENTINEL = `__original_key__`;
21
+ const KEY_SENTINEL = /* @__PURE__ */ Symbol(`original_group_key`);
22
22
  const withKeysAndValues = stream.pipe(
23
23
  map.map((data) => {
24
24
  const key = keyExtractor(data);
@@ -1 +1 @@
1
- {"version":3,"file":"groupBy.cjs","sources":["../../../src/operators/groupBy.ts"],"sourcesContent":["import { serializeValue } from '../utils.js'\nimport { map } from './map.js'\nimport { reduce } from './reduce.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\ntype GroupKey = Record<string, unknown>\n\ntype BasicAggregateFunction<T, R, V = unknown> = {\n preMap: (data: T) => V\n reduce: (values: Array<[V, number]>) => V\n postMap?: (result: V) => R\n}\n\ntype PipedAggregateFunction<T, R> = {\n pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>\n}\n\ntype AggregateFunction<T, R, V = unknown> =\n | BasicAggregateFunction<T, R, V>\n | PipedAggregateFunction<T, R>\n\ntype ExtractAggregateReturnType<T, A> =\n A extends AggregateFunction<T, infer R, any> ? R : never\n\ntype AggregatesReturnType<T, A> = {\n [K in keyof A]: ExtractAggregateReturnType<T, A[K]>\n}\n\nfunction isPipedAggregateFunction<T, R>(\n aggregate: AggregateFunction<T, R>,\n): aggregate is PipedAggregateFunction<T, R> {\n return `pipe` in aggregate\n}\n\n/**\n * Groups data by key and applies multiple aggregate operations\n * @param keyExtractor Function to extract grouping key from data\n * @param aggregates Object mapping aggregate names to aggregate functions\n */\nexport function groupBy<\n T,\n K extends GroupKey,\n A extends Record<string, AggregateFunction<T, any, any>>,\n>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {\n type ResultType = K & AggregatesReturnType<T, A>\n\n const basicAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(\n ([_, aggregate]) => !isPipedAggregateFunction(aggregate),\n ),\n ) as Record<string, BasicAggregateFunction<T, any, any>>\n\n // @ts-expect-error - TODO: we don't use this yet, but we will\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const pipedAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(([_, aggregate]) =>\n isPipedAggregateFunction(aggregate),\n ),\n ) as Record<string, PipedAggregateFunction<T, any>>\n\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<KeyValue<string, ResultType>> => {\n // Special key to store the original key object\n const KEY_SENTINEL = `__original_key__`\n\n // First map to extract keys and pre-aggregate values\n const withKeysAndValues = stream.pipe(\n map((data) => {\n const key = keyExtractor(data)\n const keyString = serializeValue(key)\n\n // Create values object with pre-aggregated values\n const values: Record<string, unknown> = {}\n\n // Store the original key object\n values[KEY_SENTINEL] = key\n\n // Add pre-aggregated values\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n values[name] = aggregate.preMap(data)\n }\n\n return [keyString, values] as KeyValue<string, Record<string, unknown>>\n }),\n )\n\n // Then reduce to compute aggregates\n const reduced = withKeysAndValues.pipe(\n reduce((values) => {\n // Calculate total multiplicity to check if the group should exist\n let totalMultiplicity = 0\n for (const [_, multiplicity] of values) {\n totalMultiplicity += multiplicity\n }\n\n // If total multiplicity is 0 or negative, the group should be removed completely\n if (totalMultiplicity <= 0) {\n return []\n }\n\n const result: Record<string, unknown> = {}\n\n // Get the original key from first value in group\n const originalKey = values[0]?.[0]?.[KEY_SENTINEL]\n result[KEY_SENTINEL] = originalKey\n\n // Apply each aggregate function\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n const preValues = values.map(\n ([v, m]) => [v[name], m] as [any, number],\n )\n result[name] = aggregate.reduce(preValues)\n }\n\n return [[result, 1]]\n }),\n )\n\n // Finally map to extract the key and include all values\n return reduced.pipe(\n map(([keyString, values]) => {\n // Extract the original key\n const key = values[KEY_SENTINEL] as K\n\n // Create intermediate result with key values and aggregate results\n const result: Record<string, unknown> = {}\n\n // Add key properties to result\n Object.assign(result, key)\n\n // Apply postMap if provided\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n if (aggregate.postMap) {\n result[name] = aggregate.postMap(values[name])\n } else {\n result[name] = values[name]\n }\n }\n\n // Return with the string key instead of the object\n return [keyString, result] as KeyValue<string, ResultType>\n }),\n )\n }\n}\n\n/**\n * Creates a sum aggregate function\n */\nexport function sum<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let total = 0\n for (const [value, multiplicity] of values) {\n total += value * multiplicity\n }\n return total\n },\n }\n}\n\n/**\n * Creates a count aggregate function\n */\nexport function count<T>(\n valueExtractor: (value: T) => any = (v) => v,\n): AggregateFunction<T, number, number> {\n return {\n // Count only not-null values (the `== null` comparison gives true for both null and undefined)\n preMap: (data: T) => (valueExtractor(data) == null ? 0 : 1),\n reduce: (values: Array<[number, number]>) => {\n let totalCount = 0\n for (const [nullMultiplier, multiplicity] of values) {\n totalCount += nullMultiplier * multiplicity\n }\n return totalCount\n },\n }\n}\n\n/**\n * Creates an average aggregate function\n */\nexport function avg<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, { sum: number; count: number }> {\n return {\n preMap: (data: T) => ({\n sum: valueExtractor(data),\n count: 0,\n }),\n reduce: (values: Array<[{ sum: number; count: number }, number]>) => {\n let totalSum = 0\n let totalCount = 0\n for (const [value, multiplicity] of values) {\n totalSum += value.sum * multiplicity\n totalCount += multiplicity\n }\n return {\n sum: totalSum,\n count: totalCount,\n }\n },\n postMap: (result: { sum: number; count: number }) => {\n return result.sum / result.count\n },\n }\n}\n\ntype CanMinMax = number | Date | bigint | string\n\n/**\n * Creates a min aggregate function that computes the minimum value in a group\n * @param valueExtractor Function to extract a comparable value from each data entry\n */\nexport function min<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function min<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function min<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let minValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!minValue || (value && value < minValue)) {\n minValue = value\n }\n }\n return minValue\n },\n }\n}\n\n/**\n * Creates a max aggregate function that computes the maximum value in a group\n * @param valueExtractor Function to extract a comparable value from each data entry\n */\nexport function max<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function max<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function max<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let maxValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!maxValue || (value && value > maxValue)) {\n maxValue = value\n }\n }\n return maxValue\n },\n }\n}\n\n/**\n * Creates a median aggregate function that computes the middle value in a sorted group\n * If there's an even number of values, returns the average of the two middle values\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function median<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, Array<number>> {\n return {\n preMap: (data: T) => [valueExtractor(data)],\n reduce: (values: Array<[Array<number>, number]>) => {\n // Flatten all values, taking multiplicity into account\n const allValues: Array<number> = []\n for (const [valueArray, multiplicity] of values) {\n for (const value of valueArray) {\n // Add each value multiple times based on multiplicity\n for (let i = 0; i < multiplicity; i++) {\n allValues.push(value)\n }\n }\n }\n\n // Return empty array if no values\n if (allValues.length === 0) {\n return []\n }\n\n // Sort values\n allValues.sort((a, b) => a - b)\n\n return allValues\n },\n postMap: (result: Array<number>) => {\n if (result.length === 0) return 0\n\n const mid = Math.floor(result.length / 2)\n\n // If even number of values, average the two middle values\n if (result.length % 2 === 0) {\n return (result[mid - 1]! + result[mid]!) / 2\n }\n\n // If odd number of values, return the middle value\n return result[mid]!\n },\n }\n}\n\n/**\n * Creates a mode aggregate function that computes the most frequent value in a group\n * If multiple values have the same highest frequency, returns the first one encountered\n * @param valueExtractor Function to extract a value from each data entry\n */\nexport function mode<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, Map<number, number>> {\n return {\n preMap: (data: T) => {\n const value = valueExtractor(data)\n const frequencyMap = new Map<number, number>()\n frequencyMap.set(value, 1)\n return frequencyMap\n },\n reduce: (values: Array<[Map<number, number>, number]>) => {\n // Combine all frequency maps\n const combinedMap = new Map<number, number>()\n\n for (const [frequencyMap, multiplicity] of values) {\n for (const [value, frequencyCount] of frequencyMap.entries()) {\n const currentCount = combinedMap.get(value) || 0\n combinedMap.set(value, currentCount + frequencyCount * multiplicity)\n }\n }\n\n return combinedMap\n },\n postMap: (result: Map<number, number>) => {\n if (result.size === 0) return 0\n\n let modeValue = 0\n let maxFrequency = 0\n\n for (const [value, frequency] of result.entries()) {\n if (frequency > maxFrequency) {\n maxFrequency = frequency\n modeValue = value\n }\n }\n\n return modeValue\n },\n }\n}\n\nexport const groupByOperators = {\n sum,\n count,\n avg,\n min,\n max,\n median,\n mode,\n}\n"],"names":["map","serializeValue","reduce"],"mappings":";;;;;A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CAAC,OAAO,SAAS,KAAK,OAAO,WAAW;AACjD,YAAI,YAAY,cAAc;AAC5B,yBAAe;AACf,sBAAY;AAAA,QACd;AAAA,MACF;AAEA,aAAO;AAAA,IACT;AAAA,EAAA;AAEJ;AAEO,MAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;;;;;;;;"}
1
+ {"version":3,"file":"groupBy.cjs","sources":["../../../src/operators/groupBy.ts"],"sourcesContent":["import { serializeValue } from '../utils.js'\nimport { map } from './map.js'\nimport { reduce } from './reduce.js'\nimport type { IStreamBuilder, KeyValue } from '../types.js'\n\ntype GroupKey = Record<string, unknown>\n\ntype BasicAggregateFunction<T, R, V = unknown> = {\n preMap: (data: T) => V\n reduce: (values: Array<[V, number]>) => V\n postMap?: (result: V) => R\n}\n\ntype PipedAggregateFunction<T, R> = {\n pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>\n}\n\ntype AggregateFunction<T, R, V = unknown> =\n | BasicAggregateFunction<T, R, V>\n | PipedAggregateFunction<T, R>\n\ntype ExtractAggregateReturnType<T, A> =\n A extends AggregateFunction<T, infer R, any> ? R : never\n\ntype AggregatesReturnType<T, A> = {\n [K in keyof A]: ExtractAggregateReturnType<T, A[K]>\n}\n\nfunction isPipedAggregateFunction<T, R>(\n aggregate: AggregateFunction<T, R>,\n): aggregate is PipedAggregateFunction<T, R> {\n return `pipe` in aggregate\n}\n\n/**\n * Groups data by key and applies multiple aggregate operations\n * @param keyExtractor Function to extract grouping key from data\n * @param aggregates Object mapping aggregate names to aggregate functions\n */\nexport function groupBy<\n T,\n K extends GroupKey,\n A extends Record<string, AggregateFunction<T, any, any>>,\n>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {\n type ResultType = K & AggregatesReturnType<T, A>\n\n const basicAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(\n ([_, aggregate]) => !isPipedAggregateFunction(aggregate),\n ),\n ) as Record<string, BasicAggregateFunction<T, any, any>>\n\n // @ts-expect-error - TODO: we don't use this yet, but we will\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const pipedAggregates = Object.fromEntries(\n Object.entries(aggregates).filter(([_, aggregate]) =>\n isPipedAggregateFunction(aggregate),\n ),\n ) as Record<string, PipedAggregateFunction<T, any>>\n\n return (\n stream: IStreamBuilder<T>,\n ): IStreamBuilder<KeyValue<string, ResultType>> => {\n // Special key to store the original key object\n const KEY_SENTINEL = Symbol(`original_group_key`)\n\n // First map to extract keys and pre-aggregate values\n const withKeysAndValues = stream.pipe(\n map((data) => {\n const key = keyExtractor(data)\n const keyString = serializeValue(key)\n\n // Create values object with pre-aggregated values\n const values: Record<string | symbol, unknown> = {}\n\n // Store the original key object\n values[KEY_SENTINEL] = key\n\n // Add pre-aggregated values\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n values[name] = aggregate.preMap(data)\n }\n\n return [keyString, values] as KeyValue<\n string,\n Record<string | symbol, unknown>\n >\n }),\n )\n\n // Then reduce to compute aggregates\n const reduced = withKeysAndValues.pipe(\n reduce((values) => {\n // Calculate total multiplicity to check if the group should exist\n let totalMultiplicity = 0\n for (const [_, multiplicity] of values) {\n totalMultiplicity += multiplicity\n }\n\n // If total multiplicity is 0 or negative, the group should be removed completely\n if (totalMultiplicity <= 0) {\n return []\n }\n\n const result: Record<PropertyKey, unknown> = {}\n\n // Get the original key from first value in group\n const originalKey = values[0]?.[0]?.[KEY_SENTINEL]\n result[KEY_SENTINEL] = originalKey\n\n // Apply each aggregate function\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n const preValues = values.map(\n ([v, m]) => [v[name], m] as [any, number],\n )\n result[name] = aggregate.reduce(preValues)\n }\n\n return [[result, 1]]\n }),\n )\n\n // Finally map to extract the key and include all values\n return reduced.pipe(\n map(([keyString, values]) => {\n // Extract the original key\n const key = values[KEY_SENTINEL] as K\n\n // Create intermediate result with key values and aggregate results\n const result: Record<string, unknown> = {}\n\n // Add key properties to result\n Object.assign(result, key)\n\n // Apply postMap if provided\n for (const [name, aggregate] of Object.entries(basicAggregates)) {\n if (aggregate.postMap) {\n result[name] = aggregate.postMap(values[name])\n } else {\n result[name] = values[name]\n }\n }\n\n // Return with the string key instead of the object\n return [keyString, result] as KeyValue<string, ResultType>\n }),\n )\n }\n}\n\n/**\n * Creates a sum aggregate function\n */\nexport function sum<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, number> {\n return {\n preMap: (data: T) => valueExtractor(data),\n reduce: (values: Array<[number, number]>) => {\n let total = 0\n for (const [value, multiplicity] of values) {\n total += value * multiplicity\n }\n return total\n },\n }\n}\n\n/**\n * Creates a count aggregate function\n */\nexport function count<T>(\n valueExtractor: (value: T) => any = (v) => v,\n): AggregateFunction<T, number, number> {\n return {\n // Count only not-null values (the `== null` comparison gives true for both null and undefined)\n preMap: (data: T) => (valueExtractor(data) == null ? 0 : 1),\n reduce: (values: Array<[number, number]>) => {\n let totalCount = 0\n for (const [nullMultiplier, multiplicity] of values) {\n totalCount += nullMultiplier * multiplicity\n }\n return totalCount\n },\n }\n}\n\n/**\n * Creates an average aggregate function\n */\nexport function avg<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, { sum: number; count: number }> {\n return {\n preMap: (data: T) => ({\n sum: valueExtractor(data),\n count: 0,\n }),\n reduce: (values: Array<[{ sum: number; count: number }, number]>) => {\n let totalSum = 0\n let totalCount = 0\n for (const [value, multiplicity] of values) {\n totalSum += value.sum * multiplicity\n totalCount += multiplicity\n }\n return {\n sum: totalSum,\n count: totalCount,\n }\n },\n postMap: (result: { sum: number; count: number }) => {\n return result.sum / result.count\n },\n }\n}\n\ntype CanMinMax = number | Date | bigint | string\n\n/**\n * Creates a min aggregate function that computes the minimum value in a group\n * @param valueExtractor Function to extract a comparable value from each data entry\n */\nexport function min<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function min<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function min<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let minValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!minValue || (value && value < minValue)) {\n minValue = value\n }\n }\n return minValue\n },\n }\n}\n\n/**\n * Creates a max aggregate function that computes the maximum value in a group\n * @param valueExtractor Function to extract a comparable value from each data entry\n */\nexport function max<T extends CanMinMax>(): AggregateFunction<\n T,\n T | undefined,\n T | undefined\n>\nexport function max<T, V extends CanMinMax>(\n valueExtractor: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined>\nexport function max<T, V extends CanMinMax>(\n valueExtractor?: (value: T) => V,\n): AggregateFunction<T, V | undefined, V | undefined> {\n const extractor = valueExtractor ?? ((v: T) => v as unknown as V)\n return {\n preMap: (data: T) => extractor(data),\n reduce: (values) => {\n let maxValue: V | undefined\n for (const [value, _multiplicity] of values) {\n if (!maxValue || (value && value > maxValue)) {\n maxValue = value\n }\n }\n return maxValue\n },\n }\n}\n\n/**\n * Creates a median aggregate function that computes the middle value in a sorted group\n * If there's an even number of values, returns the average of the two middle values\n * @param valueExtractor Function to extract a numeric value from each data entry\n */\nexport function median<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, Array<number>> {\n return {\n preMap: (data: T) => [valueExtractor(data)],\n reduce: (values: Array<[Array<number>, number]>) => {\n // Flatten all values, taking multiplicity into account\n const allValues: Array<number> = []\n for (const [valueArray, multiplicity] of values) {\n for (const value of valueArray) {\n // Add each value multiple times based on multiplicity\n for (let i = 0; i < multiplicity; i++) {\n allValues.push(value)\n }\n }\n }\n\n // Return empty array if no values\n if (allValues.length === 0) {\n return []\n }\n\n // Sort values\n allValues.sort((a, b) => a - b)\n\n return allValues\n },\n postMap: (result: Array<number>) => {\n if (result.length === 0) return 0\n\n const mid = Math.floor(result.length / 2)\n\n // If even number of values, average the two middle values\n if (result.length % 2 === 0) {\n return (result[mid - 1]! + result[mid]!) / 2\n }\n\n // If odd number of values, return the middle value\n return result[mid]!\n },\n }\n}\n\n/**\n * Creates a mode aggregate function that computes the most frequent value in a group\n * If multiple values have the same highest frequency, returns the first one encountered\n * @param valueExtractor Function to extract a value from each data entry\n */\nexport function mode<T>(\n valueExtractor: (value: T) => number = (v) => v as unknown as number,\n): AggregateFunction<T, number, Map<number, number>> {\n return {\n preMap: (data: T) => {\n const value = valueExtractor(data)\n const frequencyMap = new Map<number, number>()\n frequencyMap.set(value, 1)\n return frequencyMap\n },\n reduce: (values: Array<[Map<number, number>, number]>) => {\n // Combine all frequency maps\n const combinedMap = new Map<number, number>()\n\n for (const [frequencyMap, multiplicity] of values) {\n for (const [value, frequencyCount] of frequencyMap.entries()) {\n const currentCount = combinedMap.get(value) || 0\n combinedMap.set(value, currentCount + frequencyCount * multiplicity)\n }\n }\n\n return combinedMap\n },\n postMap: (result: Map<number, number>) => {\n if (result.size === 0) return 0\n\n let modeValue = 0\n let maxFrequency = 0\n\n for (const [value, frequency] of result.entries()) {\n if (frequency > maxFrequency) {\n maxFrequency = frequency\n modeValue = value\n }\n }\n\n return modeValue\n },\n }\n}\n\nexport const groupByOperators = {\n sum,\n count,\n avg,\n min,\n max,\n median,\n mode,\n}\n"],"names":["map","serializeValue","reduce"],"mappings":";;;;;AA4BA,SAAS,yBACP,WAC2C;AAC3C,SAAO,UAAU;AACnB;AAOO,SAAS,QAId,cAA8B,aAAgB,IAAS;AAGvD,QAAM,kBAAkB,OAAO;AAAA,IAC7B,OAAO,QAAQ,UAAU,EAAE;AAAA,MACzB,CAAC,CAAC,GAAG,SAAS,MAAM,CAAC,yBAAyB,SAAS;AAAA,IAAA;AAAA,EACzD;AAKsB,SAAO;AAAA,IAC7B,OA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;;;;;"}
@@ -75,11 +75,10 @@ class GroupedTopKWithFractionalIndexOperator extends graph.UnaryOperator {
75
75
  }
76
76
  run() {
77
77
  const result = [];
78
- for (const message of this.inputMessages()) {
79
- for (const [item, multiplicity] of message.getInner()) {
80
- const [key, value] = item;
81
- this.#processElement(key, value, multiplicity, result);
82
- }
78
+ for (const [[key, value], multiplicity] of topKState.topKBatch(
79
+ this.inputMessages()
80
+ )) {
81
+ this.#processElement(key, value, multiplicity, result);
83
82
  }
84
83
  if (result.length > 0) {
85
84
  this.output.sendData(new multiset.MultiSet(result));
@@ -1 +1 @@
1
- {"version":3,"file":"groupedTopKWithFractionalIndex.cjs","sources":["../../../src/operators/groupedTopKWithFractionalIndex.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport { TopKState, handleMoveIn, handleMoveOut } from './topKState.js'\nimport { TopKArray, createKeyedComparator } from './topKArray.js'\nimport type { IndexedValue, TopK } from './topKArray.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\n\nexport interface GroupedTopKWithFractionalIndexOptions<K, T> {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n /**\n * Function to extract a group key from the element's key and value.\n * Elements with the same group key will be sorted and limited together.\n */\n groupKeyFn: (key: K, value: T) => unknown\n}\n\n/**\n * Operator for grouped fractional indexed topK operations.\n * This operator maintains separate topK windows for each group,\n * allowing per-group limits and ordering.\n *\n * The input is a keyed stream [K, T] and outputs [K, IndexedValue<T>].\n * Elements are grouped by the groupKeyFn, and each group maintains\n * its own sorted collection with independent limit/offset.\n */\nexport class GroupedTopKWithFractionalIndexOperator<\n K extends string | number,\n T,\n> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {\n #groupStates: Map<unknown, TopKState<K, T>> = new Map()\n #groupKeyFn: (key: K, value: T) => unknown\n #comparator: (a: [K, T], b: [K, T]) => number\n #offset: number\n #limit: number\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: GroupedTopKWithFractionalIndexOptions<K, T>,\n ) {\n super(id, inputA, output)\n this.#groupKeyFn = options.groupKeyFn\n this.#limit = options.limit ?? Infinity\n this.#offset = options.offset ?? 0\n this.#comparator = createKeyedComparator(comparator)\n options.setSizeCallback?.(() => this.#getTotalSize())\n options.setWindowFn?.(this.#moveTopK.bind(this))\n }\n\n /**\n * Creates a new TopK data structure for a group.\n * Can be overridden in subclasses to use different implementations (e.g., B+ tree).\n */\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: [K, T], b: [K, T]) => number,\n ): TopK<[K, T]> {\n return new TopKArray(offset, limit, comparator)\n }\n\n #getTotalSize(): number {\n let size = 0\n for (const state of this.#groupStates.values()) {\n size += state.size\n }\n return size\n }\n\n #getOrCreateGroupState(groupKey: unknown): TopKState<K, T> {\n let state = this.#groupStates.get(groupKey)\n if (!state) {\n const topK = this.createTopK(this.#offset, this.#limit, this.#comparator)\n state = new TopKState(topK)\n this.#groupStates.set(groupKey, state)\n }\n return state\n }\n\n #cleanupGroupIfEmpty(groupKey: unknown, state: TopKState<K, T>): void {\n if (state.isEmpty) {\n this.#groupStates.delete(groupKey)\n }\n }\n\n /**\n * Moves the topK window for all groups based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n #moveTopK({ offset, limit }: { offset?: number; limit?: number }): void {\n if (offset !== undefined) {\n this.#offset = offset\n }\n if (limit !== undefined) {\n this.#limit = limit\n }\n\n const result: Array<[[K, IndexedValue<T>], number]> = []\n let hasChanges = false\n\n for (const state of this.#groupStates.values()) {\n const diff = state.move({ offset: this.#offset, limit: this.#limit }) // TODO: think we should just pass offset and limit\n\n diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n hasChanges = true\n }\n }\n\n if (hasChanges) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.#processElement(key, value, multiplicity, result)\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n #processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>,\n ): void {\n const groupKey = this.#groupKeyFn(key, value)\n const state = this.#getOrCreateGroupState(groupKey)\n\n const changes = state.processElement(key, value, multiplicity)\n handleMoveIn(changes.moveIn, result)\n handleMoveOut(changes.moveOut, result)\n\n // Cleanup empty groups to prevent memory leaks\n this.#cleanupGroupIfEmpty(groupKey, state)\n }\n}\n\n/**\n * Limits the number of results per group based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * This operator groups elements by the provided groupKeyFn and applies the limit/offset\n * independently to each group.\n *\n * @param comparator - A function that compares two elements for ordering\n * @param options - Configuration including groupKeyFn, limit, and offset\n * @returns A piped operator that orders elements per group and limits results per group\n */\nexport function groupedTopKWithFractionalIndex<K extends string | number, T>(\n comparator: (a: T, b: T) => number,\n options: GroupedTopKWithFractionalIndexOptions<K, T>,\n): PipedOperator<[K, T], [K, IndexedValue<T>]> {\n return (\n stream: IStreamBuilder<[K, T]>,\n ): IStreamBuilder<[K, IndexedValue<T>]> => {\n const output = new StreamBuilder<[K, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[K, IndexedValue<T>]>(),\n )\n const operator = new GroupedTopKWithFractionalIndexOperator<K, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n options,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","createKeyedComparator","TopKArray","TopKState","handleMoveIn","handleMoveOut","MultiSet","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;;AAgCO,MAAM,+CAGHA,MAAAA,cAA4C;AAAA,EACpD,mCAAkD,IAAA;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,IACA,QACA,QACA,YACA,SACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,cAAc,QAAQ;AAC3B,SAAK,SAAS,QAAQ,SAAS;AAC/B,SAAK,UAAU,QAAQ,UAAU;AACjC,SAAK,cAAcC,UAAAA,sBAAsB,UAAU;AACnD,YAAQ,kBAAkB,MAAM,KAAK,cAAA,CAAe;AACpD,YAAQ,cAAc,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,WACR,QACA,OACA,YACc;AACd,WAAO,IAAIC,UAAAA,UAAU,QAAQ,OAAO,UAAU;AAAA,EAChD;AAAA,EAEA,gBAAwB;AACtB,QAAI,OAAO;AACX,eAAW,SAAS,KAAK,aAAa,OAAA,GAAU;AAC9C,cAAQ,MAAM;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AAAA,EAEA,uBAAuB,UAAoC;AACzD,QAAI,QAAQ,KAAK,aAAa,IAAI,QAAQ;AAC1C,QAAI,CAAC,OAAO;AACV,YAAM,OAAO,KAAK,WAAW,KAAK,SAAS,KAAK,QAAQ,KAAK,WAAW;AACxE,cAAQ,IAAIC,UAAAA,UAAU,IAAI;AAC1B,WAAK,aAAa,IAAI,UAAU,KAAK;AAAA,IACvC;AACA,WAAO;AAAA,EACT;AAAA,EAEA,qBAAqB,UAAmB,OAA8B;AACpE,QAAI,MAAM,SAAS;AACjB,WAAK,aAAa,OAAO,QAAQ;AAAA,IACnC;AAAA,EACF;AAAA;AAAA;AAAA;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F;AAeO,SAAS,+BACd,YACA,SAC6C;AAC7C,SAAO,CACL,WACyC;AACzC,UAAM,SAAS,IAAIE,GAAAA;AAAAA,MACjB,OAAO;AAAA,MACP,IAAIC,MAAAA,uBAAA;AAAA,IAA6C;AAEnD,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;;;"}
1
+ {"version":3,"file":"groupedTopKWithFractionalIndex.cjs","sources":["../../../src/operators/groupedTopKWithFractionalIndex.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport {\n TopKState,\n handleMoveIn,\n handleMoveOut,\n topKBatch,\n} from './topKState.js'\nimport { TopKArray, createKeyedComparator } from './topKArray.js'\nimport type { IndexedValue, TopK } from './topKArray.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\n\nexport interface GroupedTopKWithFractionalIndexOptions<K, T> {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n /**\n * Function to extract a group key from the element's key and value.\n * Elements with the same group key will be sorted and limited together.\n */\n groupKeyFn: (key: K, value: T) => unknown\n}\n\n/**\n * Operator for grouped fractional indexed topK operations.\n * This operator maintains separate topK windows for each group,\n * allowing per-group limits and ordering.\n *\n * The input is a keyed stream [K, T] and outputs [K, IndexedValue<T>].\n * Elements are grouped by the groupKeyFn, and each group maintains\n * its own sorted collection with independent limit/offset.\n */\nexport class GroupedTopKWithFractionalIndexOperator<\n K extends string | number,\n T,\n> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {\n #groupStates: Map<unknown, TopKState<K, T>> = new Map()\n #groupKeyFn: (key: K, value: T) => unknown\n #comparator: (a: [K, T], b: [K, T]) => number\n #offset: number\n #limit: number\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: GroupedTopKWithFractionalIndexOptions<K, T>,\n ) {\n super(id, inputA, output)\n this.#groupKeyFn = options.groupKeyFn\n this.#limit = options.limit ?? Infinity\n this.#offset = options.offset ?? 0\n this.#comparator = createKeyedComparator(comparator)\n options.setSizeCallback?.(() => this.#getTotalSize())\n options.setWindowFn?.(this.#moveTopK.bind(this))\n }\n\n /**\n * Creates a new TopK data structure for a group.\n * Can be overridden in subclasses to use different implementations (e.g., B+ tree).\n */\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: [K, T], b: [K, T]) => number,\n ): TopK<[K, T]> {\n return new TopKArray(offset, limit, comparator)\n }\n\n #getTotalSize(): number {\n let size = 0\n for (const state of this.#groupStates.values()) {\n size += state.size\n }\n return size\n }\n\n #getOrCreateGroupState(groupKey: unknown): TopKState<K, T> {\n let state = this.#groupStates.get(groupKey)\n if (!state) {\n const topK = this.createTopK(this.#offset, this.#limit, this.#comparator)\n state = new TopKState(topK)\n this.#groupStates.set(groupKey, state)\n }\n return state\n }\n\n #cleanupGroupIfEmpty(groupKey: unknown, state: TopKState<K, T>): void {\n if (state.isEmpty) {\n this.#groupStates.delete(groupKey)\n }\n }\n\n /**\n * Moves the topK window for all groups based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n #moveTopK({ offset, limit }: { offset?: number; limit?: number }): void {\n if (offset !== undefined) {\n this.#offset = offset\n }\n if (limit !== undefined) {\n this.#limit = limit\n }\n\n const result: Array<[[K, IndexedValue<T>], number]> = []\n let hasChanges = false\n\n for (const state of this.#groupStates.values()) {\n const diff = state.move({ offset: this.#offset, limit: this.#limit }) // TODO: think we should just pass offset and limit\n\n diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n hasChanges = true\n }\n }\n\n if (hasChanges) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const [[key, value], multiplicity] of topKBatch(\n this.inputMessages(),\n )) {\n this.#processElement(key, value, multiplicity, result)\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n #processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>,\n ): void {\n const groupKey = this.#groupKeyFn(key, value)\n const state = this.#getOrCreateGroupState(groupKey)\n\n const changes = state.processElement(key, value, multiplicity)\n handleMoveIn(changes.moveIn, result)\n handleMoveOut(changes.moveOut, result)\n\n // Cleanup empty groups to prevent memory leaks\n this.#cleanupGroupIfEmpty(groupKey, state)\n }\n}\n\n/**\n * Limits the number of results per group based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * This operator groups elements by the provided groupKeyFn and applies the limit/offset\n * independently to each group.\n *\n * @param comparator - A function that compares two elements for ordering\n * @param options - Configuration including groupKeyFn, limit, and offset\n * @returns A piped operator that orders elements per group and limits results per group\n */\nexport function groupedTopKWithFractionalIndex<K extends string | number, T>(\n comparator: (a: T, b: T) => number,\n options: GroupedTopKWithFractionalIndexOptions<K, T>,\n): PipedOperator<[K, T], [K, IndexedValue<T>]> {\n return (\n stream: IStreamBuilder<[K, T]>,\n ): IStreamBuilder<[K, IndexedValue<T>]> => {\n const output = new StreamBuilder<[K, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[K, IndexedValue<T>]>(),\n )\n const operator = new GroupedTopKWithFractionalIndexOperator<K, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n options,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":["UnaryOperator","createKeyedComparator","TopKArray","TopKState","handleMoveIn","handleMoveOut","MultiSet","topKBatch","StreamBuilder","DifferenceStreamWriter"],"mappings":";;;;;;;AAqCO,MAAM,+CAGHA,MAAAA,cAA4C;AAAA,EACpD,mCAAkD,IAAA;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,IACA,QACA,QACA,YACA,SACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,cAAc,QAAQ;AAC3B,SAAK,SAAS,QAAQ,SAAS;AAC/B,SAAK,UAAU,QAAQ,UAAU;AACjC,SAAK,cAAcC,UAAAA,sBAAsB,UAAU;AACnD,YAAQ,kBAAkB,MAAM,KAAK,cAAA,CAAe;AACpD,YAAQ,cAAc,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,WACR,QACA,OACA,YACc;AACd,WAAO,IAAIC,UAAAA,UAAU,QAAQ,OAAO,UAAU;AAAA,EAChD;AAAA,EAEA,gBAAwB;AACtB,QAAI,OAAO;AACX,eAAW,SAAS,KAAK,aAAa,OAAA,GAAU;AAC9C,cAAQ,MAAM;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AAAA,EAEA,uBAAuB,UAAoC;AACzD,QAAI,QAAQ,KAAK,aAAa,IAAI,QAAQ;AAC1C,QAAI,CAAC,OAAO;AACV,YAAM,OAAO,KAAK,WAAW,KAAK,SAAS,KAAK,QAAQ,KAAK,WAAW;AACxE,cAAQ,IAAIC,UAAAA,UAAU,IAAI;AAC1B,WAAK,aAAa,IAAI,UAAU,KAAK;AAAA,IACvC;AACA,WAAO;AAAA,EACT;AAAA,EAEA,qBAAqB,UAAmB,OAA8B;AACpE,QAAI,MAAM,SAAS;AACjB,WAAK,aAAa,OAAO,QAAQ;AAAA,IACnC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AA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