Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(harper.js): expose stats logging and summarization
Elijah Potter5f34e7fa1f3c
diff --git a/harper-stats/src/summary.rs b/harper-stats/src/summary.rsindex ae4dd7962..c27aef956 100644--- a/harper-stats/src/summary.rs+++ b/harper-stats/src/summary.rs@@ -3,7 +3,7 @@ use std::{collections::HashMap, fmt::Display};use harper_core::linting::{LintGroupConfig, LintKind};pub struct Summary {- pub lint_counts: HashMap<LintKind, usize>,+ pub lint_counts: HashMap<LintKind, u32>,pub final_config: LintGroupConfig,}@@ -24,7 +24,7 @@ impl Summary {}/// Get the count for a particular lint kind.- pub fn get_count(&self, kind: LintKind) -> usize {+ pub fn get_count(&self, kind: LintKind) -> u32 {self.lint_counts.get(&kind).copied().unwrap_or(0)}}diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rsindex e831c4b6b..11cb9e917 100644--- a/harper-wasm/src/lib.rs+++ b/harper-wasm/src/lib.rs@@ -1,6 +1,8 @@#![doc = include_str!("../README.md")]+use std::collections::HashMap;use std::convert::Into;+use std::io::Cursor;use std::sync::Arc;use harper_core::language_detection::is_doc_likely_english;@@ -16,9 +18,6 @@ use wasm_bindgen::JsValue;use wasm_bindgen::prelude::wasm_bindgen;/// Setup the WebAssembly module's logging.-///-///-/// painful.#[wasm_bindgen(start)]pub fn setup() {console_error_panic_hook::set_once();@@ -169,6 +168,19 @@ impl Linter {Ok(())}+ pub fn summarize_stats(&self) -> JsValue {+ serde_wasm_bindgen::to_value(+ &self+ .stats+ .summarize()+ .lint_counts+ .iter()+ .map(|(key, value)| (key.to_string_key(), *value))+ .collect::<HashMap<_, _>>(),+ )+ .unwrap()+ }+/// Get a Record containing the descriptions of all the linting rules.pub fn get_lint_descriptions_as_object(&self) -> JsValue {let serializer = serde_wasm_bindgen::Serializer::json_compatible();@@ -295,6 +307,23 @@ impl Linter {Ok(source.iter().collect())}++ pub fn generate_stats_file(&self) -> String {+ let mut output = Vec::new();+ self.stats.write(&mut output).unwrap();++ String::from_utf8(output).unwrap()+ }++ pub fn import_stats_file(&mut self, file: String) -> Result<(), String> {+ let data = file.as_bytes();+ let mut read = Cursor::new(data);++ let mut new_stats = Stats::read(&mut read).map_err(|err| err.to_string())?;+ self.stats.records.append(&mut new_stats.records);++ Ok(())+ }}#[wasm_bindgen]diff --git a/packages/harper.js/src/Linter.test.ts b/packages/harper.js/src/Linter.test.tsindex 0ddfba9d9..97e438484 100644--- a/packages/harper.js/src/Linter.test.ts+++ b/packages/harper.js/src/Linter.test.ts@@ -187,6 +187,32 @@ for (const [linterName, Linter] of Object.entries(linters)) {expect(lints).toHaveLength(0);});++ test(`${linterName} can save and restore stat records`, async () => {+ const linter = new Linter({ binary });+ linter.setup();++ const source = 'This is an test.';++ const lints = await linter.lint(source);++ let lint = lints[0];++ expect(lint).not.toBeNull()++ let sug = lint.suggestions()[0];++ expect(sug).not.toBeNull()++ const applied = await linter.applySuggestion(lint, sug);++ expect(applied).toBe("This is a test.");++ const stats = await linter.generateStatsFile();++ const newLinter = new Linter({ binary });+ await newLinter.importStatsFile(stats);+ });}test('Linters have the same config format', async () => {diff --git a/packages/harper.js/src/Linter.ts b/packages/harper.js/src/Linter.tsindex 20a1261e2..661b2f9a1 100644--- a/packages/harper.js/src/Linter.ts+++ b/packages/harper.js/src/Linter.ts@@ -77,6 +77,15 @@ export default interface Linter {/** Get the dialect of English this linter was constructed for. */setDialect(dialect: Dialect): Promise<void>;++ /** Summarize the linter's usage statistics. */+ summarizeStats(): Promise<Record<string, number>>;++ /** Generate a statistics log file you can save to permanent storage. */+ generateStatsFile(): Promise<string>;++ /** Import a statistics log file. */+ importStatsFile(statsFile: string): Promise<void>;}export interface LinterInit {diff --git a/packages/harper.js/src/LocalLinter.ts b/packages/harper.js/src/LocalLinter.tsindex e80f02858..335759dc1 100644--- a/packages/harper.js/src/LocalLinter.ts+++ b/packages/harper.js/src/LocalLinter.ts@@ -142,4 +142,19 @@ export default class LocalLinter implements Linter {return Promise.resolve();}++ async summarizeStats(): Promise<Record<string, number>> {+ const inner = await this.inner;+ return inner.summarize_stats();+ }++ async generateStatsFile(): Promise<string> {+ const inner = await this.inner;+ return inner.generate_stats_file();+ }++ async importStatsFile(statsFile: string): Promise<void> {+ const inner = await this.inner;+ return inner.import_stats_file(statsFile);+ }}diff --git a/packages/harper.js/src/WorkerLinter/index.ts b/packages/harper.js/src/WorkerLinter/index.tsindex b3136d7bc..3e1869724 100644--- a/packages/harper.js/src/WorkerLinter/index.ts+++ b/packages/harper.js/src/WorkerLinter/index.ts@@ -149,6 +149,18 @@ export default class WorkerLinter implements Linter {return this.rpc('setDialect', [dialect]);}+ summarizeStats(): Promise<Record<string, number>> {+ return this.rpc('summarizeStats', []);+ }++ generateStatsFile(): Promise<string> {+ return this.rpc('generateStatsFile', []);+ }++ importStatsFile(statsFile: string): Promise<void> {+ return this.rpc('importStatsFile', [statsFile]);+ }+/** Run a procedure on the remote worker. */private async rpc(procName: string, args: unknown[]): Promise<any> {const promise = new Promise((resolve, reject) => {