Basic TypeScript Application
Prerequisites
Section titled “Prerequisites”- Language-specific tools - Install Heim Prerequisites
- Heim cli and runtime - Install Heim
- Text Editor - VsCode is a great option with language-specific plugins
- Terminal - Heim is accessed through its command-line interface
Start by running
heim newto create a project from a template.Use the up/down arrow keys to select the template and press enter:
Heim Cli heim@system:~/repos$ heim new? Select template: ›csharp-httpcsharp-http-asyncpython-httprust-http...❯ typescript-http...Next, we will choose the HTTP method that the application will respond on.
For this we will choose the default value of
GET:Heim Cli ✔ Select template: · typescript-http? Http trigger method POST/GET, Default (GET) ›Next, we need to choose the path that the application will listen on.
Once the trigger path is set, we’ll be able to go to the trigger path, and use the HTTP method we set to trigger the application.
Heim Cli ✔ Select template: · typescript-http✔ Http trigger method POST/GET, Default · GET? Http trigger path /??? , Default (/hello) › /my-typescript-applicationLast, we will need to set the name of the application.
Heim Cli ✔ Select template: · typescript-http✔ Http trigger method POST/GET, Default · GET✔ Http trigger path /??? , Default · /my-typescript-application? Package name, (Required) › my-typescript-applicationRendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/component.toml""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/run.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/ip-name-lookup.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/terminal.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/network.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/clocks/timezone.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/nuget.config""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/filesystem/preopens.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/http/handler.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/http/proxy.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/io/poll.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/io/streams.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/command.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/http/types.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/stdio.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/my-typescript-application.csproj""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/.gitignore""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/random/insecure.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/filesystem/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/udp-create-socket.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/random/insecure-seed.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/application.toml""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/io/error.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/clocks/monotonic-clock.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/exit.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/imports.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/random/random.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/clocks/wall-clock.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/tcp-create-socket.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/tcp.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/random/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/cli/environment.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/udp.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/clocks/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/filesystem/types.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/io/world.wit""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/Program.cs""Rendered Template: ""/tmp/heimQ2z7DE/my-typescript-application/wit/deps/sockets/instance-network.wit""[00:00:00] ######################################## 40/40 SuccessINFO [ Heim new ] New component created: Some("/home/heim/my-typescript-application")Once we’ve gone through all the previous steps, we’ll have a project ready to go.
Let’s open the project in your text editor to check on what our new application looks like…
Now, you will have an application folder with this structure:
Directorynode_modules
- …
Directorywit/
Directorydeps/
- …
- wold.wit
Directorytypes
- …
Directorysrc
- http.ts
- .gitignore
- component.toml
- application.toml
- package.json
- tsconfig.json
- vite.config.ts
Take note of the marked configuration files. Let’s take a look at these files, next.
component.toml
Section titled “component.toml”The component.toml file, defines a component, and one or more components make up an application in Heim.
component.tomlname = "my-typescript-application"version = "0.1.0"[registry.metadata]authors = [""]description = "Description of my-typescript-application"license = ""categories = [""][build.dev]build = "npm run build"wasm_path = "./dist/my-typescript-application.wasm"[build.prod]build = "npm run build"wasm_path = "./dist/my-typescript-application.wasm"a simple component.toml, with explanatory comments
application.toml
Section titled “application.toml”The application.toml is what defines an application. A application.toml is required for deploying an application to Heim.
application.tomlname = "my-typescript-application"component_target = 'my-typescript-application:0.1.0'[[trigger]]type = 'http'path = '/my-typescript-application'method = 'GET'a simple application.toml, with explanatory comments
Open
src/http.tsand take a look at the code we have:http.tsimport {IncomingRequest,ResponseOutparam,OutgoingBody,OutgoingResponse,Fields,} from "wasi:http/types@0.2.1";export const incomingHandler = {async handle(incomingRequest: IncomingRequest,responseOutparam: ResponseOutparam) {// Start building an outgoing responseconst outgoingResponse = new OutgoingResponse(Fields.fromList([["Content-Type", new TextEncoder().encode("application/json")]]));// Access the outgoing response bodylet outgoingBody = outgoingResponse.body();{// Create a stream for the response bodylet outputStream = outgoingBody.write();// Write hello world to the response streamconst json = await (await fetch(`https://dummyjson.com/recipes/1`)).json();outputStream.blockingWriteAndFlush(new Uint8Array(new TextEncoder().encode(JSON.stringify(json))));// @ts-ignore: This is required in order to dispose the stream before we returnoutputStream[Symbol.dispose]();}// Set the status code for the responseoutgoingResponse.setStatusCode(200);// Finish the response bodyOutgoingBody.finish(outgoingBody, undefined);// Set the created response to an "OK" Result<T> valueResponseOutparam.set(outgoingResponse, {tag: "ok",val: outgoingResponse,});},};The http.ts file contains boilerplate source code.
Now, we want to start the application. Read on to learn the steps needed to start an application.
Run heim start, to start the heim runtime:
heim runtime heim@system:~/repos$ heim startStarting Runtime with Config:...Http server listening on: http://127.0.0.1:3000Heim portal: http://127.0.0.1:3000/heim/portal/Note that the Heim portal comes included with any Heim installation, and that it will be available on
http://127.0.0.1:3000/heim/portal/once you’ve installed Heim.Before deploying your application make sure all of your dependencies are installed for your TypeScript project by running
Terminal window npm installTo build the application and deploy it to our local-instance, we will run heim deploy. By default, this will create a debug build, but we can change it to a release build with the
--releaseflag:heim cli heim@system:~/repos$ heim deployINFO [ heim_cli::wasm::build ] Building Component: my-typescript-applicationRestore complete (0,6s)my-typescript-application succeeded (4,5s) → bin\Debug\net9.0\wasi-wasm\publish\Build succeeded in 7,7sINFO [ heim_registry::registry ] "my-typescript-application":"0.1.0":cb4abe161542a7b146fe27c5f5cdb60970d68a369f5703bde252664ddbe2eedfINFO [ Heim::Deploy ] Heim application `my-typescript-application` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash 8aba8efca7c309fe7cafce25df43fe78bbe9d0479f9b709cea97f9d507048a11 for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [GET] http://127.0.0.1:3000/my-typescript-applicationINFO [ Heim::Deploy ] Written and deployed application `my-typescript-application`.From here, you can see that we are able to access the application on
http://127.0.0.1:3000/my-typescript-application:curl heim@system:~/repos$ curl http://127.0.0.1:3000/my-typescript-applicationHello World!To deploy the application to the cloud instance, we will run heim deploy with the
--cloudflag. This will generate a release build as default, but it can be changed to a debug with the the--devflag.This will deploy the application to your subdomain at
my-subdomain.cloud.heim.devheim cli heim@system:~/repos$ heim deploy --cloudINFO [ heim_registry::registry ] "my-typescript-application":"0.1.0":02f6d7d3c34210438f293efc1ff2f8e9494f783a402e5dcbe6a308fea40d870eINFO [ Heim::Deploy ] Heim application `my-typescript-application` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Optimizing base componentINFO [ Heim::Pipeline ] Optimized base component, size before optimization: 2881425 bytes, size after optimization: 2278867 bytesINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash 62fd854418968a7c0cc383e962382dfc8e2d420b7fa5a4d48c6058ebb8544a05 for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [GET] https://my-subdomain.cloud.heim.dev/my-typescript-applicationINFO [ Heim::Deploy ] Written and deployed application `my-typescript-application`.And, in the heim runtime you will see something like this, if you started the runtime with the
--verboseflag:INFO WasmComponentHandler{app_id="localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:my-typescript-application:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"uri=/my-typescript-application}:heim_runtime::services::handlers::wasm_component_handler: 48:app_id="localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:my-typescript-application:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"uri=/my-typescript-application method=GETtrigger=Trigger {app_id: AppId("localhost:00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000:my-typescript-application:bbcb756cbf72e572fd47f3c299f44e1d083522aaa2696c3b0b24653deb884d3c"),path: "/my-typescript-application",method: "GET",function_target: None,hash: "",domain: "127.0.0.1"}The Heim runtime output above summarizes all the basic information about your application.
Let’s add an environment variable to our
component.toml.:component.tomlname = "my-typescript-application"version = "0.1.0"[registry.metadata]authors = [""]description = "Description of my-typescript-application"license = ""categories = [""][build.dev]build = "npm run build"wasm_path = "./dist/my-typescript-application.wasm"[build.prod]build = "npm run build"wasm_path = "./dist/my-typescript-application.wasm"[input.env]HELLO_MESSAGE = { type = "String" }While we’re at it we can change the
HTTP methodtoPOST, and set thepathto a new value. Furthermore, we’ll set a value to theHELLO_MESSAGEenvironment variable:application.tomlname = "my-typescript-application"component_target = 'my-typescript-application:0.1.0'[[trigger]]type = 'http'path = '/mypath'path = '/my-typescript-application'method = 'POST'method = 'GET'[env]HELLO_MESSAGE = "you"Finally, we’ll update the code to use the new environment variable, and modify our code to expect a JSON body, and return another JSON body:
http.tsimport {IncomingRequest,ResponseOutparam,OutgoingBody,OutgoingResponse,Fields,} from "wasi:http/types@0.2.1";import { getEnvironment } from "wasi:cli/environment@0.2.1";export const incomingHandler = {async handle(incomingRequest: IncomingRequest,responseOutparam: ResponseOutparam) {// Get a readable stream from the incoming requestconst request = incomingRequest.consume();const requestStream = request.stream();const pollable = requestStream.subscribe();// Read the stream as chunkslet chunks: Uint8Array[] = [];while (true) {await pollable.block();try {const chunk = requestStream.read(BigInt(1024));if (chunk.length === 0) {continue;}chunks.push(chunk);} catch (err) {// EOF is an errorbreak;}}// Combine the chunks to a Uint8Arrayconst totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);const fullBody = new Uint8Array(totalLength);let offset = 0;for (const chunk of chunks) {fullBody.set(chunk, offset);offset += chunk.length;}// Parse the body as a stringconst text = new TextDecoder().decode(fullBody);const json = JSON.parse(text);// Retrieve the environment variable we specified in component.toml and set the value for in application.tomlconst env_var = getEnvironment().find(([key]) => key == "HELLO_MESSAGE")?.[1];// Start building an outgoing responseconst outgoingResponse = new OutgoingResponse(Fields.fromList([["Content-Type", new TextEncoder().encode("application/json")]]));// Access the outgoing response bodylet outgoingBody = outgoingResponse.body();{// Create a stream for the response bodylet outputStream = outgoingBody.write();// Read the body and get env variableoutputStream.blockingWriteAndFlush(new Uint8Array(new TextEncoder().encode(JSON.stringify(`${json.message}, ${env_var}!`))));// @ts-ignore: This is required in order to dispose the stream before we returnoutputStream[Symbol.dispose]();}// Set the status code for the responseoutgoingResponse.setStatusCode(200);// Finish the response bodyOutgoingBody.finish(outgoingBody, undefined);// Set the created response to an "OK" Result<T> valueResponseOutparam.set(outgoingResponse, {tag: "ok",val: outgoingResponse,});},};Since the runtime is already running, we just need to build and deploy the application again, for our changes to take effect.
heim cli heim@system:~/repos$ heim deployINFO [ heim_cli::wasm::build ] Building Component: my-typescript-applicationRestore complete (0,4s)my-typescript-application succeeded (1,6s)Build succeeded in 3,3sINFO [ heim_registry::registry ] "my-typescript-application":"0.1.0":382c7a9e524efcc78f954ce0441933576d07974001bce9a36460ac32a94a5a8eINFO [ Heim::Deploy ] Heim application `my-typescript-application` is now built and written to registry.INFO [ Heim::Pipeline ] Starting pipeline 'Deploy application'INFO [ Heim::Pipeline ] Storing unoptimized component stateINFO [ Heim::Pipeline ] Checking if defined regions in app definition is validINFO [ Heim::Pipeline ] Continuing with localhost region heim-localhostINFO [ Heim::Pipeline ] Getting region specific application environment valuesINFO [ Heim::Pipeline ] Set environment values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting region specific application scaling valuesINFO [ Heim::Pipeline ] Set scaling values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting capabilitiesINFO [ Heim::Pipeline ] Set capabilities values for region 'heim-localhost'INFO [ Heim::Pipeline ] Getting triggersINFO [ Heim::Pipeline ] Set trigger values for region 'heim-localhost'INFO [ Heim::Pipeline ] Component environment values are valid for all regionsINFO [ Heim::Pipeline ] Checking for region with changes to buildINFO [ Heim::Pipeline ] Region "heim-localhost" has been changed and will be builtINFO [ Heim::Pipeline ] Storing component and optimized componentINFO [ Heim::Pipeline ] Stored component at ''INFO [ Heim::Pipeline ] Stored optimized component at ''INFO [ Heim::Pipeline ] Storing region statesINFO [ Heim::Pipeline ] Stored state for region(s) heim-localhost successfullyINFO [ Heim::Pipeline ] Creating and caching application(s)INFO [ Heim::Pipeline ] Creating and caching application(s) for region(s) heim-localhostINFO [ Heim::Pipeline ] Created application with hash db42889eeb46b4f4053adbf48239592c5a84e2c87ffe6d32f65d056f5d318c8e for region(s) heim-localhostINFO [ Heim::Pipeline ] Application has been deployed for region(s) heim-localhostINFO [ Heim::Pipeline ] Pipeline 'Deploy application' finished with status 'Success'INFO [ Heim::Deploy ] Heim deploy pipeline was successfulINFO [ Heim::Deploy ] Application is accaccessible at:INFO [ Heim::Deploy ] [POST] http://127.0.0.1:3000/mypathINFO [ Heim::Deploy ] Written and deployed application `my-typescript-application`.curl heim@system:~/repos$ curl.exe -X POST "http://127.0.0.1:3000/mypath" -H "Content-Type: application/json" -d '{\"message\":\"Hello\"}'Hello, you!When we are done, we can use the shortcut
Ctrl+Cto shut down the runtime.To clean up any resources from the guide you can run
heim clear. This will remove all data from the cache.
Summary
Section titled “Summary”-
- run
heim new - select the typescript-http
template - choose
HTTP method - choose trigger
path - set application
name
- run
-
- open the created application folder/project in your text editor
Take note of the configuration files:
-
- open
http.ts:
- run
heim startto start the Heim runtime
- run
heim deployto build and deploy the application.
- run
heim deploy --cloudto deploy the application to the cloud instance.
- open
-
- edit the
package.jsonfile to add useful dependencies - edit the
component.tomlfile to add environment variables - edit the
application.tomlfile to change the HTTP method - edit the
application.tomlfile to change the trigger path - edit the
application.tomlfile to set environment variable values - edit the
src/http.tsfile to use new environment variables - edit the
src/http.tsfile to set up return and accept values - deploy the application again to see your changes
- edit the
-
- use the
Ctrl+Cshortcut to shut down the Heim runtime - use the
heim clearcommand to remove all data from cache
- use the