Skip to content

Commit 1e6d5ff

Browse files
Expose normalizePath helper
1 parent 746abad commit 1e6d5ff

File tree

9 files changed

+36
-27
lines changed

9 files changed

+36
-27
lines changed

packages/directory-plugin/src/index.js

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { promises as fs } from 'fs';
2+
import { normalizePath } from 'wmr';
23
import path from 'path';
34

4-
const pathToPosix = p => p.split(path.sep).join(path.posix.sep);
5-
65
/**
76
* @param {object} [options]
87
* @param {string} [options.cwd]
@@ -17,7 +16,7 @@ function directoryPlugin(options) {
1716
const resolved = await this.resolve(id.slice(4) + '\0', importer, { skipSelf: true });
1817

1918
if (resolved) {
20-
return '\0dir:' + pathToPosix(resolved.id).replace(/\0$/, '');
19+
return '\0dir:' + normalizePath(resolved.id).replace(/\0$/, '');
2120
}
2221
},
2322
async load(id) {

packages/sw-plugin/src/index.js

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import path from 'path';
22
import { request } from 'http';
3-
4-
const pathToPosix = p => p.split(path.sep).join(path.posix.sep);
3+
import { normalizePath } from 'wmr';
54

65
/**
76
* Service Worker plugin for WMR.
@@ -19,7 +18,7 @@ export default function swPlugin(options) {
1918

2019
const wmrProxyPlugin = {
2120
resolveId(id) {
22-
const normalizedId = id[1] + id[2] === ':\\' ? pathToPosix(id.slice(2)) : id;
21+
const normalizedId = id[1] + id[2] === ':\\' ? normalizePath(id.slice(2)) : id;
2322
if (id.startsWith('/@npm/')) return id;
2423
if (!/^\.*\//.test(normalizedId)) return '/@npm/' + id;
2524
},
@@ -49,7 +48,7 @@ export default function swPlugin(options) {
4948
async resolveId(id, importer) {
5049
if (!id.startsWith('sw:')) return;
5150
const resolved = await this.resolve(id.slice(3), importer);
52-
if (resolved) return `\0sw:${pathToPosix(resolved.id)}`;
51+
if (resolved) return `\0sw:${normalizePath(resolved.id)}`;
5352
},
5453
async load(id) {
5554
if (!id.startsWith('\0sw:')) return;

packages/wmr/index.js

+9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1+
import path from 'path';
2+
13
/**
24
* Wrapper for improved intellisense completion
35
* @type {typeof import("wmr").defineConfig}
46
*/
57
export const defineConfig = config => config;
8+
9+
/**
10+
* Normalize a file path across OSes.
11+
* @param {string} file
12+
* @returns {string}
13+
*/
14+
export const normalizePath = file => file.split(path.win32.sep).join(path.posix.sep);

packages/wmr/src/bundler.js

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
import { relative, sep, posix, resolve, dirname } from 'path';
1+
import { relative, posix, resolve, dirname } from 'path';
22
import * as rollup from 'rollup';
33
import terser from './plugins/fast-minify.js';
44
import totalist from 'totalist';
55
import { getPlugins } from './lib/plugins.js';
6-
7-
/** @param {string} p */
8-
const pathToPosix = p => p.split(sep).join(posix.sep);
6+
import { normalizePath } from '../index.js';
97

108
/** @param {import('wmr').BuildOptions} options */
119
export async function bundleProd(options) {
@@ -18,7 +16,7 @@ export async function bundleProd(options) {
1816
await totalist(cwd, (rel, abs) => {
1917
if (ignore.test(abs)) return;
2018
if (!/\.html?/.test(rel)) return;
21-
input.push('./' + pathToPosix(relative(root, abs)));
19+
input.push('./' + normalizePath(relative(root, abs)));
2220
});
2321

2422
const bundle = await rollup.rollup({
@@ -46,7 +44,7 @@ export async function bundleProd(options) {
4644
plugins: [minify && terser({ compress: true, sourcemap })],
4745
sourcemap,
4846
sourcemapPathTransform(p, mapPath) {
49-
let url = pathToPosix(relative(cwd, resolve(dirname(mapPath), p)));
47+
let url = normalizePath(relative(cwd, resolve(dirname(mapPath), p)));
5048
// strip leading relative path
5149
url = url.replace(/^\.\//g, '');
5250
// replace internal npm prefix

packages/wmr/src/lib/rollup-plugin-container.js

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
1-
import { resolve, relative, dirname, sep, posix } from 'path';
1+
import { resolve, relative, dirname, posix } from 'path';
22
import { createHash } from 'crypto';
33
import { promises as fs } from 'fs';
44
import * as acorn from 'acorn';
55
import * as kl from 'kolorist';
66
import acornClassFields from 'acorn-class-fields';
77
import { debug, formatResolved, formatPath } from './output-utils.js';
8+
import { normalizePath } from '../../index.js';
89

910
// Rollup respects "module", Node 14 doesn't.
1011
const cjsDefault = m => ('default' in m ? m.default : m);
1112
/** @type acorn */
1213
const { Parser } = cjsDefault(acorn);
1314

14-
const toPosixPath = path => path.split(sep).join(posix.sep);
15-
1615
/** Fast splice(x,1) when order doesn't matter (h/t Rich)
1716
* @param {Array} array @param {number} index
1817
*/
@@ -54,7 +53,7 @@ export function createPluginContainer(plugins, opts = {}) {
5453
const MODULES = opts.modules || new Map();
5554

5655
function generateFilename({ type, name, fileName, source }) {
57-
const posixName = toPosixPath(name);
56+
const posixName = normalizePath(name);
5857
if (!fileName) {
5958
fileName =
6059
(type === 'entry' && ctx.outputOptions.file) || ctx.outputOptions[type + 'FileNames'] || '[name][extname]';
@@ -321,7 +320,7 @@ export function createPluginContainer(plugins, opts = {}) {
321320
return result;
322321
}
323322
}
324-
return JSON.stringify('/' + fileName.split(sep).join(posix.sep));
323+
return JSON.stringify('/' + normalizePath(fileName));
325324
}
326325
};
327326

packages/wmr/src/plugins/url-plugin.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { relative, basename, sep, posix } from 'path';
1+
import { relative, basename } from 'path';
22
import { promises as fs } from 'fs';
3+
import { normalizePath } from '../../index.js';
34

45
export const IMPLICIT_URL = /\.(?:png|jpe?g|gif|webp|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)$/i;
56

@@ -27,7 +28,7 @@ export default function urlPlugin({ inline, cwd } = {}) {
2728

2829
// In dev mode, we turn the import into an inline module that avoids a network request:
2930
if (inline) {
30-
const url = '/' + relative(cwd, resolved.id).replace(/^\./, '').split(sep).join(posix.sep) + '?asset';
31+
const url = '/' + normalizePath(relative(cwd, resolved.id).replace(/^\./, '')) + '?asset';
3132
return {
3233
id: escapeUrl(`data:text/javascript,export default${JSON.stringify(url)}`),
3334
external: true

packages/wmr/src/plugins/wmr/styles-plugin.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { promises as fs } from 'fs';
22
import { basename, dirname, relative, resolve, sep, posix } from 'path';
3+
import { normalizePath } from '../../../index.js';
34
import { transformCssImports } from '../../lib/transform-css-imports.js';
45
import { transformCss } from '../../lib/transform-css.js';
56

@@ -20,7 +21,7 @@ export function processSass(sass) {
2021
*/
2122
export async function modularizeCss(css, id, mappings = [], idAbsolute) {
2223
// normalize to posix id for consistent hashing
23-
if (id.match(/^[^/]*\\/)) id = id.split(sep).join(posix.sep);
24+
if (id.match(/^[^/]*\\/)) id = normalizePath(id);
2425

2526
const suffix = '_' + hash(id);
2627

@@ -123,7 +124,7 @@ export default function wmrStylesPlugin({ cwd, hot, fullPath, production } = {})
123124
const isModular = /\.module\.(css|s[ac]ss)$/.test(id);
124125

125126
let idRelative = cwd ? relative(cwd || '', resolve(cwd, id)) : multiRelative(cwds, id);
126-
if (idRelative.match(/^[^/]*\\/)) idRelative = idRelative.split(sep).join(posix.sep);
127+
if (idRelative.match(/^[^/]*\\/)) idRelative = normalizePath(idRelative);
127128

128129
const mappings = [];
129130
if (isModular) {

packages/wmr/src/wmr-middleware.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { getMimeType } from './lib/mimetypes.js';
1111
import { debug, formatPath } from './lib/output-utils.js';
1212
import { getPlugins } from './lib/plugins.js';
1313
import { watch } from './lib/fs-watcher.js';
14+
import { normalizePath } from '../index.js';
1415

1516
const NOOP = () => {};
1617

@@ -96,7 +97,7 @@ export default function wmrMiddleware(options) {
9697
watcher.on('change', filename => {
9798
NonRollup.watchChange(resolve(cwd, filename));
9899
// normalize paths to 'nix:
99-
filename = filename.split(sep).join(posix.sep);
100+
filename = normalizePath(filename);
100101

101102
// Delete any generated CSS Modules mapping modules:
102103
const suffix = /\.module\.(css|s[ac]ss)$/.test(filename) ? '.js' : '';
@@ -158,7 +159,7 @@ export default function wmrMiddleware(options) {
158159
let file = resolve(cwd, osPath);
159160

160161
// Rollup-style CWD-relative Unix-normalized path "id":
161-
let id = relative(cwd, file).replace(/^\.\//, '').replace(/^[\0]/, '').split(sep).join(posix.sep);
162+
let id = normalizePath(relative(cwd, file).replace(/^\.\//, '').replace(/^[\0]/, ''));
162163

163164
// add back any prefix if there was one:
164165
file = prefix + file;
@@ -319,7 +320,7 @@ export const TRANSFORMS = {
319320
if (resolved) {
320321
spec = typeof resolved == 'object' ? resolved.id : resolved;
321322
if (/^(\/|\\|[a-z]:\\)/i.test(spec)) {
322-
spec = relative(dirname(file), spec).split(sep).join(posix.sep);
323+
spec = normalizePath(relative(dirname(file), spec));
323324
if (!/^\.?\.?\//.test(spec)) {
324325
spec = './' + spec;
325326
}
@@ -330,7 +331,7 @@ export const TRANSFORMS = {
330331
return spec;
331332
}
332333

333-
spec = relative(cwd, spec).split(sep).join(posix.sep);
334+
spec = normalizePath(relative(cwd, spec));
334335
if (!/^(\/|[\w-]+:)/.test(spec)) spec = `/${spec}`;
335336
return spec;
336337
}
@@ -340,7 +341,7 @@ export const TRANSFORMS = {
340341
spec = spec.replace(/^\0?([a-z-]+):(.+)$/, (s, prefix, spec) => {
341342
// \0abc:/abs/disk/path --> /@abc/cwd-relative-path
342343
if (spec[0] === '/' || spec[0] === sep) {
343-
spec = relative(cwd, spec).split(sep).join(posix.sep);
344+
spec = normalizePath(relative(cwd, spec));
344345
}
345346
return '/@' + prefix + '/' + spec;
346347
});

packages/wmr/types.d.ts

+2
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ declare module 'wmr' {
6868
export function defineConfig<
6969
T extends Partial<Options> | ((options: Options) => void | Partial<Options> | Promise<void | Partial<Options>>)
7070
>(options: T): T;
71+
72+
export function normalizePath(path: string): string;
7173
}
7274

7375
// Declarations used by WMR-based applications

0 commit comments

Comments
 (0)