Skip to content

Commit

Permalink
fix: getVisitorKeys throwing when called before parse (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
AngusMorton authored Dec 4, 2023
1 parent 8f2ea07 commit f1caf74
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ const embeddedPlaceholderReg = /__EMBEDDED_PLACEHOLDER_(\d+)__/g;
let currentCompiler: typeof Compiler;
let currentConfig: Config;

function getCurrentCompiler(): [typeof Compiler, Config] {
try {
return [
(currentCompiler ||= rootRequire("@marko/compiler")),
(currentConfig ||= rootRequire("@marko/compiler/config").default),
];
} catch (cause) {
throw new Error(
"You must have @marko/compiler installed to use prettier-plugin-marko.",
{ cause },
);
}
}

export const languages: SupportLanguage[] = [
{
name: "marko",
Expand Down Expand Up @@ -113,19 +127,7 @@ export const parsers: Record<string, Parser<Node>> = {
async parse(text, opts) {
const { filepath = defaultFilePath } = opts;

const [{ compile, types: t }, config] = (() => {
try {
return [
(currentCompiler ||= rootRequire("@marko/compiler")),
(currentConfig ||= rootRequire("@marko/compiler/config").default),
];
} catch (cause) {
throw new Error(
"You must have @marko/compiler installed to use prettier-plugin-marko.",
{ cause },
);
}
})() as [typeof Compiler, Config];
const [{ compile, types: t }, config] = getCurrentCompiler();

const translator = (() => {
try {
Expand Down Expand Up @@ -693,7 +695,7 @@ export const printers: Record<string, Printer<types.Node>> = {
embed(path, opts) {
const node = path.getNode() as types.Node;
const type = node?.type;
const { types: t } = currentCompiler;
const [{ types: t }] = getCurrentCompiler();

switch (type) {
case "File":
Expand Down Expand Up @@ -1092,7 +1094,8 @@ export const printers: Record<string, Printer<types.Node>> = {
};
},
getVisitorKeys(node) {
return (currentCompiler.types as any).VISITOR_KEYS[node.type] || emptyArr;
const [compiler] = getCurrentCompiler();
return (compiler.types as any).VISITOR_KEYS[node.type] || emptyArr;
},
},
};
Expand Down

0 comments on commit f1caf74

Please sign in to comment.