-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathpostcss-cli-resources.ts
206 lines (169 loc) · 5.54 KB
/
postcss-cli-resources.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { interpolateName } from 'loader-utils';
import * as path from 'path';
import { Declaration, Plugin } from 'postcss';
import * as url from 'url';
import { assertIsError } from '../../utils/error';
function wrapUrl(url: string): string {
let wrappedUrl;
const hasSingleQuotes = url.indexOf("'") >= 0;
if (hasSingleQuotes) {
wrappedUrl = `"${url}"`;
} else {
wrappedUrl = `'${url}'`;
}
return `url(${wrappedUrl})`;
}
export interface PostcssCliResourcesOptions {
baseHref?: string;
deployUrl?: string;
resourcesOutputPath?: string;
rebaseRootRelative?: boolean;
/** CSS is extracted to a `.css` or is embedded in a `.js` file. */
extracted?: boolean;
filename: (resourcePath: string) => string;
loader: import('webpack').LoaderContext<unknown>;
emitFile: boolean;
}
async function resolve(
file: string,
base: string,
resolver: (file: string, base: string) => Promise<string>,
): Promise<string> {
try {
return await resolver('./' + file, base);
} catch {
return resolver(file, base);
}
}
export const postcss = true;
export default function (options?: PostcssCliResourcesOptions): Plugin {
if (!options) {
throw new Error('No options were specified to "postcss-cli-resources".');
}
const {
deployUrl = '',
resourcesOutputPath = '',
filename,
loader,
emitFile,
extracted,
} = options;
const process = async (inputUrl: string, context: string, resourceCache: Map<string, string>) => {
// If root-relative, absolute or protocol relative url, leave as is
if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) {
return inputUrl;
}
if (/^\//.test(inputUrl)) {
return inputUrl;
}
// If starts with a caret, remove and return remainder
// this supports bypassing asset processing
if (inputUrl.startsWith('^')) {
return inputUrl.slice(1);
}
const cacheKey = path.resolve(context, inputUrl);
const cachedUrl = resourceCache.get(cacheKey);
if (cachedUrl) {
return cachedUrl;
}
if (inputUrl.startsWith('~')) {
inputUrl = inputUrl.slice(1);
}
const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/'));
const resolver = (file: string, base: string) =>
new Promise<string>((resolve, reject) => {
loader.resolve(base, decodeURI(file), (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result as string);
});
});
const result = await resolve(pathname as string, context, resolver);
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(result, (err, content) => {
if (err) {
reject(err);
return;
}
let outputPath = interpolateName({ resourcePath: result }, filename(result), {
content,
context: loader.context || loader.rootContext,
}).replace(/\\|\//g, '-');
if (resourcesOutputPath) {
outputPath = path.posix.join(resourcesOutputPath, outputPath);
}
loader.addDependency(result);
if (emitFile) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
loader.emitFile(outputPath, content!, undefined, { sourceFilename: result });
}
let outputUrl = outputPath.replace(/\\/g, '/');
if (hash || search) {
outputUrl = url.format({ pathname: outputUrl, hash, search });
}
if (deployUrl && !extracted) {
outputUrl = url.resolve(deployUrl, outputUrl);
}
resourceCache.set(cacheKey, outputUrl);
resolve(outputUrl);
});
});
};
const resourceCache = new Map<string, string>();
const processed = Symbol('postcss-cli-resources');
return {
postcssPlugin: 'postcss-cli-resources',
async Declaration(decl) {
if (!decl.value.includes('url') || processed in decl) {
return;
}
const value = decl.value;
const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|(.+?))\s*\)/g;
const segments: string[] = [];
let match;
let lastIndex = 0;
let modified = false;
// We want to load it relative to the file that imports
const inputFile = decl.source && decl.source.input.file;
const context = (inputFile && path.dirname(inputFile)) || loader.context;
// eslint-disable-next-line no-cond-assign
while ((match = urlRegex.exec(value))) {
const originalUrl = match[1] || match[2] || match[3];
let processedUrl;
try {
processedUrl = await process(originalUrl, context, resourceCache);
} catch (err) {
assertIsError(err);
loader.emitError(decl.error(err.message, { word: originalUrl }));
continue;
}
if (lastIndex < match.index) {
segments.push(value.slice(lastIndex, match.index));
}
if (!processedUrl || originalUrl === processedUrl) {
segments.push(match[0]);
} else {
segments.push(wrapUrl(processedUrl));
modified = true;
}
lastIndex = match.index + match[0].length;
}
if (lastIndex < value.length) {
segments.push(value.slice(lastIndex));
}
if (modified) {
decl.value = segments.join('');
}
(decl as Declaration & { [processed]: boolean })[processed] = true;
},
};
}