@wyw-in-js/vite 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Anton Evzhakov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/esm/index.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * This file contains a Vite loader for wyw-in-js.
3
+ * It uses the transform.ts function to generate class names from source code,
4
+ * returns transformed code without template literals and attaches generated source maps
5
+ */
6
+
7
+ import { existsSync } from 'fs';
8
+ import path from 'path';
9
+ import { createFilter } from '@rollup/pluginutils';
10
+ import { optimizeDeps } from 'vite';
11
+ import { logger, syncResolve } from '@wyw-in-js/shared';
12
+ import { createFileReporter, getFileIdx, slugify, transform, TransformCacheCollection } from '@wyw-in-js/transform';
13
+ export default function wywInJS({
14
+ debug,
15
+ include,
16
+ exclude,
17
+ sourceMap,
18
+ preprocessor,
19
+ ...rest
20
+ } = {}) {
21
+ const filter = createFilter(include, exclude);
22
+ const cssLookup = {};
23
+ const cssFileLookup = {};
24
+ let config;
25
+ let devServer;
26
+ const {
27
+ emitter,
28
+ onDone
29
+ } = createFileReporter(debug ?? false);
30
+
31
+ // <dependency id, targets>
32
+ const targets = [];
33
+ const cache = new TransformCacheCollection();
34
+ return {
35
+ name: 'wyw-in-js',
36
+ enforce: 'post',
37
+ buildEnd() {
38
+ onDone(process.cwd());
39
+ },
40
+ configResolved(resolvedConfig) {
41
+ config = resolvedConfig;
42
+ },
43
+ configureServer(_server) {
44
+ devServer = _server;
45
+ },
46
+ load(url) {
47
+ const [id] = url.split('?', 1);
48
+ return cssLookup[id];
49
+ },
50
+ /* eslint-disable-next-line consistent-return */
51
+ resolveId(importeeUrl) {
52
+ const [id] = importeeUrl.split('?', 1);
53
+ if (cssLookup[id]) return id;
54
+ return cssFileLookup[id];
55
+ },
56
+ handleHotUpdate(ctx) {
57
+ // it's module, so just transform it
58
+ if (ctx.modules.length) return ctx.modules;
59
+
60
+ // Select affected modules of changed dependency
61
+ const affected = targets.filter(x =>
62
+ // file is dependency of any target
63
+ x.dependencies.some(dep => dep === ctx.file) ||
64
+ // or changed module is a dependency of any target
65
+ x.dependencies.some(dep => ctx.modules.some(m => m.file === dep)));
66
+ const deps = affected.flatMap(target => target.dependencies);
67
+
68
+ // eslint-disable-next-line no-restricted-syntax
69
+ for (const depId of deps) {
70
+ cache.invalidateForFile(depId);
71
+ }
72
+ return affected.map(target => devServer.moduleGraph.getModuleById(target.id)).concat(ctx.modules).filter(m => !!m);
73
+ },
74
+ async transform(code, url) {
75
+ const [id] = url.split('?', 1);
76
+
77
+ // Do not transform ignored and generated files
78
+ if (url.includes('node_modules') || !filter(url) || id in cssLookup) return;
79
+ const log = logger.extend('vite').extend(getFileIdx(id));
80
+ log('transform %s', id);
81
+ const asyncResolve = async (what, importer, stack) => {
82
+ const resolved = await this.resolve(what, importer);
83
+ if (resolved) {
84
+ if (resolved.external) {
85
+ // If module is marked as external, Rollup will not resolve it,
86
+ // so we need to resolve it ourselves with default resolver
87
+ const resolvedId = syncResolve(what, importer, stack);
88
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
89
+ return resolvedId;
90
+ }
91
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
92
+ // Vite adds param like `?v=667939b3` to cached modules
93
+ const resolvedId = resolved.id.split('?', 1)[0];
94
+ if (resolvedId.startsWith('\0')) {
95
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
96
+ // https://rollupjs.org/guide/en/#outputexports
97
+ return null;
98
+ }
99
+ if (!existsSync(resolvedId)) {
100
+ await optimizeDeps(config);
101
+ }
102
+ return resolvedId;
103
+ }
104
+ log("resolve ❌ '%s'@'%s", what, importer);
105
+ throw new Error(`Could not resolve ${what}`);
106
+ };
107
+ const transformServices = {
108
+ options: {
109
+ filename: id,
110
+ root: process.cwd(),
111
+ preprocessor,
112
+ pluginOptions: rest
113
+ },
114
+ cache,
115
+ eventEmitter: emitter
116
+ };
117
+ const result = await transform(transformServices, code, asyncResolve);
118
+ let {
119
+ cssText,
120
+ dependencies
121
+ } = result;
122
+ if (!cssText) return;
123
+ dependencies ??= [];
124
+ const slug = slugify(cssText);
125
+ const cssFilename = path.normalize(`${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`).replace(/\\/g, path.posix.sep);
126
+ const cssRelativePath = path.relative(config.root, cssFilename).replace(/\\/g, path.posix.sep);
127
+ const cssId = `/${cssRelativePath}`;
128
+ if (sourceMap && result.cssSourceMapText) {
129
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
130
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
131
+ }
132
+ cssLookup[cssFilename] = cssText;
133
+ cssFileLookup[cssId] = cssFilename;
134
+ result.code += `\nimport ${JSON.stringify(cssFilename)};\n`;
135
+ if (devServer?.moduleGraph) {
136
+ const module = devServer.moduleGraph.getModuleById(cssId);
137
+ if (module) {
138
+ devServer.moduleGraph.invalidateModule(module);
139
+ module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
140
+ }
141
+ }
142
+ for (let i = 0, end = dependencies.length; i < end; i++) {
143
+ // eslint-disable-next-line no-await-in-loop
144
+ const depModule = await this.resolve(dependencies[i], url, {
145
+ isEntry: false
146
+ });
147
+ if (depModule) dependencies[i] = depModule.id;
148
+ }
149
+ const target = targets.find(t => t.id === id);
150
+ if (!target) targets.push({
151
+ id,
152
+ dependencies
153
+ });else target.dependencies = dependencies;
154
+ /* eslint-disable-next-line consistent-return */
155
+ return {
156
+ code: result.code,
157
+ map: result.sourceMap
158
+ };
159
+ }
160
+ };
161
+ }
162
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["existsSync","path","createFilter","optimizeDeps","logger","syncResolve","createFileReporter","getFileIdx","slugify","transform","TransformCacheCollection","wywInJS","debug","include","exclude","sourceMap","preprocessor","rest","filter","cssLookup","cssFileLookup","config","devServer","emitter","onDone","targets","cache","name","enforce","buildEnd","process","cwd","configResolved","resolvedConfig","configureServer","_server","load","url","id","split","resolveId","importeeUrl","handleHotUpdate","ctx","modules","length","affected","x","dependencies","some","dep","file","m","deps","flatMap","target","depId","invalidateForFile","map","moduleGraph","getModuleById","concat","code","includes","log","extend","asyncResolve","what","importer","stack","resolved","resolve","external","resolvedId","startsWith","Error","transformServices","options","filename","root","pluginOptions","eventEmitter","result","cssText","slug","cssFilename","normalize","replace","posix","sep","cssRelativePath","relative","cssId","cssSourceMapText","Buffer","from","toString","JSON","stringify","module","invalidateModule","lastHMRTimestamp","lastInvalidationTimestamp","Date","now","i","end","depModule","isEntry","find","t","push"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Vite loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { existsSync } from 'fs';\nimport path from 'path';\n\nimport type { FilterPattern } from '@rollup/pluginutils';\nimport { createFilter } from '@rollup/pluginutils';\nimport { optimizeDeps } from 'vite';\nimport type { ModuleNode, Plugin, ResolvedConfig, ViteDevServer } from 'vite';\n\nimport { logger, syncResolve } from '@wyw-in-js/shared';\nimport type {\n IFileReporterOptions,\n PluginOptions,\n Preprocessor,\n} from '@wyw-in-js/transform';\nimport {\n createFileReporter,\n getFileIdx,\n slugify,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype VitePluginOptions = {\n debug?: IFileReporterOptions | false | null | undefined;\n exclude?: FilterPattern;\n include?: FilterPattern;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport { Plugin };\n\nexport default function wywInJS({\n debug,\n include,\n exclude,\n sourceMap,\n preprocessor,\n ...rest\n}: VitePluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cssFileLookup: { [key: string]: string } = {};\n let config: ResolvedConfig;\n let devServer: ViteDevServer;\n\n const { emitter, onDone } = createFileReporter(debug ?? false);\n\n // <dependency id, targets>\n const targets: { dependencies: string[]; id: string }[] = [];\n const cache = new TransformCacheCollection();\n return {\n name: 'wyw-in-js',\n enforce: 'post',\n buildEnd() {\n onDone(process.cwd());\n },\n configResolved(resolvedConfig: ResolvedConfig) {\n config = resolvedConfig;\n },\n configureServer(_server) {\n devServer = _server;\n },\n load(url: string) {\n const [id] = url.split('?', 1);\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importeeUrl: string) {\n const [id] = importeeUrl.split('?', 1);\n if (cssLookup[id]) return id;\n return cssFileLookup[id];\n },\n handleHotUpdate(ctx) {\n // it's module, so just transform it\n if (ctx.modules.length) return ctx.modules;\n\n // Select affected modules of changed dependency\n const affected = targets.filter(\n (x) =>\n // file is dependency of any target\n x.dependencies.some((dep) => dep === ctx.file) ||\n // or changed module is a dependency of any target\n x.dependencies.some((dep) => ctx.modules.some((m) => m.file === dep))\n );\n const deps = affected.flatMap((target) => target.dependencies);\n\n // eslint-disable-next-line no-restricted-syntax\n for (const depId of deps) {\n cache.invalidateForFile(depId);\n }\n\n return affected\n .map((target) => devServer.moduleGraph.getModuleById(target.id))\n .concat(ctx.modules)\n .filter((m): m is ModuleNode => !!m);\n },\n async transform(code: string, url: string) {\n const [id] = url.split('?', 1);\n\n // Do not transform ignored and generated files\n if (url.includes('node_modules') || !filter(url) || id in cssLookup)\n return;\n\n const log = logger.extend('vite').extend(getFileIdx(id));\n\n log('transform %s', id);\n\n const asyncResolve = async (\n what: string,\n importer: string,\n stack: string[]\n ) => {\n const resolved = await this.resolve(what, importer);\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n const resolvedId = syncResolve(what, importer, stack);\n log(\"resolve ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n return resolvedId;\n }\n\n log(\"resolve ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?', 1)[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n if (!existsSync(resolvedId)) {\n await optimizeDeps(config);\n }\n\n return resolvedId;\n }\n\n log(\"resolve ❌ '%s'@'%s\", what, importer);\n throw new Error(`Could not resolve ${what}`);\n };\n\n const transformServices = {\n options: {\n filename: id,\n root: process.cwd(),\n preprocessor,\n pluginOptions: rest,\n },\n cache,\n eventEmitter: emitter,\n };\n\n const result = await transform(transformServices, code, asyncResolve);\n\n let { cssText, dependencies } = result;\n\n if (!cssText) return;\n dependencies ??= [];\n\n const slug = slugify(cssText);\n\n const cssFilename = path\n .normalize(`${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`)\n .replace(/\\\\/g, path.posix.sep);\n\n const cssRelativePath = path\n .relative(config.root, cssFilename)\n .replace(/\\\\/g, path.posix.sep);\n\n const cssId = `/${cssRelativePath}`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[cssFilename] = cssText;\n cssFileLookup[cssId] = cssFilename;\n\n result.code += `\\nimport ${JSON.stringify(cssFilename)};\\n`;\n if (devServer?.moduleGraph) {\n const module = devServer.moduleGraph.getModuleById(cssId);\n\n if (module) {\n devServer.moduleGraph.invalidateModule(module);\n module.lastHMRTimestamp =\n module.lastInvalidationTimestamp || Date.now();\n }\n }\n\n for (let i = 0, end = dependencies.length; i < end; i++) {\n // eslint-disable-next-line no-await-in-loop\n const depModule = await this.resolve(dependencies[i], url, {\n isEntry: false,\n });\n if (depModule) dependencies[i] = depModule.id;\n }\n const target = targets.find((t) => t.id === id);\n if (!target) targets.push({ id, dependencies });\n else target.dependencies = dependencies;\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n },\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,UAAU,QAAQ,IAAI;AAC/B,OAAOC,IAAI,MAAM,MAAM;AAGvB,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,YAAY,QAAQ,MAAM;AAGnC,SAASC,MAAM,EAAEC,WAAW,QAAQ,mBAAmB;AAMvD,SACEC,kBAAkB,EAClBC,UAAU,EACVC,OAAO,EACPC,SAAS,EACTC,wBAAwB,QACnB,sBAAsB;AAY7B,eAAe,SAASC,OAAOA,CAAC;EAC9BC,KAAK;EACLC,OAAO;EACPC,OAAO;EACPC,SAAS;EACTC,YAAY;EACZ,GAAGC;AACc,CAAC,GAAG,CAAC,CAAC,EAAU;EACjC,MAAMC,MAAM,GAAGhB,YAAY,CAACW,OAAO,EAAEC,OAAO,CAAC;EAC7C,MAAMK,SAAoC,GAAG,C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,GAAG1D,YAAY,CAACH,MAAM,EAAE4D,CAAC,GAAGC,GAAG,EAAED,CAAC,EAAE,EAAE;QACvD;QACA,MAAME,SAAS,GAAG,MAAM,IAAI,CAACpC,OAAO,CAACvB,YAAY,CAACyD,CAAC,CAAC,EAAEpE,GAAG,EAAE;UACzDuE,OAAO,EAAE;QACX,CAAC,CAAC;QACF,IAAID,SAAS,EAAE3D,YAAY,CAACyD,CAAC,CAAC,GAAGE,SAAS,CAACrE,EAAE;MAC/C;MACA,MAAMiB,MAAM,GAAG9B,OAAO,CAACoF,IAAI,CAAEC,CAAC,IAAKA,CAAC,CAACxE,EAAE,KAAKA,EAAE,CAAC;MAC/C,IAAI,CAACiB,MAAM,EAAE9B,OAAO,CAACsF,IAAI,CAAC;QAAEzE,EAAE;QAAEU;MAAa,CAAC,CAAC,CAAC,KAC3CO,MAAM,CAACP,YAAY,GAAGA,YAAY;MACvC;MACA,OAAO;QAAEc,IAAI,EAAEoB,MAAM,CAACpB,IAAI;QAAEJ,GAAG,EAAEwB,MAAM,CAACnE;MAAU,CAAC;IACrD;EACF,CAAC;AACH"}
package/lib/index.js ADDED
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = wywInJS;
7
+ var _fs = require("fs");
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _pluginutils = require("@rollup/pluginutils");
10
+ var _vite = require("vite");
11
+ var _shared = require("@wyw-in-js/shared");
12
+ var _transform = require("@wyw-in-js/transform");
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+ /**
15
+ * This file contains a Vite loader for wyw-in-js.
16
+ * It uses the transform.ts function to generate class names from source code,
17
+ * returns transformed code without template literals and attaches generated source maps
18
+ */
19
+
20
+ function wywInJS({
21
+ debug,
22
+ include,
23
+ exclude,
24
+ sourceMap,
25
+ preprocessor,
26
+ ...rest
27
+ } = {}) {
28
+ const filter = (0, _pluginutils.createFilter)(include, exclude);
29
+ const cssLookup = {};
30
+ const cssFileLookup = {};
31
+ let config;
32
+ let devServer;
33
+ const {
34
+ emitter,
35
+ onDone
36
+ } = (0, _transform.createFileReporter)(debug !== null && debug !== void 0 ? debug : false);
37
+
38
+ // <dependency id, targets>
39
+ const targets = [];
40
+ const cache = new _transform.TransformCacheCollection();
41
+ return {
42
+ name: 'wyw-in-js',
43
+ enforce: 'post',
44
+ buildEnd() {
45
+ onDone(process.cwd());
46
+ },
47
+ configResolved(resolvedConfig) {
48
+ config = resolvedConfig;
49
+ },
50
+ configureServer(_server) {
51
+ devServer = _server;
52
+ },
53
+ load(url) {
54
+ const [id] = url.split('?', 1);
55
+ return cssLookup[id];
56
+ },
57
+ /* eslint-disable-next-line consistent-return */
58
+ resolveId(importeeUrl) {
59
+ const [id] = importeeUrl.split('?', 1);
60
+ if (cssLookup[id]) return id;
61
+ return cssFileLookup[id];
62
+ },
63
+ handleHotUpdate(ctx) {
64
+ // it's module, so just transform it
65
+ if (ctx.modules.length) return ctx.modules;
66
+
67
+ // Select affected modules of changed dependency
68
+ const affected = targets.filter(x =>
69
+ // file is dependency of any target
70
+ x.dependencies.some(dep => dep === ctx.file) ||
71
+ // or changed module is a dependency of any target
72
+ x.dependencies.some(dep => ctx.modules.some(m => m.file === dep)));
73
+ const deps = affected.flatMap(target => target.dependencies);
74
+
75
+ // eslint-disable-next-line no-restricted-syntax
76
+ for (const depId of deps) {
77
+ cache.invalidateForFile(depId);
78
+ }
79
+ return affected.map(target => devServer.moduleGraph.getModuleById(target.id)).concat(ctx.modules).filter(m => !!m);
80
+ },
81
+ async transform(code, url) {
82
+ var _dependencies, _devServer;
83
+ const [id] = url.split('?', 1);
84
+
85
+ // Do not transform ignored and generated files
86
+ if (url.includes('node_modules') || !filter(url) || id in cssLookup) return;
87
+ const log = _shared.logger.extend('vite').extend((0, _transform.getFileIdx)(id));
88
+ log('transform %s', id);
89
+ const asyncResolve = async (what, importer, stack) => {
90
+ const resolved = await this.resolve(what, importer);
91
+ if (resolved) {
92
+ if (resolved.external) {
93
+ // If module is marked as external, Rollup will not resolve it,
94
+ // so we need to resolve it ourselves with default resolver
95
+ const resolvedId = (0, _shared.syncResolve)(what, importer, stack);
96
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
97
+ return resolvedId;
98
+ }
99
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
100
+ // Vite adds param like `?v=667939b3` to cached modules
101
+ const resolvedId = resolved.id.split('?', 1)[0];
102
+ if (resolvedId.startsWith('\0')) {
103
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
104
+ // https://rollupjs.org/guide/en/#outputexports
105
+ return null;
106
+ }
107
+ if (!(0, _fs.existsSync)(resolvedId)) {
108
+ await (0, _vite.optimizeDeps)(config);
109
+ }
110
+ return resolvedId;
111
+ }
112
+ log("resolve ❌ '%s'@'%s", what, importer);
113
+ throw new Error(`Could not resolve ${what}`);
114
+ };
115
+ const transformServices = {
116
+ options: {
117
+ filename: id,
118
+ root: process.cwd(),
119
+ preprocessor,
120
+ pluginOptions: rest
121
+ },
122
+ cache,
123
+ eventEmitter: emitter
124
+ };
125
+ const result = await (0, _transform.transform)(transformServices, code, asyncResolve);
126
+ let {
127
+ cssText,
128
+ dependencies
129
+ } = result;
130
+ if (!cssText) return;
131
+ (_dependencies = dependencies) !== null && _dependencies !== void 0 ? _dependencies : dependencies = [];
132
+ const slug = (0, _transform.slugify)(cssText);
133
+ const cssFilename = _path.default.normalize(`${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`).replace(/\\/g, _path.default.posix.sep);
134
+ const cssRelativePath = _path.default.relative(config.root, cssFilename).replace(/\\/g, _path.default.posix.sep);
135
+ const cssId = `/${cssRelativePath}`;
136
+ if (sourceMap && result.cssSourceMapText) {
137
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
138
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
139
+ }
140
+ cssLookup[cssFilename] = cssText;
141
+ cssFileLookup[cssId] = cssFilename;
142
+ result.code += `\nimport ${JSON.stringify(cssFilename)};\n`;
143
+ if ((_devServer = devServer) !== null && _devServer !== void 0 && _devServer.moduleGraph) {
144
+ const module = devServer.moduleGraph.getModuleById(cssId);
145
+ if (module) {
146
+ devServer.moduleGraph.invalidateModule(module);
147
+ module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
148
+ }
149
+ }
150
+ for (let i = 0, end = dependencies.length; i < end; i++) {
151
+ // eslint-disable-next-line no-await-in-loop
152
+ const depModule = await this.resolve(dependencies[i], url, {
153
+ isEntry: false
154
+ });
155
+ if (depModule) dependencies[i] = depModule.id;
156
+ }
157
+ const target = targets.find(t => t.id === id);
158
+ if (!target) targets.push({
159
+ id,
160
+ dependencies
161
+ });else target.dependencies = dependencies;
162
+ /* eslint-disable-next-line consistent-return */
163
+ return {
164
+ code: result.code,
165
+ map: result.sourceMap
166
+ };
167
+ }
168
+ };
169
+ }
170
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_fs","require","_path","_interopRequireDefault","_pluginutils","_vite","_shared","_transform","obj","__esModule","default","wywInJS","debug","include","exclude","sourceMap","preprocessor","rest","filter","createFilter","cssLookup","cssFileLookup","config","devServer","emitter","onDone","createFileReporter","targets","cache","TransformCacheCollection","name","enforce","buildEnd","process","cwd","configResolved","resolvedConfig","configureServer","_server","load","url","id","split","resolveId","importeeUrl","handleHotUpdate","ctx","modules","length","affected","x","dependencies","some","dep","file","m","deps","flatMap","target","depId","invalidateForFile","map","moduleGraph","getModuleById","concat","transform","code","_dependencies","_devServer","includes","log","logger","extend","getFileIdx","asyncResolve","what","importer","stack","resolved","resolve","external","resolvedId","syncResolve","startsWith","existsSync","optimizeDeps","Error","transformServices","options","filename","root","pluginOptions","eventEmitter","result","cssText","slug","slugify","cssFilename","path","normalize","replace","posix","sep","cssRelativePath","relative","cssId","cssSourceMapText","Buffer","from","toString","JSON","stringify","module","invalidateModule","lastHMRTimestamp","lastInvalidationTimestamp","Date","now","i","end","depModule","isEntry","find","t","push"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Vite loader for wyw-in-js.\n * It uses the transform.ts function to generate class names from source code,\n * returns transformed code without template literals and attaches generated source maps\n */\n\nimport { existsSync } from 'fs';\nimport path from 'path';\n\nimport type { FilterPattern } from '@rollup/pluginutils';\nimport { createFilter } from '@rollup/pluginutils';\nimport { optimizeDeps } from 'vite';\nimport type { ModuleNode, Plugin, ResolvedConfig, ViteDevServer } from 'vite';\n\nimport { logger, syncResolve } from '@wyw-in-js/shared';\nimport type {\n IFileReporterOptions,\n PluginOptions,\n Preprocessor,\n} from '@wyw-in-js/transform';\nimport {\n createFileReporter,\n getFileIdx,\n slugify,\n transform,\n TransformCacheCollection,\n} from '@wyw-in-js/transform';\n\ntype VitePluginOptions = {\n debug?: IFileReporterOptions | false | null | undefined;\n exclude?: FilterPattern;\n include?: FilterPattern;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n} & Partial<PluginOptions>;\n\nexport { Plugin };\n\nexport default function wywInJS({\n debug,\n include,\n exclude,\n sourceMap,\n preprocessor,\n ...rest\n}: VitePluginOptions = {}): Plugin {\n const filter = createFilter(include, exclude);\n const cssLookup: { [key: string]: string } = {};\n const cssFileLookup: { [key: string]: string } = {};\n let config: ResolvedConfig;\n let devServer: ViteDevServer;\n\n const { emitter, onDone } = createFileReporter(debug ?? false);\n\n // <dependency id, targets>\n const targets: { dependencies: string[]; id: string }[] = [];\n const cache = new TransformCacheCollection();\n return {\n name: 'wyw-in-js',\n enforce: 'post',\n buildEnd() {\n onDone(process.cwd());\n },\n configResolved(resolvedConfig: ResolvedConfig) {\n config = resolvedConfig;\n },\n configureServer(_server) {\n devServer = _server;\n },\n load(url: string) {\n const [id] = url.split('?', 1);\n return cssLookup[id];\n },\n /* eslint-disable-next-line consistent-return */\n resolveId(importeeUrl: string) {\n const [id] = importeeUrl.split('?', 1);\n if (cssLookup[id]) return id;\n return cssFileLookup[id];\n },\n handleHotUpdate(ctx) {\n // it's module, so just transform it\n if (ctx.modules.length) return ctx.modules;\n\n // Select affected modules of changed dependency\n const affected = targets.filter(\n (x) =>\n // file is dependency of any target\n x.dependencies.some((dep) => dep === ctx.file) ||\n // or changed module is a dependency of any target\n x.dependencies.some((dep) => ctx.modules.some((m) => m.file === dep))\n );\n const deps = affected.flatMap((target) => target.dependencies);\n\n // eslint-disable-next-line no-restricted-syntax\n for (const depId of deps) {\n cache.invalidateForFile(depId);\n }\n\n return affected\n .map((target) => devServer.moduleGraph.getModuleById(target.id))\n .concat(ctx.modules)\n .filter((m): m is ModuleNode => !!m);\n },\n async transform(code: string, url: string) {\n const [id] = url.split('?', 1);\n\n // Do not transform ignored and generated files\n if (url.includes('node_modules') || !filter(url) || id in cssLookup)\n return;\n\n const log = logger.extend('vite').extend(getFileIdx(id));\n\n log('transform %s', id);\n\n const asyncResolve = async (\n what: string,\n importer: string,\n stack: string[]\n ) => {\n const resolved = await this.resolve(what, importer);\n if (resolved) {\n if (resolved.external) {\n // If module is marked as external, Rollup will not resolve it,\n // so we need to resolve it ourselves with default resolver\n const resolvedId = syncResolve(what, importer, stack);\n log(\"resolve ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n return resolvedId;\n }\n\n log(\"resolve ✅ '%s'@'%s -> %O\\n%s\", what, importer, resolved);\n // Vite adds param like `?v=667939b3` to cached modules\n const resolvedId = resolved.id.split('?', 1)[0];\n\n if (resolvedId.startsWith('\\0')) {\n // \\0 is a special character in Rollup that tells Rollup to not include this in the bundle\n // https://rollupjs.org/guide/en/#outputexports\n return null;\n }\n\n if (!existsSync(resolvedId)) {\n await optimizeDeps(config);\n }\n\n return resolvedId;\n }\n\n log(\"resolve ❌ '%s'@'%s\", what, importer);\n throw new Error(`Could not resolve ${what}`);\n };\n\n const transformServices = {\n options: {\n filename: id,\n root: process.cwd(),\n preprocessor,\n pluginOptions: rest,\n },\n cache,\n eventEmitter: emitter,\n };\n\n const result = await transform(transformServices, code, asyncResolve);\n\n let { cssText, dependencies } = result;\n\n if (!cssText) return;\n dependencies ??= [];\n\n const slug = slugify(cssText);\n\n const cssFilename = path\n .normalize(`${id.replace(/\\.[jt]sx?$/, '')}_${slug}.css`)\n .replace(/\\\\/g, path.posix.sep);\n\n const cssRelativePath = path\n .relative(config.root, cssFilename)\n .replace(/\\\\/g, path.posix.sep);\n\n const cssId = `/${cssRelativePath}`;\n\n if (sourceMap && result.cssSourceMapText) {\n const map = Buffer.from(result.cssSourceMapText).toString('base64');\n cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;\n }\n\n cssLookup[cssFilename] = cssText;\n cssFileLookup[cssId] = cssFilename;\n\n result.code += `\\nimport ${JSON.stringify(cssFilename)};\\n`;\n if (devServer?.moduleGraph) {\n const module = devServer.moduleGraph.getModuleById(cssId);\n\n if (module) {\n devServer.moduleGraph.invalidateModule(module);\n module.lastHMRTimestamp =\n module.lastInvalidationTimestamp || Date.now();\n }\n }\n\n for (let i = 0, end = dependencies.length; i < end; i++) {\n // eslint-disable-next-line no-await-in-loop\n const depModule = await this.resolve(dependencies[i], url, {\n isEntry: false,\n });\n if (depModule) dependencies[i] = depModule.id;\n }\n const target = targets.find((t) => t.id === id);\n if (!target) targets.push({ id, dependencies });\n else target.dependencies = dependencies;\n /* eslint-disable-next-line consistent-return */\n return { code: result.code, map: result.sourceMap };\n },\n };\n}\n"],"mappings":";;;;;;AAMA,IAAAA,GAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAC,sBAAA,CAAAF,OAAA;AAGA,IAAAG,YAAA,GAAAH,OAAA;AACA,IAAAI,KAAA,GAAAJ,OAAA;AAGA,IAAAK,OAAA,GAAAL,OAAA;AAMA,IAAAM,UAAA,GAAAN,OAAA;AAM8B,SAAAE,uBAAAK,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF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1.1",
4
+ "dependencies": {
5
+ "@rollup/pluginutils": "^5.0.4",
6
+ "@wyw-in-js/shared": "0.1.1",
7
+ "@wyw-in-js/transform": "0.1.1"
8
+ },
9
+ "devDependencies": {
10
+ "@types/node": "^16.18.55",
11
+ "source-map": "^0.7.4",
12
+ "vite": ">=3.2.7",
13
+ "@wyw-in-js/babel-config": "0.1.1",
14
+ "@wyw-in-js/eslint-config": "0.1.1",
15
+ "@wyw-in-js/jest-preset": "0.1.1",
16
+ "@wyw-in-js/ts-config": "0.1.1"
17
+ },
18
+ "engines": {
19
+ "node": ">=16.0.0"
20
+ },
21
+ "exports": {
22
+ "import": "./esm/index.js",
23
+ "require": "./lib/index.js",
24
+ "types": "./types/index.d.ts"
25
+ },
26
+ "files": [
27
+ "esm/",
28
+ "lib/",
29
+ "types/"
30
+ ],
31
+ "license": "MIT",
32
+ "main": "lib/index.js",
33
+ "module": "esm/index.js",
34
+ "peerDependencies": {
35
+ "vite": ">=3.2.7"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "types": "types/index.d.ts",
41
+ "scripts": {
42
+ "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
43
+ "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
44
+ "build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
45
+ "lint": "eslint --ext .js,.ts ."
46
+ }
47
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This file contains a Vite loader for wyw-in-js.
3
+ * It uses the transform.ts function to generate class names from source code,
4
+ * returns transformed code without template literals and attaches generated source maps
5
+ */
6
+ import type { FilterPattern } from '@rollup/pluginutils';
7
+ import type { Plugin } from 'vite';
8
+ import type { IFileReporterOptions, PluginOptions, Preprocessor } from '@wyw-in-js/transform';
9
+ type VitePluginOptions = {
10
+ debug?: IFileReporterOptions | false | null | undefined;
11
+ exclude?: FilterPattern;
12
+ include?: FilterPattern;
13
+ preprocessor?: Preprocessor;
14
+ sourceMap?: boolean;
15
+ } & Partial<PluginOptions>;
16
+ export { Plugin };
17
+ export default function wywInJS({ debug, include, exclude, sourceMap, preprocessor, ...rest }?: VitePluginOptions): Plugin;
package/types/index.js ADDED
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /**
3
+ * This file contains a Vite loader for wyw-in-js.
4
+ * It uses the transform.ts function to generate class names from source code,
5
+ * returns transformed code without template literals and attaches generated source maps
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const fs_1 = require("fs");
12
+ const path_1 = __importDefault(require("path"));
13
+ const pluginutils_1 = require("@rollup/pluginutils");
14
+ const vite_1 = require("vite");
15
+ const shared_1 = require("@wyw-in-js/shared");
16
+ const transform_1 = require("@wyw-in-js/transform");
17
+ function wywInJS({ debug, include, exclude, sourceMap, preprocessor, ...rest } = {}) {
18
+ const filter = (0, pluginutils_1.createFilter)(include, exclude);
19
+ const cssLookup = {};
20
+ const cssFileLookup = {};
21
+ let config;
22
+ let devServer;
23
+ const { emitter, onDone } = (0, transform_1.createFileReporter)(debug ?? false);
24
+ // <dependency id, targets>
25
+ const targets = [];
26
+ const cache = new transform_1.TransformCacheCollection();
27
+ return {
28
+ name: 'wyw-in-js',
29
+ enforce: 'post',
30
+ buildEnd() {
31
+ onDone(process.cwd());
32
+ },
33
+ configResolved(resolvedConfig) {
34
+ config = resolvedConfig;
35
+ },
36
+ configureServer(_server) {
37
+ devServer = _server;
38
+ },
39
+ load(url) {
40
+ const [id] = url.split('?', 1);
41
+ return cssLookup[id];
42
+ },
43
+ /* eslint-disable-next-line consistent-return */
44
+ resolveId(importeeUrl) {
45
+ const [id] = importeeUrl.split('?', 1);
46
+ if (cssLookup[id])
47
+ return id;
48
+ return cssFileLookup[id];
49
+ },
50
+ handleHotUpdate(ctx) {
51
+ // it's module, so just transform it
52
+ if (ctx.modules.length)
53
+ return ctx.modules;
54
+ // Select affected modules of changed dependency
55
+ const affected = targets.filter((x) =>
56
+ // file is dependency of any target
57
+ x.dependencies.some((dep) => dep === ctx.file) ||
58
+ // or changed module is a dependency of any target
59
+ x.dependencies.some((dep) => ctx.modules.some((m) => m.file === dep)));
60
+ const deps = affected.flatMap((target) => target.dependencies);
61
+ // eslint-disable-next-line no-restricted-syntax
62
+ for (const depId of deps) {
63
+ cache.invalidateForFile(depId);
64
+ }
65
+ return affected
66
+ .map((target) => devServer.moduleGraph.getModuleById(target.id))
67
+ .concat(ctx.modules)
68
+ .filter((m) => !!m);
69
+ },
70
+ async transform(code, url) {
71
+ const [id] = url.split('?', 1);
72
+ // Do not transform ignored and generated files
73
+ if (url.includes('node_modules') || !filter(url) || id in cssLookup)
74
+ return;
75
+ const log = shared_1.logger.extend('vite').extend((0, transform_1.getFileIdx)(id));
76
+ log('transform %s', id);
77
+ const asyncResolve = async (what, importer, stack) => {
78
+ const resolved = await this.resolve(what, importer);
79
+ if (resolved) {
80
+ if (resolved.external) {
81
+ // If module is marked as external, Rollup will not resolve it,
82
+ // so we need to resolve it ourselves with default resolver
83
+ const resolvedId = (0, shared_1.syncResolve)(what, importer, stack);
84
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
85
+ return resolvedId;
86
+ }
87
+ log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
88
+ // Vite adds param like `?v=667939b3` to cached modules
89
+ const resolvedId = resolved.id.split('?', 1)[0];
90
+ if (resolvedId.startsWith('\0')) {
91
+ // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
92
+ // https://rollupjs.org/guide/en/#outputexports
93
+ return null;
94
+ }
95
+ if (!(0, fs_1.existsSync)(resolvedId)) {
96
+ await (0, vite_1.optimizeDeps)(config);
97
+ }
98
+ return resolvedId;
99
+ }
100
+ log("resolve ❌ '%s'@'%s", what, importer);
101
+ throw new Error(`Could not resolve ${what}`);
102
+ };
103
+ const transformServices = {
104
+ options: {
105
+ filename: id,
106
+ root: process.cwd(),
107
+ preprocessor,
108
+ pluginOptions: rest,
109
+ },
110
+ cache,
111
+ eventEmitter: emitter,
112
+ };
113
+ const result = await (0, transform_1.transform)(transformServices, code, asyncResolve);
114
+ let { cssText, dependencies } = result;
115
+ if (!cssText)
116
+ return;
117
+ dependencies ??= [];
118
+ const slug = (0, transform_1.slugify)(cssText);
119
+ const cssFilename = path_1.default
120
+ .normalize(`${id.replace(/\.[jt]sx?$/, '')}_${slug}.css`)
121
+ .replace(/\\/g, path_1.default.posix.sep);
122
+ const cssRelativePath = path_1.default
123
+ .relative(config.root, cssFilename)
124
+ .replace(/\\/g, path_1.default.posix.sep);
125
+ const cssId = `/${cssRelativePath}`;
126
+ if (sourceMap && result.cssSourceMapText) {
127
+ const map = Buffer.from(result.cssSourceMapText).toString('base64');
128
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
129
+ }
130
+ cssLookup[cssFilename] = cssText;
131
+ cssFileLookup[cssId] = cssFilename;
132
+ result.code += `\nimport ${JSON.stringify(cssFilename)};\n`;
133
+ if (devServer?.moduleGraph) {
134
+ const module = devServer.moduleGraph.getModuleById(cssId);
135
+ if (module) {
136
+ devServer.moduleGraph.invalidateModule(module);
137
+ module.lastHMRTimestamp =
138
+ module.lastInvalidationTimestamp || Date.now();
139
+ }
140
+ }
141
+ for (let i = 0, end = dependencies.length; i < end; i++) {
142
+ // eslint-disable-next-line no-await-in-loop
143
+ const depModule = await this.resolve(dependencies[i], url, {
144
+ isEntry: false,
145
+ });
146
+ if (depModule)
147
+ dependencies[i] = depModule.id;
148
+ }
149
+ const target = targets.find((t) => t.id === id);
150
+ if (!target)
151
+ targets.push({ id, dependencies });
152
+ else
153
+ target.dependencies = dependencies;
154
+ /* eslint-disable-next-line consistent-return */
155
+ return { code: result.code, map: result.sourceMap };
156
+ },
157
+ };
158
+ }
159
+ exports.default = wywInJS;