-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode-block-loader.js
196 lines (159 loc) · 4.98 KB
/
code-block-loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const { compile, transform } = require('@vanilla-extract/integration');
const evalCode = require('eval');
const { transformCss } = require('@vanilla-extract/css/transformCss');
const { setAdapter, removeAdapter } = require('@vanilla-extract/css/adapter');
const getAdapter = () => {
const localClassNames = new Set();
const composedClassLists = [];
let bufferedCSSObjs = [];
const cssFiles = {};
return {
adapter: {
appendCss: (cssObj) => {
bufferedCSSObjs.push(cssObj);
},
registerClassName: (className) => {
localClassNames.add(className);
},
registerComposition: (composition) => {
composedClassLists.push(composition);
},
markCompositionUsed: () => {},
onEndFileScope: (fileScope) => {
cssFiles[fileScope.filePath] = transformCss({
localClassNames: Array.from(localClassNames),
composedClassLists,
cssObjs: bufferedCSSObjs,
}).join('\n');
bufferedCSSObjs = [];
},
getIdentOption: () => 'debug',
},
cssFiles,
};
};
function extractFilesFromCodeBlock(code) {
const fileMatches = code.matchAll(/(?:\/\/\s(?<fileName>[\w\.]+\.tsx?))/g);
let lastIndex = code.length - 1;
return Array.from(fileMatches, (match) => ({
...match.groups,
index: match.index,
})).reduceRight((acc, curr) => {
const result = [
{
fileName: curr.fileName,
contents: code
.slice(curr.index + `// ${curr.fileName}`.length, lastIndex)
.trim(),
},
...acc,
];
lastIndex = curr.index;
return result;
}, []);
}
async function getCss(entrypointFile, files, rootContext) {
// Any relative file is considered virtual
const virtualFileFilter = /^\.\//;
const virtualFileNamespace = 'virtual-file-ns';
const { source: compiledSource } = await compile({
filePath: entrypointFile,
cwd: rootContext,
esbuildOptions: {
plugins: [
{
name: 'virtual-entrypoint',
setup(build) {
build.onResolve({ filter: virtualFileFilter }, ({ path }) => {
const file = files.find(({ fileName }) =>
path.includes(fileName),
);
return {
namespace: virtualFileNamespace,
path: file.fileName.replace(/\.css\.ts$/, ''),
};
});
build.onLoad(
{ filter: /.*/, namespace: virtualFileNamespace },
async ({ path }) => {
const file = files.find(({ fileName }) =>
fileName.includes(path),
);
if (file) {
const contents = await transform({
source: file.contents,
filePath: file.fileName,
rootPath: rootContext,
packageName: 'vanilla-extract-site',
identOption: 'debug',
});
return {
contents,
loader: 'ts',
resolveDir: rootContext,
};
}
},
);
},
},
],
},
});
const { adapter, cssFiles } = getAdapter();
setAdapter(adapter);
evalCode(compiledSource, entrypointFile, { console, process }, true);
removeAdapter(adapter);
return cssFiles;
}
async function loader(source) {
this.cacheable(true);
const callback = this.async();
try {
const rootContext = this.rootContext;
const result = source.matchAll(
/```(?<language>.+)\n(?<code>(?:.|\n)*?)```/g,
);
const codeBlocks = Array.from(result, (match) => ({
...match.groups,
startIndex: match.index,
endIndex: match.index + match[0].length,
}));
const newSource = [];
let currIndex = 0;
for (const { code, language, startIndex, endIndex } of codeBlocks) {
// Check for `tsx compiled` too so we can correctly highlight `tsx` code blocks but still
// compile subsequent `.css.ts` files
if (language !== 'ts compiled' && language !== 'tsx compiled') {
continue;
}
const files = extractFilesFromCodeBlock(code);
if (files.length === 0) {
continue;
}
let cssFiles = {};
const styleFilesNames = files
.filter((f) => f.fileName.endsWith('.css.ts'))
.map(({ fileName }) => `./${fileName}`);
for (const styleFileName of styleFilesNames) {
cssFiles = {
...cssFiles,
...(await getCss(styleFileName, files, rootContext)),
};
}
newSource.push(source.slice(currIndex, startIndex));
newSource.push(
`<compiledcode code={${JSON.stringify(files)}} css={${JSON.stringify(
cssFiles,
)}} />`,
);
currIndex = endIndex;
}
newSource.push(source.slice(currIndex));
return callback(null, newSource.join('\n'));
} catch (e) {
console.error(e);
return callback(e, source);
}
}
module.exports = loader;