codepen-demokit 0.0.0-stage → 1.0.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.
- package/README.md +229 -2
- package/bin/cli.mjs +154 -0
- package/lib/build-json.mjs +439 -0
- package/lib/build-site.mjs +193 -0
- package/lib/config.mjs +245 -0
- package/lib/init.mjs +651 -0
- package/lib/serve.mjs +369 -0
- package/lib/sync-codepen.mjs +1326 -0
- package/package.json +35 -4
- package/shell/index.html +48 -0
- package/shell/scripts.js +201 -0
- package/shell/styles.css +299 -0
- package/templates/AGENTS.md +76 -0
- package/templates/README.md +62 -0
- package/templates/config.json.example +10 -0
- package/templates/gitignore +27 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { watch } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const MAX_SCAN_DEPTH = 4;
|
|
7
|
+
const MAX_HTML_HEAD_BYTES = 16 * 1024;
|
|
8
|
+
const MAX_CDPN_JSON_BYTES = 64 * 1024;
|
|
9
|
+
|
|
10
|
+
const ACRONYMS = new Map([
|
|
11
|
+
['ai', 'AI'],
|
|
12
|
+
['api', 'API'],
|
|
13
|
+
['apis', 'APIs'],
|
|
14
|
+
['aria', 'ARIA'],
|
|
15
|
+
['cls', 'CLS'],
|
|
16
|
+
['css', 'CSS'],
|
|
17
|
+
['cwv', 'CWV'],
|
|
18
|
+
['dom', 'DOM'],
|
|
19
|
+
['html', 'HTML'],
|
|
20
|
+
['http', 'HTTP'],
|
|
21
|
+
['inp', 'INP'],
|
|
22
|
+
['js', 'JS'],
|
|
23
|
+
['json', 'JSON'],
|
|
24
|
+
['lcp', 'LCP'],
|
|
25
|
+
['mcp', 'MCP'],
|
|
26
|
+
['pwa', 'PWA'],
|
|
27
|
+
['svg', 'SVG'],
|
|
28
|
+
['ui', 'UI'],
|
|
29
|
+
['url', 'URL'],
|
|
30
|
+
['ux', 'UX'],
|
|
31
|
+
['wasm', 'WASM'],
|
|
32
|
+
['webgl', 'WebGL'],
|
|
33
|
+
['webgpu', 'WebGPU'],
|
|
34
|
+
['webmcp', 'WebMCP'],
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
const MINOR_WORDS = new Set([
|
|
38
|
+
'a',
|
|
39
|
+
'an',
|
|
40
|
+
'and',
|
|
41
|
+
'as',
|
|
42
|
+
'at',
|
|
43
|
+
'by',
|
|
44
|
+
'for',
|
|
45
|
+
'from',
|
|
46
|
+
'in',
|
|
47
|
+
'of',
|
|
48
|
+
'on',
|
|
49
|
+
'or',
|
|
50
|
+
'the',
|
|
51
|
+
'to',
|
|
52
|
+
'with',
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
const NAMED_HTML_ENTITIES = new Map([
|
|
56
|
+
['amp', '&'],
|
|
57
|
+
['apos', "'"],
|
|
58
|
+
['gt', '>'],
|
|
59
|
+
['lt', '<'],
|
|
60
|
+
['mdash', '—'],
|
|
61
|
+
['nbsp', ' '],
|
|
62
|
+
['ndash', '–'],
|
|
63
|
+
['quot', '"'],
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
const utf8Decoder = new TextDecoder('utf-8');
|
|
67
|
+
|
|
68
|
+
function isWithinRoot(candidatePath, rootPath) {
|
|
69
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function compareNatural(a, b) {
|
|
73
|
+
return a.localeCompare(b, 'en', { numeric: true, sensitivity: 'base' });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function formatFolderTitle(folderName) {
|
|
77
|
+
const words = folderName.split(/[-_]+/).filter(Boolean);
|
|
78
|
+
return words
|
|
79
|
+
.map((word, index) => {
|
|
80
|
+
const lower = word.toLowerCase();
|
|
81
|
+
if (ACRONYMS.has(lower)) {
|
|
82
|
+
return ACRONYMS.get(lower);
|
|
83
|
+
}
|
|
84
|
+
if (index > 0 && index < words.length - 1 && MINOR_WORDS.has(lower)) {
|
|
85
|
+
return lower;
|
|
86
|
+
}
|
|
87
|
+
return word[0].toUpperCase() + word.slice(1);
|
|
88
|
+
})
|
|
89
|
+
.join(' ');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function decodeHtmlEntities(input) {
|
|
93
|
+
return input.replace(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([a-zA-Z]{2,10}));/g, (match, dec, hex, named) => {
|
|
94
|
+
if (dec || hex) {
|
|
95
|
+
const codePoint = Number.parseInt(dec ?? hex, dec ? 10 : 16);
|
|
96
|
+
if (Number.isInteger(codePoint) && codePoint >= 0 && codePoint <= 0x10ffff) {
|
|
97
|
+
return String.fromCodePoint(codePoint);
|
|
98
|
+
}
|
|
99
|
+
return match;
|
|
100
|
+
}
|
|
101
|
+
return NAMED_HTML_ENTITIES.get(named.toLowerCase()) ?? match;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function normalizeText(value, maxLength) {
|
|
106
|
+
const cleaned = decodeHtmlEntities(value).replace(/\s+/g, ' ').trim();
|
|
107
|
+
if (!cleaned) return null;
|
|
108
|
+
return cleaned.length > maxLength ? `${cleaned.slice(0, maxLength - 1)}…` : cleaned;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function extractTitle(headHtml) {
|
|
112
|
+
const match = /<title\b[^>]{0,200}>([\s\S]{0,500}?)<\/title>/i.exec(headHtml);
|
|
113
|
+
return match ? normalizeText(match[1], 160) : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function extractMetaDescription(headHtml) {
|
|
117
|
+
const metaTagPattern = /<meta\b[^>]{1,1000}>/gi;
|
|
118
|
+
const attrPattern = /([a-zA-Z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
|
|
119
|
+
|
|
120
|
+
for (const tagMatch of headHtml.matchAll(metaTagPattern)) {
|
|
121
|
+
let metaName = null;
|
|
122
|
+
let metaContent = null;
|
|
123
|
+
|
|
124
|
+
for (const attrMatch of tagMatch[0].matchAll(attrPattern)) {
|
|
125
|
+
const key = attrMatch[1].toLowerCase();
|
|
126
|
+
const value = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? '';
|
|
127
|
+
if (key === 'name') {
|
|
128
|
+
metaName = value.trim().toLowerCase();
|
|
129
|
+
} else if (key === 'content') {
|
|
130
|
+
metaContent = value;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (metaName === 'description' && metaContent !== null) {
|
|
135
|
+
return normalizeText(metaContent, 320);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function sanitizeCodePenUrl(rawUrl) {
|
|
143
|
+
if (typeof rawUrl !== 'string') return null;
|
|
144
|
+
try {
|
|
145
|
+
const parsed = new URL(rawUrl.trim());
|
|
146
|
+
if (parsed.protocol !== 'https:') return null;
|
|
147
|
+
if (parsed.hostname !== 'codepen.io' && !parsed.hostname.endsWith('.codepen.io')) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
return parsed.href;
|
|
151
|
+
} catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function readPartialUtf8(filePath, maxBytes) {
|
|
157
|
+
const handle = await fs.open(filePath, 'r');
|
|
158
|
+
try {
|
|
159
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
160
|
+
const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
|
|
161
|
+
return utf8Decoder.decode(buffer.subarray(0, bytesRead));
|
|
162
|
+
} finally {
|
|
163
|
+
await handle.close();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function resolveSafeRealFile(candidatePath, srcDir, srcRealpath) {
|
|
168
|
+
if (!isWithinRoot(candidatePath, srcDir)) return null;
|
|
169
|
+
let stat;
|
|
170
|
+
try {
|
|
171
|
+
stat = await fs.stat(candidatePath);
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
if (!stat.isFile()) return null;
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
const realPath = await fs.realpath(candidatePath);
|
|
179
|
+
if (!isWithinRoot(realPath, srcRealpath)) return null;
|
|
180
|
+
return { realPath, size: stat.size };
|
|
181
|
+
} catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function resolveSafeRealDir(candidatePath, srcDir, srcRealpath) {
|
|
187
|
+
if (!isWithinRoot(candidatePath, srcDir)) return null;
|
|
188
|
+
let stat;
|
|
189
|
+
try {
|
|
190
|
+
stat = await fs.stat(candidatePath);
|
|
191
|
+
} catch {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
if (!stat.isDirectory()) return null;
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
const realPath = await fs.realpath(candidatePath);
|
|
198
|
+
if (!isWithinRoot(realPath, srcRealpath)) return null;
|
|
199
|
+
return realPath;
|
|
200
|
+
} catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function readDemoEntry(segments, srcDir, srcRealpath) {
|
|
206
|
+
const demoDir = path.resolve(srcDir, ...segments);
|
|
207
|
+
const indexFile = await resolveSafeRealFile(path.join(demoDir, 'index.html'), srcDir, srcRealpath);
|
|
208
|
+
if (!indexFile) return null;
|
|
209
|
+
|
|
210
|
+
let title = null;
|
|
211
|
+
let description = null;
|
|
212
|
+
try {
|
|
213
|
+
const headHtml = await readPartialUtf8(indexFile.realPath, MAX_HTML_HEAD_BYTES);
|
|
214
|
+
title = extractTitle(headHtml);
|
|
215
|
+
description = extractMetaDescription(headHtml);
|
|
216
|
+
} catch {
|
|
217
|
+
// Fall back to folder name when HTML metadata cannot be read
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let codepenUrl = null;
|
|
221
|
+
const cdpnFile = await resolveSafeRealFile(path.join(demoDir, '.cdpn.json'), srcDir, srcRealpath);
|
|
222
|
+
if (cdpnFile && cdpnFile.size <= MAX_CDPN_JSON_BYTES) {
|
|
223
|
+
try {
|
|
224
|
+
const rawJson = await fs.readFile(cdpnFile.realPath, 'utf8');
|
|
225
|
+
const parsed = JSON.parse(rawJson);
|
|
226
|
+
codepenUrl = sanitizeCodePenUrl(parsed?.url);
|
|
227
|
+
} catch {
|
|
228
|
+
codepenUrl = null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
title: title ?? formatFolderTitle(segments.at(-1)),
|
|
234
|
+
description,
|
|
235
|
+
path: `${segments.join('/')}/`,
|
|
236
|
+
href: `./${segments.map(encodeURIComponent).join('/')}/`,
|
|
237
|
+
codepenUrl,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function scanGroupNode(dirRealpath, segments, depth, visitedRealpaths, srcDir, srcRealpath) {
|
|
242
|
+
if (depth > MAX_SCAN_DEPTH) return { demos: [], groups: [] };
|
|
243
|
+
|
|
244
|
+
let entries;
|
|
245
|
+
try {
|
|
246
|
+
entries = await fs.readdir(dirRealpath, { withFileTypes: true });
|
|
247
|
+
} catch {
|
|
248
|
+
return { demos: [], groups: [] };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const demos = [];
|
|
252
|
+
const groups = [];
|
|
253
|
+
|
|
254
|
+
for (const entry of entries) {
|
|
255
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
|
256
|
+
|
|
257
|
+
const childSegments = [...segments, entry.name];
|
|
258
|
+
const childCandidate = path.resolve(srcDir, ...childSegments);
|
|
259
|
+
const childRealDir = await resolveSafeRealDir(childCandidate, srcDir, srcRealpath);
|
|
260
|
+
if (!childRealDir || visitedRealpaths.has(childRealDir)) continue;
|
|
261
|
+
|
|
262
|
+
visitedRealpaths.add(childRealDir);
|
|
263
|
+
|
|
264
|
+
const demoEntry = await readDemoEntry(childSegments, srcDir, srcRealpath);
|
|
265
|
+
if (demoEntry) {
|
|
266
|
+
demos.push(demoEntry);
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const subNode = await scanGroupNode(childRealDir, childSegments, depth + 1, visitedRealpaths, srcDir, srcRealpath);
|
|
271
|
+
if (subNode.demos.length > 0 || subNode.groups.length > 0) {
|
|
272
|
+
groups.push({
|
|
273
|
+
id: childSegments.join('/'),
|
|
274
|
+
title: formatFolderTitle(entry.name),
|
|
275
|
+
demos: subNode.demos,
|
|
276
|
+
groups: subNode.groups,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
demos: demos.toSorted((a, b) => compareNatural(a.path, b.path)),
|
|
283
|
+
groups: groups.toSorted((a, b) => compareNatural(a.id, b.id)),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export async function scanDemos(projectDir = process.cwd()) {
|
|
288
|
+
const srcDir = path.resolve(projectDir, 'src');
|
|
289
|
+
let srcRealpath;
|
|
290
|
+
try {
|
|
291
|
+
srcRealpath = await fs.realpath(srcDir);
|
|
292
|
+
} catch {
|
|
293
|
+
throw new Error(`Directory "src/" not found in ${path.resolve(projectDir)}.`);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const visitedRealpaths = new Set([srcRealpath]);
|
|
297
|
+
const root = await scanGroupNode(srcRealpath, [], 0, visitedRealpaths, srcDir, srcRealpath);
|
|
298
|
+
return {
|
|
299
|
+
groups: root.groups,
|
|
300
|
+
standalone: root.demos,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function countGroupDemos(groups) {
|
|
305
|
+
return groups.reduce(
|
|
306
|
+
(total, group) => total + group.demos.length + countGroupDemos(group.groups ?? []),
|
|
307
|
+
0,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export function countDemos(manifest) {
|
|
312
|
+
return (manifest.standalone?.length ?? 0) + countGroupDemos(manifest.groups ?? []);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export async function buildDemosJson({
|
|
316
|
+
projectDir = process.cwd(),
|
|
317
|
+
outputFile = path.resolve(projectDir, 'dist', 'demos.json'),
|
|
318
|
+
} = {}) {
|
|
319
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
320
|
+
const resolvedOutputFile = path.resolve(outputFile);
|
|
321
|
+
if (!isWithinRoot(resolvedOutputFile, resolvedProjectDir)) {
|
|
322
|
+
throw new Error(`Refusing to write demos.json outside project directory: ${resolvedOutputFile}`);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const manifest = await scanDemos(resolvedProjectDir);
|
|
326
|
+
const serialized = `${JSON.stringify(manifest, null, 2)}\n`;
|
|
327
|
+
const demoCount = countDemos(manifest);
|
|
328
|
+
|
|
329
|
+
let existing = null;
|
|
330
|
+
try {
|
|
331
|
+
existing = await fs.readFile(resolvedOutputFile, 'utf8');
|
|
332
|
+
} catch {
|
|
333
|
+
existing = null;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (existing === serialized) {
|
|
337
|
+
return { changed: false, demoCount, manifest, outputFile: resolvedOutputFile };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const outputDir = path.dirname(resolvedOutputFile);
|
|
341
|
+
await fs.mkdir(outputDir, { recursive: true });
|
|
342
|
+
|
|
343
|
+
const tempOutputFile = path.join(
|
|
344
|
+
outputDir,
|
|
345
|
+
`.demos.json.${process.pid}.${randomBytes(4).toString('hex')}.tmp`,
|
|
346
|
+
);
|
|
347
|
+
try {
|
|
348
|
+
await fs.writeFile(tempOutputFile, serialized, 'utf8');
|
|
349
|
+
await fs.rename(tempOutputFile, resolvedOutputFile);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
await fs.rm(tempOutputFile, { force: true }).catch(() => {});
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return { changed: true, demoCount, manifest, outputFile: resolvedOutputFile };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function shouldIgnoreWatchEvent(rawFilename) {
|
|
359
|
+
if (typeof rawFilename !== 'string' || !rawFilename) return false;
|
|
360
|
+
const normalized = rawFilename.split(path.sep).join('/');
|
|
361
|
+
if (
|
|
362
|
+
normalized === 'demos.json' ||
|
|
363
|
+
(normalized.startsWith('.demos.json.') && normalized.endsWith('.tmp'))
|
|
364
|
+
) {
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
const segments = normalized.split('/');
|
|
368
|
+
const base = segments.at(-1);
|
|
369
|
+
if (base === '.DS_Store') return true;
|
|
370
|
+
if (segments.includes('node_modules') || segments.includes('.git')) return true;
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export function watchDemos({
|
|
375
|
+
projectDir = process.cwd(),
|
|
376
|
+
outputFile = path.resolve(projectDir, 'dist', 'demos.json'),
|
|
377
|
+
debounceMs = 150,
|
|
378
|
+
onRebuild,
|
|
379
|
+
onError,
|
|
380
|
+
} = {}) {
|
|
381
|
+
const srcDir = path.resolve(projectDir, 'src');
|
|
382
|
+
let timer = null;
|
|
383
|
+
let isBuilding = false;
|
|
384
|
+
let pendingRebuild = false;
|
|
385
|
+
let closed = false;
|
|
386
|
+
|
|
387
|
+
async function runBuild() {
|
|
388
|
+
if (closed) return;
|
|
389
|
+
if (isBuilding) {
|
|
390
|
+
pendingRebuild = true;
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
isBuilding = true;
|
|
395
|
+
try {
|
|
396
|
+
const result = await buildDemosJson({ projectDir, outputFile });
|
|
397
|
+
if (result.changed) {
|
|
398
|
+
onRebuild?.(result);
|
|
399
|
+
}
|
|
400
|
+
} catch (error) {
|
|
401
|
+
onError?.(error);
|
|
402
|
+
} finally {
|
|
403
|
+
isBuilding = false;
|
|
404
|
+
if (pendingRebuild && !closed) {
|
|
405
|
+
pendingRebuild = false;
|
|
406
|
+
scheduleBuild();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function scheduleBuild() {
|
|
412
|
+
if (closed) return;
|
|
413
|
+
if (timer) clearTimeout(timer);
|
|
414
|
+
timer = setTimeout(() => {
|
|
415
|
+
timer = null;
|
|
416
|
+
void runBuild();
|
|
417
|
+
}, debounceMs);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const watcher = watch(srcDir, { recursive: true }, (_eventType, filename) => {
|
|
421
|
+
if (shouldIgnoreWatchEvent(filename)) return;
|
|
422
|
+
scheduleBuild();
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
watcher.on('error', (error) => {
|
|
426
|
+
onError?.(error);
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
return {
|
|
430
|
+
close() {
|
|
431
|
+
closed = true;
|
|
432
|
+
if (timer) {
|
|
433
|
+
clearTimeout(timer);
|
|
434
|
+
timer = null;
|
|
435
|
+
}
|
|
436
|
+
watcher.close();
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { existsSync, watch } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { buildDemosJson } from './build-json.mjs';
|
|
6
|
+
import { CONFIG_FILENAME, loadSiteConfig, renderShellIndexHtml } from './config.mjs';
|
|
7
|
+
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = path.dirname(__filename);
|
|
10
|
+
export const PACKAGE_DIR = path.resolve(__dirname, '..');
|
|
11
|
+
export const SHELL_DIR = path.join(PACKAGE_DIR, 'shell');
|
|
12
|
+
|
|
13
|
+
const SHELL_FILES = ['index.html', 'styles.css', 'scripts.js'];
|
|
14
|
+
|
|
15
|
+
function isWithinRoot(candidatePath, rootPath) {
|
|
16
|
+
return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function copySrcTree(currentSrcDir, currentDestDir, srcRealpath, isRootLevel) {
|
|
20
|
+
const entries = await fs.readdir(currentSrcDir, { withFileTypes: true });
|
|
21
|
+
|
|
22
|
+
for (const entry of entries) {
|
|
23
|
+
// Skip dotfiles/dotdirs (.cdpn.json, .cdpnignore, .codepen, .DS_Store, .gitkeep, etc.) and node_modules
|
|
24
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
|
25
|
+
// Skip any stale top-level src/demos.json — dist/demos.json is generated freshly
|
|
26
|
+
if (isRootLevel && entry.name === 'demos.json') continue;
|
|
27
|
+
|
|
28
|
+
const srcPath = path.join(currentSrcDir, entry.name);
|
|
29
|
+
const destPath = path.join(currentDestDir, entry.name);
|
|
30
|
+
|
|
31
|
+
let lstat;
|
|
32
|
+
try {
|
|
33
|
+
lstat = await fs.lstat(srcPath);
|
|
34
|
+
} catch {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (lstat.isSymbolicLink()) continue;
|
|
39
|
+
|
|
40
|
+
const realSrcPath = await fs.realpath(srcPath);
|
|
41
|
+
if (!isWithinRoot(realSrcPath, srcRealpath)) continue;
|
|
42
|
+
|
|
43
|
+
if (lstat.isDirectory()) {
|
|
44
|
+
await fs.mkdir(destPath, { recursive: true });
|
|
45
|
+
await copySrcTree(realSrcPath, destPath, srcRealpath, false);
|
|
46
|
+
} else if (lstat.isFile()) {
|
|
47
|
+
await fs.copyFile(realSrcPath, destPath);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Builds a complete, static deployable site into `<projectDir>/dist/`:
|
|
54
|
+
* - Copies all non-hidden demos and assets from `<projectDir>/src/`
|
|
55
|
+
* - Layers framework `shell/` files (`index.html`, `styles.css`, `scripts.js`) unless overridden in `src/`
|
|
56
|
+
* - Injects `site` metadata from `config.json` into the default `shell/index.html`
|
|
57
|
+
* - Generates `<projectDir>/dist/demos.json`
|
|
58
|
+
*/
|
|
59
|
+
export async function buildSite({
|
|
60
|
+
projectDir = process.cwd(),
|
|
61
|
+
outDir = path.resolve(projectDir, 'dist'),
|
|
62
|
+
} = {}) {
|
|
63
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
64
|
+
const srcDir = path.resolve(resolvedProjectDir, 'src');
|
|
65
|
+
const distDir = path.resolve(outDir);
|
|
66
|
+
|
|
67
|
+
if (!distDir.startsWith(resolvedProjectDir + path.sep)) {
|
|
68
|
+
throw new Error(`Refusing to build outside project directory: ${distDir}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
let srcRealpath;
|
|
72
|
+
try {
|
|
73
|
+
const stat = await fs.stat(srcDir);
|
|
74
|
+
if (!stat.isDirectory()) {
|
|
75
|
+
throw new Error(`"src" in ${resolvedProjectDir} is not a directory.`);
|
|
76
|
+
}
|
|
77
|
+
srcRealpath = await fs.realpath(srcDir);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
throw new Error(`Directory "src/" not found in ${resolvedProjectDir}.`, { cause: error });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
await fs.rm(distDir, { recursive: true, force: true });
|
|
83
|
+
await fs.mkdir(distDir, { recursive: true });
|
|
84
|
+
|
|
85
|
+
// 1. Copy user demos and any user-provided index overrides from src/
|
|
86
|
+
await copySrcTree(srcRealpath, distDir, srcRealpath, true);
|
|
87
|
+
|
|
88
|
+
// 2. Layer framework shell files wherever the user has not overridden them in src/
|
|
89
|
+
const siteConfig = loadSiteConfig(resolvedProjectDir);
|
|
90
|
+
for (const filename of SHELL_FILES) {
|
|
91
|
+
const destPath = path.join(distDir, filename);
|
|
92
|
+
if (existsSync(destPath)) continue;
|
|
93
|
+
|
|
94
|
+
const shellPath = path.join(SHELL_DIR, filename);
|
|
95
|
+
if (filename === 'index.html') {
|
|
96
|
+
const templateHtml = await fs.readFile(shellPath, 'utf8');
|
|
97
|
+
const renderedHtml = renderShellIndexHtml(templateHtml, siteConfig);
|
|
98
|
+
await fs.writeFile(destPath, renderedHtml, 'utf8');
|
|
99
|
+
} else {
|
|
100
|
+
await fs.copyFile(shellPath, destPath);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// 3. Generate static dist/demos.json
|
|
105
|
+
const { demoCount, manifest } = await buildDemosJson({
|
|
106
|
+
projectDir: resolvedProjectDir,
|
|
107
|
+
outputFile: path.join(distDir, 'demos.json'),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
return { distDir, demoCount, manifest };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function watchSite({
|
|
114
|
+
projectDir = process.cwd(),
|
|
115
|
+
outDir = path.resolve(projectDir, 'dist'),
|
|
116
|
+
debounceMs = 200,
|
|
117
|
+
onRebuild,
|
|
118
|
+
onError,
|
|
119
|
+
} = {}) {
|
|
120
|
+
const resolvedProjectDir = path.resolve(projectDir);
|
|
121
|
+
const srcDir = path.resolve(resolvedProjectDir, 'src');
|
|
122
|
+
let timer = null;
|
|
123
|
+
let isBuilding = false;
|
|
124
|
+
let pendingRebuild = false;
|
|
125
|
+
let closed = false;
|
|
126
|
+
|
|
127
|
+
async function runBuild() {
|
|
128
|
+
if (closed) return;
|
|
129
|
+
if (isBuilding) {
|
|
130
|
+
pendingRebuild = true;
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
isBuilding = true;
|
|
135
|
+
try {
|
|
136
|
+
const result = await buildSite({ projectDir: resolvedProjectDir, outDir });
|
|
137
|
+
onRebuild?.(result);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
onError?.(error);
|
|
140
|
+
} finally {
|
|
141
|
+
isBuilding = false;
|
|
142
|
+
if (pendingRebuild && !closed) {
|
|
143
|
+
pendingRebuild = false;
|
|
144
|
+
scheduleBuild();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function scheduleBuild() {
|
|
150
|
+
if (closed) return;
|
|
151
|
+
if (timer) clearTimeout(timer);
|
|
152
|
+
timer = setTimeout(() => {
|
|
153
|
+
timer = null;
|
|
154
|
+
void runBuild();
|
|
155
|
+
}, debounceMs);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const watchers = [];
|
|
159
|
+
|
|
160
|
+
const srcWatcher = watch(srcDir, { recursive: true }, (_eventType, filename) => {
|
|
161
|
+
if (typeof filename === 'string') {
|
|
162
|
+
const normalized = filename.split(path.sep).join('/');
|
|
163
|
+
const segments = normalized.split('/');
|
|
164
|
+
if (segments.at(-1) === '.DS_Store') return;
|
|
165
|
+
if (segments.includes('node_modules') || segments.includes('.git')) return;
|
|
166
|
+
}
|
|
167
|
+
scheduleBuild();
|
|
168
|
+
});
|
|
169
|
+
srcWatcher.on('error', (error) => onError?.(error));
|
|
170
|
+
watchers.push(srcWatcher);
|
|
171
|
+
|
|
172
|
+
// Also watch project root (non-recursively) for config.json updates
|
|
173
|
+
const rootWatcher = watch(resolvedProjectDir, (_eventType, filename) => {
|
|
174
|
+
if (filename === CONFIG_FILENAME) {
|
|
175
|
+
scheduleBuild();
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
rootWatcher.on('error', (error) => onError?.(error));
|
|
179
|
+
watchers.push(rootWatcher);
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
close() {
|
|
183
|
+
closed = true;
|
|
184
|
+
if (timer) {
|
|
185
|
+
clearTimeout(timer);
|
|
186
|
+
timer = null;
|
|
187
|
+
}
|
|
188
|
+
for (const watcher of watchers) {
|
|
189
|
+
watcher.close();
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|