From e2fb797c37e8bd80854f0985e617bcba752bc1fa Mon Sep 17 00:00:00 2001 From: Sebastian Jeltsch Date: Mon, 23 Mar 2026 17:03:07 +0100 Subject: [PATCH] Use jco guest-types for WASM guest type generation. --- guests/typescript/eslint.config.mjs | 4 +- .../generated/types/interfaces.d.ts | 60 +- .../trailbase-component-init-endpoint.d.ts | 39 +- ...se-component-sqlite-function-endpoint.d.ts | 35 +- .../interfaces/trailbase-database-sqlite.d.ts | 45 +- .../wasi-clocks-monotonic-clock.d.ts | 70 +- .../interfaces/wasi-clocks-wall-clock.d.ts | 59 +- .../interfaces/wasi-filesystem-preopens.d.ts | 14 +- .../interfaces/wasi-filesystem-types.d.ts | 1371 ++++++++------- .../wasi-http-incoming-handler.d.ts | 38 +- .../wasi-http-outgoing-handler.d.ts | 42 +- .../types/interfaces/wasi-http-types.d.ts | 1546 +++++++++-------- .../types/interfaces/wasi-io-error.d.ts | 36 +- .../types/interfaces/wasi-io-poll.d.ts | 85 +- .../types/interfaces/wasi-io-streams.d.ts | 461 ++--- .../interfaces/wasi-keyvalue-atomics.d.ts | 28 +- .../types/interfaces/wasi-keyvalue-batch.d.ts | 102 +- .../types/interfaces/wasi-keyvalue-store.d.ts | 209 +-- .../interfaces/wasi-random-insecure-seed.d.ts | 43 +- .../interfaces/wasi-random-insecure.d.ts | 39 +- .../types/interfaces/wasi-random-random.d.ts | 47 +- guests/typescript/package.json | 2 +- guests/typescript/tsconfig.json | 6 +- guests/typescript/vite.config.ts | 10 +- 24 files changed, 2309 insertions(+), 2082 deletions(-) diff --git a/guests/typescript/eslint.config.mjs b/guests/typescript/eslint.config.mjs index 6440a3d5..cf6bf27b 100644 --- a/guests/typescript/eslint.config.mjs +++ b/guests/typescript/eslint.config.mjs @@ -5,7 +5,7 @@ export default [ pluginJs.configs.recommended, ...tseslint.configs.recommended, { - ignores: ["dist/", "node_modules/"], + ignores: ["dist/", "node_modules/", "generated/types"], }, { files: ["src/**/*.{js,mjs,cjs,mts,ts,tsx,jsx}"], @@ -13,8 +13,6 @@ export default [ // https://typescript-eslint.io/rules/no-explicit-any/ "@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/no-wrapper-object-types": "warn", - "@typescript-eslint/no-namespace": "off", - "no-var": "off", // http://eslint.org/docs/rules/no-unused-vars "@typescript-eslint/no-unused-vars": [ "error", diff --git a/guests/typescript/generated/types/interfaces.d.ts b/guests/typescript/generated/types/interfaces.d.ts index b9968942..3d5c6a7a 100644 --- a/guests/typescript/generated/types/interfaces.d.ts +++ b/guests/typescript/generated/types/interfaces.d.ts @@ -1,20 +1,40 @@ -// WIT world: trailbase:component/interfaces@0.1.0. -export type * as TrailbaseDatabaseSqlite010 from 'trailbase:database/sqlite@0.1.0'; // import trailbase:database/sqlite@0.1.0 -export type * as WasiClocksMonotonicClock023 from 'wasi:clocks/monotonic-clock@0.2.3'; // import wasi:clocks/monotonic-clock@0.2.3 -export type * as WasiClocksWallClock023 from 'wasi:clocks/wall-clock@0.2.3'; // import wasi:clocks/wall-clock@0.2.3 -export type * as WasiFilesystemPreopens023 from 'wasi:filesystem/preopens@0.2.3'; // import wasi:filesystem/preopens@0.2.3 -export type * as WasiFilesystemTypes023 from 'wasi:filesystem/types@0.2.3'; // import wasi:filesystem/types@0.2.3 -export type * as WasiHttpOutgoingHandler023 from 'wasi:http/outgoing-handler@0.2.3'; // import wasi:http/outgoing-handler@0.2.3 -export type * as WasiHttpTypes023 from 'wasi:http/types@0.2.3'; // import wasi:http/types@0.2.3 -export type * as WasiIoError023 from 'wasi:io/error@0.2.3'; // import wasi:io/error@0.2.3 -export type * as WasiIoPoll023 from 'wasi:io/poll@0.2.3'; // import wasi:io/poll@0.2.3 -export type * as WasiIoStreams023 from 'wasi:io/streams@0.2.3'; // import wasi:io/streams@0.2.3 -export type * as WasiKeyvalueAtomics020Draft from 'wasi:keyvalue/atomics@0.2.0-draft'; // import wasi:keyvalue/atomics@0.2.0-draft -export type * as WasiKeyvalueBatch020Draft from 'wasi:keyvalue/batch@0.2.0-draft'; // import wasi:keyvalue/batch@0.2.0-draft -export type * as WasiKeyvalueStore020Draft from 'wasi:keyvalue/store@0.2.0-draft'; // import wasi:keyvalue/store@0.2.0-draft -export type * as WasiRandomInsecureSeed023 from 'wasi:random/insecure-seed@0.2.3'; // import wasi:random/insecure-seed@0.2.3 -export type * as WasiRandomInsecure023 from 'wasi:random/insecure@0.2.3'; // import wasi:random/insecure@0.2.3 -export type * as WasiRandomRandom023 from 'wasi:random/random@0.2.3'; // import wasi:random/random@0.2.3 -export * as incomingHandler from 'wasi:http/incoming-handler@0.2.3'; // export wasi:http/incoming-handler@0.2.3 -export * as initEndpoint from 'trailbase:component/init-endpoint@0.1.0'; // export trailbase:component/init-endpiont@0.1.0 -export * as sqliteFunctionEndpoint from 'trailbase:component/sqlite-function-endpoint@0.1.0'; // export trailbase:component/sqlite-function-endpoint@0.1.0 +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +declare module "trailbase:component/interfaces@0.1.0" { + export type * as TrailbaseDatabaseSqlite010 from "trailbase:database/sqlite@0.1.0"; // import trailbase:database/sqlite@0.1.0 + export type * as WasiClocksMonotonicClock023 from "wasi:clocks/monotonic-clock@0.2.3"; // import wasi:clocks/monotonic-clock@0.2.3 + export type * as WasiClocksWallClock023 from "wasi:clocks/wall-clock@0.2.3"; // import wasi:clocks/wall-clock@0.2.3 + export type * as WasiFilesystemPreopens023 from "wasi:filesystem/preopens@0.2.3"; // import wasi:filesystem/preopens@0.2.3 + export type * as WasiFilesystemTypes023 from "wasi:filesystem/types@0.2.3"; // import wasi:filesystem/types@0.2.3 + export type * as WasiHttpOutgoingHandler023 from "wasi:http/outgoing-handler@0.2.3"; // import wasi:http/outgoing-handler@0.2.3 + export type * as WasiHttpTypes023 from "wasi:http/types@0.2.3"; // import wasi:http/types@0.2.3 + export type * as WasiIoError023 from "wasi:io/error@0.2.3"; // import wasi:io/error@0.2.3 + export type * as WasiIoPoll023 from "wasi:io/poll@0.2.3"; // import wasi:io/poll@0.2.3 + export type * as WasiIoStreams023 from "wasi:io/streams@0.2.3"; // import wasi:io/streams@0.2.3 + export type * as WasiKeyvalueAtomics020Draft from "wasi:keyvalue/atomics@0.2.0-draft"; // import wasi:keyvalue/atomics@0.2.0-draft + export type * as WasiKeyvalueBatch020Draft from "wasi:keyvalue/batch@0.2.0-draft"; // import wasi:keyvalue/batch@0.2.0-draft + export type * as WasiKeyvalueStore020Draft from "wasi:keyvalue/store@0.2.0-draft"; // import wasi:keyvalue/store@0.2.0-draft + export type * as WasiRandomInsecureSeed023 from "wasi:random/insecure-seed@0.2.3"; // import wasi:random/insecure-seed@0.2.3 + export type * as WasiRandomInsecure023 from "wasi:random/insecure@0.2.3"; // import wasi:random/insecure@0.2.3 + export type * as WasiRandomRandom023 from "wasi:random/random@0.2.3"; // import wasi:random/random@0.2.3 + export * as incomingHandler from "wasi:http/incoming-handler@0.2.3"; // export wasi:http/incoming-handler@0.2.3 + export * as initEndpoint from "trailbase:component/init-endpoint@0.1.0"; // export trailbase:component/init-endpoint@0.1.0 + export * as sqliteFunctionEndpoint from "trailbase:component/sqlite-function-endpoint@0.1.0"; // export trailbase:component/sqlite-function-endpoint@0.1.0 +} diff --git a/guests/typescript/generated/types/interfaces/trailbase-component-init-endpoint.d.ts b/guests/typescript/generated/types/interfaces/trailbase-component-init-endpoint.d.ts index fdebf7b2..0d1a7e26 100644 --- a/guests/typescript/generated/types/interfaces/trailbase-component-init-endpoint.d.ts +++ b/guests/typescript/generated/types/interfaces/trailbase-component-init-endpoint.d.ts @@ -1,9 +1,9 @@ -declare module 'trailbase:component/init-endpoint@0.1.0' { +declare module "trailbase:component/init-endpoint@0.1.0" { export function initHttpHandlers(args: Arguments): HttpHandlers; export function initJobHandlers(args: Arguments): JobHandlers; export function initSqliteFunctions(args: Arguments): SqliteFunctions; export interface Arguments { - version?: string, + version?: string; } /** * # Variants @@ -26,18 +26,27 @@ declare module 'trailbase:component/init-endpoint@0.1.0' { * * ## `"connect"` */ - export type HttpMethodType = 'get' | 'post' | 'head' | 'options' | 'patch' | 'delete' | 'put' | 'trace' | 'connect'; + export type HttpMethodType = + | "get" + | "post" + | "head" + | "options" + | "patch" + | "delete" + | "put" + | "trace" + | "connect"; export interface HttpHandlers { /** * Registered http handlers (method, path)[]. */ - handlers: Array<[HttpMethodType, string]>, + handlers: Array<[HttpMethodType, string]>; } export interface JobHandlers { /** * Registered jobs (name, spec)[]. */ - handlers: Array<[string, string]>, + handlers: Array<[string, string]>; } /** * # Variants @@ -73,13 +82,23 @@ declare module 'trailbase:component/init-endpoint@0.1.0' { * * Indicates that the function is an aggregate that internally orders the values provided to the first argument. */ - export type SqliteFunctionFlags = 'utf8' | 'utf16le' | 'utf16be' | 'utf16' | 'deterministic' | 'direct-only' | 'subtype' | 'innocuous' | 'result-subtype' | 'selforder1'; + export type SqliteFunctionFlags = + | "utf8" + | "utf16le" + | "utf16be" + | "utf16" + | "deterministic" + | "direct-only" + | "subtype" + | "innocuous" + | "result-subtype" + | "selforder1"; export interface SqliteScalarFunction { - name: string, - numArgs: number, - functionFlags: Array, + name: string; + numArgs: number; + functionFlags: Array; } export interface SqliteFunctions { - scalarFunctions: Array, + scalarFunctions: Array; } } diff --git a/guests/typescript/generated/types/interfaces/trailbase-component-sqlite-function-endpoint.d.ts b/guests/typescript/generated/types/interfaces/trailbase-component-sqlite-function-endpoint.d.ts index 5270459f..64b5c2a7 100644 --- a/guests/typescript/generated/types/interfaces/trailbase-component-sqlite-function-endpoint.d.ts +++ b/guests/typescript/generated/types/interfaces/trailbase-component-sqlite-function-endpoint.d.ts @@ -1,4 +1,4 @@ -declare module 'trailbase:component/sqlite-function-endpoint@0.1.0' { +declare module "trailbase:component/sqlite-function-endpoint@0.1.0" { export function dispatchScalarFunction(args: Arguments): Value; /** * WARNING: Evolving a variant currently breaks the ABI: @@ -6,31 +6,36 @@ declare module 'trailbase:component/sqlite-function-endpoint@0.1.0' { */ export type Error = ErrorOther; export interface ErrorOther { - tag: 'other', - val: string, + tag: "other"; + val: string; } - export type Value = ValueNull | ValueText | ValueBlob | ValueInteger | ValueReal; + export type Value = + | ValueNull + | ValueText + | ValueBlob + | ValueInteger + | ValueReal; export interface ValueNull { - tag: 'null', + tag: "null"; } export interface ValueText { - tag: 'text', - val: string, + tag: "text"; + val: string; } export interface ValueBlob { - tag: 'blob', - val: Uint8Array, + tag: "blob"; + val: Uint8Array; } export interface ValueInteger { - tag: 'integer', - val: bigint, + tag: "integer"; + val: bigint; } export interface ValueReal { - tag: 'real', - val: number, + tag: "real"; + val: number; } export interface Arguments { - functionName: string, - arguments: Array, + functionName: string; + arguments: Array; } } diff --git a/guests/typescript/generated/types/interfaces/trailbase-database-sqlite.d.ts b/guests/typescript/generated/types/interfaces/trailbase-database-sqlite.d.ts index c6060067..4cd3a8f4 100644 --- a/guests/typescript/generated/types/interfaces/trailbase-database-sqlite.d.ts +++ b/guests/typescript/generated/types/interfaces/trailbase-database-sqlite.d.ts @@ -1,36 +1,53 @@ -declare module 'trailbase:database/sqlite@0.1.0' { +declare module "trailbase:database/sqlite@0.1.0" { + /** + * NOTE: Ideally, we'd use these but they can currently block guests, w/o a + * better non-blocking event loop. + * @since(version = 0.1.0) + * execute: func(query: string, params: list) -> result; + * @since(version = 0.1.0) + * query: func(query: string, params: list) -> result>, tx-error>; + * However, transactions have to be sync. + */ export function txBegin(): void; export function txCommit(): void; export function txRollback(): void; export function txExecute(query: string, params: Array): bigint; - export function txQuery(query: string, params: Array): Array>; + export function txQuery( + query: string, + params: Array, + ): Array>; /** * WARNING: Evolving a variant currently breaks the ABI: * https://github.com/WebAssembly/component-model/issues/454 */ export type TxError = TxErrorOther; export interface TxErrorOther { - tag: 'other', - val: string, + tag: "other"; + val: string; } - export type Value = ValueNull | ValueText | ValueBlob | ValueInteger | ValueReal; + export type Value = + | ValueNull + | ValueText + | ValueBlob + | ValueInteger + | ValueReal; export interface ValueNull { - tag: 'null', + tag: "null"; } export interface ValueText { - tag: 'text', - val: string, + tag: "text"; + val: string; } export interface ValueBlob { - tag: 'blob', - val: Uint8Array, + tag: "blob"; + val: Uint8Array; } export interface ValueInteger { - tag: 'integer', - val: bigint, + tag: "integer"; + val: bigint; } export interface ValueReal { - tag: 'real', - val: number, + tag: "real"; + val: number; } } diff --git a/guests/typescript/generated/types/interfaces/wasi-clocks-monotonic-clock.d.ts b/guests/typescript/generated/types/interfaces/wasi-clocks-monotonic-clock.d.ts index 5a1530c2..56749548 100644 --- a/guests/typescript/generated/types/interfaces/wasi-clocks-monotonic-clock.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-clocks-monotonic-clock.d.ts @@ -1,34 +1,36 @@ -/** @module Interface wasi:clocks/monotonic-clock@0.2.3 **/ -/** - * Read the current value of the clock. - * - * The clock is monotonic, therefore calling this function repeatedly will - * produce a sequence of non-decreasing values. - */ -export function now(): Instant; -/** - * Query the resolution of the clock. Returns the duration of time - * corresponding to a clock tick. - */ -export function resolution(): Duration; -/** - * Create a `pollable` which will resolve once the specified instant - * has occurred. - */ -export function subscribeInstant(when: Instant): Pollable; -/** - * Create a `pollable` that will resolve after the specified duration has - * elapsed from the time this function is invoked. - */ -export function subscribeDuration(when: Duration): Pollable; -export type Pollable = import('./wasi-io-poll.js').Pollable; -/** - * An instant in time, in nanoseconds. An instant is relative to an - * unspecified initial value, and can only be compared to instances from - * the same monotonic-clock. - */ -export type Instant = bigint; -/** - * A duration of time, in nanoseconds. - */ -export type Duration = bigint; +/// +declare module "wasi:clocks/monotonic-clock@0.2.3" { + /** + * Read the current value of the clock. + * + * The clock is monotonic, therefore calling this function repeatedly will + * produce a sequence of non-decreasing values. + */ + export function now(): Instant; + /** + * Query the resolution of the clock. Returns the duration of time + * corresponding to a clock tick. + */ + export function resolution(): Duration; + /** + * Create a `pollable` which will resolve once the specified instant + * has occurred. + */ + export function subscribeInstant(when: Instant): Pollable; + /** + * Create a `pollable` that will resolve after the specified duration has + * elapsed from the time this function is invoked. + */ + export function subscribeDuration(when: Duration): Pollable; + export type Pollable = import("wasi:io/poll@0.2.3").Pollable; + /** + * An instant in time, in nanoseconds. An instant is relative to an + * unspecified initial value, and can only be compared to instances from + * the same monotonic-clock. + */ + export type Instant = bigint; + /** + * A duration of time, in nanoseconds. + */ + export type Duration = bigint; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-clocks-wall-clock.d.ts b/guests/typescript/generated/types/interfaces/wasi-clocks-wall-clock.d.ts index f16f538f..bdc5c4a6 100644 --- a/guests/typescript/generated/types/interfaces/wasi-clocks-wall-clock.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-clocks-wall-clock.d.ts @@ -1,30 +1,31 @@ -/** @module Interface wasi:clocks/wall-clock@0.2.3 **/ -/** - * Read the current value of the clock. - * - * This clock is not monotonic, therefore calling this function repeatedly - * will not necessarily produce a sequence of non-decreasing values. - * - * The returned timestamps represent the number of seconds since - * 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], - * also known as [Unix Time]. - * - * The nanoseconds field of the output is always less than 1000000000. - * - * [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 - * [Unix Time]: https://en.wikipedia.org/wiki/Unix_time - */ -export function now(): Datetime; -/** - * Query the resolution of the clock. - * - * The nanoseconds field of the output is always less than 1000000000. - */ -export function resolution(): Datetime; -/** - * A time and date in seconds plus nanoseconds. - */ -export interface Datetime { - seconds: bigint, - nanoseconds: number, +declare module "wasi:clocks/wall-clock@0.2.3" { + /** + * Read the current value of the clock. + * + * This clock is not monotonic, therefore calling this function repeatedly + * will not necessarily produce a sequence of non-decreasing values. + * + * The returned timestamps represent the number of seconds since + * 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + * also known as [Unix Time]. + * + * The nanoseconds field of the output is always less than 1000000000. + * + * [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + * [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + */ + export function now(): Datetime; + /** + * Query the resolution of the clock. + * + * The nanoseconds field of the output is always less than 1000000000. + */ + export function resolution(): Datetime; + /** + * A time and date in seconds plus nanoseconds. + */ + export interface Datetime { + seconds: bigint; + nanoseconds: number; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-filesystem-preopens.d.ts b/guests/typescript/generated/types/interfaces/wasi-filesystem-preopens.d.ts index cca6e6b5..56ef2ab7 100644 --- a/guests/typescript/generated/types/interfaces/wasi-filesystem-preopens.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-filesystem-preopens.d.ts @@ -1,6 +1,8 @@ -/** @module Interface wasi:filesystem/preopens@0.2.3 **/ -/** - * Return the set of preopened directories, and their paths. - */ -export function getDirectories(): Array<[Descriptor, string]>; -export type Descriptor = import('./wasi-filesystem-types.js').Descriptor; +/// +declare module "wasi:filesystem/preopens@0.2.3" { + /** + * Return the set of preopened directories, and their paths. + */ + export function getDirectories(): Array<[Descriptor, string]>; + export type Descriptor = import("wasi:filesystem/types@0.2.3").Descriptor; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-filesystem-types.d.ts b/guests/typescript/generated/types/interfaces/wasi-filesystem-types.d.ts index 9da5370e..fc29a07c 100644 --- a/guests/typescript/generated/types/interfaces/wasi-filesystem-types.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-filesystem-types.d.ts @@ -1,671 +1,746 @@ -/** @module Interface wasi:filesystem/types@0.2.3 **/ -/** - * Attempts to extract a filesystem-related `error-code` from the stream - * `error` provided. - * - * Stream operations which return `stream-error::last-operation-failed` - * have a payload with more information about the operation that failed. - * This payload can be passed through to this function to see if there's - * filesystem-related information about the error to return. - * - * Note that this function is fallible because not all stream-related - * errors are filesystem-related errors. - */ -export function filesystemErrorCode(err: Error): ErrorCode | undefined; -export type InputStream = import('./wasi-io-streams.js').InputStream; -export type OutputStream = import('./wasi-io-streams.js').OutputStream; -export type Error = import('./wasi-io-streams.js').Error; -export type Datetime = import('./wasi-clocks-wall-clock.js').Datetime; -/** - * File size or length of a region within a file. - */ -export type Filesize = bigint; -/** - * The type of a filesystem object referenced by a descriptor. - * - * Note: This was called `filetype` in earlier versions of WASI. - * # Variants - * - * ## `"unknown"` - * - * The type of the descriptor or file is unknown or is different from - * any of the other types specified. - * ## `"block-device"` - * - * The descriptor refers to a block device inode. - * ## `"character-device"` - * - * The descriptor refers to a character device inode. - * ## `"directory"` - * - * The descriptor refers to a directory inode. - * ## `"fifo"` - * - * The descriptor refers to a named pipe. - * ## `"symbolic-link"` - * - * The file refers to a symbolic link inode. - * ## `"regular-file"` - * - * The descriptor refers to a regular file inode. - * ## `"socket"` - * - * The descriptor refers to a socket. - */ -export type DescriptorType = 'unknown' | 'block-device' | 'character-device' | 'directory' | 'fifo' | 'symbolic-link' | 'regular-file' | 'socket'; -/** - * Descriptor flags. - * - * Note: This was called `fdflags` in earlier versions of WASI. - */ -export interface DescriptorFlags { +/// +/// +declare module "wasi:filesystem/types@0.2.3" { /** - * Read mode: Data can be read. - */ - read?: boolean, - /** - * Write mode: Data can be written to. - */ - write?: boolean, - /** - * Request that writes be performed according to synchronized I/O file - * integrity completion. The data stored in the file and the file's - * metadata are synchronized. This is similar to `O_SYNC` in POSIX. + * Attempts to extract a filesystem-related `error-code` from the stream + * `error` provided. * - * The precise semantics of this operation have not yet been defined for - * WASI. At this time, it should be interpreted as a request, and not a - * requirement. - */ - fileIntegritySync?: boolean, - /** - * Request that writes be performed according to synchronized I/O data - * integrity completion. Only the data stored in the file is - * synchronized. This is similar to `O_DSYNC` in POSIX. + * Stream operations which return `stream-error::last-operation-failed` + * have a payload with more information about the operation that failed. + * This payload can be passed through to this function to see if there's + * filesystem-related information about the error to return. * - * The precise semantics of this operation have not yet been defined for - * WASI. At this time, it should be interpreted as a request, and not a - * requirement. + * Note that this function is fallible because not all stream-related + * errors are filesystem-related errors. */ - dataIntegritySync?: boolean, + export function filesystemErrorCode(err: Error): ErrorCode | undefined; + export type InputStream = import("wasi:io/streams@0.2.3").InputStream; + export type OutputStream = import("wasi:io/streams@0.2.3").OutputStream; + export type Error = import("wasi:io/streams@0.2.3").Error; + export type Datetime = import("wasi:clocks/wall-clock@0.2.3").Datetime; /** - * Requests that reads be performed at the same level of integrity - * requested for writes. This is similar to `O_RSYNC` in POSIX. + * File size or length of a region within a file. + */ + export type Filesize = bigint; + /** + * The type of a filesystem object referenced by a descriptor. * - * The precise semantics of this operation have not yet been defined for - * WASI. At this time, it should be interpreted as a request, and not a - * requirement. - */ - requestedWriteSync?: boolean, - /** - * Mutating directories mode: Directory contents may be mutated. + * Note: This was called `filetype` in earlier versions of WASI. + * # Variants * - * When this flag is unset on a descriptor, operations using the - * descriptor which would create, rename, delete, modify the data or - * metadata of filesystem objects, or obtain another handle which - * would permit any of those, shall fail with `error-code::read-only` if - * they would otherwise succeed. + * ## `"unknown"` * - * This may only be set on directories. - */ - mutateDirectory?: boolean, -} -/** - * Flags determining the method of how paths are resolved. - */ -export interface PathFlags { - /** - * As long as the resolved path corresponds to a symbolic link, it is - * expanded. - */ - symlinkFollow?: boolean, -} -/** - * Open flags used by `open-at`. - */ -export interface OpenFlags { - /** - * Create file if it does not exist, similar to `O_CREAT` in POSIX. - */ - create?: boolean, - /** - * Fail if not a directory, similar to `O_DIRECTORY` in POSIX. - */ - directory?: boolean, - /** - * Fail if file already exists, similar to `O_EXCL` in POSIX. - */ - exclusive?: boolean, - /** - * Truncate file to size 0, similar to `O_TRUNC` in POSIX. - */ - truncate?: boolean, -} -/** - * Number of hard links to an inode. - */ -export type LinkCount = bigint; -/** - * File attributes. - * - * Note: This was called `filestat` in earlier versions of WASI. - */ -export interface DescriptorStat { - /** - * File type. - */ - type: DescriptorType, - /** - * Number of hard links to the file. - */ - linkCount: LinkCount, - /** - * For regular files, the file size in bytes. For symbolic links, the - * length in bytes of the pathname contained in the symbolic link. - */ - size: Filesize, - /** - * Last data access timestamp. + * The type of the descriptor or file is unknown or is different from + * any of the other types specified. + * ## `"block-device"` * - * If the `option` is none, the platform doesn't maintain an access - * timestamp for this file. - */ - dataAccessTimestamp?: Datetime, - /** - * Last data modification timestamp. + * The descriptor refers to a block device inode. + * ## `"character-device"` * - * If the `option` is none, the platform doesn't maintain a - * modification timestamp for this file. - */ - dataModificationTimestamp?: Datetime, - /** - * Last file status-change timestamp. + * The descriptor refers to a character device inode. + * ## `"directory"` * - * If the `option` is none, the platform doesn't maintain a - * status-change timestamp for this file. + * The descriptor refers to a directory inode. + * ## `"fifo"` + * + * The descriptor refers to a named pipe. + * ## `"symbolic-link"` + * + * The file refers to a symbolic link inode. + * ## `"regular-file"` + * + * The descriptor refers to a regular file inode. + * ## `"socket"` + * + * The descriptor refers to a socket. */ - statusChangeTimestamp?: Datetime, -} -/** - * When setting a timestamp, this gives the value to set it to. - */ -export type NewTimestamp = NewTimestampNoChange | NewTimestampNow | NewTimestampTimestamp; -/** - * Leave the timestamp set to its previous value. - */ -export interface NewTimestampNoChange { - tag: 'no-change', -} -/** - * Set the timestamp to the current time of the system clock associated - * with the filesystem. - */ -export interface NewTimestampNow { - tag: 'now', -} -/** - * Set the timestamp to the given value. - */ -export interface NewTimestampTimestamp { - tag: 'timestamp', - val: Datetime, -} -/** - * A directory entry. - */ -export interface DirectoryEntry { + export type DescriptorType = + | "unknown" + | "block-device" + | "character-device" + | "directory" + | "fifo" + | "symbolic-link" + | "regular-file" + | "socket"; /** - * The type of the file referred to by this directory entry. + * Descriptor flags. + * + * Note: This was called `fdflags` in earlier versions of WASI. */ - type: DescriptorType, + export interface DescriptorFlags { + /** + * Read mode: Data can be read. + */ + read?: boolean; + /** + * Write mode: Data can be written to. + */ + write?: boolean; + /** + * Request that writes be performed according to synchronized I/O file + * integrity completion. The data stored in the file and the file's + * metadata are synchronized. This is similar to `O_SYNC` in POSIX. + * + * The precise semantics of this operation have not yet been defined for + * WASI. At this time, it should be interpreted as a request, and not a + * requirement. + */ + fileIntegritySync?: boolean; + /** + * Request that writes be performed according to synchronized I/O data + * integrity completion. Only the data stored in the file is + * synchronized. This is similar to `O_DSYNC` in POSIX. + * + * The precise semantics of this operation have not yet been defined for + * WASI. At this time, it should be interpreted as a request, and not a + * requirement. + */ + dataIntegritySync?: boolean; + /** + * Requests that reads be performed at the same level of integrity + * requested for writes. This is similar to `O_RSYNC` in POSIX. + * + * The precise semantics of this operation have not yet been defined for + * WASI. At this time, it should be interpreted as a request, and not a + * requirement. + */ + requestedWriteSync?: boolean; + /** + * Mutating directories mode: Directory contents may be mutated. + * + * When this flag is unset on a descriptor, operations using the + * descriptor which would create, rename, delete, modify the data or + * metadata of filesystem objects, or obtain another handle which + * would permit any of those, shall fail with `error-code::read-only` if + * they would otherwise succeed. + * + * This may only be set on directories. + */ + mutateDirectory?: boolean; + } /** - * The name of the object. + * Flags determining the method of how paths are resolved. */ - name: string, -} -/** - * Error codes returned by functions, similar to `errno` in POSIX. - * Not all of these error codes are returned by the functions provided by this - * API; some are used in higher-level library layers, and others are provided - * merely for alignment with POSIX. - * # Variants - * - * ## `"access"` - * - * Permission denied, similar to `EACCES` in POSIX. - * ## `"would-block"` - * - * Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. - * ## `"already"` - * - * Connection already in progress, similar to `EALREADY` in POSIX. - * ## `"bad-descriptor"` - * - * Bad descriptor, similar to `EBADF` in POSIX. - * ## `"busy"` - * - * Device or resource busy, similar to `EBUSY` in POSIX. - * ## `"deadlock"` - * - * Resource deadlock would occur, similar to `EDEADLK` in POSIX. - * ## `"quota"` - * - * Storage quota exceeded, similar to `EDQUOT` in POSIX. - * ## `"exist"` - * - * File exists, similar to `EEXIST` in POSIX. - * ## `"file-too-large"` - * - * File too large, similar to `EFBIG` in POSIX. - * ## `"illegal-byte-sequence"` - * - * Illegal byte sequence, similar to `EILSEQ` in POSIX. - * ## `"in-progress"` - * - * Operation in progress, similar to `EINPROGRESS` in POSIX. - * ## `"interrupted"` - * - * Interrupted function, similar to `EINTR` in POSIX. - * ## `"invalid"` - * - * Invalid argument, similar to `EINVAL` in POSIX. - * ## `"io"` - * - * I/O error, similar to `EIO` in POSIX. - * ## `"is-directory"` - * - * Is a directory, similar to `EISDIR` in POSIX. - * ## `"loop"` - * - * Too many levels of symbolic links, similar to `ELOOP` in POSIX. - * ## `"too-many-links"` - * - * Too many links, similar to `EMLINK` in POSIX. - * ## `"message-size"` - * - * Message too large, similar to `EMSGSIZE` in POSIX. - * ## `"name-too-long"` - * - * Filename too long, similar to `ENAMETOOLONG` in POSIX. - * ## `"no-device"` - * - * No such device, similar to `ENODEV` in POSIX. - * ## `"no-entry"` - * - * No such file or directory, similar to `ENOENT` in POSIX. - * ## `"no-lock"` - * - * No locks available, similar to `ENOLCK` in POSIX. - * ## `"insufficient-memory"` - * - * Not enough space, similar to `ENOMEM` in POSIX. - * ## `"insufficient-space"` - * - * No space left on device, similar to `ENOSPC` in POSIX. - * ## `"not-directory"` - * - * Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. - * ## `"not-empty"` - * - * Directory not empty, similar to `ENOTEMPTY` in POSIX. - * ## `"not-recoverable"` - * - * State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. - * ## `"unsupported"` - * - * Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. - * ## `"no-tty"` - * - * Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. - * ## `"no-such-device"` - * - * No such device or address, similar to `ENXIO` in POSIX. - * ## `"overflow"` - * - * Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. - * ## `"not-permitted"` - * - * Operation not permitted, similar to `EPERM` in POSIX. - * ## `"pipe"` - * - * Broken pipe, similar to `EPIPE` in POSIX. - * ## `"read-only"` - * - * Read-only file system, similar to `EROFS` in POSIX. - * ## `"invalid-seek"` - * - * Invalid seek, similar to `ESPIPE` in POSIX. - * ## `"text-file-busy"` - * - * Text file busy, similar to `ETXTBSY` in POSIX. - * ## `"cross-device"` - * - * Cross-device link, similar to `EXDEV` in POSIX. - */ -export type ErrorCode = 'access' | 'would-block' | 'already' | 'bad-descriptor' | 'busy' | 'deadlock' | 'quota' | 'exist' | 'file-too-large' | 'illegal-byte-sequence' | 'in-progress' | 'interrupted' | 'invalid' | 'io' | 'is-directory' | 'loop' | 'too-many-links' | 'message-size' | 'name-too-long' | 'no-device' | 'no-entry' | 'no-lock' | 'insufficient-memory' | 'insufficient-space' | 'not-directory' | 'not-empty' | 'not-recoverable' | 'unsupported' | 'no-tty' | 'no-such-device' | 'overflow' | 'not-permitted' | 'pipe' | 'read-only' | 'invalid-seek' | 'text-file-busy' | 'cross-device'; -/** - * File or memory access pattern advisory information. - * # Variants - * - * ## `"normal"` - * - * The application has no advice to give on its behavior with respect - * to the specified data. - * ## `"sequential"` - * - * The application expects to access the specified data sequentially - * from lower offsets to higher offsets. - * ## `"random"` - * - * The application expects to access the specified data in a random - * order. - * ## `"will-need"` - * - * The application expects to access the specified data in the near - * future. - * ## `"dont-need"` - * - * The application expects that it will not access the specified data - * in the near future. - * ## `"no-reuse"` - * - * The application expects to access the specified data once and then - * not reuse it thereafter. - */ -export type Advice = 'normal' | 'sequential' | 'random' | 'will-need' | 'dont-need' | 'no-reuse'; -/** - * A 128-bit hash value, split into parts because wasm doesn't have a - * 128-bit integer type. - */ -export interface MetadataHashValue { + export interface PathFlags { + /** + * As long as the resolved path corresponds to a symbolic link, it is + * expanded. + */ + symlinkFollow?: boolean; + } /** - * 64 bits of a 128-bit hash value. + * Open flags used by `open-at`. */ - lower: bigint, + export interface OpenFlags { + /** + * Create file if it does not exist, similar to `O_CREAT` in POSIX. + */ + create?: boolean; + /** + * Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + */ + directory?: boolean; + /** + * Fail if file already exists, similar to `O_EXCL` in POSIX. + */ + exclusive?: boolean; + /** + * Truncate file to size 0, similar to `O_TRUNC` in POSIX. + */ + truncate?: boolean; + } /** - * Another 64 bits of a 128-bit hash value. + * Number of hard links to an inode. */ - upper: bigint, -} + export type LinkCount = bigint; + /** + * File attributes. + * + * Note: This was called `filestat` in earlier versions of WASI. + */ + export interface DescriptorStat { + /** + * File type. + */ + type: DescriptorType; + /** + * Number of hard links to the file. + */ + linkCount: LinkCount; + /** + * For regular files, the file size in bytes. For symbolic links, the + * length in bytes of the pathname contained in the symbolic link. + */ + size: Filesize; + /** + * Last data access timestamp. + * + * If the `option` is none, the platform doesn't maintain an access + * timestamp for this file. + */ + dataAccessTimestamp?: Datetime; + /** + * Last data modification timestamp. + * + * If the `option` is none, the platform doesn't maintain a + * modification timestamp for this file. + */ + dataModificationTimestamp?: Datetime; + /** + * Last file status-change timestamp. + * + * If the `option` is none, the platform doesn't maintain a + * status-change timestamp for this file. + */ + statusChangeTimestamp?: Datetime; + } + /** + * When setting a timestamp, this gives the value to set it to. + */ + export type NewTimestamp = + | NewTimestampNoChange + | NewTimestampNow + | NewTimestampTimestamp; + /** + * Leave the timestamp set to its previous value. + */ + export interface NewTimestampNoChange { + tag: "no-change"; + } + /** + * Set the timestamp to the current time of the system clock associated + * with the filesystem. + */ + export interface NewTimestampNow { + tag: "now"; + } + /** + * Set the timestamp to the given value. + */ + export interface NewTimestampTimestamp { + tag: "timestamp"; + val: Datetime; + } + /** + * A directory entry. + */ + export interface DirectoryEntry { + /** + * The type of the file referred to by this directory entry. + */ + type: DescriptorType; + /** + * The name of the object. + */ + name: string; + } + /** + * Error codes returned by functions, similar to `errno` in POSIX. + * Not all of these error codes are returned by the functions provided by this + * API; some are used in higher-level library layers, and others are provided + * merely for alignment with POSIX. + * # Variants + * + * ## `"access"` + * + * Permission denied, similar to `EACCES` in POSIX. + * ## `"would-block"` + * + * Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + * ## `"already"` + * + * Connection already in progress, similar to `EALREADY` in POSIX. + * ## `"bad-descriptor"` + * + * Bad descriptor, similar to `EBADF` in POSIX. + * ## `"busy"` + * + * Device or resource busy, similar to `EBUSY` in POSIX. + * ## `"deadlock"` + * + * Resource deadlock would occur, similar to `EDEADLK` in POSIX. + * ## `"quota"` + * + * Storage quota exceeded, similar to `EDQUOT` in POSIX. + * ## `"exist"` + * + * File exists, similar to `EEXIST` in POSIX. + * ## `"file-too-large"` + * + * File too large, similar to `EFBIG` in POSIX. + * ## `"illegal-byte-sequence"` + * + * Illegal byte sequence, similar to `EILSEQ` in POSIX. + * ## `"in-progress"` + * + * Operation in progress, similar to `EINPROGRESS` in POSIX. + * ## `"interrupted"` + * + * Interrupted function, similar to `EINTR` in POSIX. + * ## `"invalid"` + * + * Invalid argument, similar to `EINVAL` in POSIX. + * ## `"io"` + * + * I/O error, similar to `EIO` in POSIX. + * ## `"is-directory"` + * + * Is a directory, similar to `EISDIR` in POSIX. + * ## `"loop"` + * + * Too many levels of symbolic links, similar to `ELOOP` in POSIX. + * ## `"too-many-links"` + * + * Too many links, similar to `EMLINK` in POSIX. + * ## `"message-size"` + * + * Message too large, similar to `EMSGSIZE` in POSIX. + * ## `"name-too-long"` + * + * Filename too long, similar to `ENAMETOOLONG` in POSIX. + * ## `"no-device"` + * + * No such device, similar to `ENODEV` in POSIX. + * ## `"no-entry"` + * + * No such file or directory, similar to `ENOENT` in POSIX. + * ## `"no-lock"` + * + * No locks available, similar to `ENOLCK` in POSIX. + * ## `"insufficient-memory"` + * + * Not enough space, similar to `ENOMEM` in POSIX. + * ## `"insufficient-space"` + * + * No space left on device, similar to `ENOSPC` in POSIX. + * ## `"not-directory"` + * + * Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + * ## `"not-empty"` + * + * Directory not empty, similar to `ENOTEMPTY` in POSIX. + * ## `"not-recoverable"` + * + * State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + * ## `"unsupported"` + * + * Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + * ## `"no-tty"` + * + * Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + * ## `"no-such-device"` + * + * No such device or address, similar to `ENXIO` in POSIX. + * ## `"overflow"` + * + * Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + * ## `"not-permitted"` + * + * Operation not permitted, similar to `EPERM` in POSIX. + * ## `"pipe"` + * + * Broken pipe, similar to `EPIPE` in POSIX. + * ## `"read-only"` + * + * Read-only file system, similar to `EROFS` in POSIX. + * ## `"invalid-seek"` + * + * Invalid seek, similar to `ESPIPE` in POSIX. + * ## `"text-file-busy"` + * + * Text file busy, similar to `ETXTBSY` in POSIX. + * ## `"cross-device"` + * + * Cross-device link, similar to `EXDEV` in POSIX. + */ + export type ErrorCode = + | "access" + | "would-block" + | "already" + | "bad-descriptor" + | "busy" + | "deadlock" + | "quota" + | "exist" + | "file-too-large" + | "illegal-byte-sequence" + | "in-progress" + | "interrupted" + | "invalid" + | "io" + | "is-directory" + | "loop" + | "too-many-links" + | "message-size" + | "name-too-long" + | "no-device" + | "no-entry" + | "no-lock" + | "insufficient-memory" + | "insufficient-space" + | "not-directory" + | "not-empty" + | "not-recoverable" + | "unsupported" + | "no-tty" + | "no-such-device" + | "overflow" + | "not-permitted" + | "pipe" + | "read-only" + | "invalid-seek" + | "text-file-busy" + | "cross-device"; + /** + * File or memory access pattern advisory information. + * # Variants + * + * ## `"normal"` + * + * The application has no advice to give on its behavior with respect + * to the specified data. + * ## `"sequential"` + * + * The application expects to access the specified data sequentially + * from lower offsets to higher offsets. + * ## `"random"` + * + * The application expects to access the specified data in a random + * order. + * ## `"will-need"` + * + * The application expects to access the specified data in the near + * future. + * ## `"dont-need"` + * + * The application expects that it will not access the specified data + * in the near future. + * ## `"no-reuse"` + * + * The application expects to access the specified data once and then + * not reuse it thereafter. + */ + export type Advice = + | "normal" + | "sequential" + | "random" + | "will-need" + | "dont-need" + | "no-reuse"; + /** + * A 128-bit hash value, split into parts because wasm doesn't have a + * 128-bit integer type. + */ + export interface MetadataHashValue { + /** + * 64 bits of a 128-bit hash value. + */ + lower: bigint; + /** + * Another 64 bits of a 128-bit hash value. + */ + upper: bigint; + } -export class Descriptor implements Partial { - /** - * This type does not have a public constructor. - */ - private constructor(); - /** - * Return a stream for reading from a file, if available. - * - * May fail with an error-code describing why the file cannot be read. - * - * Multiple read, write, and append streams may be active on the same open - * file and they do not interfere with each other. - * - * Note: This allows using `read-stream`, which is similar to `read` in POSIX. - */ - readViaStream(offset: Filesize): InputStream; - /** - * Return a stream for writing to a file, if available. - * - * May fail with an error-code describing why the file cannot be written. - * - * Note: This allows using `write-stream`, which is similar to `write` in - * POSIX. - */ - writeViaStream(offset: Filesize): OutputStream; - /** - * Return a stream for appending to a file, if available. - * - * May fail with an error-code describing why the file cannot be appended. - * - * Note: This allows using `write-stream`, which is similar to `write` with - * `O_APPEND` in POSIX. - */ - appendViaStream(): OutputStream; - /** - * Provide file advisory information on a descriptor. - * - * This is similar to `posix_fadvise` in POSIX. - */ - advise(offset: Filesize, length: Filesize, advice: Advice): void; - /** - * Synchronize the data of a file to disk. - * - * This function succeeds with no effect if the file descriptor is not - * opened for writing. - * - * Note: This is similar to `fdatasync` in POSIX. - */ - syncData(): void; - /** - * Get flags associated with a descriptor. - * - * Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. - * - * Note: This returns the value that was the `fs_flags` value returned - * from `fdstat_get` in earlier versions of WASI. - */ - getFlags(): DescriptorFlags; - /** - * Get the dynamic type of a descriptor. - * - * Note: This returns the same value as the `type` field of the `fd-stat` - * returned by `stat`, `stat-at` and similar. - * - * Note: This returns similar flags to the `st_mode & S_IFMT` value provided - * by `fstat` in POSIX. - * - * Note: This returns the value that was the `fs_filetype` value returned - * from `fdstat_get` in earlier versions of WASI. - */ - getType(): DescriptorType; - /** - * Adjust the size of an open file. If this increases the file's size, the - * extra bytes are filled with zeros. - * - * Note: This was called `fd_filestat_set_size` in earlier versions of WASI. - */ - setSize(size: Filesize): void; - /** - * Adjust the timestamps of an open file or directory. - * - * Note: This is similar to `futimens` in POSIX. - * - * Note: This was called `fd_filestat_set_times` in earlier versions of WASI. - */ - setTimes(dataAccessTimestamp: NewTimestamp, dataModificationTimestamp: NewTimestamp): void; - /** - * Read from a descriptor, without using and updating the descriptor's offset. - * - * This function returns a list of bytes containing the data that was - * read, along with a bool which, when true, indicates that the end of the - * file was reached. The returned list will contain up to `length` bytes; it - * may return fewer than requested, if the end of the file is reached or - * if the I/O operation is interrupted. - * - * In the future, this may change to return a `stream`. - * - * Note: This is similar to `pread` in POSIX. - */ - read(length: Filesize, offset: Filesize): [Uint8Array, boolean]; - /** - * Write to a descriptor, without using and updating the descriptor's offset. - * - * It is valid to write past the end of a file; the file is extended to the - * extent of the write, with bytes between the previous end and the start of - * the write set to zero. - * - * In the future, this may change to take a `stream`. - * - * Note: This is similar to `pwrite` in POSIX. - */ - write(buffer: Uint8Array, offset: Filesize): Filesize; - /** - * Read directory entries from a directory. - * - * On filesystems where directories contain entries referring to themselves - * and their parents, often named `.` and `..` respectively, these entries - * are omitted. - * - * This always returns a new stream which starts at the beginning of the - * directory. Multiple streams may be active on the same directory, and they - * do not interfere with each other. - */ - readDirectory(): DirectoryEntryStream; - /** - * Synchronize the data and metadata of a file to disk. - * - * This function succeeds with no effect if the file descriptor is not - * opened for writing. - * - * Note: This is similar to `fsync` in POSIX. - */ - sync(): void; - /** - * Create a directory. - * - * Note: This is similar to `mkdirat` in POSIX. - */ - createDirectoryAt(path: string): void; - /** - * Return the attributes of an open file or directory. - * - * Note: This is similar to `fstat` in POSIX, except that it does not return - * device and inode information. For testing whether two descriptors refer to - * the same underlying filesystem object, use `is-same-object`. To obtain - * additional data that can be used do determine whether a file has been - * modified, use `metadata-hash`. - * - * Note: This was called `fd_filestat_get` in earlier versions of WASI. - */ - stat(): DescriptorStat; - /** - * Return the attributes of a file or directory. - * - * Note: This is similar to `fstatat` in POSIX, except that it does not - * return device and inode information. See the `stat` description for a - * discussion of alternatives. - * - * Note: This was called `path_filestat_get` in earlier versions of WASI. - */ - statAt(pathFlags: PathFlags, path: string): DescriptorStat; - /** - * Adjust the timestamps of a file or directory. - * - * Note: This is similar to `utimensat` in POSIX. - * - * Note: This was called `path_filestat_set_times` in earlier versions of - * WASI. - */ - setTimesAt(pathFlags: PathFlags, path: string, dataAccessTimestamp: NewTimestamp, dataModificationTimestamp: NewTimestamp): void; - /** - * Create a hard link. - * - * Note: This is similar to `linkat` in POSIX. - */ - linkAt(oldPathFlags: PathFlags, oldPath: string, newDescriptor: Descriptor, newPath: string): void; - /** - * Open a file or directory. - * - * If `flags` contains `descriptor-flags::mutate-directory`, and the base - * descriptor doesn't have `descriptor-flags::mutate-directory` set, - * `open-at` fails with `error-code::read-only`. - * - * If `flags` contains `write` or `mutate-directory`, or `open-flags` - * contains `truncate` or `create`, and the base descriptor doesn't have - * `descriptor-flags::mutate-directory` set, `open-at` fails with - * `error-code::read-only`. - * - * Note: This is similar to `openat` in POSIX. - */ - openAt(pathFlags: PathFlags, path: string, openFlags: OpenFlags, flags: DescriptorFlags): Descriptor; - /** - * Read the contents of a symbolic link. - * - * If the contents contain an absolute or rooted path in the underlying - * filesystem, this function fails with `error-code::not-permitted`. - * - * Note: This is similar to `readlinkat` in POSIX. - */ - readlinkAt(path: string): string; - /** - * Remove a directory. - * - * Return `error-code::not-empty` if the directory is not empty. - * - * Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - */ - removeDirectoryAt(path: string): void; - /** - * Rename a filesystem object. - * - * Note: This is similar to `renameat` in POSIX. - */ - renameAt(oldPath: string, newDescriptor: Descriptor, newPath: string): void; - /** - * Create a symbolic link (also known as a "symlink"). - * - * If `old-path` starts with `/`, the function fails with - * `error-code::not-permitted`. - * - * Note: This is similar to `symlinkat` in POSIX. - */ - symlinkAt(oldPath: string, newPath: string): void; - /** - * Unlink a filesystem object that is not a directory. - * - * Return `error-code::is-directory` if the path refers to a directory. - * Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - */ - unlinkFileAt(path: string): void; - /** - * Test whether two descriptors refer to the same filesystem object. - * - * In POSIX, this corresponds to testing whether the two descriptors have the - * same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. - * wasi-filesystem does not expose device and inode numbers, so this function - * may be used instead. - */ - isSameObject(other: Descriptor): boolean; - /** - * Return a hash of the metadata associated with a filesystem object referred - * to by a descriptor. - * - * This returns a hash of the last-modification timestamp and file size, and - * may also include the inode number, device number, birth timestamp, and - * other metadata fields that may change when the file is modified or - * replaced. It may also include a secret value chosen by the - * implementation and not otherwise exposed. - * - * Implementations are encouraged to provide the following properties: - * - * - If the file is not modified or replaced, the computed hash value should - * usually not change. - * - If the object is modified or replaced, the computed hash value should - * usually change. - * - The inputs to the hash should not be easily computable from the - * computed hash. - * - * However, none of these is required. - */ - metadataHash(): MetadataHashValue; - /** - * Return a hash of the metadata associated with a filesystem object referred - * to by a directory descriptor and a relative path. - * - * This performs the same hash computation as `metadata-hash`. - */ - metadataHashAt(pathFlags: PathFlags, path: string): MetadataHashValue; - [Symbol.dispose]?: () => void; -} + export class Descriptor implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Return a stream for reading from a file, if available. + * + * May fail with an error-code describing why the file cannot be read. + * + * Multiple read, write, and append streams may be active on the same open + * file and they do not interfere with each other. + * + * Note: This allows using `read-stream`, which is similar to `read` in POSIX. + */ + readViaStream(offset: Filesize): InputStream; + /** + * Return a stream for writing to a file, if available. + * + * May fail with an error-code describing why the file cannot be written. + * + * Note: This allows using `write-stream`, which is similar to `write` in + * POSIX. + */ + writeViaStream(offset: Filesize): OutputStream; + /** + * Return a stream for appending to a file, if available. + * + * May fail with an error-code describing why the file cannot be appended. + * + * Note: This allows using `write-stream`, which is similar to `write` with + * `O_APPEND` in POSIX. + */ + appendViaStream(): OutputStream; + /** + * Provide file advisory information on a descriptor. + * + * This is similar to `posix_fadvise` in POSIX. + */ + advise(offset: Filesize, length: Filesize, advice: Advice): void; + /** + * Synchronize the data of a file to disk. + * + * This function succeeds with no effect if the file descriptor is not + * opened for writing. + * + * Note: This is similar to `fdatasync` in POSIX. + */ + syncData(): void; + /** + * Get flags associated with a descriptor. + * + * Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + * + * Note: This returns the value that was the `fs_flags` value returned + * from `fdstat_get` in earlier versions of WASI. + */ + getFlags(): DescriptorFlags; + /** + * Get the dynamic type of a descriptor. + * + * Note: This returns the same value as the `type` field of the `fd-stat` + * returned by `stat`, `stat-at` and similar. + * + * Note: This returns similar flags to the `st_mode & S_IFMT` value provided + * by `fstat` in POSIX. + * + * Note: This returns the value that was the `fs_filetype` value returned + * from `fdstat_get` in earlier versions of WASI. + */ + getType(): DescriptorType; + /** + * Adjust the size of an open file. If this increases the file's size, the + * extra bytes are filled with zeros. + * + * Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + */ + setSize(size: Filesize): void; + /** + * Adjust the timestamps of an open file or directory. + * + * Note: This is similar to `futimens` in POSIX. + * + * Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + */ + setTimes( + dataAccessTimestamp: NewTimestamp, + dataModificationTimestamp: NewTimestamp, + ): void; + /** + * Read from a descriptor, without using and updating the descriptor's offset. + * + * This function returns a list of bytes containing the data that was + * read, along with a bool which, when true, indicates that the end of the + * file was reached. The returned list will contain up to `length` bytes; it + * may return fewer than requested, if the end of the file is reached or + * if the I/O operation is interrupted. + * + * In the future, this may change to return a `stream`. + * + * Note: This is similar to `pread` in POSIX. + */ + read(length: Filesize, offset: Filesize): [Uint8Array, boolean]; + /** + * Write to a descriptor, without using and updating the descriptor's offset. + * + * It is valid to write past the end of a file; the file is extended to the + * extent of the write, with bytes between the previous end and the start of + * the write set to zero. + * + * In the future, this may change to take a `stream`. + * + * Note: This is similar to `pwrite` in POSIX. + */ + write(buffer: Uint8Array, offset: Filesize): Filesize; + /** + * Read directory entries from a directory. + * + * On filesystems where directories contain entries referring to themselves + * and their parents, often named `.` and `..` respectively, these entries + * are omitted. + * + * This always returns a new stream which starts at the beginning of the + * directory. Multiple streams may be active on the same directory, and they + * do not interfere with each other. + */ + readDirectory(): DirectoryEntryStream; + /** + * Synchronize the data and metadata of a file to disk. + * + * This function succeeds with no effect if the file descriptor is not + * opened for writing. + * + * Note: This is similar to `fsync` in POSIX. + */ + sync(): void; + /** + * Create a directory. + * + * Note: This is similar to `mkdirat` in POSIX. + */ + createDirectoryAt(path: string): void; + /** + * Return the attributes of an open file or directory. + * + * Note: This is similar to `fstat` in POSIX, except that it does not return + * device and inode information. For testing whether two descriptors refer to + * the same underlying filesystem object, use `is-same-object`. To obtain + * additional data that can be used do determine whether a file has been + * modified, use `metadata-hash`. + * + * Note: This was called `fd_filestat_get` in earlier versions of WASI. + */ + stat(): DescriptorStat; + /** + * Return the attributes of a file or directory. + * + * Note: This is similar to `fstatat` in POSIX, except that it does not + * return device and inode information. See the `stat` description for a + * discussion of alternatives. + * + * Note: This was called `path_filestat_get` in earlier versions of WASI. + */ + statAt(pathFlags: PathFlags, path: string): DescriptorStat; + /** + * Adjust the timestamps of a file or directory. + * + * Note: This is similar to `utimensat` in POSIX. + * + * Note: This was called `path_filestat_set_times` in earlier versions of + * WASI. + */ + setTimesAt( + pathFlags: PathFlags, + path: string, + dataAccessTimestamp: NewTimestamp, + dataModificationTimestamp: NewTimestamp, + ): void; + /** + * Create a hard link. + * + * Note: This is similar to `linkat` in POSIX. + */ + linkAt( + oldPathFlags: PathFlags, + oldPath: string, + newDescriptor: Descriptor, + newPath: string, + ): void; + /** + * Open a file or directory. + * + * If `flags` contains `descriptor-flags::mutate-directory`, and the base + * descriptor doesn't have `descriptor-flags::mutate-directory` set, + * `open-at` fails with `error-code::read-only`. + * + * If `flags` contains `write` or `mutate-directory`, or `open-flags` + * contains `truncate` or `create`, and the base descriptor doesn't have + * `descriptor-flags::mutate-directory` set, `open-at` fails with + * `error-code::read-only`. + * + * Note: This is similar to `openat` in POSIX. + */ + openAt( + pathFlags: PathFlags, + path: string, + openFlags: OpenFlags, + flags: DescriptorFlags, + ): Descriptor; + /** + * Read the contents of a symbolic link. + * + * If the contents contain an absolute or rooted path in the underlying + * filesystem, this function fails with `error-code::not-permitted`. + * + * Note: This is similar to `readlinkat` in POSIX. + */ + readlinkAt(path: string): string; + /** + * Remove a directory. + * + * Return `error-code::not-empty` if the directory is not empty. + * + * Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + */ + removeDirectoryAt(path: string): void; + /** + * Rename a filesystem object. + * + * Note: This is similar to `renameat` in POSIX. + */ + renameAt(oldPath: string, newDescriptor: Descriptor, newPath: string): void; + /** + * Create a symbolic link (also known as a "symlink"). + * + * If `old-path` starts with `/`, the function fails with + * `error-code::not-permitted`. + * + * Note: This is similar to `symlinkat` in POSIX. + */ + symlinkAt(oldPath: string, newPath: string): void; + /** + * Unlink a filesystem object that is not a directory. + * + * Return `error-code::is-directory` if the path refers to a directory. + * Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + */ + unlinkFileAt(path: string): void; + /** + * Test whether two descriptors refer to the same filesystem object. + * + * In POSIX, this corresponds to testing whether the two descriptors have the + * same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + * wasi-filesystem does not expose device and inode numbers, so this function + * may be used instead. + */ + isSameObject(other: Descriptor): boolean; + /** + * Return a hash of the metadata associated with a filesystem object referred + * to by a descriptor. + * + * This returns a hash of the last-modification timestamp and file size, and + * may also include the inode number, device number, birth timestamp, and + * other metadata fields that may change when the file is modified or + * replaced. It may also include a secret value chosen by the + * implementation and not otherwise exposed. + * + * Implementations are encouraged to provide the following properties: + * + * - If the file is not modified or replaced, the computed hash value should + * usually not change. + * - If the object is modified or replaced, the computed hash value should + * usually change. + * - The inputs to the hash should not be easily computable from the + * computed hash. + * + * However, none of these is required. + */ + metadataHash(): MetadataHashValue; + /** + * Return a hash of the metadata associated with a filesystem object referred + * to by a directory descriptor and a relative path. + * + * This performs the same hash computation as `metadata-hash`. + */ + metadataHashAt(pathFlags: PathFlags, path: string): MetadataHashValue; + [Symbol.dispose](): void; + } -export class DirectoryEntryStream implements Partial { - /** - * This type does not have a public constructor. - */ - private constructor(); - /** - * Read a single directory entry from a `directory-entry-stream`. - */ - readDirectoryEntry(): DirectoryEntry | undefined; - [Symbol.dispose]?: () => void; + export class DirectoryEntryStream implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Read a single directory entry from a `directory-entry-stream`. + */ + readDirectoryEntry(): DirectoryEntry | undefined; + [Symbol.dispose](): void; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-http-incoming-handler.d.ts b/guests/typescript/generated/types/interfaces/wasi-http-incoming-handler.d.ts index a43b7ff0..a12ed3f2 100644 --- a/guests/typescript/generated/types/interfaces/wasi-http-incoming-handler.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-http-incoming-handler.d.ts @@ -1,16 +1,22 @@ -/** @module Interface wasi:http/incoming-handler@0.2.3 **/ -/** - * This function is invoked with an incoming HTTP Request, and a resource - * `response-outparam` which provides the capability to reply with an HTTP - * Response. The response is sent by calling the `response-outparam.set` - * method, which allows execution to continue after the response has been - * sent. This enables both streaming to the response body, and performing other - * work. - * - * The implementor of this function must write a response to the - * `response-outparam` before returning, or else the caller will respond - * with an error on its behalf. - */ -export function handle(request: IncomingRequest, responseOut: ResponseOutparam): void; -export type IncomingRequest = import('./wasi-http-types.js').IncomingRequest; -export type ResponseOutparam = import('./wasi-http-types.js').ResponseOutparam; +/// +declare module "wasi:http/incoming-handler@0.2.3" { + /** + * This function is invoked with an incoming HTTP Request, and a resource + * `response-outparam` which provides the capability to reply with an HTTP + * Response. The response is sent by calling the `response-outparam.set` + * method, which allows execution to continue after the response has been + * sent. This enables both streaming to the response body, and performing other + * work. + * + * The implementor of this function must write a response to the + * `response-outparam` before returning, or else the caller will respond + * with an error on its behalf. + */ + export function handle( + request: IncomingRequest, + responseOut: ResponseOutparam, + ): void; + export type IncomingRequest = import("wasi:http/types@0.2.3").IncomingRequest; + export type ResponseOutparam = + import("wasi:http/types@0.2.3").ResponseOutparam; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-http-outgoing-handler.d.ts b/guests/typescript/generated/types/interfaces/wasi-http-outgoing-handler.d.ts index e00f8bfd..ab02ff2f 100644 --- a/guests/typescript/generated/types/interfaces/wasi-http-outgoing-handler.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-http-outgoing-handler.d.ts @@ -1,18 +1,24 @@ -/** @module Interface wasi:http/outgoing-handler@0.2.3 **/ -/** - * This function is invoked with an outgoing HTTP Request, and it returns - * a resource `future-incoming-response` which represents an HTTP Response - * which may arrive in the future. - * - * The `options` argument accepts optional parameters for the HTTP - * protocol's transport layer. - * - * This function may return an error if the `outgoing-request` is invalid - * or not allowed to be made. Otherwise, protocol errors are reported - * through the `future-incoming-response`. - */ -export function handle(request: OutgoingRequest, options: RequestOptions | undefined): FutureIncomingResponse; -export type OutgoingRequest = import('./wasi-http-types.js').OutgoingRequest; -export type RequestOptions = import('./wasi-http-types.js').RequestOptions; -export type FutureIncomingResponse = import('./wasi-http-types.js').FutureIncomingResponse; -export type ErrorCode = import('./wasi-http-types.js').ErrorCode; +/// +declare module "wasi:http/outgoing-handler@0.2.3" { + /** + * This function is invoked with an outgoing HTTP Request, and it returns + * a resource `future-incoming-response` which represents an HTTP Response + * which may arrive in the future. + * + * The `options` argument accepts optional parameters for the HTTP + * protocol's transport layer. + * + * This function may return an error if the `outgoing-request` is invalid + * or not allowed to be made. Otherwise, protocol errors are reported + * through the `future-incoming-response`. + */ + export function handle( + request: OutgoingRequest, + options: RequestOptions | undefined, + ): FutureIncomingResponse; + export type OutgoingRequest = import("wasi:http/types@0.2.3").OutgoingRequest; + export type RequestOptions = import("wasi:http/types@0.2.3").RequestOptions; + export type FutureIncomingResponse = + import("wasi:http/types@0.2.3").FutureIncomingResponse; + export type ErrorCode = import("wasi:http/types@0.2.3").ErrorCode; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-http-types.d.ts b/guests/typescript/generated/types/interfaces/wasi-http-types.d.ts index d51ad1b5..bae62c65 100644 --- a/guests/typescript/generated/types/interfaces/wasi-http-types.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-http-types.d.ts @@ -1,759 +1,819 @@ -/** @module Interface wasi:http/types@0.2.3 **/ -/** - * Attempts to extract a http-related `error` from the wasi:io `error` - * provided. - * - * Stream operations which return - * `wasi:io/stream/stream-error::last-operation-failed` have a payload of - * type `wasi:io/error/error` with more information about the operation - * that failed. This payload can be passed through to this function to see - * if there's http-related information about the error to return. - * - * Note that this function is fallible because not all io-errors are - * http-related errors. - */ -export function httpErrorCode(err: IoError): ErrorCode | undefined; -export type Duration = import('./wasi-clocks-monotonic-clock.js').Duration; -export type InputStream = import('./wasi-io-streams.js').InputStream; -export type OutputStream = import('./wasi-io-streams.js').OutputStream; -export type IoError = import('./wasi-io-error.js').Error; -export type Pollable = import('./wasi-io-poll.js').Pollable; -/** - * This type corresponds to HTTP standard Methods. - */ -export type Method = MethodGet | MethodHead | MethodPost | MethodPut | MethodDelete | MethodConnect | MethodOptions | MethodTrace | MethodPatch | MethodOther; -export interface MethodGet { - tag: 'get', -} -export interface MethodHead { - tag: 'head', -} -export interface MethodPost { - tag: 'post', -} -export interface MethodPut { - tag: 'put', -} -export interface MethodDelete { - tag: 'delete', -} -export interface MethodConnect { - tag: 'connect', -} -export interface MethodOptions { - tag: 'options', -} -export interface MethodTrace { - tag: 'trace', -} -export interface MethodPatch { - tag: 'patch', -} -export interface MethodOther { - tag: 'other', - val: string, -} -/** - * This type corresponds to HTTP standard Related Schemes. - */ -export type Scheme = SchemeHttp | SchemeHttps | SchemeOther; -export interface SchemeHttp { - tag: 'HTTP', -} -export interface SchemeHttps { - tag: 'HTTPS', -} -export interface SchemeOther { - tag: 'other', - val: string, -} -/** - * Defines the case payload type for `DNS-error` above: - */ -export interface DnsErrorPayload { - rcode?: string, - infoCode?: number, -} -/** - * Defines the case payload type for `TLS-alert-received` above: - */ -export interface TlsAlertReceivedPayload { - alertId?: number, - alertMessage?: string, -} -/** - * Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - */ -export interface FieldSizePayload { - fieldName?: string, - fieldSize?: number, -} -/** - * These cases are inspired by the IANA HTTP Proxy Error Types: - * - */ -export type ErrorCode = ErrorCodeDnsTimeout | ErrorCodeDnsError | ErrorCodeDestinationNotFound | ErrorCodeDestinationUnavailable | ErrorCodeDestinationIpProhibited | ErrorCodeDestinationIpUnroutable | ErrorCodeConnectionRefused | ErrorCodeConnectionTerminated | ErrorCodeConnectionTimeout | ErrorCodeConnectionReadTimeout | ErrorCodeConnectionWriteTimeout | ErrorCodeConnectionLimitReached | ErrorCodeTlsProtocolError | ErrorCodeTlsCertificateError | ErrorCodeTlsAlertReceived | ErrorCodeHttpRequestDenied | ErrorCodeHttpRequestLengthRequired | ErrorCodeHttpRequestBodySize | ErrorCodeHttpRequestMethodInvalid | ErrorCodeHttpRequestUriInvalid | ErrorCodeHttpRequestUriTooLong | ErrorCodeHttpRequestHeaderSectionSize | ErrorCodeHttpRequestHeaderSize | ErrorCodeHttpRequestTrailerSectionSize | ErrorCodeHttpRequestTrailerSize | ErrorCodeHttpResponseIncomplete | ErrorCodeHttpResponseHeaderSectionSize | ErrorCodeHttpResponseHeaderSize | ErrorCodeHttpResponseBodySize | ErrorCodeHttpResponseTrailerSectionSize | ErrorCodeHttpResponseTrailerSize | ErrorCodeHttpResponseTransferCoding | ErrorCodeHttpResponseContentCoding | ErrorCodeHttpResponseTimeout | ErrorCodeHttpUpgradeFailed | ErrorCodeHttpProtocolError | ErrorCodeLoopDetected | ErrorCodeConfigurationError | ErrorCodeInternalError; -export interface ErrorCodeDnsTimeout { - tag: 'DNS-timeout', -} -export interface ErrorCodeDnsError { - tag: 'DNS-error', - val: DnsErrorPayload, -} -export interface ErrorCodeDestinationNotFound { - tag: 'destination-not-found', -} -export interface ErrorCodeDestinationUnavailable { - tag: 'destination-unavailable', -} -export interface ErrorCodeDestinationIpProhibited { - tag: 'destination-IP-prohibited', -} -export interface ErrorCodeDestinationIpUnroutable { - tag: 'destination-IP-unroutable', -} -export interface ErrorCodeConnectionRefused { - tag: 'connection-refused', -} -export interface ErrorCodeConnectionTerminated { - tag: 'connection-terminated', -} -export interface ErrorCodeConnectionTimeout { - tag: 'connection-timeout', -} -export interface ErrorCodeConnectionReadTimeout { - tag: 'connection-read-timeout', -} -export interface ErrorCodeConnectionWriteTimeout { - tag: 'connection-write-timeout', -} -export interface ErrorCodeConnectionLimitReached { - tag: 'connection-limit-reached', -} -export interface ErrorCodeTlsProtocolError { - tag: 'TLS-protocol-error', -} -export interface ErrorCodeTlsCertificateError { - tag: 'TLS-certificate-error', -} -export interface ErrorCodeTlsAlertReceived { - tag: 'TLS-alert-received', - val: TlsAlertReceivedPayload, -} -export interface ErrorCodeHttpRequestDenied { - tag: 'HTTP-request-denied', -} -export interface ErrorCodeHttpRequestLengthRequired { - tag: 'HTTP-request-length-required', -} -export interface ErrorCodeHttpRequestBodySize { - tag: 'HTTP-request-body-size', - val: bigint | undefined, -} -export interface ErrorCodeHttpRequestMethodInvalid { - tag: 'HTTP-request-method-invalid', -} -export interface ErrorCodeHttpRequestUriInvalid { - tag: 'HTTP-request-URI-invalid', -} -export interface ErrorCodeHttpRequestUriTooLong { - tag: 'HTTP-request-URI-too-long', -} -export interface ErrorCodeHttpRequestHeaderSectionSize { - tag: 'HTTP-request-header-section-size', - val: number | undefined, -} -export interface ErrorCodeHttpRequestHeaderSize { - tag: 'HTTP-request-header-size', - val: FieldSizePayload | undefined, -} -export interface ErrorCodeHttpRequestTrailerSectionSize { - tag: 'HTTP-request-trailer-section-size', - val: number | undefined, -} -export interface ErrorCodeHttpRequestTrailerSize { - tag: 'HTTP-request-trailer-size', - val: FieldSizePayload, -} -export interface ErrorCodeHttpResponseIncomplete { - tag: 'HTTP-response-incomplete', -} -export interface ErrorCodeHttpResponseHeaderSectionSize { - tag: 'HTTP-response-header-section-size', - val: number | undefined, -} -export interface ErrorCodeHttpResponseHeaderSize { - tag: 'HTTP-response-header-size', - val: FieldSizePayload, -} -export interface ErrorCodeHttpResponseBodySize { - tag: 'HTTP-response-body-size', - val: bigint | undefined, -} -export interface ErrorCodeHttpResponseTrailerSectionSize { - tag: 'HTTP-response-trailer-section-size', - val: number | undefined, -} -export interface ErrorCodeHttpResponseTrailerSize { - tag: 'HTTP-response-trailer-size', - val: FieldSizePayload, -} -export interface ErrorCodeHttpResponseTransferCoding { - tag: 'HTTP-response-transfer-coding', - val: string | undefined, -} -export interface ErrorCodeHttpResponseContentCoding { - tag: 'HTTP-response-content-coding', - val: string | undefined, -} -export interface ErrorCodeHttpResponseTimeout { - tag: 'HTTP-response-timeout', -} -export interface ErrorCodeHttpUpgradeFailed { - tag: 'HTTP-upgrade-failed', -} -export interface ErrorCodeHttpProtocolError { - tag: 'HTTP-protocol-error', -} -export interface ErrorCodeLoopDetected { - tag: 'loop-detected', -} -export interface ErrorCodeConfigurationError { - tag: 'configuration-error', -} -/** - * This is a catch-all error for anything that doesn't fit cleanly into a - * more specific case. It also includes an optional string for an - * unstructured description of the error. Users should not depend on the - * string for diagnosing errors, as it's not required to be consistent - * between implementations. - */ -export interface ErrorCodeInternalError { - tag: 'internal-error', - val: string | undefined, -} -/** - * This type enumerates the different kinds of errors that may occur when - * setting or appending to a `fields` resource. - */ -export type HeaderError = HeaderErrorInvalidSyntax | HeaderErrorForbidden | HeaderErrorImmutable; -/** - * This error indicates that a `field-name` or `field-value` was - * syntactically invalid when used with an operation that sets headers in a - * `fields`. - */ -export interface HeaderErrorInvalidSyntax { - tag: 'invalid-syntax', -} -/** - * This error indicates that a forbidden `field-name` was used when trying - * to set a header in a `fields`. - */ -export interface HeaderErrorForbidden { - tag: 'forbidden', -} -/** - * This error indicates that the operation on the `fields` was not - * permitted because the fields are immutable. - */ -export interface HeaderErrorImmutable { - tag: 'immutable', -} -/** - * Field keys are always strings. - * - * Field keys should always be treated as case insensitive by the `fields` - * resource for the purposes of equality checking. - * - * # Deprecation - * - * This type has been deprecated in favor of the `field-name` type. - */ -export type FieldKey = string; -/** - * Field names are always strings. - * - * Field names should always be treated as case insensitive by the `fields` - * resource for the purposes of equality checking. - */ -export type FieldName = FieldKey; -/** - * Field values should always be ASCII strings. However, in - * reality, HTTP implementations often have to interpret malformed values, - * so they are provided as a list of bytes. - */ -export type FieldValue = Uint8Array; -/** - * Headers is an alias for Fields. - */ -export type Headers = Fields; -/** - * Trailers is an alias for Fields. - */ -export type Trailers = Fields; -/** - * This type corresponds to the HTTP standard Status Code. - */ -export type StatusCode = number; -export type Result = { tag: 'ok', val: T } | { tag: 'err', val: E }; - -export class Fields implements Partial { +/// +/// +/// +/// +declare module "wasi:http/types@0.2.3" { /** - * Construct an empty HTTP Fields. - * - * The resulting `fields` is mutable. - */ - constructor() - /** - * Construct an HTTP Fields. - * - * The resulting `fields` is mutable. - * - * The list represents each name-value pair in the Fields. Names - * which have multiple values are represented by multiple entries in this - * list with the same name. - * - * The tuple is a pair of the field name, represented as a string, and - * Value, represented as a list of bytes. - * - * An error result will be returned if any `field-name` or `field-value` is - * syntactically invalid, or if a field is forbidden. - */ - static fromList(entries: Array<[FieldName, FieldValue]>): Fields; - /** - * Get all of the values corresponding to a name. If the name is not present - * in this `fields` or is syntactically invalid, an empty list is returned. - * However, if the name is present but empty, this is represented by a list - * with one or more empty field-values present. - */ - get(name: FieldName): Array; - /** - * Returns `true` when the name is present in this `fields`. If the name is - * syntactically invalid, `false` is returned. - */ - has(name: FieldName): boolean; - /** - * Set all of the values for a name. Clears any existing values for that - * name, if they have been set. - * - * Fails with `header-error.immutable` if the `fields` are immutable. - * - * Fails with `header-error.invalid-syntax` if the `field-name` or any of - * the `field-value`s are syntactically invalid. - */ - set(name: FieldName, value: Array): void; - /** - * Delete all values for a name. Does nothing if no values for the name - * exist. - * - * Fails with `header-error.immutable` if the `fields` are immutable. - * - * Fails with `header-error.invalid-syntax` if the `field-name` is - * syntactically invalid. - */ - 'delete'(name: FieldName): void; - /** - * Append a value for a name. Does not change or delete any existing - * values for that name. - * - * Fails with `header-error.immutable` if the `fields` are immutable. - * - * Fails with `header-error.invalid-syntax` if the `field-name` or - * `field-value` are syntactically invalid. - */ - append(name: FieldName, value: FieldValue): void; - /** - * Retrieve the full set of names and values in the Fields. Like the - * constructor, the list represents each name-value pair. - * - * The outer list represents each name-value pair in the Fields. Names - * which have multiple values are represented by multiple entries in this - * list with the same name. - * - * The names and values are always returned in the original casing and in - * the order in which they will be serialized for transport. - */ - entries(): Array<[FieldName, FieldValue]>; - /** - * Make a deep copy of the Fields. Equivalent in behavior to calling the - * `fields` constructor on the return value of `entries`. The resulting - * `fields` is mutable. - */ - clone(): Fields; - [Symbol.dispose]?: () => void; -} - -export class FutureIncomingResponse implements Partial { - /** - * This type does not have a public constructor. + * Attempts to extract a http-related `error` from the wasi:io `error` + * provided. + * + * Stream operations which return + * `wasi:io/stream/stream-error::last-operation-failed` have a payload of + * type `wasi:io/error/error` with more information about the operation + * that failed. This payload can be passed through to this function to see + * if there's http-related information about the error to return. + * + * Note that this function is fallible because not all io-errors are + * http-related errors. */ - private constructor(); + export function httpErrorCode(err: IoError): ErrorCode | undefined; + export type Duration = import("wasi:clocks/monotonic-clock@0.2.3").Duration; + export type InputStream = import("wasi:io/streams@0.2.3").InputStream; + export type OutputStream = import("wasi:io/streams@0.2.3").OutputStream; + export type IoError = import("wasi:io/error@0.2.3").Error; + export type Pollable = import("wasi:io/poll@0.2.3").Pollable; /** - * Returns a pollable which becomes ready when either the Response has - * been received, or an error has occurred. When this pollable is ready, - * the `get` method will return `some`. - */ - subscribe(): Pollable; - /** - * Returns the incoming HTTP Response, or an error, once one is ready. - * - * The outer `option` represents future readiness. Users can wait on this - * `option` to become `some` using the `subscribe` method. - * - * The outer `result` is used to retrieve the response or error at most - * once. It will be success on the first call in which the outer option - * is `some`, and error on subsequent calls. - * - * The inner `result` represents that either the incoming HTTP Response - * status and headers have received successfully, or that an error - * occurred. Errors may also occur while consuming the response body, - * but those will be reported by the `incoming-body` and its - * `output-stream` child. - */ - get(): Result, void> | undefined; - [Symbol.dispose]?: () => void; -} - -export class FutureTrailers implements Partial { - /** - * This type does not have a public constructor. + * This type corresponds to HTTP standard Methods. */ - private constructor(); + export type Method = + | MethodGet + | MethodHead + | MethodPost + | MethodPut + | MethodDelete + | MethodConnect + | MethodOptions + | MethodTrace + | MethodPatch + | MethodOther; + export interface MethodGet { + tag: "get"; + } + export interface MethodHead { + tag: "head"; + } + export interface MethodPost { + tag: "post"; + } + export interface MethodPut { + tag: "put"; + } + export interface MethodDelete { + tag: "delete"; + } + export interface MethodConnect { + tag: "connect"; + } + export interface MethodOptions { + tag: "options"; + } + export interface MethodTrace { + tag: "trace"; + } + export interface MethodPatch { + tag: "patch"; + } + export interface MethodOther { + tag: "other"; + val: string; + } /** - * Returns a pollable which becomes ready when either the trailers have - * been received, or an error has occurred. When this pollable is ready, - * the `get` method will return `some`. - */ - subscribe(): Pollable; - /** - * Returns the contents of the trailers, or an error which occurred, - * once the future is ready. - * - * The outer `option` represents future readiness. Users can wait on this - * `option` to become `some` using the `subscribe` method. - * - * The outer `result` is used to retrieve the trailers or error at most - * once. It will be success on the first call in which the outer option - * is `some`, and error on subsequent calls. - * - * The inner `result` represents that either the HTTP Request or Response - * body, as well as any trailers, were received successfully, or that an - * error occurred receiving them. The optional `trailers` indicates whether - * or not trailers were present in the body. - * - * When some `trailers` are returned by this method, the `trailers` - * resource is immutable, and a child. Use of the `set`, `append`, or - * `delete` methods will return an error, and the resource must be - * dropped before the parent `future-trailers` is dropped. - */ - get(): Result, void> | undefined; - [Symbol.dispose]?: () => void; -} - -export class IncomingBody implements Partial { - /** - * This type does not have a public constructor. + * This type corresponds to HTTP standard Related Schemes. */ - private constructor(); + export type Scheme = SchemeHttp | SchemeHttps | SchemeOther; + export interface SchemeHttp { + tag: "HTTP"; + } + export interface SchemeHttps { + tag: "HTTPS"; + } + export interface SchemeOther { + tag: "other"; + val: string; + } /** - * Returns the contents of the body, as a stream of bytes. - * - * Returns success on first call: the stream representing the contents - * can be retrieved at most once. Subsequent calls will return error. - * - * The returned `input-stream` resource is a child: it must be dropped - * before the parent `incoming-body` is dropped, or consumed by - * `incoming-body.finish`. - * - * This invariant ensures that the implementation can determine whether - * the user is consuming the contents of the body, waiting on the - * `future-trailers` to be ready, or neither. This allows for network - * backpressure is to be applied when the user is consuming the body, - * and for that backpressure to not inhibit delivery of the trailers if - * the user does not read the entire body. - */ - stream(): InputStream; - /** - * Takes ownership of `incoming-body`, and returns a `future-trailers`. - * This function will trap if the `input-stream` child is still alive. - */ - static finish(this_: IncomingBody): FutureTrailers; - [Symbol.dispose]?: () => void; -} - -export class IncomingRequest implements Partial { - /** - * This type does not have a public constructor. + * Defines the case payload type for `DNS-error` above: */ - private constructor(); + export interface DnsErrorPayload { + rcode?: string; + infoCode?: number; + } /** - * Returns the method of the incoming request. - */ - method(): Method; - /** - * Returns the path with query parameters from the request, as a string. - */ - pathWithQuery(): string | undefined; - /** - * Returns the protocol scheme from the request. - */ - scheme(): Scheme | undefined; - /** - * Returns the authority of the Request's target URI, if present. - */ - authority(): string | undefined; - /** - * Get the `headers` associated with the request. - * - * The returned `headers` resource is immutable: `set`, `append`, and - * `delete` operations will fail with `header-error.immutable`. - * - * The `headers` returned are a child resource: it must be dropped before - * the parent `incoming-request` is dropped. Dropping this - * `incoming-request` before all children are dropped will trap. - */ - headers(): Headers; - /** - * Gives the `incoming-body` associated with this request. Will only - * return success at most once, and subsequent calls will return error. - */ - consume(): IncomingBody; - [Symbol.dispose]?: () => void; -} - -export class IncomingResponse implements Partial { - /** - * This type does not have a public constructor. + * Defines the case payload type for `TLS-alert-received` above: */ - private constructor(); + export interface TlsAlertReceivedPayload { + alertId?: number; + alertMessage?: string; + } /** - * Returns the status code from the incoming response. - */ - status(): StatusCode; - /** - * Returns the headers from the incoming response. - * - * The returned `headers` resource is immutable: `set`, `append`, and - * `delete` operations will fail with `header-error.immutable`. - * - * This headers resource is a child: it must be dropped before the parent - * `incoming-response` is dropped. - */ - headers(): Headers; - /** - * Returns the incoming body. May be called at most once. Returns error - * if called additional times. - */ - consume(): IncomingBody; - [Symbol.dispose]?: () => void; -} - -export class OutgoingBody implements Partial { - /** - * This type does not have a public constructor. + * Defines the case payload type for `HTTP-response-{header,trailer}-size` above: */ - private constructor(); + export interface FieldSizePayload { + fieldName?: string; + fieldSize?: number; + } /** - * Returns a stream for writing the body contents. - * - * The returned `output-stream` is a child resource: it must be dropped - * before the parent `outgoing-body` resource is dropped (or finished), - * otherwise the `outgoing-body` drop or `finish` will trap. - * - * Returns success on the first call: the `output-stream` resource for - * this `outgoing-body` may be retrieved at most once. Subsequent calls - * will return error. - */ - write(): OutputStream; - /** - * Finalize an outgoing body, optionally providing trailers. This must be - * called to signal that the response is complete. If the `outgoing-body` - * is dropped without calling `outgoing-body.finalize`, the implementation - * should treat the body as corrupted. - * - * Fails if the body's `outgoing-request` or `outgoing-response` was - * constructed with a Content-Length header, and the contents written - * to the body (via `write`) does not match the value given in the - * Content-Length. - */ - static finish(this_: OutgoingBody, trailers: Trailers | undefined): void; - [Symbol.dispose]?: () => void; -} - -export class OutgoingRequest implements Partial { - /** - * Construct a new `outgoing-request` with a default `method` of `GET`, and - * `none` values for `path-with-query`, `scheme`, and `authority`. - * - * * `headers` is the HTTP Headers for the Request. - * - * It is possible to construct, or manipulate with the accessor functions - * below, an `outgoing-request` with an invalid combination of `scheme` - * and `authority`, or `headers` which are not permitted to be sent. - * It is the obligation of the `outgoing-handler.handle` implementation - * to reject invalid constructions of `outgoing-request`. - */ - constructor(headers: Headers) - /** - * Returns the resource corresponding to the outgoing Body for this - * Request. - * - * Returns success on the first call: the `outgoing-body` resource for - * this `outgoing-request` can be retrieved at most once. Subsequent - * calls will return error. - */ - body(): OutgoingBody; - /** - * Get the Method for the Request. - */ - method(): Method; - /** - * Set the Method for the Request. Fails if the string present in a - * `method.other` argument is not a syntactically valid method. - */ - setMethod(method: Method): void; - /** - * Get the combination of the HTTP Path and Query for the Request. - * When `none`, this represents an empty Path and empty Query. - */ - pathWithQuery(): string | undefined; - /** - * Set the combination of the HTTP Path and Query for the Request. - * When `none`, this represents an empty Path and empty Query. Fails is the - * string given is not a syntactically valid path and query uri component. - */ - setPathWithQuery(pathWithQuery: string | undefined): void; - /** - * Get the HTTP Related Scheme for the Request. When `none`, the - * implementation may choose an appropriate default scheme. - */ - scheme(): Scheme | undefined; - /** - * Set the HTTP Related Scheme for the Request. When `none`, the - * implementation may choose an appropriate default scheme. Fails if the - * string given is not a syntactically valid uri scheme. - */ - setScheme(scheme: Scheme | undefined): void; - /** - * Get the authority of the Request's target URI. A value of `none` may be used - * with Related Schemes which do not require an authority. The HTTP and - * HTTPS schemes always require an authority. - */ - authority(): string | undefined; - /** - * Set the authority of the Request's target URI. A value of `none` may be used - * with Related Schemes which do not require an authority. The HTTP and - * HTTPS schemes always require an authority. Fails if the string given is - * not a syntactically valid URI authority. - */ - setAuthority(authority: string | undefined): void; - /** - * Get the headers associated with the Request. - * - * The returned `headers` resource is immutable: `set`, `append`, and - * `delete` operations will fail with `header-error.immutable`. - * - * This headers resource is a child: it must be dropped before the parent - * `outgoing-request` is dropped, or its ownership is transferred to - * another component by e.g. `outgoing-handler.handle`. - */ - headers(): Headers; - [Symbol.dispose]?: () => void; -} - -export class OutgoingResponse implements Partial { - /** - * Construct an `outgoing-response`, with a default `status-code` of `200`. - * If a different `status-code` is needed, it must be set via the - * `set-status-code` method. - * - * * `headers` is the HTTP Headers for the Response. - */ - constructor(headers: Headers) - /** - * Get the HTTP Status Code for the Response. - */ - statusCode(): StatusCode; - /** - * Set the HTTP Status Code for the Response. Fails if the status-code - * given is not a valid http status code. - */ - setStatusCode(statusCode: StatusCode): void; - /** - * Get the headers associated with the Request. - * - * The returned `headers` resource is immutable: `set`, `append`, and - * `delete` operations will fail with `header-error.immutable`. - * - * This headers resource is a child: it must be dropped before the parent - * `outgoing-request` is dropped, or its ownership is transferred to - * another component by e.g. `outgoing-handler.handle`. - */ - headers(): Headers; - /** - * Returns the resource corresponding to the outgoing Body for this Response. - * - * Returns success on the first call: the `outgoing-body` resource for - * this `outgoing-response` can be retrieved at most once. Subsequent - * calls will return error. - */ - body(): OutgoingBody; - [Symbol.dispose]?: () => void; -} - -export class RequestOptions implements Partial { - /** - * Construct a default `request-options` value. - */ - constructor() - /** - * The timeout for the initial connect to the HTTP Server. - */ - connectTimeout(): Duration | undefined; - /** - * Set the timeout for the initial connect to the HTTP Server. An error - * return value indicates that this timeout is not supported. - */ - setConnectTimeout(duration: Duration | undefined): void; - /** - * The timeout for receiving the first byte of the Response body. - */ - firstByteTimeout(): Duration | undefined; - /** - * Set the timeout for receiving the first byte of the Response body. An - * error return value indicates that this timeout is not supported. - */ - setFirstByteTimeout(duration: Duration | undefined): void; - /** - * The timeout for receiving subsequent chunks of bytes in the Response - * body stream. - */ - betweenBytesTimeout(): Duration | undefined; - /** - * Set the timeout for receiving subsequent chunks of bytes in the Response - * body stream. An error return value indicates that this timeout is not - * supported. - */ - setBetweenBytesTimeout(duration: Duration | undefined): void; - [Symbol.dispose]?: () => void; -} - -export class ResponseOutparam implements Partial { - /** - * This type does not have a public constructor. + * These cases are inspired by the IANA HTTP Proxy Error Types: + * */ - private constructor(); + export type ErrorCode = + | ErrorCodeDnsTimeout + | ErrorCodeDnsError + | ErrorCodeDestinationNotFound + | ErrorCodeDestinationUnavailable + | ErrorCodeDestinationIpProhibited + | ErrorCodeDestinationIpUnroutable + | ErrorCodeConnectionRefused + | ErrorCodeConnectionTerminated + | ErrorCodeConnectionTimeout + | ErrorCodeConnectionReadTimeout + | ErrorCodeConnectionWriteTimeout + | ErrorCodeConnectionLimitReached + | ErrorCodeTlsProtocolError + | ErrorCodeTlsCertificateError + | ErrorCodeTlsAlertReceived + | ErrorCodeHttpRequestDenied + | ErrorCodeHttpRequestLengthRequired + | ErrorCodeHttpRequestBodySize + | ErrorCodeHttpRequestMethodInvalid + | ErrorCodeHttpRequestUriInvalid + | ErrorCodeHttpRequestUriTooLong + | ErrorCodeHttpRequestHeaderSectionSize + | ErrorCodeHttpRequestHeaderSize + | ErrorCodeHttpRequestTrailerSectionSize + | ErrorCodeHttpRequestTrailerSize + | ErrorCodeHttpResponseIncomplete + | ErrorCodeHttpResponseHeaderSectionSize + | ErrorCodeHttpResponseHeaderSize + | ErrorCodeHttpResponseBodySize + | ErrorCodeHttpResponseTrailerSectionSize + | ErrorCodeHttpResponseTrailerSize + | ErrorCodeHttpResponseTransferCoding + | ErrorCodeHttpResponseContentCoding + | ErrorCodeHttpResponseTimeout + | ErrorCodeHttpUpgradeFailed + | ErrorCodeHttpProtocolError + | ErrorCodeLoopDetected + | ErrorCodeConfigurationError + | ErrorCodeInternalError; + export interface ErrorCodeDnsTimeout { + tag: "DNS-timeout"; + } + export interface ErrorCodeDnsError { + tag: "DNS-error"; + val: DnsErrorPayload; + } + export interface ErrorCodeDestinationNotFound { + tag: "destination-not-found"; + } + export interface ErrorCodeDestinationUnavailable { + tag: "destination-unavailable"; + } + export interface ErrorCodeDestinationIpProhibited { + tag: "destination-IP-prohibited"; + } + export interface ErrorCodeDestinationIpUnroutable { + tag: "destination-IP-unroutable"; + } + export interface ErrorCodeConnectionRefused { + tag: "connection-refused"; + } + export interface ErrorCodeConnectionTerminated { + tag: "connection-terminated"; + } + export interface ErrorCodeConnectionTimeout { + tag: "connection-timeout"; + } + export interface ErrorCodeConnectionReadTimeout { + tag: "connection-read-timeout"; + } + export interface ErrorCodeConnectionWriteTimeout { + tag: "connection-write-timeout"; + } + export interface ErrorCodeConnectionLimitReached { + tag: "connection-limit-reached"; + } + export interface ErrorCodeTlsProtocolError { + tag: "TLS-protocol-error"; + } + export interface ErrorCodeTlsCertificateError { + tag: "TLS-certificate-error"; + } + export interface ErrorCodeTlsAlertReceived { + tag: "TLS-alert-received"; + val: TlsAlertReceivedPayload; + } + export interface ErrorCodeHttpRequestDenied { + tag: "HTTP-request-denied"; + } + export interface ErrorCodeHttpRequestLengthRequired { + tag: "HTTP-request-length-required"; + } + export interface ErrorCodeHttpRequestBodySize { + tag: "HTTP-request-body-size"; + val: bigint | undefined; + } + export interface ErrorCodeHttpRequestMethodInvalid { + tag: "HTTP-request-method-invalid"; + } + export interface ErrorCodeHttpRequestUriInvalid { + tag: "HTTP-request-URI-invalid"; + } + export interface ErrorCodeHttpRequestUriTooLong { + tag: "HTTP-request-URI-too-long"; + } + export interface ErrorCodeHttpRequestHeaderSectionSize { + tag: "HTTP-request-header-section-size"; + val: number | undefined; + } + export interface ErrorCodeHttpRequestHeaderSize { + tag: "HTTP-request-header-size"; + val: FieldSizePayload | undefined; + } + export interface ErrorCodeHttpRequestTrailerSectionSize { + tag: "HTTP-request-trailer-section-size"; + val: number | undefined; + } + export interface ErrorCodeHttpRequestTrailerSize { + tag: "HTTP-request-trailer-size"; + val: FieldSizePayload; + } + export interface ErrorCodeHttpResponseIncomplete { + tag: "HTTP-response-incomplete"; + } + export interface ErrorCodeHttpResponseHeaderSectionSize { + tag: "HTTP-response-header-section-size"; + val: number | undefined; + } + export interface ErrorCodeHttpResponseHeaderSize { + tag: "HTTP-response-header-size"; + val: FieldSizePayload; + } + export interface ErrorCodeHttpResponseBodySize { + tag: "HTTP-response-body-size"; + val: bigint | undefined; + } + export interface ErrorCodeHttpResponseTrailerSectionSize { + tag: "HTTP-response-trailer-section-size"; + val: number | undefined; + } + export interface ErrorCodeHttpResponseTrailerSize { + tag: "HTTP-response-trailer-size"; + val: FieldSizePayload; + } + export interface ErrorCodeHttpResponseTransferCoding { + tag: "HTTP-response-transfer-coding"; + val: string | undefined; + } + export interface ErrorCodeHttpResponseContentCoding { + tag: "HTTP-response-content-coding"; + val: string | undefined; + } + export interface ErrorCodeHttpResponseTimeout { + tag: "HTTP-response-timeout"; + } + export interface ErrorCodeHttpUpgradeFailed { + tag: "HTTP-upgrade-failed"; + } + export interface ErrorCodeHttpProtocolError { + tag: "HTTP-protocol-error"; + } + export interface ErrorCodeLoopDetected { + tag: "loop-detected"; + } + export interface ErrorCodeConfigurationError { + tag: "configuration-error"; + } /** - * Set the value of the `response-outparam` to either send a response, - * or indicate an error. - * - * This method consumes the `response-outparam` to ensure that it is - * called at most once. If it is never called, the implementation - * will respond with an error. - * - * The user may provide an `error` to `response` to allow the - * implementation determine how to respond with an HTTP error response. - */ - static set(param: ResponseOutparam, response: Result): void; - [Symbol.dispose]?: () => void; + * This is a catch-all error for anything that doesn't fit cleanly into a + * more specific case. It also includes an optional string for an + * unstructured description of the error. Users should not depend on the + * string for diagnosing errors, as it's not required to be consistent + * between implementations. + */ + export interface ErrorCodeInternalError { + tag: "internal-error"; + val: string | undefined; + } + /** + * This type enumerates the different kinds of errors that may occur when + * setting or appending to a `fields` resource. + */ + export type HeaderError = + | HeaderErrorInvalidSyntax + | HeaderErrorForbidden + | HeaderErrorImmutable; + /** + * This error indicates that a `field-name` or `field-value` was + * syntactically invalid when used with an operation that sets headers in a + * `fields`. + */ + export interface HeaderErrorInvalidSyntax { + tag: "invalid-syntax"; + } + /** + * This error indicates that a forbidden `field-name` was used when trying + * to set a header in a `fields`. + */ + export interface HeaderErrorForbidden { + tag: "forbidden"; + } + /** + * This error indicates that the operation on the `fields` was not + * permitted because the fields are immutable. + */ + export interface HeaderErrorImmutable { + tag: "immutable"; + } + /** + * Field keys are always strings. + * + * Field keys should always be treated as case insensitive by the `fields` + * resource for the purposes of equality checking. + * + * # Deprecation + * + * This type has been deprecated in favor of the `field-name` type. + */ + export type FieldKey = string; + /** + * Field names are always strings. + * + * Field names should always be treated as case insensitive by the `fields` + * resource for the purposes of equality checking. + */ + export type FieldName = FieldKey; + /** + * Field values should always be ASCII strings. However, in + * reality, HTTP implementations often have to interpret malformed values, + * so they are provided as a list of bytes. + */ + export type FieldValue = Uint8Array; + /** + * Headers is an alias for Fields. + */ + export type Headers = Fields; + /** + * Trailers is an alias for Fields. + */ + export type Trailers = Fields; + /** + * This type corresponds to the HTTP standard Status Code. + */ + export type StatusCode = number; + export type Result = { tag: "ok"; val: T } | { tag: "err"; val: E }; + + export class Fields implements Disposable { + /** + * Construct an empty HTTP Fields. + * + * The resulting `fields` is mutable. + */ + constructor(); + /** + * Construct an HTTP Fields. + * + * The resulting `fields` is mutable. + * + * The list represents each name-value pair in the Fields. Names + * which have multiple values are represented by multiple entries in this + * list with the same name. + * + * The tuple is a pair of the field name, represented as a string, and + * Value, represented as a list of bytes. + * + * An error result will be returned if any `field-name` or `field-value` is + * syntactically invalid, or if a field is forbidden. + */ + static fromList(entries: Array<[FieldName, FieldValue]>): Fields; + /** + * Get all of the values corresponding to a name. If the name is not present + * in this `fields` or is syntactically invalid, an empty list is returned. + * However, if the name is present but empty, this is represented by a list + * with one or more empty field-values present. + */ + get(name: FieldName): Array; + /** + * Returns `true` when the name is present in this `fields`. If the name is + * syntactically invalid, `false` is returned. + */ + has(name: FieldName): boolean; + /** + * Set all of the values for a name. Clears any existing values for that + * name, if they have been set. + * + * Fails with `header-error.immutable` if the `fields` are immutable. + * + * Fails with `header-error.invalid-syntax` if the `field-name` or any of + * the `field-value`s are syntactically invalid. + */ + set(name: FieldName, value: Array): void; + /** + * Delete all values for a name. Does nothing if no values for the name + * exist. + * + * Fails with `header-error.immutable` if the `fields` are immutable. + * + * Fails with `header-error.invalid-syntax` if the `field-name` is + * syntactically invalid. + */ + delete(name: FieldName): void; + /** + * Append a value for a name. Does not change or delete any existing + * values for that name. + * + * Fails with `header-error.immutable` if the `fields` are immutable. + * + * Fails with `header-error.invalid-syntax` if the `field-name` or + * `field-value` are syntactically invalid. + */ + append(name: FieldName, value: FieldValue): void; + /** + * Retrieve the full set of names and values in the Fields. Like the + * constructor, the list represents each name-value pair. + * + * The outer list represents each name-value pair in the Fields. Names + * which have multiple values are represented by multiple entries in this + * list with the same name. + * + * The names and values are always returned in the original casing and in + * the order in which they will be serialized for transport. + */ + entries(): Array<[FieldName, FieldValue]>; + /** + * Make a deep copy of the Fields. Equivalent in behavior to calling the + * `fields` constructor on the return value of `entries`. The resulting + * `fields` is mutable. + */ + clone(): Fields; + [Symbol.dispose](): void; + } + + export class FutureIncomingResponse implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns a pollable which becomes ready when either the Response has + * been received, or an error has occurred. When this pollable is ready, + * the `get` method will return `some`. + */ + subscribe(): Pollable; + /** + * Returns the incoming HTTP Response, or an error, once one is ready. + * + * The outer `option` represents future readiness. Users can wait on this + * `option` to become `some` using the `subscribe` method. + * + * The outer `result` is used to retrieve the response or error at most + * once. It will be success on the first call in which the outer option + * is `some`, and error on subsequent calls. + * + * The inner `result` represents that either the incoming HTTP Response + * status and headers have received successfully, or that an error + * occurred. Errors may also occur while consuming the response body, + * but those will be reported by the `incoming-body` and its + * `output-stream` child. + */ + get(): Result, void> | undefined; + [Symbol.dispose](): void; + } + + export class FutureTrailers implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns a pollable which becomes ready when either the trailers have + * been received, or an error has occurred. When this pollable is ready, + * the `get` method will return `some`. + */ + subscribe(): Pollable; + /** + * Returns the contents of the trailers, or an error which occurred, + * once the future is ready. + * + * The outer `option` represents future readiness. Users can wait on this + * `option` to become `some` using the `subscribe` method. + * + * The outer `result` is used to retrieve the trailers or error at most + * once. It will be success on the first call in which the outer option + * is `some`, and error on subsequent calls. + * + * The inner `result` represents that either the HTTP Request or Response + * body, as well as any trailers, were received successfully, or that an + * error occurred receiving them. The optional `trailers` indicates whether + * or not trailers were present in the body. + * + * When some `trailers` are returned by this method, the `trailers` + * resource is immutable, and a child. Use of the `set`, `append`, or + * `delete` methods will return an error, and the resource must be + * dropped before the parent `future-trailers` is dropped. + */ + get(): Result, void> | undefined; + [Symbol.dispose](): void; + } + + export class IncomingBody implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns the contents of the body, as a stream of bytes. + * + * Returns success on first call: the stream representing the contents + * can be retrieved at most once. Subsequent calls will return error. + * + * The returned `input-stream` resource is a child: it must be dropped + * before the parent `incoming-body` is dropped, or consumed by + * `incoming-body.finish`. + * + * This invariant ensures that the implementation can determine whether + * the user is consuming the contents of the body, waiting on the + * `future-trailers` to be ready, or neither. This allows for network + * backpressure is to be applied when the user is consuming the body, + * and for that backpressure to not inhibit delivery of the trailers if + * the user does not read the entire body. + */ + stream(): InputStream; + /** + * Takes ownership of `incoming-body`, and returns a `future-trailers`. + * This function will trap if the `input-stream` child is still alive. + */ + static finish(this_: IncomingBody): FutureTrailers; + [Symbol.dispose](): void; + } + + export class IncomingRequest implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns the method of the incoming request. + */ + method(): Method; + /** + * Returns the path with query parameters from the request, as a string. + */ + pathWithQuery(): string | undefined; + /** + * Returns the protocol scheme from the request. + */ + scheme(): Scheme | undefined; + /** + * Returns the authority of the Request's target URI, if present. + */ + authority(): string | undefined; + /** + * Get the `headers` associated with the request. + * + * The returned `headers` resource is immutable: `set`, `append`, and + * `delete` operations will fail with `header-error.immutable`. + * + * The `headers` returned are a child resource: it must be dropped before + * the parent `incoming-request` is dropped. Dropping this + * `incoming-request` before all children are dropped will trap. + */ + headers(): Headers; + /** + * Gives the `incoming-body` associated with this request. Will only + * return success at most once, and subsequent calls will return error. + */ + consume(): IncomingBody; + [Symbol.dispose](): void; + } + + export class IncomingResponse implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns the status code from the incoming response. + */ + status(): StatusCode; + /** + * Returns the headers from the incoming response. + * + * The returned `headers` resource is immutable: `set`, `append`, and + * `delete` operations will fail with `header-error.immutable`. + * + * This headers resource is a child: it must be dropped before the parent + * `incoming-response` is dropped. + */ + headers(): Headers; + /** + * Returns the incoming body. May be called at most once. Returns error + * if called additional times. + */ + consume(): IncomingBody; + [Symbol.dispose](): void; + } + + export class OutgoingBody implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns a stream for writing the body contents. + * + * The returned `output-stream` is a child resource: it must be dropped + * before the parent `outgoing-body` resource is dropped (or finished), + * otherwise the `outgoing-body` drop or `finish` will trap. + * + * Returns success on the first call: the `output-stream` resource for + * this `outgoing-body` may be retrieved at most once. Subsequent calls + * will return error. + */ + write(): OutputStream; + /** + * Finalize an outgoing body, optionally providing trailers. This must be + * called to signal that the response is complete. If the `outgoing-body` + * is dropped without calling `outgoing-body.finalize`, the implementation + * should treat the body as corrupted. + * + * Fails if the body's `outgoing-request` or `outgoing-response` was + * constructed with a Content-Length header, and the contents written + * to the body (via `write`) does not match the value given in the + * Content-Length. + */ + static finish(this_: OutgoingBody, trailers: Trailers | undefined): void; + [Symbol.dispose](): void; + } + + export class OutgoingRequest implements Disposable { + /** + * Construct a new `outgoing-request` with a default `method` of `GET`, and + * `none` values for `path-with-query`, `scheme`, and `authority`. + * + * * `headers` is the HTTP Headers for the Request. + * + * It is possible to construct, or manipulate with the accessor functions + * below, an `outgoing-request` with an invalid combination of `scheme` + * and `authority`, or `headers` which are not permitted to be sent. + * It is the obligation of the `outgoing-handler.handle` implementation + * to reject invalid constructions of `outgoing-request`. + */ + constructor(headers: Headers); + /** + * Returns the resource corresponding to the outgoing Body for this + * Request. + * + * Returns success on the first call: the `outgoing-body` resource for + * this `outgoing-request` can be retrieved at most once. Subsequent + * calls will return error. + */ + body(): OutgoingBody; + /** + * Get the Method for the Request. + */ + method(): Method; + /** + * Set the Method for the Request. Fails if the string present in a + * `method.other` argument is not a syntactically valid method. + */ + setMethod(method: Method): void; + /** + * Get the combination of the HTTP Path and Query for the Request. + * When `none`, this represents an empty Path and empty Query. + */ + pathWithQuery(): string | undefined; + /** + * Set the combination of the HTTP Path and Query for the Request. + * When `none`, this represents an empty Path and empty Query. Fails is the + * string given is not a syntactically valid path and query uri component. + */ + setPathWithQuery(pathWithQuery: string | undefined): void; + /** + * Get the HTTP Related Scheme for the Request. When `none`, the + * implementation may choose an appropriate default scheme. + */ + scheme(): Scheme | undefined; + /** + * Set the HTTP Related Scheme for the Request. When `none`, the + * implementation may choose an appropriate default scheme. Fails if the + * string given is not a syntactically valid uri scheme. + */ + setScheme(scheme: Scheme | undefined): void; + /** + * Get the authority of the Request's target URI. A value of `none` may be used + * with Related Schemes which do not require an authority. The HTTP and + * HTTPS schemes always require an authority. + */ + authority(): string | undefined; + /** + * Set the authority of the Request's target URI. A value of `none` may be used + * with Related Schemes which do not require an authority. The HTTP and + * HTTPS schemes always require an authority. Fails if the string given is + * not a syntactically valid URI authority. + */ + setAuthority(authority: string | undefined): void; + /** + * Get the headers associated with the Request. + * + * The returned `headers` resource is immutable: `set`, `append`, and + * `delete` operations will fail with `header-error.immutable`. + * + * This headers resource is a child: it must be dropped before the parent + * `outgoing-request` is dropped, or its ownership is transferred to + * another component by e.g. `outgoing-handler.handle`. + */ + headers(): Headers; + [Symbol.dispose](): void; + } + + export class OutgoingResponse implements Disposable { + /** + * Construct an `outgoing-response`, with a default `status-code` of `200`. + * If a different `status-code` is needed, it must be set via the + * `set-status-code` method. + * + * * `headers` is the HTTP Headers for the Response. + */ + constructor(headers: Headers); + /** + * Get the HTTP Status Code for the Response. + */ + statusCode(): StatusCode; + /** + * Set the HTTP Status Code for the Response. Fails if the status-code + * given is not a valid http status code. + */ + setStatusCode(statusCode: StatusCode): void; + /** + * Get the headers associated with the Request. + * + * The returned `headers` resource is immutable: `set`, `append`, and + * `delete` operations will fail with `header-error.immutable`. + * + * This headers resource is a child: it must be dropped before the parent + * `outgoing-request` is dropped, or its ownership is transferred to + * another component by e.g. `outgoing-handler.handle`. + */ + headers(): Headers; + /** + * Returns the resource corresponding to the outgoing Body for this Response. + * + * Returns success on the first call: the `outgoing-body` resource for + * this `outgoing-response` can be retrieved at most once. Subsequent + * calls will return error. + */ + body(): OutgoingBody; + [Symbol.dispose](): void; + } + + export class RequestOptions implements Disposable { + /** + * Construct a default `request-options` value. + */ + constructor(); + /** + * The timeout for the initial connect to the HTTP Server. + */ + connectTimeout(): Duration | undefined; + /** + * Set the timeout for the initial connect to the HTTP Server. An error + * return value indicates that this timeout is not supported. + */ + setConnectTimeout(duration: Duration | undefined): void; + /** + * The timeout for receiving the first byte of the Response body. + */ + firstByteTimeout(): Duration | undefined; + /** + * Set the timeout for receiving the first byte of the Response body. An + * error return value indicates that this timeout is not supported. + */ + setFirstByteTimeout(duration: Duration | undefined): void; + /** + * The timeout for receiving subsequent chunks of bytes in the Response + * body stream. + */ + betweenBytesTimeout(): Duration | undefined; + /** + * Set the timeout for receiving subsequent chunks of bytes in the Response + * body stream. An error return value indicates that this timeout is not + * supported. + */ + setBetweenBytesTimeout(duration: Duration | undefined): void; + [Symbol.dispose](): void; + } + + export class ResponseOutparam implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Set the value of the `response-outparam` to either send a response, + * or indicate an error. + * + * This method consumes the `response-outparam` to ensure that it is + * called at most once. If it is never called, the implementation + * will respond with an error. + * + * The user may provide an `error` to `response` to allow the + * implementation determine how to respond with an HTTP error response. + */ + static set( + param: ResponseOutparam, + response: Result, + ): void; + [Symbol.dispose](): void; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-io-error.d.ts b/guests/typescript/generated/types/interfaces/wasi-io-error.d.ts index d1172878..7ebfd653 100644 --- a/guests/typescript/generated/types/interfaces/wasi-io-error.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-io-error.d.ts @@ -1,19 +1,19 @@ -/** @module Interface wasi:io/error@0.2.3 **/ - -export class Error implements Partial { - /** - * This type does not have a public constructor. - */ - private constructor(); - /** - * Returns a string that is suitable to assist humans in debugging - * this error. - * - * WARNING: The returned string should not be consumed mechanically! - * It may change across platforms, hosts, or other implementation - * details. Parsing this string is a major platform-compatibility - * hazard. - */ - toDebugString(): string; - [Symbol.dispose]?: () => void; +declare module "wasi:io/error@0.2.3" { + export class Error implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Returns a string that is suitable to assist humans in debugging + * this error. + * + * WARNING: The returned string should not be consumed mechanically! + * It may change across platforms, hosts, or other implementation + * details. Parsing this string is a major platform-compatibility + * hazard. + */ + toDebugString(): string; + [Symbol.dispose](): void; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-io-poll.d.ts b/guests/typescript/generated/types/interfaces/wasi-io-poll.d.ts index dae02c11..3988cb52 100644 --- a/guests/typescript/generated/types/interfaces/wasi-io-poll.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-io-poll.d.ts @@ -1,45 +1,46 @@ -/** @module Interface wasi:io/poll@0.2.3 **/ -/** - * Poll for completion on a set of pollables. - * - * This function takes a list of pollables, which identify I/O sources of - * interest, and waits until one or more of the events is ready for I/O. - * - * The result `list` contains one or more indices of handles in the - * argument list that is ready for I/O. - * - * This function traps if either: - * - the list is empty, or: - * - the list contains more elements than can be indexed with a `u32` value. - * - * A timeout can be implemented by adding a pollable from the - * wasi-clocks API to the list. - * - * This function does not return a `result`; polling in itself does not - * do any I/O so it doesn't fail. If any of the I/O sources identified by - * the pollables has an error, it is indicated by marking the source as - * being ready for I/O. - */ -export function poll(in_: Array): Uint32Array; - -export class Pollable implements Partial { +declare module "wasi:io/poll@0.2.3" { /** - * This type does not have a public constructor. + * Poll for completion on a set of pollables. + * + * This function takes a list of pollables, which identify I/O sources of + * interest, and waits until one or more of the events is ready for I/O. + * + * The result `list` contains one or more indices of handles in the + * argument list that is ready for I/O. + * + * This function traps if either: + * - the list is empty, or: + * - the list contains more elements than can be indexed with a `u32` value. + * + * A timeout can be implemented by adding a pollable from the + * wasi-clocks API to the list. + * + * This function does not return a `result`; polling in itself does not + * do any I/O so it doesn't fail. If any of the I/O sources identified by + * the pollables has an error, it is indicated by marking the source as + * being ready for I/O. */ - private constructor(); - /** - * Return the readiness of a pollable. This function never blocks. - * - * Returns `true` when the pollable is ready, and `false` otherwise. - */ - ready(): boolean; - /** - * `block` returns immediately if the pollable is ready, and otherwise - * blocks until ready. - * - * This function is equivalent to calling `poll.poll` on a list - * containing only this pollable. - */ - block(): void; - [Symbol.dispose]?: () => void; + export function poll(in_: Array): Uint32Array; + + export class Pollable implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Return the readiness of a pollable. This function never blocks. + * + * Returns `true` when the pollable is ready, and `false` otherwise. + */ + ready(): boolean; + /** + * `block` returns immediately if the pollable is ready, and otherwise + * blocks until ready. + * + * This function is equivalent to calling `poll.poll` on a list + * containing only this pollable. + */ + block(): void; + [Symbol.dispose](): void; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-io-streams.d.ts b/guests/typescript/generated/types/interfaces/wasi-io-streams.d.ts index 30f06763..0f6a9223 100644 --- a/guests/typescript/generated/types/interfaces/wasi-io-streams.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-io-streams.d.ts @@ -1,244 +1,247 @@ -/** @module Interface wasi:io/streams@0.2.3 **/ -export type Error = import('./wasi-io-error.js').Error; -export type Pollable = import('./wasi-io-poll.js').Pollable; -/** - * An error for input-stream and output-stream operations. - */ -export type StreamError = StreamErrorLastOperationFailed | StreamErrorClosed; -/** - * The last operation (a write or flush) failed before completion. - * - * More information is available in the `error` payload. - * - * After this, the stream will be closed. All future operations return - * `stream-error::closed`. - */ -export interface StreamErrorLastOperationFailed { - tag: 'last-operation-failed', - val: Error, -} -/** - * The stream is closed: no more input will be accepted by the - * stream. A closed output-stream will return this error on all - * future operations. - */ -export interface StreamErrorClosed { - tag: 'closed', -} - -export class InputStream implements Partial { +/// +/// +declare module "wasi:io/streams@0.2.3" { + export type Error = import("wasi:io/error@0.2.3").Error; + export type Pollable = import("wasi:io/poll@0.2.3").Pollable; /** - * This type does not have a public constructor. + * An error for input-stream and output-stream operations. */ - private constructor(); + export type StreamError = StreamErrorLastOperationFailed | StreamErrorClosed; /** - * Perform a non-blocking read from the stream. - * - * When the source of a `read` is binary data, the bytes from the source - * are returned verbatim. When the source of a `read` is known to the - * implementation to be text, bytes containing the UTF-8 encoding of the - * text are returned. - * - * This function returns a list of bytes containing the read data, - * when successful. The returned list will contain up to `len` bytes; - * it may return fewer than requested, but not more. The list is - * empty when no bytes are available for reading at this time. The - * pollable given by `subscribe` will be ready when more bytes are - * available. - * - * This function fails with a `stream-error` when the operation - * encounters an error, giving `last-operation-failed`, or when the - * stream is closed, giving `closed`. - * - * When the caller gives a `len` of 0, it represents a request to - * read 0 bytes. If the stream is still open, this call should - * succeed and return an empty list, or otherwise fail with `closed`. - * - * The `len` parameter is a `u64`, which could represent a list of u8 which - * is not possible to allocate in wasm32, or not desirable to allocate as - * as a return value by the callee. The callee may return a list of bytes - * less than `len` in size while more bytes are available for reading. - */ - read(len: bigint): Uint8Array; - /** - * Read bytes from a stream, after blocking until at least one byte can - * be read. Except for blocking, behavior is identical to `read`. - */ - blockingRead(len: bigint): Uint8Array; - /** - * Skip bytes from a stream. Returns number of bytes skipped. - * - * Behaves identical to `read`, except instead of returning a list - * of bytes, returns the number of bytes consumed from the stream. - */ - skip(len: bigint): bigint; - /** - * Skip bytes from a stream, after blocking until at least one byte - * can be skipped. Except for blocking behavior, identical to `skip`. - */ - blockingSkip(len: bigint): bigint; - /** - * Create a `pollable` which will resolve once either the specified stream - * has bytes available to read or the other end of the stream has been - * closed. - * The created `pollable` is a child resource of the `input-stream`. - * Implementations may trap if the `input-stream` is dropped before - * all derived `pollable`s created with this function are dropped. - */ - subscribe(): Pollable; - [Symbol.dispose]?: () => void; -} - -export class OutputStream implements Partial { - /** - * This type does not have a public constructor. + * The last operation (a write or flush) failed before completion. + * + * More information is available in the `error` payload. + * + * After this, the stream will be closed. All future operations return + * `stream-error::closed`. */ - private constructor(); + export interface StreamErrorLastOperationFailed { + tag: "last-operation-failed"; + val: Error; + } /** - * Check readiness for writing. This function never blocks. - * - * Returns the number of bytes permitted for the next call to `write`, - * or an error. Calling `write` with more bytes than this function has - * permitted will trap. - * - * When this function returns 0 bytes, the `subscribe` pollable will - * become ready when this function will report at least 1 byte, or an - * error. - */ - checkWrite(): bigint; - /** - * Perform a write. This function never blocks. - * - * When the destination of a `write` is binary data, the bytes from - * `contents` are written verbatim. When the destination of a `write` is - * known to the implementation to be text, the bytes of `contents` are - * transcoded from UTF-8 into the encoding of the destination and then - * written. - * - * Precondition: check-write gave permit of Ok(n) and contents has a - * length of less than or equal to n. Otherwise, this function will trap. - * - * returns Err(closed) without writing if the stream has closed since - * the last call to check-write provided a permit. - */ - write(contents: Uint8Array): void; - /** - * Perform a write of up to 4096 bytes, and then flush the stream. Block - * until all of these operations are complete, or an error occurs. - * - * This is a convenience wrapper around the use of `check-write`, - * `subscribe`, `write`, and `flush`, and is implemented with the - * following pseudo-code: - * - * ```text - * let pollable = this.subscribe(); - * while !contents.is_empty() { - * // Wait for the stream to become writable - * pollable.block(); - * let Ok(n) = this.check-write(); // eliding error handling - * let len = min(n, contents.len()); - * let (chunk, rest) = contents.split_at(len); - * this.write(chunk ); // eliding error handling - * contents = rest; - * } - * this.flush(); - * // Wait for completion of `flush` - * pollable.block(); - * // Check for any errors that arose during `flush` - * let _ = this.check-write(); // eliding error handling - * ``` - */ + * The stream is closed: no more input will be accepted by the + * stream. A closed output-stream will return this error on all + * future operations. + */ + export interface StreamErrorClosed { + tag: "closed"; + } + + export class InputStream implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Perform a non-blocking read from the stream. + * + * When the source of a `read` is binary data, the bytes from the source + * are returned verbatim. When the source of a `read` is known to the + * implementation to be text, bytes containing the UTF-8 encoding of the + * text are returned. + * + * This function returns a list of bytes containing the read data, + * when successful. The returned list will contain up to `len` bytes; + * it may return fewer than requested, but not more. The list is + * empty when no bytes are available for reading at this time. The + * pollable given by `subscribe` will be ready when more bytes are + * available. + * + * This function fails with a `stream-error` when the operation + * encounters an error, giving `last-operation-failed`, or when the + * stream is closed, giving `closed`. + * + * When the caller gives a `len` of 0, it represents a request to + * read 0 bytes. If the stream is still open, this call should + * succeed and return an empty list, or otherwise fail with `closed`. + * + * The `len` parameter is a `u64`, which could represent a list of u8 which + * is not possible to allocate in wasm32, or not desirable to allocate as + * as a return value by the callee. The callee may return a list of bytes + * less than `len` in size while more bytes are available for reading. + */ + read(len: bigint): Uint8Array; + /** + * Read bytes from a stream, after blocking until at least one byte can + * be read. Except for blocking, behavior is identical to `read`. + */ + blockingRead(len: bigint): Uint8Array; + /** + * Skip bytes from a stream. Returns number of bytes skipped. + * + * Behaves identical to `read`, except instead of returning a list + * of bytes, returns the number of bytes consumed from the stream. + */ + skip(len: bigint): bigint; + /** + * Skip bytes from a stream, after blocking until at least one byte + * can be skipped. Except for blocking behavior, identical to `skip`. + */ + blockingSkip(len: bigint): bigint; + /** + * Create a `pollable` which will resolve once either the specified stream + * has bytes available to read or the other end of the stream has been + * closed. + * The created `pollable` is a child resource of the `input-stream`. + * Implementations may trap if the `input-stream` is dropped before + * all derived `pollable`s created with this function are dropped. + */ + subscribe(): Pollable; + [Symbol.dispose](): void; + } + + export class OutputStream implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Check readiness for writing. This function never blocks. + * + * Returns the number of bytes permitted for the next call to `write`, + * or an error. Calling `write` with more bytes than this function has + * permitted will trap. + * + * When this function returns 0 bytes, the `subscribe` pollable will + * become ready when this function will report at least 1 byte, or an + * error. + */ + checkWrite(): bigint; + /** + * Perform a write. This function never blocks. + * + * When the destination of a `write` is binary data, the bytes from + * `contents` are written verbatim. When the destination of a `write` is + * known to the implementation to be text, the bytes of `contents` are + * transcoded from UTF-8 into the encoding of the destination and then + * written. + * + * Precondition: check-write gave permit of Ok(n) and contents has a + * length of less than or equal to n. Otherwise, this function will trap. + * + * returns Err(closed) without writing if the stream has closed since + * the last call to check-write provided a permit. + */ + write(contents: Uint8Array): void; + /** + * Perform a write of up to 4096 bytes, and then flush the stream. Block + * until all of these operations are complete, or an error occurs. + * + * This is a convenience wrapper around the use of `check-write`, + * `subscribe`, `write`, and `flush`, and is implemented with the + * following pseudo-code: + * + * ```text + * let pollable = this.subscribe(); + * while !contents.is_empty() { + * // Wait for the stream to become writable + * pollable.block(); + * let Ok(n) = this.check-write(); // eliding error handling + * let len = min(n, contents.len()); + * let (chunk, rest) = contents.split_at(len); + * this.write(chunk ); // eliding error handling + * contents = rest; + * } + * this.flush(); + * // Wait for completion of `flush` + * pollable.block(); + * // Check for any errors that arose during `flush` + * let _ = this.check-write(); // eliding error handling + * ``` + */ blockingWriteAndFlush(contents: Uint8Array): void; /** - * Request to flush buffered output. This function never blocks. - * - * This tells the output-stream that the caller intends any buffered - * output to be flushed. the output which is expected to be flushed - * is all that has been passed to `write` prior to this call. - * - * Upon calling this function, the `output-stream` will not accept any - * writes (`check-write` will return `ok(0)`) until the flush has - * completed. The `subscribe` pollable will become ready when the - * flush has completed and the stream can accept more writes. - */ + * Request to flush buffered output. This function never blocks. + * + * This tells the output-stream that the caller intends any buffered + * output to be flushed. the output which is expected to be flushed + * is all that has been passed to `write` prior to this call. + * + * Upon calling this function, the `output-stream` will not accept any + * writes (`check-write` will return `ok(0)`) until the flush has + * completed. The `subscribe` pollable will become ready when the + * flush has completed and the stream can accept more writes. + */ flush(): void; /** - * Request to flush buffered output, and block until flush completes - * and stream is ready for writing again. - */ + * Request to flush buffered output, and block until flush completes + * and stream is ready for writing again. + */ blockingFlush(): void; /** - * Create a `pollable` which will resolve once the output-stream - * is ready for more writing, or an error has occurred. When this - * pollable is ready, `check-write` will return `ok(n)` with n>0, or an - * error. - * - * If the stream is closed, this pollable is always ready immediately. - * - * The created `pollable` is a child resource of the `output-stream`. - * Implementations may trap if the `output-stream` is dropped before - * all derived `pollable`s created with this function are dropped. - */ + * Create a `pollable` which will resolve once the output-stream + * is ready for more writing, or an error has occurred. When this + * pollable is ready, `check-write` will return `ok(n)` with n>0, or an + * error. + * + * If the stream is closed, this pollable is always ready immediately. + * + * The created `pollable` is a child resource of the `output-stream`. + * Implementations may trap if the `output-stream` is dropped before + * all derived `pollable`s created with this function are dropped. + */ subscribe(): Pollable; /** - * Write zeroes to a stream. - * - * This should be used precisely like `write` with the exact same - * preconditions (must use check-write first), but instead of - * passing a list of bytes, you simply pass the number of zero-bytes - * that should be written. - */ + * Write zeroes to a stream. + * + * This should be used precisely like `write` with the exact same + * preconditions (must use check-write first), but instead of + * passing a list of bytes, you simply pass the number of zero-bytes + * that should be written. + */ writeZeroes(len: bigint): void; /** - * Perform a write of up to 4096 zeroes, and then flush the stream. - * Block until all of these operations are complete, or an error - * occurs. - * - * This is a convenience wrapper around the use of `check-write`, - * `subscribe`, `write-zeroes`, and `flush`, and is implemented with - * the following pseudo-code: - * - * ```text - * let pollable = this.subscribe(); - * while num_zeroes != 0 { - * // Wait for the stream to become writable - * pollable.block(); - * let Ok(n) = this.check-write(); // eliding error handling - * let len = min(n, num_zeroes); - * this.write-zeroes(len); // eliding error handling - * num_zeroes -= len; - * } - * this.flush(); - * // Wait for completion of `flush` - * pollable.block(); - * // Check for any errors that arose during `flush` - * let _ = this.check-write(); // eliding error handling - * ``` - */ - blockingWriteZeroesAndFlush(len: bigint): void; - /** - * Read from one stream and write to another. - * - * The behavior of splice is equivalent to: - * 1. calling `check-write` on the `output-stream` - * 2. calling `read` on the `input-stream` with the smaller of the - * `check-write` permitted length and the `len` provided to `splice` - * 3. calling `write` on the `output-stream` with that read data. - * - * Any error reported by the call to `check-write`, `read`, or - * `write` ends the splice and reports that error. - * - * This function returns the number of bytes transferred; it may be less - * than `len`. - */ - splice(src: InputStream, len: bigint): bigint; - /** - * Read from one stream and write to another, with blocking. - * - * This is similar to `splice`, except that it blocks until the - * `output-stream` is ready for writing, and the `input-stream` - * is ready for reading, before performing the `splice`. - */ - blockingSplice(src: InputStream, len: bigint): bigint; - [Symbol.dispose]?: () => void; - } + * Perform a write of up to 4096 zeroes, and then flush the stream. + * Block until all of these operations are complete, or an error + * occurs. + * + * This is a convenience wrapper around the use of `check-write`, + * `subscribe`, `write-zeroes`, and `flush`, and is implemented with + * the following pseudo-code: + * + * ```text + * let pollable = this.subscribe(); + * while num_zeroes != 0 { + * // Wait for the stream to become writable + * pollable.block(); + * let Ok(n) = this.check-write(); // eliding error handling + * let len = min(n, num_zeroes); + * this.write-zeroes(len); // eliding error handling + * num_zeroes -= len; + * } + * this.flush(); + * // Wait for completion of `flush` + * pollable.block(); + * // Check for any errors that arose during `flush` + * let _ = this.check-write(); // eliding error handling + * ``` + */ + blockingWriteZeroesAndFlush(len: bigint): void; + /** + * Read from one stream and write to another. + * + * The behavior of splice is equivalent to: + * 1. calling `check-write` on the `output-stream` + * 2. calling `read` on the `input-stream` with the smaller of the + * `check-write` permitted length and the `len` provided to `splice` + * 3. calling `write` on the `output-stream` with that read data. + * + * Any error reported by the call to `check-write`, `read`, or + * `write` ends the splice and reports that error. + * + * This function returns the number of bytes transferred; it may be less + * than `len`. + */ + splice(src: InputStream, len: bigint): bigint; + /** + * Read from one stream and write to another, with blocking. + * + * This is similar to `splice`, except that it blocks until the + * `output-stream` is ready for writing, and the `input-stream` + * is ready for reading, before performing the `splice`. + */ + blockingSplice(src: InputStream, len: bigint): bigint; + [Symbol.dispose](): void; + } +} diff --git a/guests/typescript/generated/types/interfaces/wasi-keyvalue-atomics.d.ts b/guests/typescript/generated/types/interfaces/wasi-keyvalue-atomics.d.ts index 2f2a45fa..9c23f251 100644 --- a/guests/typescript/generated/types/interfaces/wasi-keyvalue-atomics.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-keyvalue-atomics.d.ts @@ -1,13 +1,15 @@ -/** @module Interface wasi:keyvalue/atomics@0.2.0-draft **/ -/** - * Atomically increment the value associated with the key in the store by the given delta. It - * returns the new value. - * - * If the key does not exist in the store, it creates a new key-value pair with the value set - * to the given delta. - * - * If any other error occurs, it returns an `Err(error)`. - */ -export function increment(bucket: Bucket, key: string, delta: bigint): bigint; -export type Bucket = import('./wasi-keyvalue-store.js').Bucket; -export type Error = import('./wasi-keyvalue-store.js').Error; +/// +declare module "wasi:keyvalue/atomics@0.2.0-draft" { + /** + * Atomically increment the value associated with the key in the store by the given delta. It + * returns the new value. + * + * If the key does not exist in the store, it creates a new key-value pair with the value set + * to the given delta. + * + * If any other error occurs, it returns an `Err(error)`. + */ + export function increment(bucket: Bucket, key: string, delta: bigint): bigint; + export type Bucket = import("wasi:keyvalue/store@0.2.0-draft").Bucket; + export type Error = import("wasi:keyvalue/store@0.2.0-draft").Error; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-keyvalue-batch.d.ts b/guests/typescript/generated/types/interfaces/wasi-keyvalue-batch.d.ts index 451c1643..bc101c68 100644 --- a/guests/typescript/generated/types/interfaces/wasi-keyvalue-batch.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-keyvalue-batch.d.ts @@ -1,47 +1,55 @@ -/** @module Interface wasi:keyvalue/batch@0.2.0-draft **/ -/** - * Get the key-value pairs associated with the keys in the store. It returns a list of - * key-value pairs. - * - * If any of the keys do not exist in the store, it returns a `none` value for that pair in the - * list. - * - * MAY show an out-of-date value if there are concurrent writes to the store. - * - * If any other error occurs, it returns an `Err(error)`. - */ -export function getMany(bucket: Bucket, keys: Array): Array<[string, Uint8Array] | undefined>; -/** - * Set the values associated with the keys in the store. If the key already exists in the - * store, it overwrites the value. - * - * Note that the key-value pairs are not guaranteed to be set in the order they are provided. - * - * If any of the keys do not exist in the store, it creates a new key-value pair. - * - * If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not - * rollback the key-value pairs that were already set. Thus, this batch operation does not - * guarantee atomicity, implying that some key-value pairs could be set while others might - * fail. - * - * Other concurrent operations may also be able to see the partial results. - */ -export function setMany(bucket: Bucket, keyValues: Array<[string, Uint8Array]>): void; -/** - * Delete the key-value pairs associated with the keys in the store. - * - * Note that the key-value pairs are not guaranteed to be deleted in the order they are - * provided. - * - * If any of the keys do not exist in the store, it skips the key. - * - * If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not - * rollback the key-value pairs that were already deleted. Thus, this batch operation does not - * guarantee atomicity, implying that some key-value pairs could be deleted while others might - * fail. - * - * Other concurrent operations may also be able to see the partial results. - */ -export function deleteMany(bucket: Bucket, keys: Array): void; -export type Bucket = import('./wasi-keyvalue-store.js').Bucket; -export type Error = import('./wasi-keyvalue-store.js').Error; +/// +declare module "wasi:keyvalue/batch@0.2.0-draft" { + /** + * Get the key-value pairs associated with the keys in the store. It returns a list of + * key-value pairs. + * + * If any of the keys do not exist in the store, it returns a `none` value for that pair in the + * list. + * + * MAY show an out-of-date value if there are concurrent writes to the store. + * + * If any other error occurs, it returns an `Err(error)`. + */ + export function getMany( + bucket: Bucket, + keys: Array, + ): Array<[string, Uint8Array] | undefined>; + /** + * Set the values associated with the keys in the store. If the key already exists in the + * store, it overwrites the value. + * + * Note that the key-value pairs are not guaranteed to be set in the order they are provided. + * + * If any of the keys do not exist in the store, it creates a new key-value pair. + * + * If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not + * rollback the key-value pairs that were already set. Thus, this batch operation does not + * guarantee atomicity, implying that some key-value pairs could be set while others might + * fail. + * + * Other concurrent operations may also be able to see the partial results. + */ + export function setMany( + bucket: Bucket, + keyValues: Array<[string, Uint8Array]>, + ): void; + /** + * Delete the key-value pairs associated with the keys in the store. + * + * Note that the key-value pairs are not guaranteed to be deleted in the order they are + * provided. + * + * If any of the keys do not exist in the store, it skips the key. + * + * If any other error occurs, it returns an `Err(error)`. When an error occurs, it does not + * rollback the key-value pairs that were already deleted. Thus, this batch operation does not + * guarantee atomicity, implying that some key-value pairs could be deleted while others might + * fail. + * + * Other concurrent operations may also be able to see the partial results. + */ + export function deleteMany(bucket: Bucket, keys: Array): void; + export type Bucket = import("wasi:keyvalue/store@0.2.0-draft").Bucket; + export type Error = import("wasi:keyvalue/store@0.2.0-draft").Error; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-keyvalue-store.d.ts b/guests/typescript/generated/types/interfaces/wasi-keyvalue-store.d.ts index bada7e1c..633eb866 100644 --- a/guests/typescript/generated/types/interfaces/wasi-keyvalue-store.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-keyvalue-store.d.ts @@ -1,110 +1,111 @@ -/** @module Interface wasi:keyvalue/store@0.2.0-draft **/ -/** - * Get the bucket with the specified identifier. - * - * `identifier` must refer to a bucket provided by the host. - * - * `error::no-such-store` will be raised if the `identifier` is not recognized. - */ -export function open(identifier: string): Bucket; -/** - * The set of errors which may be raised by functions in this package - */ -export type Error = ErrorNoSuchStore | ErrorAccessDenied | ErrorOther; -/** - * The host does not recognize the store identifier requested. - */ -export interface ErrorNoSuchStore { - tag: 'no-such-store', -} -/** - * The requesting component does not have access to the specified store - * (which may or may not exist). - */ -export interface ErrorAccessDenied { - tag: 'access-denied', -} -/** - * Some implementation-specific error has occurred (e.g. I/O) - */ -export interface ErrorOther { - tag: 'other', - val: string, -} -/** - * A response to a `list-keys` operation. - */ -export interface KeyResponse { +declare module "wasi:keyvalue/store@0.2.0-draft" { /** - * The list of keys returned by the query. + * Get the bucket with the specified identifier. + * + * `identifier` must refer to a bucket provided by the host. + * + * `error::no-such-store` will be raised if the `identifier` is not recognized. */ - keys: Array, + export function open(identifier: string): Bucket; /** - * The continuation token to use to fetch the next page of keys. If this is `null`, then - * there are no more keys to fetch. + * The set of errors which may be raised by functions in this package */ - cursor?: bigint, -} + export type Error = ErrorNoSuchStore | ErrorAccessDenied | ErrorOther; + /** + * The host does not recognize the store identifier requested. + */ + export interface ErrorNoSuchStore { + tag: "no-such-store"; + } + /** + * The requesting component does not have access to the specified store + * (which may or may not exist). + */ + export interface ErrorAccessDenied { + tag: "access-denied"; + } + /** + * Some implementation-specific error has occurred (e.g. I/O) + */ + export interface ErrorOther { + tag: "other"; + val: string; + } + /** + * A response to a `list-keys` operation. + */ + export interface KeyResponse { + /** + * The list of keys returned by the query. + */ + keys: Array; + /** + * The continuation token to use to fetch the next page of keys. If this is `null`, then + * there are no more keys to fetch. + */ + cursor?: bigint; + } -export class Bucket implements Partial { - /** - * This type does not have a public constructor. - */ - private constructor(); - /** - * Get the value associated with the specified `key` - * - * The value is returned as an option. If the key-value pair exists in the - * store, it returns `Ok(value)`. If the key does not exist in the - * store, it returns `Ok(none)`. - * - * If any other error occurs, it returns an `Err(error)`. - */ - get(key: string): Uint8Array | undefined; - /** - * Set the value associated with the key in the store. If the key already - * exists in the store, it overwrites the value. - * - * If the key does not exist in the store, it creates a new key-value pair. - * - * If any other error occurs, it returns an `Err(error)`. - */ - set(key: string, value: Uint8Array): void; - /** - * Delete the key-value pair associated with the key in the store. - * - * If the key does not exist in the store, it does nothing. - * - * If any other error occurs, it returns an `Err(error)`. - */ - 'delete'(key: string): void; - /** - * Check if the key exists in the store. - * - * If the key exists in the store, it returns `Ok(true)`. If the key does - * not exist in the store, it returns `Ok(false)`. - * - * If any other error occurs, it returns an `Err(error)`. - */ - exists(key: string): boolean; - /** - * Get all the keys in the store with an optional cursor (for use in pagination). It - * returns a list of keys. Please note that for most KeyValue implementations, this is a - * can be a very expensive operation and so it should be used judiciously. Implementations - * can return any number of keys in a single response, but they should never attempt to - * send more data than is reasonable (i.e. on a small edge device, this may only be a few - * KB, while on a large machine this could be several MB). Any response should also return - * a cursor that can be used to fetch the next page of keys. See the `key-response` record - * for more information. - * - * Note that the keys are not guaranteed to be returned in any particular order. - * - * If the store is empty, it returns an empty list. - * - * MAY show an out-of-date list of keys if there are concurrent writes to the store. - * - * If any error occurs, it returns an `Err(error)`. - */ - listKeys(cursor: bigint | undefined): KeyResponse; - [Symbol.dispose]?: () => void; + export class Bucket implements Disposable { + /** + * This type does not have a public constructor. + */ + private constructor(); + /** + * Get the value associated with the specified `key` + * + * The value is returned as an option. If the key-value pair exists in the + * store, it returns `Ok(value)`. If the key does not exist in the + * store, it returns `Ok(none)`. + * + * If any other error occurs, it returns an `Err(error)`. + */ + get(key: string): Uint8Array | undefined; + /** + * Set the value associated with the key in the store. If the key already + * exists in the store, it overwrites the value. + * + * If the key does not exist in the store, it creates a new key-value pair. + * + * If any other error occurs, it returns an `Err(error)`. + */ + set(key: string, value: Uint8Array): void; + /** + * Delete the key-value pair associated with the key in the store. + * + * If the key does not exist in the store, it does nothing. + * + * If any other error occurs, it returns an `Err(error)`. + */ + delete(key: string): void; + /** + * Check if the key exists in the store. + * + * If the key exists in the store, it returns `Ok(true)`. If the key does + * not exist in the store, it returns `Ok(false)`. + * + * If any other error occurs, it returns an `Err(error)`. + */ + exists(key: string): boolean; + /** + * Get all the keys in the store with an optional cursor (for use in pagination). It + * returns a list of keys. Please note that for most KeyValue implementations, this is a + * can be a very expensive operation and so it should be used judiciously. Implementations + * can return any number of keys in a single response, but they should never attempt to + * send more data than is reasonable (i.e. on a small edge device, this may only be a few + * KB, while on a large machine this could be several MB). Any response should also return + * a cursor that can be used to fetch the next page of keys. See the `key-response` record + * for more information. + * + * Note that the keys are not guaranteed to be returned in any particular order. + * + * If the store is empty, it returns an empty list. + * + * MAY show an out-of-date list of keys if there are concurrent writes to the store. + * + * If any error occurs, it returns an `Err(error)`. + */ + listKeys(cursor: bigint | undefined): KeyResponse; + [Symbol.dispose](): void; + } } diff --git a/guests/typescript/generated/types/interfaces/wasi-random-insecure-seed.d.ts b/guests/typescript/generated/types/interfaces/wasi-random-insecure-seed.d.ts index 9bc8b23e..87d60389 100644 --- a/guests/typescript/generated/types/interfaces/wasi-random-insecure-seed.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-random-insecure-seed.d.ts @@ -1,21 +1,22 @@ -/** @module Interface wasi:random/insecure-seed@0.2.3 **/ -/** - * Return a 128-bit value that may contain a pseudo-random value. - * - * The returned value is not required to be computed from a CSPRNG, and may - * even be entirely deterministic. Host implementations are encouraged to - * provide pseudo-random values to any program exposed to - * attacker-controlled content, to enable DoS protection built into many - * languages' hash-map implementations. - * - * This function is intended to only be called once, by a source language - * to initialize Denial Of Service (DoS) protection in its hash-map - * implementation. - * - * # Expected future evolution - * - * This will likely be changed to a value import, to prevent it from being - * called multiple times and potentially used for purposes other than DoS - * protection. - */ -export function insecureSeed(): [bigint, bigint]; +declare module "wasi:random/insecure-seed@0.2.3" { + /** + * Return a 128-bit value that may contain a pseudo-random value. + * + * The returned value is not required to be computed from a CSPRNG, and may + * even be entirely deterministic. Host implementations are encouraged to + * provide pseudo-random values to any program exposed to + * attacker-controlled content, to enable DoS protection built into many + * languages' hash-map implementations. + * + * This function is intended to only be called once, by a source language + * to initialize Denial Of Service (DoS) protection in its hash-map + * implementation. + * + * # Expected future evolution + * + * This will likely be changed to a value import, to prevent it from being + * called multiple times and potentially used for purposes other than DoS + * protection. + */ + export function insecureSeed(): [bigint, bigint]; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-random-insecure.d.ts b/guests/typescript/generated/types/interfaces/wasi-random-insecure.d.ts index 4e93ae0f..19b25e1c 100644 --- a/guests/typescript/generated/types/interfaces/wasi-random-insecure.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-random-insecure.d.ts @@ -1,19 +1,20 @@ -/** @module Interface wasi:random/insecure@0.2.3 **/ -/** - * Return `len` insecure pseudo-random bytes. - * - * This function is not cryptographically secure. Do not use it for - * anything related to security. - * - * There are no requirements on the values of the returned bytes, however - * implementations are encouraged to return evenly distributed values with - * a long period. - */ -export function getInsecureRandomBytes(len: bigint): Uint8Array; -/** - * Return an insecure pseudo-random `u64` value. - * - * This function returns the same type of pseudo-random data as - * `get-insecure-random-bytes`, represented as a `u64`. - */ -export function getInsecureRandomU64(): bigint; +declare module "wasi:random/insecure@0.2.3" { + /** + * Return `len` insecure pseudo-random bytes. + * + * This function is not cryptographically secure. Do not use it for + * anything related to security. + * + * There are no requirements on the values of the returned bytes, however + * implementations are encouraged to return evenly distributed values with + * a long period. + */ + export function getInsecureRandomBytes(len: bigint): Uint8Array; + /** + * Return an insecure pseudo-random `u64` value. + * + * This function returns the same type of pseudo-random data as + * `get-insecure-random-bytes`, represented as a `u64`. + */ + export function getInsecureRandomU64(): bigint; +} diff --git a/guests/typescript/generated/types/interfaces/wasi-random-random.d.ts b/guests/typescript/generated/types/interfaces/wasi-random-random.d.ts index f62bdeef..7bf75612 100644 --- a/guests/typescript/generated/types/interfaces/wasi-random-random.d.ts +++ b/guests/typescript/generated/types/interfaces/wasi-random-random.d.ts @@ -1,23 +1,24 @@ -/** @module Interface wasi:random/random@0.2.3 **/ -/** - * Return `len` cryptographically-secure random or pseudo-random bytes. - * - * This function must produce data at least as cryptographically secure and - * fast as an adequately seeded cryptographically-secure pseudo-random - * number generator (CSPRNG). It must not block, from the perspective of - * the calling program, under any circumstances, including on the first - * request and on requests for numbers of bytes. The returned data must - * always be unpredictable. - * - * This function must always return fresh data. Deterministic environments - * must omit this function, rather than implementing it with deterministic - * data. - */ -export function getRandomBytes(len: bigint): Uint8Array; -/** - * Return a cryptographically-secure random or pseudo-random `u64` value. - * - * This function returns the same type of data as `get-random-bytes`, - * represented as a `u64`. - */ -export function getRandomU64(): bigint; +declare module "wasi:random/random@0.2.3" { + /** + * Return `len` cryptographically-secure random or pseudo-random bytes. + * + * This function must produce data at least as cryptographically secure and + * fast as an adequately seeded cryptographically-secure pseudo-random + * number generator (CSPRNG). It must not block, from the perspective of + * the calling program, under any circumstances, including on the first + * request and on requests for numbers of bytes. The returned data must + * always be unpredictable. + * + * This function must always return fresh data. Deterministic environments + * must omit this function, rather than implementing it with deterministic + * data. + */ + export function getRandomBytes(len: bigint): Uint8Array; + /** + * Return a cryptographically-secure random or pseudo-random `u64` value. + * + * This function returns the same type of data as `get-random-bytes`, + * represented as a `u64`. + */ + export function getRandomU64(): bigint; +} diff --git a/guests/typescript/package.json b/guests/typescript/package.json index cabbaed1..1139e08f 100644 --- a/guests/typescript/package.json +++ b/guests/typescript/package.json @@ -74,7 +74,7 @@ "build": "vite build", "check": "tsc --noEmit --skipLibCheck && vite build && eslint", "format": "prettier -w src tests", - "generate:types": "jco types -n trailbase:component/interfaces wit/ -o generated/types", + "generate:types": "jco guest-types -n trailbase:component/interfaces wit/ -o generated/types && prettier -w generated/types", "prepack": "rm -rf ./dist && pnpm build && test -e ./dist/index.js", "test": "vitest run" }, diff --git a/guests/typescript/tsconfig.json b/guests/typescript/tsconfig.json index 49abbb75..043d1d29 100644 --- a/guests/typescript/tsconfig.json +++ b/guests/typescript/tsconfig.json @@ -28,13 +28,13 @@ "wasi:keyvalue/store@0.2.0-draft": [ "./generated/types/interfaces/wasi-keyvalue-store.d.ts", ], - "trailbase:database/sqlite": [ + "trailbase:database/sqlite@0.1.0": [ "./generated/types/interfaces/trailbase-database-sqlite.d.ts" ], - "trailbase:component/init-endpoint": [ + "trailbase:component/init-endpoint@0.1.0": [ "./generated/types/interfaces/trailbase-component-init-endpoint.d.ts" ], - "trailbase:component/sqlite-function-endpoint": [ + "trailbase:component/sqlite-function-endpoint@0.1.0": [ "./generated/types/interfaces/trailbase-component-sqlite-function-endpoint.d.ts" ] } diff --git a/guests/typescript/vite.config.ts b/guests/typescript/vite.config.ts index 57df4a68..a59edc94 100644 --- a/guests/typescript/vite.config.ts +++ b/guests/typescript/vite.config.ts @@ -11,11 +11,6 @@ const entryPoints = { "kv": resolve(__dirname, 'src/kv/index.ts'), }; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function external(source: string, _importer: string | undefined, _isResolved: boolean): boolean { - return source.startsWith("wasi:") || source.startsWith("trailbase:"); -} - export default defineConfig({ build: { outDir: "./dist", @@ -44,7 +39,10 @@ export default defineConfig({ output: { entryFileNames: "[name].js", }, - external: external, + external: [ + /^wasi:.*/, + /^trailbase:.*/, + ], }, }, });