Repository navigation
Expand file tree
/
Copy pathcode-reference.mjs
More file actions
150 lines (143 loc) · 8.2 KB
/
Copy pathcode-reference.mjs
File metadata and controls
150 lines (143 loc) · 8.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/**
* Code reference for the wiki (wiki/PHP-Reference.md, wiki/JS-Reference.md), read from the source:
* - PHP: every named function and class method in admin/, inc/, src/ and pds-blocks.php, with the first line
* of its docblock (or the //===> comment above it) as the description.
* - JS: PhenixElements methods (src/scripts), window.PhenixBlocks helpers, PhenixBlocks.dataLists, window.PdsAdmin.
* File names only, no line numbers: they would make docs:check fail on every unrelated edit.
*/
import fs from 'node:fs';
import path from 'node:path';
const rel = (root, file) => path.relative(root, file).replace(/\\/g, '/');
const cell = (value) => String(value).replace(/\|/g, '\\|').replace(/</g, '<').replace(/>/g, '>');
//===> All files with an extension under some folders (sorted, so the output is the same on every OS) <===//
const filesIn = (root, dirs, ext, skip = []) => {
const out = [];
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).forEach(entry => {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) { if (!skip.includes(entry.name)) walk(full); }
else if (entry.name.endsWith(ext)) out.push(full);
});
dirs.forEach(dir => fs.existsSync(path.join(root, dir)) && walk(path.join(root, dir)));
return out.sort((a, b) => rel(root, a).localeCompare(rel(root, b)));
};
//===> Description from the lines above a declaration: a /** docblock */ or a //===> comment <===// line <===//
const describe = (lines, index) => {
let i = index - 1;
while (i >= 0 && /^\s*$/.test(lines[i])) i--;
//===> Step over the function_exists() guard: the comment is often above it <===//
if (i >= 0 && /^\s*if\s*\(\s*!\s*function_exists\(/.test(lines[i])) { i--; while (i >= 0 && /^\s*$/.test(lines[i])) i--; }
//===> One-line section comment: /*====> Name <====*/ or //====> Name <====// <===//
const oneLine = i >= 0 && lines[i].match(/^\s*(?:\/\*|\/\/)=+>\s*(.+?)\s*<=+\s*(?:\*\/|\/\/)\s*$/);
if (oneLine) return oneLine[1].trim();
if (i >= 0 && /^\s*\*?\/\s*$|^\s*\*\/\s*$/.test(lines[i])) {
let start = i;
while (start > 0 && start > i - 20 && !/\/\*\*/.test(lines[start])) start--;
if (!/\/\*\*/.test(lines[start])) return '';
const text = lines.slice(start, i + 1).map(l => l.replace(/^\s*\/?\*+\/?\s?/, '').replace(/\*\/\s*$/, '').trim())
.filter(l => l && !l.startsWith('@'));
if (text.length) return text[0];
}
if (i >= 0) {
const comment = lines[i].match(/^\s*(?:\/\/=+>|\/\*=+>)\s*(.+?)\s*<?=*(?:\/\/|\*\/)?\s*$/);
if (comment) return comment[1].replace(/\s*<=+\s*$/, '').trim();
}
return '';
};
//===> PHP: named functions and class methods <===//
export const phpReference = (root) => {
const files = filesIn(root, ['admin', 'inc', 'src'], '.php', ['node_modules']);
files.push(path.join(root, 'pds-blocks.php'));
const sections = [];
let total = 0, missing = 0;
for (const file of files) {
const lines = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n').split('\n');
const rows = [];
let currentClass = null, classDepth = 0, depth = 0;
lines.forEach((line, index) => {
const cls = line.match(/^\s*(?:final\s+|abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)/);
if (cls) { currentClass = cls[1]; classDepth = depth; }
const fn = line.match(/^\s*((?:public|private|protected)\s+)?(static\s+)?function\s+&?([A-Za-z_][A-Za-z0-9_]*)\s*\((.*)$/);
if (fn) {
const visibility = (fn[1] || '').trim();
const name = currentClass ? `${currentClass}::${fn[3]}` : fn[3];
//===> Arguments: up to the parenthesis that closes the list (defaults like array() have their own) <===//
let level = 1, args = '';
for (const char of fn[4]) {
if (char === '(') level++;
if (char === ')' && --level === 0) break;
args += char;
}
args = args.replace(/\s+/g, ' ').trim();
const note = describe(lines, index);
if (visibility !== 'private') {
rows.push({ name, args, note, visibility });
total++;
if (!note) missing++;
}
}
//===> Brace depth, to know when the class ends (strings and comments are rare enough here) <===//
const opens = (line.match(/\{/g) || []).length, closes = (line.match(/\}/g) || []).length;
depth += opens - closes;
if (currentClass && depth <= classDepth && closes > 0) currentClass = null;
});
if (rows.length) sections.push({ file: rel(root, file), rows });
}
const body = [
`${total} public functions and methods in ${sections.length} files (private methods are left out). ${missing} have no description yet: add a docblock above the function.`, '',
...sections.flatMap(s => [
`### \`${s.file}\``, '',
'| Function | Description |', '|---|---|',
...s.rows.map(r => `| \`${cell(r.name)}(${cell(r.args)})\` | ${cell(r.note) || '—'} |`),
'',
]),
].join('\n');
return { body, total, missing };
};
//===> JS: PhenixElements methods, PhenixBlocks helpers and data lists, PdsAdmin <===//
export const jsReference = (root) => {
const methods = [];
for (const file of filesIn(root, ['src/scripts'], '.ts')) {
const lines = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n').split('\n');
const isCore = file.endsWith(path.join('scripts', 'index.ts'));
lines.forEach((line, index) => {
let name = line.match(/PhenixElements\.prototype\.([A-Za-z_]+)\s*=/)?.[1];
if (!name && isCore) name = line.match(/^ {4}([a-zA-Z_]+)\s*(?:\(.*\)\s*(?::\s*[^{]+)?\{|=\s*\()/)?.[1];
if (!name || ['constructor', 'if', 'for', 'while', 'switch'].includes(name)) return;
if (methods.some(m => m.name === name && m.file === rel(root, file))) return;
methods.push({ name, file: rel(root, file), note: describe(lines, index) });
});
}
methods.sort((a, b) => a.name.localeCompare(b.name) || a.file.localeCompare(b.file));
//===> Top-level keys of an object literal assigned in a file (" key : …") <===//
const objectKeys = (file, indent) => {
const lines = fs.readFileSync(path.join(root, file), 'utf8').replace(/\r\n/g, '\n').split('\n');
return lines.map((line, index) => {
const key = line.match(new RegExp(`^ {${indent}}([A-Za-z_][A-Za-z0-9_]*)\\s*:`))?.[1];
return key ? { name: key, note: describe(lines, index) } : null;
}).filter(Boolean);
};
const helpers = objectKeys('src/blocks/pds-helpers.js', 4);
const lists = objectKeys('src/blocks/pds-data-list.js', 4);
const admin = (fs.readFileSync(path.join(root, 'admin/scripts.js'), 'utf8').match(/window\.PdsAdmin\s*=\s*\{([^}]*)\}/)?.[1] || '')
.split(',').map(s => s.trim()).filter(Boolean);
const body = [
`## \`PhenixElements\` methods (${methods.length})`, '',
'Called on a selection: `Phenix(selector).method(…)`. The options of the public ones are documented on the docs site under Design system → JavaScript API and JS components.', '',
'| Method | File | Description |', '|---|---|---|',
...methods.map(m => `| \`${m.name}\` | \`${m.file}\` | ${cell(m.note) || '—'} |`),
'',
`## \`window.PhenixBlocks\` (${helpers.length})`, '',
'Editor helpers from `src/blocks/pds-helpers.js`, loaded before every block editor script.', '',
'| Key | Description |', '|---|---|',
...helpers.map(h => `| \`${h.name}\` | ${cell(h.note) || '—'} |`),
'',
`## \`window.PhenixBlocks.dataLists\` (${lists.length})`, '',
'Option lists from `src/blocks/pds-data-list.js`, used by the editor controls.', '',
lists.map(l => `\`${l.name}\``).join(', '),
'',
`## \`window.PdsAdmin\` (${admin.length})`, '',
'Admin page helpers from `admin/scripts.js` (plugin admin pages only).', '',
admin.map(a => `\`${a}\``).join(', '),
].join('\n');
return { body, total: methods.length };
};