forked from wessberg/Polyfiller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-content-injector.js
346 lines (304 loc) · 10.1 KB
/
file-content-injector.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
import fs from "fs";
[
{
action: "copy",
source: "node_modules/@webcomponents/shadycss",
destination: "polyfill-lib/@webcomponents/shadycss-experimental"
},
{
action: "create",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/calc-parse.js",
text: `/**
@license
Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
/** @enum {string} */
const CssExpressionKind = {
CssCalcExpression: 'CssCalcExpression',
CssOtherExpression: 'CssOtherExpression'
};
/** @typedef {{pos: number, end: number}} */
let TextSpan; // eslint-disable-line no-unused-vars
/** @typedef {{kind: CssExpressionKind, text: string, span: Text}} */
let CssOtherExpression; // eslint-disable-line no-unused-vars
/** @typedef {{kind: CssExpressionKind, text: string, span: Text, children: Array<CssExpression>}} */
let CssCalcExpression; // eslint-disable-line no-unused-vars
/** @typedef {CssOtherExpression|CssCalcExpression} */
let CssExpression; // eslint-disable-line no-unused-vars
/**
* A Regular Expression that matches the string 'calc('
* @const
* @type {RegExp}
*/
const CALC_REGEXP = /calc\\(/g;
/**
* Visits and stringifies the given CssCalcExpression
* @param {CssCalcExpression} expression
* @param {number} depth
* @returns {string}
*/
function visitCssCalcExpression (expression, depth) {
return depth === 0
? \`calc(\${visitCssExpressions(expression.children, depth + 1)})\`
: \`(\${visitCssExpressions(expression.children, depth + 1)})\`;
}
/**
* Visits and stringifies the given CSSOtherExpression
* @param {CssOtherExpression} expression
* @returns {string}
*/
function visitCssOtherExpression (expression) {
return expression.text;
}
/**
* Visits and stringifies the given CSSExpression
* @param {CssExpression} expression
* @param {number} depth
* @returns {string}
*/
function visitCssExpression (expression, depth) {
switch (expression.kind) {
case CssExpressionKind.CssCalcExpression:
return visitCssCalcExpression( /** @type {CssCalcExpression} */ (expression), depth);
case CssExpressionKind.CssOtherExpression:
return visitCssOtherExpression(/** @type {CssOtherExpression} */ (expression));
default:
return '';
}
}
/**
* Visits the given CSSExpressions and stringifies them
* @param {Array<CssExpression>} expressions
* @param {number} [depth=0]
* @returns {string}
*/
function visitCssExpressions (expressions, depth = 0) {
return expressions.map(exp => visitCssExpression(exp, /** @type {number} */ (depth))).join('');
}
/**
* A minimal parser that checks CSS declaration values for 'calc' expressions and generates a syntax tree
* @param {string} input
* @param {TextSpan} offset
* @returns {Array<CssExpression>}
*/
function parseCalc (input, offset = {pos: 0, end: input.length}) {
let cursor = offset.pos + -1;
const syntax = [];
const isEOF = () => cursor >= input.length || cursor >= offset.end;
const nextToken = () => input[++cursor];
const peek = positions => input[cursor + positions];
/** @type {Array<string>} */
let readBuffer = [];
let readingStartCursor = cursor;
let reading = false;
let ignore = false;
const startReading = () => {
readingStartCursor = cursor;
reading = true;
};
const flushReadBuffer = () => {
reading = false;
if (readBuffer.length > 0) {
syntax.push({
kind: CssExpressionKind.CssOtherExpression,
span: {
pos: readingStartCursor,
end: cursor
},
text: input.slice(readingStartCursor, cursor)
});
}
readBuffer = [];
readingStartCursor = cursor;
};
while (!isEOF()) {
const next = nextToken();
let peekIndex = 0;
// Check if the next token leads to a 'calc' expression
if (
!ignore &&
next === 'c' &&
peek(++peekIndex) === 'a' &&
peek(++peekIndex) === 'l' &&
peek(++peekIndex) === 'c' &&
peek(++peekIndex) === '('
) {
flushReadBuffer();
let leftParensCount = 0;
while (peekIndex < input.length) {
const nextPeek = peek(peekIndex++);
if (nextPeek === '(') {
leftParensCount++;
} else if (nextPeek === ')') {
leftParensCount--;
if (leftParensCount === 0) {
break;
}
}
}
const span = {
pos: cursor,
end: cursor + peekIndex
};
const innerSpan = {
pos: span.pos + 'calc('.length,
end: span.end - 1
};
syntax.push({
kind: CssExpressionKind.CssCalcExpression,
span,
text: input.slice(span.pos, span.end),
children: parseCalc(input, innerSpan)
});
cursor = span.end;
readingStartCursor = span.end;
reading = true;
} else {
// The next char may be the beginning of a comment
if (
next === '/' &&
peek(1) === '*'
) {
ignore = true;
}
// The next char may be the beginning of the end of a comment
else if (
next === '*' &&
peek(1) === '/'
) {
ignore = false;
}
// Read the input and add to the read buffer
if (!reading) {
startReading();
}
if (next != null) {
readBuffer.push(next);
}
}
}
// Stop reading
flushReadBuffer();
return syntax;
}
/**
* Reduces 'calc(...)'s inside the given expression which can cssText, a CSS declaration, or a ruleset
* @param {string} expression
* @return {string}
*/
export function reduceCalc (expression) {
// This heuristic takes a fast path if possible
const calcMatch = expression.match(CALC_REGEXP);
// If the expression doesn't include 'calc' or if it only includes one, there's nothing to reduce here.
if (calcMatch == null || calcMatch.length < 2) {
return expression;
}
// Otherwise, parse the expression into a syntax tree before reducing it
const parseResults = parseCalc(expression);
return visitCssExpressions(parseResults);
}`
},
{
action: "replace",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/css-parse.js",
match: String.raw`/**`,
replacement: `import {reduceCalc} from './calc-parse.js';\n/**`
},
{
action: "replace",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/css-parse.js",
match: String.raw`removeCustomProps(node['cssText']);`,
replacement: String.raw`reduceCalc(removeCustomProps(node['cssText']));`
},
{
action: "replace",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/style-properties.js",
match: String.raw`return method && method.call(this, selector);`,
replacement: `
try {
return method && method.call(this, selector);
} catch (ex) {
return false;
}`
},
// Have it remove all rules containing :focus-visible
{
action: "replace",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/style-transformer.js",
match: String.raw`const MATCHES =`,
replacement: `const FOCUS_VISIBLE = /:(?:focus-visible)/;\nconst MATCHES =`
},
{
action: "replace",
file: "polyfill-lib/@webcomponents/shadycss-experimental/src/style-transformer.js",
match: String.raw`let stop = false;`,
replacement: String.raw`
let stop = false;
const isFocusVisible = FOCUS_VISIBLE.test(selector);
if (isFocusVisible) {
return undefined;
}`
},
].forEach(replace);
function replace(entry) {
switch (entry.action) {
case "copy": {
const {source, destination} = entry;
if (!fs.existsSync(source)) {
throw new ReferenceError(`Source does not exist: ${source}`);
}
fs.cpSync(source, destination, {force: true, recursive: true});
console.log("Copied:", source, "over to:", destination);
break;
}
case "create": {
const {file, text} = entry;
if (!fs.existsSync(file)) {
fs.writeFileSync(file, text);
console.log("Wrote file:", file, "to disk");
} else {
const fileContents = fs.readFileSync(file, "utf8");
if (fileContents !== text) {
fs.writeFileSync(file, text);
console.log("Updated contents of file:", file);
}
}
break;
}
case "replace": {
const {file, match, replacement, replacementFile} = entry;
if (!fs.existsSync(file)) {
throw new ReferenceError(`No such file: ${file}`);
}
if (replacementFile != null) {
if (!fs.existsSync(replacementFile)) {
throw new ReferenceError(`No such file: ${replacementFile}`);
}
const originalBinary = fs.readFileSync(file, "binary");
const replacementFileBinary = fs.readFileSync(replacementFile, "binary");
if (originalBinary !== replacementFileBinary) {
fs.copyFileSync(replacementFile, file);
console.log("Replaced file:", file, "with:", replacementFile);
}
} else {
const fileContents = fs.readFileSync(file, "utf8");
const matchPosition = fileContents.indexOf(match);
const replacementPosition = fileContents.indexOf(replacement);
if (matchPosition < 0 && replacementPosition < 0) {
throw new ReferenceError(`File: ${file} does not include: ${match}`);
} else if (matchPosition >= 0) {
const updatedFileContents = fileContents.slice(0, matchPosition) + replacement + fileContents.slice(matchPosition + match.length);
fs.writeFileSync(file, updatedFileContents);
console.log("Updated contents of file:", file);
}
}
break;
}
}
}