-
Notifications
You must be signed in to change notification settings - Fork 157
/
sitemap-stream.ts
180 lines (167 loc) · 5.2 KB
/
sitemap-stream.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
import {
Transform,
TransformOptions,
TransformCallback,
Readable,
Writable,
} from 'stream';
import { SitemapItemLoose, ErrorLevel, ErrorHandler } from './types';
import { validateSMIOptions, normalizeURL } from './utils';
import { SitemapItemStream } from './sitemap-item-stream';
import { EmptyStream, EmptySitemap } from './errors';
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
export const stylesheetInclude = (url: string): string => {
return `<?xml-stylesheet type="text/xsl" href="${url}"?>`;
};
const urlsetTagStart =
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
export interface NSArgs {
news: boolean;
video: boolean;
xhtml: boolean;
image: boolean;
custom?: string[];
}
const getURLSetNs: (opts: NSArgs, xslURL?: string) => string = (
{ news, video, image, xhtml, custom },
xslURL
) => {
let ns = xmlDec;
if (xslURL) {
ns += stylesheetInclude(xslURL);
}
ns += urlsetTagStart;
if (news) {
ns += ' xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"';
}
if (xhtml) {
ns += ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
}
if (image) {
ns += ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
}
if (video) {
ns += ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
}
if (custom) {
ns += ' ' + custom.join(' ');
}
return ns + '>';
};
export const closetag = '</urlset>';
export interface SitemapStreamOptions extends TransformOptions {
hostname?: string;
level?: ErrorLevel;
lastmodDateOnly?: boolean;
xmlns?: NSArgs;
xslUrl?: string;
errorHandler?: ErrorHandler;
}
const defaultXMLNS: NSArgs = {
news: true,
xhtml: true,
image: true,
video: true,
};
const defaultStreamOpts: SitemapStreamOptions = {
xmlns: defaultXMLNS,
};
/**
* A [Transform](https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream)
* for turning a
* [Readable stream](https://nodejs.org/api/stream.html#stream_readable_streams)
* of either [SitemapItemOptions](#sitemap-item-options) or url strings into a
* Sitemap. The readable stream it transforms **must** be in object mode.
*/
export class SitemapStream extends Transform {
hostname?: string;
level: ErrorLevel;
hasHeadOutput: boolean;
xmlNS: NSArgs;
xslUrl?: string;
errorHandler?: ErrorHandler;
private smiStream: SitemapItemStream;
lastmodDateOnly: boolean;
constructor(opts = defaultStreamOpts) {
opts.objectMode = true;
super(opts);
this.hasHeadOutput = false;
this.hostname = opts.hostname;
this.level = opts.level || ErrorLevel.WARN;
this.errorHandler = opts.errorHandler;
this.smiStream = new SitemapItemStream({ level: opts.level });
this.smiStream.on('data', (data) => this.push(data));
this.lastmodDateOnly = opts.lastmodDateOnly || false;
this.xmlNS = opts.xmlns || defaultXMLNS;
this.xslUrl = opts.xslUrl;
}
_transform(
item: SitemapItemLoose,
encoding: string,
callback: TransformCallback
): void {
if (!this.hasHeadOutput) {
this.hasHeadOutput = true;
this.push(getURLSetNs(this.xmlNS, this.xslUrl));
}
if (
!this.smiStream.write(
validateSMIOptions(
normalizeURL(item, this.hostname, this.lastmodDateOnly),
this.level,
this.errorHandler
)
)
) {
this.smiStream.once('drain', callback);
} else {
process.nextTick(callback);
}
}
_flush(cb: TransformCallback): void {
if (!this.hasHeadOutput) {
cb(new EmptySitemap());
} else {
this.push(closetag);
cb();
}
}
}
/**
* Converts a readable stream into a promise that resolves with the concatenated data from the stream.
*
* The function listens for 'data' events from the stream, and when the stream ends, it resolves the promise with the concatenated data. If an error occurs while reading from the stream, the promise is rejected with the error.
*
* ⚠️ CAUTION: This function should not generally be used in production / when writing to files as it holds a copy of the entire file contents in memory until finished.
*
* @param {Readable} stream - The readable stream to convert to a promise.
* @returns {Promise<Buffer>} A promise that resolves with the concatenated data from the stream as a Buffer, or rejects with an error if one occurred while reading from the stream. If the stream is empty, the promise is rejected with an EmptyStream error.
* @throws {EmptyStream} If the stream is empty.
*/
export function streamToPromise(stream: Readable): Promise<Buffer> {
return new Promise((resolve, reject): void => {
const drain: Buffer[] = [];
stream
// Error propagation is not automatic
// Bubble up errors on the read stream
.on('error', reject)
.pipe(
new Writable({
write(chunk, enc, next): void {
drain.push(chunk);
next();
},
})
)
// This bubbles up errors when writing to the internal buffer
// This is unlikely to happen, but we have this for completeness
.on('error', reject)
.on('finish', () => {
if (!drain.length) {
reject(new EmptyStream());
} else {
resolve(Buffer.concat(drain));
}
});
});
}