UNPKG

2.95 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.fixRelativeUrls = exports.processDeclarationUrls = exports.makeAbsolute = exports.isAsset = exports.isExternal = exports.collectAssets = void 0;
7const path_1 = __importDefault(require("path"));
8const url_regex_1 = __importDefault(require("url-regex"));
9const { parseValues, stringifyValues } = require('css-selector-tokenizer');
10const isUrl = url_regex_1.default({ exact: true, strict: true });
11function collectAssets(ast) {
12 const assetDependencies = [];
13 const onUrl = (node) => {
14 assetDependencies.push(node.url);
15 };
16 ast.walkDecls((decl) => processDeclarationUrls(decl, onUrl, false));
17 return assetDependencies;
18}
19exports.collectAssets = collectAssets;
20function isExternal(url) {
21 return url === '' || url.startsWith('data:') || isUrl.test(url);
22}
23exports.isExternal = isExternal;
24function isAsset(url) {
25 return !isExternal(url);
26}
27exports.isAsset = isAsset;
28function makeAbsolute(resourcePath, rootContext, moduleContext) {
29 const isAbs = path_1.default.isAbsolute(resourcePath);
30 let abs;
31 if (isExternal(resourcePath)) {
32 abs = resourcePath;
33 }
34 else if (isAbs && resourcePath.startsWith('/')) {
35 abs = path_1.default.join(rootContext, resourcePath);
36 }
37 else if (isAbs) {
38 abs = resourcePath;
39 }
40 else {
41 abs = path_1.default.join(moduleContext, resourcePath);
42 }
43 return abs;
44}
45exports.makeAbsolute = makeAbsolute;
46function processDeclarationUrls(decl, onUrl, transform) {
47 const ast = parseValues(decl.value);
48 ast.nodes.forEach((node) => {
49 node.nodes.forEach((node) => findUrls(node, onUrl));
50 });
51 if (transform) {
52 decl.value = stringifyValues(ast);
53 }
54}
55exports.processDeclarationUrls = processDeclarationUrls;
56function findUrls(node, onUrl) {
57 const { type, nodes = [] } = node;
58 switch (type) {
59 case 'value':
60 nodes.forEach((_) => findUrls(_, onUrl));
61 break;
62 case 'nested-item':
63 nodes.forEach((_) => findUrls(_, onUrl));
64 break;
65 case 'url':
66 onUrl(node);
67 break;
68 }
69}
70function fixRelativeUrls(ast, originPath, targetPath) {
71 ast.walkDecls((decl) => processDeclarationUrls(decl, (node) => {
72 if (isAsset(node.url)) {
73 if (node.url.startsWith('.')) {
74 node.url =
75 './' +
76 path_1.default
77 .join(path_1.default.relative(path_1.default.dirname(targetPath), path_1.default.dirname(originPath)), node.url)
78 .replace(/\\/gm, '/');
79 }
80 }
81 }, true));
82}
83exports.fixRelativeUrls = fixRelativeUrls;
84//# sourceMappingURL=stylable-assets.js.map
\No newline at end of file