winglang / wing

A programming language for the cloud ☁️ A unified programming model, combining infrastructure and runtime code into one language ⚡
https://winglang.io
Other
5.06k stars 198 forks source link

Unbundle-able libraries fail with cryptic error ("TypeError: Invalid URL") #7073

Open Chriscbr opened 2 months ago

Chriscbr commented 2 months ago

I tried this:

I wrote a Wing app that uses the crypto-hash npm library:

// main.w
bring cloud;

class Util {
  pub extern "./util.js" static inflight hash(query: str): str;
}

test "getUrl" {
  log(Util.hash("hello"));
}

Extern code:

import { sha256 } from "crypto-hash";

export const hash = async (query) => {
    return sha256(query, { outputFormat: "hex" });
}

This happened:

When I run wing test I get this error:

fail ┌ main.wsim » root/Default/test:getUrl
     │ Error: TypeError: Invalid URL
     │    --> target/test/main.wsim/.wing/handler_c8e701de.sandbox.cjs.bundle/index.cjs:10:56
     │    | var __hasOwnProp = Object.prototype.hasOwnProperty;
     │    | var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
     │    | var __esm = (fn, res) => function __init() {
     │ 10 |   return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
     │    |                                                        ^
     │ at __init /Users/chrisr/dev/wing-test/target/test/main.wsim/.wing/handler_c8e701de.sandbox.cjs.bundle/index.cjs:10:56
     │ at js /Users/chrisr/dev/wing-test/util.js:1:1
     │ at __init /Users/chrisr/dev/wing-test/target/test/main.wsim/.wing/handler_c8e701de.sandbox.cjs.bundle/index.cjs:10:56
     │ at hash /Users/chrisr/dev/wing-test/main.w:4:3
     └ at /Users/chrisr/dev/wing-test/main.w:8:3

Worse, if I compile this to a cloud target like tf-aws, it will happily bundle the code even though it will fail at runtime.

I expected this:

I expected the example to work, or to have a more helpful error

Is there a workaround?

Avoid using npm libraries that use features which prevent their code from being bundled like import.meta.url

Anything else?

No response

Wing Version

0.83.8

Node.js Version

20.12.2

Platform(s)

MacOS

Community Notes

Chriscbr commented 2 months ago

For this particular example, I think we can work around it by adding code to Wing SDK for "shimming" in a substitute value for import.meta.url: https://github.com/evanw/esbuild/issues/3099. Here's where we call esbuild inside Wing today: https://github.com/winglang/wing/blob/fb852cfe686b2e6ae840c4acc43b414a90cb7640/packages/%40winglang/sdk/src/shared/bundling.ts#L71-L93

Though it might be worthwhile to understand how broad this issue is (what fraction of libraries can't be reliably bundled without esbuild warnings or runtime errors? are there any ways to surface this issue more broadly?)