@ticket-gate/react 0.0.0-stage → 0.1.0-rc.1

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @ticket-gate/react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The React Compiler bailout ratchet for `@ticket-gate/engine`. `compiler.mjs` exports `reactCompiler(options)`, which runs
4
+ `babel-plugin-react-compiler` over the `.ts` and `.tsx` files of the configured scan directories and compares what the compiler
5
+ could not compile with a baseline file. A new bailout, a skipped component or hook, or a stale baseline entry fails the check.
6
+
7
+ Every project value (scan directories, exclude pattern, where `@babel/core` and the plugin resolve from, baseline path, message
8
+ texts) is an option. The package has no runtime dependency beyond the engine: `@babel/core` and `babel-plugin-react-compiler` are
9
+ resolved from the consuming project at call time.
10
+
11
+ ## Profiling a React app
12
+
13
+ `ticket-gate profile` counts what React renders during one scripted action. It reads React's own performance tracks from a Chrome
14
+ trace: Scheduler (Render and Commit) and Components (one entry per component that rendered). It measures React DOM apps; LWC is not
15
+ covered.
16
+
17
+ ```
18
+ ticket-gate profile [--build] [--runs=N] [--scenarios=] [--out=] [--compare=] [--max-renders=]
19
+ ```
20
+
21
+ The command is added by `reactPack({ profile })`, where `profile` is a function returning the config below; the config is loaded only
22
+ when the command runs. `viteProfiling({ cmd, preview })` describes the build and the preview server of a Vite app, which must alias
23
+ `react-dom/client` to `react-dom/profiling` and set `esbuild.keepNames` in its own Vite config; a wrong build is caught by the trace
24
+ guards, which fail the run with the fix instead of printing zeros. For Next.js use
25
+ `{ ...nextProfiling({ app: 'web' }) }` from `@ticket-gate/supabase-next/profile-build.mjs`, and the Supabase reset and login hooks
26
+ from `@ticket-gate/supabase-next/profile-hooks.mjs`. `lock: false` skips the stack lock for a caller that already holds it. Playwright
27
+ comes from the project (`playwrightFrom` names the `package.json` that depends on it), never from this package, so it must be installed in the project at `playwrightFrom`.
28
+
29
+ `profile.config.mjs`:
30
+
31
+ ```js
32
+ import { viteProfiling } from '@ticket-gate/react/profile.mjs';
33
+
34
+ const root = new URL('.', import.meta.url).pathname;
35
+
36
+ export default {
37
+ root,
38
+ command: 'ticket-gate profile',
39
+ lock: 'profile:web',
40
+ scenarios: { home: async () => async () => {} },
41
+ writing: [],
42
+ componentsFor: () => ['Card', 'List'],
43
+ usage: { maxRenders: 'home:<n>' },
44
+ out: `${root}profile-out`,
45
+ tracePrefix: 'web-',
46
+ context: { viewport: { width: 1280, height: 800 } },
47
+ open: async () => {},
48
+ reset: async () => {},
49
+ playwrightFrom: `${root}package.json`,
50
+ appUrl: 'http://localhost:4173',
51
+ build: viteProfiling({ cmd: 'npm run build', preview: 'npm run preview' }),
52
+ messages: { expected: 'Card, List' },
53
+ preflight: { portInUse: 'port 4173 is in use', noApp: 'nothing on :4173: run with --build', noWebEnv: 'no app env' },
54
+ services: [],
55
+ probe: (url) => fetch(url).then(() => true, () => false),
56
+ hasEnv: () => true,
57
+ };
58
+ ```
59
+
60
+ `gate.config.mjs`:
61
+
62
+ ```js
63
+ import { defineGate } from '@ticket-gate/engine';
64
+ import { reactPack } from '@ticket-gate/react/index.mjs';
65
+
66
+ export default defineGate({
67
+ steps: [],
68
+ packs: [reactPack({ profile: async () => (await import('./profile.config.mjs')).default })],
69
+ });
70
+ ```
71
+
72
+ ## Profiling every night
73
+
74
+ `reactProfile` from `@ticket-gate/react/profile.mjs` is a nightly suite runner. Put it in `nightly.suites` after the end-to-end suite, and give the suite entry `keep: runner.keep`, which is how the engine learns how many nights of traces to keep. `config` is the profile config module above, as a path relative to the worktree. Its `budgets` key is `{ [scenario]: { max, blocking? } }`, the largest median of component renders a scenario may have.
75
+
76
+ A scenario over its budget makes the night amber until its entry says `blocking: true`; then the night is red and `ticket-gate nightly status` names the merges since the last green night. A run that leaves no numbers (the build failed, the trace guards fired, the child died) is red. A run cut short at `limitS` is printed as `red (cut-short)`. A scenario that stayed within its budget, and within 10% of itself, for seven nights gets a hint to promote it to `blocking: true`. Results are kept every night and traces for the newest `keepTraces` nights. A cut-short night has no results, because `results.json` is written only when the run ends; the traces it had written are dropped once `keepTraces` reported nights exist. The runner takes no stack lock because the nightly already holds it; it profiles in a child process so that `limitS` can stop it.
77
+
78
+ ```js
79
+ import { reactProfile } from '@ticket-gate/react/profile.mjs';
80
+
81
+ const runner = reactProfile({
82
+ config: 'profile.config.mjs',
83
+ runs: 1,
84
+ scenarios: 'all',
85
+ keepTraces: 3,
86
+ });
87
+
88
+ export const suite = { name: 'profile', runner, limitS: 2700, keep: runner.keep };
89
+ ```
package/compiler.mjs ADDED
@@ -0,0 +1,391 @@
1
+ // React Compiler bailout ratchet, as a pack check. Runs babel-plugin-react-compiler
2
+ // over every .ts/.tsx file of the configured scan dirs, the way the bundlers do, and
3
+ // compares what it could not compile with a baseline file.
4
+ //
5
+ // A bailout (the compiler gave up on a function) that is not in the baseline fails
6
+ // the check. So does a "skip": a top-level function named like a component or hook
7
+ // that the compiler emitted no event for (compilationMode infer drops a use* hook
8
+ // that calls no hook). A baseline entry whose function now compiles also fails, so
9
+ // the baseline can only shrink by itself.
10
+ //
11
+ // Every project value (scan dirs, exclude pattern, where @babel/core and the plugin
12
+ // resolve from, baseline path, message texts) is an option of reactCompiler().
13
+ // run(argv) takes --update, --seed, --root=<dir>, --baseline=<path> and returns
14
+ // { code, out, err }; it never prints and never exits.
15
+ //
16
+ // Exit codes: 0 green, 1 a new, stale, unreasoned or skipped function or a plugin-version
17
+ // mismatch, 2 the plugin did not load or a file did not parse.
18
+ import { spawnSync } from 'node:child_process';
19
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
20
+ import { createRequire } from 'node:module';
21
+ import { dirname, join, resolve } from 'node:path';
22
+
23
+ const PLUGIN = 'babel-plugin-react-compiler';
24
+ export const COMPONENT_OR_HOOK = /^(use[A-Z0-9]|[A-Z])/;
25
+
26
+ class CheckFailure extends Error {
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ }
31
+ }
32
+
33
+ const fail = (code, message) => {
34
+ throw new CheckFailure(code, message);
35
+ };
36
+
37
+ /** `@babel/core` and the plugin as the first package of `via` resolves them, step by step. */
38
+ function loadCompiler(repo, { from, via }, install) {
39
+ try {
40
+ let req = createRequire(join(repo, from, 'package.json'));
41
+ for (const spec of via) {
42
+ let dir = dirname(req.resolve(spec));
43
+ while (!existsSync(join(dir, 'package.json'))) dir = dirname(dir);
44
+ req = createRequire(join(dir, 'package.json'));
45
+ }
46
+ const pluginEntry = req.resolve(PLUGIN);
47
+ let pdir = dirname(pluginEntry);
48
+ const nameOf = (d) =>
49
+ existsSync(join(d, 'package.json'))
50
+ ? JSON.parse(readFileSync(join(d, 'package.json'), 'utf8')).name
51
+ : null;
52
+ while (nameOf(pdir) !== PLUGIN) pdir = dirname(pdir);
53
+ return {
54
+ babel: req('@babel/core'),
55
+ plugin: req(PLUGIN),
56
+ version: JSON.parse(readFileSync(join(pdir, 'package.json'), 'utf8'))
57
+ .version,
58
+ };
59
+ } catch (e) {
60
+ return fail(
61
+ 2,
62
+ `could not load @babel/core and ${PLUGIN} through ${via.at(-1)} (${e.message}). Run \`${install}\`.`,
63
+ );
64
+ }
65
+ }
66
+
67
+ const isFn = (n) =>
68
+ n &&
69
+ (n.type === 'FunctionDeclaration' ||
70
+ n.type === 'FunctionExpression' ||
71
+ n.type === 'ArrowFunctionExpression');
72
+
73
+ const sameStart = (node, loc) =>
74
+ node.loc?.start.line === loc?.start?.line &&
75
+ node.loc?.start.column === loc?.start?.column;
76
+
77
+ /** Visit every node with its parent. */
78
+ function walk(node, parent, visit) {
79
+ if (!node || typeof node.type !== 'string') return;
80
+ visit(node, parent);
81
+ for (const key of Object.keys(node)) {
82
+ if (
83
+ key === 'loc' ||
84
+ key === 'leadingComments' ||
85
+ key === 'trailingComments' ||
86
+ key === 'innerComments'
87
+ )
88
+ continue;
89
+ const v = node[key];
90
+ if (Array.isArray(v)) for (const c of v) walk(c, node, visit);
91
+ else if (v && typeof v === 'object') walk(v, node, visit);
92
+ }
93
+ }
94
+
95
+ /** R2: the logger names only successes, so a bailout takes its name from the AST. */
96
+ function nameAt(ast, fnLoc) {
97
+ let name = null;
98
+ const parents = new Map();
99
+ walk(ast, null, (node, parent) => {
100
+ parents.set(node, parent);
101
+ if (name !== null || !isFn(node) || !sameStart(node, fnLoc)) return;
102
+ if (node.id?.name) {
103
+ name = node.id.name;
104
+ return;
105
+ }
106
+ let up = parents.get(node);
107
+ while (up?.type === 'CallExpression') up = parents.get(up);
108
+ if (up?.type === 'VariableDeclarator' && up.id.type === 'Identifier')
109
+ name = up.id.name;
110
+ else if (up?.type === 'ExportDefaultDeclaration') name = 'default';
111
+ else name = '<anonymous>';
112
+ });
113
+ return name ?? '<anonymous>';
114
+ }
115
+
116
+ const WRAPPERS = /^(forwardRef|memo)$/;
117
+ const calleeName = (call) =>
118
+ call.callee.name ?? call.callee.property?.name ?? '';
119
+
120
+ /** Top-level functions: { name, node }. */
121
+ function topLevelFunctions(ast) {
122
+ const out = [];
123
+ for (const stmt of ast.program.body) {
124
+ const decl =
125
+ stmt.type === 'ExportNamedDeclaration' ||
126
+ stmt.type === 'ExportDefaultDeclaration'
127
+ ? stmt.declaration
128
+ : stmt;
129
+ if (decl?.type === 'FunctionDeclaration' && decl.id)
130
+ out.push({ name: decl.id.name, node: decl });
131
+ else if (decl?.type === 'VariableDeclaration')
132
+ for (const d of decl.declarations) {
133
+ if (d.id.type !== 'Identifier') continue;
134
+ let init = d.init;
135
+ while (
136
+ init?.type === 'CallExpression' &&
137
+ WRAPPERS.test(calleeName(init))
138
+ )
139
+ init = init.arguments.find(
140
+ (a) => isFn(a) || a.type === 'CallExpression',
141
+ );
142
+ if (isFn(init)) out.push({ name: d.id.name, node: init });
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ const categoryOf = (e) =>
149
+ e.kind === 'PipelineError'
150
+ ? 'Pipeline'
151
+ : (e.detail?.category ?? e.detail?.options?.category ?? 'Unknown');
152
+ const reasonOf = (e) =>
153
+ e.detail?.reason ??
154
+ e.detail?.options?.reason ??
155
+ (typeof e.data === 'string' ? e.data : 'unknown');
156
+
157
+ function listFiles(root, scanDirs, exclude) {
158
+ const r = spawnSync('git', ['ls-files', '--', ...scanDirs], {
159
+ cwd: root,
160
+ encoding: 'utf8',
161
+ });
162
+ if (r.status !== 0)
163
+ fail(
164
+ 2,
165
+ `git ls-files failed in ${root}: ${r.stderr.trim()}. Run it inside a git work tree.`,
166
+ );
167
+ return r.stdout
168
+ .split('\n')
169
+ .filter(
170
+ (f) => /\.tsx?$/.test(f) && !exclude.test(f) && existsSync(join(root, f)),
171
+ )
172
+ .sort();
173
+ }
174
+
175
+ export function scan(root, { babel, plugin }, { scanDirs, exclude }) {
176
+ const files = listFiles(root, scanDirs, exclude);
177
+ const bailouts = new Map();
178
+ const skipped = [];
179
+ let compiled = 0;
180
+ for (const path of files) {
181
+ const events = [];
182
+ const options = {
183
+ babelrc: false,
184
+ configFile: false,
185
+ filename: join(root, path),
186
+ parserOpts: {
187
+ plugins: path.endsWith('.tsx') ? ['typescript', 'jsx'] : ['typescript'],
188
+ },
189
+ };
190
+ const code = readFileSync(join(root, path), 'utf8');
191
+ let ast;
192
+ try {
193
+ babel.transformSync(code, {
194
+ ...options,
195
+ plugins: [
196
+ [
197
+ plugin,
198
+ {
199
+ target: '19',
200
+ panicThreshold: 'none',
201
+ logger: { logEvent: (_f, event) => events.push(event) },
202
+ },
203
+ ],
204
+ ],
205
+ });
206
+ ast = babel.parseSync(code, options);
207
+ } catch (e) {
208
+ return fail(
209
+ 2,
210
+ `${path} did not parse or transform: ${String(e.message).split('\n')[0]}. Fix the syntax error first.`,
211
+ );
212
+ }
213
+ for (const e of events) {
214
+ if (e.kind === 'CompileSuccess') compiled += 1;
215
+ if (e.kind !== 'CompileError' && e.kind !== 'PipelineError') continue;
216
+ const name = nameAt(ast, e.fnLoc);
217
+ const category = categoryOf(e);
218
+ const key = `${path}|${name}|${category}`;
219
+ if (!bailouts.has(key))
220
+ bailouts.set(key, {
221
+ key,
222
+ path,
223
+ line: e.fnLoc?.start?.line ?? 0,
224
+ name,
225
+ category,
226
+ reason: reasonOf(e),
227
+ });
228
+ }
229
+ for (const { name, node } of topLevelFunctions(ast)) {
230
+ if (!COMPONENT_OR_HOOK.test(name)) continue;
231
+ if (events.some((e) => e.fnLoc && sameStart(node, e.fnLoc))) continue;
232
+ skipped.push({
233
+ key: `${path}|${name}`,
234
+ path,
235
+ line: node.loc.start.line,
236
+ name,
237
+ });
238
+ }
239
+ }
240
+ return {
241
+ files: files.length,
242
+ compiled,
243
+ bailouts: [...bailouts.values()],
244
+ skipped,
245
+ };
246
+ }
247
+
248
+ export function compare(report, baseline) {
249
+ const known = new Set(baseline.bailouts.map((e) => e.key));
250
+ const current = new Set(report.bailouts.map((b) => b.key));
251
+ const allowedSkips = new Set(baseline.skipped.map((e) => e.key));
252
+ const currentSkips = new Set(report.skipped.map((s) => s.key));
253
+ const entries = [...baseline.bailouts, ...baseline.skipped];
254
+ const fresh = report.bailouts.filter((b) => !known.has(b.key));
255
+ const stale = baseline.bailouts.filter((e) => !current.has(e.key));
256
+ const staleSkips = baseline.skipped.filter((e) => !currentSkips.has(e.key));
257
+ const unskipped = report.skipped.filter((s) => !allowedSkips.has(s.key));
258
+ const unreasoned = entries.filter((e) => e.allow === '');
259
+ return {
260
+ fresh,
261
+ stale: [...stale, ...staleSkips],
262
+ unskipped,
263
+ unreasoned,
264
+ };
265
+ }
266
+
267
+ const byKey = (p, q) => (p.key < q.key ? -1 : p.key > q.key ? 1 : 0);
268
+
269
+ /** Next baseline for the current scan (rules in the header). */
270
+ export function updateBaseline(
271
+ report,
272
+ baseline,
273
+ version,
274
+ { seed = false, comment } = {},
275
+ ) {
276
+ const old = new Map(
277
+ [...baseline.bailouts, ...baseline.skipped].map((e) => [e.key, e]),
278
+ );
279
+ const withAllow = (entry) => {
280
+ const prev = old.get(entry.key);
281
+ if (prev?.allow !== undefined) entry.allow = prev.allow;
282
+ else if (!prev && !seed) entry.allow = '';
283
+ return entry;
284
+ };
285
+ return {
286
+ comment: comment,
287
+ plugin: version,
288
+ bailouts: report.bailouts
289
+ .map((b) => withAllow({ key: b.key, reason: b.reason }))
290
+ .sort(byKey),
291
+ skipped: report.skipped.map((s) => withAllow({ key: s.key })).sort(byKey),
292
+ };
293
+ }
294
+
295
+ function loadBaseline(path, version) {
296
+ try {
297
+ const b = JSON.parse(readFileSync(path, 'utf8'));
298
+ return { ...b, bailouts: b.bailouts ?? [], skipped: b.skipped ?? [] };
299
+ } catch {
300
+ return { plugin: version, bailouts: [], skipped: [] };
301
+ }
302
+ }
303
+
304
+ export function reactCompiler({
305
+ repo,
306
+ scanDirs,
307
+ exclude,
308
+ resolve: resolveVia,
309
+ baseline: baselineRel,
310
+ comment,
311
+ name,
312
+ update,
313
+ install,
314
+ }) {
315
+ const scope = { scanDirs, exclude };
316
+
317
+ function run(argv) {
318
+ const out = [];
319
+ try {
320
+ const opt = (flag) =>
321
+ argv.find((a) => a.startsWith(`--${flag}=`))?.slice(flag.length + 3);
322
+ const root = resolve(opt('root') ?? repo);
323
+ const baselinePath = resolve(opt('baseline') ?? join(root, baselineRel));
324
+ const compiler = loadCompiler(repo, resolveVia, install);
325
+ const pluginVersion = compiler.version;
326
+ const report = scan(root, compiler, scope);
327
+ const baseline = loadBaseline(baselinePath, pluginVersion);
328
+
329
+ if (argv.includes('--update')) {
330
+ const next = updateBaseline(report, baseline, pluginVersion, {
331
+ seed: argv.includes('--seed'),
332
+ comment,
333
+ });
334
+ writeFileSync(baselinePath, JSON.stringify(next, null, 2) + '\n');
335
+ out.push(
336
+ `${name}: baseline rewritten, ${next.bailouts.length} bailouts, ${next.skipped.length} skips.`,
337
+ );
338
+ return { code: 0, out, err: [] };
339
+ }
340
+
341
+ const { fresh, stale, unskipped, unreasoned } = compare(report, baseline);
342
+ let problems = 0;
343
+ if (baseline.plugin !== pluginVersion) {
344
+ problems += 1;
345
+ out.push(
346
+ `plugin ${pluginVersion} != baseline ${baseline.plugin}: re-seed with --update`,
347
+ );
348
+ }
349
+ for (const b of fresh) {
350
+ problems += 1;
351
+ out.push(
352
+ `new bailout: ${b.path}:${b.line} ${b.name} [${b.category}] ${b.reason}`,
353
+ );
354
+ }
355
+ for (const e of stale) {
356
+ problems += 1;
357
+ out.push(`stale: ${e.key} (fixed - run ${update})`);
358
+ }
359
+ for (const s of unskipped) {
360
+ problems += 1;
361
+ out.push(
362
+ `skipped: ${s.path}:${s.line} ${s.name} is named like a component or hook but was not compiled ('use memo', or an allow entry)`,
363
+ );
364
+ }
365
+ for (const e of unreasoned) {
366
+ problems += 1;
367
+ out.push(`unreasoned: ${e.key}`);
368
+ }
369
+ const debt = baseline.bailouts.filter(
370
+ (e) => e.allow === undefined,
371
+ ).length;
372
+ const allowed = baseline.bailouts.length - debt;
373
+ out.push(
374
+ `${name}: ${report.files} files, ${report.compiled} compiled functions, ${report.bailouts.length} bailouts (${debt} debt, ${allowed} allowed), ${baseline.skipped.length} allowed skips`,
375
+ );
376
+ return { code: problems > 0 ? 1 : 0, out, err: [] };
377
+ } catch (e) {
378
+ if (e instanceof CheckFailure)
379
+ return { code: e.code, out: [], err: [`${name}: ${e.message}`] };
380
+ throw e;
381
+ }
382
+ }
383
+
384
+ return {
385
+ scan: (root, compiler) => scan(root, compiler, scope),
386
+ compare,
387
+ updateBaseline: (report, baselineJson, version, { seed = false } = {}) =>
388
+ updateBaseline(report, baselineJson, version, { seed, comment }),
389
+ run,
390
+ };
391
+ }