typed-macro icon indicating copy to clipboard operation
typed-macro copied to clipboard

support `withAsyncHandler` to handle async event

Open zheeeng opened this issue 4 years ago • 3 comments
trafficstars

At present long time consumption task reports Reached the maximum recursion when apply macros:

import { defineMacro } from "vite-plugin-macro";

const run = <T>(block: () => T) => block();

const sleep = (ms: number) => new Promise(resolve => {
    setTimeout(resolve, ms);
})

export const bootstrapMacro = defineMacro("bootstrap")
  .withSignature("(msg: string, repeat?: number): void")
  .withHandler(async ({ path, args }, { template, types }) => {
    await sleep(1000)
    const msg = run(() => {
      if (args.length === 0) throw new Error("empty arguments is invalid");
      const firstArg = args[0];
      if (!types.isStringLiteral(firstArg))
        throw new Error("please use literal string as message");
      return firstArg.value;
    });
    
    const repeat = run(() => {
      if (args.length < 2) return 5;
      const secondArg = args[1];
      if (!types.isNumericLiteral(secondArg))
        throw new Error("please use literal number as repeat");
      return secondArg.value;
    });

    path.replaceWith(
      template.statement.ast`console.log("${Array.from(
        { length: repeat },
        () => msg
      ).join(" ")}")`
    );
  });

zheeeng avatar Sep 03 '21 03:09 zheeeng

This doesn't seem to be a common requirement. I've written 30+ macros for my project with this plugin, but I haven't encountered async scenario yet. Can you describe the usage scenario?

unbyte avatar Sep 03 '21 05:09 unbyte

This doesn't seem to be a common requirement. I've written 30+ macros for my project with this plugin, but I haven't encountered async scenario yet. Can you describe the usage scenario?

I'm recently using es-module-lexer to parse some file content, it requires to use it asynchronously, any idea on this?

zheeeng avatar Mar 04 '22 12:03 zheeeng

I'm sure async functions won't lead to what I worried about before, but I need to rethink the design of related API.

unbyte avatar Mar 04 '22 14:03 unbyte