@dcloudio/uni-cli-shared 3.0.0-alpha-3021320211118002 → 3.0.0-alpha-3021320211122001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.urlToBuiltUrl = exports.getAssetHash = exports.assetFileNamesToFileName = exports.getAssetFilename = exports.fileToUrl = exports.checkPublicFile = exports.registerAssetToChunk = exports.assetPlugin = exports.chunkToEmittedAssetsMap = exports.assetUrlRE = void 0;
26
+ const path_1 = __importDefault(require("path"));
27
+ const url_1 = require("url");
28
+ const fs_1 = __importStar(require("fs"));
29
+ const lite_1 = __importDefault(require("mime/lite"));
30
+ const utils_1 = require("../utils");
31
+ const constants_1 = require("../constants");
32
+ const magic_string_1 = __importDefault(require("magic-string"));
33
+ const crypto_1 = require("crypto");
34
+ const utils_2 = require("../utils");
35
+ exports.assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
36
+ const rawRE = /(\?|&)raw(?:&|$)/;
37
+ const urlRE = /(\?|&)url(?:&|$)/;
38
+ exports.chunkToEmittedAssetsMap = new WeakMap();
39
+ const assetCache = new WeakMap();
40
+ const assetHashToFilenameMap = new WeakMap();
41
+ // save hashes of the files that has been emitted in build watch
42
+ const emittedHashMap = new WeakMap();
43
+ /**
44
+ * Also supports loading plain strings with import text from './foo.txt?raw'
45
+ */
46
+ function assetPlugin(config) {
47
+ // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
48
+ assetHashToFilenameMap.set(config, new Map());
49
+ return {
50
+ name: 'vite:asset',
51
+ buildStart() {
52
+ assetCache.set(config, new Map());
53
+ emittedHashMap.set(config, new Set());
54
+ },
55
+ resolveId(id) {
56
+ if (!config.assetsInclude((0, utils_1.cleanUrl)(id))) {
57
+ return;
58
+ }
59
+ // imports to absolute urls pointing to files in /public
60
+ // will fail to resolve in the main resolver. handle them here.
61
+ const publicFile = checkPublicFile(id, config);
62
+ if (publicFile) {
63
+ return id;
64
+ }
65
+ },
66
+ async load(id) {
67
+ if (id.startsWith('\0')) {
68
+ // Rollup convention, this id should be handled by the
69
+ // plugin that marked it with \0
70
+ return;
71
+ }
72
+ // raw requests, read from disk
73
+ if (rawRE.test(id)) {
74
+ const file = checkPublicFile(id, config) || (0, utils_1.cleanUrl)(id);
75
+ // raw query, read file and return as string
76
+ return `export default ${JSON.stringify(await fs_1.promises.readFile(file, 'utf-8'))}`;
77
+ }
78
+ if (!config.assetsInclude((0, utils_1.cleanUrl)(id)) && !urlRE.test(id)) {
79
+ return;
80
+ }
81
+ id = id.replace(urlRE, '$1').replace(/[\?&]$/, '');
82
+ const url = await fileToUrl(id, config, this);
83
+ return `export default ${JSON.stringify(url)}`;
84
+ },
85
+ renderChunk(code, chunk) {
86
+ let match;
87
+ let s;
88
+ // Urls added with JS using e.g.
89
+ // imgElement.src = "my/file.png" are using quotes
90
+ // Urls added in CSS that is imported in JS end up like
91
+ // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
92
+ // In both cases, the wrapping should already be fine
93
+ while ((match = exports.assetUrlRE.exec(code))) {
94
+ s = s || (s = new magic_string_1.default(code));
95
+ const [full, hash, postfix = ''] = match;
96
+ // some internal plugins may still need to emit chunks (e.g. worker) so
97
+ // fallback to this.getFileName for that.
98
+ const file = getAssetFilename(hash, config) || this.getFileName(hash);
99
+ registerAssetToChunk(chunk, file);
100
+ const outputFilepath = config.base + file + postfix;
101
+ s.overwrite(match.index, match.index + full.length, outputFilepath);
102
+ }
103
+ if (s) {
104
+ return {
105
+ code: s.toString(),
106
+ map: config.build.sourcemap ? s.generateMap({ hires: true }) : null,
107
+ };
108
+ }
109
+ else {
110
+ return null;
111
+ }
112
+ },
113
+ generateBundle(_, bundle) {
114
+ // do not emit assets for SSR build
115
+ if (config.command === 'build' && config.build.ssr) {
116
+ for (const file in bundle) {
117
+ if (bundle[file].type === 'asset' &&
118
+ !file.includes('ssr-manifest.json')) {
119
+ delete bundle[file];
120
+ }
121
+ }
122
+ }
123
+ },
124
+ };
125
+ }
126
+ exports.assetPlugin = assetPlugin;
127
+ function registerAssetToChunk(chunk, file) {
128
+ let emitted = exports.chunkToEmittedAssetsMap.get(chunk);
129
+ if (!emitted) {
130
+ emitted = new Set();
131
+ exports.chunkToEmittedAssetsMap.set(chunk, emitted);
132
+ }
133
+ emitted.add((0, utils_1.cleanUrl)(file));
134
+ }
135
+ exports.registerAssetToChunk = registerAssetToChunk;
136
+ function checkPublicFile(url, { publicDir }) {
137
+ // note if the file is in /public, the resolver would have returned it
138
+ // as-is so it's not going to be a fully resolved path.
139
+ if (!publicDir || !url.startsWith('/')) {
140
+ return;
141
+ }
142
+ const publicFile = path_1.default.join(publicDir, (0, utils_1.cleanUrl)(url));
143
+ if (fs_1.default.existsSync(publicFile)) {
144
+ return publicFile;
145
+ }
146
+ else {
147
+ return;
148
+ }
149
+ }
150
+ exports.checkPublicFile = checkPublicFile;
151
+ function fileToUrl(id, config, ctx) {
152
+ if (config.command === 'serve') {
153
+ return fileToDevUrl(id, config);
154
+ }
155
+ else {
156
+ return fileToBuiltUrl(id, config, ctx);
157
+ }
158
+ }
159
+ exports.fileToUrl = fileToUrl;
160
+ function fileToDevUrl(id, config) {
161
+ var _a, _b;
162
+ let rtn;
163
+ if (checkPublicFile(id, config)) {
164
+ // in public dir, keep the url as-is
165
+ rtn = id;
166
+ }
167
+ else if (id.startsWith(config.root)) {
168
+ // in project root, infer short public path
169
+ rtn = '/' + path_1.default.posix.relative(config.root, id);
170
+ }
171
+ else {
172
+ // outside of project root, use absolute fs path
173
+ // (this is special handled by the serve static middleware
174
+ rtn = path_1.default.posix.join(constants_1.FS_PREFIX + id);
175
+ }
176
+ const origin = (_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : '';
177
+ return origin + config.base + rtn.replace(/^\//, '');
178
+ }
179
+ function getAssetFilename(hash, config) {
180
+ var _a;
181
+ return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash);
182
+ }
183
+ exports.getAssetFilename = getAssetFilename;
184
+ /**
185
+ * converts the source filepath of the asset to the output filename based on the assetFileNames option. \
186
+ * this function imitates the behavior of rollup.js. \
187
+ * https://rollupjs.org/guide/en/#outputassetfilenames
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * const content = Buffer.from('text');
192
+ * const fileName = assetFileNamesToFileName(
193
+ * 'assets/[name].[hash][extname]',
194
+ * '/path/to/file.txt',
195
+ * getAssetHash(content),
196
+ * content
197
+ * )
198
+ * // fileName: 'assets/file.982d9e3e.txt'
199
+ * ```
200
+ *
201
+ * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
202
+ * @param file filepath of the asset
203
+ * @param contentHash hash of the asset. used for `'[hash]'` placeholder
204
+ * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
205
+ * @returns output filename
206
+ */
207
+ function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
208
+ const basename = path_1.default.basename(file);
209
+ // placeholders for `assetFileNames`
210
+ // `hash` is slightly different from the rollup's one
211
+ const extname = path_1.default.extname(basename);
212
+ const ext = extname.substr(1);
213
+ const name = basename.slice(0, -extname.length);
214
+ const hash = contentHash;
215
+ if (typeof assetFileNames === 'function') {
216
+ assetFileNames = assetFileNames({
217
+ name: file,
218
+ source: content,
219
+ type: 'asset',
220
+ });
221
+ if (typeof assetFileNames !== 'string') {
222
+ throw new TypeError('assetFileNames must return a string');
223
+ }
224
+ }
225
+ else if (typeof assetFileNames !== 'string') {
226
+ throw new TypeError('assetFileNames must be a string or a function');
227
+ }
228
+ const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
229
+ switch (placeholder) {
230
+ case '[ext]':
231
+ return ext;
232
+ case '[extname]':
233
+ return extname;
234
+ case '[hash]':
235
+ return hash;
236
+ case '[name]':
237
+ return name;
238
+ }
239
+ throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
240
+ });
241
+ return fileName;
242
+ }
243
+ exports.assetFileNamesToFileName = assetFileNamesToFileName;
244
+ /**
245
+ * Register an asset to be emitted as part of the bundle (if necessary)
246
+ * and returns the resolved public URL
247
+ */
248
+ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
249
+ var _a, _b, _c;
250
+ if (!skipPublicCheck && checkPublicFile(id, config)) {
251
+ return config.base + id.slice(1);
252
+ }
253
+ const cache = assetCache.get(config);
254
+ const cached = cache.get(id);
255
+ if (cached) {
256
+ return cached;
257
+ }
258
+ const file = (0, utils_1.cleanUrl)(id);
259
+ const content = await fs_1.promises.readFile(file);
260
+ let url;
261
+ if (config.build.lib ||
262
+ (!file.endsWith('.svg') &&
263
+ content.length < Number(config.build.assetsInlineLimit))) {
264
+ // base64 inlined as a string
265
+ url = `data:${lite_1.default.getType(file)};base64,${content.toString('base64')}`;
266
+ }
267
+ else {
268
+ // emit as asset
269
+ // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
270
+ // that uses runtime url sniffing and it can be verbose when targeting
271
+ // non-module format. It also fails to cascade the asset content change
272
+ // into the chunk's hash, so we have to do our own content hashing here.
273
+ // https://bundlers.tooling.report/hashing/asset-cascade/
274
+ // https://github.com/rollup/rollup/issues/3415
275
+ const map = assetHashToFilenameMap.get(config);
276
+ const contentHash = getAssetHash(content);
277
+ const { search, hash } = (0, url_1.parse)(id);
278
+ const postfix = (search || '') + (hash || '');
279
+ const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output;
280
+ const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c :
281
+ // defaults to '<assetsDir>/[name].[hash][extname]'
282
+ // slightly different from rollup's one ('assets/[name]-[hash][extname]')
283
+ path_1.default.posix.join(config.build.assetsDir, '[name].[hash][extname]');
284
+ const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
285
+ if (!map.has(contentHash)) {
286
+ map.set(contentHash, fileName);
287
+ }
288
+ const emittedSet = emittedHashMap.get(config);
289
+ if (!emittedSet.has(contentHash)) {
290
+ const name = (0, utils_2.normalizePath)(path_1.default.relative(config.root, file));
291
+ pluginContext.emitFile({
292
+ name,
293
+ fileName,
294
+ type: 'asset',
295
+ source: content,
296
+ });
297
+ emittedSet.add(contentHash);
298
+ }
299
+ url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`;
300
+ }
301
+ cache.set(id, url);
302
+ return url;
303
+ }
304
+ function getAssetHash(content) {
305
+ return (0, crypto_1.createHash)('sha256').update(content).digest('hex').slice(0, 8);
306
+ }
307
+ exports.getAssetHash = getAssetHash;
308
+ async function urlToBuiltUrl(url, importer, config, pluginContext) {
309
+ if (checkPublicFile(url, config)) {
310
+ return config.base + url.slice(1);
311
+ }
312
+ const file = url.startsWith('/')
313
+ ? path_1.default.join(config.root, url)
314
+ : path_1.default.join(path_1.default.dirname(importer), url);
315
+ return fileToBuiltUrl(file, config, pluginContext,
316
+ // skip public check since we just did it above
317
+ true);
318
+ }
319
+ exports.urlToBuiltUrl = urlToBuiltUrl;
@@ -0,0 +1,67 @@
1
+ import { Plugin } from '../plugin';
2
+ import { ResolvedConfig } from '../config';
3
+ import { RenderedChunk, RollupError } from 'rollup';
4
+ import { ResolveFn } from '../';
5
+ import * as Postcss from 'postcss';
6
+ export interface CSSOptions {
7
+ /**
8
+ * https://github.com/css-modules/postcss-modules
9
+ */
10
+ modules?: CSSModulesOptions | false;
11
+ preprocessorOptions?: Record<string, any>;
12
+ postcss?: string | (Postcss.ProcessOptions & {
13
+ plugins?: Postcss.Plugin[];
14
+ });
15
+ }
16
+ export interface CSSModulesOptions {
17
+ getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
18
+ scopeBehaviour?: 'global' | 'local';
19
+ globalModulePaths?: RegExp[];
20
+ generateScopedName?: string | ((name: string, filename: string, css: string) => string);
21
+ hashPrefix?: string;
22
+ /**
23
+ * default: null
24
+ */
25
+ localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null;
26
+ }
27
+ export declare const isCSSRequest: (request: string) => boolean;
28
+ export declare const isDirectCSSRequest: (request: string) => boolean;
29
+ export declare const isDirectRequest: (request: string) => boolean;
30
+ export declare const chunkToEmittedCssFileMap: WeakMap<RenderedChunk, Set<string>>;
31
+ export declare const removedPureCssFilesCache: WeakMap<Readonly<Omit<import("vite").UserConfig, "plugins" | "alias" | "dedupe" | "assetsInclude" | "optimizeDeps"> & {
32
+ configFile: string | undefined;
33
+ configFileDependencies: string[];
34
+ inlineConfig: import("vite").InlineConfig;
35
+ root: string;
36
+ base: string;
37
+ publicDir: string;
38
+ command: "build" | "serve";
39
+ mode: string;
40
+ isProduction: boolean;
41
+ env: Record<string, any>;
42
+ resolve: import("vite").ResolveOptions & {
43
+ alias: import("vite").Alias[];
44
+ };
45
+ plugins: readonly Plugin[];
46
+ server: import("vite").ResolvedServerOptions;
47
+ build: Required<Omit<import("vite").BuildOptions, "base" | "cleanCssOptions" | "polyfillDynamicImport" | "brotliSize">>;
48
+ assetsInclude: (file: string) => boolean;
49
+ logger: import("vite").Logger;
50
+ createResolver: (options?: Partial<import("vite").InternalResolveOptions> | undefined) => ResolveFn;
51
+ optimizeDeps: Omit<import("vite").DepOptimizationOptions, "keepNames">;
52
+ }>, Map<string, RenderedChunk>>;
53
+ /**
54
+ * Plugin applied before user plugins
55
+ */
56
+ export declare function cssPlugin(config: ResolvedConfig): Plugin;
57
+ /**
58
+ * Plugin applied after user plugins
59
+ */
60
+ export declare function cssPostPlugin(config: ResolvedConfig): Plugin;
61
+ export declare const cssUrlRE: RegExp;
62
+ export interface StylePreprocessorResults {
63
+ code: string;
64
+ map?: object;
65
+ errors: RollupError[];
66
+ deps: string[];
67
+ }