Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(harper.js): use `BinaryModule` to load and manage wasm APIs

Asuka109c7ce23674fe2
diff --git a/packages/harper.js/package.json b/packages/harper.js/package.json
index 2d020f4f1..561e656ed 100644
--- a/packages/harper.js/package.json
+++ b/packages/harper.js/package.json
@@ -17,7 +17,10 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
- "test": "vitest run --browser"
+ "test": "vitest run --browser",
+ "test:debug": "vitest run --browser.headless false --testTimeout 0",
+ "api:extractor": "api-extractor run",
+ "api:documenter": "api-documenter markdown -i temp"
},
"devDependencies": {
"@microsoft/api-documenter": "^7.26.7",
diff --git a/packages/harper.js/src/Linter.bench.ts b/packages/harper.js/src/Linter.bench.ts
index 6d11c2ba4..5c8f317e0 100644
--- a/packages/harper.js/src/Linter.bench.ts
+++ b/packages/harper.js/src/Linter.bench.ts
@@ -1,6 +1,7 @@
import { bench } from 'vitest';
import LocalLinter from './LocalLinter';
import WorkerLinter from './WorkerLinter';
+import { binary } from './binary';
const linters = {
WorkerLinter: WorkerLinter,
@@ -8,7 +9,7 @@ const linters = {
};
for (const [linterName, Linter] of Object.entries(linters)) {
- const linter = new Linter();
+ const linter = new Linter({ binary });
// Prime caches
linter.setup();
diff --git a/packages/harper.js/src/Linter.test.ts b/packages/harper.js/src/Linter.test.ts
index c1de1be45..b9eb1ac46 100644
--- a/packages/harper.js/src/Linter.test.ts
+++ b/packages/harper.js/src/Linter.test.ts
@@ -26,11 +26,7 @@ for (const [linterName, Linter] of Object.entries(linters)) {
linter.lint('The the problem is...')
];
- const results = [];
-
- for (const promise of promises) {
- results.push(await promise);
- }
+ const results = await Promise.all(promises);
expect(results[0].length).toBe(1);
expect(results[0][0].suggestions().length).toBe(1);
diff --git a/packages/harper.js/src/Linter.ts b/packages/harper.js/src/Linter.ts
index b2100d168..0ee052872 100644
--- a/packages/harper.js/src/Linter.ts
+++ b/packages/harper.js/src/Linter.ts
@@ -1,5 +1,6 @@
import type { Lint, Span, Suggestion } from 'harper-wasm';
import { LintConfig, LintOptions } from './main';
+import { BinaryModule } from './binary';
/** An interface for an object that can perform linting actions. */
export default interface Linter {
@@ -67,5 +68,5 @@ export default interface Linter {
export interface LinterInit {
/** The module or path to the WebAssembly binary. */
- binary: string;
+ binary: BinaryModule;
}
diff --git a/packages/harper.js/src/LocalLinter.ts b/packages/harper.js/src/LocalLinter.ts
index ea32ffbf2..265f75a82 100644
--- a/packages/harper.js/src/LocalLinter.ts
+++ b/packages/harper.js/src/LocalLinter.ts
@@ -2,131 +2,106 @@ import type { Lint, Span, Suggestion, Linter as WasmLinter } from 'harper-wasm';
import { Language } from 'harper-wasm';
import Linter, { LinterInit } from './Linter';
import { LintConfig, LintOptions } from './main';
-import { binary, loadBinary } from './binary';
+import { BinaryModule } from './binary';
/** A Linter that runs in the current JavaScript context (meaning it is allowed to block the event loop). */
export default class LocalLinter implements Linter {
- private binary: string;
- private inner: WasmLinter | undefined;
+ binary: BinaryModule;
+ private inner: Promise<WasmLinter>;
constructor(init: LinterInit) {
this.binary = init.binary;
- }
-
- /** Initialize the WebAssembly and construct the inner Linter. */
- private async initialize(): Promise<void> {
- if (!this.inner) {
- const exports = await loadBinary(this.binary);
- exports.setup();
- this.inner = exports.Linter.new();
- }
+ this.inner = this.binary.setup().then(() => this.binary.createLinter());
}
async setup(): Promise<void> {
- await this.initialize();
- this.inner!.lint('', Language.Plain);
+ await this.lint('', { language: 'plaintext' });
const exported = await this.exportIgnoredLints();
await this.importIgnoredLints(exported);
}
async lint(text: string, options?: LintOptions): Promise<Lint[]> {
- await this.initialize();
- const lints = this.inner!.lint(
- text,
- options?.language === 'plaintext' ? Language.Plain : Language.Markdown
- );
+ const inner = await this.inner;
+ const language = options?.language === 'plaintext' ? Language.Plain : Language.Markdown;
+ const lints = inner.lint(text, language);
return lints;
}
async applySuggestion(text: string, suggestion: Suggestion, span: Span): Promise<string> {
- const wasm = await loadBinary(binary);
- return wasm.apply_suggestion(text, span, suggestion);
+ return await this.binary.applySuggestion(text, suggestion, span);
}
async isLikelyEnglish(text: string): Promise<boolean> {
- await this.initialize();
- return this.inner!.is_likely_english(text);
+ const inner = await this.inner;
+ return inner.is_likely_english(text);
}
async isolateEnglish(text: string): Promise<string> {
- await this.initialize();
- return this.inner!.isolate_english(text);
+ const inner = await this.inner;
+ return inner.isolate_english(text);
}
async getLintConfig(): Promise<LintConfig> {
- await this.initialize();
-
- return this.inner!.get_lint_config_as_object();
+ const inner = await this.inner;
+ return inner.get_lint_config_as_object();
}
async getDefaultLintConfigAsJSON(): Promise<string> {
- const wasm = await loadBinary(binary);
-
- return wasm.get_default_lint_config_as_json();
+ return this.binary.getDefaultLintConfigAsJSON();
}
async getDefaultLintConfig(): Promise<LintConfig> {
- const wasm = await loadBinary(binary);
-
- return wasm.get_default_lint_config();
+ return this.binary.getDefaultLintConfig();
}
async setLintConfig(config: LintConfig): Promise<void> {
- await this.initialize();
-
- this.inner!.set_lint_config_from_object(config);
+ const inner = await this.inner;
+ inner.set_lint_config_from_object(config);
}
async getLintConfigAsJSON(): Promise<string> {
- await this.initialize();
-
- return this.inner!.get_lint_config_as_json();
+ const inner = await this.inner;
+ return inner.get_lint_config_as_json();
}
async setLintConfigWithJSON(config: string): Promise<void> {
- await this.initialize();
-
- this.inner!.set_lint_config_from_json(config);
+ const inner = await this.inner;
+ inner.set_lint_config_from_json(config);
}
async toTitleCase(text: string): Promise<string> {
- const wasm = await loadBinary(binary);
- return wasm.to_title_case(text);
+ return this.binary.toTitleCase(text);
}
async getLintDescriptions(): Promise<Record<string, string>> {
- await this.initialize();
- return this.inner!.get_lint_descriptions_as_object();
+ const inner = await this.inner;
+ return inner.get_lint_descriptions_as_object();
}
async getLintDescriptionsAsJSON(): Promise<string> {
- await this.initialize();
- return this.inner!.get_lint_descriptions_as_json();
+ const inner = await this.inner;
+ return inner.get_lint_descriptions_as_json();
}
async ignoreLint(lint: Lint): Promise<void> {
- await this.initialize();
-
- this.inner!.ignore_lint(lint);
+ const inner = await this.inner;
+ inner.ignore_lint(lint);
}
async exportIgnoredLints(): Promise<string> {
- await this.initialize();
-
- return this.inner!.export_ignored_lints();
+ const inner = await this.inner;
+ return inner.export_ignored_lints();
}
async importIgnoredLints(json: string): Promise<void> {
- await this.initialize();
-
- return this.inner!.import_ignored_lints(json);
+ const inner = await this.inner;
+ inner.import_ignored_lints(json);
}
async clearIgnoredLints(): Promise<void> {
- await this.initialize();
-
- return this.inner!.clear_ignored_lints();
+ const inner = await this.inner;
+ inner.clear_ignored_lints();
}
}
diff --git a/packages/harper.js/src/WorkerLinter/communication.ts b/packages/harper.js/src/WorkerLinter/communication.ts
deleted file mode 100644
index 655e78601..000000000
--- a/packages/harper.js/src/WorkerLinter/communication.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { binary, loadBinary } from '../binary';
-
-/** This module aims to define the communication protocol between the main thread and the worker.
- * Note that much of the complication here comes from the fact that we can't serialize function calls or referenced WebAssembly memory.*/
-
-export type Type =
- | 'string'
- | 'number'
- | 'boolean'
- | 'Suggestion'
- | 'Lint'
- | 'Span'
- | 'Array'
- | 'undefined';
-
-/** Serializable argument to a procedure to be run on the web worker. */
-export type RequestArg = {
- json: string;
- type: Type;
-};
-
-export async function serialize(req: DeserializedRequest): Promise<SerializedRequest> {
- return {
- procName: req.procName,
- args: await Promise.all(req.args.map(serializeArg))
- };
-}
-
-export async function serializeArg(arg: any): Promise<RequestArg> {
- const { Lint, Span, Suggestion } = await loadBinary(binary);
-
- if (Array.isArray(arg)) {
- return { json: JSON.stringify(await Promise.all(arg.map(serializeArg))), type: 'Array' };
- }
-
- switch (typeof arg) {
- case 'string':
- case 'number':
- case 'boolean':
- case 'undefined':
- // @ts-expect-error see the `Type` type.
- return { json: JSON.stringify(arg), type: typeof arg };
- }
-
- if (arg.to_json != undefined) {
- const json = arg.to_json();
- let type: Type | undefined = undefined;
-
- if (arg instanceof Lint) {
- type = 'Lint';
- } else if (arg instanceof Suggestion) {
- type = 'Suggestion';
- } else if (arg instanceof Span) {
- type = 'Span';
- }
-
- if (type == undefined) {
- throw new Error('Unhandled case');
- }
-
- return { json, type };
- }
-
- throw new Error('Unhandled case');
-}
-
-export async function deserializeArg(requestArg: RequestArg): Promise<any> {
- const { Lint, Span, Suggestion } = await loadBinary(binary);
-
- switch (requestArg.type) {
- case 'undefined':
- return undefined;
- case 'boolean':
- case 'number':
- case 'string':
- return JSON.parse(requestArg.json);
- case 'Suggestion':
- return Suggestion.from_json(requestArg.json);
- case 'Lint':
- return Lint.from_json(requestArg.json);
- case 'Span':
- return Span.from_json(requestArg.json);
- case 'Array':
- return await Promise.all(JSON.parse(requestArg.json).map(deserializeArg));
- default:
- throw new Error(`Unhandled case: ${requestArg.type}`);
- }
-}
-
-/** An object that is sent to the web worker to request work to be done. */
-export type SerializedRequest = {
- /** The procedure to be executed. */
- procName: string;
- /** The arguments to the procedure */
- args: RequestArg[];
-};
-
-export function isSerializedRequest(v: unknown): v is SerializedRequest {
- return typeof v === 'object' && v !== null && 'procName' in v && 'args' in v;
-}
-
-/** An object that is received by the web worker to request work to be done. */
-export type DeserializedRequest = {
- /** The procedure to be executed. */
- procName: string;
- /** The arguments to the procedure */
- args: any[];
-};
-
-export async function deserialize(request: SerializedRequest): Promise<DeserializedRequest> {
- return {
- procName: request.procName,
- args: await Promise.all(request.args.map(deserializeArg))
- };
-}
diff --git a/packages/harper.js/src/WorkerLinter/index.ts b/packages/harper.js/src/WorkerLinter/index.ts
index 229e7dcf1..588d2940f 100644
--- a/packages/harper.js/src/WorkerLinter/index.ts
+++ b/packages/harper.js/src/WorkerLinter/index.ts
@@ -1,22 +1,22 @@
-import { DeserializedRequest, deserializeArg, serialize } from './communication';
import type { Lint, Suggestion, Span } from 'harper-wasm';
import Linter, { LinterInit } from '../Linter';
-import Worker from './worker?worker&inline';
+import Worker from './worker.ts?worker&inline';
import { LintConfig, LintOptions } from '../main';
+import { BinaryModule, DeserializedRequest } from '../binary';
/** The data necessary to complete a request once the worker has responded. */
-type RequestItem = {
+export interface RequestItem {
resolve: (item: unknown) => void;
reject: (item: unknown) => void;
request: DeserializedRequest;
-};
+}
/** A Linter that spins up a dedicated web worker to do processing on a separate thread.
* Main benefit: this Linter will not block the event loop for large documents.
*
* NOTE: This class will not work properly in Node. In that case, just use `LocalLinter`. */
export default class WorkerLinter implements Linter {
- private binary: string;
+ private binary: BinaryModule;
private worker: Worker;
private requestQueue: RequestItem[];
private working = true;
@@ -24,13 +24,14 @@ export default class WorkerLinter implements Linter {
constructor(init: LinterInit) {
this.binary = init.binary;
this.worker = new Worker();
+ console.log('worker', Worker, this.worker);
this.requestQueue = [];
// Fires when the worker sends 'ready'.
this.worker.onmessage = () => {
this.setupMainEventListeners();
- this.worker.postMessage(this.binary);
+ this.worker.postMessage(this.binary.url);
this.working = false;
this.submitRemainingRequests();
@@ -40,7 +41,7 @@ export default class WorkerLinter implements Linter {
private setupMainEventListeners() {
this.worker.onmessage = (e: MessageEvent) => {
const { resolve } = this.requestQueue.shift()!;
- deserializeArg(e.data).then((v) => {
+ this.binary.deserializeArg(e.data).then((v) => {
resolve(v);
this.working = false;
@@ -132,9 +133,13 @@ export default class WorkerLinter implements Linter {
/** Run a procedure on the remote worker. */
private async rpc(procName: string, args: any[]): Promise<any> {
+ console.log('rpc >', procName, args);
const promise = new Promise((resolve, reject) => {
this.requestQueue.push({
- resolve,
+ resolve: (v) => {
+ console.log('rpc <', procName, v);
+ resolve(v);
+ },
reject,
request: { procName, args }
});
@@ -146,16 +151,19 @@ export default class WorkerLinter implements Linter {
}
private async submitRemainingRequests() {
+ console.log('submitRemainingRequests', this.working);
if (this.working) {
return;
}
this.working = true;
+ console.log(this.requestQueue[0]);
if (this.requestQueue.length > 0) {
const { request } = this.requestQueue[0];
-
- this.worker.postMessage(await serialize(request));
+ const serialized = await this.binary.serialize(request);
+ console.log('submitRemainingRequests >', serialized);
+ this.worker.postMessage(serialized);
} else {
this.working = false;
}
diff --git a/packages/harper.js/src/WorkerLinter/worker.ts b/packages/harper.js/src/WorkerLinter/worker.ts
index 625b4152f..c41f1bc28 100644
--- a/packages/harper.js/src/WorkerLinter/worker.ts
+++ b/packages/harper.js/src/WorkerLinter/worker.ts
@@ -1,30 +1,31 @@
/// <reference lib="webworker" />
-import LocalLinter from '../LocalLinter';
-import { deserialize, serializeArg, SerializedRequest, isSerializedRequest } from './communication';
+import { isSerializedRequest, SerializedRequest } from '../binary';
+// @ts-expect-error: https://github.com/vitest-dev/vitest/pull/6569/files#diff-929cb96abb1c2e297c6711af0875db4ecdc700c54b824cc4ce7e0716657b28aeR375
+import { BinaryModule } from '../binary?worker_file&type=module';
+// @ts-expect-error
+import LocalLinter from '../LocalLinter?worker_file&type=module';
-const scope = self as unknown as ServiceWorkerGlobalScope;
+// Notify the main thread that we are ready
+self.postMessage('ready');
-scope.onmessage = (e) => {
- const binary = e.data;
- if (typeof binary !== 'string') {
- throw new TypeError(`Expected binary to be a string of url but got ${typeof binary}.`);
+self.onmessage = (e) => {
+ const binaryUrl = e.data;
+ if (typeof binaryUrl !== 'string') {
+ throw new TypeError(`Expected binary to be a string of url but got ${typeof binaryUrl}.`);
}
+ const binary = new BinaryModule(binaryUrl);
const linter = new LocalLinter({ binary });
async function processRequest(v: SerializedRequest) {
- const { procName, args } = await deserialize(v);
+ const { procName, args } = await binary.deserialize(v);
if (procName in linter) {
- // @ts-expect-error
const res = await linter[procName](...args);
- postMessage(await serializeArg(res));
+ postMessage(await binary.serializeArg(res));
}
}
- scope.onmessage = (e) => {
+ self.onmessage = (e) => {
isSerializedRequest(e.data) && processRequest(e.data);
};
};
-
-// Notify the main thread that we are ready
-postMessage('ready');
diff --git a/packages/harper.js/src/WorkerLinter/communication.test.ts b/packages/harper.js/src/binary.test.ts
similarity index 64%
rename from packages/harper.js/src/WorkerLinter/communication.test.ts
rename to packages/harper.js/src/binary.test.ts
index b8299cb62..5f192bafe 100644
--- a/packages/harper.js/src/WorkerLinter/communication.test.ts
+++ b/packages/harper.js/src/binary.test.ts
@@ -1,13 +1,12 @@
import { expect, test } from 'vitest';
-import { deserializeArg, serializeArg } from './communication';
import { Span } from 'harper-wasm';
-import LocalLinter from '../LocalLinter';
-import { binary } from '../binary';
+import LocalLinter from './LocalLinter';
+import { binary } from './binary';
test('works with strings', async () => {
const start = 'This is a string';
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end).toBe(start);
expect(typeof end).toBe(typeof start);
@@ -16,7 +15,7 @@ test('works with strings', async () => {
test('works with false booleans', async () => {
const start = false;
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end).toBe(start);
expect(typeof end).toBe(typeof start);
@@ -25,7 +24,7 @@ test('works with false booleans', async () => {
test('works with true booleans', async () => {
const start = true;
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end).toBe(start);
expect(typeof end).toBe(typeof start);
@@ -34,7 +33,7 @@ test('works with true booleans', async () => {
test('works with numbers', async () => {
const start = 123;
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end).toBe(start);
expect(typeof end).toBe(typeof start);
@@ -43,7 +42,7 @@ test('works with numbers', async () => {
test('works with Spans', async () => {
const start = Span.new(123, 321);
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end.start).toBe(start.start);
expect(end.len()).toBe(start.len());
@@ -57,7 +56,7 @@ test('works with Lints', async () => {
expect(start).not.toBeNull();
- const end = await deserializeArg(structuredClone(await serializeArg(start)));
+ const end = await binary.deserializeArg(structuredClone(await binary.serializeArg(start)));
expect(end.message()).toBe(start.message());
expect(end.lint_kind()).toBe(start.lint_kind());
diff --git a/packages/harper.js/src/binary.ts b/packages/harper.js/src/binary.ts
index 4dad4d7c0..b5ff58bc3 100644
--- a/packages/harper.js/src/binary.ts
+++ b/packages/harper.js/src/binary.ts
@@ -1,11 +1,181 @@
-import { default as _binary } from 'harper-wasm/harper_wasm_bg.wasm?url';
-import { default as _inlinedBinary } from 'harper-wasm/harper_wasm_bg.wasm?inline';
+import { default as binaryUrl } from 'harper-wasm/harper_wasm_bg.wasm?url';
+import { default as binaryInlinedUrl } from 'harper-wasm/harper_wasm_bg.wasm?inline';
+import type { Span, Suggestion, Linter as WasmLinter } from 'harper-wasm';
+import { invariant } from './utils';
+import { LintConfig } from './main';
-export async function loadBinary(binary: string) {
- const exports = await import('harper-wasm');
- await exports.default({ module_or_path: binary });
- return exports;
+const _loadedBinaryMap = new Map<string, typeof import('harper-wasm')>();
+
+export async function loadBinary(binary: string): Promise<typeof import('harper-wasm')> {
+ if (_loadedBinaryMap.has(binary)) {
+ return _loadedBinaryMap.get(binary)!;
+ } else {
+ const exports = await import('harper-wasm');
+ await exports.default({ module_or_path: binary });
+ _loadedBinaryMap.set(binary, exports);
+ return exports;
+ }
+}
+
+export type SerializableTypes =
+ | 'string'
+ | 'number'
+ | 'boolean'
+ | 'Suggestion'
+ | 'Lint'
+ | 'Span'
+ | 'Array'
+ | 'undefined';
+
+/** Serializable argument to a procedure to be run on the web worker. */
+export interface RequestArg {
+ json: string;
+ type: SerializableTypes;
+}
+
+/** An object that is sent to the web worker to request work to be done. */
+export interface SerializedRequest {
+ /** The procedure to be executed. */
+ procName: string;
+ /** The arguments to the procedure */
+ args: RequestArg[];
+}
+
+/** An object that is received by the web worker to request work to be done. */
+export interface DeserializedRequest {
+ /** The procedure to be executed. */
+ procName: string;
+ /** The arguments to the procedure */
+ args: any[];
+}
+
+export function isSerializedRequest(v: unknown): v is SerializedRequest {
+ return typeof v === 'object' && v !== null && 'procName' in v && 'args' in v;
+}
+
+/** This class aims to define the communication protocol between the main thread and the worker.
+ * Note that much of the complication here comes from the fact that we can't serialize function calls or referenced WebAssembly memory.*/
+export class BinaryModule {
+ private exported: Promise<typeof import('harper-wasm')>;
+
+ constructor(public url: string) {
+ this.exported = import('harper-wasm').then(async (exports) => {
+ await exports.default({ module_or_path: url });
+ return exports;
+ });
+ }
+
+ async applySuggestion(text: string, suggestion: Suggestion, span: Span): Promise<string> {
+ const exported = await this.exported;
+ return exported.apply_suggestion(text, span, suggestion);
+ }
+
+ async getDefaultLintConfigAsJSON(): Promise<string> {
+ const exported = await this.exported;
+ return exported.get_default_lint_config_as_json();
+ }
+
+ async getDefaultLintConfig(): Promise<LintConfig> {
+ const exported = await this.exported;
+ return exported.get_default_lint_config();
+ }
+
+ async toTitleCase(text: string): Promise<string> {
+ const exported = await this.exported;
+ return exported.to_title_case(text);
+ }
+
+ async setup(): Promise<void> {
+ const exported = await this.exported;
+ exported.setup();
+ }
+
+ async createLinter(): Promise<WasmLinter> {
+ const exported = await this.exported;
+ return exported.Linter.new();
+ }
+
+ async serializeArg(arg: any): Promise<RequestArg> {
+ const { Lint, Span, Suggestion } = await this.exported;
+
+ if (Array.isArray(arg)) {
+ return {
+ json: JSON.stringify(await Promise.all(arg.map((a) => this.serializeArg(a)))),
+ type: 'Array'
+ };
+ }
+
+ const argType = typeof arg;
+ switch (argType) {
+ case 'string':
+ case 'number':
+ case 'boolean':
+ case 'undefined':
+ return { json: JSON.stringify(arg), type: argType };
+ }
+
+ if (arg.to_json != undefined) {
+ const json = arg.to_json();
+ let type: SerializableTypes | undefined = undefined;
+
+ if (arg instanceof Lint) {
+ type = 'Lint';
+ } else if (arg instanceof Suggestion) {
+ type = 'Suggestion';
+ } else if (arg instanceof Span) {
+ type = 'Span';
+ }
+
+ if (type == undefined) {
+ throw new Error('Unhandled case');
+ }
+
+ return { json, type };
+ }
+
+ throw new Error('Unhandled case');
+ }
+
+ async serialize(req: DeserializedRequest): Promise<SerializedRequest> {
+ return {
+ procName: req.procName,
+ args: await Promise.all(req.args.map((arg) => this.serializeArg(arg)))
+ };
+ }
+
+ async deserializeArg(requestArg: RequestArg): Promise<any> {
+ const { Lint, Span, Suggestion } = await this.exported;
+
+ switch (requestArg.type) {
+ case 'undefined':
+ return undefined;
+ case 'boolean':
+ case 'number':
+ case 'string':
+ return JSON.parse(requestArg.json);
+ case 'Suggestion':
+ return Suggestion.from_json(requestArg.json);
+ case 'Lint':
+ return Lint.from_json(requestArg.json);
+ case 'Span':
+ return Span.from_json(requestArg.json);
+ case 'Array':
+ const parsed = JSON.parse(requestArg.json);
+ invariant(Array.isArray(parsed));
+ return await Promise.all(parsed.map((arg) => this.deserializeArg(arg)));
+ default:
+ throw new Error(`Unhandled case: ${requestArg.type}`);
+ }
+ }
+
+ async deserialize(request: SerializedRequest): Promise<DeserializedRequest> {
+ return {
+ procName: request.procName,
+ args: await Promise.all(request.args.map((arg) => this.deserializeArg(arg)))
+ };
+ }
}
-export const binary: string = _binary;
-export const inlinedBinary: string = _inlinedBinary;
+export const binary = new BinaryModule(binaryUrl);
+
+export const binaryInlined = new BinaryModule(binaryInlinedUrl);
diff --git a/packages/harper.js/src/main.ts b/packages/harper.js/src/main.ts
index 4cf97be58..e9e7ab8d6 100644
--- a/packages/harper.js/src/main.ts
+++ b/packages/harper.js/src/main.ts
@@ -1,15 +1,24 @@
-export { Lint, Span, Suggestion, SuggestionKind } from 'harper-wasm';
+export type { Lint, Span, Suggestion, SuggestionKind } from 'harper-wasm';
export type { default as Linter, LinterInit } from './Linter';
export { default as LocalLinter } from './LocalLinter';
export { default as WorkerLinter } from './WorkerLinter';
-export { binary, inlinedBinary } from './binary';
+export {
+ type DeserializedRequest,
+ type RequestArg,
+ type SerializableTypes,
+ type SerializedRequest,
+ BinaryModule,
+ binary,
+ binaryInlined,
+ isSerializedRequest
+} from './binary';
/** A linting rule configuration dependent on upstream Harper's available rules.
* This is a record, since you shouldn't hard-code the existence of any particular rules and should generalize based on this struct. */
export type LintConfig = Record<string, boolean | undefined>;
/** The option used to configure the parser for an individual linting operation. */
-export type LintOptions = {
+export interface LintOptions {
/** The markup language that is being passed. Defaults to `markdown`. */
language?: 'plaintext' | 'markdown';
-};
+}
diff --git a/packages/harper.js/src/utils.ts b/packages/harper.js/src/utils.ts
new file mode 100644
index 000000000..00d71dd3c
--- /dev/null
+++ b/packages/harper.js/src/utils.ts
@@ -0,0 +1,5 @@
+export function invariant(condition: unknown, message?: string): asserts condition {
+ if (!condition) {
+ throw new Error(message ?? 'Invariant failed');
+ }
+}
diff --git a/packages/harper.js/vite.config.js b/packages/harper.js/vite.config.js
index 1fa0af05f..8be7ec3a9 100644
--- a/packages/harper.js/vite.config.js
+++ b/packages/harper.js/vite.config.js
@@ -27,10 +27,10 @@ export default defineConfig({
}),
],
worker: {
- format: 'es',
+ format: 'iife',
rollupOptions: {
output: {
- inlineDynamicImports: true
+ // inlineDynamicImports: true
}
}
},
@@ -42,8 +42,8 @@ export default defineConfig({
test: {
browser: {
provider: 'playwright',
- enabled: true,
headless: true,
+ enabled: true,
screenshotFailures: false,
instances: [
{ browser: 'chromium' },