-
Notifications
You must be signed in to change notification settings - Fork 6
/
serverRenderPlugin.ts
240 lines (208 loc) · 6.75 KB
/
serverRenderPlugin.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
import type { AssetManifest } from './assetManifest';
import type { Request } from './request';
import type { Response } from './response';
export type RootComponent = (props: any) => React.ReactElement;
export interface ClientPluginReference {
importSpec: string;
options?: unknown;
}
interface RendererPluginHostOptions {
assetManifest: AssetManifest;
deadlineAt: number;
request: Readonly<Request>;
renderMode: 'client' | 'server';
start: number;
}
interface ServerPluginContext<TPluginState = unknown>
extends RendererPluginHostOptions {
state: TPluginState;
}
export interface ServerPlugin<TPluginState = unknown> {
name: string;
/**
* Create a per-build state object or value that will be available throughout the render
* pipeline as the `ctx.state` property on all hooks.
*/
createState?(ctx: Omit<ServerPluginContext, 'state'>): TPluginState;
/**
* Wrap or replace the root React component. Useful for injecting Providers.
*
* Example:
* ```js
* function wrapProviderPlugin(provider, providerProps = null) {
* return {
* name: 'wrap-provider-plugin',
* decorateApp(ctx, app) {
* return () => React.createElement(provider, providerProps, React.createElement(app));
* }
* }
* }
* ```
*/
decorateApp?(
ctx: ServerPluginContext<TPluginState>,
app: RootComponent
): RootComponent;
/**
* Called at each tick of the server render loop to see if circumstances are such that no further
* rendering should happen. For example, a routing plugin that receives a redirect instruction
* would return `true` to prevent any further renders from happening.
*/
shouldAbortRendering?(ctx: ServerPluginContext<TPluginState>): boolean;
/**
* Called at each tick of the server render loop to see if the plugin has any pending operations
* that should be awaited.
*
* Note that even if a plugin returns pending operations, it is possible that the request is
* served without waiting for these to complete. This might happen if the render deadline
* passes or if another plugin signals that rendering should abort via `shouldAbortRendering`.
*/
getPendingOperations?(
ctx: ServerPluginContext<TPluginState>
): PromiseLike<unknown>[];
/**
* Called after the server render loop is exited, giving plugins an opportunity to stop any
* pending work.
*/
cancelPendingOperations?(
ctx: ServerPluginContext<TPluginState>
): PromiseLike<void>;
/**
* Called with an [linkedom](https://npm.im/linkedom) `Document` instance, giving plugins
* the ability to manipulate the document prior to serializing and serving it.
*
* Plugins might use this to set the document's title, change element attributes or perform
* any other DOM manipulation that should be reflected in the actual HTML served.
*/
renderHtml?(ctx: ServerPluginContext<TPluginState>, document: Document): void;
/**
* Get bootstrap data that the server-side plugin wishes to pass to the client-side plugin.
*
* This gives server plugins the ability to pass data to their client-side counterparts. A
* server-side plugin might, for example, accumulate some state in an object returned by the
* `createState` hook.
*/
getClientBootstrapData?(ctx: ServerPluginContext<TPluginState>): unknown;
/**
* Decorate or replace the pending Response.
*
* This gives server plugins the ability to modify or replace the Response object that is about
* to be served back to the caller. This is useful for server plugins that might want to inject
* custom http headers or even replace the response with a redirect.
*/
decorateResponse?(
ctx: ServerPluginContext<TPluginState>,
response: Response
): Response | undefined | null;
}
export class RendererPluginHost {
private readonly pluginsWithState: Array<{
readonly plugin: Readonly<ServerPlugin>;
readonly state: unknown;
}> = [];
private readonly ctx: Readonly<RendererPluginHostOptions>;
constructor(
plugins: ReadonlyArray<Readonly<ServerPlugin>>,
options: RendererPluginHostOptions
) {
this.ctx = options;
for (const plugin of plugins) {
// Initialize each plugin's state (if any)
this.pluginsWithState.push({
plugin: plugin,
state: plugin.createState?.(this.ctx),
});
}
}
getBuildPlugins() {}
decorateApp(app: RootComponent) {
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.decorateApp === 'function') {
// Apply a sort of reducer pattern to wrap / decorate
// the app component with whatever the Plugin wants to
// contribute.
app = plugin.decorateApp(
{
...this.ctx,
state,
},
app
);
}
}
return app;
}
shouldAbortRendering(): boolean {
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.shouldAbortRendering === 'function') {
if (
plugin.shouldAbortRendering({
...this.ctx,
state,
})
) {
return true;
}
}
}
return false;
}
getPendingOperations(): PromiseLike<unknown>[] {
const pendingOperations: PromiseLike<unknown>[] = [];
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.getPendingOperations === 'function') {
pendingOperations.push(
...plugin.getPendingOperations({
...this.ctx,
state,
})
);
}
}
return pendingOperations;
}
async cancelPendingOperations(): Promise<void> {
const promises: PromiseLike<void>[] = [];
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.cancelPendingOperations === 'function') {
promises.push(
plugin.cancelPendingOperations({
...this.ctx,
state,
})
);
}
}
if (promises.length) {
await Promise.all(promises);
}
}
renderHtml(document: Document) {
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.renderHtml === 'function') {
plugin.renderHtml(
{
...this.ctx,
state,
},
document
);
}
}
}
getClientBootstrapData(): Record<string, unknown> {
const bootstrapData: Record<string, unknown> = {};
for (const { plugin, state } of this.pluginsWithState) {
if (typeof plugin.getClientBootstrapData === 'function') {
const clientBootstrapData = plugin.getClientBootstrapData({
...this.ctx,
state,
});
if (clientBootstrapData) {
bootstrapData[plugin.name] = clientBootstrapData;
}
}
}
return bootstrapData;
}
}