@wyw-in-js/webpack-loader 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,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.
@@ -0,0 +1,18 @@
1
+ import { createFileReporter } from '@wyw-in-js/transform';
2
+ export const sharedState = {};
3
+ export class WYWinJSDebugPlugin {
4
+ constructor(options) {
5
+ const {
6
+ emitter,
7
+ onDone
8
+ } = createFileReporter(options ?? false);
9
+ sharedState.emitter = emitter;
10
+ this.onDone = onDone;
11
+ }
12
+ apply(compiler) {
13
+ compiler.hooks.shutdown.tap('WYWinJSDebug', () => {
14
+ this.onDone(process.cwd());
15
+ });
16
+ }
17
+ }
18
+ //# sourceMappingURL=WYWinJSDebugPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WYWinJSDebugPlugin.js","names":["createFileReporter","sharedState","WYWinJSDebugPlugin","constructor","options","emitter","onDone","apply","compiler","hooks","shutdown","tap","process","cwd"],"sources":["../src/WYWinJSDebugPlugin.ts"],"sourcesContent":["import type { Compiler } from 'webpack';\n\nimport type { EventEmitter, IFileReporterOptions } from '@wyw-in-js/transform';\nimport { createFileReporter } from '@wyw-in-js/transform';\n\nexport const sharedState: {\n emitter?: EventEmitter;\n} = {};\n\nexport class WYWinJSDebugPlugin {\n private readonly onDone: (root: string) => void;\n\n constructor(options?: IFileReporterOptions) {\n const { emitter, onDone } = createFileReporter(options ?? false);\n sharedState.emitter = emitter;\n this.onDone = onDone;\n }\n\n apply(compiler: Compiler) {\n compiler.hooks.shutdown.tap('WYWinJSDebug', () => {\n this.onDone(process.cwd());\n });\n }\n}\n"],"mappings":"AAGA,SAASA,kBAAkB,QAAQ,sBAAsB;AAEzD,OAAO,MAAMC,WAEZ,GAAG,CAAC,CAAC;AAEN,OAAO,MAAMC,kBAAkB,CAAC;EAG9BC,WAAWA,CAACC,OAA8B,EAAE;IAC1C,MAAM;MAAEC,OAAO;MAAEC;IAAO,CAAC,GAAGN,kBAAkB,CAACI,OAAO,IAAI,KAAK,CAAC;IAChEH,WAAW,CAACI,OAAO,GAAGA,OAAO;IAC7B,IAAI,CAACC,MAAM,GAAGA,MAAM;EACtB;EAEAC,KAAKA,CAACC,QAAkB,EAAE;IACxBA,QAAQ,CAACC,KAAK,CAACC,QAAQ,CAACC,GAAG,CAAC,cAAc,EAAE,MAAM;MAChD,IAAI,CAACL,MAAM,CAACM,OAAO,CAACC,GAAG,CAAC,CAAC,CAAC;IAC5B,CAAC,CAAC;EACJ;AACF"}
package/esm/cache.js ADDED
@@ -0,0 +1,40 @@
1
+ // memory cache, which is the default cache implementation in WYW-in-JS
2
+
3
+ class MemoryCache {
4
+ cache = new Map();
5
+ dependenciesCache = new Map();
6
+ get(key) {
7
+ return Promise.resolve(this.cache.get(key) ?? '');
8
+ }
9
+ getDependencies(key) {
10
+ return Promise.resolve(this.dependenciesCache.get(key) ?? []);
11
+ }
12
+ set(key, value) {
13
+ this.cache.set(key, value);
14
+ return Promise.resolve();
15
+ }
16
+ setDependencies(key, value) {
17
+ this.dependenciesCache.set(key, value);
18
+ return Promise.resolve();
19
+ }
20
+ }
21
+ export const memoryCache = new MemoryCache();
22
+
23
+ /**
24
+ * return cache instance from `options.cacheProvider`
25
+ * @param cacheProvider string | ICache | undefined
26
+ * @returns ICache instance
27
+ */
28
+ export const getCacheInstance = async cacheProvider => {
29
+ if (!cacheProvider) {
30
+ return memoryCache;
31
+ }
32
+ if (typeof cacheProvider === 'string') {
33
+ return require(cacheProvider);
34
+ }
35
+ if (typeof cacheProvider === 'object' && 'get' in cacheProvider && 'set' in cacheProvider) {
36
+ return cacheProvider;
37
+ }
38
+ throw new Error(`Invalid cache provider: ${cacheProvider}`);
39
+ };
40
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","names":["MemoryCache","cache","Map","dependenciesCache","get","key","Promise","resolve","getDependencies","set","value","setDependencies","memoryCache","getCacheInstance","cacheProvider","require","Error"],"sources":["../src/cache.ts"],"sourcesContent":["export interface ICache {\n get: (key: string) => Promise<string>;\n getDependencies?: (key: string) => Promise<string[]>;\n set: (key: string, value: string) => Promise<void>;\n setDependencies?: (key: string, value: string[]) => Promise<void>;\n}\n\n// memory cache, which is the default cache implementation in WYW-in-JS\n\nclass MemoryCache implements ICache {\n private cache: Map<string, string> = new Map();\n\n private dependenciesCache: Map<string, string[]> = new Map();\n\n public get(key: string): Promise<string> {\n return Promise.resolve(this.cache.get(key) ?? '');\n }\n\n public getDependencies(key: string): Promise<string[]> {\n return Promise.resolve(this.dependenciesCache.get(key) ?? []);\n }\n\n public set(key: string, value: string): Promise<void> {\n this.cache.set(key, value);\n return Promise.resolve();\n }\n\n public setDependencies(key: string, value: string[]): Promise<void> {\n this.dependenciesCache.set(key, value);\n return Promise.resolve();\n }\n}\n\nexport const memoryCache = new MemoryCache();\n\n/**\n * return cache instance from `options.cacheProvider`\n * @param cacheProvider string | ICache | undefined\n * @returns ICache instance\n */\nexport const getCacheInstance = async (\n cacheProvider: string | ICache | undefined\n): Promise<ICache> => {\n if (!cacheProvider) {\n return memoryCache;\n }\n if (typeof cacheProvider === 'string') {\n return require(cacheProvider);\n }\n if (\n typeof cacheProvider === 'object' &&\n 'get' in cacheProvider &&\n 'set' in cacheProvider\n ) {\n return cacheProvider;\n }\n throw new Error(`Invalid cache provider: ${cacheProvider}`);\n};\n"],"mappings":"AAOA;;AAEA,MAAMA,WAAW,CAAmB;EAC1BC,KAAK,GAAwB,IAAIC,GAAG,CAAC,CAAC;EAEtCC,iBAAiB,GAA0B,IAAID,GAAG,CAAC,CAAC;EAErDE,GAAGA,CAACC,GAAW,EAAmB;IACvC,OAAOC,OAAO,CAACC,OAAO,CAAC,IAAI,CAACN,KAAK,CAACG,GAAG,CAACC,GAAG,CAAC,IAAI,EAAE,CAAC;EACnD;EAEOG,eAAeA,CAACH,GAAW,EAAqB;IACrD,OAAOC,OAAO,CAACC,OAAO,CAAC,IAAI,CAACJ,iBAAiB,CAACC,GAAG,CAACC,GAAG,CAAC,IAAI,EAAE,CAAC;EAC/D;EAEOI,GAAGA,CAACJ,GAAW,EAAEK,KAAa,EAAiB;IACpD,IAAI,CAACT,KAAK,CAACQ,GAAG,CAACJ,GAAG,EAAEK,KAAK,CAAC;IAC1B,OAAOJ,OAAO,CAACC,OAAO,CAAC,CAAC;EAC1B;EAEOI,eAAeA,CAACN,GAAW,EAAEK,KAAe,EAAiB;IAClE,IAAI,CAACP,iBAAiB,CAACM,GAAG,CAACJ,GAAG,EAAEK,KAAK,CAAC;IACtC,OAAOJ,OAAO,CAACC,OAAO,CAAC,CAAC;EAC1B;AACF;AAEA,OAAO,MAAMK,WAAW,GAAG,IAAIZ,WAAW,CAAC,CAAC;;AAE5C;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMa,gBAAgB,GAAG,MAC9BC,aAA0C,IACtB;EACpB,IAAI,CAACA,aAAa,EAAE;IAClB,OAAOF,WAAW;EACpB;EACA,IAAI,OAAOE,aAAa,KAAK,QAAQ,EAAE;IACrC,OAAOC,OAAO,CAACD,aAAa,CAAC;EAC/B;EACA,IACE,OAAOA,aAAa,KAAK,QAAQ,IACjC,KAAK,IAAIA,aAAa,IACtB,KAAK,IAAIA,aAAa,EACtB;IACA,OAAOA,aAAa;EACtB;EACA,MAAM,IAAIE,KAAK,CAAE,2BAA0BF,aAAc,EAAC,CAAC;AAC7D,CAAC"}
package/esm/index.js ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * This file contains a Webpack 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 path from 'path';
8
+ import { logger } from '@wyw-in-js/shared';
9
+ import { transform, TransformCacheCollection } from '@wyw-in-js/transform';
10
+ import { sharedState } from './WYWinJSDebugPlugin';
11
+ import { getCacheInstance } from './cache';
12
+ export { WYWinJSDebugPlugin } from './WYWinJSDebugPlugin';
13
+ const outputCssLoader = require.resolve('./outputCssLoader');
14
+ const cache = new TransformCacheCollection();
15
+ const webpack5Loader = function webpack5LoaderPlugin(content, inputSourceMap) {
16
+ function convertSourceMap(value, filename) {
17
+ if (typeof value === 'string' || !value) {
18
+ return undefined;
19
+ }
20
+ return {
21
+ ...value,
22
+ file: value.file ?? filename,
23
+ mappings: value.mappings ?? '',
24
+ names: value.names ?? [],
25
+ sources: value.sources ?? [],
26
+ version: value.version ?? 3
27
+ };
28
+ }
29
+
30
+ // tell Webpack this loader is async
31
+ this.async();
32
+ logger('loader %s', this.resourcePath);
33
+ const {
34
+ sourceMap = undefined,
35
+ preprocessor = undefined,
36
+ extension = '.wyw-in-js.css',
37
+ cacheProvider,
38
+ ...rest
39
+ } = this.getOptions() || {};
40
+ const outputFileName = this.resourcePath.replace(/\.[^.]+$/, extension);
41
+ const resolveModule = this.getResolve({
42
+ dependencyType: 'esm'
43
+ });
44
+ const asyncResolve = (token, importer) => {
45
+ const context = path.isAbsolute(importer) ? path.dirname(importer) : path.join(process.cwd(), path.dirname(importer));
46
+ return new Promise((resolve, reject) => {
47
+ resolveModule(context, token, (err, result) => {
48
+ if (err) {
49
+ reject(err);
50
+ } else if (result) {
51
+ this.addDependency(result);
52
+ resolve(result);
53
+ } else {
54
+ reject(new Error(`Cannot resolve ${token}`));
55
+ }
56
+ });
57
+ });
58
+ };
59
+ const transformServices = {
60
+ options: {
61
+ filename: this.resourcePath,
62
+ inputSourceMap: convertSourceMap(inputSourceMap, this.resourcePath),
63
+ root: process.cwd(),
64
+ preprocessor,
65
+ pluginOptions: rest
66
+ },
67
+ cache,
68
+ eventEmitter: sharedState.emitter
69
+ };
70
+ transform(transformServices, content.toString(), asyncResolve).then(async result => {
71
+ if (result.cssText) {
72
+ let {
73
+ cssText
74
+ } = result;
75
+ if (sourceMap) {
76
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.cssSourceMapText || '').toString('base64')}*/`;
77
+ }
78
+ await Promise.all(result.dependencies?.map(dep => asyncResolve(dep, this.resourcePath)) ?? []);
79
+ try {
80
+ const cacheInstance = await getCacheInstance(cacheProvider);
81
+ await cacheInstance.set(this.resourcePath, cssText);
82
+ await cacheInstance.setDependencies?.(this.resourcePath, this.getDependencies());
83
+ const request = `${outputFileName}!=!${outputCssLoader}?cacheProvider=${encodeURIComponent(typeof cacheProvider === 'string' ? cacheProvider : '')}!${this.resourcePath}`;
84
+ const stringifiedRequest = JSON.stringify(this.utils.contextify(this.context || this.rootContext, request));
85
+ this.callback(null, `${result.code}\n\nrequire(${stringifiedRequest});`, result.sourceMap ?? undefined);
86
+ } catch (err) {
87
+ this.callback(err);
88
+ }
89
+ return;
90
+ }
91
+ this.callback(null, result.code, result.sourceMap ?? undefined);
92
+ }, err => this.callback(err)).catch(err => this.callback(err));
93
+ };
94
+ export default webpack5Loader;
95
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["path","logger","transform","TransformCacheCollection","sharedState","getCacheInstance","WYWinJSDebugPlugin","outputCssLoader","require","resolve","cache","webpack5Loader","webpack5LoaderPlugin","content","inputSourceMap","convertSourceMap","value","filename","undefined","file","mappings","names","sources","version","async","resourcePath","sourceMap","preprocessor","extension","cacheProvider","rest","getOptions","outputFileName","replace","resolveModule","getResolve","dependencyType","asyncResolve","token","importer","context","isAbsolute","dirname","join","process","cwd","Promise","reject","err","result","addDependency","Error","transformServices","options","root","pluginOptions","eventEmitter","emitter","toString","then","cssText","Buffer","from","cssSourceMapText","all","dependencies","map","dep","cacheInstance","set","setDependencies","getDependencies","request","encodeURIComponent","stringifiedRequest","JSON","stringify","utils","contextify","rootContext","callback","code","catch"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Webpack 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 path from 'path';\n\nimport type { RawSourceMap } from 'source-map';\nimport type { RawLoaderDefinitionFunction } from 'webpack';\n\nimport { logger } from '@wyw-in-js/shared';\nimport type { Preprocessor, Result } from '@wyw-in-js/transform';\nimport { transform, TransformCacheCollection } from '@wyw-in-js/transform';\n\nimport { sharedState } from './WYWinJSDebugPlugin';\nimport type { ICache } from './cache';\nimport { getCacheInstance } from './cache';\n\nexport { WYWinJSDebugPlugin } from './WYWinJSDebugPlugin';\n\nconst outputCssLoader = require.resolve('./outputCssLoader');\n\ntype Loader = RawLoaderDefinitionFunction<{\n cacheProvider?: string | ICache;\n extension?: string;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n}>;\n\nconst cache = new TransformCacheCollection();\n\nconst webpack5Loader: Loader = function webpack5LoaderPlugin(\n content,\n inputSourceMap\n) {\n function convertSourceMap(\n value: typeof inputSourceMap,\n filename: string\n ): RawSourceMap | undefined {\n if (typeof value === 'string' || !value) {\n return undefined;\n }\n\n return {\n ...value,\n file: value.file ?? filename,\n mappings: value.mappings ?? '',\n names: value.names ?? [],\n sources: value.sources ?? [],\n version: value.version ?? 3,\n };\n }\n\n // tell Webpack this loader is async\n this.async();\n\n logger('loader %s', this.resourcePath);\n\n const {\n sourceMap = undefined,\n preprocessor = undefined,\n extension = '.wyw-in-js.css',\n cacheProvider,\n ...rest\n } = this.getOptions() || {};\n\n const outputFileName = this.resourcePath.replace(/\\.[^.]+$/, extension);\n const resolveModule = this.getResolve({ dependencyType: 'esm' });\n\n const asyncResolve = (token: string, importer: string): Promise<string> => {\n const context = path.isAbsolute(importer)\n ? path.dirname(importer)\n : path.join(process.cwd(), path.dirname(importer));\n return new Promise((resolve, reject) => {\n resolveModule(context, token, (err, result) => {\n if (err) {\n reject(err);\n } else if (result) {\n this.addDependency(result);\n resolve(result);\n } else {\n reject(new Error(`Cannot resolve ${token}`));\n }\n });\n });\n };\n\n const transformServices = {\n options: {\n filename: this.resourcePath,\n inputSourceMap: convertSourceMap(inputSourceMap, this.resourcePath),\n root: process.cwd(),\n preprocessor,\n pluginOptions: rest,\n },\n cache,\n eventEmitter: sharedState.emitter,\n };\n\n transform(transformServices, content.toString(), asyncResolve)\n .then(\n async (result: Result) => {\n if (result.cssText) {\n let { cssText } = result;\n\n if (sourceMap) {\n cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(\n result.cssSourceMapText || ''\n ).toString('base64')}*/`;\n }\n\n await Promise.all(\n result.dependencies?.map((dep) =>\n asyncResolve(dep, this.resourcePath)\n ) ?? []\n );\n\n try {\n const cacheInstance = await getCacheInstance(cacheProvider);\n\n await cacheInstance.set(this.resourcePath, cssText);\n\n await cacheInstance.setDependencies?.(\n this.resourcePath,\n this.getDependencies()\n );\n\n const request = `${outputFileName}!=!${outputCssLoader}?cacheProvider=${encodeURIComponent(\n typeof cacheProvider === 'string' ? cacheProvider : ''\n )}!${this.resourcePath}`;\n const stringifiedRequest = JSON.stringify(\n this.utils.contextify(this.context || this.rootContext, request)\n );\n\n this.callback(\n null,\n `${result.code}\\n\\nrequire(${stringifiedRequest});`,\n result.sourceMap ?? undefined\n );\n } catch (err) {\n this.callback(err as Error);\n }\n\n return;\n }\n\n this.callback(null, result.code, result.sourceMap ?? undefined);\n },\n (err: Error) => this.callback(err)\n )\n .catch((err: Error) => this.callback(err));\n};\n\nexport default webpack5Loader;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,OAAOA,IAAI,MAAM,MAAM;AAKvB,SAASC,MAAM,QAAQ,mBAAmB;AAE1C,SAASC,SAAS,EAAEC,wBAAwB,QAAQ,sBAAsB;AAE1E,SAASC,WAAW,QAAQ,sBAAsB;AAElD,SAASC,gBAAgB,QAAQ,SAAS;AAE1C,SAASC,kBAAkB,QAAQ,sBAAsB;AAEzD,MAAMC,eAAe,GAAGC,OAAO,CAACC,OAAO,CAAC,mBAAmB,CAAC;AAS5D,MAAMC,KAAK,GAAG,IAAIP,wBAAwB,CAAC,CAAC;AAE5C,MAAMQ,cAAsB,GAAG,SAASC,oBAAoBA,CAC1DC,OAAO,EACPC,cAAc,EACd;EACA,SAASC,gBAAgBA,CACvBC,KAA4B,EAC5BC,QAAgB,EACU;IAC1B,IAAI,OAAOD,KAAK,KAAK,QAAQ,IAAI,CAACA,KAAK,EAAE;MACvC,OAAOE,SAAS;IAClB;IAEA,OAAO;MACL,GAAGF,KAAK;MACRG,IAAI,EAAEH,KAAK,CAACG,IAAI,IAAIF,QAAQ;MAC5BG,QAAQ,EAAEJ,KAAK,CAACI,QAAQ,IAAI,EAAE;MAC9BC,KAAK,EAAEL,KAAK,CAACK,KAAK,IAAI,EAAE;MACxBC,OAAO,EAAEN,KAAK,CAACM,OAAO,IAAI,EAAE;MAC5BC,OAAO,EAAEP,KAAK,CAACO,OAAO,IAAI;IAC5B,CAAC;EACH;;EAEA;EACA,IAAI,CAACC,KAAK,CAAC,CAAC;EAEZvB,MAAM,CAAC,WAAW,EAAE,IAAI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SAAS,CACvC,IAAI,CAACC,KAAK,CAACC,UAAU,CAAC,IAAI,CAACtC,OAAO,IAAI,IAAI,CAACuC,WAAW,EAAEP,OAAO,CACjE,CAAC;QAED,IAAI,CAACQ,QAAQ,CACX,IAAI,EACH,GAAE/B,MAAM,CAACgC,IAAK,eAAcP,kBAAmB,IAAG,EACnDzB,MAAM,CAACvB,SAAS,IAAIR,SACtB,CAAC;MACH,CAAC,CAAC,OAAO8B,GAAG,EAAE;QACZ,IAAI,CAACgC,QAAQ,CAAChC,GAAY,CAAC;MAC7B;MAEA;IACF;IAEA,IAAI,CAACgC,QAAQ,CAAC,IAAI,EAAE/B,MAAM,CAACgC,IAAI,EAAEhC,MAAM,CAACvB,SAAS,IAAIR,SAAS,CAAC;EACjE,CAAC,EACA8B,GAAU,IAAK,IAAI,CAACgC,QAAQ,CAAChC,GAAG,CACnC,CAAC,CACAkC,KAAK,CAAElC,GAAU,IAAK,IAAI,CAACgC,QAAQ,CAAChC,GAAG,CAAC,CAAC;AAC9C,CAAC;AAED,eAAerC,cAAc"}
@@ -0,0 +1,19 @@
1
+ import { getCacheInstance } from './cache';
2
+ export default async function outputCssLoader() {
3
+ this.async();
4
+ const {
5
+ cacheProvider
6
+ } = this.getOptions();
7
+ try {
8
+ const cacheInstance = await getCacheInstance(cacheProvider);
9
+ const result = await cacheInstance.get(this.resourcePath);
10
+ const dependencies = (await cacheInstance.getDependencies?.(this.resourcePath)) ?? [];
11
+ dependencies.forEach(dependency => {
12
+ this.addDependency(dependency);
13
+ });
14
+ this.callback(null, result);
15
+ } catch (err) {
16
+ this.callback(err);
17
+ }
18
+ }
19
+ //# sourceMappingURL=outputCssLoader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outputCssLoader.js","names":["getCacheInstance","outputCssLoader","async","cacheProvider","getOptions","cacheInstance","result","get","resourcePath","dependencies","getDependencies","forEach","dependency","addDependency","callback","err"],"sources":["../src/outputCssLoader.ts"],"sourcesContent":["import type webpack from 'webpack';\n\nimport type { ICache } from './cache';\nimport { getCacheInstance } from './cache';\n\nexport default async function outputCssLoader(\n this: webpack.LoaderContext<{ cacheProvider: string | ICache | undefined }>\n) {\n this.async();\n const { cacheProvider } = this.getOptions();\n\n try {\n const cacheInstance = await getCacheInstance(cacheProvider);\n\n const result = await cacheInstance.get(this.resourcePath);\n const dependencies =\n (await cacheInstance.getDependencies?.(this.resourcePath)) ?? [];\n\n dependencies.forEach((dependency) => {\n this.addDependency(dependency);\n });\n\n this.callback(null, result);\n } catch (err) {\n this.callback(err as Error);\n }\n}\n"],"mappings":"AAGA,SAASA,gBAAgB,QAAQ,SAAS;AAE1C,eAAe,eAAeC,eAAeA,CAAA,EAE3C;EACA,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,MAAM;IAAEC;EAAc,CAAC,GAAG,IAAI,CAACC,UAAU,CAAC,CAAC;EAE3C,IAAI;IACF,MAAMC,aAAa,GAAG,MAAML,gBAAgB,CAACG,aAAa,CAAC;IAE3D,MAAMG,MAAM,GAAG,MAAMD,aAAa,CAACE,GAAG,CAAC,IAAI,CAACC,YAAY,CAAC;IACzD,MAAMC,YAAY,GAChB,CAAC,MAAMJ,aAAa,CAACK,eAAe,GAAG,IAAI,CAACF,YAAY,CAAC,KAAK,EAAE;IAElEC,YAAY,CAACE,OAAO,CAAEC,UAAU,IAAK;MACnC,IAAI,CAACC,aAAa,CAACD,UAAU,CAAC;IAChC,CAAC,CAAC;IAEF,IAAI,CAACE,QAAQ,CAAC,IAAI,EAAER,MAAM,CAAC;EAC7B,CAAC,CAAC,OAAOS,GAAG,EAAE;IACZ,IAAI,CAACD,QAAQ,CAACC,GAAY,CAAC;EAC7B;AACF"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.sharedState = exports.WYWinJSDebugPlugin = void 0;
7
+ var _transform = require("@wyw-in-js/transform");
8
+ const sharedState = exports.sharedState = {};
9
+ class WYWinJSDebugPlugin {
10
+ constructor(options) {
11
+ const {
12
+ emitter,
13
+ onDone
14
+ } = (0, _transform.createFileReporter)(options !== null && options !== void 0 ? options : false);
15
+ sharedState.emitter = emitter;
16
+ this.onDone = onDone;
17
+ }
18
+ apply(compiler) {
19
+ compiler.hooks.shutdown.tap('WYWinJSDebug', () => {
20
+ this.onDone(process.cwd());
21
+ });
22
+ }
23
+ }
24
+ exports.WYWinJSDebugPlugin = WYWinJSDebugPlugin;
25
+ //# sourceMappingURL=WYWinJSDebugPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WYWinJSDebugPlugin.js","names":["_transform","require","sharedState","exports","WYWinJSDebugPlugin","constructor","options","emitter","onDone","createFileReporter","apply","compiler","hooks","shutdown","tap","process","cwd"],"sources":["../src/WYWinJSDebugPlugin.ts"],"sourcesContent":["import type { Compiler } from 'webpack';\n\nimport type { EventEmitter, IFileReporterOptions } from '@wyw-in-js/transform';\nimport { createFileReporter } from '@wyw-in-js/transform';\n\nexport const sharedState: {\n emitter?: EventEmitter;\n} = {};\n\nexport class WYWinJSDebugPlugin {\n private readonly onDone: (root: string) => void;\n\n constructor(options?: IFileReporterOptions) {\n const { emitter, onDone } = createFileReporter(options ?? false);\n sharedState.emitter = emitter;\n this.onDone = onDone;\n }\n\n apply(compiler: Compiler) {\n compiler.hooks.shutdown.tap('WYWinJSDebug', () => {\n this.onDone(process.cwd());\n });\n }\n}\n"],"mappings":";;;;;;AAGA,IAAAA,UAAA,GAAAC,OAAA;AAEO,MAAMC,WAEZ,GAAAC,OAAA,CAAAD,WAAA,GAAG,CAAC,CAAC;AAEC,MAAME,kBAAkB,CAAC;EAG9BC,WAAWA,CAACC,OAA8B,EAAE;IAC1C,MAAM;MAAEC,OAAO;MAAEC;IAAO,CAAC,GAAG,IAAAC,6BAAkB,EAACH,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAI,KAAK,CAAC;IAChEJ,WAAW,CAACK,OAAO,GAAGA,OAAO;IAC7B,IAAI,CAACC,MAAM,GAAGA,MAAM;EACtB;EAEAE,KAAKA,CAACC,QAAkB,EAAE;IACxBA,QAAQ,CAACC,KAAK,CAACC,QAAQ,CAACC,GAAG,CAAC,cAAc,EAAE,MAAM;MAChD,IAAI,CAACN,MAAM,CAACO,OAAO,CAACC,GAAG,CAAC,CAAC,CAAC;IAC5B,CAAC,CAAC;EACJ;AACF;AAACb,OAAA,CAAAC,kBAAA,GAAAA,kBAAA"}
package/lib/cache.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.memoryCache = exports.getCacheInstance = void 0;
7
+ // memory cache, which is the default cache implementation in WYW-in-JS
8
+
9
+ class MemoryCache {
10
+ cache = new Map();
11
+ dependenciesCache = new Map();
12
+ get(key) {
13
+ var _this$cache$get;
14
+ return Promise.resolve((_this$cache$get = this.cache.get(key)) !== null && _this$cache$get !== void 0 ? _this$cache$get : '');
15
+ }
16
+ getDependencies(key) {
17
+ var _this$dependenciesCac;
18
+ return Promise.resolve((_this$dependenciesCac = this.dependenciesCache.get(key)) !== null && _this$dependenciesCac !== void 0 ? _this$dependenciesCac : []);
19
+ }
20
+ set(key, value) {
21
+ this.cache.set(key, value);
22
+ return Promise.resolve();
23
+ }
24
+ setDependencies(key, value) {
25
+ this.dependenciesCache.set(key, value);
26
+ return Promise.resolve();
27
+ }
28
+ }
29
+ const memoryCache = exports.memoryCache = new MemoryCache();
30
+
31
+ /**
32
+ * return cache instance from `options.cacheProvider`
33
+ * @param cacheProvider string | ICache | undefined
34
+ * @returns ICache instance
35
+ */
36
+ const getCacheInstance = async cacheProvider => {
37
+ if (!cacheProvider) {
38
+ return memoryCache;
39
+ }
40
+ if (typeof cacheProvider === 'string') {
41
+ return require(cacheProvider);
42
+ }
43
+ if (typeof cacheProvider === 'object' && 'get' in cacheProvider && 'set' in cacheProvider) {
44
+ return cacheProvider;
45
+ }
46
+ throw new Error(`Invalid cache provider: ${cacheProvider}`);
47
+ };
48
+ exports.getCacheInstance = getCacheInstance;
49
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","names":["MemoryCache","cache","Map","dependenciesCache","get","key","_this$cache$get","Promise","resolve","getDependencies","_this$dependenciesCac","set","value","setDependencies","memoryCache","exports","getCacheInstance","cacheProvider","require","Error"],"sources":["../src/cache.ts"],"sourcesContent":["export interface ICache {\n get: (key: string) => Promise<string>;\n getDependencies?: (key: string) => Promise<string[]>;\n set: (key: string, value: string) => Promise<void>;\n setDependencies?: (key: string, value: string[]) => Promise<void>;\n}\n\n// memory cache, which is the default cache implementation in WYW-in-JS\n\nclass MemoryCache implements ICache {\n private cache: Map<string, string> = new Map();\n\n private dependenciesCache: Map<string, string[]> = new Map();\n\n public get(key: string): Promise<string> {\n return Promise.resolve(this.cache.get(key) ?? '');\n }\n\n public getDependencies(key: string): Promise<string[]> {\n return Promise.resolve(this.dependenciesCache.get(key) ?? []);\n }\n\n public set(key: string, value: string): Promise<void> {\n this.cache.set(key, value);\n return Promise.resolve();\n }\n\n public setDependencies(key: string, value: string[]): Promise<void> {\n this.dependenciesCache.set(key, value);\n return Promise.resolve();\n }\n}\n\nexport const memoryCache = new MemoryCache();\n\n/**\n * return cache instance from `options.cacheProvider`\n * @param cacheProvider string | ICache | undefined\n * @returns ICache instance\n */\nexport const getCacheInstance = async (\n cacheProvider: string | ICache | undefined\n): Promise<ICache> => {\n if (!cacheProvider) {\n return memoryCache;\n }\n if (typeof cacheProvider === 'string') {\n return require(cacheProvider);\n }\n if (\n typeof cacheProvider === 'object' &&\n 'get' in cacheProvider &&\n 'set' in cacheProvider\n ) {\n return cacheProvider;\n }\n throw new Error(`Invalid cache provider: ${cacheProvider}`);\n};\n"],"mappings":";;;;;;AAOA;;AAEA,MAAMA,WAAW,CAAmB;EAC1BC,KAAK,GAAwB,IAAIC,GAAG,CAAC,CAAC;EAEtCC,iBAAiB,GAA0B,IAAID,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AC,CAAC;AAC7D,CAAC;AAACF,OAAA,CAAAC,gBAAA,GAAAA,gBAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "WYWinJSDebugPlugin", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _WYWinJSDebugPlugin.WYWinJSDebugPlugin;
10
+ }
11
+ });
12
+ exports.default = void 0;
13
+ var _path = _interopRequireDefault(require("path"));
14
+ var _shared = require("@wyw-in-js/shared");
15
+ var _transform = require("@wyw-in-js/transform");
16
+ var _WYWinJSDebugPlugin = require("./WYWinJSDebugPlugin");
17
+ var _cache = require("./cache");
18
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
+ /**
20
+ * This file contains a Webpack loader for WYW-in-JS.
21
+ * It uses the transform.ts function to generate class names from source code,
22
+ * returns transformed code without template literals and attaches generated source maps
23
+ */
24
+
25
+ const outputCssLoader = require.resolve('./outputCssLoader');
26
+ const cache = new _transform.TransformCacheCollection();
27
+ const webpack5Loader = function webpack5LoaderPlugin(content, inputSourceMap) {
28
+ function convertSourceMap(value, filename) {
29
+ var _value$file, _value$mappings, _value$names, _value$sources, _value$version;
30
+ if (typeof value === 'string' || !value) {
31
+ return undefined;
32
+ }
33
+ return {
34
+ ...value,
35
+ file: (_value$file = value.file) !== null && _value$file !== void 0 ? _value$file : filename,
36
+ mappings: (_value$mappings = value.mappings) !== null && _value$mappings !== void 0 ? _value$mappings : '',
37
+ names: (_value$names = value.names) !== null && _value$names !== void 0 ? _value$names : [],
38
+ sources: (_value$sources = value.sources) !== null && _value$sources !== void 0 ? _value$sources : [],
39
+ version: (_value$version = value.version) !== null && _value$version !== void 0 ? _value$version : 3
40
+ };
41
+ }
42
+
43
+ // tell Webpack this loader is async
44
+ this.async();
45
+ (0, _shared.logger)('loader %s', this.resourcePath);
46
+ const {
47
+ sourceMap = undefined,
48
+ preprocessor = undefined,
49
+ extension = '.wyw-in-js.css',
50
+ cacheProvider,
51
+ ...rest
52
+ } = this.getOptions() || {};
53
+ const outputFileName = this.resourcePath.replace(/\.[^.]+$/, extension);
54
+ const resolveModule = this.getResolve({
55
+ dependencyType: 'esm'
56
+ });
57
+ const asyncResolve = (token, importer) => {
58
+ const context = _path.default.isAbsolute(importer) ? _path.default.dirname(importer) : _path.default.join(process.cwd(), _path.default.dirname(importer));
59
+ return new Promise((resolve, reject) => {
60
+ resolveModule(context, token, (err, result) => {
61
+ if (err) {
62
+ reject(err);
63
+ } else if (result) {
64
+ this.addDependency(result);
65
+ resolve(result);
66
+ } else {
67
+ reject(new Error(`Cannot resolve ${token}`));
68
+ }
69
+ });
70
+ });
71
+ };
72
+ const transformServices = {
73
+ options: {
74
+ filename: this.resourcePath,
75
+ inputSourceMap: convertSourceMap(inputSourceMap, this.resourcePath),
76
+ root: process.cwd(),
77
+ preprocessor,
78
+ pluginOptions: rest
79
+ },
80
+ cache,
81
+ eventEmitter: _WYWinJSDebugPlugin.sharedState.emitter
82
+ };
83
+ (0, _transform.transform)(transformServices, content.toString(), asyncResolve).then(async result => {
84
+ var _result$sourceMap2;
85
+ if (result.cssText) {
86
+ var _result$dependencies$, _result$dependencies;
87
+ let {
88
+ cssText
89
+ } = result;
90
+ if (sourceMap) {
91
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.cssSourceMapText || '').toString('base64')}*/`;
92
+ }
93
+ await Promise.all((_result$dependencies$ = (_result$dependencies = result.dependencies) === null || _result$dependencies === void 0 ? void 0 : _result$dependencies.map(dep => asyncResolve(dep, this.resourcePath))) !== null && _result$dependencies$ !== void 0 ? _result$dependencies$ : []);
94
+ try {
95
+ var _cacheInstance$setDep, _result$sourceMap;
96
+ const cacheInstance = await (0, _cache.getCacheInstance)(cacheProvider);
97
+ await cacheInstance.set(this.resourcePath, cssText);
98
+ await ((_cacheInstance$setDep = cacheInstance.setDependencies) === null || _cacheInstance$setDep === void 0 ? void 0 : _cacheInstance$setDep.call(cacheInstance, this.resourcePath, this.getDependencies()));
99
+ const request = `${outputFileName}!=!${outputCssLoader}?cacheProvider=${encodeURIComponent(typeof cacheProvider === 'string' ? cacheProvider : '')}!${this.resourcePath}`;
100
+ const stringifiedRequest = JSON.stringify(this.utils.contextify(this.context || this.rootContext, request));
101
+ this.callback(null, `${result.code}\n\nrequire(${stringifiedRequest});`, (_result$sourceMap = result.sourceMap) !== null && _result$sourceMap !== void 0 ? _result$sourceMap : undefined);
102
+ } catch (err) {
103
+ this.callback(err);
104
+ }
105
+ return;
106
+ }
107
+ this.callback(null, result.code, (_result$sourceMap2 = result.sourceMap) !== null && _result$sourceMap2 !== void 0 ? _result$sourceMap2 : undefined);
108
+ }, err => this.callback(err)).catch(err => this.callback(err));
109
+ };
110
+ var _default = exports.default = webpack5Loader;
111
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_path","_interopRequireDefault","require","_shared","_transform","_WYWinJSDebugPlugin","_cache","obj","__esModule","default","outputCssLoader","resolve","cache","TransformCacheCollection","webpack5Loader","webpack5LoaderPlugin","content","inputSourceMap","convertSourceMap","value","filename","_value$file","_value$mappings","_value$names","_value$sources","_value$version","undefined","file","mappings","names","sources","version","async","logger","resourcePath","sourceMap","preprocessor","extension","cacheProvider","rest","getOptions","outputFileName","replace","resolveModule","getResolve","dependencyType","asyncResolve","token","importer","context","path","isAbsolute","dirname","join","process","cwd","Promise","reject","err","result","addDependency","Error","transformServices","options","root","pluginOptions","eventEmitter","sharedState","emitter","transform","toString","then","_result$sourceMap2","cssText","_result$dependencies$","_result$dependencies","Buffer","from","cssSourceMapText","all","dependencies","map","dep","_cacheInstance$setDep","_result$sourceMap","cacheInstance","getCacheInstance","set","setDependencies","call","getDependencies","request","encodeURIComponent","stringifiedRequest","JSON","stringify","utils","contextify","rootContext","callback","code","catch","_default","exports"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * This file contains a Webpack 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 path from 'path';\n\nimport type { RawSourceMap } from 'source-map';\nimport type { RawLoaderDefinitionFunction } from 'webpack';\n\nimport { logger } from '@wyw-in-js/shared';\nimport type { Preprocessor, Result } from '@wyw-in-js/transform';\nimport { transform, TransformCacheCollection } from '@wyw-in-js/transform';\n\nimport { sharedState } from './WYWinJSDebugPlugin';\nimport type { ICache } from './cache';\nimport { getCacheInstance } from './cache';\n\nexport { WYWinJSDebugPlugin } from './WYWinJSDebugPlugin';\n\nconst outputCssLoader = require.resolve('./outputCssLoader');\n\ntype Loader = RawLoaderDefinitionFunction<{\n cacheProvider?: string | ICache;\n extension?: string;\n preprocessor?: Preprocessor;\n sourceMap?: boolean;\n}>;\n\nconst cache = new TransformCacheCollection();\n\nconst webpack5Loader: Loader = function webpack5LoaderPlugin(\n content,\n inputSourceMap\n) {\n function convertSourceMap(\n value: typeof inputSourceMap,\n filename: string\n ): RawSourceMap | undefined {\n if (typeof value === 'string' || !value) {\n return undefined;\n }\n\n return {\n ...value,\n file: value.file ?? filename,\n mappings: value.mappings ?? '',\n names: value.names ?? [],\n sources: value.sources ?? [],\n version: value.version ?? 3,\n };\n }\n\n // tell Webpack this loader is async\n this.async();\n\n logger('loader %s', this.resourcePath);\n\n const {\n sourceMap = undefined,\n preprocessor = undefined,\n extension = '.wyw-in-js.css',\n cacheProvider,\n ...rest\n } = this.getOptions() || {};\n\n const outputFileName = this.resourcePath.replace(/\\.[^.]+$/, extension);\n const resolveModule = this.getResolve({ dependencyType: 'esm' });\n\n const asyncResolve = (token: string, importer: string): Promise<string> => {\n const context = path.isAbsolute(importer)\n ? path.dirname(importer)\n : path.join(process.cwd(), path.dirname(importer));\n return new Promise((resolve, reject) => {\n resolveModule(context, token, (err, result) => {\n if (err) {\n reject(err);\n } else if (result) {\n this.addDependency(result);\n resolve(result);\n } else {\n reject(new Error(`Cannot resolve ${token}`));\n }\n });\n });\n };\n\n const transformServices = {\n options: {\n filename: this.resourcePath,\n inputSourceMap: convertSourceMap(inputSourceMap, this.resourcePath),\n root: process.cwd(),\n preprocessor,\n pluginOptions: rest,\n },\n cache,\n eventEmitter: sharedState.emitter,\n };\n\n transform(transformServices, content.toString(), asyncResolve)\n .then(\n async (result: Result) => {\n if (result.cssText) {\n let { cssText } = result;\n\n if (sourceMap) {\n cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(\n result.cssSourceMapText || ''\n ).toString('base64')}*/`;\n }\n\n await Promise.all(\n result.dependencies?.map((dep) =>\n asyncResolve(dep, this.resourcePath)\n ) ?? []\n );\n\n try {\n const cacheInstance = await getCacheInstance(cacheProvider);\n\n await cacheInstance.set(this.resourcePath, cssText);\n\n await cacheInstance.setDependencies?.(\n this.resourcePath,\n this.getDependencies()\n );\n\n const request = `${outputFileName}!=!${outputCssLoader}?cacheProvider=${encodeURIComponent(\n typeof cacheProvider === 'string' ? cacheProvider : ''\n )}!${this.resourcePath}`;\n const stringifiedRequest = JSON.stringify(\n this.utils.contextify(this.context || this.rootContext, request)\n );\n\n this.callback(\n null,\n `${result.code}\\n\\nrequire(${stringifiedRequest});`,\n result.sourceMap ?? undefined\n );\n } catch (err) {\n this.callback(err as Error);\n }\n\n return;\n }\n\n this.callback(null, result.code, result.sourceMap ?? undefined);\n },\n (err: Error) => this.callback(err)\n )\n .catch((err: Error) => this.callback(err));\n};\n\nexport default webpack5Loader;\n"],"mappings":";;;;;;;;;;;;AAMA,IAAAA,KAAA,GAAAC,sBAAA,CAAAC,OAAA;AAKA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAF,OAAA;AAEA,IAAAG,mBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAA2C,SAAAD,uBAAAM,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA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C;QACxB,MAAM2D,kBAAkB,GAAGC,IAAI,CAACC,SAAS,CACvC,IAAI,CAACC,KAAK,CAACC,UAAU,CAAC,IAAI,CAAChD,OAAO,IAAI,IAAI,CAACiD,WAAW,EAAEP,OAAO,CACjE,CAAC;QAED,IAAI,CAACQ,QAAQ,CACX,IAAI,EACH,GAAExC,MAAM,CAACyC,IAAK,eAAcP,kBAAmB,IAAG,GAAAT,iBAAA,GACnDzB,MAAM,CAACxB,SAAS,cAAAiD,iBAAA,cAAAA,iBAAA,GAAI1D,SACtB,CAAC;MACH,CAAC,CAAC,OAAOgC,GAAG,EAAE;QACZ,IAAI,CAACyC,QAAQ,CAACzC,GAAY,CAAC;MAC7B;MAEA;IACF;IAEA,IAAI,CAACyC,QAAQ,CAAC,IAAI,EAAExC,MAAM,CAACyC,IAAI,GAAA5B,kBAAA,GAAEb,MAAM,CAACxB,SAAS,cAAAqC,kBAAA,cAAAA,kBAAA,GAAI9C,SAAS,CAAC;EACjE,CAAC,EACAgC,GAAU,IAAK,IAAI,CAACyC,QAAQ,CAACzC,GAAG,CACnC,CAAC,CACA2C,KAAK,CAAE3C,GAAU,IAAK,IAAI,CAACyC,QAAQ,CAACzC,GAAG,CAAC,CAAC;AAC9C,CAAC;AAAC,IAAA4C,QAAA,GAAAC,OAAA,CAAA9F,OAAA,GAEaK,cAAc"}
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = outputCssLoader;
7
+ var _cache = require("./cache");
8
+ async function outputCssLoader() {
9
+ this.async();
10
+ const {
11
+ cacheProvider
12
+ } = this.getOptions();
13
+ try {
14
+ var _await$cacheInstance$, _cacheInstance$getDep;
15
+ const cacheInstance = await (0, _cache.getCacheInstance)(cacheProvider);
16
+ const result = await cacheInstance.get(this.resourcePath);
17
+ const dependencies = (_await$cacheInstance$ = await ((_cacheInstance$getDep = cacheInstance.getDependencies) === null || _cacheInstance$getDep === void 0 ? void 0 : _cacheInstance$getDep.call(cacheInstance, this.resourcePath))) !== null && _await$cacheInstance$ !== void 0 ? _await$cacheInstance$ : [];
18
+ dependencies.forEach(dependency => {
19
+ this.addDependency(dependency);
20
+ });
21
+ this.callback(null, result);
22
+ } catch (err) {
23
+ this.callback(err);
24
+ }
25
+ }
26
+ //# sourceMappingURL=outputCssLoader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outputCssLoader.js","names":["_cache","require","outputCssLoader","async","cacheProvider","getOptions","_await$cacheInstance$","_cacheInstance$getDep","cacheInstance","getCacheInstance","result","get","resourcePath","dependencies","getDependencies","call","forEach","dependency","addDependency","callback","err"],"sources":["../src/outputCssLoader.ts"],"sourcesContent":["import type webpack from 'webpack';\n\nimport type { ICache } from './cache';\nimport { getCacheInstance } from './cache';\n\nexport default async function outputCssLoader(\n this: webpack.LoaderContext<{ cacheProvider: string | ICache | undefined }>\n) {\n this.async();\n const { cacheProvider } = this.getOptions();\n\n try {\n const cacheInstance = await getCacheInstance(cacheProvider);\n\n const result = await cacheInstance.get(this.resourcePath);\n const dependencies =\n (await cacheInstance.getDependencies?.(this.resourcePath)) ?? [];\n\n dependencies.forEach((dependency) => {\n this.addDependency(dependency);\n });\n\n this.callback(null, result);\n } catch (err) {\n this.callback(err as Error);\n }\n}\n"],"mappings":";;;;;;AAGA,IAAAA,MAAA,GAAAC,OAAA;AAEe,eAAeC,eAAeA,CAAA,EAE3C;EACA,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,MAAM;IAAEC;EAAc,CAAC,GAAG,IAAI,CAACC,UAAU,CAAC,CAAC;EAE3C,IAAI;IAAA,IAAAC,qBAAA,EAAAC,qBAAA;IACF,MAAMC,aAAa,GAAG,MAAM,IAAAC,uBAAgB,EAACL,aAAa,CAAC;IAE3D,MAAMM,MAAM,GAAG,MAAMF,aAAa,CAACG,GAAG,CAAC,IAAI,CAACC,YAAY,CAAC;IACzD,MAAMC,YAAY,IAAAP,qBAAA,GACf,QAAAC,qBAAA,GAAMC,aAAa,CAACM,eAAe,cAAAP,qBAAA,uBAA7BA,qBAAA,CAAAQ,IAAA,CAAAP,aAAa,EAAmB,IAAI,CAACI,YAAY,CAAC,eAAAN,qBAAA,cAAAA,qBAAA,GAAK,EAAE;IAElEO,YAAY,CAACG,OAAO,CAAEC,UAAU,IAAK;MACnC,IAAI,CAACC,aAAa,CAACD,UAAU,CAAC;IAChC,CAAC,CAAC;IAEF,IAAI,CAACE,QAAQ,CAAC,IAAI,EAAET,MAAM,CAAC;EAC7B,CAAC,CAAC,OAAOU,GAAG,EAAE;IACZ,IAAI,CAACD,QAAQ,CAACC,GAAY,CAAC;EAC7B;AACF"}
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@wyw-in-js/webpack-loader",
3
+ "version": "0.1.0",
4
+ "dependencies": {
5
+ "@wyw-in-js/shared": "0.1.0",
6
+ "@wyw-in-js/transform": "0.1.0"
7
+ },
8
+ "devDependencies": {
9
+ "@types/node": "^16.18.55",
10
+ "source-map": "^0.7.4",
11
+ "webpack": "^5.76.0",
12
+ "@wyw-in-js/babel-config": "0.1.0",
13
+ "@wyw-in-js/eslint-config": "0.1.0",
14
+ "@wyw-in-js/ts-config": "0.1.0"
15
+ },
16
+ "engines": {
17
+ "node": ">=16.0.0"
18
+ },
19
+ "files": [
20
+ "esm/",
21
+ "lib/",
22
+ "types/"
23
+ ],
24
+ "license": "MIT",
25
+ "main": "lib/index.js",
26
+ "module": "esm/index.js",
27
+ "peerDependencies": {
28
+ "webpack": "^5.76.0"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "types": "types/index.d.ts",
34
+ "scripts": {
35
+ "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
36
+ "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
37
+ "build:types": "tsc --project ./tsconfig.lib.json --baseUrl . --rootDir ./src",
38
+ "lint": "eslint --ext .js,.ts ."
39
+ }
40
+ }
@@ -0,0 +1,10 @@
1
+ import type { Compiler } from 'webpack';
2
+ import type { EventEmitter, IFileReporterOptions } from '@wyw-in-js/transform';
3
+ export declare const sharedState: {
4
+ emitter?: EventEmitter;
5
+ };
6
+ export declare class WYWinJSDebugPlugin {
7
+ private readonly onDone;
8
+ constructor(options?: IFileReporterOptions);
9
+ apply(compiler: Compiler): void;
10
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WYWinJSDebugPlugin = exports.sharedState = void 0;
4
+ const transform_1 = require("@wyw-in-js/transform");
5
+ exports.sharedState = {};
6
+ class WYWinJSDebugPlugin {
7
+ onDone;
8
+ constructor(options) {
9
+ const { emitter, onDone } = (0, transform_1.createFileReporter)(options ?? false);
10
+ exports.sharedState.emitter = emitter;
11
+ this.onDone = onDone;
12
+ }
13
+ apply(compiler) {
14
+ compiler.hooks.shutdown.tap('WYWinJSDebug', () => {
15
+ this.onDone(process.cwd());
16
+ });
17
+ }
18
+ }
19
+ exports.WYWinJSDebugPlugin = WYWinJSDebugPlugin;
@@ -0,0 +1,22 @@
1
+ export interface ICache {
2
+ get: (key: string) => Promise<string>;
3
+ getDependencies?: (key: string) => Promise<string[]>;
4
+ set: (key: string, value: string) => Promise<void>;
5
+ setDependencies?: (key: string, value: string[]) => Promise<void>;
6
+ }
7
+ declare class MemoryCache implements ICache {
8
+ private cache;
9
+ private dependenciesCache;
10
+ get(key: string): Promise<string>;
11
+ getDependencies(key: string): Promise<string[]>;
12
+ set(key: string, value: string): Promise<void>;
13
+ setDependencies(key: string, value: string[]): Promise<void>;
14
+ }
15
+ export declare const memoryCache: MemoryCache;
16
+ /**
17
+ * return cache instance from `options.cacheProvider`
18
+ * @param cacheProvider string | ICache | undefined
19
+ * @returns ICache instance
20
+ */
21
+ export declare const getCacheInstance: (cacheProvider: string | ICache | undefined) => Promise<ICache>;
22
+ export {};
package/types/cache.js ADDED
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCacheInstance = exports.memoryCache = void 0;
4
+ // memory cache, which is the default cache implementation in WYW-in-JS
5
+ class MemoryCache {
6
+ cache = new Map();
7
+ dependenciesCache = new Map();
8
+ get(key) {
9
+ return Promise.resolve(this.cache.get(key) ?? '');
10
+ }
11
+ getDependencies(key) {
12
+ return Promise.resolve(this.dependenciesCache.get(key) ?? []);
13
+ }
14
+ set(key, value) {
15
+ this.cache.set(key, value);
16
+ return Promise.resolve();
17
+ }
18
+ setDependencies(key, value) {
19
+ this.dependenciesCache.set(key, value);
20
+ return Promise.resolve();
21
+ }
22
+ }
23
+ exports.memoryCache = new MemoryCache();
24
+ /**
25
+ * return cache instance from `options.cacheProvider`
26
+ * @param cacheProvider string | ICache | undefined
27
+ * @returns ICache instance
28
+ */
29
+ const getCacheInstance = async (cacheProvider) => {
30
+ if (!cacheProvider) {
31
+ return exports.memoryCache;
32
+ }
33
+ if (typeof cacheProvider === 'string') {
34
+ return require(cacheProvider);
35
+ }
36
+ if (typeof cacheProvider === 'object' &&
37
+ 'get' in cacheProvider &&
38
+ 'set' in cacheProvider) {
39
+ return cacheProvider;
40
+ }
41
+ throw new Error(`Invalid cache provider: ${cacheProvider}`);
42
+ };
43
+ exports.getCacheInstance = getCacheInstance;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This file contains a Webpack 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 { RawLoaderDefinitionFunction } from 'webpack';
7
+ import type { Preprocessor } from '@wyw-in-js/transform';
8
+ import type { ICache } from './cache';
9
+ export { WYWinJSDebugPlugin } from './WYWinJSDebugPlugin';
10
+ type Loader = RawLoaderDefinitionFunction<{
11
+ cacheProvider?: string | ICache;
12
+ extension?: string;
13
+ preprocessor?: Preprocessor;
14
+ sourceMap?: boolean;
15
+ }>;
16
+ declare const webpack5Loader: Loader;
17
+ export default webpack5Loader;
package/types/index.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * This file contains a Webpack 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
+ exports.WYWinJSDebugPlugin = void 0;
12
+ const path_1 = __importDefault(require("path"));
13
+ const shared_1 = require("@wyw-in-js/shared");
14
+ const transform_1 = require("@wyw-in-js/transform");
15
+ const WYWinJSDebugPlugin_1 = require("./WYWinJSDebugPlugin");
16
+ const cache_1 = require("./cache");
17
+ var WYWinJSDebugPlugin_2 = require("./WYWinJSDebugPlugin");
18
+ Object.defineProperty(exports, "WYWinJSDebugPlugin", { enumerable: true, get: function () { return WYWinJSDebugPlugin_2.WYWinJSDebugPlugin; } });
19
+ const outputCssLoader = require.resolve('./outputCssLoader');
20
+ const cache = new transform_1.TransformCacheCollection();
21
+ const webpack5Loader = function webpack5LoaderPlugin(content, inputSourceMap) {
22
+ function convertSourceMap(value, filename) {
23
+ if (typeof value === 'string' || !value) {
24
+ return undefined;
25
+ }
26
+ return {
27
+ ...value,
28
+ file: value.file ?? filename,
29
+ mappings: value.mappings ?? '',
30
+ names: value.names ?? [],
31
+ sources: value.sources ?? [],
32
+ version: value.version ?? 3,
33
+ };
34
+ }
35
+ // tell Webpack this loader is async
36
+ this.async();
37
+ (0, shared_1.logger)('loader %s', this.resourcePath);
38
+ const { sourceMap = undefined, preprocessor = undefined, extension = '.wyw-in-js.css', cacheProvider, ...rest } = this.getOptions() || {};
39
+ const outputFileName = this.resourcePath.replace(/\.[^.]+$/, extension);
40
+ const resolveModule = this.getResolve({ dependencyType: 'esm' });
41
+ const asyncResolve = (token, importer) => {
42
+ const context = path_1.default.isAbsolute(importer)
43
+ ? path_1.default.dirname(importer)
44
+ : path_1.default.join(process.cwd(), path_1.default.dirname(importer));
45
+ return new Promise((resolve, reject) => {
46
+ resolveModule(context, token, (err, result) => {
47
+ if (err) {
48
+ reject(err);
49
+ }
50
+ else if (result) {
51
+ this.addDependency(result);
52
+ resolve(result);
53
+ }
54
+ else {
55
+ reject(new Error(`Cannot resolve ${token}`));
56
+ }
57
+ });
58
+ });
59
+ };
60
+ const transformServices = {
61
+ options: {
62
+ filename: this.resourcePath,
63
+ inputSourceMap: convertSourceMap(inputSourceMap, this.resourcePath),
64
+ root: process.cwd(),
65
+ preprocessor,
66
+ pluginOptions: rest,
67
+ },
68
+ cache,
69
+ eventEmitter: WYWinJSDebugPlugin_1.sharedState.emitter,
70
+ };
71
+ (0, transform_1.transform)(transformServices, content.toString(), asyncResolve)
72
+ .then(async (result) => {
73
+ if (result.cssText) {
74
+ let { cssText } = result;
75
+ if (sourceMap) {
76
+ cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.cssSourceMapText || '').toString('base64')}*/`;
77
+ }
78
+ await Promise.all(result.dependencies?.map((dep) => asyncResolve(dep, this.resourcePath)) ?? []);
79
+ try {
80
+ const cacheInstance = await (0, cache_1.getCacheInstance)(cacheProvider);
81
+ await cacheInstance.set(this.resourcePath, cssText);
82
+ await cacheInstance.setDependencies?.(this.resourcePath, this.getDependencies());
83
+ const request = `${outputFileName}!=!${outputCssLoader}?cacheProvider=${encodeURIComponent(typeof cacheProvider === 'string' ? cacheProvider : '')}!${this.resourcePath}`;
84
+ const stringifiedRequest = JSON.stringify(this.utils.contextify(this.context || this.rootContext, request));
85
+ this.callback(null, `${result.code}\n\nrequire(${stringifiedRequest});`, result.sourceMap ?? undefined);
86
+ }
87
+ catch (err) {
88
+ this.callback(err);
89
+ }
90
+ return;
91
+ }
92
+ this.callback(null, result.code, result.sourceMap ?? undefined);
93
+ }, (err) => this.callback(err))
94
+ .catch((err) => this.callback(err));
95
+ };
96
+ exports.default = webpack5Loader;
@@ -0,0 +1,5 @@
1
+ import type webpack from 'webpack';
2
+ import type { ICache } from './cache';
3
+ export default function outputCssLoader(this: webpack.LoaderContext<{
4
+ cacheProvider: string | ICache | undefined;
5
+ }>): Promise<void>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const cache_1 = require("./cache");
4
+ async function outputCssLoader() {
5
+ this.async();
6
+ const { cacheProvider } = this.getOptions();
7
+ try {
8
+ const cacheInstance = await (0, cache_1.getCacheInstance)(cacheProvider);
9
+ const result = await cacheInstance.get(this.resourcePath);
10
+ const dependencies = (await cacheInstance.getDependencies?.(this.resourcePath)) ?? [];
11
+ dependencies.forEach((dependency) => {
12
+ this.addDependency(dependency);
13
+ });
14
+ this.callback(null, result);
15
+ }
16
+ catch (err) {
17
+ this.callback(err);
18
+ }
19
+ }
20
+ exports.default = outputCssLoader;