| 1 |
import { parseSync, traverse, types as t } from "@babel/core"; |
| 2 |
import { traversePattern, privateKeyPathIterator } from "../lib/util.js"; |
| 3 |
|
| 4 |
function wrapSourceInClassEnvironment(input) { |
| 5 |
const usedPrivateNames = new Set(); |
| 6 |
let matched; |
| 7 |
const re = /#[\w_]+/g; |
| 8 |
while ((matched = re.exec(input)) !== null) { |
| 9 |
usedPrivateNames.add(matched[0]); |
| 10 |
} |
| 11 |
let result = "(class {"; |
| 12 |
for (const name of usedPrivateNames) { |
| 13 |
result += name + ";"; |
| 14 |
} |
| 15 |
result += "m(){ " + input + "}})"; |
| 16 |
return result; |
| 17 |
} |
| 18 |
|
| 19 |
function getPath(input, parserOpts = { plugins: ["destructuringPrivate"] }) { |
| 20 |
let targetPath; |
| 21 |
traverse( |
| 22 |
parseSync(wrapSourceInClassEnvironment(input), { |
| 23 |
parserOpts, |
| 24 |
filename: "example.js", |
| 25 |
configFile: false, |
| 26 |
}), |
| 27 |
{ |
| 28 |
Pattern(path) { |
| 29 |
targetPath = path; |
| 30 |
path.stop(); |
| 31 |
}, |
| 32 |
}, |
| 33 |
); |
| 34 |
return targetPath; |
| 35 |
} |
| 36 |
|
| 37 |
describe("traversePattern", () => { |
| 38 |
it("should visit property with private keys in depth-first order", () => { |
| 39 |
const patternPath = getPath( |
| 40 |
"const { #a: { #b: b, c, ...d }, e: [{ #c: [{ #d: { #c: g } }] }, ...{ #b: h }], #a: i } = obj;", |
| 41 |
); |
| 42 |
const keys = [ |
| 43 |
...traversePattern(patternPath.node, function* (node) { |
| 44 |
if (t.isObjectProperty(node)) { |
| 45 |
const propertyKey = node.key; |
| 46 |
if (t.isPrivateName(propertyKey)) { |
| 47 |
yield propertyKey.id.name; |
| 48 |
} |
| 49 |
} |
| 50 |
}), |
| 51 |
]; |
| 52 |
|
| 53 |
expect(keys).toEqual(["a", "b", "c", "d", "c", "b", "a"]); |
| 54 |
}); |
| 55 |
}); |
| 56 |
|
| 57 |
describe("privateKeyPathIterator", () => { |
| 58 |
const indexPaths = [ |
| 59 |
...privateKeyPathIterator( |
| 60 |
getPath( |
| 61 |
"const { #a: { a, #b: b, c, ...d }, e: [{ #c: [{ d: e, #d: { #c: f } }] }, ...{ #b: g }], #a: i } = obj;", |
| 62 |
).node, |
| 63 |
), |
| 64 |
].map(indexPath => indexPath.join(",")); |
| 65 |
expect(indexPaths).toEqual([ |
| 66 |
"0", |
| 67 |
"0,1", |
| 68 |
"1,0,0", |
| 69 |
"1,0,0,0,1", |
| 70 |
"1,0,0,0,1,0", |
| 71 |
"1,1,0,0", |
| 72 |
"2", |
| 73 |
]); |
| 74 |
}); |