-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.js
360 lines (313 loc) · 9.14 KB
/
index.test.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
const Vinyl = require('vinyl');
const fs = require('fs');
const path = require('path');
const sass = require('sass');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const tap = require('gulp-tap');
const { async, sync } = require('.');
const replaceExt = require('replace-ext');
const TEST_DIR = path.join(__dirname, 'tests');
/**
* Normalises newlines and trims whitespace from the beginning and
* end of the provided string or buffer.
*
* @param {string|Buffer} input
*/
const normalise = input => {
return input.toString().replace(/[\r\n]+/gu, '\n').trim();
};
/**
* Hastily decode the JSON of an embedded sourcemap within a buffer. Handles URI and Base64 encoding,
* but otherwise this function is only intended for these tests and not a universal solution.
*
* @param {Buffer} buffer
*/
const extractSourceMap = buffer => {
const sourceMapPattern = /(?<=sourceMappingURL=)(?<url>.*)(?=\s*\*\/)/i;
const contents = buffer.toString('utf-8');
const match = contents.match(sourceMapPattern);
if (match) {
const urlPattern = /(?:data:)([^;,]+)(;[^;,]+)*?(?<isBase64>;base64)?(?:,)(?<contents>.*)/;
const urlMatch = match.groups.url.match(urlPattern);
if (urlMatch) {
let contents = urlMatch.groups.contents;
if (urlMatch.groups.isBase64) {
contents = Buffer.from(contents, 'base64').toString('utf-8');
} else {
contents = decodeURI(contents);
}
try {
return JSON.parse(contents.trim());
} catch (e) {
console.warn(e);
return null;
}
}
}
return null;
};
/**
* Creates a new Vinyl file from `input.scss` in the provided directory,
* then passes that to the plugin to be compiled. Results are compared
* with `expected.css` from the provided directory.
*
* @param {(sass: any, options: any) => internal.Transform} compiler
* @param {string} testDirectory
* @param {sass.Options<"sync" | "async">} options
* @returns {Promise<Vinyl>}
*/
const compileTestDirectory = (compiler, testDirectory, options = {}) => {
const filePath = path.join(testDirectory, 'input.scss');
const file = new Vinyl({
cwd: __dirname,
base: testDirectory,
path: filePath,
contents: fs.readFileSync(filePath),
stat: fs.statSync(filePath),
});
return new Promise((resolve, reject) => {
const stream = compiler(sass, {
style: 'compressed',
...options,
}).on('error', error => {
reject(error);
});
stream.write(file);
stream.end(() => {
resolve(file);
});
});
};
const OPTS_SYNC_IMPORTS = {
importers: [
{
/**
* @param {string} url
* @returns {URL|null}
*/
canonicalize(url) {
return url.startsWith('color:') ? new URL(url) : null;
},
/**
* @param {URL} url
* @returns {Promise<{ contents: string, syntax: string }>}
*/
load(url) {
return {
contents: `body { color: ${ url.pathname }; }`,
syntax: 'scss',
};
},
},
],
};
const OPTS_ASYNC_IMPORTS = {
importers: [
{
/**
* @param {string} url
* @returns {Promise<URL|null>}
*/
canonicalize(url) {
return new Promise(resolve => {
setTimeout(() => {
resolve(url.startsWith('color:') ? new URL(url) : null);
}, 500);
});
},
/**
* @param {URL} url
* @returns {Promise<{ contents: string, syntax: string }>}
*/
load(url) {
return new Promise(resolve => {
setTimeout(() => {
resolve({
contents: `body { color: ${ url.pathname }; }`,
syntax: 'scss',
});
}, 500);
});
},
},
],
};
describe.each([
['Async', async],
['Sync', sync],
])(`%s compilation`, (_name, compiler) => {
test.each([
['Compiles @import directive', 'imports', {}],
['Compiles empty input file', 'empty', {}],
['Compiles @use directive', 'use', {}],
['Compiles @use directive with named members', 'use-members', {}],
['Compiles @use with @forward directives', 'forward', {}],
['Compiles with custom synchronous importers', 'importers', OPTS_SYNC_IMPORTS],
])('%s', async (_message, directoryName, options) => {
const testDirectory = path.join(TEST_DIR, directoryName);
const expected = normalise(fs.readFileSync(path.join(testDirectory, 'expected.css'), 'utf-8'));
const file = await compileTestDirectory(compiler, testDirectory, options);
expect(path.extname(file.path)).toBe('.css');
expect(normalise(file.contents)).toBe(expected);
});
test('Fails on invalid SCSS', () => {
const file = new Vinyl({
cwd: TEST_DIR,
base: TEST_DIR,
path: path.join(__dirname, 'invalid.scss'),
contents: Buffer.from('body { !background: red; }'),
});
expect(() => {
return new Promise((resolve, reject) => {
const stream = compiler(sass, {
style: 'compressed',
}).on('error', error => {
reject(error);
});
stream.write(file);
stream.end(() => {
resolve(file);
});
});
}).rejects.toThrow(/^expected/iu);
});
test("File's atimeMs, mtimeMs, and ctimeMs stats are updated", async () => {
const testDirectory = path.join(TEST_DIR, 'imports');
const testFile = path.join(testDirectory, 'input.scss');
const stats = fs.statSync(testFile);
const file = await compileTestDirectory(sync, testDirectory);
expect(file.stat.atimeMs).toBeGreaterThan(stats.atimeMs);
expect(file.stat.mtimeMs).toBeGreaterThan(stats.mtimeMs);
expect(file.stat.ctimeMs).toBeGreaterThan(stats.ctimeMs);
});
describe('gulp', () => {
const filePath = path.join(TEST_DIR, 'sourcemaps', 'input.scss');
const outputPath = path.join(path.dirname(filePath), 'results');
const trashResults = () => {
fs.readdirSync(outputPath, 'utf-8').forEach(file => {
if (['.css', '.map'].includes(path.extname(file))) {
fs.unlinkSync(path.join(outputPath, file));
}
});
};
beforeAll(trashResults);
afterEach(trashResults);
test('Works with gulp-sourcemaps', () => {
return new Promise((resolve, reject) => {
gulp.src(filePath)
.pipe(sourcemaps.init())
.pipe(compiler(sass))
.pipe(sourcemaps.write())
.pipe(tap(file => {
try {
expect(file).toHaveProperty('sourceMap');
expect(extractSourceMap(file.contents)).toMatchObject({
file: replaceExt(path.basename(filePath), '.css'),
names: [],
sources: [
/\/_imported.scss$/,
],
});
} catch (e) {
reject(e);
}
}))
.on('finish', () => {
resolve();
});
});
});
test('Works with internal inlined sourcemap support', async () => {
await new Promise(resolve => {
gulp.src(filePath, { sourcemaps: true })
.pipe(compiler(sass))
.pipe(gulp.dest(outputPath, {
sourcemaps: true,
}))
.on('finish', () => {
resolve();
});
});
const outputFile = path.join(outputPath, 'input.css');
const outputContents = fs.readFileSync(outputFile);
expect(extractSourceMap(outputContents)).toMatchObject({
file: path.basename(outputFile),
names: [],
sources: [
/\/_imported.scss$/,
],
});
});
test('Works with internal external sourcemap support', async () => {
await new Promise(resolve => {
gulp.src(filePath, { sourcemaps: true })
.pipe(compiler(sass))
.pipe(gulp.dest(outputPath, {
sourcemaps: '.',
}))
.on('finish', () => {
resolve();
});
});
const outputFile = path.join(outputPath, 'input.css');
const outputContents = fs.readFileSync(outputFile, 'utf-8');
expect(outputContents).toMatch(/sourceMappingURL=input\.css\.map/);
});
});
});
describe(`Async compilation`, () => {
test('Compiles with custom async importers', async () => {
const testDirectory = path.join(TEST_DIR, 'importers');
const expected = normalise(fs.readFileSync(path.join(testDirectory, 'expected.css'), 'utf-8'));
const file = await compileTestDirectory(async, testDirectory, OPTS_ASYNC_IMPORTS);
expect(path.extname(file.path)).toBe('.css');
expect(normalise(file.contents)).toBe(expected);
});
});
describe(`Sync compilation`, () => {
test('Cannot use async importers with sync compilation', () => {
expect(() => {
const testDirectory = path.join(TEST_DIR, 'importers');
return compileTestDirectory(sync, testDirectory, OPTS_ASYNC_IMPORTS);
}).rejects.toThrow(/canonicalize.*synchronous compile functions/iu);
});
});
describe('normalise()', () => {
test('Trims', () => {
const a = ' test\r\nline\r\n ';
expect(normalise(a)).toBe('test\nline');
});
});
describe('extractSourceMap()', () => {
const INPUT = {
version: 3,
sourceRoot: '',
sources: ['_imported.scss'],
names: [],
mappings: 'AAAA,KACC',
file: 'expected.css',
};
const URL_ENCODED_INPUT = [
'/*# sourceMappingURL=',
'data:application/json,',
encodeURI(JSON.stringify(INPUT)),
' */',
].join('');
const BASE64_INPUT = [
'/*# sourceMappingURL=',
'data:application/json;base64,',
Buffer.from(JSON.stringify(INPUT), 'utf-8').toString('base64'),
' */',
].join('');
test('Extracts JSON from URL-encoded sourcemap', () => {
const result = extractSourceMap(URL_ENCODED_INPUT);
expect(result).not.toBeNull();
expect(result).toMatchObject(INPUT);
});
test('Extracts JSON from base64 encoded sourcemap', () => {
const result = extractSourceMap(BASE64_INPUT);
expect(result).not.toBeNull();
expect(result).toMatchObject(INPUT);
});
});