1
1
import * as fs from "fs" ;
2
2
import * as path from "path" ;
3
3
import { promisify } from "util" ;
4
+ import { JSDOM } from "jsdom" ;
5
+ import { CallbackWrapper } from "./misc"
4
6
5
7
export async function postProcess ( workDir : string , filePattern : string ) : Promise < void > {
6
8
const readdir = promisify ( fs . readdir ) ;
@@ -15,6 +17,7 @@ export async function postProcess(workDir: string, filePattern: string): Promise
15
17
}
16
18
17
19
await postProcessBody ( workDir , htmlFiles [ 0 ] , txtFiles [ 0 ] ) ;
20
+ await postProcessHeader ( workDir , htmlFiles [ 0 ] ) ;
18
21
}
19
22
20
23
async function postProcessBody ( workDir : string , htmlFile : string , ssrFile : string ) : Promise < void > {
@@ -41,5 +44,40 @@ async function postProcessBody(workDir: string, htmlFile: string, ssrFile: strin
41
44
console . error ( `Failed to write to file ${ htmlFilePath } , error: ${ err } ` )
42
45
} ) ;
43
46
out . forEach ( str => { stream . write ( str ) ; } ) ;
47
+
44
48
stream . end ( ) ;
49
+
50
+ let cbWrapper : CallbackWrapper | undefined ;
51
+ const waitForBufferFlush = new Promise < void > ( ( resolve ) => { cbWrapper = new CallbackWrapper ( resolve ) ; } ) ;
52
+
53
+ stream . on ( "close" , function ( ) {
54
+ cbWrapper ?. invoke ( ) ;
55
+ } ) ;
56
+
57
+ await waitForBufferFlush ;
58
+ }
59
+
60
+ async function postProcessHeader ( workDir : string , htmlFile : string ) : Promise < void > {
61
+ const htmlFilePath = path . join ( workDir , htmlFile ) ;
62
+ const jsdom = await JSDOM . fromFile ( htmlFilePath ) ;
63
+
64
+ if ( ! jsdom ) {
65
+ throw "JSDOM creation failure" ;
66
+ }
67
+
68
+ const writeFile = promisify ( fs . writeFile ) ;
69
+ const hdr : HTMLHeadElement = jsdom . window . document . head ;
70
+ const script = jsdom . window . document . createElement ( "script" ) ;
71
+ const structuredData = `{
72
+ "@context": "https://schema.org",
73
+ "@type": "WebPage",
74
+ "datePublished": "${ new Date ( ) . toISOString ( ) . split ( "T" ) [ 0 ] } ",
75
+ }` ;
76
+
77
+ script . setAttribute ( "type" , "application/ld+json" ) ;
78
+ script . textContent = structuredData ;
79
+ hdr . appendChild ( script ) ;
80
+ await writeFile ( htmlFilePath , jsdom . serialize ( ) ) ;
45
81
}
82
+
83
+
0 commit comments