@wyw-in-js/vite 1.0.9 → 2.0.0-alpha.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/lib/index.js DELETED
@@ -1,627 +0,0 @@
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 _vite = require("vite");
10
- var _shared = require("@wyw-in-js/shared");
11
- var _transform = require("@wyw-in-js/transform");
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- /**
14
- * This file contains a Vite loader for wyw-in-js.
15
- * It uses the transform.ts function to generate class names from source code,
16
- * returns transformed code without template literals and attaches generated source maps
17
- */
18
-
19
- const isWindowsAbsolutePath = value => /^[a-zA-Z]:[\\/]/.test(value);
20
- const normalizeToPosix = value => value.replace(/\\/g, _path.default.posix.sep);
21
- const isInside = (childPath, parentPath) => {
22
- const rel = _path.default.relative(parentPath, childPath);
23
- return rel === '' || !rel.startsWith('..') && !_path.default.isAbsolute(rel);
24
- };
25
- const isWywCssAssetName = value => value.endsWith('.wyw-in-js.css');
26
- const normalizeAssetRelativePath = value => {
27
- const normalized = _path.default.posix.normalize(normalizeToPosix(value).replace(/^\/+/, ''));
28
- if (normalized.startsWith('..') || _path.default.posix.isAbsolute(normalized)) {
29
- return null;
30
- }
31
- return normalized;
32
- };
33
- const stripExtension = value => {
34
- const ext = _path.default.posix.extname(value);
35
- return ext ? value.slice(0, -ext.length) : value;
36
- };
37
- const getComparableAssetPaths = (value, rootDir) => {
38
- const variants = new Set();
39
- const normalized = normalizeToPosix(value);
40
- variants.add(normalized);
41
- if (_path.default.isAbsolute(value) || isWindowsAbsolutePath(normalized)) {
42
- if (isInside(value, rootDir)) {
43
- const relativeToRoot = normalizeAssetRelativePath(_path.default.relative(rootDir, value));
44
- if (relativeToRoot) {
45
- variants.add(relativeToRoot);
46
- }
47
- }
48
- return variants;
49
- }
50
- const relativePath = normalizeAssetRelativePath(value);
51
- if (relativePath) {
52
- variants.add(relativePath);
53
- }
54
- return variants;
55
- };
56
- const getStringValues = value => {
57
- if (!Array.isArray(value)) return [];
58
- return value.filter(item => typeof item === 'string');
59
- };
60
- const getOutputAssetNames = asset => [...(typeof asset.name === 'string' ? [asset.name] : []), ...getStringValues(asset.names), ...(typeof asset.originalFileName === 'string' ? [asset.originalFileName] : []), ...getStringValues(asset.originalFileNames)];
61
- const isOutputAssetLike = value => !!value && typeof value === 'object' && value.type === 'asset' && typeof value.fileName === 'string';
62
- const isOutputChunkLike = value => !!value && typeof value === 'object' && value.type === 'chunk' && typeof value.fileName === 'string' && typeof value.code === 'string';
63
- const getTrackedModuleIdForChunk = (chunk, cssFilesByModuleId) => {
64
- if (typeof chunk.facadeModuleId === 'string' && cssFilesByModuleId.has(chunk.facadeModuleId)) {
65
- return chunk.facadeModuleId;
66
- }
67
- if (!Array.isArray(chunk.moduleIds)) {
68
- return null;
69
- }
70
- const moduleId = chunk.moduleIds.find(id => typeof id === 'string' && cssFilesByModuleId.has(id));
71
- return moduleId !== null && moduleId !== void 0 ? moduleId : null;
72
- };
73
- const findWywCssAssetFileName = (bundle, cssFilename, rootDir) => {
74
- const expectedNames = getComparableAssetPaths(cssFilename, rootDir);
75
- for (const item of Object.values(bundle)) {
76
- if (isOutputAssetLike(item) && item.fileName.endsWith('.css')) {
77
- const isMatch = getOutputAssetNames(item).some(assetName => {
78
- const variants = getComparableAssetPaths(assetName, rootDir);
79
- return Array.from(variants).some(variant => expectedNames.has(variant));
80
- });
81
- if (isMatch) {
82
- return normalizeToPosix(item.fileName);
83
- }
84
- }
85
- }
86
- return null;
87
- };
88
- const getRelativeImportPath = (fromFileName, toFileName) => {
89
- const fromDir = _path.default.posix.dirname(normalizeToPosix(fromFileName));
90
- const relativePath = _path.default.posix.relative(fromDir, normalizeToPosix(toFileName));
91
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
92
- };
93
- const escapeForRegExp = value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
94
- const hasStaticImport = (code, specifier) => new RegExp(`(^|\\n)\\s*import\\s*(?:["']${escapeForRegExp(specifier)}["']|[^\\n;]+\\s+from\\s+["']${escapeForRegExp(specifier)}["'])`, 'm').test(code);
95
- const hasRequireCall = (code, specifier) => new RegExp(`(^|[;\\n])\\s*require\\(\\s*["']${escapeForRegExp(specifier)}["']\\s*\\)`, 'm').test(code);
96
- const getCssLoadStatement = (format, specifier) => format === 'cjs' ? `require(${JSON.stringify(specifier)});\n` : `import ${JSON.stringify(specifier)};\n`;
97
- const hasCssLoadStatement = (code, specifier, format) => format === 'cjs' ? hasRequireCall(code, specifier) : hasStaticImport(code, specifier);
98
- const prependCssLoadStatement = (code, specifier, format) => {
99
- const statement = getCssLoadStatement(format, specifier);
100
- let insertAt = 0;
101
- if (code.startsWith('#!')) {
102
- const lineBreakIndex = code.indexOf('\n');
103
- if (lineBreakIndex >= 0) {
104
- insertAt = lineBreakIndex + 1;
105
- } else {
106
- return `${code}\n${statement}`;
107
- }
108
- }
109
- if (format === 'cjs') {
110
- const directiveMatch = /^(?:\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*');)+/.exec(code.slice(insertAt));
111
- if (directiveMatch) {
112
- insertAt += directiveMatch[0].length;
113
- }
114
- }
115
- return `${code.slice(0, insertAt)}${statement}${code.slice(insertAt)}`;
116
- };
117
- const VITE_FS_PREFIX = '/@fs/';
118
- const safeDecodeURIComponent = value => {
119
- try {
120
- return decodeURIComponent(value);
121
- } catch {
122
- return value;
123
- }
124
- };
125
- const normalizeViteFsPath = value => {
126
- const fsPath = value.slice(VITE_FS_PREFIX.length);
127
- return _path.default.normalize(safeDecodeURIComponent(fsPath));
128
- };
129
- const isCssReloadTarget = value => {
130
- if (!value || typeof value !== 'object') return false;
131
- const reloadTarget = value;
132
- return !!reloadTarget.moduleGraph && typeof reloadTarget.moduleGraph.getModuleById === 'function' && typeof reloadTarget.reloadModule === 'function';
133
- };
134
- const getCssReloadTarget = (environment, server) => {
135
- if (isCssReloadTarget(environment)) {
136
- return environment;
137
- }
138
- if (server !== null && server !== void 0 && server.moduleGraph) {
139
- return {
140
- moduleGraph: server.moduleGraph,
141
- reloadModule: module => server.reloadModule(module)
142
- };
143
- }
144
- return null;
145
- };
146
- const getWywCssAssetFileNames = (resolvedConfig, output, originalAssetFileNames) => {
147
- if (!output.preserveModules) return null;
148
- const rootDir = resolvedConfig.root;
149
- const preserveModulesRootValue = output.preserveModulesRoot;
150
- let preserveModulesRootAbs = null;
151
- if (typeof preserveModulesRootValue === 'string') {
152
- preserveModulesRootAbs = _path.default.isAbsolute(preserveModulesRootValue) ? preserveModulesRootValue : _path.default.resolve(rootDir, preserveModulesRootValue);
153
- }
154
- const preserveModulesRootRel = preserveModulesRootAbs && isInside(preserveModulesRootAbs, rootDir) ? normalizeToPosix(_path.default.relative(rootDir, preserveModulesRootAbs)) : null;
155
- return assetInfo => {
156
- const template = typeof originalAssetFileNames === 'function' ? originalAssetFileNames(assetInfo) : originalAssetFileNames;
157
- const assetName = assetInfo === null || assetInfo === void 0 ? void 0 : assetInfo.name;
158
- if (typeof assetName !== 'string' || !isWywCssAssetName(assetName)) {
159
- return template;
160
- }
161
- if (!template.includes('[')) {
162
- return template;
163
- }
164
- let relativePath = null;
165
- const assetNameNormalized = normalizeToPosix(assetName);
166
- if (_path.default.isAbsolute(assetName) || isWindowsAbsolutePath(assetNameNormalized)) {
167
- const preserveRel = preserveModulesRootAbs && isInside(assetName, preserveModulesRootAbs) ? _path.default.relative(preserveModulesRootAbs, assetName) : null;
168
- if (preserveRel && !_path.default.isAbsolute(preserveRel) && !preserveRel.startsWith('..')) {
169
- relativePath = preserveRel;
170
- } else if (isInside(assetName, rootDir)) {
171
- relativePath = _path.default.relative(rootDir, assetName);
172
- }
173
- } else if (preserveModulesRootRel && assetNameNormalized.startsWith(`${preserveModulesRootRel}/`)) {
174
- relativePath = assetNameNormalized.slice(preserveModulesRootRel.length + 1);
175
- } else {
176
- relativePath = assetNameNormalized;
177
- }
178
- const normalized = relativePath ? normalizeAssetRelativePath(relativePath) : null;
179
- if (!normalized) {
180
- return template;
181
- }
182
- const withoutExt = stripExtension(normalized);
183
- if (template.includes('[name]')) {
184
- const dir = _path.default.posix.dirname(withoutExt);
185
- if (dir === '.' || dir === '') {
186
- return template;
187
- }
188
- return template.replace(/\[name\]/g, `${dir}/[name]`);
189
- }
190
- const dir = _path.default.posix.dirname(withoutExt);
191
- if (dir === '.' || dir === '') {
192
- return template;
193
- }
194
- const idx = template.indexOf('[');
195
- if (idx < 0) {
196
- return template;
197
- }
198
- const prefix = template.slice(0, idx);
199
- if (prefix !== '' && !prefix.endsWith('/')) {
200
- return template;
201
- }
202
- return `${prefix}${dir}/${template.slice(idx)}`;
203
- };
204
- };
205
- function wywInJS({
206
- debug,
207
- include,
208
- exclude,
209
- sourceMap,
210
- preserveCssPaths,
211
- keepComments,
212
- prefixer,
213
- preprocessor,
214
- ssrDevCss,
215
- ssrDevCssPath,
216
- transformLibraries,
217
- ...rest
218
- } = {}) {
219
- const filter = (0, _vite.createFilter)(include, exclude);
220
- const cssLookup = {};
221
- const cssFileLookup = {};
222
- const cssFilesByModuleId = new Map();
223
- const pendingCssReloads = new WeakMap();
224
- let ssrDevCssVersion = 0;
225
- let config;
226
- let devServer;
227
- let importMetaEnvForEval = null;
228
- const ssrDevCssEnabled = Boolean(ssrDevCss);
229
- const [ssrDevCssPathname, ssrDevCssQuery] = (ssrDevCssPath !== null && ssrDevCssPath !== void 0 ? ssrDevCssPath : '/_wyw-in-js/ssr.css').split('?', 2);
230
- const ssrDevCssRoute = ssrDevCssPathname.startsWith('/') ? ssrDevCssPathname : `/${ssrDevCssPathname}`;
231
- const getSsrDevCssHref = () => {
232
- const versionParam = `v=${ssrDevCssVersion}`;
233
- const query = ssrDevCssQuery ? `${ssrDevCssQuery}&${versionParam}` : versionParam;
234
- return `${ssrDevCssRoute}?${query}`;
235
- };
236
- const getSsrDevCssContents = () => {
237
- const entries = Object.entries(cssLookup);
238
- if (entries.length === 0) return '';
239
- const merged = entries.sort(([a], [b]) => a.localeCompare(b)).map(([, cssText]) => cssText).join('\n');
240
- return `${merged}\n`;
241
- };
242
- const {
243
- emitter,
244
- onDone
245
- } = (0, _transform.createFileReporter)(debug !== null && debug !== void 0 ? debug : false);
246
- const scheduleCssReload = (reloadTarget, cssFilename) => {
247
- let state = pendingCssReloads.get(reloadTarget);
248
- if (!state) {
249
- state = {
250
- files: new Set()
251
- };
252
- pendingCssReloads.set(reloadTarget, state);
253
- }
254
- state.files.add(cssFilename);
255
- if (state.timer) return;
256
- state.timer = setTimeout(() => {
257
- state.timer = undefined;
258
- const ids = Array.from(state.files);
259
- state.files.clear();
260
- const {
261
- moduleGraph
262
- } = reloadTarget;
263
- for (const id of ids) {
264
- const module = moduleGraph.getModuleById(id);
265
- if (module) reloadTarget.reloadModule(module);
266
- }
267
- }, 0);
268
- };
269
-
270
- // <dependency id, targets>
271
- const targets = [];
272
- const clientCache = new _transform.TransformCacheCollection();
273
- const ssrCache = new _transform.TransformCacheCollection();
274
- const caches = new Set([clientCache, ssrCache]);
275
- const getCache = isSsr => isSsr ? ssrCache : clientCache;
276
- const isInsideCacheDir = filename => {
277
- if (!config.cacheDir) {
278
- return false;
279
- }
280
- const relative = _path.default.relative(config.cacheDir, filename);
281
- return relative !== '' && !relative.startsWith('..') && !_path.default.isAbsolute(relative);
282
- };
283
- const getDepsOptimizer = () => {
284
- var _ref, _ref2, _server$environments$, _server$environments;
285
- if (!devServer) return null;
286
- const server = devServer;
287
- return (_ref = (_ref2 = (_server$environments$ = (_server$environments = server.environments) === null || _server$environments === void 0 || (_server$environments = _server$environments.client) === null || _server$environments === void 0 ? void 0 : _server$environments.depsOptimizer) !== null && _server$environments$ !== void 0 ? _server$environments$ : server.depsOptimizer) !== null && _ref2 !== void 0 ? _ref2 : server._depsOptimizer) !== null && _ref !== void 0 ? _ref : null;
288
- };
289
- const waitForOptimizedDep = async filename => {
290
- var _depsOptimizer$isOpti, _depsOptimizer$init, _depsOptimizer$metada;
291
- const depsOptimizer = getDepsOptimizer();
292
- if (!(depsOptimizer !== null && depsOptimizer !== void 0 && (_depsOptimizer$isOpti = depsOptimizer.isOptimizedDepFile) !== null && _depsOptimizer$isOpti !== void 0 && _depsOptimizer$isOpti.call(depsOptimizer, filename))) {
293
- return false;
294
- }
295
- await ((_depsOptimizer$init = depsOptimizer.init) === null || _depsOptimizer$init === void 0 ? void 0 : _depsOptimizer$init.call(depsOptimizer));
296
- await depsOptimizer.scanProcessing;
297
- const info = (_depsOptimizer$metada = depsOptimizer.metadata) === null || _depsOptimizer$metada === void 0 || (_depsOptimizer$metada = _depsOptimizer$metada.depInfoList) === null || _depsOptimizer$metada === void 0 ? void 0 : _depsOptimizer$metada.find(item => item.file === filename);
298
- if (info !== null && info !== void 0 && info.processing) {
299
- await info.processing;
300
- }
301
- return true;
302
- };
303
- let viteResolver = null;
304
- const resolveClient = (what, importer) => {
305
- if (!viteResolver) {
306
- throw new Error('Vite resolver is not initialized yet');
307
- }
308
- return viteResolver(what, importer, false, false);
309
- };
310
- const resolveSsr = (what, importer) => {
311
- if (!viteResolver) {
312
- throw new Error('Vite resolver is not initialized yet');
313
- }
314
- return viteResolver(what, importer, false, true);
315
- };
316
- const createAsyncResolver = (0, _shared.asyncResolverFactory)(async (resolved, what, importer, stack) => {
317
- const log = _shared.logger.extend('vite').extend((0, _transform.getFileIdx)(importer));
318
- if (resolved) {
319
- log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
320
-
321
- // Vite adds param like `?v=667939b3` to cached modules
322
- let resolvedId = resolved.split('?', 1)[0];
323
- if (resolvedId.startsWith('\0')) {
324
- // \0 is a special character in Rollup that tells Rollup to not include this in the bundle
325
- // https://rollupjs.org/guide/en/#outputexports
326
- return null;
327
- }
328
- if (resolvedId.startsWith(VITE_FS_PREFIX)) {
329
- resolvedId = normalizeViteFsPath(resolvedId);
330
- }
331
- if (resolvedId.startsWith('/@')) {
332
- return null;
333
- }
334
- if (!(0, _fs.existsSync)(resolvedId)) {
335
- // When Vite resolves to an optimized deps entry (cacheDir) it may not be written yet.
336
- // Wait for Vite's optimizer instead of calling optimizeDeps() manually (deprecated in Vite 7).
337
- try {
338
- await waitForOptimizedDep(resolvedId);
339
- } catch {
340
- // If optimizer failed, fall through to preserve previous behavior and surface the error.
341
- }
342
-
343
- // Vite can return an optimized deps entry (from cacheDir) before it's written to disk.
344
- // Manually calling optimizeDeps is deprecated in Vite 7 and can also get called many times.
345
- // Instead, fall back to resolving the original module path directly.
346
- if (!(0, _fs.existsSync)(resolvedId) && isInsideCacheDir(resolvedId)) {
347
- try {
348
- return (0, _shared.syncResolve)(what, importer, stack);
349
- } catch {
350
- // Fall through to preserve previous behavior: return resolvedId and let WyW surface the error.
351
- }
352
- }
353
- }
354
- if (!(0, _fs.existsSync)(resolvedId) && !_path.default.isAbsolute(resolvedId)) {
355
- // Vite can resolve an import to a bare specifier when bundling for SSR and marking it as external.
356
- // In that case we still need a real file path for WyW evaluation.
357
- return (0, _shared.syncResolve)(what, importer, stack);
358
- }
359
- return resolvedId;
360
- }
361
- log("resolve ❌ '%s'@'%s", what, importer);
362
-
363
- // Vite can inject virtual ids like /@react-refresh in dev.
364
- if (what.startsWith('/@') || what.startsWith('\0')) {
365
- return null;
366
- }
367
- if (!what.startsWith('.') && !what.startsWith('/') && !_path.default.isAbsolute(what)) {
368
- // Keep compatibility with SSR externalization: fall back to Node resolution for bare specifiers.
369
- return (0, _shared.syncResolve)(what, importer, stack);
370
- }
371
- throw new Error(`Could not resolve ${what}`);
372
- }, (what, importer) => [what, importer]);
373
- const asyncResolveClient = createAsyncResolver(resolveClient);
374
- const asyncResolveSsr = createAsyncResolver(resolveSsr);
375
- return {
376
- name: 'wyw-in-js',
377
- enforce: 'post',
378
- buildEnd() {
379
- onDone(process.cwd());
380
- },
381
- configResolved(resolvedConfig) {
382
- var _config$envPrefix;
383
- config = resolvedConfig;
384
- viteResolver = config.createResolver();
385
- if (preserveCssPaths && config.command === 'build') {
386
- const outputs = config.build.rollupOptions.output;
387
- let outputEntries = [];
388
- if (Array.isArray(outputs)) {
389
- outputEntries = outputs;
390
- } else if (outputs) {
391
- outputEntries = [outputs];
392
- }
393
- outputEntries.forEach(entry => {
394
- var _output$assetFileName, _config$build$assetsD;
395
- if (!entry || typeof entry !== 'object') return;
396
- const output = entry;
397
- if (!output.preserveModules) return;
398
- const template = (_output$assetFileName = output.assetFileNames) !== null && _output$assetFileName !== void 0 ? _output$assetFileName : `${(_config$build$assetsD = config.build.assetsDir) !== null && _config$build$assetsD !== void 0 ? _config$build$assetsD : 'assets'}/[name].[hash].[ext]`;
399
- const assetFileNames = getWywCssAssetFileNames(config, output, template);
400
- if (assetFileNames) output.assetFileNames = assetFileNames;
401
- });
402
- }
403
- const envPrefix = (_config$envPrefix = config.envPrefix) !== null && _config$envPrefix !== void 0 ? _config$envPrefix : 'VITE_';
404
- const envDir =
405
- // envDir is absolute in modern Vite, but keep a fallback for older versions
406
- 'envDir' in config && typeof config.envDir === 'string' ? config.envDir : config.root;
407
- const loaded = (0, _vite.loadEnv)(config.mode, envDir, envPrefix);
408
- const base = {
409
- ...loaded,
410
- BASE_URL: config.base,
411
- MODE: config.mode,
412
- DEV: config.command === 'serve',
413
- PROD: config.command === 'build'
414
- };
415
- importMetaEnvForEval = {
416
- client: {
417
- ...base,
418
- SSR: false
419
- },
420
- ssr: {
421
- ...base,
422
- SSR: true
423
- }
424
- };
425
- },
426
- configureServer(_server) {
427
- devServer = _server;
428
- if (!ssrDevCssEnabled || config.command !== 'serve') return;
429
- devServer.middlewares.use((req, res, next) => {
430
- const {
431
- url
432
- } = req;
433
- if (!url) {
434
- next();
435
- return;
436
- }
437
- const [pathname] = url.split('?', 1);
438
- if (pathname !== ssrDevCssRoute) {
439
- next();
440
- return;
441
- }
442
- const etag = `W/"${ssrDevCssVersion}"`;
443
- const ifNoneMatch = req.headers['if-none-match'];
444
- if (ifNoneMatch === etag) {
445
- res.statusCode = 304;
446
- res.end();
447
- return;
448
- }
449
- res.statusCode = 200;
450
- res.setHeader('Content-Type', 'text/css; charset=utf-8');
451
- res.setHeader('Cache-Control', 'no-cache');
452
- res.setHeader('ETag', etag);
453
- res.end(getSsrDevCssContents());
454
- });
455
- },
456
- transformIndexHtml(html) {
457
- if (!ssrDevCssEnabled || config.command !== 'serve') return undefined;
458
- return {
459
- html,
460
- tags: [{
461
- tag: 'link',
462
- attrs: {
463
- rel: 'stylesheet',
464
- href: getSsrDevCssHref()
465
- },
466
- injectTo: 'head-prepend'
467
- }]
468
- };
469
- },
470
- load(url) {
471
- const [id] = url.split('?', 1);
472
- return cssLookup[id];
473
- },
474
- /* eslint-disable-next-line consistent-return */
475
- resolveId(importeeUrl) {
476
- const [id] = importeeUrl.split('?', 1);
477
- if (cssLookup[id]) return id;
478
- return cssFileLookup[id];
479
- },
480
- handleHotUpdate(ctx) {
481
- // it's module, so just transform it
482
- if (ctx.modules.length) return ctx.modules;
483
-
484
- // Select affected modules of changed dependency
485
- const affected = targets.filter(x =>
486
- // file is dependency of any target
487
- x.dependencies.some(dep => dep === ctx.file) ||
488
- // or changed module is a dependency of any target
489
- x.dependencies.some(dep => ctx.modules.some(m => m.file === dep)));
490
- const deps = affected.flatMap(target => target.dependencies);
491
-
492
- // eslint-disable-next-line no-restricted-syntax
493
- for (const depId of deps) {
494
- for (const cache of caches) {
495
- cache.invalidateForFile(depId);
496
- }
497
- }
498
- return affected.map(target => devServer.moduleGraph.getModuleById(target.id)).concat(ctx.modules).filter(m => !!m);
499
- },
500
- generateBundle(outputOptions, bundle) {
501
- if (config.command !== 'build') return;
502
- if (!outputOptions.preserveModules) return;
503
- if (config.build.cssCodeSplit === false) return;
504
- Object.values(bundle).forEach(item => {
505
- if (!isOutputChunkLike(item)) {
506
- return;
507
- }
508
- const chunk = item;
509
- const moduleId = getTrackedModuleIdForChunk(chunk, cssFilesByModuleId);
510
- if (!moduleId) {
511
- return;
512
- }
513
- const cssFilename = cssFilesByModuleId.get(moduleId);
514
- if (!cssFilename) {
515
- return;
516
- }
517
- const emittedCssFileName = findWywCssAssetFileName(bundle, cssFilename, config.root);
518
- if (!emittedCssFileName) {
519
- return;
520
- }
521
- const relativeCssImport = getRelativeImportPath(chunk.fileName, emittedCssFileName);
522
- if (hasCssLoadStatement(chunk.code, relativeCssImport, outputOptions.format)) {
523
- return;
524
- }
525
- chunk.code = prependCssLoadStatement(chunk.code, relativeCssImport, outputOptions.format);
526
- });
527
- },
528
- async transform(code, url, transformOptions) {
529
- const [id] = url.split('?', 1);
530
-
531
- // Do not transform ignored and generated files
532
- if (!transformLibraries && url.includes('node_modules') || !filter(url) || id in cssLookup) return;
533
- const log = _shared.logger.extend('vite').extend((0, _transform.getFileIdx)(id));
534
- log('transform %s', id);
535
- const isSsr = typeof transformOptions === 'boolean' ? transformOptions : Boolean(transformOptions === null || transformOptions === void 0 ? void 0 : transformOptions.ssr);
536
- const overrideContext = (context, filename) => {
537
- var _importMetaEnvForEval;
538
- const env = (_importMetaEnvForEval = importMetaEnvForEval) === null || _importMetaEnvForEval === void 0 ? void 0 : _importMetaEnvForEval[isSsr ? 'ssr' : 'client'];
539
- const withEnv = env ? {
540
- ...context,
541
- __wyw_import_meta_env: env
542
- } : context;
543
- return rest.overrideContext ? rest.overrideContext(withEnv, filename) : withEnv;
544
- };
545
- const transformServices = {
546
- options: {
547
- filename: id,
548
- root: process.cwd(),
549
- prefixer,
550
- keepComments,
551
- preprocessor,
552
- pluginOptions: {
553
- ...rest,
554
- overrideContext
555
- }
556
- },
557
- cache: getCache(isSsr),
558
- emitWarning: message => this.warn(message),
559
- eventEmitter: emitter
560
- };
561
- const asyncResolve = isSsr ? asyncResolveSsr : asyncResolveClient;
562
- const result = await (0, _transform.transform)(transformServices, code, asyncResolve);
563
- let {
564
- cssText,
565
- dependencies
566
- } = result;
567
-
568
- // Heads up, there are three cases:
569
- // 1. cssText is undefined, it means that file was not transformed
570
- // 2. cssText is empty, it means that file was transformed, but it does not contain any styles
571
- // 3. cssText is not empty, it means that file was transformed and it contains styles
572
-
573
- if (typeof cssText === 'undefined') {
574
- cssFilesByModuleId.delete(id);
575
- return;
576
- }
577
- if (cssText === '') {
578
- cssFilesByModuleId.delete(id);
579
- /* eslint-disable-next-line consistent-return */
580
- return {
581
- code: result.code,
582
- map: result.sourceMap
583
- };
584
- }
585
- dependencies !== null && dependencies !== void 0 ? dependencies : dependencies = [];
586
- const cssFilename = _path.default.normalize(`${id.replace(/\.[jt]sx?$/, '')}.wyw-in-js.css`).replace(/\\/g, _path.default.posix.sep);
587
- cssFilesByModuleId.set(id, cssFilename);
588
- const cssRelativePath = _path.default.relative(config.root, cssFilename).replace(/\\/g, _path.default.posix.sep);
589
- const cssId = `/${cssRelativePath}`;
590
- if (sourceMap && result.cssSourceMapText) {
591
- const map = Buffer.from(result.cssSourceMapText).toString('base64');
592
- cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
593
- }
594
- const didCssChange = cssLookup[cssFilename] !== cssText;
595
- cssLookup[cssFilename] = cssText;
596
- cssFileLookup[cssId] = cssFilename;
597
- result.code += `\nimport ${JSON.stringify(cssFilename)};\n`;
598
- for (let i = 0, end = dependencies.length; i < end; i++) {
599
- // eslint-disable-next-line no-await-in-loop
600
- const depModule = await this.resolve(dependencies[i], url, {
601
- isEntry: false
602
- });
603
- if (depModule) dependencies[i] = depModule.id;
604
- }
605
- const target = targets.find(t => t.id === id);
606
- if (!target) targets.push({
607
- id,
608
- dependencies
609
- });else target.dependencies = dependencies;
610
- if (didCssChange) {
611
- const reloadTarget = getCssReloadTarget(this.environment, devServer);
612
- if (reloadTarget) {
613
- scheduleCssReload(reloadTarget, cssFilename);
614
- }
615
- if (ssrDevCssEnabled && config.command === 'serve') {
616
- ssrDevCssVersion += 1;
617
- }
618
- }
619
- /* eslint-disable-next-line consistent-return */
620
- return {
621
- code: result.code,
622
- map: result.sourceMap
623
- };
624
- }
625
- };
626
- }
627
- //# sourceMappingURL=index.js.map