@makechart/viewer 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Change Logs
2
+
3
+ ## v0.0.2
4
+
5
+ - add playground ( `/playground` in `mctest serve` ): apply any test case's data / config / size,
6
+ replay its steps in real time, swap data from `mod.sample` or suite data, edit raw as CSV and
7
+ binding as JSON, and tweak config from a panel generated from `mod.config`
8
+ - modules not found locally are fetched from npm CDN ( jsdelivr ) and cached in `~/.cache/mctest`.
9
+ add `--offline` to disable it
10
+ - add `ctx.capture(label)`: save the current markup without waiting or flushing, for animation
11
+ frames driven by `chart.anim.step`. `steps` / `cases` accept a single item without an array
12
+ - drag helper sends both pointer and mouse events with integer coordinates ( d3-brush listens to mouse )
13
+ - normalize csscope scope tokens, hex colors as `rgb()` and transform spacing, so d3 / lite
14
+ variants of the same chart compare equal
15
+
16
+ ## v0.0.1
17
+
18
+ - init release
19
+ - `mctest` cli: run test cases of a makechart chart in a headless browser and compare the output with
20
+ snapshots in `test/snapshot` ( `-u` to update, `-g` to filter, `--ci`, `--loose`, `--dpr` )
21
+ - `mctest serve`: UI showing current and baseline side by side; accept re-runs the case headlessly
22
+ so snapshots always come from the same environment
23
+ - resolve frontend dependencies at runtime under `/assets/lib/<name>/<ver>/<path>`, with local
24
+ overrides via `-l name:dir` ( same syntax as `fedep -l` ) or `MCTEST_LINK`
25
+ - test case API ( `mctest.suite` ): data sets, per-case config, steps with intermediate snaps,
26
+ pointer drag helper, `combo` / `label` / seeded `random` helpers
27
+ - crossfilter cases via `@plotdb/dash` boards
28
+ - deterministic output: `chart.anim` is switched to manual and flushed, capture waits for a quiet DOM,
29
+ markup is serialized with sorted attributes and rounded numbers, volatile ids are normalized
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zbryikt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @makechart/viewer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ makechart 圖表的 test suite engine。每張圖在自己的 repo 放 test case,engine 用 headless 瀏覽器以各種資料、參數跑過,把輸出跟存下來的 snapshot 比對;也能用 `@plotdb/dash` 把幾張圖串起來測 crossfilter。
4
+
5
+
6
+ ## 安裝
7
+
8
+ 在 chart repo 裡:
9
+
10
+ npm install -D @makechart/viewer
11
+
12
+ 本地開發 engine 時可以改用 `npm link` 或 `npm install -D <path-to-viewer>`。
13
+
14
+ 需要一個 headless 瀏覽器:預設用 playwright 的 chromium ( `npx playwright install chromium-headless-shell` ),沒裝就用系統的 Chrome。
15
+
16
+
17
+ ## 使用
18
+
19
+ 在 chart repo 的根目錄:
20
+
21
+ npx mctest # 跑全部 case. 沒有 snapshot 的會直接存起來
22
+ npx mctest -u # 不一致的也更新 snapshot
23
+ npx mctest -g stack # 只跑名字含 stack 的 ( 也可以是 regexp )
24
+ npx mctest --ci # 沒有 snapshot 也算失敗
25
+ npx mctest serve -o # 開 UI: 並排看 current / baseline, accept
26
+
27
+ `npx mctest -h` 看全部選項。結束碼不是 0 代表有 case 失敗,失敗的 markup 與截圖放在 `test/output/`。
28
+
29
+
30
+ ## playground
31
+
32
+ `npx mctest serve` 之後開 `/playground` ( UI 右上角也有連結 ),拿圖來玩:
33
+
34
+ - 上方選一個 test case 就套用它的資料、config 與大小;有 steps 的 ( 標 ▶ ) 可以按「跑 steps」,用真實時間看動畫
35
+ - 「換資料」可以換成 `mod.sample` 或 suite 裡任一份 data,設定保留
36
+ - 左側設定面板依 `mod.config` 自動產生 ( number / boolean / choice / color / format / text );palette 給幾組現成的,font / quantity 沒有元件
37
+ - raw 用 CSV 編輯、binding 用 JSON,按「套用資料」
38
+ - 圖的容器可以拖右下角改大小;`window.chart` 是圖的實例,可以在 console 直接操作
39
+
40
+ ## 依賴從哪裡來
41
+
42
+ engine 自己起一個 server,前端依賴走與 makechart 相同的路徑 `/assets/lib/<name>/<version>/<path>`,版本一律忽略,依序找:
43
+
44
+ 1. `-l name:dir` ( 或環境變數 `MCTEST_LINK` ) 指定的本地目錄,有 `dist/` 先找 `dist/`
45
+ 2. 受測的圖自己 ( package.json 的 name -> `./dist` )
46
+ 3. `node_modules`,先 chart repo 再 engine 自己的 ( npm link 的 symlink 一樣適用 )
47
+
48
+ 所以本地開發不必每張圖都 clone,要改的那幾個連過去就好:
49
+
50
+ npx mctest -l "@makechart/base:../base;@plotdb/chart:~/workspace/plotdb/projects/chart"
51
+
52
+ `-l` 的寫法同 `fedep -l`。`@plotdb/dash` 目前沒有發佈,dash 的 case 要把它連過來,沒連的話這些 case 會是 error。
53
+
54
+
55
+ ## 寫 test case
56
+
57
+ `test/index.ls` ( 或 `test/index.js` ),在瀏覽器裡執行,可以用全域的 `mctest`:
58
+
59
+ mctest.suite do
60
+ size: [480 300] # 預設的圖大小 ( px )
61
+ config: {} # 所有 case 共用的 config
62
+ data:
63
+ fruit: {raw: [...], binding: {...}} # 也可以是回傳 {raw, binding, subset?} 的 function
64
+ cases:
65
+ * name: "stack", data: \fruit, config: {multiple: \stack}
66
+ * name: "filter"
67
+ steps:
68
+ * (chart, ctx) ->
69
+ chart.filter {name: {type: \index, value: <[A B]>}}
70
+ ctx.snap \filtered # 在這裡多存一格
71
+ * (chart) -> chart.filter {name: undefined}
72
+ * name: "dash" # 多張圖, 用 @plotdb/dash 的 board
73
+ dash: {def: {...}, size: [900 320]}
74
+ steps: [(board, ctx) -> board.set-filter \a, {field: \region, values: <[North]>}]
75
+
76
+ - `name` 是 snapshot 的檔名,要唯一。
77
+ - `steps` 依序執行,每一步之後等畫面穩定。可以回傳 promise。
78
+ - `ctx`:`root` ( 這個 case 的容器 )、`snap(label)`、`drag(node, [x0, y0], [x1, y1])` ( 相對座標 0~1,送 pointer 事件 )、`chart(id)` ( dash 時取某個 panel 的圖 )、`wait(ms)`、`random(seed)`。
79
+ - helper:`mctest.combo {type: <[column bar]>, multiple: <[stack group]>}` 產生所有組合,`mctest.label o` 把組合轉成名字,`mctest.random seed` 是固定種子的亂數。
80
+ - `skip: true` 略過。`suite.chart` 預設是 package.json 的 name。
81
+
82
+ 資料請用固定種子產生,否則每次跑都不一樣。
83
+
84
+
85
+ ## 怎麼比對
86
+
87
+ - 動畫:有 `chart.anim` 的圖 ( @plotdb/chart 的補間時鐘 ) 一律切成 manual,再直接 flush 到終點,所以結果跟機器快慢無關。還在用 d3 transition 的圖只能等它跑完。
88
+ - 穩定:DOM 連續 `quiet` ms ( 預設 250 ) 沒有變動才擷取,要比圖裡的 debounce 長。
89
+ - markup:自己序列化 DOM,屬性依名字排序,一個 tag 一行,數字取到小數兩位,並把每次都會變的亂數 id 換掉 ( ldview scope、legend id;圖表自己的用 `suite.normalize: [[regexp, 取代字串]]` 補 )。
90
+ - 每個 case 都在固定於頁面 (0, 0) 的位置執行,版面不受前面的 case 影響。
91
+ - 結果:`pass` 完全相同;`near` 結構相同、只差數字,而且差距在 `tolerance` 內 ( 預設 1 );`diff`;`new` 沒有 snapshot。cli 預設把 `near` 也算失敗,加 `--loose` 才放過。`near` 多半出現在 UI:你的瀏覽器跟 headless 的 DPR、視窗不同,文字寬度會有小數誤差。
92
+
93
+ snapshot 一律由 headless 產生 ( viewport 1600x1000,DPR 預設 2,`--dpr` 可改 )。UI 的 accept 也是請 server 用 headless 重跑那幾個 case 再存,不會存 UI 所在瀏覽器畫出來的版本。
94
+
95
+ 文字寬度跟字型、瀏覽器版本有關,不同機器 ( 例如 CI 的 linux ) 需要各自的 baseline,或固定瀏覽器與字型。
96
+
97
+
98
+ ## 檔案
99
+
100
+ - `bin/cli.js` — 指令
101
+ - `lib/server.js` — http server:依賴解析、test case 編譯、snapshot API
102
+ - `lib/runner.js` — headless 瀏覽器 ( playwright-core )
103
+ - `src/suite.ls` — 瀏覽器端 engine:case 定義、執行、正規化、比對
104
+ - `src/playground.ls`、`web/playground.html` — playground
105
+ - `src/ui.ls`、`web/index.html` — UI ( headless 也是跑這頁 )
package/bin/cli.js ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ // mctest - makechart 圖表的 test suite. 在 chart repo 的根目錄執行:
3
+ //
4
+ // npx mctest headless 跑全部 case, 跟 test/snapshot 比對. 沒有 snapshot 的會直接存起來
5
+ // npx mctest -u 不一致的也直接更新 snapshot
6
+ // npx mctest -g stack 只跑名字含 stack 的 ( 也可以是 regexp )
7
+ // npx mctest serve [-o] 開 UI 看圖、比對、accept ( accept 時用 headless 重跑再存 )
8
+ //
9
+ // 共用選項:
10
+ // -l name:dir[;name:dir] 本地目錄取代 node_modules 裡的版本 ( 同 fedep -l, 有 dist/ 用 dist/ )
11
+ // 也可以用環境變數 MCTEST_LINK
12
+ // -p port serve 的 port ( 預設 8722 ), run 預設隨機
13
+ // --ci 沒有 snapshot 的 case 算失敗, 不自動存
14
+ // --browser chrome|<path> 指定瀏覽器. 預設用 playwright 的 chromium, 沒裝就用系統的 Chrome
15
+ // --loose 數字差在 tolerance 內 ( near ) 也算過. 預設不算: 真的差 1px 的改動也要抓到
16
+ // --dpr n headless 的 devicePixelRatio ( 預設 2, 同 Mac 螢幕 ). 文字寬度會隨它有小數誤差
17
+ // --headed run 時顯示瀏覽器視窗
18
+ // --offline 本機找不到的模組不向 npm CDN 拿
19
+ // -v 印出 404、從 CDN 拿的檔案與頁面的 console
20
+ const fs = require('fs'), path = require('path');
21
+ const {create, parseLinks} = require('../lib/server');
22
+ const {Runner, writeSnapshot} = require('../lib/runner');
23
+
24
+ function parseArgs(argv) {
25
+ const o = {cmd: 'run', links: {}, grep: '', update: false, ci: false, loose: false, dpr: 2, headed: false, verbose: false, open: false};
26
+ const links = [process.env.MCTEST_LINK || ''];
27
+ for (let i = 0; i < argv.length; i++) {
28
+ const a = argv[i], next = () => argv[++i];
29
+ if (a === 'serve' || a === 'run') o.cmd = a;
30
+ else if (a === '-u' || a === '--update') o.update = true;
31
+ else if (a === '-g' || a === '--grep') o.grep = next();
32
+ else if (a === '-l' || a === '--link') links.push(next());
33
+ else if (a === '-p' || a === '--port') o.port = +next();
34
+ else if (a === '-o' || a === '--open') o.open = true;
35
+ else if (a === '--ci') o.ci = true;
36
+ else if (a === '--offline') o.offline = true;
37
+ else if (a === '--loose') o.loose = true;
38
+ else if (a === '--dpr') o.dpr = +next();
39
+ else if (a === '--browser') o.browser = next();
40
+ else if (a === '--headed') o.headed = true;
41
+ else if (a === '-v' || a === '--verbose') o.verbose = true;
42
+ else if (a === '-h' || a === '--help') o.cmd = 'help';
43
+ else { console.error(`[mctest] unknown option: ${a}`); process.exit(2); }
44
+ }
45
+ o.links = parseLinks(links.join(';'));
46
+ return o;
47
+ }
48
+
49
+ async function run(o, srv) {
50
+ const port = await srv.listen(o.port);
51
+ const outDir = path.join(srv.testDir, 'output');
52
+ fs.rmSync(outDir, {recursive: true, force: true});
53
+ const runner = new Runner(o, port);
54
+ let code = 0;
55
+ try {
56
+ const results = await runner.run({grep: o.grep, keepPage: true});
57
+ const cnt = {};
58
+ for (const r of results) {
59
+ let s = r.status;
60
+ if (s === 'near' && !o.loose) s = 'diff';
61
+ if (s === 'diff' && o.update) s = 'updated';
62
+ else if (s === 'new' && !o.ci) s = 'added';
63
+ cnt[s] = (cnt[s] || 0) + 1;
64
+ if (s === 'updated' || s === 'added') writeSnapshot(srv, r);
65
+ if (['diff', 'new', 'error'].includes(s)) {
66
+ // 失敗的留下目前的 markup 跟截圖 ( 給 CI 當 artifact ), 對照用 serve 看比較方便
67
+ fs.mkdirSync(outDir, {recursive: true});
68
+ if (r.current) fs.writeFileSync(path.join(outDir, r.file + '.html'), r.current);
69
+ await runner.shot(r.file, path.join(outDir, r.file + '.png'));
70
+ code = 1;
71
+ }
72
+ const mark = {pass: '✓', near: '≈', updated: '↻', added: '+', skip: '-', diff: '✗', new: '✗', error: '✗'}[s];
73
+ const note = s === 'pass' ? '' : ` ( ${r.status}${r.status === 'near' ? ` ±${r.delta}` : ''}${s !== r.status ? ` -> ${s}` : ''} )`;
74
+ if (!['pass', 'near'].includes(s) || o.verbose) console.log(` ${mark} ${r.name}${note}`);
75
+ if (s === 'diff' || s === 'updated') console.log(` line ${r.line}\n - ${r.expect}\n + ${r.actual}`);
76
+ if (s === 'new') console.log(' no snapshot ( run without --ci to save it )');
77
+ if (s === 'error') console.log(' ' + String(r.error).split('\n').slice(0, 4).join('\n '));
78
+ }
79
+ console.log(`\n${results.length} cases: ` + Object.entries(cnt).map(([k, v]) => `${k} ${v}`).join(', '));
80
+ if (code) console.log(`\n失敗的 case 輸出在 ${path.relative(process.cwd(), outDir)}/. 用 \`npx mctest serve\` 對照, 確認沒問題再 \`npx mctest -u\``);
81
+ } finally {
82
+ await runner.close();
83
+ await srv.close();
84
+ }
85
+ return code;
86
+ }
87
+
88
+ async function serve(o, srv) {
89
+ const port = await srv.listen(o.port || 8722);
90
+ // UI 的 accept: 用 headless 重跑那幾個 case 再存, 不收 UI 所在瀏覽器畫的版本
91
+ const runner = new Runner(o, port);
92
+ srv.accept = async (names) => {
93
+ const rs = await runner.run({names});
94
+ rs.filter(r => r.current).forEach(r => writeSnapshot(srv, r));
95
+ return rs.map(r => ({name: r.name, file: r.file, status: r.current ? 'saved' : r.status, error: r.error}));
96
+ };
97
+ const url = `http://localhost:${port}/`;
98
+ console.log(`[mctest] ${srv.pkg.name} -> ${url}`);
99
+ for (const [k, v] of Object.entries(srv.links)) console.log(`[mctest] link ${k} -> ${v}`);
100
+ if (o.open) {
101
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
102
+ require('child_process').exec(`${cmd} ${url}`);
103
+ }
104
+ }
105
+
106
+ const o = parseArgs(process.argv.slice(2));
107
+ if (o.cmd === 'help') {
108
+ console.log(fs.readFileSync(__filename, 'utf8').split('\n').slice(1).filter(l => l.startsWith('//')).map(l => l.slice(3)).join('\n'));
109
+ process.exit(0);
110
+ }
111
+ if (!fs.existsSync('package.json')) { console.error('[mctest] run it in the root of a chart repo ( package.json not found )'); process.exit(2); }
112
+ const srv = create({links: o.links, verbose: o.verbose, offline: o.offline});
113
+ (o.cmd === 'serve' ? serve(o, srv) : run(o, srv).then(c => process.exit(c)))
114
+ .catch(e => { console.error(e.stack || e); process.exit(1); });
package/lib/runner.js ADDED
@@ -0,0 +1,64 @@
1
+ // 用 headless 瀏覽器跑 case. cli 的 run 與 serve 的 accept 共用, 所以 snapshot 一律出自同一種環境
2
+ // ( 同一個瀏覽器、viewport、DPR ). UI 所在的瀏覽器只拿來看, 不寫 snapshot.
3
+ const fs = require('fs'), path = require('path');
4
+
5
+ async function launch(o = {}) {
6
+ const {chromium} = require('playwright-core');
7
+ const base = {headless: !o.headed};
8
+ if (o.browser && o.browser !== 'chrome') return chromium.launch({...base, executablePath: o.browser});
9
+ if (o.browser === 'chrome') return chromium.launch({...base, channel: 'chrome'});
10
+ try { return await chromium.launch(base); } catch (e) {
11
+ // playwright 的 chromium 沒裝 ( 或版本對不上 ): 改用系統的 Chrome.
12
+ // Chrome 會自動更新, 文字寬度可能因此有小數誤差 ( 見 near )
13
+ return chromium.launch({...base, channel: 'chrome'});
14
+ }
15
+ }
16
+
17
+ class Runner {
18
+ constructor(o, port) { this.o = o; this.port = port; this.queue = Promise.resolve(); }
19
+
20
+ async _open() {
21
+ if (this.browser) return;
22
+ this.browser = await launch(this.o);
23
+ this.ctx = await this.browser.newContext({viewport: {width: 1600, height: 1000}, deviceScaleFactor: this.o.dpr || 2});
24
+ }
25
+
26
+ // opt: {grep} 或 {names: [...]} ( 完整名字 ). 每次都開新頁, 拿到 test/index.ls 的最新版
27
+ run(opt = {}) {
28
+ const job = this.queue.then(() => this._run(opt));
29
+ this.queue = job.catch(() => {});
30
+ return job;
31
+ }
32
+
33
+ async _run(opt) {
34
+ await this._open();
35
+ const page = this.page = await this.ctx.newPage();
36
+ page.on('pageerror', e => console.error('[page error]', e.message));
37
+ if (this.o.verbose) page.on('console', m => console.log('[page]', m.text()));
38
+ await page.goto(`http://127.0.0.1:${this.port}/?headless`);
39
+ await page.waitForFunction(() => window.mctest && mctest.ui && (mctest.ui.ready || mctest.ui.error), null, {timeout: 30000});
40
+ const err = await page.evaluate(() => mctest.ui.error);
41
+ if (err) throw new Error(err);
42
+ const results = await page.evaluate((opt) => mctest.ui.run(opt), opt);
43
+ if (opt.keepPage) return results;
44
+ await page.close();
45
+ this.page = null;
46
+ return results;
47
+ }
48
+
49
+ // 失敗的 case 截圖 ( 要在 run 時帶 keepPage )
50
+ async shot(file, dest) {
51
+ if (!this.page) return;
52
+ await this.page.locator(`.case[data-file="${file}"] .pane.current`).screenshot({path: dest}).catch(() => {});
53
+ }
54
+
55
+ async closePage() { if (this.page) await this.page.close(); this.page = null; }
56
+ async close() { if (this.browser) await this.browser.close(); this.browser = null; }
57
+ }
58
+
59
+ function writeSnapshot(srv, r) {
60
+ fs.mkdirSync(srv.snapDir, {recursive: true});
61
+ fs.writeFileSync(path.join(srv.snapDir, r.file + '.html'), r.current);
62
+ }
63
+
64
+ module.exports = {Runner, launch, writeSnapshot};
package/lib/server.js ADDED
@@ -0,0 +1,206 @@
1
+ // mctest server: 在受測 chart 的 repo ( cwd ) 裡起一個 http server.
2
+ //
3
+ // / engine 的 UI ( web/index.html )
4
+ // /playground 拿圖來玩: 改設定、資料, 套用 test case ( web/playground.html )
5
+ // /engine/<file> engine 的前端檔案 ( <name>.js 由 src/<name>.ls 即時編譯, 其餘在 web/ )
6
+ // /assets/lib/<name>/<ver>/<path>
7
+ // 前端依賴, 規則同 makechart server / fedep ( 版本一律忽略, 用找到的那份 ):
8
+ // 1. -l 指定的本地目錄 ( 有 dist/ 先找 dist/ )
9
+ // 2. 受測的 chart 自己 ( package.json name -> cwd/dist )
10
+ // 3. node_modules ( 先 cwd 再 engine 自己的 ), 含 npm link 的 symlink
11
+ // 4. npm CDN ( jsdelivr ), 快取在 ~/.cache/mctest. --offline 時不拿
12
+ // /test/index.js chart 的 test case ( test/index.ls 即時編譯, 或 test/index.js )
13
+ // /test/<path> chart 的 test/ 目錄 ( 放資料檔用 )
14
+ // /api/info {name, version, links}
15
+ // GET /api/snapshot/<name> 讀 test/snapshot/<name>.html ( 沒有回 204 )
16
+ // POST /api/accept {names} 用 headless 重跑這些 case 並存成 snapshot ( serve 才有, 見 bin/cli.js )
17
+ const http = require('http'), fs = require('fs'), path = require('path');
18
+
19
+ const engineRoot = path.resolve(__dirname, '..');
20
+ const types = {
21
+ '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.json': 'application/json',
22
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.csv': 'text/csv', '.woff2': 'font/woff2', '.txt': 'text/plain'
23
+ };
24
+
25
+ // "name:dir;name:dir" ( 同 fedep -l ) -> {name: absdir}
26
+ function parseLinks(s) {
27
+ const ret = {};
28
+ (s || '').split(';').map(v => v.trim()).filter(v => v).forEach(v => {
29
+ const i = v.lastIndexOf(':');
30
+ if (i <= 0) throw new Error(`[mctest] bad link spec: ${v} ( expect name:dir )`);
31
+ ret[v.slice(0, i)] = path.resolve(v.slice(i + 1).replace(/^~/, require('os').homedir()));
32
+ });
33
+ return ret;
34
+ }
35
+
36
+ function findModule(name, from) {
37
+ for (let d = from; ; d = path.dirname(d)) {
38
+ const p = path.join(d, 'node_modules', name);
39
+ if (fs.existsSync(path.join(p, 'package.json'))) return p;
40
+ if (d === path.dirname(d)) return null;
41
+ }
42
+ }
43
+
44
+ function isFile(f) { try { return fs.statSync(f).isFile(); } catch (e) { return false; } }
45
+
46
+ // 本機找不到的模組改向 npm CDN 拿 ( 同 makechart 的 registry 最後去 npm 抓 ), 快取在 ~/.cache/mctest.
47
+ // 版本是 main 就拿 latest. 快取以 <name>/<version>/<path> 存, latest 的快取一天後重抓
48
+ const cacheRoot = process.env.MCTEST_CACHE || path.join(require('os').homedir(), '.cache', 'mctest');
49
+ const pending = {};
50
+ function fetchRemote(name, version, rest, cdn) {
51
+ const ver = (!version || version === 'main') ? 'latest' : version;
52
+ const f = path.join(cacheRoot, name, ver, rest);
53
+ if (!f.startsWith(cacheRoot + path.sep)) return Promise.resolve(null);
54
+ try {
55
+ const st = fs.statSync(f);
56
+ if (st.isFile() && (ver !== 'latest' || Date.now() - st.mtimeMs < 86400000)) return Promise.resolve(f);
57
+ } catch (e) {}
58
+ const miss = f + '.404';
59
+ if (isFile(miss) && Date.now() - fs.statSync(miss).mtimeMs < 86400000) return Promise.resolve(null);
60
+ if (pending[f]) return pending[f];
61
+ const url = `${cdn}/${name}@${ver}/${rest}`;
62
+ return pending[f] = fetch(url).then(async (r) => {
63
+ fs.mkdirSync(path.dirname(f), {recursive: true});
64
+ if (!r.ok) { fs.writeFileSync(miss, String(r.status)); return null; }
65
+ fs.writeFileSync(f, Buffer.from(await r.arrayBuffer()));
66
+ return f;
67
+ }).catch(() => null).finally(() => { delete pending[f]; });
68
+ }
69
+
70
+ function create(opt = {}) {
71
+ const cwd = path.resolve(opt.cwd || '.');
72
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json')));
73
+ const links = Object.assign({}, opt.links || {});
74
+ const testDir = path.join(cwd, opt.testDir || 'test');
75
+ const snapDir = path.join(testDir, 'snapshot');
76
+
77
+ // 一個模組可能的根目錄, 依序嘗試
78
+ const roots = (name) => {
79
+ const dev = (d) => [path.join(d, 'dist'), d];
80
+ if (links[name]) return dev(links[name]);
81
+ if (name === pkg.name) return dev(cwd);
82
+ const ret = [];
83
+ for (const from of [cwd, engineRoot]) {
84
+ const m = findModule(name, from);
85
+ if (m) ret.push(m, path.join(m, 'dist'));
86
+ }
87
+ return ret;
88
+ };
89
+ const resolveLib = (name, rest) => {
90
+ for (const r of roots(name)) {
91
+ const f = path.join(r, rest);
92
+ if (!f.startsWith(r + path.sep)) return null;
93
+ if (isFile(f)) return f;
94
+ // block 的 path 可以是目錄 ( 例如 @plotdb/konfig 的 base ), 同 registry 補 index.html
95
+ if (isFile(path.join(f, 'index.html'))) return path.join(f, 'index.html');
96
+ }
97
+ return null;
98
+ };
99
+
100
+ // <name>.js 由 src/<name>.ls 即時編譯 ( 依 mtime 快取 ), 開發 engine 時改了重新整理即生效
101
+ const compiled = {};
102
+ const engineFile = (p) => {
103
+ const src = /^[\w-]+\.js$/.test(p) && path.join(engineRoot, 'src', p.replace(/\.js$/, '.ls'));
104
+ if (src && isFile(src)) {
105
+ const m = fs.statSync(src).mtimeMs;
106
+ if (!compiled[p] || compiled[p].m !== m) {
107
+ compiled[p] = {m, code: require('livescript').compile(fs.readFileSync(src, 'utf8'), {filename: src})};
108
+ }
109
+ return {body: compiled[p].code, type: types['.js']};
110
+ }
111
+ const f = path.join(engineRoot, 'web', p);
112
+ if (!f.startsWith(path.join(engineRoot, 'web') + path.sep) || !isFile(f)) return null;
113
+ return {file: f};
114
+ };
115
+
116
+ const caseFile = () => {
117
+ const ls = path.join(testDir, 'index.ls'), js = path.join(testDir, 'index.js');
118
+ if (isFile(ls)) return require('livescript').compile(fs.readFileSync(ls, 'utf8'), {filename: ls});
119
+ if (isFile(js)) return fs.readFileSync(js, 'utf8');
120
+ return 'console.warn("[mctest] no test/index.ls or test/index.js found")';
121
+ };
122
+
123
+ const snapName = (n) => {
124
+ if (!/^[\w.=,+@-]+$/.test(n)) return null;
125
+ return path.join(snapDir, n + '.html');
126
+ };
127
+
128
+ const send = (res, code, body, type) => {
129
+ res.writeHead(code, {'Content-Type': type || 'text/plain; charset=utf-8', 'Cache-Control': 'no-store'});
130
+ res.end(body);
131
+ };
132
+ const sendFile = (res, f) => {
133
+ res.writeHead(200, {'Content-Type': types[path.extname(f)] || 'application/octet-stream', 'Cache-Control': 'no-store'});
134
+ fs.createReadStream(f).pipe(res);
135
+ };
136
+
137
+ const handle = (req, res) => {
138
+ let p;
139
+ try { p = decodeURIComponent(req.url.split('?')[0]); } catch (e) { return send(res, 400, 'bad url'); }
140
+ let m;
141
+ if (p === '/' || p === '/index.html') return sendFile(res, path.join(engineRoot, 'web', 'index.html'));
142
+ if (p === '/playground') return sendFile(res, path.join(engineRoot, 'web', 'playground.html'));
143
+ if ((m = /^\/engine\/(.+)$/.exec(p))) {
144
+ let r;
145
+ try { r = engineFile(m[1]); } catch (e) { return send(res, 500, String(e.stack || e)); }
146
+ if (!r) return send(res, 404, 'not found');
147
+ return r.file ? sendFile(res, r.file) : send(res, 200, r.body, r.type);
148
+ }
149
+ if ((m = /^\/assets\/lib\/((?:@[^/]+\/)?[^/]+)\/([^/]+)\/(.+)$/.exec(p))) {
150
+ const f = resolveLib(m[1], m[3]);
151
+ if (f) return sendFile(res, f);
152
+ if (opt.offline) { if (opt.verbose) console.log('[mctest] 404', p); return send(res, 404, 'not found'); }
153
+ return fetchRemote(m[1], m[2], m[3], opt.cdn || 'https://cdn.jsdelivr.net/npm').then((f) => {
154
+ if (!f) { if (opt.verbose) console.log('[mctest] 404', p); return send(res, 404, 'not found'); }
155
+ if (opt.verbose) console.log('[mctest] remote', p);
156
+ sendFile(res, f);
157
+ });
158
+ }
159
+ if (p === '/test/index.js') {
160
+ try { return send(res, 200, caseFile(), types['.js']); } catch (e) {
161
+ return send(res, 200, `console.error(${JSON.stringify('[mctest] compile test case failed:\n' + (e.stack || e))})`, types['.js']);
162
+ }
163
+ }
164
+ if (p === '/api/info') {
165
+ return send(res, 200, JSON.stringify({name: pkg.name, version: pkg.version, links}), types['.json']);
166
+ }
167
+ if ((m = /^\/api\/snapshot\/(.+)$/.exec(p))) {
168
+ const f = snapName(m[1]);
169
+ if (!f) return send(res, 400, 'bad name');
170
+ // 沒有 snapshot 回 204 而不是 404, 免得瀏覽器 console 每個新 case 都噴一行錯
171
+ return isFile(f) ? sendFile(res, f) : send(res, 204, '');
172
+ }
173
+ if (p === '/api/accept' && req.method === 'POST') {
174
+ if (!api.accept) return send(res, 501, 'accept is only available in `mctest serve`');
175
+ const buf = [];
176
+ req.on('data', d => buf.push(d));
177
+ req.on('end', () => {
178
+ let names;
179
+ try { names = JSON.parse(Buffer.concat(buf).toString()).names; } catch (e) { return send(res, 400, 'bad body'); }
180
+ api.accept(names)
181
+ .then(r => send(res, 200, JSON.stringify(r), types['.json']))
182
+ .catch(e => send(res, 500, String(e.stack || e)));
183
+ });
184
+ return;
185
+ }
186
+ if ((m = /^\/test\/(.+)$/.exec(p))) {
187
+ const f = path.join(testDir, m[1]);
188
+ if (f.startsWith(testDir + path.sep) && isFile(f)) return sendFile(res, f);
189
+ return send(res, 404, 'not found');
190
+ }
191
+ send(res, 404, 'not found');
192
+ };
193
+
194
+ const server = http.createServer(handle);
195
+ const api = {
196
+ server, pkg, cwd, links, snapDir, testDir,
197
+ listen: (port) => new Promise((res, rej) => {
198
+ server.once('error', rej);
199
+ server.listen(port || 0, '127.0.0.1', () => res(server.address().port));
200
+ }),
201
+ close: () => new Promise(res => server.close(res))
202
+ };
203
+ return api;
204
+ }
205
+
206
+ module.exports = {create, parseLinks};
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@makechart/viewer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "makechart 圖表的 test suite engine: 用不同資料、參數跑圖, 比對輸出 snapshot, 並以 @plotdb/dash 測 crossfilter",
5
+ "homepage": "https://github.com/makechart/viewer",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/makechart/viewer"
9
+ },
10
+ "bin": {
11
+ "mctest": "bin/cli.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "lib",
16
+ "src",
17
+ "web",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "release": "npm publish --access public"
22
+ },
23
+ "keywords": [
24
+ "makechart",
25
+ "chart",
26
+ "test",
27
+ "snapshot"
28
+ ],
29
+ "author": "zbryikt",
30
+ "license": "MIT",
31
+ "dependencies": {
32
+ "@loadingio/ldquery": "^3.0.7",
33
+ "@makechart/base": "^0.1.1",
34
+ "@plotdb/block": "^5.3.0",
35
+ "@plotdb/chart": "^3.5.0",
36
+ "@plotdb/csscope": "^5.0.3",
37
+ "@plotdb/konfig": "^4.11.1",
38
+ "@plotdb/layout": "^0.0.12",
39
+ "@plotdb/rescope": "^5.0.12",
40
+ "@plotdb/semver": "^0.0.3",
41
+ "@xlfont/choose": "^0.0.32",
42
+ "@xlfont/load": "^2.1.6",
43
+ "ldcolor": "^1.1.3",
44
+ "ldview": "^1.7.2",
45
+ "livescript": "^1.6.0",
46
+ "playwright-core": "^1.65.0",
47
+ "proxise": "^1.0.1",
48
+ "wrap-svg-text": "^0.0.8",
49
+ "zmgr": "^2.2.3"
50
+ }
51
+ }