oxc/wasm/parser
oxc-bot d56264ee9a
release(crates): v0.30.3 (#6104)
## [0.30.3] - 2024-09-27

### Bug Fixes

- a8338dd isolated-declarations: Accidentally collected references of
original ast (#6102) (Dunqing)
- 933a743 semantic: Add interfaces and functions to
`SymbolFlags::ClassExcludes` (#6057) (DonIsaac)

### Documentation

- 6167f29 oxc-transform: Modify the example code in the `Readme` file
(#6103) (loong.woo)

---------

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2024-09-27 14:23:48 +08:00
..
src refactor(wasm): add source_type for parser, replace class options with plain object (#5217) 2024-08-26 15:08:35 +08:00
.gitignore feat: setup wasm parser for npm (#2221) 2024-01-30 21:40:10 +08:00
Cargo.toml chore(dprint): format toml files (#5599) 2024-09-08 14:26:16 +08:00
CHANGELOG.md Release crates v0.26.0 (#5418) 2024-09-03 10:36:02 +08:00
package.json release(crates): v0.30.3 (#6104) 2024-09-27 14:23:48 +08:00
README.md chore: use dprint to format js, json and markdown 2024-09-08 13:24:58 +08:00
test-node.mjs chore: use dprint to format js, json and markdown 2024-09-08 13:24:58 +08:00

About

Experimental wasm package for the oxc parser, with full TypeScript typings support.

This package is built with different wasm-pack's target builds:

  • wasm-pack build --target web for bundler (webpack / vite) consumption.
  • wasm-pack build --target nodejs for node.js

And exports the files as

"main": "./node/oxc_parser_wasm.js",
"browser": "./web/oxc_parser_wasm.js",
"types": "./node/oxc_parser_wasm.d.ts",

Checkout oxc-parser for usage in node.js via napi bindings.

Source code: https://github.com/oxc-project/oxc/tree/main/wasm/parser

Usage

import initWasm, { parseSync } from '@oxc-parser/wasm';

async function main() {
  await initWasm();

  const code = 'let foo';
  const result = parseSync(code, { sourceFilename: 'test.ts' });
  console.log(result);
}

main();

Notes

UTF8 vs UTF16 byte offsets

The span value returned from the ASTs and diagnostics is in UTF8 byte offsets. Converting to UTF16 byte offsets:

let sourceTextUtf8 = new TextEncoder().encode(sourceText);

const convertToUtf8 = (sourceTextUtf8, d) => {
  return new TextDecoder().decode(sourceTextUtf8.slice(0, d)).length;
};

const diagnostics = result.errors.map((d) => ({
  from: convertToUtf8(sourceTextUtf8, d.start),
  to: convertToUtf8(sourceTextUtf8, d.end),
  severity: d.severity.toLowerCase(),
  message: d.message,
}));

Vite

wasm-pack build --target web is used for the wasm build.

You may need something like https://github.com/nshen/vite-plugin-wasm-pack to get it working with vite, otherwise vite will load the wasm file as a HTML file causing a CompileError: WebAssembly.instantiate(): expected magic word error.