-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpugToTypes.ts
437 lines (355 loc) · 11.2 KB
/
pugToTypes.ts
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { render } from "pug"
import { Document, load as loadCheerio } from "cheerio"
import { camelCase } from "change-case"
import chokidar from "chokidar"
import path from "node:path"
import pth from "node:path"
import fss, {promises as fs} from "fs"
declare const Bun: any
import { program } from "commander"
program
.option('-w, --watch')
.parse()
const options = program.opts() as {watch?: boolean}
const htmlInterfaceString = `
"a": HTMLAnchorElement;
"abbr": HTMLElement;
"address": HTMLElement;
"area": HTMLAreaElement;
"article": HTMLElement;
"aside": HTMLElement;
"audio": HTMLAudioElement;
"b": HTMLElement;
"base": HTMLBaseElement;
"bdi": HTMLElement;
"bdo": HTMLElement;
"blockquote": HTMLQuoteElement;
"body": HTMLBodyElement;
"br": HTMLBRElement;
"button": HTMLButtonElement;
"canvas": HTMLCanvasElement;
"caption": HTMLTableCaptionElement;
"cite": HTMLElement;
"code": HTMLElement;
"col": HTMLTableColElement;
"colgroup": HTMLTableColElement;
"data": HTMLDataElement;
"datalist": HTMLDataListElement;
"dd": HTMLElement;
"del": HTMLModElement;
"details": HTMLDetailsElement;
"dfn": HTMLElement;
"dialog": HTMLDialogElement;
"div": HTMLDivElement;
"dl": HTMLDListElement;
"dt": HTMLElement;
"em": HTMLElement;
"embed": HTMLEmbedElement;
"fieldset": HTMLFieldSetElement;
"figcaption": HTMLElement;
"figure": HTMLElement;
"footer": HTMLElement;
"form": HTMLFormElement;
"h1": HTMLHeadingElement;
"h2": HTMLHeadingElement;
"h3": HTMLHeadingElement;
"h4": HTMLHeadingElement;
"h5": HTMLHeadingElement;
"h6": HTMLHeadingElement;
"head": HTMLHeadElement;
"header": HTMLElement;
"hgroup": HTMLElement;
"hr": HTMLHRElement;
"html": HTMLHtmlElement;
"i": HTMLElement;
"iframe": HTMLIFrameElement;
"img": HTMLImageElement;
"input": HTMLInputElement;
"ins": HTMLModElement;
"kbd": HTMLElement;
"label": HTMLLabelElement;
"legend": HTMLLegendElement;
"li": HTMLLIElement;
"link": HTMLLinkElement;
"main": HTMLElement;
"map": HTMLMapElement;
"mark": HTMLElement;
"menu": HTMLMenuElement;
"meta": HTMLMetaElement;
"meter": HTMLMeterElement;
"nav": HTMLElement;
"noscript": HTMLElement;
"object": HTMLObjectElement;
"ol": HTMLOListElement;
"optgroup": HTMLOptGroupElement;
"option": HTMLOptionElement;
"output": HTMLOutputElement;
"p": HTMLParagraphElement;
"picture": HTMLPictureElement;
"pre": HTMLPreElement;
"progress": HTMLProgressElement;
"q": HTMLQuoteElement;
"rp": HTMLElement;
"rt": HTMLElement;
"ruby": HTMLElement;
"s": HTMLElement;
"samp": HTMLElement;
"script": HTMLScriptElement;
"search": HTMLElement;
"section": HTMLElement;
"select": HTMLSelectElement;
"slot": HTMLSlotElement;
"small": HTMLElement;
"source": HTMLSourceElement;
"span": HTMLSpanElement;
"strong": HTMLElement;
"style": HTMLStyleElement;
"sub": HTMLElement;
"summary": HTMLElement;
"sup": HTMLElement;
"table": HTMLTableElement;
"tbody": HTMLTableSectionElement;
"td": HTMLTableCellElement;
"template": HTMLTemplateElement;
"textarea": HTMLTextAreaElement;
"tfoot": HTMLTableSectionElement;
"th": HTMLTableCellElement;
"thead": HTMLTableSectionElement;
"time": HTMLTimeElement;
"title": HTMLTitleElement;
"tr": HTMLTableRowElement;
"track": HTMLTrackElement;
"u": HTMLElement;
"ul": HTMLUListElement;
"var": HTMLElement;
"video": HTMLVideoElement;
"wbr": HTMLElement;
`;
const svgInterfaceString = `
"a": SVGAElement;
"animate": SVGAnimateElement;
"animateMotion": SVGAnimateMotionElement;
"animateTransform": SVGAnimateTransformElement;
"circle": SVGCircleElement;
"clipPath": SVGClipPathElement;
"defs": SVGDefsElement;
"desc": SVGDescElement;
"ellipse": SVGEllipseElement;
"feBlend": SVGFEBlendElement;
"feColorMatrix": SVGFEColorMatrixElement;
"feComponentTransfer": SVGFEComponentTransferElement;
"feComposite": SVGFECompositeElement;
"feConvolveMatrix": SVGFEConvolveMatrixElement;
"feDiffuseLighting": SVGFEDiffuseLightingElement;
"feDisplacementMap": SVGFEDisplacementMapElement;
"feDistantLight": SVGFEDistantLightElement;
"feDropShadow": SVGFEDropShadowElement;
"feFlood": SVGFEFloodElement;
"feFuncA": SVGFEFuncAElement;
"feFuncB": SVGFEFuncBElement;
"feFuncG": SVGFEFuncGElement;
"feFuncR": SVGFEFuncRElement;
"feGaussianBlur": SVGFEGaussianBlurElement;
"feImage": SVGFEImageElement;
"feMerge": SVGFEMergeElement;
"feMergeNode": SVGFEMergeNodeElement;
"feMorphology": SVGFEMorphologyElement;
"feOffset": SVGFEOffsetElement;
"fePointLight": SVGFEPointLightElement;
"feSpecularLighting": SVGFESpecularLightingElement;
"feSpotLight": SVGFESpotLightElement;
"feTile": SVGFETileElement;
"feTurbulence": SVGFETurbulenceElement;
"filter": SVGFilterElement;
"foreignObject": SVGForeignObjectElement;
"g": SVGGElement;
"image": SVGImageElement;
"line": SVGLineElement;
"linearGradient": SVGLinearGradientElement;
"marker": SVGMarkerElement;
"mask": SVGMaskElement;
"metadata": SVGMetadataElement;
"mpath": SVGMPathElement;
"path": SVGPathElement;
"pattern": SVGPatternElement;
"polygon": SVGPolygonElement;
"polyline": SVGPolylineElement;
"radialGradient": SVGRadialGradientElement;
"rect": SVGRectElement;
"script": SVGScriptElement;
"set": SVGSetElement;
"stop": SVGStopElement;
"style": SVGStyleElement;
"svg": SVGSVGElement;
"switch": SVGSwitchElement;
"symbol": SVGSymbolElement;
"text": SVGTextElement;
"textPath": SVGTextPathElement;
"title": SVGTitleElement;
"tspan": SVGTSpanElement;
"use": SVGUseElement;
"view": SVGViewElement;
`;
const htmlMap = parseInterface(htmlInterfaceString);
const svgMap = parseInterface(svgInterfaceString);
const rootPath = "app/_component"
const componentIndex = new Map<string, {
path: string
}>()
const kind = "add"
const paths = [] as string[]
await readDirRecursiveOnce(rootPath, (path: string) => {
updateComponentIndex(path, kind)
paths.push(path)
})
let proms = [] as Promise<any>[]
for (const path of paths) {
proms.push(handlePugUpdate(path, kind))
}
await Promise.all(proms)
proms = []
for (const filePath of paths) {
proms.push((async () => {
if (filePath.endsWith(".ts") && path.basename(path.dirname(filePath) + ".ts") === path.basename(filePath)) {
if (!await fileExists(path.join(path.dirname(filePath), "pugBody.gen.ts"))) {
await fs.writeFile(path.join(path.dirname(filePath), "pugBody.gen.ts"), `export interface BodyTypes {}`)
}
}
})())
}
await Promise.all(proms)
console.log("PugToTypes: Done")
if (options.watch) {
console.log("PugToTypes: Watching...")
chokidar.watch(rootPath, { ignoreInitial: true }).on("add", (path: string) => updateComponentIndex(path, "add"))
chokidar.watch(rootPath, { ignoreInitial: true }).on("unlink", (path: string) => updateComponentIndex(path, "remove"))
// after initial
setTimeout(() => {
chokidar.watch(rootPath, { ignoreInitial: true }).on("add", (path: string) => handlePugUpdate(path, "add"))
chokidar.watch(rootPath, { ignoreInitial: true }).on("change", (path: string) => handlePugUpdate(path, "change"))
}, 500)
}
async function readDirRecursiveOnce(dir: string, func: (path: string) => (void | Promise<void>)) {
const proms = [] as (void | Promise<void>)[]
const files = await fs.readdir(dir)
const subDirs = [] as string[]
for await (const filePath of files) {
const file = await fs.stat(path.join(dir, filePath))
if (file.isDirectory()) {
subDirs.push(filePath)
}
else if (file.isFile()) {
proms.push(func(path.join(dir, filePath)))
}
}
for (const subDir of subDirs) {
proms.push(readDirRecursiveOnce(path.join(dir, subDir), func))
}
await Promise.all(proms)
}
function updateComponentIndex(dir: string, kind: "add" | "remove") {
const name = path.basename(dir) as string
if (!name.endsWith(".ts")) return
if (kind === "add") {
componentIndex.set(name.slice(0, -3), { path: dir })
}
else if (kind === "remove") {
componentIndex.delete(name.slice(0, -3))
}
}
async function pugToTypes(pugFilePath: string) {
const pugContent = await fs.readFile(pugFilePath, "utf8")
const html = render(pugContent, { pretty: true })
const $ = loadCheerio(html);
const allElems = [...$("body *")]
const types = {
imports: new Map<ComponentPath, ComponentTagName | false>(),
types: [] as string[]
}
for (const el of allElems) {
const componentTagName = parseComponentTagName(el.tagName.toLowerCase())
if (componentTagName !== false) {
const component = componentIndex.get(componentTagName)
if (component) {
const componentPath = "./" + removeExtension(path.relative(path.join(pugFilePath, ".."), component.path))
types.imports.set(componentPath, false)
}
}
}
const elemsWithName = allElems.filter((el) => "name" in el.attribs)
const links = elemsWithName.map((el) => ({name: el.attribs.name, tagName: el.tagName.toLowerCase(), componentTagName: parseComponentTagName(el.tagName.toLowerCase())} as const))
type ComponentPath = string
type ComponentTagName = string
for (const { name, tagName, componentTagName } of links) {
if (componentTagName !== false) {
const component = componentIndex.get(componentTagName)
if (component) {
const componentPath = "./" + removeExtension(path.relative(path.join(pugFilePath, ".."), component.path))
const elemName = capitalize(componentTagName)
types.imports.set(componentPath, elemName)
// types.imports.add(`import ${elemName} from "${componentPath}"; import "${componentPath}"`)
types.types.push(`${name}: ${elemName}`)
}
else {
types.types.push(`${name}: HTMLElement`)
}
}
else {
if (htmlMap.has(tagName)) {
types.types.push(`${name}: ${htmlMap.get(tagName)}`)
}
else if (svgMap.has(tagName)) {
types.types.push(`${name}: ${svgMap.get(tagName)}`)
}
else {
types.types.push(`${name}: HTMLElement`)
}
}
}
return [...types.imports.keys()].map((componentPath) => {
const elemName = types.imports.get(componentPath)
const justElemImport = `import "${componentPath}"`
if (elemName === false) return justElemImport
else return `import ${elemName} from "${componentPath}"; ` + justElemImport
}).join("\n") + (types.imports.size > 0 ? "\n\n" : "") +
`export interface BodyTypes {
${types.types.join("\n ")}
}
`
}
async function handlePugUpdate(dir: string, kind: "add" | "change") {
const name = path.basename(dir) as string
if (!name.endsWith(".pug")) return
const types = await pugToTypes(dir)
const typesPath = path.join(path.dirname(dir), "pugBody.gen.ts")
await fs.writeFile(typesPath, types)
}
function removeExtension(s: string) {
return s.replace(/\.[^/.]+$/, "")
}
function parseComponentTagName(s: string) {
if (s.startsWith("c-")) return camelCase(s.slice(2))
else return false
}
function capitalize(s: string) {
return s[0].toUpperCase() + s.slice(1)
}
function parseInterface(interfaceString: string): Map<string, string> {
const map = new Map<string, string>();
const lines = interfaceString.split('\n');
// Assuming each line is in the format: '"tag": ClassName;'
for (let line of lines) {
const match = line.match(/"(\w+)": (\w+);/);
if (match) {
const tag = match[1];
const className = match[2];
map.set(tag, className);
}
}
return map;
}
function fileExists(filePath: string) {
return fs.access(filePath)
.then(() => true)
.catch(() => false)
}