Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
whitequark committed Apr 4, 2024
0 parents commit d666115
Show file tree
Hide file tree
Showing 20 changed files with 479 additions and 0 deletions.
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
patreon: whitequark
87 changes: 87 additions & 0 deletions .github/workflows/package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
on: [push, pull_request]
name: Test & publish
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out source code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up node
uses: actions/setup-node@v4
with:
node-version: '18.x'
- name: Prepare metadata
run: node prepare.mjs
- name: Install dependencies
run: npm install
- name: Build generated code
run: npm run build
- name: Run tests
run: npm run test
- name: Build JavaScript artifact
run: |
mkdir -p dist
npm pack --pack-destination dist
- name: Upload JavaScript artifact
uses: actions/upload-artifact@v4
with:
name: dist-npmjs
path: dist/
- name: Build Python artifact
run: |
pip install build
python -m build pypi
- name: Upload Python artifact
uses: actions/upload-artifact@v4
with:
name: dist-pypi
path: pypi/dist/
check: # group all `test (*)` workflows into one for the required status check
needs: test
if: ${{ always() && !contains(needs.*.result, 'cancelled') }}
runs-on: ubuntu-latest
steps:
- run: ${{ contains(needs.*.result, 'failure') && 'false' || 'true' }}
publish-python:
needs: check
if: ${{ github.event_name == 'push' && github.repository == 'YoWASP/wavedrom' && github.event.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
environment: publish
permissions:
id-token: write
steps:
- name: Download Python artifacts
uses: actions/download-artifact@v4
with:
name: dist-pypi
path: dist-tree/
- name: Prepare artifacts for publishing
run: |
mkdir dist
find dist-tree -name '*.whl' -exec mv {} dist/ \;
- name: Publish wheels to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
publish-javascript:
needs: check
if: ${{ github.event_name == 'push' && github.repository == 'YoWASP/wavedrom' && github.event.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
environment: publish
permissions:
id-token: write
steps:
- name: Set up Node.js
uses: actions/setup-node@v4
with:
registry-url: 'https://registry.npmjs.org'
- name: Download JavaScript artifact
uses: actions/download-artifact@v4
with:
name: dist-npmjs
path: dist/
- name: Publish package to NPM
run: npm publish --access public $(find dist -name *.tgz -printf 'file:%p ')
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_CONFIG_PROVENANCE: true
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/package-lock.json
/package.json
/node_modules
/dist
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Catherine <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
YoWASP WaveDrom package
=======================

This package provides a self-contained [WaveDrom] renderer for JavaScript and Python applications. See the [overview of the YoWASP project][yowasp] for details.

[WaveDrom]: https://wavedrom.com/
[yowasp]: https://yowasp.org/

Command-line tool
-----------------

This package installs a command-line tool `yowasp-wavedrom`.

```
Usage: yowasp-wavedrom [<input.json>] [<output.svg>]
```

API reference (JavaScript)
--------------------------

The [@yowasp/wavedrom] package has one entry point, `render(source): string`. It accepts a JavaScript object in the WaveJSON format and returns an SVG image serialized as a string:

```js
import { render } from '@yowasp/wavedrom';

console.log(render({signal: [{ name: "clk", wave: "p..." }, { name: "data", wave: "01.0" }]}));
// => <svg.../svg>
```

[@yowasp/wavedrom]: https://www.npmjs.com/package/@yowasp/wavedrom

API reference (Python)
----------------------

The [yowasp-wavedrom] package has one entry point, `render(source) -> str`. It accepts a Python dictionary in the WaveJSON format and returns an SVG image serialized as a string:

```py
from yowasp_wavedrom import render

print(render({"signal": [{ "name": "clk", "wave": "p..." }, { "name": "data", "wave": "01.0" }]}))
# => <svg.../svg>
```

[yowasp-wavedrom]: https://pypi.org/project/yowasp-wavedrom

Implementation notes
--------------------

This package embeds the [upstream WaveDrom library][upstream] bundled with the minimal amount of dependencies necessary to produce a serialized SVG, and, for the Python package, with a JavaScript runtime. In addition, the output is post-processed compared to the upstream library as follows:

* The `id` attribute of the root `<svg>` element is removed.
* The stylesheets are altered to take into account dark color scheme preference via media queries.
* When rendering waveform diagrams, the `default` skin automatically switches between light and dark color scheme, and the `light` skin corresponds to the upstream `default` skin.
* Several otherwise blocking bugs are worked around.

[upstream]: https://npmjs.org/package/wavedrom

Updates
-------

Unlike most [YoWASP] packages, this package does not automatically track upstream releases. Please [open a pull request](https://github.com/YoWASP/wavedrom/pulls) bumping the version of `wavedrom` in `package-in.json` if you need a feature from a newer version of [WaveDrom].

License
-------

This package is covered by the [MIT license](LICENSE.txt).
17 changes: 17 additions & 0 deletions bin/yowasp-wavedrom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env node

import { readFileSync, writeFileSync } from 'fs';
import { render } from '@yowasp/wavedrom';

const args = process.argv.slice(2);
if (!(args.length >= 0 && args.length <= 2)) {
console.error(`Usage: yowasp-wavedrom [- | <input.json>] [- | <output.svg>]`);
process.exit(1);
}

const inputPathOrFd = (args[0] === undefined || args[0] === '-') ? process.stdin.fd : args[0];
const outputPathOrFd = (args[1] === undefined || args[1] === '-') ? process.stdout.fd : args[1];

const source = JSON.parse(readFileSync(inputPathOrFd, 'utf-8'));
const output = render(source);
writeFileSync(outputPathOrFd, output, 'utf-8');
42 changes: 42 additions & 0 deletions build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { build } from 'esbuild';
import { componentize } from '@bytecodealliance/componentize-js';
import { readFile, writeFile } from 'node:fs/promises';

// Bundle, for npm
await build({
logLevel: 'info',
entryPoints: ['lib/api.js'],
bundle: true,
format: 'esm',
outfile: 'out/bundle.js',
});

// Componentize, for PyPI
// This isn't currently used pending https://github.com/bytecodealliance/wasmtime-py/pull/224,
// but is planned for later use and kept tested in the meantime.
const { component } = await componentize(`\
${await readFile('out/bundle.js', 'utf8')}
export function renderJson(sourceJSON) {
return render(JSON.parse(sourceJSON));
}
`, `\
package local:wavedrom;
world wavedrom {
export render-json: func(json: string) -> string;
}
`, {
disableFeatures: ['random', 'stdio', 'clocks']
});
await writeFile('out/wavedrom.component.wasm', component);

// Bundle, for PyPI
// This is what's actually used right now.
await build({
logLevel: 'info',
entryPoints: ['lib/api.js'],
bundle: true,
format: 'cjs',
outfile: 'pypi/yowasp_wavedrom/bundle.js',
});
1 change: 1 addition & 0 deletions lib/api.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export function render(source: any): string;
63 changes: 63 additions & 0 deletions lib/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { default as onml_stringify } from 'onml/stringify.js';
import { default as WaveSkin_default } from 'wavedrom/skins/default.js';
import { default as WaveSkin_narrow } from 'wavedrom/skins/narrow.js';
import { default as WaveSkin_narrower } from 'wavedrom/skins/narrower.js';
import { default as WaveSkin_narrowerer } from 'wavedrom/skins/narrowerer.js';
import { default as WaveSkin_lowkey } from 'wavedrom/skins/lowkey.js';
import { default as WaveSkin_dark } from 'wavedrom/skins/dark.js';
import { default as WaveDrom_renderSignal } from 'wavedrom/lib/render-signal.js';
import { default as WaveDrom_renderReg } from 'wavedrom/lib/render-reg.js';
import { default as WaveDrom_renderAssign } from 'logidrom/lib/render-assign.js';

const WaveSkin = {
light: WaveSkin_default.default,
...WaveSkin_dark,
...WaveSkin_narrow,
...WaveSkin_narrower,
...WaveSkin_narrowerer,
...WaveSkin_lowkey,
};

// Make the default skin respect browser dark mode.
WaveSkin.default = JSON.parse(JSON.stringify(WaveSkin.light));
// `laneParamsFromSkin` uses hardcoded offsets into the skin to derive parameters, so the tag
// structure of a skin must be preserved exactly, e.g. there can be exactly one <style> element.
WaveSkin.default[2][2] = `\
@media(prefers-color-scheme:light){${WaveSkin.light[2][2]}}\
@media(prefers-color-scheme:dark){${WaveSkin.dark[2][2]}}`;

function renderSignal(source) {
const rendered = WaveDrom_renderSignal(0, source, WaveSkin);
delete rendered[1]['id'];
delete rendered[4][2][1]['style']; // workaround for https://github.com/wavedrom/wavedrom/issues/409
return onml_stringify(rendered); // note: https://github.com/wavedrom/wavedrom/issues/412
}

function renderBitField(source) {
const rendered = WaveDrom_renderReg(0, source);
rendered.splice(2, 0, ['style', {}, '@media(prefers-color-scheme:dark){:root{filter:invert(1)}}']);
return onml_stringify(rendered);
}

function renderCircuit(source) {
const rendered = WaveDrom_renderAssign(0, source);
delete rendered[1]['id'];
rendered[1]['xmlns'] = 'http://www.w3.org/2000/svg'; // workaround for https://github.com/wavedrom/wavedrom/issues/413
rendered.splice(3, 0, ['style', {}, '@media(prefers-color-scheme:dark){:root{filter:invert(1)}.gate{fill:#1c60a8}}']);
return onml_stringify(rendered);
}

export function render(source) {
if (source.signal && source.reg === undefined && source.assign === undefined)
return renderSignal(source);
if (source.signal === undefined && source.reg && source.assign === undefined)
return renderBitField(source);
if (source.signal === undefined && source.reg === undefined && source.assign)
return renderCircuit(source);
if (Object.keys(source).length == 0)
throw new Error(`Cannot render empty object`);
throw new Error(`Cannot render object with keys: ${Object.keys(source)}`);
}

// The only way to make working with this library tolerable was heavy drinking during development
// of this wrapper.
1 change: 1 addition & 0 deletions out/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*
37 changes: 37 additions & 0 deletions package-in.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@yowasp/wavedrom",
"version": null,
"description": "WaveDrom generates diagrams for digital waveforms, bit fields, and simple combinational circuits",
"author": "Catherine <[email protected]>",
"license": "MIT",
"homepage": "https://yowasp.org/",
"repository": {
"type": "git",
"url": "git+https://github.com/YoWASP/wavedrom.git"
},
"bugs": {
"url": "https://github.com/YoWASP/wavedrom/issues"
},
"type": "module",
"files": ["out/bundle.js", "bin/yowasp-wavedrom.js"],
"exports": {
"types": "./lib/api.d.ts",
"default": "./out/bundle.js"
},
"bin": {
"yowasp-wavedrom": "./bin/yowasp-wavedrom.js"
},
"dependencies": {
"wavedrom": "3.5.0",
"onml": "2.1.0"
},
"devDependencies": {
"esbuild": "^0.20.2",
"@bytecodealliance/componentize-js": "^0.8.3",
"@bytecodealliance/jco": "^1.1.1"
},
"scripts": {
"build": "node build.mjs",
"test": "cd test && jco transpile ../out/wavedrom.component.wasm -o out/ && node test.mjs"
}
}
16 changes: 16 additions & 0 deletions prepare.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { execFileSync } from 'child_process';
import { readFileSync, writeFileSync } from 'fs';

const revCount = execFileSync('git', ['rev-list', 'HEAD'], {encoding: 'utf-8'}).split('\n').length - 1;

const packageJSON = JSON.parse(readFileSync('package-in.json', {encoding: 'utf-8'}));
const wavedromVersion = packageJSON.dependencies.wavedrom;

const npmVersion = `${wavedromVersion}-${revCount}`;
console.log(`version ${npmVersion} (NPM)`);
packageJSON.version = npmVersion;
writeFileSync('package.json', JSON.stringify(packageJSON, null, 4));

const pypiVersion = `${wavedromVersion}.${revCount}`;
console.log(`version ${pypiVersion} (PyPI)`);
writeFileSync('pypi/version.txt', pypiVersion);
8 changes: 8 additions & 0 deletions pypi/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
__pycache__/
/*.egg-info
/.eggs
/build
/dist

/version.txt
/yowasp_wavedrom/bundle.js
1 change: 1 addition & 0 deletions pypi/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include version.txt
1 change: 1 addition & 0 deletions pypi/README.md
Loading

0 comments on commit d666115

Please sign in to comment.