Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bring typescript (WIP) #63

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .github/workflows/typescript-pull.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: typescript-pull
on:
pull_request:
paths:
- typescript/**
jobs:
build-typescript:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
sparse-checkout: typescript
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
registry-url: https://registry.npmjs.org
- name: Install winglang
run: npm i -g winglang
- name: Install dependencies
run: npm install --include=dev
working-directory: typescript
- name: Test
run: wing test
working-directory: typescript
- name: Pack
run: wing pack
working-directory: typescript
53 changes: 53 additions & 0 deletions .github/workflows/typescript-release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: typescript-release
on:
push:
branches:
- main
paths:
- typescript/**
jobs:
build-typescript:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
sparse-checkout: typescript
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
registry-url: https://registry.npmjs.org
- name: Install winglang
run: npm i -g winglang
- name: Install dependencies
run: npm install --include=dev
working-directory: typescript
- name: Test
run: wing test
working-directory: typescript
- name: Pack
run: wing pack
working-directory: typescript
- name: Get package version
run: echo WINGLIB_VERSION=$(node -p "require('./package.json').version") >>
"$GITHUB_ENV"
working-directory: typescript
- name: Publish
run: npm publish --access=public --registry https://registry.npmjs.org --tag
latest *.tgz
working-directory: typescript
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Tag commit
uses: tvdias/github-tagger@v0.0.1
with:
repo-token: ${{ secrets.PROJEN_GITHUB_TOKEN }}
tag: typescript-v${{ env.WINGLIB_VERSION }}
- name: GitHub release
uses: softprops/action-gh-release@v1
with:
name: typescript v${{ env.WINGLIB_VERSION }}
tag_name: typescript-v${{ env.WINGLIB_VERSION }}
files: "*.tgz"
token: ${{ secrets.PROJEN_GITHUB_TOKEN }}
18 changes: 12 additions & 6 deletions .mergify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,12 @@ pull_request_rules:
- -check-failure=build-redis
- -check-pending=build-redis
- -check-stale=build-redis
- -check-failure=build-sagemaker
- -check-pending=build-sagemaker
- -check-stale=build-sagemaker
- -check-failure=build-ts-function
- -check-pending=build-ts-function
- -check-stale=build-ts-function
- -check-failure=build-typescript
- -check-pending=build-typescript
- -check-stale=build-typescript
- -check-failure=build-websockets
- -check-pending=build-websockets
- -check-stale=build-websockets
Expand Down Expand Up @@ -101,9 +104,12 @@ pull_request_rules:
- -check-failure=build-redis
- -check-pending=build-redis
- -check-stale=build-redis
- -check-failure=build-sagemaker
- -check-pending=build-sagemaker
- -check-stale=build-sagemaker
- -check-failure=build-ts-function
- -check-pending=build-ts-function
- -check-stale=build-ts-function
- -check-failure=build-typescript
- -check-pending=build-typescript
- -check-stale=build-typescript
- -check-failure=build-websockets
- -check-pending=build-websockets
- -check-stale=build-websockets
Expand Down
2 changes: 2 additions & 0 deletions typescript/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target/
node_modules/
21 changes: 21 additions & 0 deletions typescript/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Wing

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
58 changes: 58 additions & 0 deletions typescript/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# TypeScript support for Winglang

> TODO

## Prerequisites

* [winglang](https://winglang.io).

## Installation

`sh
npm i @winglibs/typescript
`

## Usage

The `FunctionHandler`, `QueueHandler` and `ApiEndpointHandler` types can be used to define inflight
handlers from a TypeScript codebase.

For example:

```ts
// src/index.ts
exports.handler = async (event, context) => {
console.log("Welcome to TypeScript", event);
return {
status: 200,
body: JSON.stringify({ message: "Hello, TypeScript" }),
};
};
Comment on lines +23 to +30
Copy link
Contributor

@Chriscbr Chriscbr Jan 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add types to this example?

As a user I'd want some kind of information or disclaimer about what the signature of the function should be and whether it's enforced by the Wing library or not, since it might mean the same function I write in TypeScript for a typescript.FunctionHandler can't be reused in a typescript.QueueHandler automatically, or something like that.

```

```js
// main.w
bring typescript;

new cloud.Function(new typescript.FunctionHandler("./src"));
eladb marked this conversation as resolved.
Show resolved Hide resolved
```

## TODO

- [x] Lift cloud resources into TypeScript
- [ ] Generate .d.ts file with type information for handler (and lifts)
- [ ] Tests
- [ ] Typechecking
- [ ] Hot reloading
- [ ] Bundling configuration
- [ ] README

Workarounds:

* https://github.com/winglang/wing/issues/5476
* `__dirname` to reference `src`
* `patchToInflight`

## License

This library is licensed under the [MIT License](./LICENSE).
20 changes: 20 additions & 0 deletions typescript/example/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Handler } from "./index.wing";

export const handler: Handler = async ({ myBucket, myQueue }, event: any) => {
eladb marked this conversation as resolved.
Show resolved Hide resolved
await myBucket.put("hello.txt", "from typescript");
await myQueue.push("hello");

console.log("Welcome to TypeScript");
console.log("event:", event);

const output = await myBucket.list();
console.log(output);

return {
status: 200,
body: JSON.stringify({
message: "Hello, TypeScript",
event,
}),
};
};
1 change: 1 addition & 0 deletions typescript/example/index.wing.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type Handler = (context: any, event: any) => Promise<any>;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be generated with types based on lifting

62 changes: 62 additions & 0 deletions typescript/inflight.test.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
bring cloud;
bring expect;
bring http;
bring util;
bring "./inflight.w" as typescript;

let myBucket = new cloud.Bucket();
let myQueue = new cloud.Queue();

new cloud.Function(inflight () => {
myBucket.put("bing.txt", "123");
}) as "write";

let handler = new typescript.Inflight(
src: "./example/index",
lift: {
myBucket: { obj: myBucket, ops: ["put"] },
myQueue: { obj: myQueue, ops: ["push"] },
}
);

myQueue.setConsumer(inflight (msg) => {
log("queue received {msg}");
});

let fn = new cloud.Function(handler.forFunction()) as "typescript function";

let api = new cloud.Api();
api.get("/foo", handler.forApiEndpoint());
api.post("/bar", handler.forApiEndpoint());

test "api" {
let response = http.get("{api.url}/foo?boom=42");
log(response.body);
let body = Json.parse(response.body);
expect.equal(body.get("message").asStr(), "Hello, TypeScript");
expect.equal(body.get("event").get("query").get("boom").asStr(), "42");
}

test "queue" {
myQueue.push("boom boom");

// this asserts that the consumer actually pops from the queue
util.waitUntil(() => {
return myQueue.approxSize() == 0;
});
}

test "function" {
let response = fn.invoke("18993487");
let r: Json = unsafeCast(response);

let bodyStr = r.get("body").asStr();

let body = Json.parse(bodyStr);
expect.equal(body.get("event").asStr(), "18993487");
expect.equal(body.get("message").asStr(), "Hello, TypeScript");

// expect the bucket to have an object
expect.equal(myBucket.get("hello.txt"), "from typescript");

}
73 changes: 73 additions & 0 deletions typescript/inflight.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
bring cloud;
bring fs;

pub struct Lift {
obj: std.IResource;
ops: Array<str>;
}

pub struct InflightProps {
src: str;
lift: Map<Lift>?;
}


pub class Inflight {
code: str;
lift: Map<Lift>;

new(props: InflightProps) {
let var src = props.src;

let postfix = "/index";
if !src.endsWith(postfix) {
throw "src must end with /index (for now)";
}

src = src.substring(0, src.length - postfix.length);

this.lift = props?.lift ?? {};

let tmpdir = fs.mkdtemp();
let bundle = Util.createBundle(src, [], tmpdir);
this.code = fs.readFile(bundle.entrypointPath);

nodeof(this).hidden = true;
}

pub forFunction(): cloud.IFunctionHandler {
let h: cloud.IFunctionHandler = inflight (event: str): str? => { };
Util.patchToInflight(h, this.lift, this.code);
return h;
}

pub forQueueConsumer(): cloud.IQueueSetConsumerHandler {
let h: cloud.IQueueSetConsumerHandler = inflight (event: str): str? => { };
Util.patchToInflight(h, this.lift, this.code);
return h;
}

pub forApiEndpoint(): cloud.IApiEndpointHandler {
let h: cloud.IApiEndpointHandler = inflight (req: cloud.ApiRequest): cloud.ApiResponse => {
return { status: 500 };
};
Util.patchToInflight(h, this.lift, this.code);
return h;
}
}

struct Bundle {
entrypointPath: str;
directory: str;
hash: str;
outfilePath: str;
sourcemapPath: str;
}

class Util {
extern "./util.js"
pub static patchToInflight(h: std.IInflight, lift: Map<Lift>, code: str): void;

extern "./util.js"
pub static createBundle(entrypoint: str, external: Array<str>?, outputDir: str?): Bundle;
}
Loading
Loading