@procedures/collections 0.46.0 → 0.47.2

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 (233) hide show
  1. package/CHANGELOG.md +42 -8
  2. package/README.md +30 -0
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/index.d.ts +1 -58
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +3 -94
  7. package/dist/index.js.map +1 -1
  8. package/dist/storage/index.d.ts +2 -2
  9. package/dist/storage/index.d.ts.map +1 -1
  10. package/dist/storage/index.js +1 -1
  11. package/dist/storage/index.js.map +1 -1
  12. package/dist/storage/memory.d.ts +1 -1
  13. package/dist/storage/memory.d.ts.map +1 -1
  14. package/dist/storage/memory.js +1 -1
  15. package/dist/storage/memory.js.map +1 -1
  16. package/dist/testing/index.d.ts +1 -1
  17. package/dist/testing/index.d.ts.map +1 -1
  18. package/dist/testing/index.js +1 -1
  19. package/dist/testing/index.js.map +1 -1
  20. package/dist/testing/storage-contract.js +1 -1
  21. package/dist/testing/storage-contract.js.map +1 -1
  22. package/dist/undo/index.d.ts +1 -1
  23. package/dist/undo/index.js +1 -1
  24. package/dist/undo/undo-log.d.ts +1 -1
  25. package/dist/undo/undo-log.js +1 -1
  26. package/package.json +6 -6
  27. package/src/index.ts +338 -213
  28. package/src/storage/index.ts +2 -2
  29. package/src/storage/memory.ts +1 -1
  30. package/src/testing/index.ts +1 -1
  31. package/src/testing/storage-contract.ts +1 -1
  32. package/src/undo/index.ts +1 -1
  33. package/src/undo/undo-log.ts +1 -1
  34. package/dist/async/async-queue.d.ts +0 -170
  35. package/dist/async/async-queue.d.ts.map +0 -1
  36. package/dist/async/async-queue.js +0 -404
  37. package/dist/async/async-queue.js.map +0 -1
  38. package/dist/async/channels.d.ts +0 -211
  39. package/dist/async/channels.d.ts.map +0 -1
  40. package/dist/async/channels.js +0 -393
  41. package/dist/async/channels.js.map +0 -1
  42. package/dist/async/settled.d.ts +0 -23
  43. package/dist/async/settled.d.ts.map +0 -1
  44. package/dist/async/settled.js +0 -32
  45. package/dist/async/settled.js.map +0 -1
  46. package/dist/behaviors/bounded.d.ts +0 -79
  47. package/dist/behaviors/bounded.d.ts.map +0 -1
  48. package/dist/behaviors/bounded.js +0 -393
  49. package/dist/behaviors/bounded.js.map +0 -1
  50. package/dist/behaviors/composite.d.ts +0 -17
  51. package/dist/behaviors/composite.d.ts.map +0 -1
  52. package/dist/behaviors/composite.js +0 -93
  53. package/dist/behaviors/composite.js.map +0 -1
  54. package/dist/behaviors/evented.d.ts +0 -154
  55. package/dist/behaviors/evented.d.ts.map +0 -1
  56. package/dist/behaviors/evented.js +0 -299
  57. package/dist/behaviors/evented.js.map +0 -1
  58. package/dist/behaviors/lru.d.ts +0 -84
  59. package/dist/behaviors/lru.d.ts.map +0 -1
  60. package/dist/behaviors/lru.js +0 -376
  61. package/dist/behaviors/lru.js.map +0 -1
  62. package/dist/behaviors/readonly.d.ts +0 -73
  63. package/dist/behaviors/readonly.d.ts.map +0 -1
  64. package/dist/behaviors/readonly.js +0 -189
  65. package/dist/behaviors/readonly.js.map +0 -1
  66. package/dist/behaviors/safe.d.ts +0 -163
  67. package/dist/behaviors/safe.d.ts.map +0 -1
  68. package/dist/behaviors/safe.js +0 -176
  69. package/dist/behaviors/safe.js.map +0 -1
  70. package/dist/behaviors/synchronized.d.ts +0 -88
  71. package/dist/behaviors/synchronized.d.ts.map +0 -1
  72. package/dist/behaviors/synchronized.js +0 -285
  73. package/dist/behaviors/synchronized.js.map +0 -1
  74. package/dist/behaviors/ttl.d.ts +0 -118
  75. package/dist/behaviors/ttl.d.ts.map +0 -1
  76. package/dist/behaviors/ttl.js +0 -354
  77. package/dist/behaviors/ttl.js.map +0 -1
  78. package/dist/contracts/model.d.ts +0 -29
  79. package/dist/contracts/model.d.ts.map +0 -1
  80. package/dist/contracts/model.js +0 -26
  81. package/dist/contracts/model.js.map +0 -1
  82. package/dist/core/effects.d.ts +0 -176
  83. package/dist/core/effects.d.ts.map +0 -1
  84. package/dist/core/effects.js +0 -180
  85. package/dist/core/effects.js.map +0 -1
  86. package/dist/core/events.d.ts +0 -192
  87. package/dist/core/events.d.ts.map +0 -1
  88. package/dist/core/events.js +0 -291
  89. package/dist/core/events.js.map +0 -1
  90. package/dist/core/middleware.d.ts +0 -231
  91. package/dist/core/middleware.d.ts.map +0 -1
  92. package/dist/core/middleware.js +0 -161
  93. package/dist/core/middleware.js.map +0 -1
  94. package/dist/core/policies.d.ts +0 -220
  95. package/dist/core/policies.d.ts.map +0 -1
  96. package/dist/core/policies.js +0 -48
  97. package/dist/core/policies.js.map +0 -1
  98. package/dist/core/traits.d.ts +0 -142
  99. package/dist/core/traits.d.ts.map +0 -1
  100. package/dist/core/traits.js +0 -8
  101. package/dist/core/traits.js.map +0 -1
  102. package/dist/fx/collectors.d.ts +0 -193
  103. package/dist/fx/collectors.d.ts.map +0 -1
  104. package/dist/fx/collectors.js +0 -375
  105. package/dist/fx/collectors.js.map +0 -1
  106. package/dist/fx/iter.d.ts +0 -166
  107. package/dist/fx/iter.d.ts.map +0 -1
  108. package/dist/fx/iter.js +0 -421
  109. package/dist/fx/iter.js.map +0 -1
  110. package/dist/impl/array-deque.d.ts +0 -112
  111. package/dist/impl/array-deque.d.ts.map +0 -1
  112. package/dist/impl/array-deque.js +0 -380
  113. package/dist/impl/array-deque.js.map +0 -1
  114. package/dist/impl/array-list.d.ts +0 -101
  115. package/dist/impl/array-list.d.ts.map +0 -1
  116. package/dist/impl/array-list.js +0 -387
  117. package/dist/impl/array-list.js.map +0 -1
  118. package/dist/impl/hash-map.d.ts +0 -149
  119. package/dist/impl/hash-map.d.ts.map +0 -1
  120. package/dist/impl/hash-map.js +0 -473
  121. package/dist/impl/hash-map.js.map +0 -1
  122. package/dist/impl/hash-set.d.ts +0 -125
  123. package/dist/impl/hash-set.d.ts.map +0 -1
  124. package/dist/impl/hash-set.js +0 -264
  125. package/dist/impl/hash-set.js.map +0 -1
  126. package/dist/impl/linked-hash-map.d.ts +0 -141
  127. package/dist/impl/linked-hash-map.d.ts.map +0 -1
  128. package/dist/impl/linked-hash-map.js +0 -442
  129. package/dist/impl/linked-hash-map.js.map +0 -1
  130. package/dist/impl/linked-list.d.ts +0 -109
  131. package/dist/impl/linked-list.d.ts.map +0 -1
  132. package/dist/impl/linked-list.js +0 -494
  133. package/dist/impl/linked-list.js.map +0 -1
  134. package/dist/impl/priority-queue.d.ts +0 -139
  135. package/dist/impl/priority-queue.d.ts.map +0 -1
  136. package/dist/impl/priority-queue.js +0 -343
  137. package/dist/impl/priority-queue.js.map +0 -1
  138. package/dist/impl/tree-map.d.ts +0 -153
  139. package/dist/impl/tree-map.d.ts.map +0 -1
  140. package/dist/impl/tree-map.js +0 -788
  141. package/dist/impl/tree-map.js.map +0 -1
  142. package/dist/impl/tree-set.d.ts +0 -112
  143. package/dist/impl/tree-set.d.ts.map +0 -1
  144. package/dist/impl/tree-set.js +0 -374
  145. package/dist/impl/tree-set.js.map +0 -1
  146. package/dist/interfaces/collection.d.ts +0 -119
  147. package/dist/interfaces/collection.d.ts.map +0 -1
  148. package/dist/interfaces/collection.js +0 -8
  149. package/dist/interfaces/collection.js.map +0 -1
  150. package/dist/interfaces/list.d.ts +0 -247
  151. package/dist/interfaces/list.d.ts.map +0 -1
  152. package/dist/interfaces/list.js +0 -8
  153. package/dist/interfaces/list.js.map +0 -1
  154. package/dist/interfaces/map.d.ts +0 -344
  155. package/dist/interfaces/map.d.ts.map +0 -1
  156. package/dist/interfaces/map.js +0 -8
  157. package/dist/interfaces/map.js.map +0 -1
  158. package/dist/interfaces/queue.d.ts +0 -304
  159. package/dist/interfaces/queue.d.ts.map +0 -1
  160. package/dist/interfaces/queue.js +0 -8
  161. package/dist/interfaces/queue.js.map +0 -1
  162. package/dist/interfaces/set.d.ts +0 -137
  163. package/dist/interfaces/set.d.ts.map +0 -1
  164. package/dist/interfaces/set.js +0 -8
  165. package/dist/interfaces/set.js.map +0 -1
  166. package/dist/order/index.d.ts +0 -7
  167. package/dist/order/index.d.ts.map +0 -1
  168. package/dist/order/index.js +0 -7
  169. package/dist/order/index.js.map +0 -1
  170. package/dist/order/rank.d.ts +0 -100
  171. package/dist/order/rank.d.ts.map +0 -1
  172. package/dist/order/rank.js +0 -286
  173. package/dist/order/rank.js.map +0 -1
  174. package/dist/storage/listeners.d.ts +0 -39
  175. package/dist/storage/listeners.d.ts.map +0 -1
  176. package/dist/storage/listeners.js +0 -65
  177. package/dist/storage/listeners.js.map +0 -1
  178. package/dist/testing/check.d.ts +0 -25
  179. package/dist/testing/check.d.ts.map +0 -1
  180. package/dist/testing/check.js +0 -85
  181. package/dist/testing/check.js.map +0 -1
  182. package/dist/utils/defaults.d.ts +0 -135
  183. package/dist/utils/defaults.d.ts.map +0 -1
  184. package/dist/utils/defaults.js +0 -322
  185. package/dist/utils/defaults.js.map +0 -1
  186. package/dist/utils/factories.d.ts +0 -144
  187. package/dist/utils/factories.d.ts.map +0 -1
  188. package/dist/utils/factories.js +0 -293
  189. package/dist/utils/factories.js.map +0 -1
  190. package/dist/utils/helpers.d.ts +0 -137
  191. package/dist/utils/helpers.d.ts.map +0 -1
  192. package/dist/utils/helpers.js +0 -221
  193. package/dist/utils/helpers.js.map +0 -1
  194. package/src/async/async-queue.ts +0 -481
  195. package/src/async/channels.ts +0 -450
  196. package/src/async/settled.ts +0 -41
  197. package/src/behaviors/bounded.ts +0 -485
  198. package/src/behaviors/composite.ts +0 -99
  199. package/src/behaviors/evented.ts +0 -464
  200. package/src/behaviors/lru.ts +0 -447
  201. package/src/behaviors/readonly.ts +0 -236
  202. package/src/behaviors/safe.ts +0 -372
  203. package/src/behaviors/synchronized.ts +0 -316
  204. package/src/behaviors/ttl.ts +0 -462
  205. package/src/contracts/model.ts +0 -44
  206. package/src/core/effects.ts +0 -323
  207. package/src/core/events.ts +0 -356
  208. package/src/core/middleware.ts +0 -415
  209. package/src/core/policies.ts +0 -316
  210. package/src/core/traits.ts +0 -164
  211. package/src/fx/collectors.ts +0 -500
  212. package/src/fx/iter.ts +0 -536
  213. package/src/impl/array-deque.ts +0 -463
  214. package/src/impl/array-list.ts +0 -490
  215. package/src/impl/hash-map.ts +0 -623
  216. package/src/impl/hash-set.ts +0 -342
  217. package/src/impl/linked-hash-map.ts +0 -572
  218. package/src/impl/linked-list.ts +0 -606
  219. package/src/impl/priority-queue.ts +0 -448
  220. package/src/impl/tree-map.ts +0 -912
  221. package/src/impl/tree-set.ts +0 -469
  222. package/src/interfaces/collection.ts +0 -141
  223. package/src/interfaces/list.ts +0 -281
  224. package/src/interfaces/map.ts +0 -405
  225. package/src/interfaces/queue.ts +0 -353
  226. package/src/interfaces/set.ts +0 -158
  227. package/src/order/index.ts +0 -6
  228. package/src/order/rank.ts +0 -271
  229. package/src/storage/listeners.ts +0 -72
  230. package/src/testing/check.ts +0 -81
  231. package/src/utils/defaults.ts +0 -345
  232. package/src/utils/factories.ts +0 -357
  233. package/src/utils/helpers.ts +0 -248
package/src/order/rank.ts DELETED
@@ -1,271 +0,0 @@
1
- /**
2
- * The keys of an ordered list (Graph's split, wave 2, W1): fractional indexing with base-62 keys. A
3
- * key is a string. Each item of the list keeps one, and the list sorts by it. An item that moves
4
- * between two others gets a key between theirs, so a move writes one item and no other.
5
- *
6
- * - A key has an integer part and a fraction part. The first character of the integer part gives its
7
- * length. An insertion at an end changes the integer part, so the keys stay short. An insertion
8
- * between two keys uses the fraction part, which can grow without a limit: the keys never run out,
9
- * and the list needs no rebalance.
10
- * - Compare two keys by the code units of the strings (`a < b`), never with `localeCompare`.
11
- * - Two writers that move items into the same gap at the same time can get the same key. Sort by the
12
- * key, then by the id of the item, so each reader sees one order.
13
- *
14
- * The algorithm is the one of the `fractional-indexing` package of Rocicorp (CC0), after the article
15
- * "Implementing Fractional Indexing" of David Greenspan.
16
- */
17
-
18
- /** The digits of a key, in ascending order of their code units. */
19
- export const KEY_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
20
-
21
- const ZERO = KEY_DIGITS[0]!;
22
- const LAST = KEY_DIGITS[KEY_DIGITS.length - 1]!;
23
- /** The smallest integer part. No key comes before it. */
24
- const SMALLEST_INTEGER = `A${ZERO.repeat(26)}`;
25
-
26
- function invalid(message: string): RangeError {
27
- return new RangeError(message);
28
- }
29
-
30
- /** The length of the integer part that starts with a head character: a to z give 2 to 27, Z to A give 2 to 27. */
31
- function integerLength(head: string): number {
32
- if (head >= "a" && head <= "z") return head.charCodeAt(0) - "a".charCodeAt(0) + 2;
33
- if (head >= "A" && head <= "Z") return "Z".charCodeAt(0) - head.charCodeAt(0) + 2;
34
- throw invalid(`A key cannot start with "${head}"`);
35
- }
36
-
37
- function integerPart(key: string): string {
38
- const length = integerLength(key[0] ?? "");
39
- if (length > key.length) throw invalid(`The key "${key}" is too short for its integer part`);
40
- return key.slice(0, length);
41
- }
42
-
43
- function validateKey(key: string): void {
44
- if (typeof key !== "string" || key === "") throw invalid("A key is a string that is not empty");
45
- for (const c of key) if (!KEY_DIGITS.includes(c)) throw invalid(`The key "${key}" has a character that is no digit of a key`);
46
- if (key === SMALLEST_INTEGER) throw invalid(`The key "${key}" is reserved`);
47
- const fraction = key.slice(integerPart(key).length);
48
- if (fraction.endsWith(ZERO)) throw invalid(`The fraction part of the key "${key}" ends with ${ZERO}`);
49
- }
50
-
51
- /** A fraction strictly between two fractions. `b` null is the end. Neither one ends with the zero digit. */
52
- function midpoint(a: string, b: string | null): string {
53
- if (b !== null) {
54
- let n = 0;
55
- while ((a[n] ?? ZERO) === b[n]) n++;
56
- if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
57
- }
58
- const digitA = a ? KEY_DIGITS.indexOf(a[0]!) : 0;
59
- const digitB = b !== null ? KEY_DIGITS.indexOf(b[0]!) : KEY_DIGITS.length;
60
- if (digitB - digitA > 1) return KEY_DIGITS[Math.round((digitA + digitB) / 2)]!;
61
- // The first digits are next to each other
62
- if (b !== null && b.length > 1) return b.slice(0, 1);
63
- return KEY_DIGITS[digitA]! + midpoint(a.slice(1), null);
64
- }
65
-
66
- function incrementInteger(x: string): string | null {
67
- const [head, ...digits] = x.split("") as [string, ...string[]];
68
- let carry = true;
69
- for (let i = digits.length - 1; carry && i >= 0; i--) {
70
- const d = KEY_DIGITS.indexOf(digits[i]!) + 1;
71
- if (d === KEY_DIGITS.length) digits[i] = ZERO;
72
- else {
73
- digits[i] = KEY_DIGITS[d]!;
74
- carry = false;
75
- }
76
- }
77
- if (!carry) return head + digits.join("");
78
- if (head === "Z") return `a${ZERO}`;
79
- if (head === "z") return null;
80
- const next = String.fromCharCode(head.charCodeAt(0) + 1);
81
- if (next > "a") digits.push(ZERO);
82
- else digits.pop();
83
- return next + digits.join("");
84
- }
85
-
86
- function decrementInteger(x: string): string | null {
87
- const [head, ...digits] = x.split("") as [string, ...string[]];
88
- let borrow = true;
89
- for (let i = digits.length - 1; borrow && i >= 0; i--) {
90
- const d = KEY_DIGITS.indexOf(digits[i]!) - 1;
91
- if (d === -1) digits[i] = LAST;
92
- else {
93
- digits[i] = KEY_DIGITS[d]!;
94
- borrow = false;
95
- }
96
- }
97
- if (!borrow) return head + digits.join("");
98
- if (head === "a") return `Z${LAST}`;
99
- if (head === "A") return null;
100
- const next = String.fromCharCode(head.charCodeAt(0) - 1);
101
- if (next < "Z") digits.push(LAST);
102
- else digits.pop();
103
- return next + digits.join("");
104
- }
105
-
106
- /**
107
- * This function gives a key strictly between two keys. Without `prev`, the key comes before `next`.
108
- * Without `next`, it comes after `prev`. Without both, it gives the first key of a list ("a0").
109
- *
110
- * @throws RangeError when a key is not valid, or when `prev` is not before `next`
111
- *
112
- * @example
113
- * ```ts
114
- * keyBetween(undefined, undefined); // "a0"
115
- * keyBetween("a0", undefined); // "a1", after a0
116
- * keyBetween("a0", "a1"); // "a0V"
117
- * ```
118
- */
119
- export function keyBetween(prev: string | null | undefined, next: string | null | undefined): string {
120
- const a = prev ?? null;
121
- const b = next ?? null;
122
- if (a !== null) validateKey(a);
123
- if (b !== null) validateKey(b);
124
- if (a !== null && b !== null && a >= b) throw invalid(`The key "${a}" is not before the key "${b}"`);
125
- if (a === null) {
126
- if (b === null) return `a${ZERO}`;
127
- const ib = integerPart(b);
128
- const fb = b.slice(ib.length);
129
- if (ib === SMALLEST_INTEGER) return ib + midpoint("", fb);
130
- if (ib < b) return ib;
131
- const decremented = decrementInteger(ib);
132
- if (decremented === null) throw invalid("No key comes before this one");
133
- return decremented;
134
- }
135
- const ia = integerPart(a);
136
- const fa = a.slice(ia.length);
137
- if (b === null) {
138
- const incremented = incrementInteger(ia);
139
- return incremented === null ? ia + midpoint(fa, null) : incremented;
140
- }
141
- const ib = integerPart(b);
142
- const fb = b.slice(ib.length);
143
- if (ia === ib) return ia + midpoint(fa, fb);
144
- const incremented = incrementInteger(ia);
145
- if (incremented === null) throw invalid("No key comes after this one");
146
- if (incremented < b) return incremented;
147
- return ia + midpoint(fa, null);
148
- }
149
-
150
- /**
151
- * This function gives `count` keys in ascending order, strictly between two keys, for example to put
152
- * several items at one place, or to give keys to the items of a list for the first time.
153
- *
154
- * @throws RangeError as `keyBetween`, or when `count` is not an integer of 0 or more
155
- */
156
- export function keysBetween(prev: string | null | undefined, next: string | null | undefined, count: number): string[] {
157
- if (!Number.isInteger(count) || count < 0) throw invalid(`A count of keys is an integer of 0 or more, not ${count}`);
158
- const a = prev ?? null;
159
- const b = next ?? null;
160
- if (count === 0) return [];
161
- if (count === 1) return [keyBetween(a, b)];
162
- if (b === null) {
163
- const keys = [keyBetween(a, null)];
164
- for (let i = 1; i < count; i++) keys.push(keyBetween(keys[i - 1]!, null));
165
- return keys;
166
- }
167
- if (a === null) {
168
- const keys = [keyBetween(null, b)];
169
- for (let i = 1; i < count; i++) keys.push(keyBetween(null, keys[i - 1]!));
170
- return keys.reverse();
171
- }
172
- const half = Math.floor(count / 2);
173
- const middle = keyBetween(a, b);
174
- return [...keysBetween(a, middle, half), middle, ...keysBetween(middle, b, count - half - 1)];
175
- }
176
-
177
- /** The options of `isValidKey`. */
178
- export interface KeyCheckOptions {
179
- /** The longest key that the check accepts. The default is 1024 characters. */
180
- readonly maxLength?: number;
181
- }
182
-
183
- /**
184
- * This function tells if a value is a valid key, for example a key that a client writes. A key that
185
- * is longer than `maxLength` is not valid.
186
- */
187
- export function isValidKey(key: unknown, options: KeyCheckOptions = {}): key is string {
188
- if (typeof key !== "string" || key.length > (options.maxLength ?? 1024)) return false;
189
- try {
190
- validateKey(key);
191
- return true;
192
- } catch {
193
- return false;
194
- }
195
- }
196
-
197
- /** An item of an ordered list: its id and its key. */
198
- export interface KeyedItem {
199
- readonly id: string;
200
- readonly key: string;
201
- }
202
-
203
- /**
204
- * This function gives the writes of a move: the new key of the item that moves, and new keys for the
205
- * neighbors that need them. Give the other items of the list in order (by key, then by id), without
206
- * the item that moves, and the index of the drop from 0 to their number (`dropIndex`).
207
- *
208
- * Two writers can give two items one key. A drop between two such items has no key between them, so
209
- * the helper first gives new keys to the items after the drop that have the key of the item before
210
- * it. Each write is `{ id, key }`. The writes of the neighbors come first, and the write of the item
211
- * that moves comes last.
212
- *
213
- * @throws RangeError when the index is outside the list, when the list holds the item that moves, or
214
- * when a key is not valid
215
- *
216
- * @example
217
- * ```ts
218
- * const index = dropIndex(pointer, others.map(centerOf));
219
- * for (const { id, key } of keysForDrop(others, index, dragged.id)) await save(id, { rank: key });
220
- * ```
221
- */
222
- export function keysForDrop(items: readonly KeyedItem[], index: number, movingId: string): Array<{ id: string; key: string }> {
223
- if (!Number.isInteger(index) || index < 0 || index > items.length) throw invalid(`The index ${index} is outside the list of ${items.length} items`);
224
- if (items.some((item) => item.id === movingId)) throw invalid(`The list holds the item that moves (${movingId})`);
225
- const prev = items[index - 1]?.key ?? null;
226
- // The items from the index on that do not come after the item before the drop need new keys
227
- let end = index;
228
- while (end < items.length && prev !== null && items[end]!.key <= prev) end++;
229
- const writes: Array<{ id: string; key: string }> = [];
230
- if (end > index) {
231
- const keys = keysBetween(prev, items[end]?.key ?? null, end - index);
232
- for (let i = index; i < end; i++) writes.push({ id: items[i]!.id, key: keys[i - index]! });
233
- }
234
- const next = writes.length > 0 ? writes[0]!.key : (items[index]?.key ?? null);
235
- writes.push({ id: movingId, key: keyBetween(prev, next) });
236
- return writes;
237
- }
238
-
239
- /** The order of two keys: the code units of the strings, as the keys need (never `localeCompare`). */
240
- export function compareKeys(a: string, b: string): number {
241
- return a < b ? -1 : a > b ? 1 : 0;
242
- }
243
-
244
- /** A point, for example the center of an item on the screen. */
245
- export interface Point {
246
- readonly x: number;
247
- readonly y: number;
248
- }
249
-
250
- /**
251
- * This function gives the index at which a point goes among the items of a list on the screen, in
252
- * reading order: the rows from top to bottom, and each row from left to right. It is the index of the
253
- * first item whose center comes after the point, from 0 to the number of items. A center within
254
- * `rowTolerance` of the point on the vertical axis is in the row of the point.
255
- *
256
- * Give the centers in reading order, the same order as the keys, and without the item that moves.
257
- *
258
- * @example
259
- * ```ts
260
- * const index = dropIndex(pointer, others.map(centerOf));
261
- * const key = keyBetween(keys[index - 1], keys[index]);
262
- * ```
263
- */
264
- export function dropIndex(point: Point, centers: readonly Point[], rowTolerance = 24): number {
265
- for (let i = 0; i < centers.length; i++) {
266
- const c = centers[i]!;
267
- if (point.y < c.y - rowTolerance) return i;
268
- if (Math.abs(point.y - c.y) <= rowTolerance && point.x < c.x) return i;
269
- }
270
- return centers.length;
271
- }
@@ -1,72 +0,0 @@
1
- /**
2
- * A set of listeners for the events of a storage: the change batches of `observe()`, or the status
3
- * of a sync. A storage package uses it, so each storage treats its listeners in the same way.
4
- */
5
-
6
- /** The function that gets the error of a listener. */
7
- export type ListenerErrorHandler = (error: unknown) => void;
8
-
9
- /**
10
- * The default handler of the error of a listener. It throws the error again in a microtask, as an
11
- * `EventTarget` reports the error of a listener. Thus the error is not lost, and the write that
12
- * sent the event does not fail.
13
- */
14
- export const reportListenerError: ListenerErrorHandler = (error) => {
15
- queueMicrotask(() => {
16
- throw error;
17
- });
18
- };
19
-
20
- /**
21
- * The listeners of one kind of event.
22
- *
23
- * - `emit()` gives the event to each listener, in the order of `add()`.
24
- * - A listener that `add()` gets during an `emit()` gets the next event, not this one.
25
- * - The error of a listener goes to the error handler. The other listeners get the event.
26
- * - The same function can be added two times. Each `add()` gives its own function that removes it.
27
- */
28
- export class StorageListeners<E> {
29
- private readonly listeners = new Set<{ readonly listener: (event: E) => void }>();
30
- private readonly onError: ListenerErrorHandler;
31
-
32
- /** @param onError - The function that gets the error of a listener. The default is `reportListenerError`. */
33
- constructor(onError: ListenerErrorHandler = reportListenerError) {
34
- this.onError = onError;
35
- }
36
-
37
- /** The number of listeners. */
38
- get size(): number {
39
- return this.listeners.size;
40
- }
41
-
42
- /**
43
- * This method adds a listener.
44
- *
45
- * @returns The function that removes the listener. A second use of it does nothing.
46
- */
47
- add(listener: (event: E) => void): () => void {
48
- const entry = { listener };
49
- this.listeners.add(entry);
50
- return () => {
51
- this.listeners.delete(entry);
52
- };
53
- }
54
-
55
- /** This method gives the event to each listener. */
56
- emit(event: E): void {
57
- for (const entry of [...this.listeners]) {
58
- // A listener that a listener before it removed gets no event
59
- if (!this.listeners.has(entry)) continue;
60
- try {
61
- entry.listener(event);
62
- } catch (error) {
63
- this.onError(error);
64
- }
65
- }
66
- }
67
-
68
- /** This method removes each listener. */
69
- clear(): void {
70
- this.listeners.clear();
71
- }
72
- }
@@ -1,81 +0,0 @@
1
- /**
2
- * The checks of the contract suite. The suite does not import a test framework, so a runtime
3
- * entry of this package never loads one. A failed check throws `ContractViolation`.
4
- */
5
-
6
- /** The error of a failed check of the contract suite. */
7
- export class ContractViolation extends Error {
8
- override readonly name = "ContractViolation";
9
- }
10
-
11
- /** This function gives the text of a value for a message: JSON, with a `Map` as its entries. */
12
- export function show(value: unknown): string {
13
- if (value === undefined) return "undefined";
14
- try {
15
- return JSON.stringify(value, (_key, item: unknown) => (item instanceof Map ? { Map: [...item.entries()] } : item === undefined ? "<undefined>" : item));
16
- } catch {
17
- return String(value);
18
- }
19
- }
20
-
21
- function isPlainObject(value: unknown): value is Record<string, unknown> {
22
- if (typeof value !== "object" || value === null) return false;
23
- const prototype = Object.getPrototypeOf(value) as unknown;
24
- return prototype === Object.prototype || prototype === null;
25
- }
26
-
27
- /**
28
- * This function compares two values deeply: JSON values, arrays, plain objects and maps. Two maps
29
- * are equal when they have the same keys with equal values, in any order.
30
- */
31
- export function deepEqual(actual: unknown, expected: unknown): boolean {
32
- if (Object.is(actual, expected)) return true;
33
- if (actual instanceof Map && expected instanceof Map) {
34
- if (actual.size !== expected.size) return false;
35
- for (const [key, value] of actual) {
36
- if (!expected.has(key) || !deepEqual(value, expected.get(key))) return false;
37
- }
38
- return true;
39
- }
40
- if (Array.isArray(actual) && Array.isArray(expected)) {
41
- return actual.length === expected.length && actual.every((item, index) => deepEqual(item, expected[index]));
42
- }
43
- if (isPlainObject(actual) && isPlainObject(expected)) {
44
- const keys = Object.keys(actual);
45
- if (keys.length !== Object.keys(expected).length) return false;
46
- return keys.every((key) => Object.prototype.hasOwnProperty.call(expected, key) && deepEqual(actual[key], expected[key]));
47
- }
48
- return false;
49
- }
50
-
51
- /** This function throws `ContractViolation` when the two values are not deeply equal. */
52
- export function same(actual: unknown, expected: unknown, what: string): void {
53
- if (!deepEqual(actual, expected)) {
54
- throw new ContractViolation(`${what}: expected ${show(expected)}, got ${show(actual)}`);
55
- }
56
- }
57
-
58
- /** This function throws `ContractViolation` when the condition is false. */
59
- export function holds(condition: boolean, what: string): void {
60
- if (!condition) throw new ContractViolation(what);
61
- }
62
-
63
- /**
64
- * This function starts an operation that must fail with a rejected promise, and gives the error.
65
- * A synchronous throw breaks the contract too: each method of a storage gives a promise.
66
- */
67
- export async function rejects(start: () => Promise<unknown>, what: string): Promise<unknown> {
68
- let promise: Promise<unknown>;
69
- try {
70
- promise = start();
71
- } catch (error) {
72
- throw new ContractViolation(`${what}: the method threw at once (${show(error instanceof Error ? error.message : error)}), and did not give a rejected promise`);
73
- }
74
- holds(typeof promise?.then === "function", `${what}: the method did not give a promise`);
75
- try {
76
- await promise;
77
- } catch (error) {
78
- return error;
79
- }
80
- throw new ContractViolation(`${what}: the promise did not reject`);
81
- }