Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add sanitizeURIComponent and sanitizeFilePath helpers #22

Merged
merged 5 commits into from
Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/utils.ts
Expand Up @@ -9,6 +9,19 @@ export function fileURLToPath (id: string): string {
return normalizeSlash(_fileURLToPath(id))
}

// https://datatracker.ietf.org/doc/html/rfc2396
// eslint-disable-next-line no-control-regex
const INVALID_CHAR_RE = /[\x00-\x1F\x7F<>*#"{}|^[\]`;/?:@&=+$,]+/g

export function sanitizeURIComponent (name: string = '', replacement: string = '_'): string {
return name.replace(INVALID_CHAR_RE, replacement)
}

export function sanitizeFilePath (filePath: string = '') {
return filePath.split(/[/\\]/g).map(p => sanitizeURIComponent(p)).join('/')
.replace(/^([a-zA-Z])_\//, '$1:/')
}

export function normalizeid (id: string): string {
if (typeof id !== 'string') {
// @ts-ignore
Expand Down
22 changes: 21 additions & 1 deletion test/utils.test.mjs
@@ -1,4 +1,4 @@
import { isNodeBuiltin } from 'mlly'
import { isNodeBuiltin, sanitizeFilePath } from 'mlly'
import { expect } from 'chai'

describe('isNodeBuiltin', () => {
Expand All @@ -21,3 +21,23 @@ describe('isNodeBuiltin', () => {
expect(isNodeBuiltin()).to.equal(false)
})
})

describe('sanitizeFilePath', () => {
const cases = {
'C:/te#st/[...slug].jsx': 'C:/te_st/_...slug_.jsx',
'C:\\te#st\\[...slug].jsx': 'C:/te_st/_...slug_.jsx',
'/te#st/[...slug].jsx': '/te_st/_...slug_.jsx',
'/te#st/[].jsx': '/te_st/_.jsx',
'\0a?b*c:d\x7Fe<f>g#h"i{j}k|l^m[n]o`p.jsx': '_a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p.jsx',
'': ''
}
for (const id in cases) {
it(`'${id}': ${cases[id]}`, () => {
expect(sanitizeFilePath(id)).to.equal(cases[id])
})
}

it('undefined', () => {
expect(sanitizeFilePath()).to.equal('')
})
})