Skip to content

API Reference ​

This page documents the JavaScript / WASM binding of Suzume, published to npm as @libraz/suzume. Python, Go, C/C++, and the two command-line interfaces have separate guides.

Suzume Class ​

The main class for Japanese tokenization.

Suzume.create(options?) ​

Creates a new Suzume instance.

typescript
static async create(options?: SuzumeOptions & RuntimeOptions): Promise<Suzume>

RuntimeOptions:

OptionTypeDefaultDescription
wasmPathstringundefinedURL or path of suzume.wasm, for bundlers that move it
freshWasmModulebooleanfalseInstantiate an isolated WASM runtime instead of using the shared cached runtime

SuzumeOptions:

OptionTypeDefaultDescription
preserveVubooleantrueKeeps the ヴ series as written; false folds it to the バ row (ヴァイオリン → バイオリン)
preserveCasebooleantruePreserve case (don't lowercase ASCII)
preserveSymbolsbooleanfalsePreserve punctuation-like SYMBOL tokens; emoji and content-bearing symbols remain OTHER regardless of this option
mode'normal' | 'search' | 'split''normal'Analysis mode. Use search or split for search-oriented segmentation
lemmatizebooleantrueReplaces source base forms with corrected ones. When false, tokens keep their source base form; POS and conjugation annotations are computed either way (details)
mergeCompoundsbooleanfalseMerge consecutive noun compounds where possible
skipBundledUserDictionarybooleanfalseSkip automatic loading of the bundled user dictionary
skipCoreDictionarybooleanfalseSkip automatic loading of the bundled core dictionary (L2)
reportScorerConfigbooleanfalseAdd scorer configuration diagnostics to dictionaryWarnings
skipEnvConfigbooleanfalseIgnore native scorer configuration environment variables; has no effect in the WASM build
scorerOptionsstring | Record<string, unknown> | nullundefinedFinal-priority scorer overrides, supplied as JSON text or an object serialized to JSON; null means none

Boolean options are validated, not coerced: preserveVu: 'false' throws invalid preserve_vu: "false" (expected a boolean). A null or unrecognized mode is invalid as well. Unknown option keys are ignored at runtime, while TypeScript rejects them at compile time. Every invalid option rejects Suzume.create() with a SuzumeError (see Error Handling).

Currency and unit signs, arrows, mathematical or technical marks, and emoji carry text content, so the default analysis keeps them as OTHER. Set preserveSymbols: true only when punctuation-like tokens such as 。 must also appear in the result.

Returns: Promise<Suzume>

Example:

typescript
// Default usage
const defaultSuzume = await Suzume.create()
defaultSuzume.destroy()

// Custom WASM path
const customWasmSuzume = await Suzume.create({ wasmPath: '/path/to/suzume.wasm' })
customWasmSuzume.destroy()

// With options
const customSuzume = await Suzume.create({
  preserveSymbols: true,
  preserveVu: false,
  mode: 'normal',
  mergeCompounds: true, // merges noun compounds without search mode
  scorerOptions: {
    unary: { user_dict_bonus: -3.0 },
  },
})
customSuzume.destroy()

Analysis modes:

The mode option controls how text is segmented:

ModeSegmentation
normalBalanced segmentation for general use (default)
searchMerges runs of consecutive nouns into larger search units, with formal nouns excluded
splitSkips the join rules and the optional noun-merging step

In normal mode, mergeCompounds controls noun-compound merging. search enables merging, while split disables it. Choosing a Mode defines each mode.

scorerOptions is validated during construction. Malformed JSON text rejects Suzume.create() with a SuzumeError (Parse, operation create), and an object that cannot be serialized, including one holding NaN, Infinity, -Infinity or undefined at any depth, fails with invalid scorer_options: not serializable as JSON. reportScorerConfig: true records the active configuration in dictionaryWarnings. The WASM build does not read the native scorer environment layer, so skipEnvConfig has no effect in this binding. The WASM binding has no dataDirectory option; the bundled dictionaries are always the ones inside the WASM module (Dictionary Layers compares all bindings).

Scorer options ​

scorerOptions overrides numbers the scorer adds to the cost of a candidate path. The path with the lowest total cost wins, so a negative value favors what it applies to and a positive value penalizes it. Only the keys you give change. An unknown section or key rejects create() with invalid scorer options: Unknown scorer option: unary.foo. The same JSON is accepted by every binding (scorer_options in Python and C++, ScorerOptions in Go).

JSON pathKeys (default)Controls
unaryuser_dict_bonus (-2.0), noun_prior (0.0), verb_prior (0.2), adj_prior (0.3), adv_prior (0.2)user_dict_bonus is added to every candidate from a user dictionary. The priors supply base costs for specific join and split candidates. For example, noun_prior affects some noun joins and dictionary splits, and adj_prior affects adjective candidates formed with a negative prefix, such as 不十分.
candidates.joincompound_verb_bonus (-0.8), verified_v1_bonus (-0.3), verified_noun_bonus (-0.3)Bonuses for join rule candidates
candidates.splitalpha_kanji_bonus (-0.3), alpha_katakana_bonus (-0.3), digit_kanji_1_bonus (-0.2), digit_kanji_2_bonus (-0.2), duration_period_bonus (-0.3), digit_kanji_3_penalty (0.5), dict_split_bonus (-0.5), split_base_cost (1.0), noun_verb_split_bonus (-1.0), verified_verb_bonus (-0.8)Costs of split candidates: letters beside kanji or katakana, numbers with counters, dictionary words and noun + verb
bigramnoun_to_suffix, prefix_to_noun, prefix_to_verb, pron_to_aux, verb_to_verb, verb_to_noun, verb_to_aux, adj_to_aux, adj_to_verb, adj_to_adj, part_to_verb, part_to_noun, aux_to_part, aux_to_auxThe connection cost between a POS and the one after it, replacing the built-in table value
verb_candidates, inflection22 and 28 tuning keysConfidence and cost of verb and conjugation candidates; the field names are listed in scorer_options_loader.cpp in the Suzume source

The native environment layer maps SUZUME_SCORER_{SECTION}_{KEY} onto the same keys, with JOIN, SPLIT, UNARY, BIGRAM, VERB and INFL as the sections; scorerOptions is applied after it.

For example, a lone 都庁 user-dictionary row does not split 東京都庁前 (When a Row Does Not Win). With scorerOptions: { unary: { user_dict_bonus: -4 } } the row wins and the result is 東京 / 都庁 / 前. The option applies to every user-dictionary entry, so change it only when the entries you load are meant to override the built-in analysis.

Shared WASM runtime ​

By default, calls with the same wasmPath share one cached WASM runtime. Each Suzume object gets its own analyzer handle and options inside that runtime's linear memory.

One cached runtime, many handles
Three Suzume objects on the JS heap and their handles in WASM linear memory. A and B use the shared runtime; C has its own through freshWasmModule. A is freed by FinalizationRegistry after GC, B immediately by destroy(). An out-of-memory abort ends every handle on the shared runtime.JS heapWhat the GC tracksWASM linear memoryShared runtimecached per wasmPathIsolated runtimeSuzume Acreate()handle Anative state + optionsSuzume Bcreate()handle BfreedSuzume CfreshWasmModulehandle Cnative state + optionsFinalizationRegistryafter GCdestroy()freed immediatelyOut-of-memory abortstops every handleon this runtimeSeparate linear memoryNot affected by that abort
Linear memory belongs to the runtime, so destroy() frees one handle while an abort ends them all. The GC sees only the JS objects; without destroy(), the native state waits for a collection that WASM memory use does not prompt.

Set freshWasmModule: true when an instance must have an isolated runtime. The standalone version() function uses the same cache unless it also receives freshWasmModule: true.


mode ​

Reads or changes the analysis mode without reloading dictionaries. Mode names are case-sensitive and lowercase; any other value throws a SuzumeError (InvalidInput) such as invalid mode: "fast" (expected one of: normal, search, split).

typescript
get mode(): 'normal' | 'search' | 'split'
set mode(value: 'normal' | 'search' | 'split')
typescript
console.log(suzume.mode) // "normal"
suzume.mode = 'split'

analyze(text) ​

Analyzes Japanese text and returns an array of tokens.

typescript
analyze(text: string): readonly Morpheme[]
ParameterTypeDescription
textstringJapanese text to analyze

Returns: readonly Morpheme[]

Example:

typescript
const result = suzume.analyze('東京に行きました')

// Result:
// [
//   { surface: '東京', pos: 'NOUN', posJa: '名詞', ... },
//   { surface: 'に', pos: 'PARTICLE', posJa: '助詞', ... },
//   { surface: '行き', pos: 'VERB', posJa: '動詞', ... },
//   { surface: 'まし', pos: 'AUX', posJa: '助動詞', ... },
//   { surface: 'た', pos: 'AUX', posJa: '助動詞', ... }
// ]

analyzeWithNormalizedText(text) ​

Analyzes text and returns both the morphemes and the exact normalized string their offsets refer to.

typescript
interface AnalysisResult {
  readonly normalizedText: string
  readonly morphemes: readonly Morpheme[]
}

analyzeWithNormalizedText(text: string): AnalysisResult

Use the UTF-16 offsets when slicing a JavaScript string:

typescript
const { normalizedText, morphemes } =
  suzume.analyzeWithNormalizedText('🎉𠮷字を読む')

for (const morpheme of morphemes) {
  const surface = normalizedText.slice(
    morpheme.startUtf16,
    morpheme.endUtf16,
  )
  console.log(surface)
}

start and end are Unicode code-point offsets into normalizedText. startUtf16 and endUtf16 are JavaScript UTF-16 code-unit offsets and can be passed directly to String.prototype.slice(). The two sets differ before or across characters outside the Basic Multilingual Plane, including many emoji and rare kanji.

Offsets refer to the normalized text, which may differ from the input; see Offsets for the concept. Content-bearing symbols and emoji stay in the default output as OTHER, so their ranges remain represented even when preserveSymbols is false.


generateTags(text, options?) ​

Generates tags for search indexing, classification, and content analysis. By default it returns content words (nouns, verbs, adjectives, and adverbs) while filtering out particles, auxiliaries, formal nouns, and low-information words.

typescript
generateTags(text: string, options?: TagOptions): readonly Tag[]

Tag:

PropertyTypeDescription
tagstringTag text (surface or base form depending on useBaseForm)
posPosLabelPart of speech (NOUN, VERB, ADJ, ADV, etc.)
ParameterTypeDescription
textstringJapanese text to extract tags from
optionsTagOptionsOptional tag generation settings

TagOptions:

OptionTypeDefaultDescription
posFilterTagPosLabel | readonly TagPosLabel[]undefined (all)POS categories to include, as one name or an array; undefined, null and an empty array include every filterable category
excludeBasicbooleanfalseExclude basic verbs/words with hiragana-only base form
useBaseFormbooleantrueUse the base form instead of the surface form
minLengthnumber2Minimum tag length in characters; an integer from 0 to 4294967295
maxTagsnumber0Maximum number of tags (0 = unlimited); an integer from 0 to 4294967295
excludeParticlesbooleantrueExclude particles; applies only when PARTICLE is not named in posFilter
excludeAuxiliariesbooleantrueExclude auxiliaries; applies only when AUX is not named in posFilter
excludeFormalNounsbooleantrueExclude formal nouns such as こと and もの
excludeLowInfobooleantrueExclude low-information words
removeDuplicatesbooleantrueRemove duplicate tags

TagPosLabel is 'NOUN' | 'VERB' | 'ADJ' | 'ADV' | 'PARTICLE' | 'AUX', exported from the package entry (import type { TagPosLabel } from '@libraz/suzume'). Names are exact and case-sensitive, and a NOUN filter also admits PRON. The generator always considers nouns (including pronouns), verbs, adjectives, adverbs, particles, and auxiliaries; conjunctions, symbols, and other POS categories are excluded even when the filter is empty. A non-empty posFilter adds a whitelist over those filterable categories. Pronouns can still be removed by excludeLowInfo. Naming PARTICLE or AUX returns those tags even though excludeParticles and excludeAuxiliaries default to true.

Invalid values fail the whole call with a SuzumeError (InvalidInput) that lists the accepted names, for example invalid pos_filter: "adjective" (expected one of: NOUN, VERB, ADJ, ADV, PARTICLE, AUX). Invalid minLength or maxTags values (fractions, NaN, negatives) throw invalid min_length: 2.5 (expected an integer from 0 to 4294967295).

Returns: readonly Tag[]

Examples:

typescript
// Basic usage
const tags = suzume.generateTags('東京スカイツリーに行きました')
// [{ tag: '東京', pos: 'NOUN' },
//  { tag: 'スカイツリー', pos: 'NOUN' },
//  { tag: '行く', pos: 'VERB' }]

// Nouns only
const nouns = suzume.generateTags('美しい花が静かに咲いている', {
  posFilter: ['NOUN'],
  minLength: 1,
})
// [{ tag: '花', pos: 'NOUN' }]

// Particles and auxiliaries
const functionWords = suzume.generateTags('花が咲きます', {
  posFilter: ['PARTICLE', 'AUX'],
  minLength: 1,
})
// [{ tag: 'が', pos: 'PARTICLE' },
//  { tag: 'ます', pos: 'AUX' }]

// Exclude basic verbs (hiragana-only base form like する, いる, ある, なる...)
const tags2 = suzume.generateTags('新しいプロジェクトを開始して管理する', {
  excludeBasic: false
})
// [{ tag: '新しい', pos: 'ADJ' },
//  { tag: 'プロジェクト', pos: 'NOUN' },
//  { tag: '開始', pos: 'NOUN' },
//  { tag: 'する', pos: 'VERB' },
//  { tag: '管理', pos: 'NOUN' }]

const tags3 = suzume.generateTags('新しいプロジェクトを開始して管理する', {
  excludeBasic: true
})
// [{ tag: '新しい', pos: 'ADJ' },
//  { tag: 'プロジェクト', pos: 'NOUN' },
//  { tag: '開始', pos: 'NOUN' },
//  { tag: '管理', pos: 'NOUN' }]
// 'する' is excluded (base form is hiragana-only)

// Limit results
const top3 = suzume.generateTags('東京タワーと東京スカイツリーを見学しました', {
  maxTags: 3
})
// [{ tag: '東京', pos: 'NOUN' },
//  { tag: 'タワー', pos: 'NOUN' },
//  { tag: 'スカイツリー', pos: 'NOUN' }]

excludeBasic

excludeBasic: true filters out words whose base form is written entirely in hiragana. It removes entries such as する, いる, ある, なる, いく, and くる while keeping kanji-containing entries such as 開始, 管理, and 確認.

Each filter step removes its own kind of token
The 22 tokens of the sample sentence pass through the generateTags steps and leave the tags 読む, ある, 東京 and 買う. Particles, auxiliaries, a formal noun, a conjunction, a determiner, short words and duplicates drop at their own steps.analyze(): 22 tokensその本を読んだことがあるしかし東京で東京の本を買ったので読んでみた1ParticlesexcludeParticlesをがでのをのでで15 left2AuxiliariesexcludeAuxiliariesだたみた11 left3Formal nounsexcludeFormalNounsこと10 left4Low-info wordsexcludeLowInfoこと is already gone at step 310 left5Conjunctionsalwaysしかし9 left6Symbolsalwaysno symbol tokens by default9 left7POS filterposFilterその8 left9Tag textuseBaseForm読ん → 読む 買っ → 買う8 left10Min lengthminLength本本6 left11DeduplicationremoveDuplicates東京読ん4 leftgenerateTags() result読むある東京買う
Measured with default options. Most particles are one character, so lifting the exclusion alone still leaves them to the min-length step; only ので shows up in the tags. こと is both a formal noun and a low-info word, so both options must be lifted to keep it. Steps 8 and 12 (excludeBasic, maxTags) are inactive by default.
posFilter. None selected keeps every part of speech
Loading WASM...
Filter pipeline

The tag generator applies these filters in order:

StepFilterBehavior
1ParticlesExcluded when excludeParticles is true (default), unless PARTICLE is named in a non-empty posFilter
2AuxiliariesExcluded when excludeAuxiliaries is true (default), unless AUX is named in a non-empty posFilter
3Formal nounsExcluded when excludeFormalNouns is true (default)
4Low-info wordsExcluded when excludeLowInfo is true (default)
5ConjunctionsAlways excluded
6SymbolsAlways excluded
7POS filterIf posFilter is non-empty, only matching categories pass, and a named POS lifts its own particle or auxiliary exclusion; an empty or undefined filter still admits only nouns (including pronouns), verbs, adjectives, adverbs, particles, and auxiliaries
8Basic wordsIf excludeBasic: true, words with hiragana-only base form are excluded
9Tag textThe base form or surface is selected according to useBaseForm
10Min lengthTags shorter than minLength Unicode characters are excluded
11DeduplicationDuplicate tags are removed when removeDuplicates is true
12Result limitGeneration stops at maxTags; 0 is unlimited

loadUserDictionary(data) ​

Adds source user dictionary entries to the analyzer. Loads are cumulative until clearUserDictionaries() is called, and a failed load leaves earlier dictionaries installed.

typescript
loadUserDictionary(data: string | Uint8Array): number
ParameterTypeDescription
datastring | Uint8ArrayDictionary entries in the TSV format, as text or as its UTF-8 bytes

Returns: number — the count of expanded entries installed, always at least 1. One source row can install multiple entries when Suzume expands conjugated forms, so the count can exceed the number of rows.

Throws: SuzumeError with the native code and text, operation load_user_dictionary, when the source cannot be loaded, including empty or entry-less text. Bytes that are not valid UTF-8 fail with Parse and Dictionary entry is not valid UTF-8 at line N. Any other argument type throws InvalidInput, for example invalid dictionary: 123 (expected a string or binary data). Nonfatal skipped-row and expansion diagnostics are appended to dictionaryWarnings.

Format: surface<TAB>POS[<TAB>conj_type][<TAB>base_form]. The conjugation type is optional; specify it when inflected forms should be expanded. A third field that is not a recognized conjugation type is treated as the base form. A numeric third field is an error; to use a numeric base form, write it in column 4 and leave column 3 empty. Comma-delimited rows and rows in the old four-column layout fail with a Parse error. See User Dictionaries for the complete format.

Example:

typescript
// Single entry
suzume.loadUserDictionary('ChatGPT\tNOUN\n') // 1

// Multiple entries
suzume.loadUserDictionary(`
ChatGPT	NOUN
スカイツリー	NOUN
DeepL	NOUN
`) // 3

// Conjugating entry: the count includes the expanded forms
suzume.loadUserDictionary('検査する\tVERB\tSURU\n') // 7

// UTF-8 bytes, for example read from a file
suzume.loadUserDictionary(new TextEncoder().encode('ChatGPT\tNOUN\n')) // 1

loadBinaryDictionary(data) ​

Adds a compiled binary dictionary (.dic) at runtime. Binary and source dictionary loads are cumulative.

typescript
loadBinaryDictionary(data: Uint8Array): number
ParameterTypeDescription
dataUint8ArrayBinary dictionary data (.dic format)

Returns: number — the count of entries installed, always at least 1.

Throws: SuzumeError with code DictionaryLoadFailed and the native text (for example Dictionary file too small) when the bytes cannot be loaded.

Example:

typescript
// Load from file (Node.js)
import { readFile } from 'fs/promises'
const dictData = new Uint8Array(await readFile('custom.dic'))
suzume.loadBinaryDictionary(dictData)

// Load from URL (Browser)
const response = await fetch('/dictionaries/custom.dic')
const browserDictData = new Uint8Array(await response.arrayBuffer())
suzume.loadBinaryDictionary(browserDictData)

Binary vs source dictionaries

Binary dictionaries (.dic) load faster than source TSV. Use suzume-cli dict compile to compile a TSV dictionary.


clearUserDictionaries() ​

Removes dictionaries loaded by the caller and clears their runtime warnings. The automatically loaded bundled user dictionary, if present, remains installed. Throws SuzumeError (operation clear_user_dictionaries) after destroy().

typescript
clearUserDictionaries(): void

hasCoreDictionary ​

Reports whether the bundled core dictionary (L2) is loaded.

typescript
get hasCoreDictionary(): boolean

This is false when the analyzer was created with skipCoreDictionary: true or when automatic core-dictionary loading failed.


version(options?) ​

Returns the version without creating an analyzer handle.

typescript
import { version } from '@libraz/suzume'

const current = await version()
console.log(current) // semantic-version string
typescript
function version(options?: RuntimeOptions): Promise<string>

The function is asynchronous because it must instantiate or retrieve the WASM runtime. If the module cannot be loaded, it rejects with a SuzumeError (Internal, operation version).


dictionaryWarnings ​

Returns nonfatal diagnostics recorded for this analyzer, or an empty array when there are none.

typescript
get dictionaryWarnings(): readonly string[]

The array contains constructor-time dictionary-loading diagnostics, optional scorer-configuration diagnostics, and warnings from successful source dictionary loads, such as skipped records or duplicate expanded entries. clearUserDictionaries() removes warnings from caller-loaded source dictionaries while retaining construction diagnostics. A fatal load failure is always reported as a SuzumeError thrown by the loading method.


wasmMemoryBytes() ​

Returns the current size of this runtime's WebAssembly linear memory in bytes.

typescript
wasmMemoryBytes(): number

Instances on the shared runtime report the same underlying memory size. Throws SuzumeError after destroy().


destroy() ​

Releases this analyzer handle and its allocations. The shared WASM runtime remains cached for other and future instances.

typescript
destroy(): void

After destroy(), every member that needs the handle (analyze, analyzeWithNormalizedText, generateTags, the dictionary methods, mode, dictionaryWarnings, hasCoreDictionary, wasmMemoryBytes) throws a SuzumeError with code InvalidInput and the message Suzume instance has been released. destroy() itself is idempotent. Call it explicitly when you are done with an instance. See Memory Management for what happens if you do not.

Example:

typescript
const suzume = await Suzume.create()
// ... use suzume ...
suzume.destroy() // Free resources immediately

Morpheme Interface ​

Represents a single linguistic token.

typescript
interface Morpheme {
  readonly surface: string      // Surface form (as appears in text)
  readonly pos: PosLabel        // Part of speech (English)
  readonly baseForm: string     // Base form
  readonly posJa: string        // Part of speech (Japanese)
  readonly conjType: string | null  // Conjugation type; null if none applies
  readonly conjForm: string | null  // Conjugation form; null if not conjugatable
  readonly extendedPos: string  // Stable extended POS code (e.g. "VERB_連用")
  readonly start: number        // Start Unicode code-point offset in normalized text
  readonly end: number          // End Unicode code-point offset in normalized text
  readonly startUtf16: number   // Start JavaScript UTF-16 offset
  readonly endUtf16: number     // End JavaScript UTF-16 offset
  readonly isUserDict: boolean
  readonly isFormalNoun: boolean
  readonly isLowInfo: boolean
  readonly isUnknown: boolean
  readonly isFromDictionary: boolean
  readonly score: number
}

Properties ​

PropertyTypeDescriptionExample
surfacestringSurface form as it appears in text"食べ"
posPosLabelPart of speech in English"VERB"
baseFormstringBase form"食べる"
posJastringPart of speech in Japanese"動詞"
conjTypestring | nullConjugation type"一段"
conjFormstring | nullConjugation form"連用形"
extendedPosstringStable extended POS code"VERB_連用"
startnumberStart Unicode code-point offset in normalized text0
endnumberEnd Unicode code-point offset in normalized text2
startUtf16numberStart JavaScript UTF-16 offset in normalized text0
endUtf16numberEnd JavaScript UTF-16 offset in normalized text2
isUserDictbooleanTrue when matched from a user dictionaryfalse
isFormalNounbooleanTrue for formal nouns such as こと and ものfalse
isLowInfobooleanTrue when marked as low information for tag generationfalse
isUnknownbooleanTrue when generated as an unknown-word candidatetrue
isFromDictionarybooleanTrue when matched from any dictionaryfalse
scorenumberCost the analyzer assigned to the token; lower is more likely, and values are not comparable across inputs-0.17

conjType and conjForm are null for tokens that do not conjugate (nouns, particles). They can also be null or partly filled for tokens that do: conjForm may be set while conjType is null, as for the adjective 美しかっ (conjForm 連用形) or the auxiliary いる in 見ている (AUX_継続, conjForm 終止形). Treat a null conjType as "no conjugation type available", not as "does not conjugate"; use pos, extendedPos, and conjForm to judge the form.

Part-of-Speech Values ​

PosLabel is the union of the coarse pos values, and is the type of both Morpheme.pos and Tag.pos. The coarse and extended label tables, shared by every binding, are on Part-of-Speech Labels.

Error Handling ​

Every error the package throws is a SuzumeError, which extends Error. It carries a stable code, the operation that raised it, and, when it wraps another error, a cause. Native failures keep the library's own message text; the package adds no prefix.

typescript
const ErrorCode = {
  Success: 0,
  InvalidUtf8: 1,
  DictionaryLoadFailed: 2,
  FileNotFound: 3,
  Parse: 4,
  OutOfMemory: 5,
  InvalidInput: 6,
  Internal: 7,
  Unknown: 255,
} as const
type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]

class SuzumeError extends Error {
  readonly code: ErrorCode
  readonly operation?: SuzumeOperation
  readonly cause?: unknown
  constructor(
    message: string,
    code: number = ErrorCode.Internal,
    options?: { operation?: SuzumeOperation; cause?: unknown },
  )
}

ErrorCode is a plain object plus a union type, so there is no reverse lookup from number to name; read error.code and compare it with the named constants. Values 0 to 7 mirror the C ABI; Unknown (255) is reserved for the binding, and any other number passed to the constructor becomes Unknown.

operation is one of the snake_case SuzumeOperation tokens shared with the other bindings: create, analyze, generate_tags, load_user_dictionary, load_binary_dictionary, clear_user_dictionaries, mode, version, dictionary_warnings, has_core_dictionary and wasm_memory_bytes. A setter carries its getter's token, so assigning an invalid mode reports mode.

typescript
import { ErrorCode, Suzume, SuzumeError } from '@libraz/suzume'

let suzume: Suzume | undefined
try {
  suzume = await Suzume.create()
  suzume.analyze('\uD800') // unpaired UTF-16 surrogate
} catch (error) {
  if (error instanceof SuzumeError && error.code === ErrorCode.InvalidInput) {
    console.error(error.operation, error.message)
    // analyze invalid text: contains an unpaired surrogate
  }
} finally {
  suzume?.destroy()
}
SituationResult
Invalid option or argument: unknown mode or POS name, a size outside its range, a non-boolean flag, bad scorerOptions, a non-string text, a dictionary that is neither a string nor a Uint8Array, or text with an unpaired UTF-16 surrogate (dictionary text and the keys and string values of scorerOptions included)Throws SuzumeError with InvalidInput; the message names the option and the accepted values, for example invalid text: 123 (expected a string)
Native failure in Suzume.create(), analyze(), analyzeWithNormalizedText(), generateTags(), the dictionary methods, mode changes, or clearUserDictionaries()Throws SuzumeError with the native code and text
WASM module fails to loadSuzume.create() or version() rejects with SuzumeError (Internal, operation create or version); the loader error is the cause
Method that needs a live handle, called after destroy()Throws SuzumeError with InvalidInput and the message Suzume instance has been released

instanceof SuzumeError also catches option errors, so check code to tell a caller mistake from a native failure.

When a call has more than one problem, the error reported is the first in this order: a released instance, then the text, then the options in the row order of the SuzumeOptions and TagOptions tables.

WebAssembly out-of-memory behavior

An allocation failure aborts the WASM runtime instead of returning a normal OutOfMemory result. It does not follow the catchable SuzumeError path, and the affected runtime cannot be reused. Because instances share a runtime by default, an abort also invalidates the other handles on that runtime. Process long documents in chunks, and use freshWasmModule: true when failure isolation is required.


Memory Management ​

Suzume allocates its memory in WebAssembly linear memory, outside the JavaScript heap; the figure under Shared WASM runtime shows which side the GC sees. In Node.js, V8 does not count that memory toward heap usage, so many undestroyed handles can grow memory use while the GC sees no pressure and the FinalizationRegistry cleanup is delayed. destroy() is the contract for releasing a handle; the FinalizationRegistry is only a backstop. Call it explicitly, especially in server-side code.

Every call on an instance is synchronous and runs to completion, so one instance can be shared freely within a JavaScript thread. A worker needs its own instance, since a WebAssembly module belongs to the thread that loaded it.

typescript
// Good: Clean up when done
const suzume = await Suzume.create()
try {
  const result = suzume.analyze(text)
  // process result...
} finally {
  suzume.destroy()
}

// For long-running apps: reuse the instance
class MyApp {
  private suzume: Suzume | null = null

  async init() {
    this.suzume = await Suzume.create()
  }

  analyze(text: string) {
    return this.suzume?.analyze(text) ?? []
  }

  dispose() {
    this.suzume?.destroy()
    this.suzume = null
  }
}