From a8e9d7f87b457780b2b67282947b483db478aac2 Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Thu, 24 Nov 2022 11:09:02 +0100 Subject: [PATCH] :recycle: Use @github/actions-script method for require --- src/index.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 64cc6dc..197f648 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,13 @@ import { getInput, setFailed, setOutput } from "@actions/core"; import { execSync } from "child_process"; +import frontMatter from "front-matter"; import { readdir, readFile, writeFile } from "fs-extra"; import markdownToTxt from "markdown-to-txt"; -import { join } from "path"; +import { join, resolve } from "path"; import { format } from "prettier"; import truncate from "truncate-sentences"; -import frontMatter from "front-matter"; + +declare var __non_webpack_require__: any; interface Item { slug: string; @@ -18,6 +20,44 @@ interface Item { caption?: string; } +const AsyncFunction = Object.getPrototypeOf(async () => null).constructor; + +type AsyncFunctionArguments = Item & { + require: NodeRequire; + __original_require__: NodeRequire; +}; + +export function callAsyncFunction( + args: AsyncFunctionArguments, + source: string +): Promise { + const fn = new AsyncFunction(...Object.keys(args), source); + return fn(...Object.values(args)); +} +export const wrapRequire = new Proxy(__non_webpack_require__, { + apply: (target, thisArg, [moduleID]) => { + if (moduleID.startsWith(".")) { + moduleID = resolve(moduleID); + return target.apply(thisArg, [moduleID]); + } + + const modulePath = target.resolve.apply(thisArg, [ + moduleID, + { + // Webpack does not have an escape hatch for getting the actual + // module, other than `eval`. + paths: [process.cwd()], + }, + ]); + + return target.apply(thisArg, [modulePath]); + }, + + get: (target, prop, receiver) => { + Reflect.get(target, prop, receiver); + }, +}); + /** * Get a item from a file * @param directory - The directory where the file resides @@ -87,10 +127,14 @@ const parseItemFile = async ( if (caption) { // I know, I know... - const captionData = eval(`(function (data) { - const { slug, path, source, title, date, excerpt, attributes } = data; - ${caption} - })(${JSON.stringify(result)})`); + const captionData = await callAsyncFunction( + { + require: wrapRequire, + __original_require__: __non_webpack_require__, + ...result, + }, + caption + ); if (captionData) result.caption = captionData; }