11import { registerPlugin , HandledRoute } from '@scullyio/scully' ;
2- import * as from 'fs' ;
2+ import * as fs from 'fs/promises' ;
3+ import { marked } from 'marked' ;
34
5+ // @ts -ignore
6+ import { JSDOM } from 'jsdom' ;
47
58const Plugin = async ( routes ?: HandledRoute [ ] , config = { } ) : Promise < HandledRoute [ ] > => {
69 if ( ! routes ) {
710 return [ ] ;
811 }
912
10- routes . map ( ( route ) => {
11- console . log ( route ) ;
12- if ( route . type !== 'contentFolder' ) return route ;
13+ for ( let i = 0 , l = routes . length ; i < l ; i ++ ) {
14+ const route = routes [ i ] ;
15+
16+ if ( route . type !== 'contentFolder' ) continue ;
17+
18+ if ( route . data === undefined ) {
19+ route . data = { } ;
20+ }
1321
1422 // Remove strange extension (".html") added by esa from the url
1523 if ( route . templateFile ?. match ( / \. h t m l \. m d $ / ) ) {
@@ -21,11 +29,53 @@ const Plugin = async (routes?: HandledRoute[], config = {}): Promise<HandledRout
2129 route . data . tags = route . data . tags . split ( / \s * , \s * / ) ;
2230 }
2331
24- // Open file
32+ // Parse file
33+ if ( route . templateFile && route . templateFile . match ( / \. m d $ / ) ) {
34+ try {
35+ let markdown = await fs . readFile ( route . templateFile , 'utf-8' ) ;
36+ let markdownLines = markdown . split ( / \n / ) ;
37+ let endLineOfMetaData = 0 ;
38+ for ( let i = 1 ; i < markdownLines . length ; i ++ ) {
39+ if ( markdownLines [ i ] . match ( / ^ - - - $ / ) ) {
40+ endLineOfMetaData = i ;
41+ break ;
42+ }
43+ }
44+ markdown = markdownLines . slice ( endLineOfMetaData + 1 ) . join ( '\n' ) ;
45+
46+ const html = marked . parse ( markdown ) ;
47+ const dom = new JSDOM ( html ) ;
2548
49+ // Extract beginning text
50+ route . data . beginningText = '' ;
51+ const paragraphs = dom . window . document . querySelectorAll ( 'p' ) ;
52+ for ( let i = 0 ; i < paragraphs . length ; i ++ ) {
53+ const paragraph = paragraphs [ i ] ;
54+ if ( paragraph . textContent ?. length ) {
55+ route . data . beginningText += paragraph . textContent ;
56+ }
57+ if ( route . data . beginningText . length > 200 ) {
58+ break ;
59+ }
60+ }
61+
62+ // Extract images
63+ route . data . imageUrls = [ ] ;
64+ const imageElems = dom . window . document . querySelectorAll ( 'img' ) ;
65+ for ( let i = 0 ; i < imageElems . length ; i ++ ) {
66+ const image = imageElems [ i ] ;
67+ route . data . imageUrls . push ( image . src ) ;
68+ }
69+ } catch ( e : any ) {
70+ console . error ( `[EsaRouteProcess]` , e ) ;
71+ }
72+ } else {
73+ console . warn ( `[EsaRouteProcess]` , 'Could not parse file' , route . templateFile ) ;
74+ }
75+
76+ routes [ i ] = route ;
77+ }
2678
27- return route ;
28- } ) ;
2979 return routes ;
3080} ;
3181
0 commit comments