@esportsplus/reactivity 0.40.0 → 0.42.0

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 (61) hide show
  1. package/README.md +16 -10
  2. package/bench/compiler.bench.ts +122 -0
  3. package/bench/kairo.bench.ts +1 -1
  4. package/bench/lib/reactive-adapter.ts +1 -1
  5. package/bench/ownership.bench.ts +9 -5
  6. package/bench/reactive/array.bench.ts +7 -2
  7. package/bench/reactive/reactive-object.bench.ts +3 -2
  8. package/bench/system.bench.ts +9 -5
  9. package/build/compiler/array.js +28 -25
  10. package/build/compiler/bindings.d.ts +3 -1
  11. package/build/compiler/bindings.js +36 -18
  12. package/build/compiler/index.d.ts +3 -2
  13. package/build/compiler/index.js +21 -13
  14. package/build/compiler/object.js +30 -21
  15. package/build/compiler/plugins/vite.d.ts +29 -6
  16. package/build/compiler/primitives.js +9 -9
  17. package/build/constants.d.ts +3 -1
  18. package/build/constants.js +3 -1
  19. package/build/reactive/array.js +89 -17
  20. package/build/reactive/index.d.ts +1 -1
  21. package/build/reactive/object.d.ts +3 -3
  22. package/build/reactive/object.js +1 -1
  23. package/build/system.d.ts +4 -3
  24. package/build/system.js +48 -16
  25. package/oxlintrc.json +3 -0
  26. package/package.json +15 -7
  27. package/pnpm-workspace.yaml +4 -7
  28. package/src/compiler/array.ts +30 -27
  29. package/src/compiler/bindings.ts +52 -23
  30. package/src/compiler/index.ts +37 -20
  31. package/src/compiler/object.ts +43 -30
  32. package/src/compiler/primitives.ts +13 -10
  33. package/src/constants.ts +6 -1
  34. package/src/reactive/array.ts +133 -24
  35. package/src/reactive/index.ts +3 -3
  36. package/src/reactive/object.ts +4 -4
  37. package/src/system.ts +68 -23
  38. package/test/async-hardening.test.ts +2 -2
  39. package/test/async-iterable.test.ts +3 -3
  40. package/test/compiler/__snapshots__/output.test.ts.snap +157 -0
  41. package/test/compiler/compiler.test.ts +51 -9
  42. package/test/compiler/composition.test.ts +110 -0
  43. package/test/compiler/coverage.test.ts +22 -22
  44. package/test/compiler/origins.test.ts +156 -0
  45. package/test/compiler/output.test.ts +116 -0
  46. package/test/deep-graphs.test.ts +6 -6
  47. package/test/effects.test.ts +5 -5
  48. package/test/errors.test.ts +4 -4
  49. package/test/invalidate.test.ts +2 -2
  50. package/test/ownership.test.ts +30 -30
  51. package/test/pause.test.ts +267 -0
  52. package/test/reactive/array.test.ts +13 -12
  53. package/test/reactive/reactive.test.ts +6 -6
  54. package/test/signal-selector.test.ts +4 -4
  55. package/test/system.test.ts +13 -13
  56. package/test/untrack.test.ts +10 -10
  57. package/tsconfig.build.json +3 -0
  58. package/tsconfig.json +2 -2
  59. package/vitest.config.ts +2 -2
  60. package/bench/tsconfig.json +0 -16
  61. package/test/tsconfig.json +0 -16
package/README.md CHANGED
@@ -112,18 +112,18 @@ state.userId = 2;
112
112
  ### Effects
113
113
 
114
114
  ```typescript
115
- import { effect, reactive } from '@esportsplus/reactivity';
115
+ import { dispose, effect, reactive } from '@esportsplus/reactivity';
116
116
 
117
117
  let count = reactive(0);
118
118
 
119
- let cleanup = effect(() => {
119
+ let node = effect(() => {
120
120
  console.log('Count is:', count);
121
121
  });
122
122
 
123
123
  count = 1; // logs: Count is: 1
124
124
  count = 2; // logs: Count is: 2
125
125
 
126
- cleanup(); // stops the effect
126
+ dispose(node); // stops the effect
127
127
  ```
128
128
 
129
129
  ## Transformer Plugins
@@ -221,7 +221,7 @@ let user = new ReactiveObject_1();
221
221
  | `reactive(() => expr)` | Creates a computed value (compile-time only) |
222
222
  | `reactive({...})` | Creates a reactive object with signals and computeds |
223
223
  | `reactive([...])` | Creates a reactive array |
224
- | `effect(fn, apply?)` | Runs a function that re-executes when dependencies change. Returns a dispose function. Optional `apply(value, prev)` runs untracked after each run with `fn`'s return value |
224
+ | `effect(fn, apply?)` | Runs a function that re-executes when dependencies change. Returns the effect's node (`Computed<T>`); stop it with `dispose(node)`. Optional `apply(value, prev)` runs untracked after each run with `fn`'s return value |
225
225
  | `root(fn, owner?)` | Creates an untracked scope. If `fn` accepts an argument, a dispose function is provided. With `owner`, the scope belongs to that node instead of whatever is running: `root(() => …, owner)` runs `fn` owned by `owner` (to re-enter it after an `await`), `root((dispose) => …, owner)` creates a child root of `owner`. Reads stay untracked. Throws on a disposed owner |
226
226
  | `owner()` | The node that owns what is created now: the running effect/computed, else the running root's scope, else `null`. Its `.owner` chain reaches every enclosing owner |
227
227
  | `onCleanup(fn)` | Registers a cleanup function for the current effect/computed |
@@ -240,7 +240,9 @@ These operate directly on signal/computed nodes — the transformer emits them,
240
240
  | `untrack(fn)` | Runs `fn` without tracking dependencies; returns `fn`'s result. Ownership is unchanged: effects, computeds, child roots and `onCleanup` created inside are owned by the running effect/computed (or the enclosing `root((dispose) => …)`) and torn down on its next re-run or dispose. Use a zero-arg `root(() => …)` for deliberately detached work |
241
241
  | `batch(fn)` | Groups writes so dependent effects defer until `fn` returns; pair with `flush()` for a synchronous transaction |
242
242
  | `flush()` | Synchronously settles all pending computed/effect updates |
243
- | `dispose(computed)` | Disposes a computed and its dependencies |
243
+ | `dispose(node)` | Disposes a computed or effect node and its dependencies |
244
+ | `pause(effect)` | Stops an effect from running: a change that reaches it marks it stale instead. Called from inside the effect's own run, it abandons that run and keeps the dependencies the run had not read. Throws for a computed; a no-op on a disposed effect |
245
+ | `resume(effect)` | Lets a paused effect run again. If a change reached it while paused it runs once (on the next microtask, or now with `flush()`); otherwise nothing runs. Throws for a computed; a no-op on a disposed effect |
244
246
  | `computed.invalidate(computed)` | Forces re-derivation of a computed on next read (re-dispatches an async computed's promise for a refetch) |
245
247
  | `signal.selector(signal, key)` | Per-key selector: within a tracking scope, subscribes to whether `signal`'s value equals `key`, so only key-matching observers re-run on write (O(1) fan-out) |
246
248
 
@@ -332,13 +334,17 @@ All standard array methods (`push`, `pop`, `shift`, `unshift`, `splice`, `sort`,
332
334
 
333
335
  ```bash
334
336
  pnpm install
335
- pnpm build # tsc
336
- pnpm test # vitest run
337
- pnpm bench # vitest bench --run
337
+ pnpm build # tsc -p tsconfig.build.json
338
+ pnpm typecheck # tsc --noEmit over src, test and bench
339
+ pnpm lint # oxlint, type-aware, warnings denied
340
+ pnpm test # vitest run
341
+ pnpm bench # vitest bench --run (add --reporter=verbose to print results when piped)
342
+ pnpm verify # build, typecheck, lint and test
338
343
  ```
339
344
 
340
- `agent:test` (`tsc --noEmit && vitest run`) and `agent:bench` (`vitest bench --run`) are the
341
- CI-facing aliases of the same build/test/bench commands.
345
+ `agent:test` (`pnpm typecheck && vitest run`) and `agent:bench` (`vitest bench --run`) are the
346
+ CI-facing aliases of the same test/bench commands. `test/compiler/output.test.ts` pins whole
347
+ compiled modules; a compiler change that alters them must update the snapshot deliberately.
342
348
 
343
349
  ## Changes in 0.35.0
344
350
 
@@ -0,0 +1,122 @@
1
+ import { afterAll, test } from 'vitest';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { coordinator, languageService } from '@esportsplus/typescript/compiler';
6
+ import type { ts } from '@esportsplus/typescript';
7
+
8
+ import pipeline from '~/compiler/index';
9
+
10
+
11
+ // A small app: a state module, a central barrel, consumers reading through it, and modules the
12
+ // compiler must leave alone (no import at all, or imports that never reach reactive)
13
+ const FILES: Record<string, string> = {
14
+ 'app.ts': [
15
+ "export { reactive as make } from '@esportsplus/reactivity';",
16
+ "export * from './state';"
17
+ ].join('\n'),
18
+ 'consumer.ts': [
19
+ "import { count, list, make, store } from './app';",
20
+ "import * as app from './app';",
21
+ 'export let local = make(0);',
22
+ 'export let a = () => count + app.count + local;',
23
+ 'export let b = () => list.length + store.items.length;',
24
+ 'export let c = () => { list[0] = count; local += count; };'
25
+ ].join('\n'),
26
+ 'helpers.ts': [
27
+ "import { join } from 'node:path';",
28
+ 'export let path = (a: string, b: string) => join(a, b);',
29
+ 'export let sum = (values: number[]) => values.reduce((total, value) => total + value, 0);'
30
+ ].join('\n'),
31
+ 'plain.ts': [
32
+ 'export let clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));',
33
+ 'export let range = (n: number) => Array.from({ length: n }, (_, i) => i);'
34
+ ].join('\n'),
35
+ 'runtime.ts': [
36
+ "import { reactive } from '@esportsplus/reactivity';",
37
+ 'let count = reactive(0);',
38
+ 'let doubled = reactive(() => count * 2);',
39
+ 'let list = reactive([1, 2, 3]);',
40
+ 'let store = reactive({ items: [1], n: 1 });',
41
+ 'export let run = (): number => {',
42
+ ' let total = 0;',
43
+ ' for (let i = 0; i < 100; i++) {',
44
+ ' count++;',
45
+ ' list[0] = i;',
46
+ ' store.n = i;',
47
+ ' total += doubled + list.length + store.n;',
48
+ ' }',
49
+ ' return total;',
50
+ '};'
51
+ ].join('\n'),
52
+ 'state.ts': [
53
+ "import { reactive } from '@esportsplus/reactivity';",
54
+ 'export let count = reactive(0);',
55
+ 'export let list = reactive([1, 2]);',
56
+ 'export let store = reactive({ items: [1], n: 1 });'
57
+ ].join('\n')
58
+ };
59
+
60
+ const NAMES = Object.keys(FILES);
61
+
62
+
63
+ let directory = mkdtempSync(join(process.cwd(), '.fixture-bench-')).replace(/\\/g, '/'),
64
+ config = directory + '/tsconfig.json';
65
+
66
+ for (let i = 0, n = NAMES.length; i < n; i++) {
67
+ writeFileSync(join(directory, NAMES[i]), FILES[NAMES[i]]);
68
+ }
69
+
70
+ writeFileSync(config, JSON.stringify({
71
+ compilerOptions: { module: 'esnext', moduleResolution: 'bundler', strict: true, target: 'esnext', types: [] },
72
+ files: NAMES.map(name => './' + name)
73
+ }));
74
+
75
+
76
+ // One build pass: every module is transformed against one program and one checker, as tsc and vite
77
+ // hand them in, so the coordinator's memo is shared across the pass. Each pass wraps the checker
78
+ // anew, so its memo starts empty and every query the pass needs reaches tsgo once.
79
+ function build(names: string[]): string[] {
80
+ let checker: ts.Checker | null = null,
81
+ code: string[] = [];
82
+
83
+ for (let i = 0, n = names.length; i < n; i++) {
84
+ let id = directory + '/' + names[i],
85
+ project = languageService.update(config, id, FILES[names[i]]);
86
+
87
+ checker ??= new Proxy(project.checker, {});
88
+ code.push(coordinator.transform([pipeline], FILES[names[i]], project.program.getSourceFile(id)!, { checker, program: project.program }, directory, new Map()).code);
89
+ }
90
+
91
+ return code;
92
+ }
93
+
94
+
95
+ afterAll(() => {
96
+ languageService.dispose();
97
+ rmSync(directory, { force: true, recursive: true });
98
+ });
99
+
100
+
101
+ test('compiler transform', async ({ bench }) => {
102
+ await bench.compare(
103
+ bench('every module of the app', () => {
104
+ build(NAMES);
105
+ }),
106
+ bench('modules without reactive (no import, unrelated import)', () => {
107
+ build(['helpers.ts', 'plain.ts']);
108
+ })
109
+ );
110
+ });
111
+
112
+ test('compiled output', async ({ bench }) => {
113
+ let file = directory + '/runtime.compiled.ts';
114
+
115
+ writeFileSync(file, build(['runtime.ts'])[0]);
116
+
117
+ let { run } = await import(pathToFileURL(file).href) as { run: () => number };
118
+
119
+ await bench('signal, computed, array and object reads and writes', () => {
120
+ run();
121
+ }).run();
122
+ });
@@ -157,7 +157,7 @@ function diamond() {
157
157
  }
158
158
 
159
159
  function mux() {
160
- let heads = new Array(100).fill(null).map(() => framework.signal(0));
160
+ let heads = Array.from({ length: 100 }, () => framework.signal(0));
161
161
 
162
162
  let muxed = framework.computed(() => Object.fromEntries(heads.map((h) => h.read()).entries()));
163
163
 
@@ -21,7 +21,7 @@ const framework = {
21
21
  read: () => read(node)
22
22
  };
23
23
  },
24
- effect: (fn: () => void): VoidFunction => effect(fn),
24
+ effect: (fn: () => void) => effect(fn),
25
25
  signal: <T>(value: T): ReactiveSignal<T> => {
26
26
  let node = signal(value);
27
27
 
@@ -1,7 +1,11 @@
1
1
  import { test } from 'vitest';
2
- import { computed, dispose, effect, flush, onCleanup, read, root, signal, write } from '~/system';
2
+ import { computed, dispose as disposeNode, effect, flush, onCleanup, read, root, signal, write } from '~/system';
3
3
  import type { Computed } from '~/system';
4
4
 
5
+ // Vitest's module runner turns each imported call into a namespace getter read; one local binding keeps that
6
+ // out of the measured loops
7
+ const dispose = disposeNode;
8
+
5
9
 
6
10
  const CHURN = 1000;
7
11
 
@@ -41,9 +45,9 @@ test('ownership churn', async ({ bench }) => {
41
45
  bench(`${CHURN} child effects created + disposed under one owner`, () => {
42
46
  let owner = computed(() => {
43
47
  for (let i = 0; i < CHURN; i++) {
44
- effect(() => {
48
+ dispose(effect(() => {
45
49
  onCleanup(noop);
46
- })();
50
+ }));
47
51
  }
48
52
 
49
53
  return 0;
@@ -110,7 +114,7 @@ test('ownership effect re-run', async ({ bench }) => {
110
114
  })
111
115
  );
112
116
 
113
- stop();
117
+ dispose(stop);
114
118
  });
115
119
 
116
120
 
@@ -208,5 +212,5 @@ test('ownership single cleanup', async ({ bench }) => {
208
212
  })
209
213
  );
210
214
 
211
- stop();
215
+ dispose(stop);
212
216
  });
@@ -1,6 +1,10 @@
1
1
  import { test } from 'vitest';
2
2
  import { ReactiveArray } from '~/reactive/array';
3
- import { effect } from '~/system';
3
+ import { dispose as disposeNode, effect } from '~/system';
4
+
5
+ // Vitest's module runner turns each imported call into a namespace getter read; one local binding keeps that
6
+ // out of the measured loops
7
+ const dispose = disposeNode;
4
8
 
5
9
 
6
10
  test('ReactiveArray creation', async ({ bench }) => {
@@ -231,9 +235,10 @@ test('ReactiveArray reactive length', async ({ bench }) => {
231
235
  let arr = new ReactiveArray([1, 2, 3]);
232
236
 
233
237
  let stop = effect(() => {
238
+ // oxlint-disable-next-line no-unused-expressions -- the tracked read is what is measured
234
239
  arr.$length;
235
240
  });
236
241
 
237
- stop();
242
+ dispose(stop);
238
243
  }).run();
239
244
  });
@@ -16,8 +16,8 @@ test('ReactiveObject creation', async ({ bench }) => {
16
16
  }),
17
17
  bench('create with async computed property', () => {
18
18
  new ReactiveObject({
19
- value: 1,
20
- async: () => Promise.resolve(0)
19
+ async: () => Promise.resolve(0),
20
+ value: 1
21
21
  });
22
22
  })
23
23
  );
@@ -29,6 +29,7 @@ test('ReactiveObject read/write', async ({ bench }) => {
29
29
  bench('read property (signal-backed)', () => {
30
30
  let obj = new ReactiveObject({ a: 1, b: 2, c: 3, d: 4, e: 5 });
31
31
 
32
+ // oxlint-disable-next-line no-unused-expressions -- the getter read is what is measured
32
33
  (obj as any).a;
33
34
  }),
34
35
  bench('write property (signal-backed)', () => {
@@ -1,7 +1,11 @@
1
1
  import { test } from 'vitest';
2
- import { computed, dispose, effect, onCleanup, read, root, signal, write } from '~/system';
2
+ import { computed, dispose as disposeNode, effect, onCleanup, read, root, signal, write } from '~/system';
3
3
  import type { Computed } from '~/system';
4
4
 
5
+ // Vitest's module runner turns each imported call into a namespace getter read; one local binding keeps that
6
+ // out of the measured loops
7
+ const dispose = disposeNode;
8
+
5
9
 
6
10
  test('signal', async ({ bench }) => {
7
11
  await bench.compare(
@@ -93,7 +97,7 @@ test('effect', async ({ bench }) => {
93
97
  bench('create + dispose effect', () => {
94
98
  let stop = effect(() => {});
95
99
 
96
- stop();
100
+ dispose(stop);
97
101
  }),
98
102
  bench('effect with 1 signal', () => {
99
103
  let s = signal(0);
@@ -102,7 +106,7 @@ test('effect', async ({ bench }) => {
102
106
  read(s);
103
107
  });
104
108
 
105
- stop();
109
+ dispose(stop);
106
110
  }),
107
111
  bench('effect with 10 signals', () => {
108
112
  let signals: ReturnType<typeof signal<number>>[] = [];
@@ -117,7 +121,7 @@ test('effect', async ({ bench }) => {
117
121
  }
118
122
  });
119
123
 
120
- stop();
124
+ dispose(stop);
121
125
  })
122
126
  );
123
127
  });
@@ -245,7 +249,7 @@ test('effect stress', async ({ bench }) => {
245
249
  for (let i = 0; i < 1000; i++) {
246
250
  let stop = effect(() => {});
247
251
 
248
- stop();
252
+ dispose(stop);
249
253
  }
250
254
  }).run();
251
255
  });
@@ -32,10 +32,10 @@ function declare(ctx, node) {
32
32
  }
33
33
  let typeParam = elementType ? `<${elementType}>` : '';
34
34
  ctx.replacements.push({
35
- node,
36
- generate: (sf) => expression.elements.length > 0
37
- ? ` new ${NAMESPACE}.ReactiveArray${typeParam}(${expression.getText(sf)})`
38
- : ` new ${NAMESPACE}.ReactiveArray${typeParam}()`
35
+ generate: (_sourceFile, text) => expression.elements.length > 0
36
+ ? ` new ${NAMESPACE}.ReactiveArray${typeParam}(${text(expression)})`
37
+ : ` new ${NAMESPACE}.ReactiveArray${typeParam}()`,
38
+ node
39
39
  });
40
40
  }
41
41
  }
@@ -73,10 +73,10 @@ function length(access, replacements) {
73
73
  if (parent && ts.isBinaryExpression(parent) && parent.left === access && (parent.operatorToken.kind === ts.SyntaxKind.EqualsToken || COMPOUND_OPERATORS.has(parent.operatorToken.kind))) {
74
74
  let op = COMPOUND_OPERATORS.get(parent.operatorToken.kind);
75
75
  replacements.push({
76
- node: parent,
77
- generate: (sf) => op === undefined
78
- ? `${expr.getText(sf)}.$length = ${parent.right.getText(sf)}`
79
- : `${expr.getText(sf)}.$length = ${expr.getText(sf)}.length ${op} ${parent.right.getText(sf)}`
76
+ generate: (_sourceFile, text) => op === undefined
77
+ ? `${text(expr)}.$length = ${text(parent.right)}`
78
+ : `${text(expr)}.$length = ${text(expr)}.length ${op} ${text(parent.right)}`,
79
+ node: parent
80
80
  });
81
81
  }
82
82
  else if (parent &&
@@ -84,19 +84,19 @@ function length(access, replacements) {
84
84
  (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken)) {
85
85
  let op = parent.operator === ts.SyntaxKind.PlusPlusToken ? '+' : '-';
86
86
  replacements.push({
87
- node: parent,
88
- generate: (sf) => `${expr.getText(sf)}.$length = ${expr.getText(sf)}.length ${op} 1`
87
+ generate: (_sourceFile, text) => `${text(expr)}.$length = ${text(expr)}.length ${op} 1`,
88
+ node: parent
89
89
  });
90
90
  }
91
91
  else {
92
92
  replacements.push({
93
- node: access,
94
- generate: (sf) => `${expr.getText(sf)}.$length`
93
+ generate: (_sourceFile, text) => `${text(expr)}.$length`,
94
+ node: access
95
95
  });
96
96
  }
97
97
  }
98
98
  function write(access, ctx) {
99
- let parent = access.parent, array = (sf) => access.expression.getText(sf), index = (sf) => access.argumentExpression.getText(sf);
99
+ let parent = access.parent;
100
100
  if (ts.isDeleteExpression(parent)) {
101
101
  ctx.failures.push({ message: 'an element of a reactive array cannot be deleted; use splice()', node: parent });
102
102
  return;
@@ -104,19 +104,22 @@ function write(access, ctx) {
104
104
  if (ts.isBinaryExpression(parent)) {
105
105
  let op = COMPOUND_OPERATORS.get(parent.operatorToken.kind), right = parent.right;
106
106
  ctx.replacements.push({
107
- node: parent,
108
- generate: (sf) => op === undefined
109
- ? `${array(sf)}.$set(${index(sf)}, ${right.getText(sf)})`
110
- : `((_a, _k) => _a.$set(_k, _a[_k] ${op} (${right.getText(sf)})))(${array(sf)}, ${index(sf)})`
107
+ generate: (_sourceFile, text) => op === undefined
108
+ ? `${text(access.expression)}.$set(${text(access.argumentExpression)}, ${text(right)})`
109
+ : `((_a, _k) => _a.$set(_k, _a[_k] ${op} (${text(right)})))(${text(access.expression)}, ${text(access.argumentExpression)})`,
110
+ node: parent
111
111
  });
112
112
  return;
113
113
  }
114
114
  let unary = parent, op = unary.operator === ts.SyntaxKind.PlusPlusToken ? '+' : '-';
115
115
  ctx.replacements.push({
116
- node: unary,
117
- generate: (sf) => ts.isPrefixUnaryExpression(unary)
118
- ? `((_a, _k) => (_a.$set(_k, _a[_k] ${op} 1), _a[_k]))(${array(sf)}, ${index(sf)})`
119
- : `((_a, _k, _v) => (_a.$set(_k, _v ${op} 1), _v))(${array(sf)}, ${index(sf)}, ${array(sf)}[${index(sf)}])`
116
+ generate: (_sourceFile, text) => {
117
+ let array = text(access.expression), index = text(access.argumentExpression);
118
+ return ts.isPrefixUnaryExpression(unary)
119
+ ? `((_a, _k) => (_a.$set(_k, _a[_k] ${op} 1), _a[_k]))(${array}, ${index})`
120
+ : `((_a, _k, _v) => (_a.$set(_k, _v ${op} 1), _v))(${array}, ${index}, ${array}[${index}])`;
121
+ },
122
+ node: unary
120
123
  });
121
124
  }
122
125
  export default (sourceFile, bindings, isReactiveCall) => {
@@ -147,10 +150,10 @@ export default (sourceFile, bindings, isReactiveCall) => {
147
150
  }
148
151
  let name = assignment.left.text, elements = scope.unwrap(assignment.right);
149
152
  result.replacements.push({
150
- node: assignment,
151
- generate: (sf) => elements.elements.length > 0
152
- ? `${name}.splice(0, ${name}.length, ...${elements.getText(sf)})`
153
- : `${name}.splice(0, ${name}.length)`
153
+ generate: (_sourceFile, text) => elements.elements.length > 0
154
+ ? `${name}.splice(0, ${name}.length, ...${text(elements)})`
155
+ : `${name}.splice(0, ${name}.length)`,
156
+ node: assignment
154
157
  });
155
158
  }
156
159
  return result;
@@ -4,12 +4,13 @@ import { TYPES } from './constants.js';
4
4
  import type { Bindings } from './types.js';
5
5
  declare const arrays: (bindings: Bindings, nodes: ts.Node[]) => Set<ts.Node>;
6
6
  declare const classify: (bindings: Bindings, call: ts.CallExpression) => TYPES | null;
7
- declare const create: (checker: ts.Checker, program: ts.Program, sourceFile: ts.SourceFile) => Bindings;
7
+ declare const create: (queries: ts.Checker, program: ts.Program, sourceFile: ts.SourceFile) => Bindings;
8
8
  declare const denotes: (bindings: Bindings, expression: ts.Expression) => boolean;
9
9
  declare const holds: (bindings: Bindings, found: Origin | null) => boolean;
10
10
  declare const isReactiveCall: (bindings: Bindings, node: ts.Node) => node is ts.CallExpression;
11
11
  declare const kind: (bindings: Bindings, found: Origin | null) => TYPES | null;
12
12
  declare const origin: (bindings: Bindings, node: ts.Node) => Origin | null;
13
+ declare const prefetch: (bindings: Bindings, calls: ts.CallExpression[]) => void;
13
14
  declare const unwrap: (expression: ts.Expression) => ts.Expression;
14
15
  declare const _default: {
15
16
  arrays: typeof arrays;
@@ -20,6 +21,7 @@ declare const _default: {
20
21
  isReactiveCall: typeof isReactiveCall;
21
22
  kind: typeof kind;
22
23
  origin: typeof origin;
24
+ prefetch: typeof prefetch;
23
25
  unwrap: typeof unwrap;
24
26
  };
25
27
  export default _default;
@@ -1,5 +1,5 @@
1
1
  import { ts } from '@esportsplus/typescript';
2
- import { references } from '@esportsplus/typescript/compiler';
2
+ import { checker, references } from '@esportsplus/typescript/compiler';
3
3
  import { ENTRYPOINT, PACKAGE_NAME, TYPES } from './constants.js';
4
4
  const ARRAY_BRAND = 'once';
5
5
  const REACTIVE_ARRAY = 'ReactiveArray';
@@ -32,7 +32,7 @@ function assignments(bindings, file) {
32
32
  function cachesOf(program) {
33
33
  let found = caches.get(program);
34
34
  if (!found) {
35
- found = { arrays: new Map(), assignments: new Map(), kinds: new Map() };
35
+ found = { assignments: new Map(), kinds: new Map() };
36
36
  caches.set(program, found);
37
37
  }
38
38
  return found;
@@ -85,19 +85,14 @@ const arrays = (bindings, nodes) => {
85
85
  if (files.size === 0) {
86
86
  return result;
87
87
  }
88
- let cache = cachesOf(bindings.program).arrays, types = bindings.checker.getTypeAtLocation(nodes);
88
+ let types = bindings.checker.getTypeAtLocation(nodes);
89
89
  for (let i = 0, n = nodes.length; i < n; i++) {
90
90
  let type = types[i];
91
91
  if (!type) {
92
92
  continue;
93
93
  }
94
- let branded = cache.get(type.id);
95
- if (branded === undefined) {
96
- let property = bindings.checker.getPropertyOfType(bindings.checker.getNonNullableType(type) ?? type, ARRAY_BRAND);
97
- branded = property?.declarations?.some(declaration => files.has(declaration.path)) === true;
98
- cache.set(type.id, branded);
99
- }
100
- if (branded) {
94
+ let property = bindings.checker.getPropertyOfType(bindings.checker.getNonNullableType(type) ?? type, ARRAY_BRAND);
95
+ if (property?.declarations?.some(declaration => files.has(declaration.path))) {
101
96
  result.add(nodes[i]);
102
97
  }
103
98
  }
@@ -121,13 +116,16 @@ const classify = (bindings, call) => {
121
116
  let type = bindings.checker.getTypeAtLocation(arg);
122
117
  return type ? kindOf(bindings.checker, type) : null;
123
118
  };
124
- const create = (checker, program, sourceFile) => ({
125
- checker,
126
- entries: new Set(references.exported(checker, program, PACKAGE_NAME, ENTRYPOINT).map(references.key)),
127
- origins: references.origins(checker, program, sourceFile),
128
- program,
129
- sourceFile
130
- });
119
+ const create = (queries, program, sourceFile) => {
120
+ let memoized = checker.cached(queries, program);
121
+ return {
122
+ checker: memoized,
123
+ entries: new Set(references.exported(memoized, program, PACKAGE_NAME, ENTRYPOINT).map(references.key)),
124
+ origins: references.origins(memoized, program, sourceFile),
125
+ program,
126
+ sourceFile
127
+ };
128
+ };
131
129
  const denotes = (bindings, expression) => {
132
130
  return references.denotes(bindings.checker, bindings.program, expression, bindings.entries);
133
131
  };
@@ -179,7 +177,27 @@ const kind = (bindings, found) => {
179
177
  const origin = (bindings, node) => {
180
178
  return bindings.origins.get(node) ?? references.origin(bindings.checker, bindings.program, node);
181
179
  };
180
+ const prefetch = (bindings, calls) => {
181
+ let nodes = [];
182
+ for (let i = 0, n = calls.length; i < n; i++) {
183
+ let arg = calls[i].arguments[0];
184
+ if (!arg || calls[i].arguments.length !== 1 || ts.isSpreadElement(arg)) {
185
+ continue;
186
+ }
187
+ let value = unwrap(arg);
188
+ if (ts.isArrayLiteralExpression(value) ||
189
+ ts.isArrowFunction(value) ||
190
+ ts.isFunctionExpression(value) ||
191
+ ts.isObjectLiteralExpression(value)) {
192
+ continue;
193
+ }
194
+ nodes.push(arg);
195
+ }
196
+ if (nodes.length > 0) {
197
+ bindings.checker.getTypeAtLocation(nodes);
198
+ }
199
+ };
182
200
  const unwrap = (expression) => {
183
201
  return references.unwrap(expression);
184
202
  };
185
- export default { arrays, classify, create, denotes, holds, isReactiveCall, kind, origin, unwrap };
203
+ export default { arrays, classify, create, denotes, holds, isReactiveCall, kind, origin, prefetch, unwrap };
@@ -1,9 +1,10 @@
1
1
  import type { ImportIntent, ReplacementIntent, TransformContext } from '@esportsplus/typescript/compiler';
2
2
  declare const _default: {
3
+ name: string;
3
4
  transform: (ctx: TransformContext) => {
4
- dependencies: string[];
5
- } | {
6
5
  dependencies?: undefined;
6
+ } | {
7
+ dependencies: string[];
7
8
  } | {
8
9
  imports: ImportIntent[];
9
10
  prepend: string[];
@@ -4,6 +4,7 @@ import array from './array.js';
4
4
  import object from './object.js';
5
5
  import primitives from './primitives.js';
6
6
  import scope from './bindings.js';
7
+ const REGEX_IMPORT = /\bimport\b|\brequire\s*\(/;
7
8
  function failed(sourceFile, failures) {
8
9
  let lines = [];
9
10
  for (let i = 0, n = failures.length; i < n; i++) {
@@ -42,27 +43,23 @@ function isLowered(site) {
42
43
  function siteOf(identifier) {
43
44
  let parent = identifier.parent;
44
45
  if ((ts.isPropertyAccessExpression(parent) && parent.name === identifier) ||
45
- (ts.isElementAccessExpression(parent) && parent.argumentExpression === identifier)) {
46
+ (ts.isElementAccessExpression(parent) && parent.argumentExpression === identifier && (ts.isStringLiteral(identifier) || ts.isNoSubstitutionTemplateLiteral(identifier)))) {
46
47
  return parent;
47
48
  }
48
49
  return identifier;
49
50
  }
50
51
  export default {
52
+ name: PACKAGE_NAME,
51
53
  transform: (ctx) => {
52
- let { checker, program, sourceFile } = ctx, bindings = scope.create(checker, program, sourceFile), calls = new Set(), dependencies = new Set(), failures = [], self = sourceFile.fileName.toLowerCase();
54
+ if (!REGEX_IMPORT.test(ctx.code)) {
55
+ return {};
56
+ }
57
+ let { checker, program, sourceFile } = ctx, bindings = scope.create(checker, program, sourceFile), calls = new Set(), dependencies = new Set(), entries = new Set(), failures = [], self = sourceFile.fileName.toLowerCase();
53
58
  for (let [identifier, found] of bindings.origins) {
54
- let entry = scope.holds(bindings, found);
55
- if (!entry && scope.kind(bindings, found) === null) {
56
- continue;
57
- }
58
- for (let file of [...found.through, found.declaration.path]) {
59
- if (file.toLowerCase() !== self) {
60
- dependencies.add(file);
61
- }
62
- }
63
- if (!entry) {
59
+ if (!scope.holds(bindings, found)) {
64
60
  continue;
65
61
  }
62
+ entries.add(identifier);
66
63
  let site = siteOf(identifier), parent = site.parent;
67
64
  while (parent && ts.isParenthesizedExpression(parent)) {
68
65
  parent = parent.parent;
@@ -77,6 +74,17 @@ export default {
77
74
  });
78
75
  }
79
76
  }
77
+ scope.prefetch(bindings, [...calls]);
78
+ for (let [identifier, found] of bindings.origins) {
79
+ if (!entries.has(identifier) && scope.kind(bindings, found) === null) {
80
+ continue;
81
+ }
82
+ for (let file of [...found.through, found.declaration.path]) {
83
+ if (file.toLowerCase() !== self) {
84
+ dependencies.add(file);
85
+ }
86
+ }
87
+ }
80
88
  let isReactiveCall = (node) => calls.has(node), intents = {
81
89
  imports: [],
82
90
  prepend: [],
@@ -111,7 +119,7 @@ export default {
111
119
  continue;
112
120
  }
113
121
  intents.replacements.push({
114
- generate: () => `${NAMESPACE}.reactive(${call.arguments.map(a => a.getText(sourceFile)).join(', ')})`,
122
+ generate: (_sourceFile, text) => `${NAMESPACE}.reactive(${call.arguments.map(text).join(', ')})`,
115
123
  node: call
116
124
  });
117
125
  }