From 9d4759a220a7e60bbeddf6c8e0101cf01dc0eae5 Mon Sep 17 00:00:00 2001 From: Samual Norman Date: Mon, 22 Nov 2021 00:33:46 +0000 Subject: [PATCH] automatically polyfill `Record` and `Tuple` --- src/processScript/preprocess.ts | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/processScript/preprocess.ts b/src/processScript/preprocess.ts index e9635ed..82e6d65 100644 --- a/src/processScript/preprocess.ts +++ b/src/processScript/preprocess.ts @@ -1,6 +1,12 @@ +import babelGenerator from "@babel/generator" import { parse } from "@babel/parser" +import babelTraverse, { NodePath } from "@babel/traverse" +import t, { Program } from "@babel/types" import { assert, spliceString } from "@samual/lib" +const { default: traverse } = babelTraverse as any as typeof import("@babel/traverse") +const { default: generate } = babelGenerator as any as typeof import("@babel/generator") + export type PreprocessOptions = { /** 11 a-z 0-9 characters */ uniqueID: string @@ -135,11 +141,37 @@ export function preprocess(code: string, { uniqueID = "00000000000" }: Partial

+ + traverse(file, { + Program(path) { + program = path + path.skip() + } + }) + + const needRecord = program.scope.hasGlobal("Record") + const needTuple = program.scope.hasGlobal("Tuple") + + if (needRecord || needTuple) { + file.program.body.unshift(t.importDeclaration( + needRecord + ? needTuple + ? [ + t.importSpecifier(t.identifier("Record"), t.identifier("Record")), + t.importSpecifier(t.identifier("Tuple"), t.identifier("Tuple")) + ] + : [ t.importSpecifier(t.identifier("Record"), t.identifier("Record")) ] + : [ t.importSpecifier(t.identifier("Tuple"), t.identifier("Tuple")) ], + t.stringLiteral("@bloomberg/record-tuple-polyfill") + )) + } + return { semicolons, autocomplete, seclevel, - code + code: generate(file).code } } -- knotmirror 0.0.1