Skip to content
Merged
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
26 changes: 15 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,22 +384,26 @@ and you can try again. A Node.js file error goes to the caller.
For a custom asset location, give one of these sources to
`loadTunelet(source)`:

- A URL.
- A URL or URL string.
- A fetch Response.
- A byte buffer.
- A compiled `WebAssembly.Module`.
- A promise for one of these.

For a Node.js `file:` source, use a URL object. A string source obeys fetch
rules. The first concurrent call selects the source. Later arguments do not
replace an initialized module. A custom binary must match the generated
bindings.
In Node.js, `loadTunelet` reads `file:` `URL` objects and `"file:"` URL strings
from disk. Other URLs and string sources obey fetch rules. The first concurrent
call selects the source. Later arguments do not replace an initialized module.
A custom binary must match the generated bindings.

The package root also exports `loadTunelet` as its default export. For direct
control of Wasm initialization, `tunelet/wasm` gives the generated default
initializer and `initSync`. The package root re-exports `initSync` too. Use
only one initialization entry point for each module instance. The package
gives only ESM exports. CommonJS applications can use `await import("tunelet")`.
initializer and `initSync`. The package root re-exports `initSync` too. The
package exports the Wasm binary at `tunelet/pkg/tunelet_bg.wasm` and
`tunelet/tunelet_bg.wasm`. Use only one initialization entry point for each
module instance.

The package gives only ESM exports. CommonJS applications can use
`await import("tunelet")`.

### Deployment

Expand Down Expand Up @@ -454,9 +458,9 @@ and show enums as string literals. To change the configuration, do these steps:

If a required field is absent or a value is not valid, the call throws a
JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults
to 4 if it is absent. The conversion ignores extra object properties. The
generated declarations contain the parameter documentation from the Rust
types.
to 4 if it is absent or `undefined`. The conversion ignores extra object
properties. The generated declarations contain the parameter documentation from
the Rust types.

`resynthesis.randomSeed` and the `processedFrames` field of feedback and
telemetry use `bigint`. Frame offsets, block lengths and latency use
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
"./wasm": {
"types": "./pkg/tunelet.d.ts",
"import": "./pkg/tunelet.js"
}
},
"./pkg/tunelet_bg.wasm": "./pkg/tunelet_bg.wasm",
"./tunelet_bg.wasm": "./pkg/tunelet_bg.wasm"
},
"files": [
"dist",
Expand All @@ -29,7 +31,7 @@
"sideEffects": false,
"scripts": {
"build": "npm run build:wasm && npm run build:ts",
"build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('pkg/.gitignore', { force: true })\"",
"build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/postbuild-wasm.mjs",
"build:ts": "tsc",
"check:wasm": "cargo clippy --locked --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo doc --locked --no-deps --target wasm32-unknown-unknown --features wasm",
"prepack": "npm run build",
Expand Down
216 changes: 216 additions & 0 deletions scripts/postbuild-wasm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
/**
* This script deletes `pkg/.gitignore`, adds a reference to
* `esnext.disposable`, and replaces ambient DOM and `WebAssembly` types in
* `pkg/tunelet.d.ts` with portable structural interfaces.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url));
const gitignorePath = path.join(pkgDir, ".gitignore");
const dtsPath = path.join(pkgDir, "tunelet.d.ts");

const DISPOSABLE_LIB_REFERENCE = '/// <reference lib="esnext.disposable" />';

const HEADER_ANCHOR = ["/* tslint:disable */", "/* eslint-disable */"].join(
"\n",
);

const HEADER_REPLACEMENT = [
DISPOSABLE_LIB_REFERENCE,
"/* tslint:disable */",
"/* eslint-disable */",
].join("\n");

const TUNELET_DISPOSE_ANCHOR = [
"export class Tunelet {",
" free(): void;",
" [Symbol.dispose](): void;",
].join("\n");

const INIT_INPUT_ANCHOR =
"export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;";

const INIT_INPUT_REPLACEMENT = [
"interface WasmRequest {",
" readonly method: string;",
" readonly url: string;",
" arrayBuffer(): Promise<ArrayBuffer>;",
"}",
"",
"type WasmRequestInfo = string | WasmRequest;",
"",
"interface WasmUrl {",
" readonly href: string;",
" readonly protocol: string;",
"}",
"",
"interface WasmResponse {",
" readonly ok: boolean;",
" readonly status: number;",
" readonly statusText: string;",
" readonly url: string;",
" arrayBuffer(): Promise<ArrayBuffer>;",
"}",
"",
"interface WasmBufferView {",
" readonly buffer: ArrayBufferLike;",
" readonly byteLength: number;",
" readonly byteOffset: number;",
"}",
"",
"type WasmBufferSource = ArrayBuffer | WasmBufferView;",
"",
"interface WasmModule {",
" readonly [Symbol.toStringTag]?: string | undefined;",
"}",
"",
"interface WasmMemory {",
" readonly buffer: ArrayBuffer;",
" grow(delta: number): number;",
" toFixedLengthBuffer(): ArrayBuffer;",
" toResizableBuffer(): ArrayBuffer;",
"}",
"",
"interface WasmTable {",
" readonly length: number;",
" get(index: number): any;",
" grow(delta: number, value?: any): number;",
" set(index: number, value?: any): void;",
"}",
"",
"export type InitInput = WasmRequestInfo | WasmUrl | WasmResponse | WasmBufferSource | WasmModule;",
].join("\n");

const MEMORY_ANCHOR = " readonly memory: WebAssembly.Memory;";
const MEMORY_REPLACEMENT = " readonly memory: WasmMemory;";

const TABLE_ANCHOR = " readonly __wbindgen_externrefs: WebAssembly.Table;";
const TABLE_REPLACEMENT = " readonly __wbindgen_externrefs: WasmTable;";

const SYNC_INIT_ANCHOR =
"export type SyncInitInput = BufferSource | WebAssembly.Module;";
const SYNC_INIT_REPLACEMENT =
"export type SyncInitInput = WasmBufferSource | WasmModule;";

const REPLACEMENTS = [
{
name: "header",
anchor: HEADER_ANCHOR,
replacement: HEADER_REPLACEMENT,
},
{
name: "InitInput",
anchor: INIT_INPUT_ANCHOR,
replacement: INIT_INPUT_REPLACEMENT,
},
{
name: "InitOutput.memory",
anchor: MEMORY_ANCHOR,
replacement: MEMORY_REPLACEMENT,
},
{
name: "InitOutput.__wbindgen_externrefs",
anchor: TABLE_ANCHOR,
replacement: TABLE_REPLACEMENT,
},
{
name: "SyncInitInput",
anchor: SYNC_INIT_ANCHOR,
replacement: SYNC_INIT_REPLACEMENT,
},
];

const FORBIDDEN_DECLARATION_PATTERNS = [
{ name: "RequestInfo", pattern: /\bRequestInfo\b/ },
{ name: "Response", pattern: /\bResponse\b/ },
{ name: "URL", pattern: /\bURL\b/ },
{ name: "BufferSource", pattern: /\bBufferSource\b/ },
{ name: "WebAssembly", pattern: /\bWebAssembly\b/ },
{ name: "declare global", pattern: /\bdeclare\s+global\b/ },
];

/** Checks that one exact anchor appears one time and returns its index. */
function findExactAnchor(source, name, anchor) {
const firstIndex = source.indexOf(anchor);
if (firstIndex === -1) {
throw new Error(
`Expected wasm-bindgen anchor "${name}" was not found in pkg/tunelet.d.ts`,
);
}
const secondIndex = source.indexOf(anchor, firstIndex + anchor.length);
if (secondIndex !== -1) {
throw new Error(
`Expected wasm-bindgen anchor "${name}" appeared more than one time in pkg/tunelet.d.ts`,
);
}
return firstIndex;
}

/** Replaces one exact anchor and throws if the anchor count is not one. */
function replaceExactAnchor(source, name, anchor, replacement) {
const firstIndex = findExactAnchor(source, name, anchor);
return (
source.slice(0, firstIndex) +
replacement +
source.slice(firstIndex + anchor.length)
);
}

/** Removes comments before a check for ambient identifiers. */
function stripComments(source) {
return source
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/^(?!\s*\/\/\/\s*<reference).*\/\/.*$/gm, "");
}

/** Sanitizes a declaration text and returns the updated content. */
export function sanitizeDeclarations(rawSource) {
const newline = rawSource.includes("\r\n") ? "\r\n" : "\n";
let content = rawSource.replace(/\r\n/g, "\n");

findExactAnchor(content, "Tunelet[Symbol.dispose]", TUNELET_DISPOSE_ANCHOR);

for (const item of REPLACEMENTS) {
content = replaceExactAnchor(
content,
item.name,
item.anchor,
item.replacement,
);
}

const referenceDirectives =
content.match(/\/\/\/\s*<reference\b[^\n]*/g) ?? [];
if (
referenceDirectives.length !== 1 ||
referenceDirectives[0] !== DISPOSABLE_LIB_REFERENCE ||
!content.startsWith(`${DISPOSABLE_LIB_REFERENCE}\n`)
) {
throw new Error(
'Only a top-level /// <reference lib="esnext.disposable" /> directive is permitted in pkg/tunelet.d.ts',
);
}

const codeOnly = stripComments(content);
for (const check of FORBIDDEN_DECLARATION_PATTERNS) {
if (check.pattern.test(codeOnly)) {
throw new Error(
`Unsanitized ambient type "${check.name}" stayed in pkg/tunelet.d.ts`,
);
}
}

return newline === "\r\n" ? content.replace(/\n/g, "\r\n") : content;
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
fs.rmSync(gitignorePath, { force: true });
if (!fs.existsSync(dtsPath)) {
throw new Error(`Declaration file was not found at ${dtsPath}`);
}
const original = fs.readFileSync(dtsPath, "utf8");
const sanitized = sanitizeDeclarations(original);
fs.writeFileSync(dtsPath, sanitized, "utf8");
}
Loading