Repository navigation
Expand file tree
/
Copy pathcreative-sync-dependency-docs.js
More file actions
283 lines (253 loc) · 8.7 KB
/
Copy pathcreative-sync-dependency-docs.js
File metadata and controls
283 lines (253 loc) · 8.7 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import { Log } from '../.codex/utils/logger.js';
const CREATIVE_SOURCE_FOLDER = '.codex/module.creative';
const TARGET_DOCUMENT_PATH = '.codex/module.creative/module.creative.md';
const MARKER_BEGIN = '<!-- BEGIN GENERATED CREATIVE DEPENDENCY TABLE -->';
const MARKER_END = '<!-- END GENERATED CREATIVE DEPENDENCY TABLE -->';
const IMPORT_STATEMENT_PATTERN = /import\s+[^;]*?;/gs;
const STATIC_IMPORT_CAPTURE_PATTERN = /^import\s+(?:[\w*\s{},$]+\s+from\s+)?["']([^"']+)["']\s*;?$/;
const DYNAMIC_IMPORT_PATTERN = /import\s*\(\s*["']([^"']+)["']/g;
const RE_EXPORT_PATTERN = /export\s+[^;]*?\bfrom\s+["'][^"']+["']\s*;?/gs;
export function buildInvokeCommand(app) {
return {
name: 'Sync Creative Dependency Documentation',
id: 'creative-sync-dependency-docs',
async callback() {
let phase = 'file enumeration';
try {
const files = collectCreativeJsFiles(app);
phase = 'reading and parsing';
const graph = await buildDependencyGraph(app, files);
phase = 'rendering';
const generatedAt = new Date().toISOString();
const renderedBlock = renderDependencyBlock(graph, files.length, generatedAt);
phase = 'marker validation';
const targetFile = app.vault.getAbstractFileByPath(TARGET_DOCUMENT_PATH);
if (!targetFile) {
const error = new Error(`Target document not found at "${ TARGET_DOCUMENT_PATH }".`);
Log.error(
'creative-sync-dependency-docs',
error.message,
error
);
throw error;
}
const documentText = await app.vault.read(targetFile);
const updatedText = spliceGeneratedBlock(documentText, renderedBlock);
phase = 'document writing';
await app.vault.modify(targetFile, updatedText);
} catch (error) {
Log.error(
'creative-sync-dependency-docs',
`Dependency documentation sync failed during ${ phase }.`,
error
);
throw error;
}
}
};
};
/**
* Scans every Creative module file and builds a reverse dependency map from
* imported module path to the sorted set of files that import it directly,
* along with resolved/unresolved import counts and unresolved entries.
*/
async function buildDependencyGraph(app, files) {
const importersByModule = new Map();
const unresolvedEntries = [];
let resolvedImportCount = 0;
for (const file of files) {
const source = await app.vault.cachedRead(file);
const { resolvedSpecifiers, unsupported } = extractImports(source);
for (const specifier of resolvedSpecifiers) {
if (!specifier.startsWith('.')) {
unresolvedEntries.push({ file: file.path, text: specifier });
continue;
}
const modulePath = resolveRelativeSpecifier(file.path, specifier);
resolvedImportCount += 1;
if (!importersByModule.has(modulePath)) {
importersByModule.set(modulePath, new Set());
}
importersByModule.get(modulePath).add(file.path);
}
for (const text of unsupported) {
unresolvedEntries.push({ file: file.path, text });
}
}
return {
importersByModule,
unresolvedEntries,
resolvedImportCount
};
}
/**
* Collects every .js file below the Creative module's source folder,
* sorted deterministically by vault path.
*/
function collectCreativeJsFiles(app) {
return app.vault
.getFiles()
.filter((file) => file.path.startsWith(`${ CREATIVE_SOURCE_FOLDER }/`) && file.path.endsWith('.js'))
.sort((a, b) => a.path.localeCompare(b.path));
}
/**
* Extracts static relative import specifiers from a single file's source,
* separating cleanly-resolved imports from dynamic imports, re-exports, and
* any import statement that doesn't match the module's supported forms.
*/
function extractImports(source) {
const cleaned = stripComments(source);
const resolvedSpecifiers = [];
const unsupported = [];
for (const match of cleaned.matchAll(IMPORT_STATEMENT_PATTERN)) {
const statement = match[0].trim();
const captured = statement.match(STATIC_IMPORT_CAPTURE_PATTERN);
if (captured) {
resolvedSpecifiers.push(captured[1]);
} else {
unsupported.push(statement);
}
}
for (const match of cleaned.matchAll(DYNAMIC_IMPORT_PATTERN)) {
unsupported.push(match[0].trim());
}
for (const match of cleaned.matchAll(RE_EXPORT_PATTERN)) {
unsupported.push(match[0].trim());
}
return { resolvedSpecifiers, unsupported };
}
/**
* Renders the full generated dependency block, including the split
* Creative-internal / external-shared-module tables, an unresolved-imports
* table, and a generation report, for insertion between the document's
* marker comments.
*/
function renderDependencyBlock(
{
importersByModule,
unresolvedEntries,
resolvedImportCount
},
filesScanned,
generatedAt
) {
const allModules = [...importersByModule.keys()];
const creativeModules = allModules.filter((modulePath) => modulePath.startsWith(`${ CREATIVE_SOURCE_FOLDER }/`));
const externalModules = allModules.filter((modulePath) => !modulePath.startsWith(`${ CREATIVE_SOURCE_FOLDER }/`));
const unresolvedTable = unresolvedEntries.length === 0
? '_None detected._'
: [
'| File | Import text |',
'| ---- | ----------- |',
...unresolvedEntries.map(({ file, text }) => `| \`${ file }\` | \`${ text.replace(/\|/g, '\\|') }\` |`)
].join('\n');
return [
'### Generated Direct Dependency Map',
'',
`> Generated by \`creative-sync-dependency-docs.js\` on ${ generatedAt }. This map describes static imports only.`,
'',
'#### Creative Module Files',
'',
renderModuleTable(creativeModules, importersByModule),
'',
'#### External Shared Modules',
'',
renderModuleTable(externalModules, importersByModule),
'',
'#### Unresolved / Unsupported Imports',
'',
unresolvedTable,
'',
'#### Generation Report',
'',
'| Metric | Value |',
'| ------ | ----- |',
`| Creative files scanned | ${ filesScanned } |`,
`| Static imports resolved | ${ resolvedImportCount } |`,
`| Unresolved / unsupported imports | ${ unresolvedEntries.length } |`,
`| Target document updated | \`${ TARGET_DOCUMENT_PATH }\` |`
].join('\n');
}
/**
* Renders a Markdown table for one group of module rows, joining each
* module's importers with a line break to match the module's existing
* "Used By" table convention.
*/
function renderModuleTable(modulePaths, importersByModule) {
if (modulePaths.length === 0) {
return '_None detected._';
}
const rows = modulePaths
.sort((a, b) => a.localeCompare(b))
.map((modulePath) => {
const importers = [...importersByModule.get(modulePath)].sort((a, b) => a.localeCompare(b));
return `| \`${ modulePath }\` | ${ importers.map((path) => `\`${ path }\``).join('<br>') } |`;
});
return ['| Module | Direct importers |', '| ------ | ----------------- |', ...rows].join('\n');
}
/**
* Resolves a relative import specifier against the importing file's own
* folder into a normalized, vault-relative path.
*/
function resolveRelativeSpecifier(importingFilePath, specifier) {
const resultParts = importingFilePath.split('/').slice(0, -1);
for (const part of specifier.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') {
resultParts.pop();
continue;
}
resultParts.push(part);
}
return resultParts.join('/');
}
/**
* Replaces the contents between the generated dependency markers in a
* document's text, throwing if the markers are missing, duplicated, or
* out of order rather than writing a malformed result.
*/
function spliceGeneratedBlock(documentText, renderedBlock) {
const beginCount = documentText.split(MARKER_BEGIN).length - 1;
const endCount = documentText.split(MARKER_END).length - 1;
if (beginCount === 0 || endCount === 0) {
const error = new Error('Generated dependency table markers are missing from the target document.');
Log.error(
'creative-sync-dependency-docs',
error.message,
error
);
throw error;
}
if (beginCount > 1 || endCount > 1) {
const error = new Error('Generated dependency table markers are duplicated in the target document.');
Log.error(
'creative-sync-dependency-docs',
error.message,
error
);
throw error;
}
const beginIndex = documentText.indexOf(MARKER_BEGIN);
const endIndex = documentText.indexOf(MARKER_END);
if (endIndex < beginIndex) {
const error = new Error('Generated dependency table markers are out of order in the target document.');
Log.error(
'creative-sync-dependency-docs',
error.message,
error
);
throw error;
}
const head = documentText.slice(0, beginIndex + MARKER_BEGIN.length);
const tail = documentText.slice(endIndex);
return `${ head }\n\n${ renderedBlock }\n\n${ tail }`;
}
/**
* Removes block and line comments from a JavaScript source string so
* commented-out code is never mistaken for a live import declaration.
*/
function stripComments(source) {
return source
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/(^|[^:])\/\/.*$/gm, '$1');
}