@ricsam/quickjs-test-utils 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,45 +1,99 @@
1
1
  # @ricsam/quickjs-test-utils
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
4
-
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
-
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
-
9
- ## Purpose
10
-
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@ricsam/quickjs-test-utils`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
-
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
3
+ Testing utilities including type checking for QuickJS user code.
4
+
5
+ ```bash
6
+ bun add @ricsam/quickjs-test-utils
7
+ ```
8
+
9
+ #### Type Checking QuickJS Code
10
+
11
+ Validate TypeScript/JavaScript code that will run inside QuickJS before execution using `ts-morph`:
12
+
13
+ ```typescript
14
+ import { typecheckQuickJSCode } from "@ricsam/quickjs-test-utils";
15
+
16
+ const result = typecheckQuickJSCode(`
17
+ serve({
18
+ fetch(request, server) {
19
+ const url = new URL(request.url);
20
+
21
+ if (url.pathname === "/ws") {
22
+ server.upgrade(request, { data: { userId: 123 } });
23
+ return new Response(null, { status: 101 });
24
+ }
25
+
26
+ return Response.json({ message: "Hello!" });
27
+ },
28
+ websocket: {
29
+ message(ws, message) {
30
+ ws.send("Echo: " + message);
31
+ }
32
+ }
33
+ });
34
+ `, { include: ["core", "fetch"] });
35
+
36
+ if (!result.success) {
37
+ console.error("Type errors found:");
38
+ for (const error of result.errors) {
39
+ console.error(` Line ${error.line}: ${error.message}`);
40
+ }
41
+ }
42
+ ```
43
+
44
+ **Options:**
45
+
46
+ | Option | Description |
47
+ |--------|-------------|
48
+ | `include` | Which package types to include: `"core"`, `"fetch"`, `"fs"` (default: all) |
49
+ | `compilerOptions` | Additional TypeScript compiler options |
50
+
51
+ **Using with tests:**
52
+
53
+ ```typescript
54
+ import { describe, expect, test } from "bun:test";
55
+ import { typecheckQuickJSCode } from "@ricsam/quickjs-test-utils";
56
+
57
+ describe("QuickJS code validation", () => {
58
+ test("server code is type-safe", () => {
59
+ const result = typecheckQuickJSCode(userProvidedCode, {
60
+ include: ["fetch"]
61
+ });
62
+ expect(result.success).toBe(true);
63
+ });
64
+ });
65
+ ```
66
+
67
+ #### Type Definition Strings
68
+
69
+ The type definitions are also exported as strings for custom use cases:
70
+
71
+ ```typescript
72
+ import {
73
+ CORE_TYPES, // ReadableStream, Blob, File, URL, etc.
74
+ FETCH_TYPES, // fetch, Request, Response, serve, etc.
75
+ FS_TYPES, // fs.getDirectory, FileSystemHandle, etc.
76
+ TYPE_DEFINITIONS // All types as { core, fetch, fs }
77
+ } from "@ricsam/quickjs-test-utils";
78
+
79
+ // Use with your own ts-morph project
80
+ project.createSourceFile("quickjs-globals.d.ts", FETCH_TYPES);
81
+ ```
82
+
83
+ #### Type Definition Files
84
+
85
+ Each package also exports `.d.ts` files for use with `tsconfig.json`:
86
+
87
+ ```json
88
+ {
89
+ "compilerOptions": {
90
+ "lib": ["ESNext", "DOM"]
91
+ },
92
+ "include": ["quickjs-code/**/*.ts"],
93
+ "references": [
94
+ { "path": "./node_modules/@ricsam/quickjs-core/src/quickjs.d.ts" },
95
+ { "path": "./node_modules/@ricsam/quickjs-fetch/src/quickjs.d.ts" },
96
+ { "path": "./node_modules/@ricsam/quickjs-fs/src/quickjs.d.ts" }
97
+ ]
98
+ }
99
+ ```
@@ -0,0 +1,58 @@
1
+ // @bun @bun-cjs
2
+ (function(exports, require, module, __filename, __dirname) {var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __moduleCache = /* @__PURE__ */ new WeakMap;
7
+ var __toCommonJS = (from) => {
8
+ var entry = __moduleCache.get(from), desc;
9
+ if (entry)
10
+ return entry;
11
+ entry = __defProp({}, "__esModule", { value: true });
12
+ if (from && typeof from === "object" || typeof from === "function")
13
+ __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ }));
17
+ __moduleCache.set(from, entry);
18
+ return entry;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true,
25
+ configurable: true,
26
+ set: (newValue) => all[name] = () => newValue
27
+ });
28
+ };
29
+
30
+ // packages/test-utils/src/index.ts
31
+ var exports_src = {};
32
+ __export(exports_src, {
33
+ useTestContext: () => import_context.useTestContext,
34
+ useFetchTestContext: () => import_fetch_context.useFetchTestContext,
35
+ typecheckQuickJSCode: () => import_typecheck.typecheckQuickJSCode,
36
+ startIntegrationServer: () => import_integration_server.startIntegrationServer,
37
+ formatTypecheckErrors: () => import_typecheck.formatTypecheckErrors,
38
+ evalCodeAsync: () => import_eval.evalCodeAsync,
39
+ evalCode: () => import_eval.evalCode,
40
+ disposeTestContext: () => import_context.disposeTestContext,
41
+ disposeFetchTestContext: () => import_fetch_context.disposeFetchTestContext,
42
+ createTestContext: () => import_context.createTestContext,
43
+ createFetchTestContext: () => import_fetch_context.createFetchTestContext,
44
+ TYPE_DEFINITIONS: () => import_quickjs_types.TYPE_DEFINITIONS,
45
+ FS_TYPES: () => import_quickjs_types.FS_TYPES,
46
+ FETCH_TYPES: () => import_quickjs_types.FETCH_TYPES,
47
+ CORE_TYPES: () => import_quickjs_types.CORE_TYPES
48
+ });
49
+ module.exports = __toCommonJS(exports_src);
50
+ var import_context = require("./context.ts");
51
+ var import_fetch_context = require("./fetch-context.ts");
52
+ var import_eval = require("./eval.ts");
53
+ var import_integration_server = require("./integration-server.ts");
54
+ var import_typecheck = require("./typecheck.ts");
55
+ var import_quickjs_types = require("./quickjs-types.ts");
56
+ })
57
+
58
+ //# debugId=6163F5C604565B7564756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts"],
4
+ "sourcesContent": [
5
+ "export {\n createTestContext,\n disposeTestContext,\n useTestContext,\n type TestContext,\n} from \"./context.ts\";\n\nexport {\n createFetchTestContext,\n disposeFetchTestContext,\n useFetchTestContext,\n type FetchTestContext,\n type CreateFetchTestContextOptions,\n} from \"./fetch-context.ts\";\n\nexport { evalCode, evalCodeAsync } from \"./eval.ts\";\n\nexport {\n startIntegrationServer,\n type IntegrationTestServer,\n type StartIntegrationServerOptions,\n} from \"./integration-server.ts\";\n\nexport {\n typecheckQuickJSCode,\n formatTypecheckErrors,\n type TypecheckResult,\n type TypecheckError,\n type TypecheckOptions,\n} from \"./typecheck.ts\";\n\nexport {\n CORE_TYPES,\n FETCH_TYPES,\n FS_TYPES,\n TYPE_DEFINITIONS,\n type TypeDefinitionKey,\n} from \"./quickjs-types.ts\";\n\n// For fs and runtime contexts, import from subpaths:\n// import { createFsTestContext } from \"@ricsam/quickjs-test-utils/fs\";\n// import { createRuntimeTestContext } from \"@ricsam/quickjs-test-utils/runtime\";\n"
6
+ ],
7
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,IALP;AAaO,IANP;AAQwC,IAAxC;AAMO,IAJP;AAYO,IANP;AAcO,IANP;",
8
+ "debugId": "6163F5C604565B7564756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "@ricsam/quickjs-test-utils",
3
+ "version": "1.0.0",
4
+ "type": "commonjs"
5
+ }
@@ -0,0 +1,45 @@
1
+ // @bun
2
+ // packages/test-utils/src/index.ts
3
+ import {
4
+ createTestContext,
5
+ disposeTestContext,
6
+ useTestContext
7
+ } from "./context.ts";
8
+ import {
9
+ createFetchTestContext,
10
+ disposeFetchTestContext,
11
+ useFetchTestContext
12
+ } from "./fetch-context.ts";
13
+ import { evalCode, evalCodeAsync } from "./eval.ts";
14
+ import {
15
+ startIntegrationServer
16
+ } from "./integration-server.ts";
17
+ import {
18
+ typecheckQuickJSCode,
19
+ formatTypecheckErrors
20
+ } from "./typecheck.ts";
21
+ import {
22
+ CORE_TYPES,
23
+ FETCH_TYPES,
24
+ FS_TYPES,
25
+ TYPE_DEFINITIONS
26
+ } from "./quickjs-types.ts";
27
+ export {
28
+ useTestContext,
29
+ useFetchTestContext,
30
+ typecheckQuickJSCode,
31
+ startIntegrationServer,
32
+ formatTypecheckErrors,
33
+ evalCodeAsync,
34
+ evalCode,
35
+ disposeTestContext,
36
+ disposeFetchTestContext,
37
+ createTestContext,
38
+ createFetchTestContext,
39
+ TYPE_DEFINITIONS,
40
+ FS_TYPES,
41
+ FETCH_TYPES,
42
+ CORE_TYPES
43
+ };
44
+
45
+ //# debugId=FD8F45F39BD927E164756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts"],
4
+ "sourcesContent": [
5
+ "export {\n createTestContext,\n disposeTestContext,\n useTestContext,\n type TestContext,\n} from \"./context.ts\";\n\nexport {\n createFetchTestContext,\n disposeFetchTestContext,\n useFetchTestContext,\n type FetchTestContext,\n type CreateFetchTestContextOptions,\n} from \"./fetch-context.ts\";\n\nexport { evalCode, evalCodeAsync } from \"./eval.ts\";\n\nexport {\n startIntegrationServer,\n type IntegrationTestServer,\n type StartIntegrationServerOptions,\n} from \"./integration-server.ts\";\n\nexport {\n typecheckQuickJSCode,\n formatTypecheckErrors,\n type TypecheckResult,\n type TypecheckError,\n type TypecheckOptions,\n} from \"./typecheck.ts\";\n\nexport {\n CORE_TYPES,\n FETCH_TYPES,\n FS_TYPES,\n TYPE_DEFINITIONS,\n type TypeDefinitionKey,\n} from \"./quickjs-types.ts\";\n\n// For fs and runtime contexts, import from subpaths:\n// import { createFsTestContext } from \"@ricsam/quickjs-test-utils/fs\";\n// import { createRuntimeTestContext } from \"@ricsam/quickjs-test-utils/runtime\";\n"
6
+ ],
7
+ "mappings": ";;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA;AAAA;AAAA;AAAA;AAAA;AAQA;AAEA;AAAA;AAAA;AAMA;AAAA;AAAA;AAAA;AAQA;AAAA;AAAA;AAAA;AAAA;AAAA;",
8
+ "debugId": "FD8F45F39BD927E164756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "@ricsam/quickjs-test-utils",
3
+ "version": "1.0.0",
4
+ "type": "module"
5
+ }
@@ -0,0 +1,35 @@
1
+ import { type QuickJSContext, type QuickJSRuntime } from "quickjs-emscripten";
2
+ import { type CoreHandle } from "@ricsam/quickjs-core";
3
+ export interface TestContext {
4
+ runtime: QuickJSRuntime;
5
+ context: QuickJSContext;
6
+ coreHandle: CoreHandle;
7
+ }
8
+ export declare function createTestContext(): Promise<TestContext>;
9
+ export declare function disposeTestContext(ctx: TestContext): void;
10
+ /**
11
+ * Helper for use with beforeEach/afterEach
12
+ *
13
+ * @example
14
+ * const testCtx = useTestContext();
15
+ *
16
+ * beforeEach(async () => {
17
+ * await testCtx.setup();
18
+ * });
19
+ *
20
+ * afterEach(() => {
21
+ * testCtx.teardown();
22
+ * });
23
+ *
24
+ * test("my test", () => {
25
+ * const result = evalCode(testCtx.context, `1 + 1`);
26
+ * expect(result).toBe(2);
27
+ * });
28
+ */
29
+ export declare function useTestContext(): {
30
+ setup(): Promise<TestContext>;
31
+ teardown(): void;
32
+ readonly context: QuickJSContext;
33
+ readonly runtime: QuickJSRuntime;
34
+ readonly coreHandle: CoreHandle;
35
+ };
@@ -0,0 +1,31 @@
1
+ import type { QuickJSContext } from "quickjs-emscripten";
2
+ /**
3
+ * Evaluate code synchronously and return the result
4
+ *
5
+ * Handles error checking and handle disposal automatically.
6
+ *
7
+ * @example
8
+ * const result = evalCode<number>(context, `1 + 1`);
9
+ * expect(result).toBe(2);
10
+ *
11
+ * @example
12
+ * const obj = evalCode<{ name: string }>(context, `({ name: "test" })`);
13
+ * expect(obj.name).toBe("test");
14
+ */
15
+ export declare function evalCode<T>(context: QuickJSContext, code: string): T;
16
+ /**
17
+ * Evaluate async code and return the resolved result
18
+ *
19
+ * Handles promise resolution, error checking, and handle disposal automatically.
20
+ * Also executes pending jobs after resolution.
21
+ *
22
+ * @example
23
+ * const result = await evalCodeAsync<string>(context, `
24
+ * (async () => {
25
+ * const blob = new Blob(["hello"]);
26
+ * return await blob.text();
27
+ * })()
28
+ * `);
29
+ * expect(result).toBe("hello");
30
+ */
31
+ export declare function evalCodeAsync<T>(context: QuickJSContext, code: string): Promise<T>;
@@ -0,0 +1,41 @@
1
+ import { type FetchHandle, type SetupFetchOptions } from "@ricsam/quickjs-fetch";
2
+ import { type TestContext } from "./context.ts";
3
+ export interface FetchTestContext extends TestContext {
4
+ fetchHandle: FetchHandle;
5
+ }
6
+ export interface CreateFetchTestContextOptions {
7
+ /** Handler for outbound fetch() calls from QuickJS */
8
+ onFetch?: SetupFetchOptions["onFetch"];
9
+ }
10
+ export declare function createFetchTestContext(options?: CreateFetchTestContextOptions): Promise<FetchTestContext>;
11
+ export declare function disposeFetchTestContext(ctx: FetchTestContext): void;
12
+ /**
13
+ * Helper for use with beforeEach/afterEach for fetch tests
14
+ *
15
+ * @example
16
+ * const testCtx = useFetchTestContext();
17
+ *
18
+ * beforeEach(async () => {
19
+ * await testCtx.setup();
20
+ * });
21
+ *
22
+ * afterEach(() => {
23
+ * testCtx.teardown();
24
+ * });
25
+ *
26
+ * test("headers test", () => {
27
+ * const result = evalCode(testCtx.context, `
28
+ * const headers = new Headers({ "Content-Type": "application/json" });
29
+ * headers.get("content-type");
30
+ * `);
31
+ * expect(result).toBe("application/json");
32
+ * });
33
+ */
34
+ export declare function useFetchTestContext(): {
35
+ setup(): Promise<FetchTestContext>;
36
+ teardown(): void;
37
+ readonly context: import("quickjs-emscripten").QuickJSContext;
38
+ readonly runtime: import("quickjs-emscripten").QuickJSRuntime;
39
+ readonly coreHandle: import("@ricsam/quickjs-core").CoreHandle;
40
+ readonly fetchHandle: FetchHandle;
41
+ };
@@ -0,0 +1,12 @@
1
+ import { type FsHandle, type HostDirectoryHandle } from "@ricsam/quickjs-fs";
2
+ import { type TestContext } from "./context.ts";
3
+ export interface FsTestContext extends TestContext {
4
+ fsHandle: FsHandle;
5
+ memFs: HostDirectoryHandle;
6
+ }
7
+ export interface CreateFsTestContextOptions {
8
+ /** Initial files to populate the in-memory filesystem */
9
+ initialFiles?: Record<string, string | Uint8Array>;
10
+ }
11
+ export declare function createFsTestContext(options?: CreateFsTestContextOptions): Promise<FsTestContext>;
12
+ export declare function disposeFsTestContext(ctx: FsTestContext): void;
@@ -0,0 +1,6 @@
1
+ export { createTestContext, disposeTestContext, useTestContext, type TestContext, } from "./context.ts";
2
+ export { createFetchTestContext, disposeFetchTestContext, useFetchTestContext, type FetchTestContext, type CreateFetchTestContextOptions, } from "./fetch-context.ts";
3
+ export { evalCode, evalCodeAsync } from "./eval.ts";
4
+ export { startIntegrationServer, type IntegrationTestServer, type StartIntegrationServerOptions, } from "./integration-server.ts";
5
+ export { typecheckQuickJSCode, formatTypecheckErrors, type TypecheckResult, type TypecheckError, type TypecheckOptions, } from "./typecheck.ts";
6
+ export { CORE_TYPES, FETCH_TYPES, FS_TYPES, TYPE_DEFINITIONS, type TypeDefinitionKey, } from "./quickjs-types.ts";
@@ -0,0 +1,39 @@
1
+ import { type QuickJSContext, type QuickJSRuntime } from "quickjs-emscripten";
2
+ import { type FetchHandle, type SetupFetchOptions } from "@ricsam/quickjs-fetch";
3
+ import { type CoreHandle } from "@ricsam/quickjs-core";
4
+ export interface IntegrationTestServer {
5
+ baseURL: string;
6
+ wsURL: string;
7
+ port: number;
8
+ fetchHandle: FetchHandle;
9
+ context: QuickJSContext;
10
+ runtime: QuickJSRuntime;
11
+ coreHandle: CoreHandle;
12
+ stop(): Promise<void>;
13
+ }
14
+ export interface StartIntegrationServerOptions {
15
+ /** Handler for outbound fetch() calls from QuickJS */
16
+ onFetch?: SetupFetchOptions["onFetch"];
17
+ }
18
+ /**
19
+ * Start a real HTTP server that dispatches requests to a QuickJS serve() handler.
20
+ *
21
+ * @param quickJSCode - JavaScript code to run in QuickJS, should call serve()
22
+ * @param options - Optional configuration
23
+ * @returns Server info including baseURL, wsURL, and stop function
24
+ *
25
+ * @example
26
+ * const server = await startIntegrationServer(`
27
+ * serve({
28
+ * fetch(request) {
29
+ * return new Response("Hello!");
30
+ * }
31
+ * });
32
+ * `);
33
+ *
34
+ * const response = await fetch(\`\${server.baseURL}/test\`);
35
+ * expect(await response.text()).toBe("Hello!");
36
+ *
37
+ * await server.stop();
38
+ */
39
+ export declare function startIntegrationServer(quickJSCode: string, options?: StartIntegrationServerOptions): Promise<IntegrationTestServer>;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * QuickJS type definitions as string constants.
3
+ *
4
+ * These are the canonical source for QuickJS global type definitions.
5
+ * The .d.ts files in each package are generated from these strings during build.
6
+ *
7
+ * @example
8
+ * import { TYPE_DEFINITIONS } from "@ricsam/quickjs-test-utils";
9
+ *
10
+ * // Use with ts-morph for type checking code strings
11
+ * project.createSourceFile("types.d.ts", TYPE_DEFINITIONS.fetch);
12
+ */
13
+ /**
14
+ * Type definitions for @ricsam/quickjs-core globals.
15
+ *
16
+ * Includes: ReadableStream, WritableStream, TransformStream, Blob, File, URL, URLSearchParams, DOMException
17
+ */
18
+ export declare const CORE_TYPES = "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-core\n *\n * These types define the globals injected by setupCore() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // In your tsconfig.quickjs.json\n * {\n * \"compilerOptions\": {\n * \"lib\": [\"ESNext\", \"DOM\"]\n * }\n * }\n *\n * // Then reference this file or use ts-morph for code strings\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // Web Streams API\n // ============================================\n\n /**\n * A readable stream of data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n */\n const ReadableStream: typeof globalThis.ReadableStream;\n\n /**\n * A writable stream of data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStream\n */\n const WritableStream: typeof globalThis.WritableStream;\n\n /**\n * A transform stream that can be used to pipe data through a transformer.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/TransformStream\n */\n const TransformStream: typeof globalThis.TransformStream;\n\n /**\n * Default reader for ReadableStream\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader\n */\n const ReadableStreamDefaultReader: typeof globalThis.ReadableStreamDefaultReader;\n\n /**\n * Default writer for WritableStream\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter\n */\n const WritableStreamDefaultWriter: typeof globalThis.WritableStreamDefaultWriter;\n\n // ============================================\n // Blob and File APIs\n // ============================================\n\n /**\n * A file-like object of immutable, raw data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Blob\n */\n const Blob: typeof globalThis.Blob;\n\n /**\n * A file object representing a file.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/File\n */\n const File: typeof globalThis.File;\n\n // ============================================\n // URL APIs\n // ============================================\n\n /**\n * Interface for URL manipulation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/URL\n */\n const URL: typeof globalThis.URL;\n\n /**\n * Utility for working with URL query strings.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\n */\n const URLSearchParams: typeof globalThis.URLSearchParams;\n\n // ============================================\n // Error Handling\n // ============================================\n\n /**\n * Exception type for DOM operations.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n */\n const DOMException: typeof globalThis.DOMException;\n}\n";
19
+ /**
20
+ * Type definitions for @ricsam/quickjs-fetch globals.
21
+ *
22
+ * Includes: Headers, Request, Response, AbortController, AbortSignal, FormData, fetch, serve, Server, ServerWebSocket
23
+ */
24
+ export declare const FETCH_TYPES = "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-fetch\n *\n * These types define the globals injected by setupFetch() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // Typecheck QuickJS code with serve()\n * serve({\n * fetch(request, server) {\n * if (request.url.includes(\"/ws\")) {\n * server.upgrade(request, { data: { id: 123 } });\n * return new Response(null, { status: 101 });\n * }\n * return new Response(\"Hello!\");\n * },\n * websocket: {\n * message(ws, message) {\n * ws.send(\"Echo: \" + message);\n * }\n * }\n * });\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // Standard Fetch API (from lib.dom)\n // ============================================\n\n /**\n * Headers class for HTTP headers manipulation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Headers\n */\n const Headers: typeof globalThis.Headers;\n\n /**\n * Request class for HTTP requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Request\n */\n const Request: typeof globalThis.Request;\n\n /**\n * Response class for HTTP responses.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Response\n */\n const Response: typeof globalThis.Response;\n\n /**\n * AbortController for cancelling fetch requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController\n */\n const AbortController: typeof globalThis.AbortController;\n\n /**\n * AbortSignal for listening to abort events.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n const AbortSignal: typeof globalThis.AbortSignal;\n\n /**\n * FormData for constructing form data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FormData\n */\n const FormData: typeof globalThis.FormData;\n\n /**\n * Fetch function for making HTTP requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n function fetch(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response>;\n\n // ============================================\n // QuickJS-specific: serve() API\n // ============================================\n\n /**\n * Server interface for handling WebSocket upgrades within serve() handlers.\n */\n interface Server {\n /**\n * Upgrade an HTTP request to a WebSocket connection.\n *\n * @param request - The incoming HTTP request to upgrade\n * @param options - Optional data to associate with the WebSocket connection\n * @returns true if upgrade will proceed, false otherwise\n *\n * @example\n * serve({\n * fetch(request, server) {\n * if (server.upgrade(request, { data: { userId: 123 } })) {\n * return new Response(null, { status: 101 });\n * }\n * return new Response(\"Upgrade failed\", { status: 400 });\n * }\n * });\n */\n upgrade(request: Request, options?: { data?: unknown }): boolean;\n }\n\n /**\n * ServerWebSocket interface for WebSocket connections within serve() handlers.\n *\n * @typeParam T - The type of data associated with this WebSocket connection\n */\n interface ServerWebSocket<T = unknown> {\n /**\n * User data associated with this connection.\n * Set via `server.upgrade(request, { data: ... })`.\n */\n readonly data: T;\n\n /**\n * Send a message to the client.\n *\n * @param message - The message to send (string, ArrayBuffer, or Uint8Array)\n */\n send(message: string | ArrayBuffer | Uint8Array): void;\n\n /**\n * Close the WebSocket connection.\n *\n * @param code - Optional close code (default: 1000)\n * @param reason - Optional close reason\n */\n close(code?: number, reason?: string): void;\n\n /**\n * WebSocket ready state.\n * - 0: CONNECTING\n * - 1: OPEN\n * - 2: CLOSING\n * - 3: CLOSED\n */\n readonly readyState: number;\n }\n\n /**\n * Options for the serve() function.\n *\n * @typeParam T - The type of data associated with WebSocket connections\n */\n interface ServeOptions<T = unknown> {\n /**\n * Handler for HTTP requests.\n *\n * @param request - The incoming HTTP request\n * @param server - Server interface for WebSocket upgrades\n * @returns Response or Promise resolving to Response\n */\n fetch(request: Request, server: Server): Response | Promise<Response>;\n\n /**\n * WebSocket event handlers.\n */\n websocket?: {\n /**\n * Called when a WebSocket connection is opened.\n *\n * @param ws - The WebSocket connection\n */\n open?(ws: ServerWebSocket<T>): void | Promise<void>;\n\n /**\n * Called when a message is received.\n *\n * @param ws - The WebSocket connection\n * @param message - The received message (string or ArrayBuffer)\n */\n message?(\n ws: ServerWebSocket<T>,\n message: string | ArrayBuffer\n ): void | Promise<void>;\n\n /**\n * Called when the connection is closed.\n *\n * @param ws - The WebSocket connection\n * @param code - The close code\n * @param reason - The close reason\n */\n close?(\n ws: ServerWebSocket<T>,\n code: number,\n reason: string\n ): void | Promise<void>;\n\n /**\n * Called when an error occurs.\n *\n * @param ws - The WebSocket connection\n * @param error - The error that occurred\n */\n error?(ws: ServerWebSocket<T>, error: Error): void | Promise<void>;\n };\n }\n\n /**\n * Register an HTTP server handler in QuickJS.\n *\n * Only one serve() handler can be active at a time.\n * Calling serve() again replaces the previous handler.\n *\n * @param options - Server configuration including fetch handler and optional WebSocket handlers\n *\n * @example\n * serve({\n * fetch(request, server) {\n * const url = new URL(request.url);\n *\n * if (url.pathname === \"/ws\") {\n * if (server.upgrade(request, { data: { connectedAt: Date.now() } })) {\n * return new Response(null, { status: 101 });\n * }\n * }\n *\n * if (url.pathname === \"/api/hello\") {\n * return Response.json({ message: \"Hello!\" });\n * }\n *\n * return new Response(\"Not Found\", { status: 404 });\n * },\n * websocket: {\n * open(ws) {\n * console.log(\"Connected at:\", ws.data.connectedAt);\n * },\n * message(ws, message) {\n * ws.send(\"Echo: \" + message);\n * },\n * close(ws, code, reason) {\n * console.log(\"Closed:\", code, reason);\n * }\n * }\n * });\n */\n function serve<T = unknown>(options: ServeOptions<T>): void;\n}\n";
25
+ /**
26
+ * Type definitions for @ricsam/quickjs-fs globals.
27
+ *
28
+ * Includes: fs namespace, FileSystemHandle, FileSystemFileHandle, FileSystemDirectoryHandle, FileSystemWritableFileStream
29
+ */
30
+ export declare const FS_TYPES = "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-fs\n *\n * These types define the globals injected by setupFs() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // Typecheck QuickJS code with file system access\n * const root = await fs.getDirectory(\"/data\");\n * const fileHandle = await root.getFileHandle(\"config.json\");\n * const file = await fileHandle.getFile();\n * const content = await file.text();\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // fs namespace - QuickJS-specific entry point\n // ============================================\n\n /**\n * File System namespace providing access to the file system.\n * This is the QuickJS-specific entry point (differs from browser's navigator.storage.getDirectory()).\n */\n namespace fs {\n /**\n * Get a directory handle for the given path.\n *\n * The host controls which paths are accessible. Invalid or unauthorized\n * paths will throw an error.\n *\n * @param path - The path to request from the host\n * @returns A promise resolving to a directory handle\n * @throws If the path is not allowed or doesn't exist\n *\n * @example\n * const root = await fs.getDirectory(\"/\");\n * const dataDir = await fs.getDirectory(\"/data\");\n */\n function getDirectory(path: string): Promise<FileSystemDirectoryHandle>;\n }\n\n // ============================================\n // File System Access API\n // ============================================\n\n /**\n * Base interface for file system handles.\n */\n interface FileSystemHandle {\n /**\n * The kind of handle: \"file\" or \"directory\".\n */\n readonly kind: \"file\" | \"directory\";\n\n /**\n * The name of the file or directory.\n */\n readonly name: string;\n\n /**\n * Compare two handles to check if they reference the same entry.\n *\n * @param other - Another FileSystemHandle to compare against\n * @returns true if both handles reference the same entry\n */\n isSameEntry(other: FileSystemHandle): Promise<boolean>;\n }\n\n /**\n * Handle for a file in the file system.\n */\n interface FileSystemFileHandle extends FileSystemHandle {\n /**\n * Always \"file\" for file handles.\n */\n readonly kind: \"file\";\n\n /**\n * Get the file contents as a File object.\n *\n * @returns A promise resolving to a File object\n *\n * @example\n * const file = await fileHandle.getFile();\n * const text = await file.text();\n */\n getFile(): Promise<File>;\n\n /**\n * Create a writable stream for writing to the file.\n *\n * @param options - Options for the writable stream\n * @returns A promise resolving to a writable stream\n *\n * @example\n * const writable = await fileHandle.createWritable();\n * await writable.write(\"Hello, World!\");\n * await writable.close();\n */\n createWritable(options?: {\n /**\n * If true, keeps existing file data. Otherwise, truncates the file.\n */\n keepExistingData?: boolean;\n }): Promise<FileSystemWritableFileStream>;\n }\n\n /**\n * Handle for a directory in the file system.\n */\n interface FileSystemDirectoryHandle extends FileSystemHandle {\n /**\n * Always \"directory\" for directory handles.\n */\n readonly kind: \"directory\";\n\n /**\n * Get a file handle within this directory.\n *\n * @param name - The name of the file\n * @param options - Options for getting the file handle\n * @returns A promise resolving to a file handle\n * @throws If the file doesn't exist and create is not true\n *\n * @example\n * const file = await dir.getFileHandle(\"data.json\");\n * const newFile = await dir.getFileHandle(\"output.txt\", { create: true });\n */\n getFileHandle(\n name: string,\n options?: {\n /**\n * If true, creates the file if it doesn't exist.\n */\n create?: boolean;\n }\n ): Promise<FileSystemFileHandle>;\n\n /**\n * Get a subdirectory handle within this directory.\n *\n * @param name - The name of the subdirectory\n * @param options - Options for getting the directory handle\n * @returns A promise resolving to a directory handle\n * @throws If the directory doesn't exist and create is not true\n *\n * @example\n * const subdir = await dir.getDirectoryHandle(\"logs\");\n * const newDir = await dir.getDirectoryHandle(\"cache\", { create: true });\n */\n getDirectoryHandle(\n name: string,\n options?: {\n /**\n * If true, creates the directory if it doesn't exist.\n */\n create?: boolean;\n }\n ): Promise<FileSystemDirectoryHandle>;\n\n /**\n * Remove a file or directory within this directory.\n *\n * @param name - The name of the entry to remove\n * @param options - Options for removal\n * @throws If the entry doesn't exist or cannot be removed\n *\n * @example\n * await dir.removeEntry(\"old-file.txt\");\n * await dir.removeEntry(\"old-dir\", { recursive: true });\n */\n removeEntry(\n name: string,\n options?: {\n /**\n * If true, removes directories recursively.\n */\n recursive?: boolean;\n }\n ): Promise<void>;\n\n /**\n * Resolve the path from this directory to a descendant handle.\n *\n * @param possibleDescendant - A handle that may be a descendant\n * @returns An array of path segments, or null if not a descendant\n *\n * @example\n * const path = await root.resolve(nestedFile);\n * // [\"subdir\", \"file.txt\"]\n */\n resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;\n\n /**\n * Iterate over entries in this directory.\n *\n * @returns An async iterator of [name, handle] pairs\n *\n * @example\n * for await (const [name, handle] of dir.entries()) {\n * console.log(name, handle.kind);\n * }\n */\n entries(): AsyncIterableIterator<[string, FileSystemHandle]>;\n\n /**\n * Iterate over entry names in this directory.\n *\n * @returns An async iterator of names\n *\n * @example\n * for await (const name of dir.keys()) {\n * console.log(name);\n * }\n */\n keys(): AsyncIterableIterator<string>;\n\n /**\n * Iterate over handles in this directory.\n *\n * @returns An async iterator of handles\n *\n * @example\n * for await (const handle of dir.values()) {\n * console.log(handle.name, handle.kind);\n * }\n */\n values(): AsyncIterableIterator<FileSystemHandle>;\n\n /**\n * Async iterator support for directory entries.\n *\n * @example\n * for await (const [name, handle] of dir) {\n * console.log(name, handle.kind);\n * }\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;\n }\n\n /**\n * Parameters for write operations on FileSystemWritableFileStream.\n */\n interface WriteParams {\n /**\n * The type of write operation.\n * - \"write\": Write data at the current position or specified position\n * - \"seek\": Move the file position\n * - \"truncate\": Truncate the file to a specific size\n */\n type: \"write\" | \"seek\" | \"truncate\";\n\n /**\n * The data to write (for \"write\" type).\n */\n data?: string | ArrayBuffer | Uint8Array | Blob;\n\n /**\n * The position to write at or seek to.\n */\n position?: number;\n\n /**\n * The size to truncate to (for \"truncate\" type).\n */\n size?: number;\n }\n\n /**\n * Writable stream for writing to a file.\n * Extends WritableStream with file-specific operations.\n */\n interface FileSystemWritableFileStream extends WritableStream<Uint8Array> {\n /**\n * Write data to the file.\n *\n * @param data - The data to write\n * @returns A promise that resolves when the write completes\n *\n * @example\n * await writable.write(\"Hello, World!\");\n * await writable.write(new Uint8Array([1, 2, 3]));\n * await writable.write({ type: \"write\", data: \"text\", position: 0 });\n */\n write(\n data: string | ArrayBuffer | Uint8Array | Blob | WriteParams\n ): Promise<void>;\n\n /**\n * Seek to a position in the file.\n *\n * @param position - The byte position to seek to\n * @returns A promise that resolves when the seek completes\n *\n * @example\n * await writable.seek(0); // Seek to beginning\n * await writable.write(\"Overwrite\");\n */\n seek(position: number): Promise<void>;\n\n /**\n * Truncate the file to a specific size.\n *\n * @param size - The size to truncate to\n * @returns A promise that resolves when the truncation completes\n *\n * @example\n * await writable.truncate(100); // Keep only first 100 bytes\n */\n truncate(size: number): Promise<void>;\n }\n}\n";
31
+ /**
32
+ * Map of package names to their type definitions.
33
+ */
34
+ export declare const TYPE_DEFINITIONS: {
35
+ readonly core: "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-core\n *\n * These types define the globals injected by setupCore() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // In your tsconfig.quickjs.json\n * {\n * \"compilerOptions\": {\n * \"lib\": [\"ESNext\", \"DOM\"]\n * }\n * }\n *\n * // Then reference this file or use ts-morph for code strings\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // Web Streams API\n // ============================================\n\n /**\n * A readable stream of data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n */\n const ReadableStream: typeof globalThis.ReadableStream;\n\n /**\n * A writable stream of data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStream\n */\n const WritableStream: typeof globalThis.WritableStream;\n\n /**\n * A transform stream that can be used to pipe data through a transformer.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/TransformStream\n */\n const TransformStream: typeof globalThis.TransformStream;\n\n /**\n * Default reader for ReadableStream\n * @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader\n */\n const ReadableStreamDefaultReader: typeof globalThis.ReadableStreamDefaultReader;\n\n /**\n * Default writer for WritableStream\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter\n */\n const WritableStreamDefaultWriter: typeof globalThis.WritableStreamDefaultWriter;\n\n // ============================================\n // Blob and File APIs\n // ============================================\n\n /**\n * A file-like object of immutable, raw data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Blob\n */\n const Blob: typeof globalThis.Blob;\n\n /**\n * A file object representing a file.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/File\n */\n const File: typeof globalThis.File;\n\n // ============================================\n // URL APIs\n // ============================================\n\n /**\n * Interface for URL manipulation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/URL\n */\n const URL: typeof globalThis.URL;\n\n /**\n * Utility for working with URL query strings.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\n */\n const URLSearchParams: typeof globalThis.URLSearchParams;\n\n // ============================================\n // Error Handling\n // ============================================\n\n /**\n * Exception type for DOM operations.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n */\n const DOMException: typeof globalThis.DOMException;\n}\n";
36
+ readonly fetch: "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-fetch\n *\n * These types define the globals injected by setupFetch() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // Typecheck QuickJS code with serve()\n * serve({\n * fetch(request, server) {\n * if (request.url.includes(\"/ws\")) {\n * server.upgrade(request, { data: { id: 123 } });\n * return new Response(null, { status: 101 });\n * }\n * return new Response(\"Hello!\");\n * },\n * websocket: {\n * message(ws, message) {\n * ws.send(\"Echo: \" + message);\n * }\n * }\n * });\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // Standard Fetch API (from lib.dom)\n // ============================================\n\n /**\n * Headers class for HTTP headers manipulation.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Headers\n */\n const Headers: typeof globalThis.Headers;\n\n /**\n * Request class for HTTP requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Request\n */\n const Request: typeof globalThis.Request;\n\n /**\n * Response class for HTTP responses.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Response\n */\n const Response: typeof globalThis.Response;\n\n /**\n * AbortController for cancelling fetch requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController\n */\n const AbortController: typeof globalThis.AbortController;\n\n /**\n * AbortSignal for listening to abort events.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n const AbortSignal: typeof globalThis.AbortSignal;\n\n /**\n * FormData for constructing form data.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/FormData\n */\n const FormData: typeof globalThis.FormData;\n\n /**\n * Fetch function for making HTTP requests.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n function fetch(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response>;\n\n // ============================================\n // QuickJS-specific: serve() API\n // ============================================\n\n /**\n * Server interface for handling WebSocket upgrades within serve() handlers.\n */\n interface Server {\n /**\n * Upgrade an HTTP request to a WebSocket connection.\n *\n * @param request - The incoming HTTP request to upgrade\n * @param options - Optional data to associate with the WebSocket connection\n * @returns true if upgrade will proceed, false otherwise\n *\n * @example\n * serve({\n * fetch(request, server) {\n * if (server.upgrade(request, { data: { userId: 123 } })) {\n * return new Response(null, { status: 101 });\n * }\n * return new Response(\"Upgrade failed\", { status: 400 });\n * }\n * });\n */\n upgrade(request: Request, options?: { data?: unknown }): boolean;\n }\n\n /**\n * ServerWebSocket interface for WebSocket connections within serve() handlers.\n *\n * @typeParam T - The type of data associated with this WebSocket connection\n */\n interface ServerWebSocket<T = unknown> {\n /**\n * User data associated with this connection.\n * Set via `server.upgrade(request, { data: ... })`.\n */\n readonly data: T;\n\n /**\n * Send a message to the client.\n *\n * @param message - The message to send (string, ArrayBuffer, or Uint8Array)\n */\n send(message: string | ArrayBuffer | Uint8Array): void;\n\n /**\n * Close the WebSocket connection.\n *\n * @param code - Optional close code (default: 1000)\n * @param reason - Optional close reason\n */\n close(code?: number, reason?: string): void;\n\n /**\n * WebSocket ready state.\n * - 0: CONNECTING\n * - 1: OPEN\n * - 2: CLOSING\n * - 3: CLOSED\n */\n readonly readyState: number;\n }\n\n /**\n * Options for the serve() function.\n *\n * @typeParam T - The type of data associated with WebSocket connections\n */\n interface ServeOptions<T = unknown> {\n /**\n * Handler for HTTP requests.\n *\n * @param request - The incoming HTTP request\n * @param server - Server interface for WebSocket upgrades\n * @returns Response or Promise resolving to Response\n */\n fetch(request: Request, server: Server): Response | Promise<Response>;\n\n /**\n * WebSocket event handlers.\n */\n websocket?: {\n /**\n * Called when a WebSocket connection is opened.\n *\n * @param ws - The WebSocket connection\n */\n open?(ws: ServerWebSocket<T>): void | Promise<void>;\n\n /**\n * Called when a message is received.\n *\n * @param ws - The WebSocket connection\n * @param message - The received message (string or ArrayBuffer)\n */\n message?(\n ws: ServerWebSocket<T>,\n message: string | ArrayBuffer\n ): void | Promise<void>;\n\n /**\n * Called when the connection is closed.\n *\n * @param ws - The WebSocket connection\n * @param code - The close code\n * @param reason - The close reason\n */\n close?(\n ws: ServerWebSocket<T>,\n code: number,\n reason: string\n ): void | Promise<void>;\n\n /**\n * Called when an error occurs.\n *\n * @param ws - The WebSocket connection\n * @param error - The error that occurred\n */\n error?(ws: ServerWebSocket<T>, error: Error): void | Promise<void>;\n };\n }\n\n /**\n * Register an HTTP server handler in QuickJS.\n *\n * Only one serve() handler can be active at a time.\n * Calling serve() again replaces the previous handler.\n *\n * @param options - Server configuration including fetch handler and optional WebSocket handlers\n *\n * @example\n * serve({\n * fetch(request, server) {\n * const url = new URL(request.url);\n *\n * if (url.pathname === \"/ws\") {\n * if (server.upgrade(request, { data: { connectedAt: Date.now() } })) {\n * return new Response(null, { status: 101 });\n * }\n * }\n *\n * if (url.pathname === \"/api/hello\") {\n * return Response.json({ message: \"Hello!\" });\n * }\n *\n * return new Response(\"Not Found\", { status: 404 });\n * },\n * websocket: {\n * open(ws) {\n * console.log(\"Connected at:\", ws.data.connectedAt);\n * },\n * message(ws, message) {\n * ws.send(\"Echo: \" + message);\n * },\n * close(ws, code, reason) {\n * console.log(\"Closed:\", code, reason);\n * }\n * }\n * });\n */\n function serve<T = unknown>(options: ServeOptions<T>): void;\n}\n";
37
+ readonly fs: "/**\n * QuickJS Global Type Definitions for @ricsam/quickjs-fs\n *\n * These types define the globals injected by setupFs() into a QuickJS context.\n * Use these types to typecheck user code that will run inside QuickJS.\n *\n * @example\n * // Typecheck QuickJS code with file system access\n * const root = await fs.getDirectory(\"/data\");\n * const fileHandle = await root.getFileHandle(\"config.json\");\n * const file = await fileHandle.getFile();\n * const content = await file.text();\n */\n\nexport {};\n\ndeclare global {\n // ============================================\n // fs namespace - QuickJS-specific entry point\n // ============================================\n\n /**\n * File System namespace providing access to the file system.\n * This is the QuickJS-specific entry point (differs from browser's navigator.storage.getDirectory()).\n */\n namespace fs {\n /**\n * Get a directory handle for the given path.\n *\n * The host controls which paths are accessible. Invalid or unauthorized\n * paths will throw an error.\n *\n * @param path - The path to request from the host\n * @returns A promise resolving to a directory handle\n * @throws If the path is not allowed or doesn't exist\n *\n * @example\n * const root = await fs.getDirectory(\"/\");\n * const dataDir = await fs.getDirectory(\"/data\");\n */\n function getDirectory(path: string): Promise<FileSystemDirectoryHandle>;\n }\n\n // ============================================\n // File System Access API\n // ============================================\n\n /**\n * Base interface for file system handles.\n */\n interface FileSystemHandle {\n /**\n * The kind of handle: \"file\" or \"directory\".\n */\n readonly kind: \"file\" | \"directory\";\n\n /**\n * The name of the file or directory.\n */\n readonly name: string;\n\n /**\n * Compare two handles to check if they reference the same entry.\n *\n * @param other - Another FileSystemHandle to compare against\n * @returns true if both handles reference the same entry\n */\n isSameEntry(other: FileSystemHandle): Promise<boolean>;\n }\n\n /**\n * Handle for a file in the file system.\n */\n interface FileSystemFileHandle extends FileSystemHandle {\n /**\n * Always \"file\" for file handles.\n */\n readonly kind: \"file\";\n\n /**\n * Get the file contents as a File object.\n *\n * @returns A promise resolving to a File object\n *\n * @example\n * const file = await fileHandle.getFile();\n * const text = await file.text();\n */\n getFile(): Promise<File>;\n\n /**\n * Create a writable stream for writing to the file.\n *\n * @param options - Options for the writable stream\n * @returns A promise resolving to a writable stream\n *\n * @example\n * const writable = await fileHandle.createWritable();\n * await writable.write(\"Hello, World!\");\n * await writable.close();\n */\n createWritable(options?: {\n /**\n * If true, keeps existing file data. Otherwise, truncates the file.\n */\n keepExistingData?: boolean;\n }): Promise<FileSystemWritableFileStream>;\n }\n\n /**\n * Handle for a directory in the file system.\n */\n interface FileSystemDirectoryHandle extends FileSystemHandle {\n /**\n * Always \"directory\" for directory handles.\n */\n readonly kind: \"directory\";\n\n /**\n * Get a file handle within this directory.\n *\n * @param name - The name of the file\n * @param options - Options for getting the file handle\n * @returns A promise resolving to a file handle\n * @throws If the file doesn't exist and create is not true\n *\n * @example\n * const file = await dir.getFileHandle(\"data.json\");\n * const newFile = await dir.getFileHandle(\"output.txt\", { create: true });\n */\n getFileHandle(\n name: string,\n options?: {\n /**\n * If true, creates the file if it doesn't exist.\n */\n create?: boolean;\n }\n ): Promise<FileSystemFileHandle>;\n\n /**\n * Get a subdirectory handle within this directory.\n *\n * @param name - The name of the subdirectory\n * @param options - Options for getting the directory handle\n * @returns A promise resolving to a directory handle\n * @throws If the directory doesn't exist and create is not true\n *\n * @example\n * const subdir = await dir.getDirectoryHandle(\"logs\");\n * const newDir = await dir.getDirectoryHandle(\"cache\", { create: true });\n */\n getDirectoryHandle(\n name: string,\n options?: {\n /**\n * If true, creates the directory if it doesn't exist.\n */\n create?: boolean;\n }\n ): Promise<FileSystemDirectoryHandle>;\n\n /**\n * Remove a file or directory within this directory.\n *\n * @param name - The name of the entry to remove\n * @param options - Options for removal\n * @throws If the entry doesn't exist or cannot be removed\n *\n * @example\n * await dir.removeEntry(\"old-file.txt\");\n * await dir.removeEntry(\"old-dir\", { recursive: true });\n */\n removeEntry(\n name: string,\n options?: {\n /**\n * If true, removes directories recursively.\n */\n recursive?: boolean;\n }\n ): Promise<void>;\n\n /**\n * Resolve the path from this directory to a descendant handle.\n *\n * @param possibleDescendant - A handle that may be a descendant\n * @returns An array of path segments, or null if not a descendant\n *\n * @example\n * const path = await root.resolve(nestedFile);\n * // [\"subdir\", \"file.txt\"]\n */\n resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;\n\n /**\n * Iterate over entries in this directory.\n *\n * @returns An async iterator of [name, handle] pairs\n *\n * @example\n * for await (const [name, handle] of dir.entries()) {\n * console.log(name, handle.kind);\n * }\n */\n entries(): AsyncIterableIterator<[string, FileSystemHandle]>;\n\n /**\n * Iterate over entry names in this directory.\n *\n * @returns An async iterator of names\n *\n * @example\n * for await (const name of dir.keys()) {\n * console.log(name);\n * }\n */\n keys(): AsyncIterableIterator<string>;\n\n /**\n * Iterate over handles in this directory.\n *\n * @returns An async iterator of handles\n *\n * @example\n * for await (const handle of dir.values()) {\n * console.log(handle.name, handle.kind);\n * }\n */\n values(): AsyncIterableIterator<FileSystemHandle>;\n\n /**\n * Async iterator support for directory entries.\n *\n * @example\n * for await (const [name, handle] of dir) {\n * console.log(name, handle.kind);\n * }\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;\n }\n\n /**\n * Parameters for write operations on FileSystemWritableFileStream.\n */\n interface WriteParams {\n /**\n * The type of write operation.\n * - \"write\": Write data at the current position or specified position\n * - \"seek\": Move the file position\n * - \"truncate\": Truncate the file to a specific size\n */\n type: \"write\" | \"seek\" | \"truncate\";\n\n /**\n * The data to write (for \"write\" type).\n */\n data?: string | ArrayBuffer | Uint8Array | Blob;\n\n /**\n * The position to write at or seek to.\n */\n position?: number;\n\n /**\n * The size to truncate to (for \"truncate\" type).\n */\n size?: number;\n }\n\n /**\n * Writable stream for writing to a file.\n * Extends WritableStream with file-specific operations.\n */\n interface FileSystemWritableFileStream extends WritableStream<Uint8Array> {\n /**\n * Write data to the file.\n *\n * @param data - The data to write\n * @returns A promise that resolves when the write completes\n *\n * @example\n * await writable.write(\"Hello, World!\");\n * await writable.write(new Uint8Array([1, 2, 3]));\n * await writable.write({ type: \"write\", data: \"text\", position: 0 });\n */\n write(\n data: string | ArrayBuffer | Uint8Array | Blob | WriteParams\n ): Promise<void>;\n\n /**\n * Seek to a position in the file.\n *\n * @param position - The byte position to seek to\n * @returns A promise that resolves when the seek completes\n *\n * @example\n * await writable.seek(0); // Seek to beginning\n * await writable.write(\"Overwrite\");\n */\n seek(position: number): Promise<void>;\n\n /**\n * Truncate the file to a specific size.\n *\n * @param size - The size to truncate to\n * @returns A promise that resolves when the truncation completes\n *\n * @example\n * await writable.truncate(100); // Keep only first 100 bytes\n */\n truncate(size: number): Promise<void>;\n }\n}\n";
38
+ };
39
+ /**
40
+ * Type for the keys of TYPE_DEFINITIONS.
41
+ */
42
+ export type TypeDefinitionKey = keyof typeof TYPE_DEFINITIONS;
@@ -0,0 +1,9 @@
1
+ import { type QuickJSContext, type QuickJSRuntime } from "quickjs-emscripten";
2
+ import { type RuntimeHandle, type SetupRuntimeOptions } from "@ricsam/quickjs-runtime";
3
+ export interface RuntimeTestContext {
4
+ runtime: QuickJSRuntime;
5
+ context: QuickJSContext;
6
+ runtimeHandle: RuntimeHandle;
7
+ }
8
+ export declare function createRuntimeTestContext(options?: SetupRuntimeOptions): Promise<RuntimeTestContext>;
9
+ export declare function disposeRuntimeTestContext(ctx: RuntimeTestContext): void;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Type-checking utility for QuickJS user code using ts-morph.
3
+ *
4
+ * This utility allows you to validate TypeScript code strings against
5
+ * the QuickJS global type definitions before running them in the sandbox.
6
+ *
7
+ * @example
8
+ * import { typecheckQuickJSCode } from "@ricsam/quickjs-test-utils";
9
+ *
10
+ * const result = typecheckQuickJSCode(`
11
+ * serve({
12
+ * fetch(request, server) {
13
+ * return new Response("Hello!");
14
+ * }
15
+ * });
16
+ * `, { include: ["fetch"] });
17
+ *
18
+ * if (!result.success) {
19
+ * console.error("Type errors:", result.errors);
20
+ * }
21
+ */
22
+ import { ts } from "ts-morph";
23
+ /**
24
+ * Result of type-checking QuickJS code.
25
+ */
26
+ export interface TypecheckResult {
27
+ /**
28
+ * Whether the code passed type checking.
29
+ */
30
+ success: boolean;
31
+ /**
32
+ * Array of type errors found in the code.
33
+ */
34
+ errors: TypecheckError[];
35
+ }
36
+ /**
37
+ * A single type-checking error.
38
+ */
39
+ export interface TypecheckError {
40
+ /**
41
+ * The error message from TypeScript.
42
+ */
43
+ message: string;
44
+ /**
45
+ * The line number where the error occurred (1-indexed).
46
+ */
47
+ line?: number;
48
+ /**
49
+ * The column number where the error occurred (1-indexed).
50
+ */
51
+ column?: number;
52
+ /**
53
+ * The TypeScript error code.
54
+ */
55
+ code?: number;
56
+ }
57
+ /**
58
+ * Options for type-checking QuickJS code.
59
+ */
60
+ export interface TypecheckOptions {
61
+ /**
62
+ * Which package types to include.
63
+ * @default ["core", "fetch", "fs"]
64
+ */
65
+ include?: Array<"core" | "fetch" | "fs">;
66
+ /**
67
+ * Additional compiler options to pass to TypeScript.
68
+ */
69
+ compilerOptions?: Partial<ts.CompilerOptions>;
70
+ }
71
+ /**
72
+ * Type-check QuickJS user code against the package type definitions.
73
+ *
74
+ * @param code - The TypeScript/JavaScript code to check
75
+ * @param options - Configuration options
76
+ * @returns The result of type checking
77
+ *
78
+ * @example
79
+ * // Check code that uses the fetch API
80
+ * const result = typecheckQuickJSCode(`
81
+ * const response = await fetch("https://api.example.com/data");
82
+ * const data = await response.json();
83
+ * `, { include: ["core", "fetch"] });
84
+ *
85
+ * @example
86
+ * // Check code that uses serve()
87
+ * const result = typecheckQuickJSCode(`
88
+ * serve({
89
+ * fetch(request, server) {
90
+ * return new Response("Hello!");
91
+ * }
92
+ * });
93
+ * `, { include: ["fetch"] });
94
+ *
95
+ * @example
96
+ * // Check code that uses the file system API
97
+ * const result = typecheckQuickJSCode(`
98
+ * const root = await fs.getDirectory("/data");
99
+ * const file = await root.getFileHandle("config.json");
100
+ * `, { include: ["core", "fs"] });
101
+ */
102
+ export declare function typecheckQuickJSCode(code: string, options?: TypecheckOptions): TypecheckResult;
103
+ /**
104
+ * Format type-check errors for display.
105
+ *
106
+ * @param result - The type-check result
107
+ * @returns A formatted string of errors
108
+ *
109
+ * @example
110
+ * const result = typecheckQuickJSCode(code);
111
+ * if (!result.success) {
112
+ * console.error(formatTypecheckErrors(result));
113
+ * }
114
+ */
115
+ export declare function formatTypecheckErrors(result: TypecheckResult): string;
package/package.json CHANGED
@@ -1,10 +1,66 @@
1
1
  {
2
2
  "name": "@ricsam/quickjs-test-utils",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @ricsam/quickjs-test-utils",
3
+ "version": "1.0.0",
4
+ "main": "./dist/cjs/index.cjs",
5
+ "types": "./dist/types/index.d.ts",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/types/index.d.ts",
9
+ "require": "./dist/cjs/index.cjs",
10
+ "import": "./dist/mjs/index.mjs"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "bun build ./src/index.ts --outdir ./dist --target bun",
15
+ "test": "bun test",
16
+ "typecheck": "tsc --noEmit"
17
+ },
18
+ "dependencies": {
19
+ "ts-morph": "^24.0.0"
20
+ },
21
+ "peerDependencies": {
22
+ "quickjs-emscripten": "^0.31.0",
23
+ "@ricsam/quickjs-core": "^0.2.0",
24
+ "@ricsam/quickjs-fetch": "^0.2.0",
25
+ "@ricsam/quickjs-fs": "^0.2.0",
26
+ "@ricsam/quickjs-runtime": "^0.2.0"
27
+ },
28
+ "peerDependenciesMeta": {
29
+ "@ricsam/quickjs-fs": {
30
+ "optional": true
31
+ },
32
+ "@ricsam/quickjs-runtime": {
33
+ "optional": true
34
+ }
35
+ },
36
+ "author": "Richard Samuelsson",
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/ricsam/richie-qjs.git"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/ricsam/richie-qjs/issues"
44
+ },
45
+ "homepage": "https://github.com/ricsam/richie-qjs#readme",
5
46
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
47
+ "quickjs",
48
+ "sandbox",
49
+ "javascript",
50
+ "runtime",
51
+ "fetch",
52
+ "filesystem",
53
+ "streams",
54
+ "wasm",
55
+ "emscripten"
56
+ ],
57
+ "description": "Testing utilities for QuickJS runtime",
58
+ "module": "./dist/mjs/index.mjs",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "files": [
63
+ "dist",
64
+ "README.md"
9
65
  ]
10
- }
66
+ }