@displayxr/inline3d-tools 0.0.1 → 0.1.0

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.
@@ -0,0 +1,244 @@
1
+ // Pixel analysis for inline3d-check. Pure functions over { width, height, data: RGBA bytes }, so
2
+ // they are unit-tested without a browser (test/analyze.test.mjs).
3
+
4
+ export function crop(img, x, y, w, h) {
5
+ x = Math.max(0, Math.round(x)); y = Math.max(0, Math.round(y));
6
+ w = Math.max(0, Math.min(img.width - x, Math.round(w))); h = Math.max(0, Math.min(img.height - y, Math.round(h)));
7
+ const out = new Uint8Array(w * h * 4);
8
+ for (let j = 0; j < h; j++) out.set(img.data.subarray(((y + j) * img.width + x) * 4, ((y + j) * img.width + x + w) * 4), j * w * 4);
9
+ return { width: w, height: h, data: out };
10
+ }
11
+
12
+ export function halves(img) {
13
+ const hw = Math.floor(img.width / 2);
14
+ return [crop(img, 0, 0, hw, img.height), crop(img, hw, 0, hw, img.height)];
15
+ }
16
+
17
+ /** Luminance composited over mid-grey (so transparent and opaque pixels compare sensibly). */
18
+ export function gray(img) {
19
+ const n = img.width * img.height, g = new Float32Array(n), d = img.data;
20
+ for (let i = 0; i < n; i++) {
21
+ const o = i * 4, a = d[o + 3] / 255;
22
+ const l = 0.2126 * d[o] + 0.7152 * d[o + 1] + 0.0722 * d[o + 2];
23
+ g[i] = l * a + 128 * (1 - a);
24
+ }
25
+ return g;
26
+ }
27
+
28
+ /**
29
+ * What a picture holds: the dominant colour (4-bit quantised RGBA) and the fraction of pixels that
30
+ * differ from it. `blank` = less than 0.3 % of the picture is anything but that one colour —
31
+ * an all-black, all-transparent or flat-filled eye.
32
+ */
33
+ export function contentStats(img) {
34
+ const d = img.data, n = img.width * img.height;
35
+ if (!n) return { blank: true, contentFraction: 0, opaqueFraction: 0, meanLum: 0, lumStd: 0, dominant: null, n };
36
+ const hist = new Map();
37
+ for (let i = 0; i < n; i++) {
38
+ const o = i * 4;
39
+ const k = (d[o] >> 4) | ((d[o + 1] >> 4) << 4) | ((d[o + 2] >> 4) << 8) | ((d[o + 3] >> 4) << 12);
40
+ hist.set(k, (hist.get(k) || 0) + 1);
41
+ }
42
+ let dom = 0, best = -1;
43
+ for (const [k, v] of hist) if (v > best) { best = v; dom = k; }
44
+ const dr = (dom & 15) * 16 + 8, dg = ((dom >> 4) & 15) * 16 + 8, db = ((dom >> 8) & 15) * 16 + 8, da = ((dom >> 12) & 15) * 16 + 8;
45
+ let content = 0, opaque = 0, sum = 0, sum2 = 0;
46
+ for (let i = 0; i < n; i++) {
47
+ const o = i * 4;
48
+ if (Math.abs(d[o] - dr) + Math.abs(d[o + 1] - dg) + Math.abs(d[o + 2] - db) + Math.abs(d[o + 3] - da) > 48) content++;
49
+ if (d[o + 3] > 240) opaque++;
50
+ const l = (0.2126 * d[o] + 0.7152 * d[o + 1] + 0.0722 * d[o + 2]) * (d[o + 3] / 255);
51
+ sum += l; sum2 += l * l;
52
+ }
53
+ const meanLum = sum / n;
54
+ const contentFraction = content / n;
55
+ return {
56
+ blank: contentFraction < 0.003,
57
+ contentFraction,
58
+ opaqueFraction: opaque / n,
59
+ meanLum,
60
+ lumStd: Math.sqrt(Math.max(0, sum2 / n - meanLum * meanLum)),
61
+ dominant: [dr - 8, dg - 8, db - 8, da - 8],
62
+ black: opaque / n > 0.9 && meanLum < 10 && contentFraction < 0.003,
63
+ transparent: da < 16 && contentFraction < 0.003,
64
+ n,
65
+ };
66
+ }
67
+
68
+ /** Mean |A(x) − B(x + s)| over the overlap, on grey arrays of the same w×h. */
69
+ export function madShift(A, B, w, h, s) {
70
+ let sum = 0, cnt = 0;
71
+ const x0 = Math.max(0, -s), x1 = Math.min(w, w - s);
72
+ for (let y = 0; y < h; y++) {
73
+ const r = y * w;
74
+ for (let x = x0; x < x1; x++) { sum += Math.abs(A[r + x] - B[r + x + s]); cnt++; }
75
+ }
76
+ return cnt ? sum / cnt : Infinity;
77
+ }
78
+
79
+ export function std(G) {
80
+ let s = 0, s2 = 0;
81
+ for (const v of G) { s += v; s2 += v * v; }
82
+ const m = s / (G.length || 1);
83
+ return Math.sqrt(Math.max(0, s2 / (G.length || 1) - m * m));
84
+ }
85
+
86
+ /**
87
+ * Compare two eyes. identical: the eyes are the same picture (a duplicated flat image);
88
+ * bestShift / madBest: the single horizontal shift that aligns them best; baseline: the mismatch
89
+ * at a third of the width, i.e. what "unrelated" looks like for this content.
90
+ */
91
+ export function compareEyes(L, R) {
92
+ const w = L.width, h = L.height;
93
+ const a = gray(L), b = gray(R);
94
+ let maxd = 0, big = 0, sum = 0;
95
+ for (let i = 0; i < a.length; i++) { const d = Math.abs(a[i] - b[i]); sum += d; if (d > maxd) maxd = d; if (d > 10) big++; }
96
+ const mad0 = sum / (a.length || 1);
97
+ const S = Math.max(2, Math.round(w * 0.12));
98
+ let madBest = Infinity, bestShift = 0;
99
+ for (let s = -S; s <= S; s++) { const m = madShift(a, b, w, h, s); if (m < madBest) { madBest = m; bestShift = s; } }
100
+ const baseline = madShift(a, b, w, h, Math.round(w / 3));
101
+ return {
102
+ mad0,
103
+ maxDiff: maxd,
104
+ differingFraction: big / (a.length || 1),
105
+ identical: mad0 < 0.5 && big / (a.length || 1) < 0.001,
106
+ bestShift,
107
+ madBest,
108
+ baseline,
109
+ stdL: std(a),
110
+ stdR: std(b),
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Per-block horizontal disparity, right eye relative to left (xR − xL, eye pixels): + = behind the
116
+ * glass (uncrossed), − = in front (crossed). Only textured blocks with a clear match count.
117
+ */
118
+ export function blockDisparity(L, R, { block = 12, maxShiftFrac = 0.12 } = {}) {
119
+ const w = L.width, h = L.height;
120
+ const a = gray(L), b = gray(R);
121
+ const S = Math.max(2, Math.round(w * maxShiftFrac));
122
+ const out = [];
123
+ out.textured = 0;
124
+ for (let by = 0; by + block <= h; by += block) {
125
+ for (let bx = 0; bx + block <= w; bx += block) {
126
+ let s = 0, s2 = 0;
127
+ for (let y = by; y < by + block; y++) for (let x = bx; x < bx + block; x++) { const v = a[y * w + x]; s += v; s2 += v * v; }
128
+ const nn = block * block, m = s / nn, sd = Math.sqrt(Math.max(0, s2 / nn - m * m));
129
+ if (sd < 6) continue;
130
+ out.textured++;
131
+ const costs = [];
132
+ for (let d = -S; d <= S; d++) {
133
+ if (bx + d < 0 || bx + d + block > w) { costs.push(Infinity); continue; }
134
+ let c = 0;
135
+ for (let y = by; y < by + block; y++) { const r = y * w; for (let x = bx; x < bx + block; x++) c += Math.abs(a[r + x] - b[r + x + d]); }
136
+ costs.push(c / nn);
137
+ }
138
+ let bi = 0;
139
+ for (let i = 1; i < costs.length; i++) if (costs[i] < costs[bi]) bi = i;
140
+ const best = costs[bi];
141
+ let second = Infinity;
142
+ for (let i = 0; i < costs.length; i++) if (Math.abs(i - bi) > 2 && costs[i] < second) second = costs[i];
143
+ if (!(best < 0.6 * second) || best > 12) continue;
144
+ // sub-pixel parabola
145
+ let sub = 0;
146
+ if (bi > 0 && bi < costs.length - 1 && isFinite(costs[bi - 1]) && isFinite(costs[bi + 1])) {
147
+ const den = costs[bi - 1] - 2 * best + costs[bi + 1];
148
+ if (den > 1e-6) sub = (0.5 * (costs[bi - 1] - costs[bi + 1])) / den;
149
+ }
150
+ out.push({ x: bx + block / 2, y: by + block / 2, d: bi - S + sub });
151
+ }
152
+ }
153
+ return out;
154
+ }
155
+
156
+ export function quantile(arr, q) {
157
+ if (!arr.length) return null;
158
+ const s = [...arr].sort((x, y) => x - y);
159
+ const i = Math.min(s.length - 1, Math.max(0, (s.length - 1) * q));
160
+ const lo = Math.floor(i), hi = Math.ceil(i);
161
+ return s[lo] + (s[hi] - s[lo]) * (i - lo);
162
+ }
163
+
164
+ /**
165
+ * Seam continuity of a full side-by-side buffer: the step across the middle column relative to
166
+ * the typical step between neighbouring columns. ~1 means the picture runs straight across the
167
+ * middle (one wide flat picture); a stereo pair usually breaks there (the right edge of one eye
168
+ * meets the left edge of the other).
169
+ */
170
+ export function seamRatio(img) {
171
+ const w = img.width, h = img.height, g = gray(img);
172
+ const colDiff = (x) => { let s = 0; for (let y = 0; y < h; y++) s += Math.abs(g[y * w + x] - g[y * w + x + 1]); return s / h; };
173
+ const mid = Math.floor(w / 2) - 1;
174
+ const seam = colDiff(mid);
175
+ const samples = [];
176
+ for (let k = 1; k < 16; k++) { const x = Math.floor((k / 16) * (w - 2)); if (Math.abs(x - mid) > 2) samples.push(colDiff(x)); }
177
+ const typical = quantile(samples, 0.5) || 0;
178
+ return { seam, typical, ratio: seam / Math.max(0.5, typical) };
179
+ }
180
+
181
+ /**
182
+ * A woven canvas holding ONE full-width flat picture instead of two eyes: the halves are not two
183
+ * views of one scene (no horizontal shift explains one by the other). seamRatio is reported
184
+ * alongside (a picture that runs on across the middle is the typical signature).
185
+ */
186
+ export function flatWideVerdict(buf) {
187
+ const [L, R] = halves(buf);
188
+ const cmp = compareEyes(L, R);
189
+ const seam = seamRatio(buf);
190
+ const statsL = contentStats(L), statsR = contentStats(R);
191
+ // Two tests, both must hold for "two views of one scene": a single shift explains most of the
192
+ // picture (global), and most textured blocks of EACH half find their match in the other within
193
+ // ±12 % of the eye width (local; on a plain background the global test alone is fooled).
194
+ const fwd = blockDisparity(L, R), back = blockDisparity(R, L);
195
+ const textured = fwd.textured + back.textured;
196
+ const matchRatio = textured ? (fwd.length + back.length) / textured : 1;
197
+ const sameScene = cmp.identical || (cmp.madBest < Math.max(3, 0.35 * cmp.baseline) && (textured < 8 || matchRatio >= 0.35));
198
+ // The seam is evidence, not a gate: on a mostly uniform background the "typical" column step is
199
+ // ~0 and any content crossing the middle looks like a break. Two halves that no shift within
200
+ // ±12 % of the eye width explains are not a stereo pair a display could fuse either way.
201
+ const flatWide = !sameScene && !statsL.blank && !statsR.blank && cmp.stdL > 4 && cmp.stdR > 4;
202
+ return { flatWide, sameScene, cmp, seam, matchRatio, textured };
203
+ }
204
+
205
+ /**
206
+ * A raw side-by-side pair shown FLAT (in an <img>, a 2D canvas, a video, or a woven canvas the
207
+ * browser is not weaving): the element's two halves are nearly the same picture.
208
+ */
209
+ export function sbsPairVerdict(region) {
210
+ if (region.width < 40 || region.height < 20) return { sbs: false, reason: 'too small' };
211
+ const [L, R] = halves(region);
212
+ const w = L.width, h = L.height;
213
+ const a = gray(L), b = gray(R);
214
+ const sL = std(a), sR = std(b);
215
+ const S = Math.max(2, Math.round(w * 0.06));
216
+ let madBest = Infinity, shift = 0;
217
+ for (let s = -S; s <= S; s++) { const m = madShift(a, b, w, h, s); if (m < madBest) { madBest = m; shift = s; } }
218
+ const baseline = madShift(a, b, w, h, Math.round(w / 3));
219
+ const sbs = sL > 10 && sR > 10 && madBest < 12 && madBest < 0.4 * baseline;
220
+ return { sbs, madBest, baseline, shift, stdL: sL, stdR: sR };
221
+ }
222
+
223
+ /** Shibata comfort zone at a viewing distance, as screen disparity in mm (same as the SDK's ./depth comfortZone). */
224
+ export function shibataZoneMm(viewerM = 0.65, eyeSepM = 0.063) {
225
+ const Dv = 1 / viewerM;
226
+ const frontD = Dv / 1.035 + 0.626 - Dv;
227
+ const far = Dv / 1.129 - 0.442;
228
+ const behindD = far > 0 ? Dv - far : Infinity;
229
+ const mm = (d) => eyeSepM * viewerM * d * 1000;
230
+ return { frontMm: mm(frontD), behindMm: mm(behindD) };
231
+ }
232
+
233
+ export function fromBase64Rgba(b64, w, h) {
234
+ return { width: w, height: h, data: new Uint8Array(Buffer.from(b64, 'base64')) };
235
+ }
236
+
237
+ /** Mean absolute grey difference between two equally sized regions (0..255); Infinity if sizes differ. */
238
+ export function regionDiff(A, B) {
239
+ if (!A || !B || A.width !== B.width || A.height !== B.height) return Infinity;
240
+ const a = gray(A), b = gray(B);
241
+ let t = 0;
242
+ for (let i = 0; i < a.length; i++) t += Math.abs(a[i] - b[i]);
243
+ return t / a.length;
244
+ }
@@ -0,0 +1,174 @@
1
+ // Minimal Chrome DevTools Protocol client over --remote-debugging-pipe.
2
+ //
3
+ // Zero dependencies on purpose: the checker must run with nothing but Node and a local Chrome, so
4
+ // an agent can call it without an `npm install`. The pipe transport also means no TCP port is
5
+ // opened at all (no clash with any other debugger on the box), and the browser is a child process
6
+ // we own: close() ends exactly that pid and removes its throwaway profile.
7
+
8
+ import { spawn } from 'node:child_process';
9
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { join } from 'node:path';
12
+
13
+ const DEFAULT_CHROME = {
14
+ darwin: [
15
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
16
+ '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
17
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
18
+ ],
19
+ linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser'],
20
+ win32: [
21
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
22
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
23
+ ],
24
+ };
25
+
26
+ export function findChrome() {
27
+ if (process.env.CHROME) return process.env.CHROME;
28
+ for (const p of DEFAULT_CHROME[process.platform] || []) if (existsSync(p)) return p;
29
+ return null;
30
+ }
31
+
32
+ export async function launchChrome({ chrome = findChrome(), extraArgs = [], width = 1280, height = 800 } = {}) {
33
+ if (!chrome || !existsSync(chrome)) {
34
+ throw new Error(`Chrome not found${chrome ? ` at ${chrome}` : ''}. Set CHROME=/path/to/chrome.`);
35
+ }
36
+ const profile = mkdtempSync(join(tmpdir(), 'inline3d-check-'));
37
+ const args = [
38
+ '--headless=new',
39
+ '--remote-debugging-pipe',
40
+ `--user-data-dir=${profile}`,
41
+ '--no-first-run',
42
+ '--no-default-browser-check',
43
+ '--disable-extensions',
44
+ '--disable-sync',
45
+ '--disable-component-update',
46
+ '--disable-background-networking',
47
+ '--disable-background-timer-throttling',
48
+ '--disable-renderer-backgrounding',
49
+ '--disable-backgrounding-occluded-windows',
50
+ '--autoplay-policy=no-user-gesture-required',
51
+ '--mute-audio',
52
+ '--hide-scrollbars',
53
+ '--enable-gpu',
54
+ '--ignore-gpu-blocklist',
55
+ '--enable-unsafe-swiftshader', // a software WebGL fallback where there is no GPU (CI)
56
+ `--window-size=${width},${height}`,
57
+ ...(process.platform === 'darwin' ? ['--use-angle=metal'] : []),
58
+ ...extraArgs,
59
+ 'about:blank',
60
+ ];
61
+ const proc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
62
+ let stderr = '';
63
+ proc.stderr.on('data', (d) => {
64
+ stderr = (stderr + d.toString()).slice(-4000);
65
+ });
66
+ const conn = new Connection(proc.stdio[3], proc.stdio[4]);
67
+ let exited = false;
68
+ const exitPromise = new Promise((r) => proc.once('exit', () => { exited = true; r(); }));
69
+ proc.once('error', (e) => conn._fail(e));
70
+ exitPromise.then(() => conn._fail(new Error(`Chrome exited. ${stderr.split('\n').slice(-5).join(' ')}`)));
71
+
72
+ // First round trip proves the pipe is up.
73
+ try {
74
+ await withTimeout(conn.send('Browser.getVersion'), 15000, 'Chrome did not answer on the DevTools pipe');
75
+ } catch (e) {
76
+ try { process.kill(proc.pid, 'SIGKILL'); } catch { /* gone */ }
77
+ try { rmSync(profile, { recursive: true, force: true }); } catch { /* best effort */ }
78
+ throw new Error(`${e.message}. Chrome stderr: ${stderr.split('\n').slice(-6).join(' | ')}`);
79
+ }
80
+
81
+ async function close() {
82
+ try {
83
+ if (!exited) await withTimeout(conn.send('Browser.close'), 3000, 'Browser.close');
84
+ } catch {
85
+ /* fall through to the kill */
86
+ }
87
+ if (!exited) {
88
+ try { process.kill(proc.pid, 'SIGKILL'); } catch { /* already gone */ }
89
+ }
90
+ await withTimeout(exitPromise, 5000, 'chrome exit').catch(() => {});
91
+ try { rmSync(profile, { recursive: true, force: true }); } catch { /* best effort */ }
92
+ }
93
+ return { conn, proc, pid: proc.pid, close, stderr: () => stderr };
94
+ }
95
+
96
+ export function withTimeout(p, ms, what) {
97
+ let t;
98
+ return Promise.race([
99
+ p,
100
+ new Promise((_, rej) => { t = setTimeout(() => rej(new Error(`timeout after ${ms} ms: ${what}`)), ms); }),
101
+ ]).finally(() => clearTimeout(t));
102
+ }
103
+
104
+ class Connection {
105
+ constructor(write, read) {
106
+ this._w = write;
107
+ this._id = 0;
108
+ this._pending = new Map();
109
+ this._listeners = new Map(); // `${sessionId}|${method}` -> Set<fn>
110
+ this._dead = null;
111
+ let buf = '';
112
+ read.on('data', (chunk) => {
113
+ buf += chunk.toString('utf8');
114
+ let i;
115
+ while ((i = buf.indexOf('\0')) >= 0) {
116
+ const msg = buf.slice(0, i);
117
+ buf = buf.slice(i + 1);
118
+ if (msg) this._onMessage(msg);
119
+ }
120
+ });
121
+ }
122
+ _fail(err) {
123
+ if (this._dead) return;
124
+ this._dead = err;
125
+ for (const { rej } of this._pending.values()) rej(err);
126
+ this._pending.clear();
127
+ }
128
+ _onMessage(raw) {
129
+ let m;
130
+ try { m = JSON.parse(raw); } catch { return; }
131
+ if (m.id !== undefined) {
132
+ const p = this._pending.get(m.id);
133
+ if (!p) return;
134
+ this._pending.delete(m.id);
135
+ if (m.error) p.rej(new Error(`${p.method}: ${m.error.message}${m.error.data ? ` (${m.error.data})` : ''}`));
136
+ else p.res(m.result);
137
+ return;
138
+ }
139
+ const set = this._listeners.get(`${m.sessionId || ''}|${m.method}`);
140
+ if (set) for (const fn of [...set]) { try { fn(m.params || {}); } catch { /* listener bug: ignore */ } }
141
+ }
142
+ send(method, params = {}, sessionId) {
143
+ if (this._dead) return Promise.reject(this._dead);
144
+ const id = ++this._id;
145
+ const msg = { id, method, params };
146
+ if (sessionId) msg.sessionId = sessionId;
147
+ return new Promise((res, rej) => {
148
+ this._pending.set(id, { res, rej, method });
149
+ this._w.write(JSON.stringify(msg) + '\0');
150
+ });
151
+ }
152
+ on(method, fn, sessionId = '') {
153
+ const k = `${sessionId}|${method}`;
154
+ if (!this._listeners.has(k)) this._listeners.set(k, new Set());
155
+ this._listeners.get(k).add(fn);
156
+ return () => this._listeners.get(k)?.delete(fn);
157
+ }
158
+ /** A page in its own browser context (fresh cache/storage), attached in flatten mode. */
159
+ async newPage() {
160
+ const { browserContextId } = await this.send('Target.createBrowserContext', { disposeOnDetach: true });
161
+ const { targetId } = await this.send('Target.createTarget', { url: 'about:blank', browserContextId });
162
+ const { sessionId } = await this.send('Target.attachToTarget', { targetId, flatten: true });
163
+ const page = {
164
+ sessionId,
165
+ send: (m, p) => this.send(m, p, sessionId),
166
+ on: (m, fn) => this.on(m, fn, sessionId),
167
+ close: async () => {
168
+ try { await this.send('Target.closeTarget', { targetId }); } catch { /* gone */ }
169
+ try { await this.send('Target.disposeBrowserContext', { browserContextId }); } catch { /* gone */ }
170
+ },
171
+ };
172
+ return page;
173
+ }
174
+ }
@@ -0,0 +1,66 @@
1
+ // inline3d-tools check — does this @displayxr/inline3d page really render glasses-free 3D?
2
+ //
3
+ // inline3d-tools check <url | dir | file.html> [--root <dir>] [--max-texture 4096] [--json] [--out report.json]
4
+ //
5
+ // Loads the page in headless Chrome twice: once inside a FAKE DisplayXR inline-3D environment (the
6
+ // SDK believes it is in the DisplayXR Browser and renders two eyes), once plain (the 2D fallback).
7
+ // Exit code: 0 pass or warnings only, 1 a check failed, 2 the checker itself could not run.
8
+ // Needs Node >= 18 and a local Chrome (CHROME=/path/to/chrome to override).
9
+ import { writeFileSync } from 'node:fs';
10
+ import { runCheck, formatHuman, VERSION } from './run.mjs';
11
+
12
+ export const USAGE = `inline3d-tools check ${VERSION}
13
+ usage: inline3d-tools check <url | dir | file.html> [options]
14
+
15
+ <url> a running page (your dev server: http://localhost:5173/)
16
+ <dir|file.html> served from --root (default: the dir itself / the file's dir) on 127.0.0.1
17
+ options:
18
+ --root <dir> serve this directory (use the project root when the page imports ../ or /node_modules/)
19
+ --max-texture <n> simulate a device MAX_TEXTURE_SIZE (4096 = the Android tablet)
20
+ --timeout <ms> how long to wait for the 3D run to settle (default 15000)
21
+ --viewport WxH default 1280x800
22
+ --no-fallback skip the plain-browser (2D fallback) run
23
+ --json print the JSON report only
24
+ --out <file> also write the JSON report to a file
25
+ env: CHROME=/path/to/chrome`;
26
+
27
+ function parse(argv) {
28
+ const o = { target: null, json: false, out: null, opt: {} };
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ const val = () => { const v = argv[++i]; if (v === undefined) throw new Error(`${a} needs a value`); return v; };
32
+ if (a === '-h' || a === '--help') o.help = true;
33
+ else if (a === '--version') o.version = true;
34
+ else if (a === '--json') o.json = true;
35
+ else if (a === '--out') o.out = val();
36
+ else if (a === '--root') o.opt.root = val();
37
+ else if (a === '--max-texture') o.opt.maxTexture = parseInt(val(), 10) || 0;
38
+ else if (a === '--timeout') o.opt.timeoutMs = parseInt(val(), 10) || 15000;
39
+ else if (a === '--no-fallback') o.opt.fallback = false;
40
+ else if (a === '--viewport') { const [w, h] = val().split('x').map(Number); o.opt.viewport = { width: w || 1280, height: h || 800, dpr: 1 }; }
41
+ else if (a.startsWith('-')) throw new Error(`unknown option ${a}`);
42
+ else if (!o.target) o.target = a;
43
+ else throw new Error(`unexpected argument ${a}`);
44
+ }
45
+ if (!o.target && !o.help && !o.version) throw new Error('missing target');
46
+ return o;
47
+ }
48
+
49
+ // Returns the exit code: 0 pass or warnings only, 1 a check failed, 2 the checker could not run.
50
+ export async function main(argv) {
51
+ let args;
52
+ try { args = parse(argv); } catch (e) { console.error(`${e.message}\n\n${USAGE}`); return 2; }
53
+ if (args.help) { console.log(USAGE); return 0; }
54
+ if (args.version) { console.log(VERSION); return 0; }
55
+ try {
56
+ const report = await runCheck(args.target, args.opt);
57
+ if (args.out) writeFileSync(args.out, JSON.stringify(report, null, 2));
58
+ console.log(args.json ? JSON.stringify(report, null, 2) : formatHuman(report));
59
+ return report.verdict === 'fail' ? 1 : 0;
60
+ } catch (e) {
61
+ const err = { tool: 'inline3d-check', version: VERSION, target: args.target, verdict: 'error', error: e.message };
62
+ if (args.json) console.log(JSON.stringify(err, null, 2));
63
+ else console.error(`inline3d-tools check: ${e.message}`);
64
+ return 2;
65
+ }
66
+ }