Skip to content

Commit

Permalink
Merge pull request #66 from dojyorin/dev
Browse files Browse the repository at this point in the history
feat: evaluate.
  • Loading branch information
dojyorin authored Jul 25, 2023
2 parents 09ea5fa + b32bca7 commit 65dc775
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "./test/base64.test.ts";
import "./test/crypto.test.ts";
import "./test/deep.test.ts";
import "./test/deflate.test.ts";
import "./test/evaluate.test.ts";
import "./test/fetch.test.ts";
import "./test/import.test.ts";
import "./test/json.deno.test.ts";
Expand Down
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from "./src/base64.ts";
export * from "./src/crypto.ts";
export * from "./src/deep.ts";
export * from "./src/deflate.ts";
export * from "./src/evaluate.ts";
export * from "./src/fetch.ts";
export * from "./src/import.ts";
export * from "./src/minipack.ts";
Expand Down
1 change: 1 addition & 0 deletions mod.universal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from "./src/base64.ts";
export * from "./src/crypto.ts";
export * from "./src/deep.ts";
export * from "./src/deflate.ts";
export * from "./src/evaluate.ts";
export * from "./src/fetch.ts";
export * from "./src/import.ts";
export * from "./src/minipack.ts";
Expand Down
21 changes: 21 additions & 0 deletions src/evaluate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {type Opt} from "./deep.ts";
import {base64Encode} from "./base64.ts";
import {utfEncode} from "./text.ts";

/**
* Auxiliary type for default export.
*/
export interface DefExp<T extends unknown>{
default: T;
}

/**
* Evaluate ESM JavaScript code in module scope.
* @example
* ```ts
* const {default: data} = await evaluateESM<DefExp<string>>("export default 'hello!';");
* ```
*/
export async function evaluateESM<T extends Opt<T>>(code:string):Promise<T>{
return await import(`data:text/javascript;base64,${base64Encode(utfEncode(code))}`);
}
11 changes: 11 additions & 0 deletions test/evaluate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {assertEquals} from "../deps.test.ts";
import {type DefExp, evaluateESM} from "../src/evaluate.ts";

Deno.test({
name: "Evaluate: ESM",
async fn(){
const {default: esm} = await evaluateESM<DefExp<string>>("export default 'hello!';");

assertEquals(esm, "hello!");
}
});

0 comments on commit 65dc775

Please sign in to comment.