Skip to content

Commit

Permalink
feat: add sanitizeURIComponent and sanitizeFilePath helpers (#22)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
  • Loading branch information
danielroe and pi0 committed Nov 3, 2021
1 parent 46e291a commit 9ddeab8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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('')
})
})

0 comments on commit 9ddeab8

Please sign in to comment.