-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathvite.plugin.reactivity-debug.ts
More file actions
166 lines (139 loc) · 5.17 KB
/
vite.plugin.reactivity-debug.ts
File metadata and controls
166 lines (139 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import { resolve } from 'node:path';
import type { Plugin } from 'vite';
const SRC_FENCE = '/src/frontend/src/';
const EXCLUDED_MARKERS = ['reactivity-debug', 'derived-memo'];
const isExcludedPath = (path: string): boolean =>
EXCLUDED_MARKERS.some((marker) => path.includes(marker));
const DEBUG_IMPORT_SOURCE = '$lib/utils/reactivity-debug.utils';
const DEBUG_HIT_FN = 'reactivityDebugHit';
const DEBUG_LABEL_FN = '_setNextDerivedLabel';
const debugModulePath = resolve('src/frontend/src/lib/utils/reactivity-debug.utils.ts');
// Matches $effect(() => { | $effect(async () => { | $derived.by(() => {
const EFFECT_PATTERN = /(\$(?:effect|derived\.by)\s*\(\s*(?:async\s+)?\(\s*\)\s*=>\s*\{)/g;
// Matches derived( but NOT $derived( or originalDerived(
const DERIVED_CALL_PATTERN = /(?<![.$\w])derived\s*\(/g;
const extractFileLabel = (id: string): string => {
const idx = id.indexOf(SRC_FENCE);
if (idx !== -1) {
return id.slice(idx + SRC_FENCE.length);
}
const parts = id.split('/');
return parts.slice(-2).join('/');
};
/**
* Vite plugin that transparently instruments reactive primitives so that
* every recomputation is counted and exposed via `window.__oisyReactivityDebug`.
*
* Three mechanisms:
* 1. `resolveId` — redirects `svelte/store` imports in user code to a wrapper
* that counts every store `derived` recomputation.
* 2. `transform` on `.ts` files — injects `_setNextDerivedLabel()` before every
* `derived()` call so labels survive minification.
* 3. `transform` on `.svelte` files — injects `reactivityDebugHit()` into every
* `$effect` and `$derived.by` callback, and also labels `derived()` calls.
*
* Automatically active in every environment except production (`DFX_NETWORK=ic`).
*/
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions,func-style
export function reactivityDebugPlugin(): Plugin {
let enabled = false;
return {
name: 'reactivity-debug',
enforce: 'pre',
configResolved: () => {
const network = process.env.DFX_NETWORK ?? 'local';
enabled = network !== 'ic';
if (enabled) {
// eslint-disable-next-line no-console
console.log(
'\x1b[35m[reactivity-debug]\x1b[0m plugin active — store derived + $effect/$derived.by recomputations will be counted'
);
}
},
// Redirect svelte/store → debug wrapper (auto-wraps every store `derived`)
// eslint-disable-next-line local-rules/prefer-object-params
resolveId: (source, importer) => {
if (!enabled || source !== 'svelte/store') {
return;
}
if (
!importer ||
!importer.includes(SRC_FENCE) ||
importer.includes('node_modules') ||
isExcludedPath(importer)
) {
return;
}
return debugModulePath;
},
// eslint-disable-next-line local-rules/prefer-object-params
transform: (code, id) => {
if (!enabled) {
return;
}
if (!id.includes(SRC_FENCE) || id.includes('node_modules') || isExcludedPath(id)) {
return;
}
const isSvelte = id.endsWith('.svelte');
const isTs = id.endsWith('.ts');
if (!isSvelte && !isTs) {
return;
}
const fileLabel = extractFileLabel(id);
let result = code;
let needsHitImport = false;
let needsLabelImport = false;
// --- $effect / $derived.by injection (svelte files only) ---
if (isSvelte && EFFECT_PATTERN.test(code)) {
EFFECT_PATTERN.lastIndex = 0;
result = result.replace(EFFECT_PATTERN, (match, _group: string, offset: number) => {
const afterMatch = code.slice(offset + match.length);
if (/^\s*\n\s*reactivityDebugHit/.test(afterMatch)) {
return match;
}
needsHitImport = true;
const line = code.slice(0, offset).split('\n').length;
const kind = match.includes('derived.by') ? '$derived.by' : '$effect';
return `${match}\n\t\t${DEBUG_HIT_FN}('${fileLabel}:${line}:${kind}');`;
});
}
// --- derived() label injection (ts and svelte files) ---
if (DERIVED_CALL_PATTERN.test(result)) {
DERIVED_CALL_PATTERN.lastIndex = 0;
result = result.replace(DERIVED_CALL_PATTERN, (match, offset: number) => {
needsLabelImport = true;
const line = result.slice(0, offset).split('\n').length;
return `(${DEBUG_LABEL_FN}('${fileLabel}:${line}:derived'), derived)(`;
});
}
if (result === code) {
return;
}
// --- Add imports ---
const alreadyImported = code.includes(DEBUG_IMPORT_SOURCE);
const fnsToImport = [
...(needsHitImport ? [DEBUG_HIT_FN] : []),
...(needsLabelImport ? [DEBUG_LABEL_FN] : [])
].filter((fn) => !code.includes(fn));
if (fnsToImport.length > 0 && !alreadyImported) {
const importStatement = `import { ${fnsToImport.join(', ')} } from '${DEBUG_IMPORT_SOURCE}';`;
if (isSvelte) {
result = result.replace(/(<script\b[^>]*>)/i, `$1\n\t${importStatement}`);
} else {
result = `${importStatement}\n${result}`;
}
} else if (fnsToImport.length > 0 && alreadyImported) {
// Add missing functions to existing import
for (const fn of fnsToImport) {
result = result.replace(
new RegExp(
`(import\\s*\\{[^}]*)(\\}\\s*from\\s*['"]${DEBUG_IMPORT_SOURCE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"])`
),
`$1, ${fn} $2`
);
}
}
return { code: result, map: null };
}
};
}