tailscale/cmd/tsconnect/src/pkg/pkg.ts
Mihai Parparita 1a093ef482 cmd/tsconnect: extract NPM package for reusing in other projects
`src/` is broken up into several subdirectories:
- `lib/` and `types`/ for shared code and type definitions (more code
  will be moved here)
- `app/` for the existing Preact-app
- `pkg/` for the new NPM package

A new `build-pkg` esbuild-based command is added to generate the files
for the NPM package. To generate type definitions (something that esbuild
does not do), we set up `dts-bundle-generator`.

Includes additional cleanups to the Wasm type definitions (we switch to
string literals for enums, since exported const enums are hard to use
via packages).

Also allows the control URL to be set a runtime (in addition to the
current build option), so that we don't have to rebuild the package
for dev vs. prod use.

Updates #5415

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
2022-08-24 17:29:52 -07:00

40 lines
1.3 KiB
TypeScript

// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Type definitions need to be manually imported for dts-bundle-generator to
// discover them.
/// <reference path="../types/esbuild.d.ts" />
/// <reference path="../types/wasm_js.d.ts" />
import "../wasm_exec"
import wasmURL from "./main.wasm"
/**
* Superset of the IPNConfig type, with additional configuration that is
* needed for the package to function.
*/
type IPNPackageConfig = IPNConfig & {
// Auth key used to intitialize the Tailscale client (required)
authKey: string
// URL of the main.wasm file that is included in the page, if it is not
// accessible via a relative URL.
wasmURL?: string
// Funtion invoked if the Go process panics or unexpectedly exits.
panicHandler: (err: string) => void
}
export async function createIPN(config: IPNPackageConfig): Promise<IPN> {
const go = new Go()
const wasmInstance = await WebAssembly.instantiateStreaming(
fetch(config.wasmURL ?? wasmURL),
go.importObject
)
// The Go process should never exit, if it does then it's an unhandled panic.
go.run(wasmInstance.instance).then(() =>
config.panicHandler("Unexpected shutdown")
)
return newIPN(config)
}