@plumeria/webpack-plugin 2.4.1 → 3.0.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/dist/index.d.ts CHANGED
@@ -1,11 +1,2 @@
1
- import type { Compiler } from 'webpack';
2
- import type { CSSObject } from '@plumeria/utils';
3
- export declare class PlumeriaPlugin {
4
- private stylesByFile;
5
- private outFile;
6
- constructor();
7
- apply(compiler: Compiler): void;
8
- registerFileStyles(filePath: string, styles: CSSObject): void;
9
- private generateOrderedCSS;
10
- private writeCSS;
11
- }
1
+ import type { LoaderContext } from 'webpack';
2
+ export default function loader(this: LoaderContext<unknown>, source: string): void;
package/dist/index.js CHANGED
@@ -3,84 +3,286 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PlumeriaPlugin = void 0;
7
- const path_1 = __importDefault(require("path"));
6
+ exports.default = loader;
7
+ const core_1 = require("@swc/core");
8
8
  const fs_1 = __importDefault(require("fs"));
9
- const PLUGIN_NAME = 'PlumeriaPlugin';
10
- class PlumeriaPlugin {
11
- stylesByFile = new Map();
12
- outFile;
13
- constructor() { }
14
- apply(compiler) {
15
- this.outFile = path_1.default.resolve(__dirname, '..', 'zero-virtual.css');
16
- compiler.hooks.invalid.tap(PLUGIN_NAME, (filename) => {
17
- if (filename) {
18
- const absPath = path_1.default.resolve(filename);
19
- this.stylesByFile.delete(absPath);
9
+ const path_1 = __importDefault(require("path"));
10
+ const zss_engine_1 = require("zss-engine");
11
+ const utils_1 = require("@plumeria/utils");
12
+ const VIRTUAL_FILE_PATH = path_1.default.resolve(__dirname, '..', 'zero-virtual.css');
13
+ function loader(source) {
14
+ const callback = this.async();
15
+ if (this.resourcePath.includes('node_modules') ||
16
+ !source.includes('@plumeria/core')) {
17
+ return callback(null, source);
18
+ }
19
+ this.clearDependencies();
20
+ this.addDependency(this.resourcePath);
21
+ utils_1.tables.staticTable = (0, utils_1.scanForCreateStatic)((path) => this.addDependency(path));
22
+ const { keyframesHashTableLocal, keyframesObjectTableLocal } = (0, utils_1.scanForKeyframes)((path) => this.addDependency(path));
23
+ utils_1.tables.keyframesHashTable = keyframesHashTableLocal;
24
+ utils_1.tables.keyframesObjectTable = keyframesObjectTableLocal;
25
+ const { viewTransitionHashTableLocal, viewTransitionObjectTableLocal } = (0, utils_1.scanForViewTransition)((path) => this.addDependency(path));
26
+ utils_1.tables.viewTransitionHashTable = viewTransitionHashTableLocal;
27
+ utils_1.tables.viewTransitionObjectTable = viewTransitionObjectTableLocal;
28
+ const { themeTableLocal, createThemeObjectTableLocal } = (0, utils_1.scanForCreateTheme)((path) => this.addDependency(path));
29
+ utils_1.tables.themeTable = themeTableLocal;
30
+ utils_1.tables.createThemeObjectTable = createThemeObjectTableLocal;
31
+ const extractedSheets = [];
32
+ const fileStyles = {};
33
+ const ast = (0, core_1.parseSync)(source, {
34
+ syntax: 'typescript',
35
+ tsx: true,
36
+ target: 'es2022',
37
+ });
38
+ const localConsts = (0, utils_1.collectLocalConsts)(ast);
39
+ Object.assign(utils_1.tables.staticTable, localConsts);
40
+ const localCreateStyles = {};
41
+ const replacements = [];
42
+ (0, utils_1.traverse)(ast, {
43
+ VariableDeclarator({ node }) {
44
+ if (node.id.type === 'Identifier' &&
45
+ node.init &&
46
+ utils_1.t.isCallExpression(node.init) &&
47
+ utils_1.t.isMemberExpression(node.init.callee) &&
48
+ utils_1.t.isIdentifier(node.init.callee.object, { name: 'css' }) &&
49
+ utils_1.t.isIdentifier(node.init.callee.property, { name: 'create' }) &&
50
+ node.init.arguments.length === 1 &&
51
+ utils_1.t.isObjectExpression(node.init.arguments[0].expression)) {
52
+ const obj = (0, utils_1.objectExpressionToObject)(node.init.arguments[0].expression, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
53
+ if (obj) {
54
+ localCreateStyles[node.id.value] = obj;
55
+ const hashMap = {};
56
+ Object.entries(obj).forEach(([key, style]) => {
57
+ const records = (0, utils_1.getStyleRecords)(key, style, 2);
58
+ const propMap = {};
59
+ (0, utils_1.extractOndemandStyles)(style, extractedSheets);
60
+ records.forEach((r) => {
61
+ propMap[r.key] = r.hash;
62
+ extractedSheets.push(r.sheet);
63
+ });
64
+ hashMap[key] = records.map((r) => r.hash).join(' ');
65
+ });
66
+ replacements.push({
67
+ start: node.init.span.start - ast.span.start,
68
+ end: node.init.span.end - ast.span.start,
69
+ content: JSON.stringify(hashMap),
70
+ });
71
+ }
20
72
  }
21
- });
22
- compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
23
- this.stylesByFile.clear();
24
- });
25
- compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => {
26
- nmf.hooks.createModule.tap(PLUGIN_NAME, (createData) => {
27
- const modPath = createData.matchResource ?? createData.resourceResolveData?.path;
28
- if (modPath && modPath.includes('zero-virtual.css')) {
29
- createData.settings ??= {};
30
- createData.settings.sideEffects = true;
73
+ },
74
+ CallExpression({ node }) {
75
+ const callee = node.callee;
76
+ if (utils_1.t.isMemberExpression(callee) &&
77
+ utils_1.t.isIdentifier(callee.object, { name: 'css' }) &&
78
+ utils_1.t.isIdentifier(callee.property)) {
79
+ const args = node.arguments;
80
+ if (callee.property.value === 'props') {
81
+ const merged = {};
82
+ let allStatic = true;
83
+ args.forEach((arg) => {
84
+ const expr = arg.expression;
85
+ if (utils_1.t.isObjectExpression(expr)) {
86
+ const obj = (0, utils_1.objectExpressionToObject)(expr, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
87
+ if (obj) {
88
+ Object.assign(merged, obj);
89
+ }
90
+ else {
91
+ allStatic = false;
92
+ }
93
+ }
94
+ else if (utils_1.t.isMemberExpression(expr)) {
95
+ if (utils_1.t.isIdentifier(expr.object) &&
96
+ utils_1.t.isIdentifier(expr.property)) {
97
+ const varName = expr.object.value;
98
+ const propName = expr.property.value;
99
+ const styleSet = localCreateStyles[varName];
100
+ if (styleSet && styleSet[propName]) {
101
+ Object.assign(merged, styleSet[propName]);
102
+ }
103
+ else {
104
+ allStatic = false;
105
+ }
106
+ }
107
+ else {
108
+ allStatic = false;
109
+ }
110
+ }
111
+ else if (utils_1.t.isIdentifier(expr)) {
112
+ const obj = localCreateStyles[expr.value];
113
+ if (obj) {
114
+ Object.assign(merged, obj);
115
+ }
116
+ else {
117
+ allStatic = false;
118
+ }
119
+ }
120
+ else {
121
+ allStatic = false;
122
+ }
123
+ });
124
+ if (allStatic && Object.keys(merged).length > 0) {
125
+ (0, utils_1.extractOndemandStyles)(merged, extractedSheets);
126
+ const hash = (0, zss_engine_1.genBase36Hash)(merged, 1, 8);
127
+ const records = (0, utils_1.getStyleRecords)(hash, merged, 2);
128
+ records.forEach((r) => {
129
+ extractedSheets.push(r.sheet);
130
+ });
131
+ replacements.push({
132
+ start: node.span.start - ast.span.start,
133
+ end: node.span.end - ast.span.start,
134
+ content: JSON.stringify(records.map((r) => r.hash).join(' ')),
135
+ });
136
+ }
137
+ }
138
+ else if (callee.property.value === 'keyframes' &&
139
+ args.length > 0 &&
140
+ utils_1.t.isObjectExpression(args[0].expression)) {
141
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
142
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
143
+ utils_1.tables.keyframesObjectTable[hash] = obj;
144
+ replacements.push({
145
+ start: node.span.start - ast.span.start,
146
+ end: node.span.end - ast.span.start,
147
+ content: JSON.stringify(`kf-${hash}`),
148
+ });
31
149
  }
32
- });
33
- });
150
+ else if (callee.property.value === 'viewTransition' &&
151
+ args.length > 0 &&
152
+ utils_1.t.isObjectExpression(args[0].expression)) {
153
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
154
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
155
+ utils_1.tables.viewTransitionObjectTable[hash] = obj;
156
+ replacements.push({
157
+ start: node.span.start - ast.span.start,
158
+ end: node.span.end - ast.span.start,
159
+ content: JSON.stringify(`vt-${hash}`),
160
+ });
161
+ }
162
+ else if (callee.property.value === 'createTheme' &&
163
+ args.length > 0 &&
164
+ utils_1.t.isObjectExpression(args[0].expression)) {
165
+ const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
166
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
167
+ utils_1.tables.createThemeObjectTable[hash] = obj;
168
+ replacements.push({
169
+ start: node.span.start - ast.span.start,
170
+ end: node.span.end - ast.span.start,
171
+ content: JSON.stringify(''),
172
+ });
173
+ }
174
+ else if (callee.property.value === 'createStatic' &&
175
+ args.length > 0 &&
176
+ utils_1.t.isStringLiteral(args[0].expression)) {
177
+ replacements.push({
178
+ start: node.span.start - ast.span.start,
179
+ end: node.span.end - ast.span.start,
180
+ content: JSON.stringify(''),
181
+ });
182
+ }
183
+ }
184
+ },
185
+ });
186
+ if (extractedSheets.length > 0) {
187
+ fileStyles.baseStyles =
188
+ (fileStyles.baseStyles || '') + extractedSheets.join('');
34
189
  }
35
- registerFileStyles(filePath, styles) {
36
- const absPath = path_1.default.resolve(filePath);
37
- const prev = this.stylesByFile.get(absPath) || {
38
- filePath,
39
- keyframeStyles: '',
40
- viewTransitionStyles: '',
41
- themeStyles: '',
42
- baseStyles: '',
43
- };
44
- const updatedStyles = {
45
- ...prev,
46
- ...styles,
47
- lastAccessed: Date.now(),
48
- };
49
- this.stylesByFile.set(absPath, updatedStyles);
50
- this.writeCSS();
190
+ const buffer = Buffer.from(source);
191
+ let offset = 0;
192
+ const parts = [];
193
+ replacements
194
+ .sort((a, b) => a.start - b.start)
195
+ .forEach((r) => {
196
+ parts.push(buffer.subarray(offset, r.start));
197
+ parts.push(Buffer.from(r.content));
198
+ offset = r.end;
199
+ });
200
+ parts.push(buffer.subarray(offset));
201
+ const transformedSource = Buffer.concat(parts).toString();
202
+ const VIRTUAL_CSS_PATH = require.resolve(VIRTUAL_FILE_PATH);
203
+ function stringifyRequest(loaderContext, request) {
204
+ const context = loaderContext.context || loaderContext.rootContext;
205
+ const relativePath = path_1.default.relative(context, request);
206
+ const requestPath = relativePath.startsWith('.')
207
+ ? relativePath
208
+ : './' + relativePath;
209
+ return JSON.stringify(requestPath);
51
210
  }
52
- generateOrderedCSS() {
53
- const allStyles = Array.from(this.stylesByFile.values());
54
- if (allStyles.length === 0) {
55
- return '';
211
+ const virtualCssRequest = stringifyRequest(this, `${VIRTUAL_CSS_PATH}`);
212
+ const postfix = `\nimport ${virtualCssRequest};`;
213
+ let css = '';
214
+ try {
215
+ css = fs_1.default.readFileSync(VIRTUAL_FILE_PATH, 'utf-8');
216
+ }
217
+ catch (e) {
218
+ }
219
+ function generateOrderedCSS(styles) {
220
+ const sections = [];
221
+ if (styles.keyframeStyles?.trim()) {
222
+ if (!css.includes(styles.keyframeStyles))
223
+ sections.push(styles.keyframeStyles);
224
+ }
225
+ if (styles.viewTransitionStyles?.trim()) {
226
+ if (!css.includes(styles.viewTransitionStyles))
227
+ sections.push(styles.viewTransitionStyles);
56
228
  }
57
- const sortedStyles = allStyles.sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0));
58
- const keyframeStylesSet = new Set();
59
- const viewTransitionStylesSet = new Set();
60
- const themeStylesSet = new Set();
61
- const baseStylesSet = new Set();
62
- for (const s of sortedStyles) {
63
- if (s.keyframeStyles?.trim().length > 0)
64
- keyframeStylesSet.add(s.keyframeStyles);
65
- if (s.viewTransitionStyles?.trim().length > 0)
66
- viewTransitionStylesSet.add(s.viewTransitionStyles);
67
- if (s.themeStyles?.trim().length > 0)
68
- themeStylesSet.add(s.themeStyles);
69
- if (s.baseStyles?.trim().length > 0)
70
- baseStylesSet.add(s.baseStyles);
229
+ if (styles.themeStyles?.trim()) {
230
+ if (!css.includes(styles.themeStyles))
231
+ sections.push(styles.themeStyles);
71
232
  }
72
- return [
73
- ...Array.from(keyframeStylesSet),
74
- ...Array.from(viewTransitionStylesSet),
75
- ...Array.from(themeStylesSet),
76
- ...Array.from(baseStylesSet),
77
- ]
78
- .filter(Boolean)
79
- .join('\n');
233
+ if (styles.baseStyles?.trim()) {
234
+ sections.push(styles.baseStyles);
235
+ }
236
+ return sections.join('\n');
237
+ }
238
+ const orderedCSS = generateOrderedCSS(fileStyles);
239
+ const relativeId = path_1.default.relative(process.cwd(), this.resourcePath);
240
+ const hmrCode = `
241
+ if (module.hot) {
242
+ module.hot.accept(${virtualCssRequest});
243
+
244
+ const styleId = "plumeria-hmr";
245
+ const fileKey = ${JSON.stringify(relativeId)};
246
+
247
+ let styleEl = document.getElementById(styleId);
248
+
249
+ if (!styleEl) {
250
+ styleEl = document.createElement("style");
251
+ styleEl.id = styleId;
252
+ document.head.prepend(styleEl);
253
+ styleEl.__plumeriaStyles = {};
254
+ }
255
+
256
+ styleEl.__plumeriaStyles[fileKey] = ${JSON.stringify(orderedCSS)};
257
+ styleEl.textContent = Object.values(styleEl.__plumeriaStyles).join('\\n');
258
+
259
+ module.hot.dispose(() => {
260
+ if (styleEl && styleEl.__plumeriaStyles) {
261
+ delete styleEl.__plumeriaStyles[fileKey];
262
+ styleEl.textContent = Object.values(styleEl.__plumeriaStyles).join('\\n');
263
+
264
+ if (Object.keys(styleEl.__plumeriaStyles).length === 0 && styleEl.parentNode) {
265
+ styleEl.parentNode.removeChild(styleEl);
266
+ }
267
+ }
268
+ });
269
+ }
270
+ `;
271
+ if (extractedSheets.length > 0 && process.env.NODE_ENV === 'development') {
272
+ fs_1.default.appendFileSync(VIRTUAL_FILE_PATH, extractedSheets.join(''), 'utf-8');
273
+ }
274
+ else if (extractedSheets.length > 0 &&
275
+ process.env.NODE_ENV === 'production') {
276
+ fs_1.default.writeFileSync(VIRTUAL_FILE_PATH, '');
277
+ }
278
+ const useClientDirective = /^\s*['"]use client['"]/;
279
+ if (process.env.NODE_ENV === 'production')
280
+ return callback(null, transformedSource);
281
+ if (!useClientDirective.test(source)) {
282
+ callback(null, transformedSource + postfix);
283
+ return;
80
284
  }
81
- writeCSS() {
82
- const css = this.generateOrderedCSS();
83
- fs_1.default.writeFileSync(this.outFile, css, 'utf-8');
285
+ else {
286
+ callback(null, transformedSource + hmrCode);
84
287
  }
85
288
  }
86
- exports.PlumeriaPlugin = PlumeriaPlugin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plumeria/webpack-plugin",
3
- "version": "2.4.1",
3
+ "version": "3.0.0",
4
4
  "description": "Plumeria Webpack plugin",
5
5
  "author": "Refirst 11",
6
6
  "license": "MIT",
@@ -22,12 +22,12 @@
22
22
  "zero-virtual.css"
23
23
  ],
24
24
  "dependencies": {
25
- "@plumeria/utils": "^2.4.1"
25
+ "@plumeria/utils": "^3.0.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@swc/core": "1.15.2",
29
29
  "webpack": "5.101.0",
30
- "zss-engine": "2.1.0"
30
+ "zss-engine": "2.1.2"
31
31
  },
32
32
  "publishConfig": {
33
33
  "access": "public",
@@ -1,2 +0,0 @@
1
- import type { LoaderContext } from 'webpack';
2
- export default function loader(this: LoaderContext<unknown>, source: string): void;
@@ -1,187 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = loader;
7
- const core_1 = require("@swc/core");
8
- const path_1 = __importDefault(require("path"));
9
- const fs_1 = __importDefault(require("fs"));
10
- const zss_engine_1 = require("zss-engine");
11
- const utils_1 = require("@plumeria/utils");
12
- function loader(source) {
13
- const callback = this.async();
14
- this.clearDependencies();
15
- this.addDependency(this.resourcePath);
16
- utils_1.tables.staticTable = (0, utils_1.scanForCreateStatic)((path) => this.addDependency(path));
17
- const { keyframesHashTableLocal, keyframesObjectTableLocal } = (0, utils_1.scanForKeyframes)((path) => this.addDependency(path));
18
- utils_1.tables.keyframesHashTable = keyframesHashTableLocal;
19
- utils_1.tables.keyframesObjectTable = keyframesObjectTableLocal;
20
- const { viewTransitionHashTableLocal, viewTransitionObjectTableLocal } = (0, utils_1.scanForViewTransition)((path) => this.addDependency(path));
21
- utils_1.tables.viewTransitionHashTable = viewTransitionHashTableLocal;
22
- utils_1.tables.viewTransitionObjectTable = viewTransitionObjectTableLocal;
23
- const { themeTableLocal, createThemeObjectTableLocal } = (0, utils_1.scanForCreateTheme)((path) => this.addDependency(path));
24
- utils_1.tables.themeTable = themeTableLocal;
25
- utils_1.tables.createThemeObjectTable = createThemeObjectTableLocal;
26
- const extractedObjects = [];
27
- let ast;
28
- try {
29
- ast = (0, core_1.parseSync)(source, {
30
- syntax: 'typescript',
31
- tsx: true,
32
- target: 'es2022',
33
- });
34
- }
35
- catch (err) {
36
- console.log(err);
37
- callback(null, source);
38
- return;
39
- }
40
- const localConsts = (0, utils_1.collectLocalConsts)(ast);
41
- Object.assign(utils_1.tables.staticTable, localConsts);
42
- let hasCssCreate = false;
43
- (0, utils_1.traverse)(ast, {
44
- CallExpression({ node }) {
45
- const callee = node.callee;
46
- if (utils_1.t.isMemberExpression(callee) &&
47
- utils_1.t.isIdentifier(callee.object, { name: 'css' }) &&
48
- utils_1.t.isIdentifier(callee.property)) {
49
- const args = node.arguments;
50
- if (callee.property.value === 'create' &&
51
- args.length === 1 &&
52
- utils_1.t.isObjectExpression(args[0].expression)) {
53
- hasCssCreate = true;
54
- const obj = (0, utils_1.objectExpressionToObject)(args[0].expression, utils_1.tables.staticTable, utils_1.tables.keyframesHashTable, utils_1.tables.viewTransitionHashTable, utils_1.tables.themeTable);
55
- if (obj) {
56
- extractedObjects.push(obj);
57
- }
58
- }
59
- }
60
- },
61
- });
62
- const fileStyles = {};
63
- if (extractedObjects.length > 0) {
64
- const combinedStyles = extractedObjects.reduce((acc, obj) => Object.assign(acc, obj), {});
65
- const base = (0, utils_1.createCSS)(combinedStyles);
66
- if (base) {
67
- fileStyles.baseStyles = base;
68
- }
69
- }
70
- if (Object.keys(utils_1.tables.keyframesObjectTable).length > 0) {
71
- fileStyles.keyframeStyles = Object.entries(utils_1.tables.keyframesObjectTable)
72
- .map(([hash, obj]) => (0, zss_engine_1.transpile)({ [`@keyframes kf-${hash}`]: obj }, undefined, '--global')
73
- .styleSheet)
74
- .join('\n');
75
- }
76
- if (Object.keys(utils_1.tables.viewTransitionObjectTable).length > 0) {
77
- fileStyles.viewTransitionStyles = Object.entries(utils_1.tables.viewTransitionObjectTable)
78
- .map(([hash, obj]) => (0, zss_engine_1.transpile)({
79
- [`::view-transition-group(vt-${hash})`]: obj.group,
80
- [`::view-transition-image-pair(vt-${hash})`]: obj.imagePair,
81
- [`::view-transition-old(vt-${hash})`]: obj.old,
82
- [`::view-transition-new(vt-${hash})`]: obj.new,
83
- }, undefined, '--global').styleSheet)
84
- .join('\n');
85
- }
86
- if (Object.keys(utils_1.tables.createThemeObjectTable).length > 0) {
87
- fileStyles.themeStyles = Object.values(utils_1.tables.createThemeObjectTable)
88
- .map((obj) => (0, zss_engine_1.transpile)((0, utils_1.createTheme)(obj), undefined, '--global')
89
- .styleSheet)
90
- .join('\n');
91
- }
92
- const VIRTUAL_FILE_PATH = path_1.default.resolve(__dirname, '..', 'zero-virtual.css');
93
- const VIRTUAL_CSS_PATH = require.resolve(VIRTUAL_FILE_PATH);
94
- function stringifyRequest(loaderContext, request) {
95
- return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
96
- }
97
- const virtualCssImportPath = path_1.default.posix.join(path_1.default.posix.relative(path_1.default.dirname(this.resourcePath), path_1.default.resolve(__dirname, '..', VIRTUAL_CSS_PATH)));
98
- let importPath = virtualCssImportPath;
99
- if (!importPath.startsWith('.')) {
100
- importPath = './' + importPath;
101
- }
102
- const serializedStyleRules = JSON.stringify(fileStyles);
103
- const urlParams = new URLSearchParams({
104
- from: this.resourcePath,
105
- plumeria: serializedStyleRules,
106
- });
107
- const virtualCssRequest = stringifyRequest(this, `${VIRTUAL_CSS_PATH}?${urlParams.toString()}`);
108
- const postfix = `\nimport ${virtualCssRequest};`;
109
- const pluginInstance = this._compiler?.options?.plugins.find((p) => p?.constructor?.name === 'PlumeriaPlugin');
110
- const fileKey = this.resourcePath;
111
- if (pluginInstance) {
112
- if (!pluginInstance?.__plumeriaRegistered) {
113
- pluginInstance.__plumeriaRegistered = new Map();
114
- }
115
- const cache = pluginInstance.__plumeriaRegistered;
116
- const previousRequest = cache.get(fileKey);
117
- if (previousRequest !== virtualCssRequest) {
118
- cache.set(fileKey, virtualCssRequest);
119
- pluginInstance.registerFileStyles(fileKey, fileStyles);
120
- }
121
- }
122
- let css = '';
123
- css = fs_1.default.readFileSync(path_1.default.resolve(__dirname, '../zero-virtual.css'), 'utf-8');
124
- function generateOrderedCSS(styles) {
125
- const sections = [];
126
- if (styles.keyframeStyles?.trim()) {
127
- if (!css.includes(styles.keyframeStyles))
128
- sections.push(styles.keyframeStyles);
129
- }
130
- if (styles.viewTransitionStyles?.trim()) {
131
- if (!css.includes(styles.viewTransitionStyles))
132
- sections.push(styles.viewTransitionStyles);
133
- }
134
- if (styles.themeStyles?.trim()) {
135
- if (!css.includes(styles.themeStyles))
136
- sections.push(styles.themeStyles);
137
- }
138
- if (styles.baseStyles?.trim()) {
139
- sections.push(styles.baseStyles);
140
- }
141
- return sections.join('\n');
142
- }
143
- const orderedCSS = generateOrderedCSS(fileStyles);
144
- const relativeId = path_1.default.relative(process.cwd(), this.resourcePath);
145
- const hmrCode = `
146
- if (module.hot) {
147
- module.hot.accept(${virtualCssRequest});
148
-
149
- const styleId = "plumeria-hmr";
150
- const fileKey = ${JSON.stringify(relativeId)};
151
-
152
- let styleEl = document.getElementById(styleId);
153
-
154
- if (!styleEl) {
155
- styleEl = document.createElement("style");
156
- styleEl.id = styleId;
157
- styleEl.setAttribute("data-plumeria-hmr", "");
158
- document.head.prepend(styleEl);
159
- styleEl.__plumeriaStyles = {};
160
- }
161
-
162
- styleEl.__plumeriaStyles[fileKey] = ${JSON.stringify(orderedCSS)};
163
- styleEl.textContent = Object.values(styleEl.__plumeriaStyles).join('\\n');
164
-
165
- module.hot.dispose(() => {
166
- if (styleEl && styleEl.__plumeriaStyles) {
167
- delete styleEl.__plumeriaStyles[fileKey];
168
- styleEl.textContent = Object.values(styleEl.__plumeriaStyles).join('\\n');
169
-
170
- if (Object.keys(styleEl.__plumeriaStyles).length === 0 && styleEl.parentNode) {
171
- styleEl.parentNode.removeChild(styleEl);
172
- }
173
- }
174
- });
175
- }
176
- `;
177
- if (hasCssCreate) {
178
- callback(null, source + hmrCode);
179
- return;
180
- }
181
- const useClientDirective = /^\s*['"]use client['"]/;
182
- if (!useClientDirective.test(source)) {
183
- callback(null, source + postfix);
184
- return;
185
- }
186
- callback(null, source);
187
- }