@wildshard/sdk 0.2.13 → 0.3.1
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/GUIDE.md +26 -13
- package/bin/wildshard.mjs +2 -1
- package/docs/api/EXPORT-TIERS.md +16 -4
- package/lint/export-tiers.json +12 -0
- package/lint/host-callbacks.mjs +1 -1
- package/package.json +22 -6
- package/scripts/bake/template-skins.mjs +6 -3
- package/scripts/bake/template-warden.mjs +25 -0
- package/scripts/build-shardfiles.mjs +7 -2
- package/scripts/export-ci21-guests.mjs +89 -0
- package/scripts/prepare-product.mjs +2 -2
- package/scripts/scratch-sweep.mjs +182 -0
- package/scripts/wildshard.mjs +1 -1
- package/skills/wildshard-mockup-to-model/SKILL.md +5 -3
- package/skills/wildshard-upgrade/SKILL.md +4 -4
- package/src/cli/help.ts +9 -5
- package/src/cli/upload/validate.ts +7 -5
- package/src/sharddev/as/prelude.ts +67 -0
- package/src/sharddev/assets.ts +1 -1
- package/src/sharddev/authorLint.ts +45 -0
- package/src/sharddev/bake/compactGlb.ts +1 -1
- package/src/sharddev/bake/compileScript.ts +6 -0
- package/src/sharddev/bake/glbCompression.ts +1 -1
- package/src/sharddev/bake/gltfSource.ts +1 -1
- package/src/sharddev/bake/placeholders.ts +1 -1
- package/src/sharddev/bake/terrain.ts +12 -3
- package/src/sharddev/blobBytes.ts +1 -1
- package/src/sharddev/blobs.ts +2 -2
- package/src/sharddev/checkProject.ts +7 -18
- package/src/sharddev/cli.ts +17 -4
- package/src/sharddev/engineMusic.ts +23 -0
- package/src/sharddev/formatJsonSchema.ts +1 -1
- package/src/sharddev/materialGraphFiles.ts +1 -1
- package/src/sharddev/materials.ts +7 -3
- package/src/sharddev/newProject.ts +18 -10
- package/src/sharddev/outputProduct.ts +2 -2
- package/src/sharddev/productOutput.ts +2 -2
- package/src/sharddev/project.ts +6 -1
- package/src/sharddev/projectMap.ts +1 -1
- package/src/sharddev/refusals.ts +5 -3
- package/src/sharddev/reportCard.ts +1 -1
- package/src/sharddev/scene/author.ts +184 -0
- package/src/sharddev/scene/canvas.ts +212 -0
- package/src/sharddev/scene/description.ts +223 -0
- package/src/sharddev/scene/hash.ts +23 -0
- package/src/sharddev/scene/lower.ts +341 -0
- package/src/sharddev/scene/shard.ts +41 -0
- package/src/sharddev/scene/shardfile.ts +621 -0
- package/src/sharddev/threeGate.mjs +14 -0
- package/src/sharddev/threePin.mjs +40 -0
- package/src/sharddev/watch/page.ts +284 -0
- package/src/sharddev/watch/pageEntry.ts +59 -0
- package/src/sharddev/watch/parity-baseline.json +22 -0
- package/src/sharddev/watch/parity.mjs +168 -0
- package/src/sharddev/watch/proof.mjs +199 -0
- package/src/sharddev/watch/protocol.ts +166 -0
- package/src/sharddev/watch/socket.ts +57 -0
- package/src/sharddev/watch/watch.ts +373 -0
- package/src/shards/_template/assets/3058c100bc477fd6fe8268f33b53756b8a2556e7e41c58b2216c703ca7b042c6 +1 -0
- package/src/shards/_template/assets/8a0440f392737a31cf0926a3c7dc011c320144972882945a5462c893e817d94a +0 -0
- package/src/shards/_template/behaviour/door.as +16 -26
- package/src/shards/_template/card/landscape.jpg +0 -0
- package/src/shards/_template/card/portrait.jpg +0 -0
- package/src/shards/_template/card/thumb.jpg +0 -0
- package/src/shards/_template/data/clientScripts.json +43 -43
- package/src/shards/_template/data/creatures.json +2 -2
- package/src/shards/_template/data/look.json +141 -13
- package/src/shards/_template/data/rows.json +20 -2
- package/src/shards/_template/data/skins.json +32 -0
- package/src/shards/_template/data/water.json +18 -0
- package/src/shards/_template/generators/product.ts +5 -1
- package/src/shards/_template/generators/warden.ts +273 -0
- package/src/shards/_template/generators/world.ts +52 -21
- package/src/shards/_template/hero.json +6 -6
- package/src/shards/authoring-slice/generators/shard.ts +14 -0
- package/src/shards/authoring-slice/generators/sky.ts +64 -0
- package/src/shards/authoring-slice/generators/template-sky.ts +27 -0
- package/src/shards/authoring-slice/generators/textures.ts +232 -0
- package/src/shards/authoring-slice/generators/world.ts +518 -0
- package/src/shards/authoring-slice/shard.config.ts +7 -0
- package/src/shards/mossgate/generators/shard.ts +6 -0
- package/src/shards/mossgate/generators/sky.ts +64 -0
- package/src/shards/mossgate/generators/textures.ts +249 -0
- package/src/shards/mossgate/generators/world.ts +998 -0
- package/src/shards/mossgate/shard.config.ts +7 -0
- package/scripts/shard-output-report.d.mts +0 -9
- package/scripts/shard-output-report.mjs +0 -85
- package/scripts/shard-platform-cli.mjs +0 -93
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SHARD-SOURCE AP6 (and AP7's shots): drive a running `wildshard watch` (or `dev`) page in headless Chromium.
|
|
3
|
+
//
|
|
4
|
+
// node src/sharddev/watch/proof.mjs --url http://127.0.0.1:<port>/ --out <dir> [--shots] [--time <file> --runs 10]
|
|
5
|
+
//
|
|
6
|
+
// --shots three cleanroom cameras (Mossgate `scripts/cameras.json`: hut front, hut back, pond) to <out>/<id>.png
|
|
7
|
+
// --time edits <file> `runs` times and times each write to the first frame the page draws with the edit (the page
|
|
8
|
+
// script's `framedAt`, same machine clock); it checks the page never reloaded, the frame loop never stopped and
|
|
9
|
+
// the player never moved, and writes <out>/<prefix>proof.json. The file is restored after.
|
|
10
|
+
// --edit what --time edits (SHARD-SOURCE AP6, AP17): `roof` (a material colour, the default), `fog` (density), `exposure`
|
|
11
|
+
// (the grade), `sun` (the key light's direction), `ambient` (the hemisphere's intensity), `lamp` (a point light's
|
|
12
|
+
// intensity), `hill` (AP18: ground under the player), each a line of the authoring slice's `generators/world.ts`;
|
|
13
|
+
// `quest` (AP19: the slice quest's objective, in `generators/shard.ts`), read from the page's own text.
|
|
14
|
+
// --fps the page's frame cap (default 60: GPU benches share Jake's laptop; 0 leaves it uncapped)
|
|
15
|
+
// --motion at the yard camera: frames 0.2 s apart; the flame (pulse), the near fern (sway) and the page's point lights
|
|
16
|
+
// (flicker) must change with no shard code in the page (SHARD-SOURCE AP12); numbers to <out>/proof.json
|
|
17
|
+
// --draws at each camera, the frame's draws (Game.lastFrame.calls, every pass) and the same with the shadow map held,
|
|
18
|
+
// so view and shadow draws split, plus the props' distinct materials in the scene and the fps (SHARD-SOURCE AP8)
|
|
19
|
+
// --throttle N slows the page's CPU N times (a phone stand-in: --url '<page>?tier=phone' --throttle 4)
|
|
20
|
+
import { chromium } from 'playwright';
|
|
21
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- a node script: it writes the shots and the timing beside the source edit.
|
|
22
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
23
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- a node script resolves its output folder.
|
|
24
|
+
import { join, resolve } from 'node:path';
|
|
25
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- a node script reads its flags.
|
|
26
|
+
import { parseArgs } from 'node:util';
|
|
27
|
+
|
|
28
|
+
const { values } = parseArgs({ options: { url: { type: 'string' }, out: { type: 'string' }, shots: { type: 'boolean' }, motion: { type: 'boolean' }, draws: { type: 'boolean' }, throttle: { type: 'string' }, time: { type: 'string' }, runs: { type: 'string' }, prefix: { type: 'string' }, edit: { type: 'string' }, fps: { type: 'string' } } });
|
|
29
|
+
if (values.url === undefined || values.out === undefined) throw new Error('usage: proof.mjs --url <page> --out <dir> [--shots] [--time <file> --runs N]');
|
|
30
|
+
const OUT = resolve(values.out), RUNS = Number(values.runs ?? 10), PREFIX = values.prefix ?? '';
|
|
31
|
+
mkdirSync(OUT, { recursive: true });
|
|
32
|
+
// Mossgate cleanroom scripts/cameras.json: [x, z, yaw, pitch], eye 1.68 m, vertical FOV 72
|
|
33
|
+
const CAMERAS = [['03-hut-front', -3.9, -5.6, 0.03, -0.04], ['05-door-lamp', -4.6, -7.8, 0.03, 0.05], ['04-hut-back', -3.9, -10.4, 3.4, -0.05], ['08-pond', -10.4, 0.3, 1.571, -0.08], ['yard-brazier', 2.6, -8.2, -0.62, 0.02], ['10-sky-sun', -10.4, 0.3, -0.31, 0.14]];
|
|
34
|
+
// 10-sky-sun: from the pond toward the low sun, the painted sky and its clouds (SHARD-SOURCE AP14)
|
|
35
|
+
// yard-brazier: the slice's brazier A (5.9, -12.8), its fire, sparks and ferns (SHARD-SOURCE AP10 to AP12)
|
|
36
|
+
const colourOf = (i) => ((0x40 + i * 17) << 16 | (0x90 - i * 7) << 8 | (0x30 + i * 13)).toString(16).padStart(6, '0');
|
|
37
|
+
/** The page's roof colour (page code, passed as text). */
|
|
38
|
+
const ROOF_HEX = `() => { let hex = null; window.__wildshard.world.game.rootScene.getObjectByName('devScene')?.traverse((o) => { if (o.material?.name === 'roof') hex = o.material.color.getHexString(); }); return hex; }`;
|
|
39
|
+
/** Each edit: the line it rewrites, its i-th value, and (optionally) a page reader whose value must equal `expect(i)`. */
|
|
40
|
+
const EDITS = {
|
|
41
|
+
roof: { line: /shingle: new THREE\.MeshStandardMaterial\(\{ name: 'roof', (?:color: 0x[0-9a-f]{6}, )?map: tex\.shingle, roughness: 0\.95 \}\),/u,
|
|
42
|
+
write: (i) => `shingle: new THREE.MeshStandardMaterial({ name: 'roof', color: 0x${colourOf(i)}, map: tex.shingle, roughness: 0.95 }),`, read: ROOF_HEX, expect: colourOf },
|
|
43
|
+
fog: { line: /FogExp2\(new THREE\.Color\('#d898a0'\), [0-9.]+\)/u, write: (i) => `FogExp2(new THREE.Color('#d898a0'), ${(0.0040 + i * 0.0005).toFixed(4)})` },
|
|
44
|
+
exposure: { line: /world\.post\(\{ tone: 'aces', exposure: [0-9.]+,/u, write: (i) => `world.post({ tone: 'aces', exposure: ${(0.8 + i * 0.06).toFixed(2)},` },
|
|
45
|
+
sun: { line: /key\.position\.set\(-?[0-9.]+, 30, 34\)/u, write: (i) => `key.position.set(${-30 + i * 6}, 30, 34)` },
|
|
46
|
+
ambient: { line: /new THREE\.Color\('#7a6a3c'\), [0-9.]+\)\);/u, write: (i) => `new THREE.Color('#7a6a3c'), ${(0.55 + i * 0.07).toFixed(2)}));` },
|
|
47
|
+
lamp: { line: /new THREE\.PointLight\('#ffa040', [0-9.]+, 6\.5, 1\.4\)/u, write: (i) => `new THREE.PointLight('#ffa040', ${(4 + i * 0.7).toFixed(1)}, 6.5, 1.4)` },
|
|
48
|
+
// AP18: a flat-topped hill (5 m top, 8 m foot) raised under the player at the first camera, a little higher each edit; the
|
|
49
|
+
// page counts once the player's feet stand on its top, and again a second later (they did not fall through)
|
|
50
|
+
hill: { line: /y \+= far \* \(noise\.fbm\(x \* 0\.02 \+ 50, z \* 0\.02 \+ 50, 3\) - 0\.35\) \* 7;(?: y \+= [0-9.]+ \* Math\.min\(1, Math\.max\(0, \(8 - Math\.hypot\(x \+ 3\.9, z \+ 5\.6\)\) \/ 3\)\);)?/u,
|
|
51
|
+
write: (i) => `y += far * (noise.fbm(x * 0.02 + 50, z * 0.02 + 50, 3) - 0.35) * 7; y += ${(0.2 + i * 0.3).toFixed(1)} * Math.min(1, Math.max(0, (8 - Math.hypot(x + 3.9, z + 5.6)) / 3));`,
|
|
52
|
+
read: '() => Math.round(window.__wildshard.world.player.position.y * 20) / 20', expect: (i) => Math.round((0.2 + i * 0.3) * 20) / 20, held: true },
|
|
53
|
+
};
|
|
54
|
+
// AP19: the quest's objective, as the page's quest panel says it once the simulation restarted on the new rows
|
|
55
|
+
EDITS.quest = { line: /objective: 'Walk down to the pond(?: \(\d+\))?'/u, write: (i) => `objective: 'Walk down to the pond (${i})'`,
|
|
56
|
+
read: '() => /walk down to the pond \\(\\d+\\)/iu.exec(document.body.innerText)?.[0].toLowerCase() ?? null', expect: (i) => `walk down to the pond (${i})` };
|
|
57
|
+
const EDIT = EDITS[values.edit ?? 'roof'];
|
|
58
|
+
const FPS = Number(values.fps ?? 60);
|
|
59
|
+
if (EDIT === undefined) throw new Error(`--edit: one of ${Object.keys(EDITS).join(', ')}`);
|
|
60
|
+
|
|
61
|
+
const browser = await chromium.launch({ headless: true, args: ['--use-mock-keychain', '--password-store=basic', '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] });
|
|
62
|
+
const result = {};
|
|
63
|
+
try {
|
|
64
|
+
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
|
|
65
|
+
// engine's probe controls (pose) answer only a harness-pinned page (engine scripts/debug-settings.mjs harnessPins)
|
|
66
|
+
await page.addInitScript({ content: 'window.__wildshardHarness=Object.assign(window.__wildshardHarness??{},{seed:357});' });
|
|
67
|
+
// the lane rule's 60 fps cap: a frame's callbacks run together, at most one frame per 1/FPS s
|
|
68
|
+
if (FPS > 0) await page.addInitScript({ content: `(() => { const raf = window.requestAnimationFrame.bind(window), gap = 1000 / ${FPS} - 1; let at = -1e9;
|
|
69
|
+
window.requestAnimationFrame = (run) => raf(function held(t) { if (t !== at && t - at < gap) { raf(held); return; } at = t; run(t); }); })();` });
|
|
70
|
+
page.on('pageerror', (error) => { console.error(`page error: ${error.message}`); });
|
|
71
|
+
if (values.throttle !== undefined) await (await page.context().newCDPSession(page)).send('Emulation.setCPUThrottlingRate', { rate: Number(values.throttle) });
|
|
72
|
+
await page.goto(`${values.url}${values.url.includes('?') ? '&' : '?'}skipintro`);
|
|
73
|
+
await page.waitForFunction(() => window.__wildshard?.world?.player !== undefined, undefined, { timeout: 180_000, polling: 500 });
|
|
74
|
+
const watched = await page.waitForFunction(() => (window.__wsDevScene?.framedRevision ?? 0) > 0, undefined, { timeout: 30_000, polling: 250 }).then(() => true, () => false);
|
|
75
|
+
console.info(`page ready (${watched ? 'dev scene host live' : 'no dev scene host: a baked shard'})`);
|
|
76
|
+
await page.evaluate(() => {
|
|
77
|
+
const w = window.__wildshard.world;
|
|
78
|
+
if (w.animals) w.animals.calm = true;
|
|
79
|
+
w.game.onLate(() => { for (const child of w.game.camera.children) child.visible = false; if (Math.abs(w.game.camera.fov - 72) > 0.01) { w.game.camera.fov = 72; w.game.camera.updateProjectionMatrix(); } }, 'ap6.fov');
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
if (values.shots === true) {
|
|
83
|
+
for (const [id, x, z, yaw, pitch] of CAMERAS) {
|
|
84
|
+
await page.evaluate(async (pose) => { await window.__wildshard.pose(pose); }, { x, z, yaw, pitch });
|
|
85
|
+
await page.waitForTimeout(2500);
|
|
86
|
+
await page.screenshot({ path: join(OUT, `${PREFIX}${id}.png`) });
|
|
87
|
+
console.info(`shot ${PREFIX}${id}`);
|
|
88
|
+
}
|
|
89
|
+
// the page's own frame clock, counted for 5 s (page code, passed as text: it runs in the browser, not here)
|
|
90
|
+
result.fps = await page.evaluate(`new Promise((done) => { const w = window.__wildshard.world, t0 = Date.now(); let n = 0; const stop = w.game.watchFrames(() => { n++; if (Date.now() - t0 >= 5000) { stop(); done(Math.round(n / ((Date.now() - t0) / 1000))); } }); })`);
|
|
91
|
+
console.info(`fps ${result.fps} (headless, 1280x720, 5 s at the last camera)`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (values.draws === true) {
|
|
95
|
+
// median of 20 drawn frames' whole-frame draw count (the composer's passes included)
|
|
96
|
+
const sample = `new Promise((done) => { const g = window.__wildshard.world.game, seen = []; const stop = g.watchFrames(() => { seen.push(g.lastFrame.calls); if (seen.length >= 20) { stop(); seen.sort((a, b) => a - b); done(seen[10]); } }); })`;
|
|
97
|
+
result.draws = [];
|
|
98
|
+
for (const [id, x, z, yaw, pitch] of CAMERAS) {
|
|
99
|
+
await page.evaluate(async (pose) => { await window.__wildshard.pose(pose); }, { x, z, yaw, pitch });
|
|
100
|
+
await page.waitForTimeout(2500);
|
|
101
|
+
const total = await page.evaluate(sample);
|
|
102
|
+
await page.evaluate(() => { const s = window.__wildshard.world.game.renderer.shadowMap; s.autoUpdate = false; s.needsUpdate = false; });
|
|
103
|
+
const view = await page.evaluate(sample);
|
|
104
|
+
await page.evaluate(() => { window.__wildshard.world.game.renderer.shadowMap.autoUpdate = true; });
|
|
105
|
+
result.draws.push({ id, total, view, shadow: total - view });
|
|
106
|
+
console.info(`draws ${id}: ${total} (view ${view}, shadow ${total - view})`);
|
|
107
|
+
}
|
|
108
|
+
result.materials = await page.evaluate(() => { const seen = new Set(); window.__wildshard.world.game.rootScene.traverse((o) => { if (o.isMesh && o.visible) for (const m of [o.material].flat()) seen.add(m.uuid); }); return seen.size; });
|
|
109
|
+
console.info(`${result.materials} distinct mesh materials in the scene`);
|
|
110
|
+
result.fps = await page.evaluate(`new Promise((done) => { const w = window.__wildshard.world, t0 = Date.now(); let n = 0; const stop = w.game.watchFrames(() => { n++; if (Date.now() - t0 >= 5000) { stop(); done(Math.round(n / ((Date.now() - t0) / 1000))); } }); })`);
|
|
111
|
+
console.info(`fps ${result.fps} (headless, 5 s at the last camera)`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (values.motion === true) {
|
|
115
|
+
const yard = CAMERAS.find(([id]) => id === 'yard-brazier') ?? CAMERAS[0];
|
|
116
|
+
await page.evaluate(async (pose) => { await window.__wildshard.pose(pose); }, { x: yard[1], z: yard[2], yaw: yard[3], pitch: yard[4] });
|
|
117
|
+
await page.waitForTimeout(2500);
|
|
118
|
+
// regions at 1280x720: the fire's cards, the fern at the left edge, and still ground beside them (the control)
|
|
119
|
+
const regions = { flame: [560, 250, 160, 170], fern: [0, 500, 100, 220], still: [880, 560, 160, 100] };
|
|
120
|
+
const { default: sharp } = await import('sharp');
|
|
121
|
+
const crop = (png, [left, top, width, height]) => sharp(png).extract({ left, top, width, height }).raw().toBuffer();
|
|
122
|
+
const lamps = () => { const out = []; window.__wildshard.world.game.rootScene.traverse((o) => { if (o.isPointLight && o.intensity > 0) out.push(o.intensity); }); return out; };
|
|
123
|
+
const frames = [];
|
|
124
|
+
for (let i = 0; i < 4; i++) { frames.push({ png: await page.screenshot(), lamps: await page.evaluate(`(${lamps.toString()})()`) }); await page.waitForTimeout(200); }
|
|
125
|
+
result.motion = {};
|
|
126
|
+
for (const [name, box] of Object.entries(regions)) {
|
|
127
|
+
let sum = 0, n = 0;
|
|
128
|
+
for (let i = 1; i < frames.length; i++) {
|
|
129
|
+
const a = await crop(frames[i - 1].png, box), b = await crop(frames[i].png, box);
|
|
130
|
+
for (let k = 0; k < a.length; k++) sum += Math.abs(a[k] - b[k]);
|
|
131
|
+
n += a.length;
|
|
132
|
+
}
|
|
133
|
+
result.motion[name] = Number((sum / n).toFixed(2));
|
|
134
|
+
}
|
|
135
|
+
const first = frames[0].lamps, changed = frames.slice(1).some((f) => f.lamps.some((v, k) => Math.abs(v - (first[k] ?? v)) > 1e-4));
|
|
136
|
+
result.motion.lamps = { count: first.length, changed };
|
|
137
|
+
result.motion.shardCode = await page.evaluate(() => Object.keys(globalThis).filter((k) => /^__wsShard|shardModule/u.test(k)));
|
|
138
|
+
await page.screenshot({ path: join(OUT, `${PREFIX}motion.png`) });
|
|
139
|
+
// AP11: the bloom catches the fire: the glow round it with the page's bloom on, less with it set to 0 for a frame
|
|
140
|
+
const ring = [520, 200, 240, 300];
|
|
141
|
+
const mean = async (png) => { const px = await crop(png, ring); let t = 0; for (const v of px) t += v; return t / px.length; };
|
|
142
|
+
const bloomOn = await page.evaluate(() => window.__wildshard.world.game.post?.bloom?.intensity ?? null);
|
|
143
|
+
if (bloomOn !== null && bloomOn > 0) {
|
|
144
|
+
const lit = await mean(await page.screenshot());
|
|
145
|
+
await page.evaluate(() => { window.__wildshard.world.game.post.bloom.intensity = 0; });
|
|
146
|
+
await page.waitForTimeout(300);
|
|
147
|
+
const dark = await mean(await page.screenshot());
|
|
148
|
+
await page.evaluate((v) => { window.__wildshard.world.game.post.bloom.intensity = v; }, bloomOn);
|
|
149
|
+
result.motion.bloom = { intensity: bloomOn, glow: Number((lit - dark).toFixed(2)) };
|
|
150
|
+
} else result.motion.bloom = { intensity: bloomOn, glow: 0 };
|
|
151
|
+
console.info(`bloom ${JSON.stringify(result.motion.bloom)} (mean of 255 round the fire, on minus off)`);
|
|
152
|
+
console.info(`motion: flame ${result.motion.flame}, fern ${result.motion.fern}, still ${result.motion.still} (mean |frame step| of 255), ${first.length} lamps lit, intensities change: ${changed}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (values.time !== undefined) {
|
|
156
|
+
if (!watched) throw new Error('--time needs a `wildshard watch` page');
|
|
157
|
+
const file = resolve(values.time), original = readFileSync(file, 'utf8');
|
|
158
|
+
if (!EDIT.line.test(original)) throw new Error(`--time: ${file} has no ${values.edit ?? 'roof'} line to edit`);
|
|
159
|
+
await page.evaluate(async (pose) => { await window.__wildshard.pose(pose); window.__ap6Marker = 'same page'; }, { x: CAMERAS[0][1], z: CAMERAS[0][2], yaw: CAMERAS[0][3], pitch: CAMERAS[0][4] });
|
|
160
|
+
await page.waitForTimeout(2000);
|
|
161
|
+
const runs = [];
|
|
162
|
+
try {
|
|
163
|
+
for (let i = 0; i < RUNS; i++) {
|
|
164
|
+
// the first edit's value is a change from the file's own (i = 0 may equal it), so count from 1
|
|
165
|
+
const value = i + 1, written = EDIT.write(value);
|
|
166
|
+
if (EDIT.line.exec(readFileSync(file, 'utf8'))?.[0] === written) throw new Error(`--time: edit ${value} writes the line as it is`);
|
|
167
|
+
const before = await page.evaluate(() => ({ revision: window.__wsDevScene.framedRevision, frames: window.__wsDevScene.frames, at: window.__wildshard.world.player.position.toArray() }));
|
|
168
|
+
const at = Date.now();
|
|
169
|
+
writeFileSync(file, original.replace(EDIT.line, written));
|
|
170
|
+
const handle = await page.waitForFunction(([revision, expected, read]) => {
|
|
171
|
+
const report = window.__wsDevScene;
|
|
172
|
+
if (report.framedRevision <= revision) return false;
|
|
173
|
+
// eslint-disable-next-line no-new-func -- the reader is passed in as text
|
|
174
|
+
return read === null || new Function(`return (${read})()`)() === expected ? report.framedAt : false;
|
|
175
|
+
}, [before.revision, EDIT.expect?.(value) ?? null, EDIT.read ?? null], { timeout: 30_000, polling: 'raf' });
|
|
176
|
+
const framedAt = await handle.jsonValue();
|
|
177
|
+
const after = await page.evaluate(() => ({ frames: window.__wsDevScene.frames, at: window.__wildshard.world.player.position.toArray(), marker: window.__ap6Marker, kind: window.__wsDevScene.kind ?? null, restart: window.__wsDevScene.restart ?? null, steps: { ...window.__wsDevScene.steps } }));
|
|
178
|
+
const moved = Math.hypot(...after.at.map((v, k) => v - before.at[k]));
|
|
179
|
+
// the page's own steps, from the file write: its state received, its parts fetched, swapped in, the first frame after
|
|
180
|
+
const steps = after.steps === undefined ? null : { seen: after.steps.seen - at, sent: after.steps.sent - at, received: after.steps.received - at, fetched: after.steps.fetched - at, swapped: after.steps.swapped - at, framed: framedAt - at };
|
|
181
|
+
// a ground edit: still standing on it a second later
|
|
182
|
+
let held = null;
|
|
183
|
+
if (EDIT.held === true) { await page.waitForTimeout(1000); held = await page.evaluate(`(${EDIT.read})()`) === EDIT.expect(value); }
|
|
184
|
+
runs.push({ value: written, ms: framedAt - at, frames: after.frames - before.frames, moved: Number(moved.toFixed(4)), reloaded: after.marker !== 'same page', kind: after.kind, steps, ...(after.kind === 'gameplay' ? { restart: after.restart } : {}), ...(held === null ? {} : { held }) });
|
|
185
|
+
console.info(`edit ${value}: ${written} on screen in ${framedAt - at} ms${after.kind === null ? '' : ` (${after.kind})`}${after.kind === 'gameplay' && after.restart !== null ? ` [server restart ${after.restart.serverMs} ms, quest views ${after.restart.questsMs} ms]` : ''}${steps === null ? '' : ` [seen ${steps.seen}, sent ${steps.sent}, received ${steps.received}, fetched ${steps.fetched}, swapped ${steps.swapped}]`}`);
|
|
186
|
+
await page.waitForTimeout(400);
|
|
187
|
+
}
|
|
188
|
+
} finally { writeFileSync(file, original); }
|
|
189
|
+
const sorted = runs.map((r) => r.ms).sort((a, b) => a - b), median = sorted.length % 2 === 1 ? sorted[(sorted.length - 1) / 2] : (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2;
|
|
190
|
+
result.timing = { edit: values.edit ?? 'roof', runs, median, min: sorted[0], max: sorted.at(-1), reloads: runs.filter((r) => r.reloaded).length, maxMoved: Math.max(...runs.map((r) => r.moved)), frameLoopStopped: runs.some((r) => r.frames <= 0),
|
|
191
|
+
...(EDIT.held === true ? { stood: runs.filter((r) => r.held === true).length } : {}) };
|
|
192
|
+
await page.waitForTimeout(3000);
|
|
193
|
+
await page.screenshot({ path: join(OUT, `${PREFIX}timing-last.png`) });
|
|
194
|
+
console.info(`median ${median} ms (min ${sorted[0]}, max ${sorted.at(-1)}), reloads ${result.timing.reloads}, player moved ≤ ${result.timing.maxMoved} m${result.timing.stood === undefined ? '' : `, still on the hill 1 s later in ${result.timing.stood} of ${runs.length}`}`);
|
|
195
|
+
}
|
|
196
|
+
} finally {
|
|
197
|
+
await browser.close();
|
|
198
|
+
writeFileSync(join(OUT, `${PREFIX}proof.json`), `${JSON.stringify(result, null, 2)}\n`);
|
|
199
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import type { SceneGeometry, ScenePart, ShardScene } from '../scene/description';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SHARD-SOURCE AP5 (J347): the `wildshard watch` protocol, all of it sharddev's. The watch server pushes one `WatchState`
|
|
5
|
+
* per revision over a WebSocket; the page script (`page.ts`, injected into the page `watch` serves) fetches the parts whose
|
|
6
|
+
* hash changed, and only the geometry and rasters it lacks, then drives engine's dev hook. Engine knows none of this: it
|
|
7
|
+
* holds only the hook (`src/client/game/devScene/hook.ts`), whose version is `DEV_HOOK_VERSION` below.
|
|
8
|
+
*
|
|
9
|
+
* WS /__wildshard_scene/socket one `WatchState` (JSON) per revision, the first on connect
|
|
10
|
+
* GET /__wildshard_scene/part/<name> one `WatchPart` (JSON)
|
|
11
|
+
* GET /__wildshard_scene/geometry/<key> one geometry (`encodeGeometry`), immutable by key
|
|
12
|
+
* GET /__wildshard_scene/texture/<key> one RGBA8 raster, row 0 at v = 0, immutable by key
|
|
13
|
+
* GET /__wildshard_scene/ground/<hash> AP18: the whole ground (one terrain tile's wire bytes: 257² heights and
|
|
14
|
+
* colours), immutable by hash, for the hook's `setGround`
|
|
15
|
+
* GET /__wildshard_scene/gameplay/<hash> AP19: the gameplay sections (`GAMEPLAY_SECTIONS`, JSON) for the hook's
|
|
16
|
+
* `restartGameplay`, immutable by hash
|
|
17
|
+
* POST /__wildshard_scene/reshell AP17: the page's look can't take this revision live; build a new shell (the page
|
|
18
|
+
* reloads on the state that names it)
|
|
19
|
+
*/
|
|
20
|
+
export const DEV_SCENE_PATH = '/__wildshard_scene/';
|
|
21
|
+
export const WATCH_SOCKET = '/__wildshard_scene/socket';
|
|
22
|
+
export const WATCH_RESHELL = '/__wildshard_scene/reshell';
|
|
23
|
+
/** The protocol between the watch server and its own page script: they ship together, so a mismatch is a stale page. */
|
|
24
|
+
export const WATCH_WIRE = 5;
|
|
25
|
+
/** The engine dev hook version this sdk drives: engine's `DEV_HOOK_VERSION`, named in a devserver client's build flags. */
|
|
26
|
+
export const DEV_HOOK_VERSION = 4;
|
|
27
|
+
|
|
28
|
+
export interface WatchState {
|
|
29
|
+
readonly wire: number;
|
|
30
|
+
/** the shell the page booted from: a new one (a spawn or fixed look change) means the page reloads */
|
|
31
|
+
readonly shell: number;
|
|
32
|
+
readonly revision: number;
|
|
33
|
+
/** every part and its content hash; a part missing here is gone */
|
|
34
|
+
readonly parts: readonly { readonly name: string; readonly hash: string }[];
|
|
35
|
+
/** the look section the page's shardfile would carry (AP17: day keys, sun arc, exposure, tone, vignette, bloom), set live
|
|
36
|
+
* through the hook's `setLook` */
|
|
37
|
+
readonly look: { readonly hash: string; readonly keys: readonly unknown[]; readonly look: unknown };
|
|
38
|
+
/** AP18: the ground now and the ground the shell was built with (hashes); when they differ the page fetches `ground/<hash>`
|
|
39
|
+
* and swaps it in through the hook's `setGround` */
|
|
40
|
+
readonly ground: { readonly hash: string; readonly shell: string };
|
|
41
|
+
/** AP19: the gameplay sections now and the ones the shell was built with (hashes); when they differ the page fetches
|
|
42
|
+
* `gameplay/<hash>` and restarts its simulation on them through the hook's `restartGameplay` */
|
|
43
|
+
readonly gameplay: { readonly hash: string; readonly shell: string };
|
|
44
|
+
/** AP20: the last full `wildshard build` (watch runs one once edits rest 5 s) and its budget table; null until one ran */
|
|
45
|
+
readonly build: WatchBuild | null;
|
|
46
|
+
/** the last compile's refusal; the page keeps what it has */
|
|
47
|
+
readonly error: string | null;
|
|
48
|
+
/** the wall clock (ms) this revision's edit was seen and its state sent: the timing's server half (AP6, AP17) */
|
|
49
|
+
readonly seenAt: number;
|
|
50
|
+
readonly sentAt: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** AP20: a full build's budget table, as the page shows it: the download, and each tile against its level's caps. */
|
|
54
|
+
export interface WatchBuild {
|
|
55
|
+
/** the revision the build was of, and how long it took */
|
|
56
|
+
readonly revision: number;
|
|
57
|
+
readonly ms: number;
|
|
58
|
+
/** the build's refusal (the shardfile back end or validation); the live page may still draw what the build refuses */
|
|
59
|
+
readonly error: string | null;
|
|
60
|
+
readonly download: number;
|
|
61
|
+
readonly files: number;
|
|
62
|
+
readonly tiles: number;
|
|
63
|
+
readonly triangles: number;
|
|
64
|
+
readonly draws: number;
|
|
65
|
+
/** the tiles over their level's caps (`CONTENT_CAPS`: L0 40k triangles and 8 draws, L1 10k and 2), the worst first */
|
|
66
|
+
readonly over: readonly { readonly tile: string; readonly triangles: number; readonly draws: number; readonly compressed: number }[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A built shardfile's budget table. */
|
|
70
|
+
export function budgetOf(shard: { readonly files: readonly { readonly compressed: number }[]; readonly tiles: readonly { readonly lod: number; readonly x: number; readonly z: number; readonly triangles: number; readonly draws: number; readonly compressed: number }[] }, caps: Readonly<Record<'l0' | 'l1', { readonly triangles: number; readonly draws: number; readonly compressed: number }>>): Omit<WatchBuild, 'revision' | 'ms' | 'error'> {
|
|
71
|
+
const over = shard.tiles.filter((tile) => { const cap = tile.lod === 0 ? caps.l0 : caps.l1; return tile.triangles > cap.triangles || tile.draws > cap.draws || tile.compressed > cap.compressed; })
|
|
72
|
+
.map((tile) => ({ tile: `${tile.lod}/${tile.x}/${tile.z}`, triangles: tile.triangles, draws: tile.draws, compressed: tile.compressed }))
|
|
73
|
+
.sort((a, b) => b.triangles - a.triangles);
|
|
74
|
+
return { download: shard.files.reduce((sum, file) => sum + file.compressed, 0), files: shard.files.length, tiles: shard.tiles.length,
|
|
75
|
+
triangles: shard.tiles.filter((tile) => tile.lod === 0).reduce((sum, tile) => sum + tile.triangles, 0),
|
|
76
|
+
draws: shard.tiles.filter((tile) => tile.lod === 0).reduce((sum, tile) => sum + tile.draws, 0), over };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The budget table as text lines (the page's overlay and the watch log). */
|
|
80
|
+
export function budgetLines(build: WatchBuild): string[] {
|
|
81
|
+
if (build.error !== null) return [`full build of revision ${build.revision} refused: ${build.error}`];
|
|
82
|
+
const mb = (bytes: number): string => `${(bytes / 1_048_576).toFixed(1)} MB`;
|
|
83
|
+
return [`full build of revision ${build.revision} in ${(build.ms / 1000).toFixed(1)} s: ${mb(build.download)} in ${build.files} files`,
|
|
84
|
+
`${build.tiles} tiles, ${build.triangles.toLocaleString('en-US')} triangles and ${build.draws} draws near (L0)`,
|
|
85
|
+
build.over.length === 0 ? 'every tile under its caps' : `${build.over.length} tiles over their caps:`,
|
|
86
|
+
...build.over.slice(0, 6).map((tile) => ` ${tile.tile}: ${tile.triangles.toLocaleString('en-US')} tris, ${tile.draws} draws, ${mb(tile.compressed)}`)];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** One part as the page fetches it: the hook's `DevPart` with geometry and rasters by key, and its colliders. */
|
|
90
|
+
export interface WatchPart {
|
|
91
|
+
readonly name: string;
|
|
92
|
+
readonly hash: string;
|
|
93
|
+
readonly materials: readonly unknown[];
|
|
94
|
+
readonly textures: readonly { readonly key: string; readonly width: number; readonly height: number; readonly colourSpace: 'srgb' | 'linear' }[];
|
|
95
|
+
readonly geometries: readonly string[];
|
|
96
|
+
readonly draws: readonly { readonly geometry: string; readonly material: string; readonly matrix: readonly number[]; readonly castShadow: boolean; readonly receiveShadow: boolean;
|
|
97
|
+
readonly instances: { readonly count: number; readonly matrices: readonly number[]; readonly colours: readonly number[] | null } | null }[];
|
|
98
|
+
readonly sprites: readonly unknown[];
|
|
99
|
+
readonly lamps: readonly unknown[];
|
|
100
|
+
readonly water: readonly unknown[];
|
|
101
|
+
readonly colliders: readonly { readonly centre: readonly number[]; readonly half: readonly number[]; readonly rotation: readonly number[] }[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** One part as the page's `WatchPart` JSON. Lamps and water are the shardfile's own rows (`lampRows`, `waterRows`). */
|
|
105
|
+
export function encodePart(scene: ShardScene, part: ScenePart, rows: { lamps: readonly unknown[]; water: readonly unknown[] }): WatchPart {
|
|
106
|
+
const material = (key: string): unknown => { const row = scene.materials[key]; if (row === undefined) throw new Error(`watch: part ${part.name} names material ${key} the scene lacks`); return row; };
|
|
107
|
+
return {
|
|
108
|
+
name: part.name, hash: part.hash,
|
|
109
|
+
// a Points material draws as the hook's sprite material (each point a sprite, AP11)
|
|
110
|
+
materials: part.materials.map((key) => { const row = material(key) as { kind?: string }; return row.kind === 'points' ? { ...row, kind: 'sprite' } : row; }),
|
|
111
|
+
textures: part.textures.map((key) => { const t = scene.textures[key]; if (t === undefined) throw new Error(`watch: part ${part.name} names texture ${key} the scene lacks`); return { key, width: t.width, height: t.height, colourSpace: t.colourSpace }; }),
|
|
112
|
+
geometries: part.geometries,
|
|
113
|
+
draws: part.draws.map((d) => ({ geometry: d.geometry, material: d.material, matrix: d.matrix, castShadow: d.castShadow, receiveShadow: d.receiveShadow,
|
|
114
|
+
instances: d.instances === null ? null : { count: d.instances.count, matrices: Array.from(d.instances.matrices), colours: d.instances.colours === null ? null : Array.from(d.instances.colours) } })),
|
|
115
|
+
sprites: [...part.sprites.map((s) => ({ material: s.material, position: s.position, scale: s.scale, center: s.center })),
|
|
116
|
+
...part.points.flatMap((cloud) => { const size = ((scene.materials[cloud.material]?.pointSize ?? 0) * 0.7265); const out = []; for (let i = 0; i < cloud.positions.length; i += 3) out.push({ material: cloud.material, position: [cloud.positions[i] ?? 0, cloud.positions[i + 1] ?? 0, cloud.positions[i + 2] ?? 0], scale: [size, size], center: [0.5, 0.5] }); return out; })],
|
|
117
|
+
lamps: rows.lamps, water: rows.water,
|
|
118
|
+
colliders: part.colliders.map((c) => ({ centre: c.centre, half: c.half, rotation: c.rotation })),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Five little-endian u32 element counts (position, normal, uv, colour, index), then each array in that order. */
|
|
123
|
+
export function encodeGeometry(geometry: SceneGeometry): Uint8Array {
|
|
124
|
+
const arrays = [geometry.position, geometry.normal, geometry.uv, geometry.colour, geometry.index];
|
|
125
|
+
const counts = arrays.map((a) => a?.length ?? 0), bytes = new Uint8Array(20 + counts.reduce((n, c) => n + c * 4, 0)), view = new DataView(bytes.buffer);
|
|
126
|
+
counts.forEach((count, i) => { view.setUint32(i * 4, count, true); });
|
|
127
|
+
let offset = 20;
|
|
128
|
+
for (const array of arrays) {
|
|
129
|
+
if (array === null) continue;
|
|
130
|
+
bytes.set(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), offset);
|
|
131
|
+
offset += array.byteLength;
|
|
132
|
+
}
|
|
133
|
+
return bytes;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** `encodeGeometry`'s inverse (the page script's). */
|
|
137
|
+
export function decodeGeometry(key: string, bytes: ArrayBuffer): { key: string; position: Float32Array; normal: Float32Array; uv: Float32Array | null; colour: Float32Array | null; index: Uint32Array | null } {
|
|
138
|
+
const header = new DataView(bytes, 0, 20), [positions = 0, normals = 0, uvs = 0, colours = 0, indices = 0] = [0, 1, 2, 3, 4].map((i) => header.getUint32(i * 4, true));
|
|
139
|
+
let offset = 20;
|
|
140
|
+
const take = (count: number): Float32Array => { const out = new Float32Array(bytes.slice(offset, offset + count * 4)); offset += count * 4; return out; };
|
|
141
|
+
const position = take(positions), normal = take(normals), uv = uvs > 0 ? take(uvs) : null, colour = colours > 0 ? take(colours) : null;
|
|
142
|
+
const index = indices > 0 ? new Uint32Array(bytes.slice(offset, offset + indices * 4)) : null;
|
|
143
|
+
if (offset + indices * 4 !== bytes.byteLength) throw new Error(`watch: geometry ${key} is ${bytes.byteLength} bytes, its header says ${offset + indices * 4}`);
|
|
144
|
+
return { key, position, normal, uv, colour, index };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The shard a watched page boots from: the scene's ground, look, sun, sky and spawn, with every part's draws, sprites,
|
|
149
|
+
* lamps, colliders and water left to the page script, which swaps them live through the dev hook.
|
|
150
|
+
*/
|
|
151
|
+
export function liveShell(scene: ShardScene): ShardScene {
|
|
152
|
+
// AP16: a panel part stays in the shell whole (a state row hides it there); the page streams the other parts
|
|
153
|
+
return { ...scene, parts: scene.parts.map((part) => part.panel !== undefined ? part : ({ ...part, draws: [], sprites: [], points: [], colliders: [], water: [], lights: part.lights.filter((l) => l.kind !== 'point'), materials: [], textures: [], geometries: [] })) };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The devserver client's dev hook version, from its `build-flags.json` (`devHook`, engine's app build writes it), against
|
|
158
|
+
* this sdk's: null when they agree, else why `watch` can't drive that page.
|
|
159
|
+
*/
|
|
160
|
+
export function hookMismatch(flags: unknown): string | null {
|
|
161
|
+
const version = typeof flags === 'object' && flags !== null && 'devHook' in flags ? flags.devHook : undefined;
|
|
162
|
+
if (version === DEV_HOOK_VERSION) return null;
|
|
163
|
+
return version === undefined
|
|
164
|
+
? `this engine client has no dev hook (its build flags name no devHook); wildshard watch needs engine's dev hook v${DEV_HOOK_VERSION}: move the sdk's engine pin to an engine with it, or set WILDSHARD_DEV_CLIENT to a devserver build of one`
|
|
165
|
+
: `this engine client's dev hook is v${String(version)}, this sdk drives v${DEV_HOOK_VERSION}: move the sdk and its engine pin together`;
|
|
166
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- The handshake's accept key is a SHA-1 of the client's key.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- The watch server upgrades its own HTTP requests.
|
|
4
|
+
import type { IncomingMessage } from 'node:http';
|
|
5
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- An upgraded request hands over its raw socket.
|
|
6
|
+
import type { Duplex } from 'node:stream';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* SHARD-SOURCE AP5: the watch server's WebSocket, server to page only (RFC 6455, text frames out; the page sends nothing
|
|
10
|
+
* but a close or a pong). The page script is the only client, on 127.0.0.1, so this is the handshake, one frame writer and
|
|
11
|
+
* a reader that answers a close and a ping: no extensions, no fragmentation, no dependency.
|
|
12
|
+
*/
|
|
13
|
+
export interface WatchSocket { send: (text: string) => void; close: () => void; readonly closed: () => boolean }
|
|
14
|
+
|
|
15
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
16
|
+
|
|
17
|
+
function frame(opcode: number, payload: Buffer): Buffer {
|
|
18
|
+
const length = payload.length, head = length < 126 ? Buffer.alloc(2) : length < 65_536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
|
19
|
+
head[0] = 0x80 | opcode;
|
|
20
|
+
if (length < 126) head[1] = length;
|
|
21
|
+
else if (length < 65_536) { head[1] = 126; head.writeUInt16BE(length, 2); }
|
|
22
|
+
else { head[1] = 127; head.writeBigUInt64BE(BigInt(length), 2); }
|
|
23
|
+
return Buffer.concat([head, payload]);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Answer an upgrade request; null (and a 400) when it isn't a WebSocket handshake. */
|
|
27
|
+
export function acceptSocket(request: IncomingMessage, socket: Duplex, onClose: () => void): WatchSocket | null {
|
|
28
|
+
const key = request.headers['sec-websocket-key'];
|
|
29
|
+
if (typeof key !== 'string' || request.headers.upgrade?.toLowerCase() !== 'websocket') { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); return null; }
|
|
30
|
+
const accept = createHash('sha1').update(`${key}${GUID}`).digest('base64');
|
|
31
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
|
32
|
+
let closed = false, pending = Buffer.alloc(0);
|
|
33
|
+
const end = (): void => { if (closed) return; closed = true; socket.end(); onClose(); };
|
|
34
|
+
socket.on('data', (chunk: Buffer) => {
|
|
35
|
+
pending = Buffer.concat([pending, chunk]);
|
|
36
|
+
while (pending.length >= 2) {
|
|
37
|
+
const opcode = (pending[0] ?? 0) & 0x0f, masked = ((pending[1] ?? 0) & 0x80) !== 0;
|
|
38
|
+
let length = (pending[1] ?? 0) & 0x7f, offset = 2;
|
|
39
|
+
if (length === 126) { if (pending.length < 4) return; length = pending.readUInt16BE(2); offset = 4; }
|
|
40
|
+
else if (length === 127) { if (pending.length < 10) return; length = Number(pending.readBigUInt64BE(2)); offset = 10; }
|
|
41
|
+
const mask = masked ? pending.subarray(offset, offset + 4) : null; if (masked) offset += 4;
|
|
42
|
+
if (pending.length < offset + length) return;
|
|
43
|
+
const payload = Buffer.from(pending.subarray(offset, offset + length));
|
|
44
|
+
if (mask !== null) for (let i = 0; i < payload.length; i++) payload[i] = (payload[i] ?? 0) ^ (mask[i % 4] ?? 0);
|
|
45
|
+
pending = pending.subarray(offset + length);
|
|
46
|
+
if (opcode === 0x8) { if (!closed) socket.write(frame(0x8, Buffer.alloc(0))); end(); return; }
|
|
47
|
+
if (opcode === 0x9 && !closed) socket.write(frame(0xa, payload));
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
socket.on('close', end);
|
|
51
|
+
socket.on('error', () => { end(); socket.destroy(); });
|
|
52
|
+
return {
|
|
53
|
+
send: (text) => { if (!closed) socket.write(frame(0x1, Buffer.from(text, 'utf8'))); },
|
|
54
|
+
close: () => { if (!closed) socket.write(frame(0x8, Buffer.alloc(0))); end(); },
|
|
55
|
+
closed: () => closed,
|
|
56
|
+
};
|
|
57
|
+
}
|