@textmode/docs 0.4.2 → 0.4.3

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 CHANGED
@@ -181,3 +181,11 @@ textmode-docs dates reconcile --baseline ./previous-api --target ./new-api
181
181
  ```
182
182
 
183
183
  The command preserves `lastModified` when a page is unchanged, ignoring the date field itself. It assigns the current UTC date to changed pages, new pages, and unchanged pages without a previous date. Deleted pages are ignored. `--date YYYY-MM-DD` can supply a date for reproducible builds. Keep the baseline outside the target directory: TypeDoc cleans its output during generation.
184
+
185
+ ### Example quality checks
186
+
187
+ `analyzeExampleSource(content, { title, fileName })` returns the line count, definite issues, review items, recognized defaults, and a conventional label declaration for runtime observation. The documentation check and workbench use the same analyzer. A clean result does not establish rendering, label appearance, interaction, or educational quality; inspect those in the target host.
188
+
189
+ `displayedRowLength(value, markup = true)` counts Unicode code points after removing recognized `fg`, `bg`, `inv`, `rot`, `fx`, and `fy` formatting tags. Pass `false` to count markup literally. It is a text-length helper; it does not account for glyph width, line breaks, or tab expansion.
190
+
191
+ `exampleLabelSchema` exposes the shared row limit, divider length, panel color, and palette used by the example tooling.
package/index.d.ts CHANGED
@@ -35,3 +35,30 @@ export interface TextmodeDocsConfig {
35
35
  }
36
36
 
37
37
  export declare function defineDocs<const T extends TextmodeDocsConfig>(config: T): T;
38
+
39
+ export interface ExampleQualityResult {
40
+ lineCount: number;
41
+ issues: string[];
42
+ review: string[];
43
+ recognizedDefaults: string[];
44
+ }
45
+
46
+ export interface ExampleSourceAnalysis extends ExampleQualityResult {
47
+ labelDeclaration: { end: number; layer: string; instance: string } | null;
48
+ }
49
+
50
+ export declare function displayedRowLength(value: string, markup?: boolean): number;
51
+ export declare const exampleLabelSchema: Readonly<{
52
+ rowLimit: number;
53
+ dividerLength: number;
54
+ panelColor: string;
55
+ palette: Readonly<Record<string, string>>;
56
+ }>;
57
+ export declare function analyzeExampleSource(
58
+ content: string,
59
+ options?: { title?: string; fileName?: string }
60
+ ): ExampleSourceAnalysis;
61
+ export declare function validateExamplesManifest(
62
+ manifest: unknown,
63
+ options: { projectRoot: string; examplesDir?: string; examplesManifest?: string; sourceDir?: string }
64
+ ): string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@textmode/docs",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "type": "module",
5
5
  "license": "CC0-1.0",
6
6
  "description": "Shared documentation generation and validation for the textmode.js ecosystem",
@@ -37,7 +37,7 @@
37
37
  "dependencies": {
38
38
  "typedoc": "^0.28.20",
39
39
  "typedoc-plugin-frontmatter": "^1.3.3",
40
- "typedoc-plugin-markdown": "^4.12.0",
40
+ "typedoc-plugin-markdown": "^4.14.1",
41
41
  "typedoc-vitepress-theme": "^1.1.4"
42
42
  },
43
43
  "peerDependencies": {
@@ -0,0 +1,227 @@
1
+ import ts from 'typescript';
2
+ import { checkSketchTitle } from './internal/lib/sketch-title.mjs';
3
+ import { LABEL_SCHEMA } from './internal/lib/label-schema.mjs';
4
+
5
+ function countSketchLines(content) {
6
+ if (!content) return 0;
7
+ const lines = content.split(/\r\n|\r|\n/);
8
+ if (/\r\n$|[\r\n]$/.test(content)) lines.pop();
9
+ return lines.length;
10
+ }
11
+
12
+ /** Strip supported formatting tags before counting displayed characters. */
13
+ export function displayedRowLength(value, markup = true) {
14
+ const text = markup ? value.replace(/\[\/?(?:fg|bg|inv|rot|fx|fy)(?:=[^\]]*)?\]/gi, '') : value;
15
+ return [...text].length;
16
+ }
17
+
18
+ /** Locate a conventional top-level label declaration for optional observation. */
19
+ function labelDeclaration(source) {
20
+ for (const statement of source.statements) {
21
+ if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
22
+ for (const declaration of statement.declarationList.declarations) {
23
+ if (!ts.isIdentifier(declaration.name) || !/^label\w*$/i.test(declaration.name.text)) continue;
24
+ const init = declaration.initializer;
25
+ if (
26
+ !init ||
27
+ !ts.isCallExpression(init) ||
28
+ !ts.isPropertyAccessExpression(init.expression) ||
29
+ init.expression.name.text !== 'add'
30
+ )
31
+ continue;
32
+ const layers = init.expression.expression;
33
+ if (
34
+ !ts.isPropertyAccessExpression(layers) ||
35
+ layers.name.text !== 'layers' ||
36
+ !ts.isIdentifier(layers.expression)
37
+ )
38
+ continue;
39
+ return { end: statement.end, layer: declaration.name.text, instance: layers.expression.text };
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /** Check what can be established from source; leave visual and dynamic claims for review. */
46
+ export function analyzeExampleSource(content, { title, fileName = 'sketch.js' } = {}) {
47
+ const source = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
48
+ const issues = [];
49
+ const review = [];
50
+ const lineCount = countSketchLines(content);
51
+ if (lineCount > 100) issues.push(`Sketch has ${lineCount} lines; maximum is 100.`);
52
+ for (const diagnostic of source.parseDiagnostics) {
53
+ issues.push(`Syntax: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, ' ')}`);
54
+ }
55
+ const titleCheck = checkSketchTitle(content, title);
56
+ if (titleCheck.kind === 'missing') issues.push('Missing @title in the leading JSDoc header.');
57
+ else if (titleCheck.kind === 'mismatch')
58
+ issues.push(`Header title "${titleCheck.actual}" does not match manifest title "${title}".`);
59
+
60
+ const layers = new Set();
61
+ const callbacks = [];
62
+ const instances = new Set();
63
+ function findInstances(node) {
64
+ if (
65
+ ts.isVariableDeclaration(node) &&
66
+ ts.isIdentifier(node.name) &&
67
+ node.initializer &&
68
+ ts.isCallExpression(node.initializer) &&
69
+ node.initializer.expression.getText(source) === 'textmode.create'
70
+ )
71
+ instances.add(node.name.text);
72
+ ts.forEachChild(node, findInstances);
73
+ }
74
+ findInstances(source);
75
+ let createOptions;
76
+ let hasResizeHandler = false;
77
+ let hasViewportResize = false;
78
+ function visit(node) {
79
+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'windowResized') hasResizeHandler = true;
80
+ if (ts.isVariableDeclarationList(node) && !(node.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let))) {
81
+ issues.push('Do not use `var`; prefer `const` or `let`.');
82
+ }
83
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
84
+ const method = node.expression.name.text;
85
+ if (method === 'create' && node.expression.expression.getText(source) === 'textmode')
86
+ createOptions = node.arguments[0];
87
+ if (method === 'windowResized' && instances.has(node.expression.expression.getText(source)))
88
+ hasResizeHandler = true;
89
+ if (
90
+ method === 'resizeCanvas' &&
91
+ instances.has(node.expression.expression.getText(source)) &&
92
+ node.arguments[0]?.getText(source) === 'window.innerWidth' &&
93
+ node.arguments[1]?.getText(source) === 'window.innerHeight'
94
+ )
95
+ hasViewportResize = true;
96
+ }
97
+ if (
98
+ ts.isCallExpression(node) &&
99
+ ts.isIdentifier(node.expression) &&
100
+ node.expression.text === 'resizeCanvas' &&
101
+ node.arguments[0]?.getText(source) === 'window.innerWidth' &&
102
+ node.arguments[1]?.getText(source) === 'window.innerHeight'
103
+ )
104
+ hasViewportResize = true;
105
+ if (
106
+ ts.isVariableDeclaration(node) &&
107
+ ts.isIdentifier(node.name) &&
108
+ node.initializer &&
109
+ ts.isCallExpression(node.initializer)
110
+ ) {
111
+ const call = node.initializer.expression;
112
+ if (
113
+ ts.isPropertyAccessExpression(call) &&
114
+ call.name.text === 'add' &&
115
+ ts.isPropertyAccessExpression(call.expression) &&
116
+ call.expression.name.text === 'layers'
117
+ )
118
+ layers.add(node.name.text);
119
+ }
120
+ if (
121
+ ts.isCallExpression(node) &&
122
+ ts.isPropertyAccessExpression(node.expression) &&
123
+ node.expression.name.text === 'draw' &&
124
+ ts.isIdentifier(node.expression.expression)
125
+ )
126
+ callbacks.push(node);
127
+ ts.forEachChild(node, visit);
128
+ }
129
+ visit(source);
130
+ if (!createOptions || !ts.isObjectLiteralExpression(createOptions)) {
131
+ review.push('Could not establish viewport sizing in textmode.create options.');
132
+ } else {
133
+ const options = new Map(
134
+ createOptions.properties
135
+ .filter(ts.isPropertyAssignment)
136
+ .map((property) => [property.name.getText(source), property.initializer])
137
+ );
138
+ for (const [name, expected] of [
139
+ ['width', 'window.innerWidth'],
140
+ ['height', 'window.innerHeight'],
141
+ ]) {
142
+ const option = options.get(name);
143
+ if (
144
+ createOptions.properties.some(ts.isSpreadAssignment) ||
145
+ (option && !ts.isNumericLiteral(option) && option.getText(source) !== expected)
146
+ )
147
+ review.push(`Check \`${name}\` in create options; its value cannot be established statically.`);
148
+ else if (!option || option.getText(source) !== expected)
149
+ issues.push(`\`${name}\` must be set to \`${expected}\` in create options.`);
150
+ }
151
+ const fontSize = options.get('fontSize');
152
+ if (fontSize && ts.isNumericLiteral(fontSize) && ![8, 16, 32].includes(Number(fontSize.text)))
153
+ issues.push('Literal `fontSize` must be 8, 16, or 32.');
154
+ }
155
+ if (!hasResizeHandler || !hasViewportResize) review.push('Check the resize handler and viewport resize behavior.');
156
+ // A layer name alone does not prove intent, but it limits definite row checks
157
+ // to the conventional label callback instead of unrelated artwork text.
158
+ const layerCallbacks = callbacks.filter(
159
+ (node) => layers.has(node.expression.expression.text) && /label/i.test(node.expression.expression.text)
160
+ );
161
+ if (!layerCallbacks.length)
162
+ review.push('Could not establish a dedicated label layer and draw callback; inspect it manually.');
163
+ let foundPrint = false;
164
+ let dynamic = false;
165
+ const recognizedDefaults = new Set();
166
+ const palette = LABEL_SCHEMA.palette;
167
+ for (const callback of layerCallbacks) {
168
+ function inspect(node) {
169
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
170
+ const method = node.expression.name.text;
171
+ const rgb = node.arguments
172
+ .slice(0, 3)
173
+ .map((arg) => (ts.isNumericLiteral(arg) ? arg.text : '?'))
174
+ .join(',');
175
+ if (method === 'charColor' && palette[rgb]) recognizedDefaults.add(palette[rgb]);
176
+ if (method === 'cellColor' && rgb === LABEL_SCHEMA.panelColor) recognizedDefaults.add('panel color');
177
+ }
178
+ if (
179
+ ts.isCallExpression(node) &&
180
+ ts.isPropertyAccessExpression(node.expression) &&
181
+ node.expression.name.text === 'print'
182
+ ) {
183
+ foundPrint = true;
184
+ const value = node.arguments[0];
185
+ if (value && (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value))) {
186
+ if (value.text === '-'.repeat(LABEL_SCHEMA.dividerLength))
187
+ recognizedDefaults.add(`${LABEL_SCHEMA.dividerLength}-character divider`);
188
+ const options = node.arguments[3];
189
+ const markupDisabled =
190
+ options &&
191
+ ts.isObjectLiteralExpression(options) &&
192
+ options.properties.some(
193
+ (p) =>
194
+ ts.isPropertyAssignment(p) &&
195
+ p.name.getText(source) === 'markup' &&
196
+ p.initializer.kind === ts.SyntaxKind.FalseKeyword
197
+ );
198
+ if (/[\r\n\t]/.test(value.text) || (options && !ts.isObjectLiteralExpression(options))) {
199
+ review.push('Label text or print options need review to establish displayed row lengths.');
200
+ } else {
201
+ const length = displayedRowLength(value.text, !markupDisabled);
202
+ if (length > LABEL_SCHEMA.rowLimit)
203
+ issues.push(
204
+ `Possible label row has ${length} displayed characters; maximum is ${LABEL_SCHEMA.rowLimit}.`
205
+ );
206
+ }
207
+ } else dynamic = true;
208
+ }
209
+ ts.forEachChild(node, inspect);
210
+ }
211
+ for (const arg of callback.arguments)
212
+ if (ts.isArrowFunction(arg) || ts.isFunctionExpression(arg)) inspect(arg.body);
213
+ }
214
+ if (!foundPrint) review.push('Label text could not be identified statically; inspect row lengths and content.');
215
+ if (dynamic)
216
+ review.push(
217
+ `Dynamic label text needs runtime observation and a bound of ${LABEL_SCHEMA.rowLimit} displayed characters.`
218
+ );
219
+ review.push('Inspect label layer identity, opaque panel, layout, palette, readability, and educational quality.');
220
+ return {
221
+ lineCount,
222
+ issues,
223
+ review,
224
+ recognizedDefaults: [...recognizedDefaults],
225
+ labelDeclaration: labelDeclaration(source),
226
+ };
227
+ }
package/src/index.js CHANGED
@@ -1,5 +1,9 @@
1
1
  const CONFIG_MARKER = Symbol.for('@textmode/docs/config');
2
2
 
3
+ export { analyzeExampleSource, displayedRowLength } from './example-quality.mjs';
4
+ export { LABEL_SCHEMA as exampleLabelSchema } from './internal/lib/label-schema.mjs';
5
+ export { validateExamplesManifest } from './internal/lib/example-checks.mjs';
6
+
3
7
  /**
4
8
  * Define project-specific documentation policy.
5
9
  *
@@ -1,3 +1,4 @@
1
+ import { checkSketchTitle } from './sketch-title.mjs';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
 
@@ -48,14 +49,6 @@ export function readExamplesIndex(indexPath = EXAMPLES_INDEX) {
48
49
  return fs.readFileSync(indexPath, 'utf8');
49
50
  }
50
51
 
51
- export function getSketchTitle(filePath) {
52
- const content = fs.readFileSync(filePath, 'utf8');
53
- const docstringMatch = content.match(/^\s*\/\*\*([\s\S]*?)\*\//);
54
- const titleMatch = docstringMatch?.[1].match(/@title\s+([^\r\n]+)/);
55
-
56
- return titleMatch?.[1].trim() ?? null;
57
- }
58
-
59
52
  export function getManifestExamples(manifest) {
60
53
  return manifest.groups.flatMap((group) => {
61
54
  if (Array.isArray(group.subgroups)) {
@@ -298,13 +291,13 @@ export function validateExamplesManifest(manifest, options = {}) {
298
291
  continue;
299
292
  }
300
293
 
301
- const sketchTitle = getSketchTitle(sketchPath);
294
+ const titleCheck = checkSketchTitle(fs.readFileSync(sketchPath, 'utf8'), example.title);
302
295
 
303
- if (!sketchTitle) {
296
+ if (titleCheck.kind === 'missing') {
304
297
  issues.push(`Manifest example "${example.sourceFile}" sketch is missing an @title tag.`);
305
- } else if (sketchTitle !== example.title) {
298
+ } else if (titleCheck.kind === 'mismatch') {
306
299
  issues.push(
307
- `Manifest example "${example.sourceFile}" title "${example.title}" must match sketch @title "${sketchTitle}".`
300
+ `Manifest example "${example.sourceFile}" title "${example.title}" must match sketch @title "${titleCheck.actual}".`
308
301
  );
309
302
  }
310
303
  }
@@ -320,86 +313,3 @@ export function validateExamplesManifest(manifest, options = {}) {
320
313
 
321
314
  return issues;
322
315
  }
323
-
324
- export function checkSketch(filePath) {
325
- const content = fs.readFileSync(filePath, 'utf8');
326
- const issues = [];
327
-
328
- if (content.includes('import ') || content.includes('export ')) {
329
- return { skipped: true, issues };
330
- }
331
-
332
- const docstringMatch = content.match(/^\s*\/\*\*([\s\S]*?)\*\//);
333
- if (!docstringMatch) {
334
- issues.push('Missing JSDoc-style block comment header at the top of the file.');
335
- } else {
336
- const docstring = docstringMatch[1];
337
- if (!docstring.includes('@title')) {
338
- issues.push('Docstring header is missing `@title` tag.');
339
- }
340
- }
341
-
342
- const createMatch = content.match(/textmode\.create\s*\(\s*\{([\s\S]*?)\}\s*\)/);
343
- if (!createMatch) {
344
- issues.push('Could not find `textmode.create({ ... })` call.');
345
- } else {
346
- const options = createMatch[1];
347
-
348
- if (!options.match(/width:\s*window\.innerWidth/)) {
349
- issues.push('`width` must be set to `window.innerWidth` in create options.');
350
- }
351
-
352
- if (!options.match(/height:\s*window\.innerHeight/)) {
353
- issues.push('`height` must be set to `window.innerHeight` in create options.');
354
- }
355
-
356
- const fontSizeMatch = options.match(/fontSize:\s*(\d+)/);
357
- if (fontSizeMatch) {
358
- const size = parseInt(fontSizeMatch[1], 10);
359
- if (size !== 8 && size !== 16 && size !== 32) {
360
- issues.push(`\`fontSize\` is set to \`${size}\`, but must be exactly \`8\`, \`16\`, or \`32\`.`);
361
- }
362
- }
363
- }
364
-
365
- if (!content.includes('windowResized')) {
366
- issues.push('Missing `windowResized` callback registration.');
367
- }
368
- if (!content.match(/resizeCanvas\(\s*window\.innerWidth\s*,\s*window\.innerHeight\s*\)/)) {
369
- issues.push(
370
- '`resizeCanvas` must be called with `window.innerWidth` and `window.innerHeight` inside the sketch.'
371
- );
372
- }
373
-
374
- if (/\bvar\b/.test(content)) {
375
- issues.push('Do not use `var`; prefer `const` or `let`.');
376
- }
377
-
378
- const lines = content.split('\n');
379
- if (lines.length > 100) {
380
- issues.push(`Sketch file has ${lines.length} lines, but must not exceed 100 lines.`);
381
- }
382
-
383
- if (!content.includes('layers.add(')) {
384
- issues.push('Missing dedicated label layer registration (`t.layers.add()`).');
385
- }
386
-
387
- const leftMatch = content.includes('grid.cols / 2') || content.includes('grid.cols/2');
388
- const topMatch = content.includes('grid.rows / 2') || content.includes('grid.rows/2');
389
- if (!leftMatch || !topMatch) {
390
- issues.push(
391
- 'Missing top-left labeling alignment coordinates calculation using grid center offset (`-Math.floor(t.grid.cols / 2)` and `-Math.floor(t.grid.rows / 2)`).'
392
- );
393
- }
394
-
395
- const textDrawingRegex = /(?:drawText|drawCenteredText|t\.char)\s*\(\s*(['"`])(.*?)\1/g;
396
- let match;
397
- while ((match = textDrawingRegex.exec(content)) !== null) {
398
- const text = match[2];
399
- if (text.length > 40) {
400
- issues.push(`Row of text exceeds 40 characters limit: "${text}" (${text.length} chars).`);
401
- }
402
- }
403
-
404
- return { skipped: false, issues };
405
- }
@@ -0,0 +1,13 @@
1
+ export const LABEL_SCHEMA = Object.freeze({
2
+ rowLimit: 40,
3
+ dividerLength: 36,
4
+ panelColor: '6,10,22',
5
+ palette: Object.freeze({
6
+ '120,240,180': 'title color',
7
+ '70,100,140': 'divider color',
8
+ '140,210,255': 'concept color',
9
+ '140,160,190': 'explanation color',
10
+ '140,255,200': 'live value color',
11
+ '255,200,80': 'interaction color',
12
+ }),
13
+ });
@@ -0,0 +1,8 @@
1
+ /** Check the title in the leading sketch header against an optional manifest title. */
2
+ export function checkSketchTitle(content, title) {
3
+ const header = content.match(/^\s*\/\*\*([\s\S]*?)\*\//)?.[1];
4
+ const actual = header?.match(/@title\s+([^\r\n*]+)/)?.[1].trim();
5
+ if (!actual) return { kind: 'missing' };
6
+ if (title !== undefined && actual !== title) return { kind: 'mismatch', actual };
7
+ return { kind: 'valid', actual };
8
+ }
@@ -3,11 +3,11 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
 
5
5
  import { ReflectionKind } from 'typedoc';
6
+ import { analyzeExampleSource } from '../example-quality.mjs';
6
7
 
7
8
  import { collectApiDocIssues, countApiDocIssues, createApiLinkTargets } from './lib/api-doc-checks.mjs';
8
9
  import { readMarkdownRoutes } from './lib/api-doc-routes.mjs';
9
10
  import {
10
- checkSketch,
11
11
  getManifestExamples,
12
12
  readExamplesIndex,
13
13
  readExamplesManifest,
@@ -146,18 +146,22 @@ export function examplesCheck(config) {
146
146
  return false;
147
147
  }
148
148
 
149
- const files = getManifestExamples(manifest).map((example) => example.sourceFile);
150
- console.log(`Found ${files.length} manifest examples from examples/manifest.json.`);
149
+ const examples = getManifestExamples(manifest);
150
+ console.log(`Found ${examples.length} manifest examples from examples/manifest.json.`);
151
151
 
152
152
  let passedCount = 0;
153
153
  let failedCount = 0;
154
- let skippedCount = 0;
155
154
  const failures = [];
156
- for (const file of files) {
157
- const { skipped, issues } = checkSketch(path.join(config.projectRoot, file));
158
- if (skipped) {
159
- skippedCount += 1;
160
- } else if (issues.length === 0) {
155
+ const reviews = [];
156
+ for (const { sourceFile: file, title } of examples) {
157
+ const sketchPath = path.join(config.projectRoot, file);
158
+ const { issues, review } = analyzeExampleSource(fs.readFileSync(sketchPath, 'utf8'), {
159
+ title,
160
+ fileName: sketchPath,
161
+ });
162
+ const actionable = review.filter((item) => !item.startsWith('Inspect label layer identity'));
163
+ if (actionable.length) reviews.push({ file, items: actionable });
164
+ if (issues.length === 0) {
161
165
  passedCount += 1;
162
166
  } else {
163
167
  failedCount += 1;
@@ -165,9 +169,12 @@ export function examplesCheck(config) {
165
169
  }
166
170
  }
167
171
 
168
- console.log(`\nResults: ${passedCount} passed, ${failedCount} failed, ${skippedCount} skipped.\n`);
172
+ console.log(`\nResults: ${passedCount} passed, ${failedCount} failed.\n`);
173
+ for (const { file, items } of reviews) {
174
+ for (const item of items) console.log(`Review ${file}: ${item}`);
175
+ }
169
176
  if (failures.length === 0) {
170
- console.log('All checked sketches meet the requirements successfully.');
177
+ console.log('All checked sketches passed automated checks; visual and educational review remains necessary.');
171
178
  return true;
172
179
  }
173
180