@pulsec/vite 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # @pulsec/vite
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
+ Ultra-fast Vite TypeScript, TSX, and JSX transform plugin powered by [`pulsec`](../../README.md).
4
+
5
+ ## Features
6
+
7
+ - **`enforce: 'pre'` + `esbuild: false`**: Eliminates double transpilation in Vite pipelines.
8
+ - **Zero-regex hot-path filtering**: Instantly skips `?raw`/`?url`/`?worker`/`?inline` asset queries, `node_modules`, and plain `.js` files.
9
+ - **In-memory LRU cache**: Instant cache hits on repeated HMR / multi-environment transforms.
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { defineConfig } from 'vite';
15
+ import pulsec from '@pulsec/vite';
16
+
17
+ export default defineConfig({
18
+ plugins: [pulsec()],
19
+ });
20
+ ```
package/index.d.cts ADDED
@@ -0,0 +1,55 @@
1
+ import type { CompileOptions, SourceMapV3 } from 'pulsec';
2
+
3
+ declare function pulsec(options?: pulsec.PulsecViteOptions): pulsec.PulsecVitePlugin;
4
+
5
+ declare namespace pulsec {
6
+ export type FilterPattern = string | RegExp | Array<string | RegExp> | ((id: string) => boolean);
7
+
8
+ export interface PulsecViteOptions {
9
+ mode?: CompileOptions['mode'];
10
+ target?: CompileOptions['target'];
11
+ module?: CompileOptions['module'];
12
+ jsx?: CompileOptions['jsx'];
13
+ sourceMap?: boolean;
14
+ experimentalDecorators?: boolean;
15
+ emitDecoratorMetadata?: boolean;
16
+ skipPlainJs?: boolean;
17
+ includeNodeModules?: boolean;
18
+ include?: FilterPattern;
19
+ exclude?: FilterPattern;
20
+ disableEsbuild?: boolean;
21
+ maxCacheSize?: number;
22
+ }
23
+
24
+ export interface PulsecTransformResult {
25
+ code: string;
26
+ map: SourceMapV3 | { mappings: '' };
27
+ }
28
+
29
+ export interface PulsecTransformEngine {
30
+ transform(code: string, id: string): PulsecTransformResult | null;
31
+ shouldTransform(id: string): string | null;
32
+ setSourceMap(enabled: boolean): void;
33
+ setDelegateJsx(enabled: boolean): void;
34
+ readonly stats: { hits: number; misses: number; skipped: number };
35
+ clearCache(): void;
36
+ }
37
+
38
+ export interface PulsecVitePlugin {
39
+ name: string;
40
+ enforce: 'pre';
41
+ config(): { esbuild: false | { exclude: RegExp } } | undefined;
42
+ configResolved(config: {
43
+ command?: string;
44
+ build?: { sourcemap?: boolean | string };
45
+ esbuild?: { jsxImportSource?: string } | false;
46
+ oxc?: { jsx?: { importSource?: string } } | false;
47
+ }): void;
48
+ transform(code: string, id: string): PulsecTransformResult | null;
49
+ }
50
+
51
+ export function createPulsecTransform(options?: PulsecViteOptions): PulsecTransformEngine;
52
+ export { pulsec, pulsec as default };
53
+ }
54
+
55
+ export = pulsec;
package/index.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { CompileOptions, SourceMapV3 } from 'pulsec';
2
+
3
+ export type FilterPattern = string | RegExp | Array<string | RegExp> | ((id: string) => boolean);
4
+
5
+ export interface PulsecViteOptions {
6
+ /** Compilation mode (default: `'transform'`). */
7
+ mode?: CompileOptions['mode'];
8
+ /** ECMAScript target (default: `'esnext'`). */
9
+ target?: CompileOptions['target'];
10
+ /** Output module format (default: `'preserve'`). */
11
+ module?: CompileOptions['module'];
12
+ /** JSX emit mode (default: `'automatic'`). */
13
+ jsx?: CompileOptions['jsx'];
14
+ /** Emit source maps (defaults to `true` in dev and `Boolean(config.build.sourcemap)` in build). */
15
+ sourceMap?: boolean;
16
+ /** Enable legacy TypeScript experimental decorators. */
17
+ experimentalDecorators?: boolean;
18
+ /** Emit design-time decorator metadata. */
19
+ emitDecoratorMetadata?: boolean;
20
+ /** Skip plain `.js`/`.mjs`/`.cjs` files (default: `true`). */
21
+ skipPlainJs?: boolean;
22
+ /** Transform files inside `node_modules` (default: `false`). */
23
+ includeNodeModules?: boolean;
24
+ /** Optional include filter. */
25
+ include?: FilterPattern;
26
+ /** Optional exclude filter. */
27
+ exclude?: FilterPattern;
28
+ /**
29
+ * Controls how Vite's built-in `esbuild` transform is configured:
30
+ * - `undefined` (default): excludes TS/TSX/JSX from esbuild while preserving chunk `build.target`/minify.
31
+ * - `true`: sets `esbuild: false`.
32
+ * - `false`: leaves `esbuild` untouched.
33
+ */
34
+ disableEsbuild?: boolean;
35
+ /** Maximum number of entries in the in-memory LRU transform cache (default: `512`, `0` disables). */
36
+ maxCacheSize?: number;
37
+ }
38
+
39
+ export interface PulsecTransformResult {
40
+ code: string;
41
+ map: SourceMapV3 | { mappings: '' };
42
+ }
43
+
44
+ export interface PulsecTransformEngine {
45
+ transform(code: string, id: string): PulsecTransformResult | null;
46
+ shouldTransform(id: string): string | null;
47
+ setSourceMap(enabled: boolean): void;
48
+ setDelegateJsx(enabled: boolean): void;
49
+ readonly stats: { hits: number; misses: number; skipped: number };
50
+ clearCache(): void;
51
+ }
52
+
53
+ export interface PulsecVitePlugin {
54
+ name: string;
55
+ enforce: 'pre';
56
+ config(): { esbuild: false | { exclude: RegExp } } | undefined;
57
+ configResolved(config: {
58
+ command?: string;
59
+ build?: { sourcemap?: boolean | string };
60
+ esbuild?: { jsxImportSource?: string } | false;
61
+ oxc?: { jsx?: { importSource?: string } } | false;
62
+ }): void;
63
+ transform(code: string, id: string): PulsecTransformResult | null;
64
+ }
65
+
66
+ export function createPulsecTransform(options?: PulsecViteOptions): PulsecTransformEngine;
67
+ export function pulsec(options?: PulsecViteOptions): PulsecVitePlugin;
68
+ export default pulsec;
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@pulsec/vite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Ultra-fast Vite TypeScript/TSX/JSX transform plugin powered by pulsec.",
5
+ "keywords": [
6
+ "vite",
7
+ "vite-plugin",
8
+ "typescript",
9
+ "tsx",
10
+ "jsx",
11
+ "compiler",
12
+ "pulsec"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "author": "Tatsuo Kaniwa",
16
+ "homepage": "https://github.com/t-k/pulsec#readme",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/t-k/pulsec.git",
20
+ "directory": "packages/vite"
21
+ },
22
+ "type": "module",
23
+ "main": "./src/index.cjs",
24
+ "module": "./src/index.mjs",
25
+ "types": "./index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./index.d.ts",
30
+ "default": "./src/index.mjs"
31
+ },
32
+ "require": {
33
+ "types": "./index.d.cts",
34
+ "default": "./src/index.cjs"
35
+ }
36
+ },
37
+ "./transform": {
38
+ "require": "./src/transform.cjs"
39
+ }
40
+ },
41
+ "files": [
42
+ "src/",
43
+ "index.d.ts",
44
+ "index.d.cts",
45
+ "README.md",
46
+ "LICENSE"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "engines": {
52
+ "node": "^22.18.0 || >=24.11.0"
53
+ },
54
+ "scripts": {
55
+ "test": "node --test test/*.test.mjs"
56
+ },
57
+ "dependencies": {
58
+ "pulsec": "^0.4.1"
59
+ },
60
+ "peerDependencies": {
61
+ "vite": ">=5.0.0"
62
+ }
63
+ }
package/src/index.cjs ADDED
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ const { createPulsecTransform, hasCustomTsconfigJsxImportSource } = require('./transform.cjs');
4
+
5
+ // Only exclude non-node_modules `.ts`/`.mts`/`.cts` from Vite's built-in esbuild by default.
6
+ // Keeping `.tsx`/`.jsx` and `node_modules` out of esbuild.exclude ensures:
7
+ // 1. `node_modules` TS files (e.g. ssr.noExternal) remain handled by Vite.
8
+ // 2. If a later plugin or tsconfig sets a custom jsxImportSource (e.g. Preact) and pulsec
9
+ // delegates `.tsx`/`.jsx`, Vite's esbuild/oxc pipeline still transforms them.
10
+ const TS_ONLY_NON_NM_EXCLUDE = /^(?!.*(?:\/|\\)node_modules(?:\/|\\)).*\.(?:[cm]?ts)(?:\?|$)/i;
11
+ const TS_ONLY_ALL_EXCLUDE = /\.(?:[cm]?ts)(?:\?|$)/i;
12
+ const TS_JSX_NON_NM_EXCLUDE = /^(?!.*(?:\/|\\)node_modules(?:\/|\\)).*\.(?:[cm]?ts|tsx|jsx)(?:\?|$)/i;
13
+ const TS_JSX_ALL_EXCLUDE = /\.(?:[cm]?ts|tsx|jsx)(?:\?|$)/i;
14
+
15
+ function detectCustomJsxSource(config) {
16
+ const custom = (config && config.oxc && config.oxc.jsx && config.oxc.jsx.importSource)
17
+ || (config && config.esbuild && config.esbuild.jsxImportSource);
18
+ if (custom && custom !== 'react') return true;
19
+ if (hasCustomTsconfigJsxImportSource(config && config.root)) return true;
20
+ return false;
21
+ }
22
+
23
+ /**
24
+ * Vite plugin for ultra-fast TypeScript, TSX, and JSX transformation powered by pulsec.
25
+ */
26
+ function pulsec(options = {}) {
27
+ const engine = createPulsecTransform(options);
28
+ const disableEsbuild = options.disableEsbuild;
29
+ const includeNodeModules = Boolean(options.includeNodeModules);
30
+
31
+ const plugin = {
32
+ name: 'pulsec:vite',
33
+ enforce: 'pre',
34
+
35
+ config(userConfig) {
36
+ const delegateJsx = options.jsx === undefined && detectCustomJsxSource(userConfig);
37
+ if (delegateJsx) {
38
+ engine.setDelegateJsx(true);
39
+ }
40
+ if (disableEsbuild === false) return undefined;
41
+ if (disableEsbuild === true) return { esbuild: false };
42
+ if (options.exclude || options.include) return undefined;
43
+ // Only exclude .tsx/.jsx from esbuild when user explicitly pins `options.jsx`;
44
+ // otherwise keep .tsx/.jsx eligible for esbuild in case a later plugin configures Preact/Solid JSX.
45
+ const excludeJsx = options.jsx !== undefined && options.jsx !== 'preserve';
46
+ const pattern = excludeJsx
47
+ ? (includeNodeModules ? TS_JSX_ALL_EXCLUDE : TS_JSX_NON_NM_EXCLUDE)
48
+ : (includeNodeModules ? TS_ONLY_ALL_EXCLUDE : TS_ONLY_NON_NM_EXCLUDE);
49
+ return {
50
+ esbuild: {
51
+ exclude: pattern,
52
+ },
53
+ };
54
+ },
55
+
56
+ configResolved(config) {
57
+ if (options.jsx === undefined && detectCustomJsxSource(config)) {
58
+ engine.setDelegateJsx(true);
59
+ }
60
+ if (options.sourceMap !== undefined) return;
61
+ if (config && config.command === 'build') {
62
+ engine.setSourceMap(Boolean(config.build && config.build.sourcemap));
63
+ } else {
64
+ engine.setSourceMap(true);
65
+ }
66
+ },
67
+
68
+ transform(code, id) {
69
+ try {
70
+ return engine.transform(code, id);
71
+ } catch (err) {
72
+ if (this && typeof this.error === 'function') {
73
+ this.error({
74
+ message: err instanceof Error ? err.message : String(err),
75
+ id: err && err.id ? err.id : id,
76
+ loc: err && err.loc ? err.loc : undefined,
77
+ });
78
+ return null;
79
+ }
80
+ throw err;
81
+ }
82
+ },
83
+ };
84
+
85
+ Object.defineProperty(plugin, '__pulsecStats', {
86
+ value: engine.stats,
87
+ enumerable: false,
88
+ });
89
+ Object.defineProperty(plugin, '__pulsecClearCache', {
90
+ value: engine.clearCache,
91
+ enumerable: false,
92
+ });
93
+
94
+ return plugin;
95
+ }
96
+
97
+ module.exports = pulsec;
98
+ module.exports.default = pulsec;
99
+ module.exports.pulsec = pulsec;
100
+ module.exports.createPulsecTransform = createPulsecTransform;
package/src/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import pulsec from './index.cjs';
2
+
3
+ export const { createPulsecTransform } = pulsec;
4
+ export { pulsec };
5
+ export default pulsec;
@@ -0,0 +1,430 @@
1
+ 'use strict';
2
+
3
+ const nodePath = require('node:path');
4
+ function loadPulsec() {
5
+ if (!__dirname.includes(`${nodePath.sep}node_modules${nodePath.sep}`)) {
6
+ try {
7
+ return require('../../../src/compiler.cjs');
8
+ } catch {
9
+ // fall through to package resolution
10
+ }
11
+ }
12
+ return require('pulsec');
13
+ }
14
+
15
+ const { compile } = loadPulsec();
16
+
17
+ const SKIP_QUERIES = ['raw', 'url', 'worker', 'sharedworker', 'inline', 'init', 'wasm'];
18
+
19
+ function hasSkipQuery(query) {
20
+ if (!query) return false;
21
+ const parts = query.split('&');
22
+ for (let i = 0; i < parts.length; i++) {
23
+ const eq = parts[i].indexOf('=');
24
+ const key = eq >= 0 ? parts[i].slice(0, eq) : parts[i];
25
+ if (SKIP_QUERIES.includes(key)) return true;
26
+ }
27
+ return false;
28
+ }
29
+
30
+ function isTransformablePath(cleanId, skipPlainJs) {
31
+ const len = cleanId.length;
32
+ if (len < 3) return false;
33
+ // Fast suffix check without allocating a lowercased string on every call.
34
+ const c1 = cleanId.charCodeAt(len - 1) | 32;
35
+ const c2 = cleanId.charCodeAt(len - 2) | 32;
36
+ const c3 = cleanId.charCodeAt(len - 3) | 32;
37
+ // .ts
38
+ if (c1 === 115 && c2 === 116 && cleanId.charCodeAt(len - 3) === 46) {
39
+ // Reject .d.ts
40
+ if (len >= 5 && (cleanId.charCodeAt(len - 4) | 32) === 100 && cleanId.charCodeAt(len - 5) === 46) return false;
41
+ return true;
42
+ }
43
+ if (len >= 4 && cleanId.charCodeAt(len - 4) === 46) {
44
+ // .tsx / .jsx
45
+ if (c1 === 120 && c2 === 115 && (c3 === 116 || c3 === 106)) return true;
46
+ // .mts / .cts
47
+ if (c1 === 115 && c2 === 116 && (c3 === 109 || c3 === 99)) {
48
+ if (len >= 6 && (cleanId.charCodeAt(len - 5) | 32) === 100 && cleanId.charCodeAt(len - 6) === 46) return false;
49
+ return true;
50
+ }
51
+ // .mjs / .cjs
52
+ if (!skipPlainJs && c1 === 115 && c2 === 106 && (c3 === 109 || c3 === 99)) return true;
53
+ }
54
+ // .js
55
+ if (!skipPlainJs && c1 === 115 && c2 === 106 && cleanId.charCodeAt(len - 3) === 46) return true;
56
+ return false;
57
+ }
58
+
59
+ function offsetToLineColumn(source, offset) {
60
+ if (typeof offset !== 'number' || offset < 0) return { line: 1, column: 0 };
61
+ const limit = Math.min(offset, source.length);
62
+ let line = 1;
63
+ let lastNewline = -1;
64
+ for (let i = 0; i < limit; i++) {
65
+ if (source.charCodeAt(i) === 10) {
66
+ line++;
67
+ lastNewline = i;
68
+ }
69
+ }
70
+ return { line, column: limit - lastNewline - 1 };
71
+ }
72
+
73
+ function compileFilter(matcher) {
74
+ if (!matcher) return null;
75
+ if (typeof matcher === 'function') return matcher;
76
+ const list = Array.isArray(matcher) ? matcher : [matcher];
77
+ return id => {
78
+ for (let i = 0; i < list.length; i++) {
79
+ const m = list[i];
80
+ if (m instanceof RegExp) {
81
+ if (m.global || m.sticky) m.lastIndex = 0;
82
+ if (m.test(id)) return true;
83
+ } else if (typeof m === 'string' && id.includes(m)) {
84
+ return true;
85
+ }
86
+ }
87
+ return false;
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Creates a high-throughput, LRU-cached pulsec transform function shared by
93
+ * `@pulsec/vite` and `@pulsec/vitest`.
94
+ */
95
+ function createPulsecTransform(options = {}) {
96
+ const skipPlainJs = options.skipPlainJs !== false;
97
+ const includeNodeModules = Boolean(options.includeNodeModules);
98
+ const includeFilter = compileFilter(options.include);
99
+ const excludeFilter = compileFilter(options.exclude);
100
+ const maxCacheSize = options.maxCacheSize ?? 512;
101
+ const cache = maxCacheSize > 0 ? new Map() : null;
102
+ const stats = { hits: 0, misses: 0, skipped: 0 };
103
+
104
+ let sourceMapEnabled = options.sourceMap ?? true;
105
+ let delegateJsx = false;
106
+ const compileBase = {
107
+ mode: options.mode || 'transform',
108
+ target: options.target || 'esnext',
109
+ module: options.module || 'preserve',
110
+ jsx: options.jsx,
111
+ experimentalDecorators: options.experimentalDecorators,
112
+ emitDecoratorMetadata: options.emitDecoratorMetadata,
113
+ };
114
+ const isDefaultTransform =
115
+ compileBase.mode === 'transform' &&
116
+ compileBase.target === 'esnext' &&
117
+ compileBase.module === 'preserve' &&
118
+ compileBase.jsx === undefined &&
119
+ !compileBase.experimentalDecorators &&
120
+ !compileBase.emitDecoratorMetadata;
121
+ const reusableMappedOpts = { file: '', sourceMap: true };
122
+ const reusablePlainOpts = { file: '' };
123
+
124
+ function setSourceMap(enabled) {
125
+ if (options.sourceMap === undefined) {
126
+ sourceMapEnabled = Boolean(enabled);
127
+ }
128
+ }
129
+
130
+ function setDelegateJsx(enabled) {
131
+ if (options.jsx === undefined) {
132
+ delegateJsx = Boolean(enabled);
133
+ }
134
+ }
135
+
136
+ function shouldTransform(id) {
137
+ if (typeof id !== 'string' || id.length === 0 || id.charCodeAt(0) === 0) {
138
+ return null;
139
+ }
140
+ const qIdx = id.indexOf('?');
141
+ let cleanId = id;
142
+ if (qIdx >= 0) {
143
+ const query = id.slice(qIdx + 1);
144
+ if (hasSkipQuery(query)) return null;
145
+ cleanId = id.slice(0, qIdx);
146
+ }
147
+
148
+ if (!includeNodeModules && cleanId.includes('node_modules') && (cleanId.includes('/node_modules/') || cleanId.includes('\\node_modules\\'))) {
149
+ return null;
150
+ }
151
+ if (!isTransformablePath(cleanId, skipPlainJs)) {
152
+ return null;
153
+ }
154
+ if ((cleanId.charCodeAt(cleanId.length - 1) | 32) === 120) {
155
+ if (delegateJsx) return null;
156
+ if (options.jsx === undefined && hasCustomTsconfigJsxImportSourceForFile(cleanId)) {
157
+ return null;
158
+ }
159
+ }
160
+ if (excludeFilter && excludeFilter(cleanId)) return null;
161
+ if (includeFilter && !includeFilter(cleanId)) return null;
162
+ return cleanId;
163
+ }
164
+
165
+ function cloneOutput(out) {
166
+ const map = out.map && typeof out.map === 'object'
167
+ ? {
168
+ ...out.map,
169
+ ...(Array.isArray(out.map.sources) ? { sources: out.map.sources.slice() } : null),
170
+ ...(Array.isArray(out.map.sourcesContent) ? { sourcesContent: out.map.sourcesContent.slice() } : null),
171
+ ...(Array.isArray(out.map.names) ? { names: out.map.names.slice() } : null),
172
+ }
173
+ : out.map;
174
+ return { code: out.code, map };
175
+ }
176
+
177
+ function transform(code, id) {
178
+ const cleanId = shouldTransform(id);
179
+ if (!cleanId) {
180
+ stats.skipped++;
181
+ return null;
182
+ }
183
+
184
+ const useMap = Boolean(sourceMapEnabled);
185
+ const cacheKey = cache ? `${cleanId}\0${useMap ? 1 : 0}` : null;
186
+ if (cache && cacheKey) {
187
+ const entry = cache.get(cacheKey);
188
+ if (entry && entry.code === code) {
189
+ // Refresh LRU order and return an isolated copy.
190
+ cache.delete(cacheKey);
191
+ cache.set(cacheKey, entry);
192
+ stats.hits++;
193
+ return cloneOutput(entry.output);
194
+ }
195
+ stats.misses++;
196
+ }
197
+
198
+ // Preserve undefined for unset optional flags so pulsec hits its fastest native V8 path.
199
+ let compileOpts;
200
+ if (isDefaultTransform) {
201
+ compileOpts = useMap ? reusableMappedOpts : reusablePlainOpts;
202
+ compileOpts.file = cleanId;
203
+ } else if (compileBase.mode === 'strip') {
204
+ compileOpts = { file: cleanId, mode: 'strip', target: 'esnext', module: 'preserve' };
205
+ } else {
206
+ compileOpts = {
207
+ file: cleanId,
208
+ mode: compileBase.mode,
209
+ target: compileBase.target,
210
+ module: compileBase.module,
211
+ };
212
+ if (compileBase.jsx !== undefined) compileOpts.jsx = compileBase.jsx;
213
+ if (useMap) compileOpts.sourceMap = true;
214
+ if (compileBase.experimentalDecorators) compileOpts.experimentalDecorators = true;
215
+ if (compileBase.emitDecoratorMetadata) compileOpts.emitDecoratorMetadata = true;
216
+ }
217
+ const res = compile(code, compileOpts);
218
+
219
+ if (res.code === null) {
220
+ const first = (res.diagnostics && res.diagnostics[0]) || { code: 'COMPILE_ERROR', message: 'Compilation failed', start: 0 };
221
+ const loc = offsetToLineColumn(code, first.start);
222
+ const err = new Error(`[pulsec] ${first.code}: ${first.message} (${cleanId}:${loc.line}:${loc.column})`);
223
+ err.id = cleanId;
224
+ err.loc = { file: cleanId, line: loc.line, column: loc.column };
225
+ err.diagnostics = res.diagnostics;
226
+ throw err;
227
+ }
228
+
229
+ const output = {
230
+ code: res.code,
231
+ map: useMap ? (res.sourceMap || { mappings: '' }) : { mappings: '' },
232
+ };
233
+
234
+ if (cache && cacheKey) {
235
+ if (cache.has(cacheKey)) {
236
+ cache.delete(cacheKey);
237
+ } else if (cache.size >= maxCacheSize) {
238
+ const oldestKey = cache.keys().next().value;
239
+ if (oldestKey !== undefined) cache.delete(oldestKey);
240
+ }
241
+ cache.set(cacheKey, { code, output });
242
+ return cloneOutput(output);
243
+ }
244
+
245
+ return output;
246
+ }
247
+
248
+ return {
249
+ transform,
250
+ shouldTransform,
251
+ setSourceMap,
252
+ setDelegateJsx,
253
+ stats,
254
+ clearCache() {
255
+ if (cache) cache.clear();
256
+ stats.hits = 0;
257
+ stats.misses = 0;
258
+ stats.skipped = 0;
259
+ },
260
+ };
261
+ }
262
+
263
+ const fs = require('node:fs');
264
+ const path = require('node:path');
265
+
266
+ /**
267
+ * Lightweight check for non-react `jsxImportSource` across `tsconfig.json` and its
268
+ * `extends` chain without loading the TypeScript compiler.
269
+ */
270
+ function resolveTsconfigExtends(fromDir, spec) {
271
+ const isRelOrAbs = spec.startsWith('./') || spec.startsWith('../') || spec === '.' || spec === '..' || path.isAbsolute(spec);
272
+ if (isRelOrAbs) {
273
+ const candidate = path.resolve(fromDir, spec);
274
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;
275
+ if (!candidate.endsWith('.json') && fs.existsSync(`${candidate}.json`) && fs.statSync(`${candidate}.json`).isFile()) {
276
+ return `${candidate}.json`;
277
+ }
278
+ const dirCfg = path.join(candidate, 'tsconfig.json');
279
+ if (fs.existsSync(dirCfg) && fs.statSync(dirCfg).isFile()) return dirCfg;
280
+ return null;
281
+ }
282
+ const pkgs = spec.endsWith('.json') ? [spec] : [spec, `${spec}.json`, `${spec}/tsconfig.json`];
283
+ for (let i = 0; i < pkgs.length; i++) {
284
+ try {
285
+ return require.resolve(pkgs[i], { paths: [fromDir] });
286
+ } catch {
287
+ // try next
288
+ }
289
+ }
290
+ return null;
291
+ }
292
+
293
+ function stripJsonc(input) {
294
+ let out = '';
295
+ const len = input.length;
296
+ let i = 0;
297
+ while (i < len) {
298
+ const ch = input[i];
299
+ if (ch === '"') {
300
+ const start = i++;
301
+ while (i < len && input[i] !== '"') {
302
+ if (input[i] === '\\') i += 2;
303
+ else i++;
304
+ }
305
+ if (i < len) i++;
306
+ out += input.slice(start, i);
307
+ continue;
308
+ }
309
+ if (ch === '/' && input[i + 1] === '/') {
310
+ i += 2;
311
+ while (i < len && input[i] !== '\n' && input[i] !== '\r') i++;
312
+ continue;
313
+ }
314
+ if (ch === '/' && input[i + 1] === '*') {
315
+ const end = input.indexOf('*/', i + 2);
316
+ i = end < 0 ? len : end + 2;
317
+ continue;
318
+ }
319
+ out += ch;
320
+ i++;
321
+ }
322
+ // Remove trailing commas before `}` or `]` outside strings.
323
+ let cleaned = '';
324
+ const clen = out.length;
325
+ i = 0;
326
+ while (i < clen) {
327
+ const ch = out[i];
328
+ if (ch === '"') {
329
+ const start = i++;
330
+ while (i < clen && out[i] !== '"') {
331
+ if (out[i] === '\\') i += 2;
332
+ else i++;
333
+ }
334
+ if (i < clen) i++;
335
+ cleaned += out.slice(start, i);
336
+ continue;
337
+ }
338
+ if (ch === ',') {
339
+ let j = i + 1;
340
+ while (j < clen && (out[j] === ' ' || out[j] === '\t' || out[j] === '\n' || out[j] === '\r')) j++;
341
+ if (out[j] === '}' || out[j] === ']') {
342
+ i++;
343
+ continue;
344
+ }
345
+ }
346
+ cleaned += ch;
347
+ i++;
348
+ }
349
+ return cleaned;
350
+ }
351
+
352
+ function readTsconfigJsxImportSource(configPath, seen) {
353
+ try {
354
+ const real = fs.realpathSync(configPath);
355
+ if (seen.has(real)) return null;
356
+ seen.add(real);
357
+ const parsed = JSON.parse(stripJsonc(fs.readFileSync(real, 'utf8')));
358
+ if (!parsed || typeof parsed !== 'object') return null;
359
+ if (parsed.compilerOptions && typeof parsed.compilerOptions.jsxImportSource === 'string') {
360
+ return parsed.compilerOptions.jsxImportSource;
361
+ }
362
+ if (parsed.extends) {
363
+ const specs = Array.isArray(parsed.extends) ? parsed.extends : [parsed.extends];
364
+ for (let i = specs.length - 1; i >= 0; i--) {
365
+ if (typeof specs[i] !== 'string') continue;
366
+ const nextPath = resolveTsconfigExtends(path.dirname(real), specs[i]);
367
+ if (nextPath) {
368
+ const inherited = readTsconfigJsxImportSource(nextPath, seen);
369
+ if (inherited) return inherited;
370
+ }
371
+ }
372
+ }
373
+ } catch {
374
+ return null;
375
+ }
376
+ return null;
377
+ }
378
+
379
+ const dirJsxSourceCache = new Map();
380
+
381
+ function hasCustomTsconfigJsxImportSource(rootDir) {
382
+ try {
383
+ const tcPath = path.join(rootDir || process.cwd(), 'tsconfig.json');
384
+ if (!fs.existsSync(tcPath)) return false;
385
+ const src = readTsconfigJsxImportSource(tcPath, new Set());
386
+ return Boolean(src && src !== 'react');
387
+ } catch {
388
+ return false;
389
+ }
390
+ }
391
+
392
+ function hasCustomTsconfigJsxImportSourceForFile(filePath) {
393
+ if (!path.isAbsolute(filePath)) return false;
394
+ const startDir = path.dirname(filePath);
395
+ const cached = dirJsxSourceCache.get(startDir);
396
+ if (cached !== undefined) return cached;
397
+
398
+ const visited = [];
399
+ let cur = startDir;
400
+ let custom = false;
401
+ while (true) {
402
+ const hit = dirJsxSourceCache.get(cur);
403
+ if (hit !== undefined) {
404
+ custom = hit;
405
+ break;
406
+ }
407
+ visited.push(cur);
408
+ const tcPath = path.join(cur, 'tsconfig.json');
409
+ if (fs.existsSync(tcPath)) {
410
+ const src = readTsconfigJsxImportSource(tcPath, new Set());
411
+ custom = Boolean(src && src !== 'react');
412
+ break;
413
+ }
414
+ const parent = path.dirname(cur);
415
+ if (parent === cur) break;
416
+ cur = parent;
417
+ }
418
+ for (let i = 0; i < visited.length; i++) {
419
+ dirJsxSourceCache.set(visited[i], custom);
420
+ }
421
+ return custom;
422
+ }
423
+
424
+ module.exports = {
425
+ createPulsecTransform,
426
+ isTransformablePath,
427
+ hasSkipQuery,
428
+ offsetToLineColumn,
429
+ hasCustomTsconfigJsxImportSource,
430
+ };