@clarity-js/port 0.0.0-stage → 1.5.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/README.md +253 -2
- package/bin/clarity-port.js +68 -0
- package/package.json +21 -4
- package/src/fiber.js +277 -0
- package/src/index.js +153 -0
- package/src/react.js +999 -0
- package/src/three.js +614 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/port — React components and three.js scenes, ported to Clarity.js.
|
|
3
|
+
*
|
|
4
|
+
* import { portReact, portThree, portFiles } from '@clarity-js/port'
|
|
5
|
+
*
|
|
6
|
+
* `portReact(source, { typescript, filename })` ports one React file's text (src/react.js);
|
|
7
|
+
* a file that draws with React Three Fiber comes out as @clarity-js/gl markup (src/fiber.js).
|
|
8
|
+
* `portThree(source, { typescript, filename })` ports a script that builds a three.js scene (src/three.js).
|
|
9
|
+
* `portFiles(paths, options)` ports files and folders on disk: it writes each `.clarity` file
|
|
10
|
+
* (and the module that goes beside it), compiles and lints what it wrote, and gives back, per
|
|
11
|
+
* file, what it did and what is left for a person.
|
|
12
|
+
*
|
|
13
|
+
* Author: Özdemir Şarman
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { portReact } from './react.js';
|
|
19
|
+
import { portThree, isThreeScript } from './three.js';
|
|
20
|
+
|
|
21
|
+
export { portReact, portThree, isThreeScript };
|
|
22
|
+
|
|
23
|
+
const SOURCES = /\.(jsx|tsx)$/;
|
|
24
|
+
const SCRIPTS = /\.(js|mjs|ts)$/; // … of which only those that build a three.js scene are ported
|
|
25
|
+
const SKIP = new Set(['node_modules', 'dist', 'build', '.git', '.next', 'coverage', 'out']);
|
|
26
|
+
const TESTS = /\.(test|spec|stories)\.[jt]sx$/;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Every .jsx and .tsx file under the paths given (tests and stories are left out), and every
|
|
30
|
+
* .js, .mjs and .ts file that builds a three.js scene (it imports three and makes a Scene).
|
|
31
|
+
*/
|
|
32
|
+
export function findSources(paths) {
|
|
33
|
+
const found = [];
|
|
34
|
+
const walk = (p, named) => {
|
|
35
|
+
const stat = fs.statSync(p);
|
|
36
|
+
if (stat.isDirectory()) { for (const name of fs.readdirSync(p).sort()) if (!SKIP.has(name) && !name.startsWith('.')) walk(path.join(p, name), false); }
|
|
37
|
+
else if (SOURCES.test(p) && (named || !TESTS.test(p))) found.push(path.resolve(p));
|
|
38
|
+
// a script found in a folder is taken only when it builds a scene; one named on its own is always tried
|
|
39
|
+
else if (SCRIPTS.test(p) && !/\.d\.ts$/.test(p) && (named || (!/\.(test|spec|config)\.\w+$/.test(p) && stat.size < 2e6 && isThreeScript(fs.readFileSync(p, 'utf8'))))) found.push(path.resolve(p));
|
|
40
|
+
};
|
|
41
|
+
for (const p of paths) walk(p, true);
|
|
42
|
+
return [...new Set(found)];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @typedef {object} PortedFile
|
|
47
|
+
* @property {string} from the React file, or the three.js script
|
|
48
|
+
* @property {string | null} to the `.clarity` file written (or that would be), null when the file holds no function component
|
|
49
|
+
* @property {string | null} shared the module written beside it, if any
|
|
50
|
+
* @property {string[]} components
|
|
51
|
+
* @property {import('./react.js').PortNote[]} notes
|
|
52
|
+
* @property {boolean} compiles the written file compiles
|
|
53
|
+
* @property {string | null} error why it does not
|
|
54
|
+
* @property {Array<{ line: number, column: number, rule: string, message: string, severity: string }>} lint what the linter says about it
|
|
55
|
+
* @property {'ported' | 'needs work' | 'does not compile' | 'nothing to port'} status
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Ports React files and three.js scripts on disk.
|
|
60
|
+
*
|
|
61
|
+
* @param {string[]} paths files and folders
|
|
62
|
+
* @param {object} options
|
|
63
|
+
* @param {object} options.typescript the `typescript` module (the parser)
|
|
64
|
+
* @param {(source: string, options: object) => { code: string }} [options.compile] Clarity's `compile`: with it every file is compiled
|
|
65
|
+
* @param {(source: string, options: object) => { issues: object[] }} [options.lint] Clarity's `lintCode`
|
|
66
|
+
* @param {string} [options.out] a folder to write into (the files keep their places under the first path given); default: beside each source
|
|
67
|
+
* @param {boolean} [options.write=true] false: write nothing, only say what would be written
|
|
68
|
+
* @returns {PortedFile[]}
|
|
69
|
+
*/
|
|
70
|
+
export function portFiles(paths, options = {}) {
|
|
71
|
+
const ts = options.typescript;
|
|
72
|
+
if (typeof ts?.createSourceFile !== 'function') throw new Error('portFiles needs the `typescript` module with its JavaScript API (TypeScript 5 or 6; TypeScript 7.0 has none): portFiles(paths, { typescript })');
|
|
73
|
+
const sources = findSources(paths);
|
|
74
|
+
// the files that give a component: an import of one of them will name its .clarity file (a .tsx file that
|
|
75
|
+
// holds only styled elements, constants or types gives none, and keeps its import as it is)
|
|
76
|
+
const set = new Set();
|
|
77
|
+
for (const f of sources.filter((x) => SOURCES.test(x))) { try { if (portReact(fs.readFileSync(f, 'utf8'), { typescript: ts, filename: path.basename(f) }).clarity) set.add(f.replace(SOURCES, '')); } catch { /* it is told below */ } }
|
|
78
|
+
const root = paths.length === 1 && fs.statSync(paths[0]).isDirectory() ? path.resolve(paths[0]) : null;
|
|
79
|
+
const results = [];
|
|
80
|
+
for (const from of sources) {
|
|
81
|
+
const text = fs.readFileSync(from, 'utf8');
|
|
82
|
+
const script = !SOURCES.test(from); // a three.js script
|
|
83
|
+
const typed = /\.tsx$/.test(from);
|
|
84
|
+
// an import names a component that is ported too when its file is one of those being ported
|
|
85
|
+
const isComponentFile = (spec) => spec.startsWith('.') && (set.has(path.resolve(path.dirname(from), spec.replace(/\.[jt]sx?$/, ''))) || set.has(path.resolve(path.dirname(from), spec, 'index')));
|
|
86
|
+
let r;
|
|
87
|
+
try { r = script ? portThree(text, { typescript: ts, filename: path.basename(from) }) : portReact(text, { typescript: ts, filename: path.basename(from), isComponentFile }); }
|
|
88
|
+
catch (e) { results.push({ from, to: null, shared: null, components: [], notes: [{ line: 1, level: 'todo', text: `could not be read: ${String(e.message).split('\n')[0]}` }], compiles: false, error: String(e.message).split('\n')[0], lint: [], status: 'does not compile' }); continue; }
|
|
89
|
+
if (!r.clarity) { results.push({ from, to: null, shared: null, components: [], notes: r.notes, compiles: false, error: null, lint: [], status: 'nothing to port' }); continue; }
|
|
90
|
+
|
|
91
|
+
const folder = options.out && root ? path.join(path.resolve(options.out), path.relative(root, path.dirname(from))) : options.out ? path.resolve(options.out) : path.dirname(from);
|
|
92
|
+
// a component's file is named as the component is: spin-top.js becomes SpinTop.clarity
|
|
93
|
+
const to = path.join(folder, script ? `${r.components[0]}.clarity` : path.basename(from).replace(SOURCES, '.clarity'));
|
|
94
|
+
const shared = r.shared ? path.join(folder, r.shared.name) : null;
|
|
95
|
+
let compiles = true, error = null, lint = [];
|
|
96
|
+
if (options.compile) {
|
|
97
|
+
try { options.compile(r.clarity, { filename: to, typescript: typed ? ts : undefined }); }
|
|
98
|
+
catch (e) { compiles = false; error = String(e.message).split('\n')[0]; }
|
|
99
|
+
}
|
|
100
|
+
if (compiles && options.lint) {
|
|
101
|
+
try { lint = options.lint(r.clarity, { filename: to, typescript: typed ? ts : undefined }).issues.map(({ line, column, rule, message, severity }) => ({ line, column, rule, message, severity })); } catch { lint = []; }
|
|
102
|
+
}
|
|
103
|
+
if (options.write !== false) {
|
|
104
|
+
fs.mkdirSync(folder, { recursive: true });
|
|
105
|
+
fs.writeFileSync(to, r.clarity);
|
|
106
|
+
if (shared) fs.writeFileSync(shared, r.shared.code);
|
|
107
|
+
}
|
|
108
|
+
const left = r.notes.filter((n) => n.level === 'todo').length;
|
|
109
|
+
// a name that is not there, or one declared twice, is a mistake in what was written, whatever the notes say
|
|
110
|
+
const wrong = lint.filter(isMistake).length;
|
|
111
|
+
results.push({ from, to, shared, components: r.components, notes: r.notes, compiles, error, lint, status: !compiles ? 'does not compile' : left || wrong ? 'needs work' : 'ported' });
|
|
112
|
+
}
|
|
113
|
+
return results;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A remark of the linter that says the written file is wrong (not one about style, or about something unused). */
|
|
117
|
+
const isMistake = (issue) => issue.severity === 'error' || issue.rule === 'no-undef';
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The results as a report for a terminal.
|
|
121
|
+
* @param {PortedFile[]} results
|
|
122
|
+
* @param {{ cwd?: string, verbose?: boolean }} [options] verbose: also the rules that were applied
|
|
123
|
+
* @returns {string}
|
|
124
|
+
*/
|
|
125
|
+
export function formatReport(results, options = {}) {
|
|
126
|
+
const cwd = options.cwd ?? process.cwd();
|
|
127
|
+
const rel = (f) => (path.relative(cwd, f) || f).split(path.sep).join('/');
|
|
128
|
+
const lines = [];
|
|
129
|
+
// a remark is a sentence or two: it is folded at 88 columns, under its own start
|
|
130
|
+
const fold = (head, text) => {
|
|
131
|
+
const out = []; let line = head;
|
|
132
|
+
for (const word of text.split(' ')) { if (line.length + word.length > 88 && line.trim().length > head.trim().length) { out.push(line.trimEnd()); line = ' '.repeat(head.length) + word + ' '; } else line += word + ' '; }
|
|
133
|
+
out.push(line.trimEnd());
|
|
134
|
+
return out;
|
|
135
|
+
};
|
|
136
|
+
const MARK = { ported: '✓', 'needs work': '~', 'does not compile': '✗', 'nothing to port': '-' };
|
|
137
|
+
for (const r of results) {
|
|
138
|
+
const todos = r.notes.filter((n) => n.level === 'todo'), rules = r.notes.filter((n) => n.level === 'done');
|
|
139
|
+
if (r.status === 'nothing to port') { lines.push(`- ${rel(r.from)}: ${SOURCES.test(r.from) ? 'no function component in it' : 'no scene a rule can follow'}${todos.length ? '' : ' (left as it is)'}`); for (const n of todos) lines.push(...fold(` line ${n.line}: `, n.text)); continue; }
|
|
140
|
+
if (!r.to) { lines.push(`${MARK[r.status]} ${rel(r.from)}: ${r.error ?? 'could not be read'}`); continue; }
|
|
141
|
+
lines.push(`${MARK[r.status]} ${rel(r.from)} → ${rel(r.to)}${r.shared ? ` (+ ${path.basename(r.shared)})` : ''}: ${r.status === 'ported' ? `compiles, nothing left to do` : r.status === 'needs work' ? `compiles; ${[todos.length ? `${todos.length} thing${todos.length === 1 ? '' : 's'} left for you` : '', r.lint.some(isMistake) ? `the linter found ${r.lint.filter(isMistake).length === 1 ? 'a mistake' : `${r.lint.filter(isMistake).length} mistakes`} in it` : ''].filter(Boolean).join(', and ')}` : `does not compile yet: ${r.error}`}`);
|
|
142
|
+
for (const n of todos) lines.push(...fold(` line ${n.line}: `, n.text));
|
|
143
|
+
if (options.verbose) for (const n of rules) lines.push(...fold(` (line ${n.line}: `, `${n.text})`));
|
|
144
|
+
for (const i of r.lint) lines.push(...fold(` lint ${rel(r.to)}:${i.line}:${i.column} `, `${i.rule}: ${i.message}`));
|
|
145
|
+
}
|
|
146
|
+
const count = (s) => results.filter((r) => r.status === s).length;
|
|
147
|
+
lines.push('');
|
|
148
|
+
const parts = [[count('ported'), 'ported'], [count('needs work'), 'with things left for you'], [count('does not compile'), 'that do not compile yet'], [count('nothing to port'), 'with nothing to port']].filter(([n]) => n).map(([n, what]) => `${n} ${what}`);
|
|
149
|
+
lines.push(`${results.length} file${results.length === 1 ? '' : 's'}${parts.length ? ': ' + parts.join(', ') : ''}.`);
|
|
150
|
+
lines.push('A port is by rule: read each file once, and use the page.');
|
|
151
|
+
if (results.some((r) => r.notes.some((n) => n.level === 'todo'))) lines.push('The lines above say where a rule did not reach.');
|
|
152
|
+
return lines.join('\n');
|
|
153
|
+
}
|