forked from gatsbyjs/gatsby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.ts
581 lines (505 loc) · 16.1 KB
/
manager.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
import reporter from "gatsby-cli/lib/reporter"
import { applyTrailingSlashOption, TrailingSlash } from "gatsby-page-utils"
import { generateHtmlPath } from "gatsby-core-utils/page-html"
import { slash } from "gatsby-core-utils/path"
import { generatePageDataPath } from "gatsby-core-utils/page-data"
import { posix } from "path"
import { sync as globSync } from "glob"
import telemetry from "gatsby-telemetry"
import { copy, pathExists, unlink } from "fs-extra"
import type {
FunctionsManifest,
IAdaptContext,
RoutesManifest,
Route,
IAdapterManager,
IFunctionRoute,
IAdapter,
IAdapterFinalConfig,
IAdapterConfig,
} from "./types"
import { store, readState } from "../../redux"
import { getPageMode } from "../page-mode"
import { getStaticQueryPath } from "../static-query-utils"
import { getAdapterInit } from "./init"
import {
LmdbOnCdnPath,
shouldBundleDatastore,
shouldGenerateEngines,
} from "../engines-helpers"
import {
BASE_HEADERS,
MUST_REVALIDATE_HEADERS,
PERMAMENT_CACHING_HEADERS,
} from "./constants"
import { createHeadersMatcher } from "./create-headers"
import { HTTP_STATUS_CODE } from "../../redux/types"
import type { IHeader } from "../../redux/types"
import { rankRoute } from "../rank-route"
import {
getRoutePathFromFunction,
getRoutePathFromPage,
} from "./get-route-path"
import { noOpAdapterManager } from "./no-op-manager"
import { getDefaultDbPath } from "../../datastore/lmdb/lmdb-datastore"
async function setAdapter({
instance,
manager,
}: {
instance?: IAdapter
manager: IAdapterManager
}): Promise<void> {
const configFromAdapter = await manager.config()
store.dispatch({
type: `SET_ADAPTER`,
payload: {
manager,
instance,
config: configFromAdapter,
},
})
if (instance) {
// if adapter reports that it doesn't support certain features, we need to fail the build
// to avoid broken deploys
const incompatibleFeatures: Array<string> = []
// pathPrefix support
if (
configFromAdapter?.supports?.pathPrefix === false &&
store.getState().program.prefixPaths &&
store.getState().config.pathPrefix
) {
incompatibleFeatures.push(`pathPrefix is not supported.`)
}
// trailingSlash support
if (configFromAdapter?.supports?.trailingSlash) {
const { trailingSlash } = store.getState().config
if (
!configFromAdapter.supports.trailingSlash.includes(
trailingSlash ?? `always`
)
) {
incompatibleFeatures.push(
`trailingSlash option "${trailingSlash}". Supported option${
configFromAdapter.supports.trailingSlash.length > 1 ? `s` : ``
}: ${configFromAdapter.supports.trailingSlash
.map(option => `"${option}"`)
.join(`, `)}`
)
}
}
if (incompatibleFeatures.length > 0) {
reporter.warn(
`Adapter "${
instance.name
}" is not compatible with following settings:\n${incompatibleFeatures
.map(line => ` - ${line}`)
.join(`\n`)}`
)
}
if (configFromAdapter.pluginsToDisable.length > 0) {
store.dispatch({
type: `DISABLE_PLUGINS_BY_NAME`,
payload: {
pluginsToDisable: configFromAdapter.pluginsToDisable,
reason: `Not compatible with the "${instance.name}" adapter. Please remove it from your gatsby-config.`,
},
})
}
}
}
export async function initAdapterManager(): Promise<IAdapterManager> {
let adapter: IAdapter
const config = store.getState().config
const { adapter: adapterFromGatsbyConfig, trailingSlash, pathPrefix } = config
// If the user specified an adapter inside their gatsby-config, use that instead of trying to figure out an adapter for the current environment
if (adapterFromGatsbyConfig) {
adapter = adapterFromGatsbyConfig
reporter.verbose(`Using adapter ${adapter.name} from gatsby-config`)
} else {
const adapterInit =
adapterFromGatsbyConfig === false ? false : await getAdapterInit()
// If we don't have adapter, use no-op adapter manager
if (!adapterInit) {
telemetry.trackFeatureIsUsed(`adapter:no-op`)
const manager = noOpAdapterManager()
await setAdapter({ manager })
return manager
}
adapter = adapterInit()
}
reporter.info(`Using ${adapter.name} adapter`)
telemetry.trackFeatureIsUsed(`adapter:${adapter.name}`)
const directoriesToCache = [`.cache`, `public`]
const manager: IAdapterManager = {
restoreCache: async (): Promise<void> => {
if (!adapter.cache) {
return
}
const result = await adapter.cache.restore({
directories: directoriesToCache,
reporter,
})
if (result === false) {
// if adapter reports `false`, we can skip trying to re-hydrate state
return
}
const cachedState = readState()
// readState() returns empty object if there is no cached state or it's corrupted etc
// so we want to avoid dispatching RESTORE_CACHE action in that case
if (Object.keys(cachedState).length > 0) {
store.dispatch({
type: `RESTORE_CACHE`,
payload: cachedState,
})
}
},
storeCache: async (): Promise<void> => {
if (!adapter.cache) {
return
}
await adapter.cache.store({ directories: directoriesToCache, reporter })
},
adapt: async (): Promise<void> => {
if (!adapter.adapt) {
return
}
// handle lmdb file
const mdbInPublicPath = `public/${LmdbOnCdnPath}`
if (!shouldBundleDatastore()) {
const mdbPath = getDefaultDbPath() + `/data.mdb`
copy(mdbPath, mdbInPublicPath)
} else {
// ensure public dir doesn't have lmdb file
if (await pathExists(mdbInPublicPath)) {
await unlink(mdbInPublicPath)
}
}
let _routesManifest: RoutesManifest | undefined = undefined
let _functionsManifest: FunctionsManifest | undefined = undefined
const adaptContext: IAdaptContext = {
get routesManifest(): RoutesManifest {
if (!_routesManifest) {
_routesManifest = getRoutesManifest()
}
return _routesManifest
},
get functionsManifest(): FunctionsManifest {
if (!_functionsManifest) {
_functionsManifest = getFunctionsManifest()
}
return _functionsManifest
},
reporter,
// Our internal Gatsby config allows this to be undefined but for the adapter we should always pass through the default values and correctly show this in the TypeScript types
trailingSlash: trailingSlash as TrailingSlash,
pathPrefix: pathPrefix as string,
}
await adapter.adapt(adaptContext)
},
config: async (): Promise<IAdapterFinalConfig> => {
let configFromAdapter: undefined | IAdapterConfig = undefined
if (adapter.config) {
configFromAdapter = await adapter.config({ reporter })
if (
configFromAdapter?.excludeDatastoreFromEngineFunction &&
!configFromAdapter?.deployURL
) {
throw new Error(
`Can't exclude datastore from engine function without adapter providing deployURL`
)
}
}
return {
excludeDatastoreFromEngineFunction:
configFromAdapter?.excludeDatastoreFromEngineFunction ?? false,
deployURL: configFromAdapter?.deployURL,
supports: configFromAdapter?.supports,
pluginsToDisable: configFromAdapter?.pluginsToDisable ?? [],
}
},
}
await setAdapter({ manager, instance: adapter })
return manager
}
let webpackAssets: Set<string> | undefined
export function setWebpackAssets(assets: Set<string>): void {
webpackAssets = assets
}
type RouteWithScore = { score: number } & Route
function getRoutesManifest(): RoutesManifest {
const routes: Array<RouteWithScore> = []
const state = store.getState()
const createHeaders = createHeadersMatcher(state.config.headers)
const fileAssets = new Set(
globSync(`**/**`, {
cwd: posix.join(process.cwd(), `public`),
nodir: true,
dot: true,
}).map(filePath => slash(filePath))
)
// TODO: This could be a "addSortedRoute" function that would add route to the list in sorted order. TBD if necessary performance-wise
function addRoute(route: Route): void {
if (!route.path.startsWith(`/`)) {
route.path = `/${route.path}`
}
// Apply trailing slash behavior unless it's a redirect. Redirects should always be exact matches
if (route.type !== `redirect`) {
route.path = applyTrailingSlashOption(
route.path,
state.config.trailingSlash
)
}
if (route.type !== `function`) {
route.headers = createHeaders(route.path, route.headers)
}
;(route as RouteWithScore).score = rankRoute(route.path)
routes.push(route as RouteWithScore)
}
function addStaticRoute({
path,
pathToFillInPublicDir,
headers,
}: {
path: string
pathToFillInPublicDir: string
headers: IHeader["headers"]
}): void {
addRoute({
path,
type: `static`,
filePath: posix.join(`public`, pathToFillInPublicDir),
headers,
})
if (fileAssets.has(pathToFillInPublicDir)) {
fileAssets.delete(pathToFillInPublicDir)
} else {
reporter.verbose(
`[Adapters] Tried to remove "${pathToFillInPublicDir}" from fileAssets but it wasn't there`
)
}
}
// routes - pages - static (SSG) or function (DSG/SSR)
for (const page of state.pages.values()) {
const htmlRoutePath = slash(getRoutePathFromPage(page))
const pageDataRoutePath = slash(generatePageDataPath(``, htmlRoutePath))
const pageMode = getPageMode(page)
if (pageMode === `SSG`) {
const htmlFilePath = slash(generateHtmlPath(``, page.path))
const pageDataFilePath = slash(generatePageDataPath(``, page.path))
addStaticRoute({
path: htmlRoutePath,
pathToFillInPublicDir: htmlFilePath,
headers: MUST_REVALIDATE_HEADERS,
})
addStaticRoute({
path: pageDataRoutePath,
pathToFillInPublicDir: pageDataFilePath,
headers: MUST_REVALIDATE_HEADERS,
})
} else {
const commonFields: Omit<IFunctionRoute, "path"> = {
type: `function`,
functionId: `ssr-engine`,
}
if (pageMode === `DSG`) {
commonFields.cache = true
}
addRoute({
path: htmlRoutePath,
...commonFields,
})
addRoute({
path: pageDataRoutePath,
...commonFields,
})
}
}
// static query json assets
for (const staticQueryComponent of state.staticQueryComponents.values()) {
const staticQueryResultPath = getStaticQueryPath(staticQueryComponent.hash)
addStaticRoute({
path: staticQueryResultPath,
pathToFillInPublicDir: staticQueryResultPath,
headers: MUST_REVALIDATE_HEADERS,
})
}
// app-data.json
{
const appDataFilePath = posix.join(`page-data`, `app-data.json`)
addStaticRoute({
path: appDataFilePath,
pathToFillInPublicDir: appDataFilePath,
headers: MUST_REVALIDATE_HEADERS,
})
}
// webpack assets
if (!webpackAssets) {
reporter.panic({
id: `12200`,
context: {},
})
}
for (const asset of webpackAssets) {
addStaticRoute({
path: asset,
pathToFillInPublicDir: asset,
headers: PERMAMENT_CACHING_HEADERS,
})
}
// chunk-map.json
{
const chunkMapFilePath = posix.join(`chunk-map.json`)
addStaticRoute({
path: chunkMapFilePath,
pathToFillInPublicDir: chunkMapFilePath,
headers: MUST_REVALIDATE_HEADERS,
})
}
// webpack.stats.json
{
const webpackStatsFilePath = posix.join(`webpack.stats.json`)
addStaticRoute({
path: webpackStatsFilePath,
pathToFillInPublicDir: webpackStatsFilePath,
headers: MUST_REVALIDATE_HEADERS,
})
}
for (const slice of state.slices.values()) {
const sliceDataPath = posix.join(`slice-data`, `${slice.name}.json`)
addStaticRoute({
path: sliceDataPath,
pathToFillInPublicDir: sliceDataPath,
headers: MUST_REVALIDATE_HEADERS,
})
}
function addSliceHtmlRoute(name: string, hasChildren: boolean): void {
const sliceHtml1Path = posix.join(`_gatsby`, `slices`, `${name}-1.html`)
addStaticRoute({
path: sliceHtml1Path,
pathToFillInPublicDir: sliceHtml1Path,
headers: MUST_REVALIDATE_HEADERS,
})
if (hasChildren) {
const sliceHtml2Path = posix.join(`_gatsby`, `slices`, `${name}-2.html`)
addStaticRoute({
path: sliceHtml2Path,
pathToFillInPublicDir: sliceHtml2Path,
headers: MUST_REVALIDATE_HEADERS,
})
}
}
addSliceHtmlRoute(`_gatsby-scripts`, false)
for (const [
name,
{ hasChildren },
] of state.html.slicesProps.bySliceId.entries()) {
addSliceHtmlRoute(name, hasChildren)
}
// redirect routes
for (const redirect of state.redirects.values()) {
addRoute({
path: redirect.fromPath,
type: `redirect`,
toPath: redirect.toPath,
status:
redirect.statusCode ??
(redirect.isPermanent
? HTTP_STATUS_CODE.MOVED_PERMANENTLY_301
: HTTP_STATUS_CODE.FOUND_302),
ignoreCase: redirect.ignoreCase,
headers: BASE_HEADERS,
})
}
// function routes
for (const functionInfo of state.functions.values()) {
addRoute({
path: `/api/${getRoutePathFromFunction(functionInfo)}`,
type: `function`,
functionId: functionInfo.functionId,
})
}
for (const fileAsset of fileAssets) {
// try to classify remaining assets
let headers: IHeader["headers"] | undefined = undefined
if (fileAsset.startsWith(`~partytown`)) {
// no hashes, must revalidate
headers = MUST_REVALIDATE_HEADERS
} else if (
fileAsset.startsWith(`_gatsby/image`) ||
fileAsset.startsWith(`_gatsby/file`)
) {
headers = PERMAMENT_CACHING_HEADERS
}
if (!headers) {
headers = BASE_HEADERS
}
addStaticRoute({
path: fileAsset,
pathToFillInPublicDir: fileAsset,
headers,
})
}
return (
routes
.sort((a, b) => {
// The higher the score, the higher the specificity of our path
const order = b.score - a.score
if (order !== 0) {
return order
}
// if specificity is the same we do lexigraphic comparison of path to ensure
// deterministic order regardless of order pages where created
return a.path.localeCompare(b.path)
})
// The score should be internal only, so we remove it from the final manifest
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.map(({ score, ...rest }): Route => {
return { ...rest }
})
)
}
function getFunctionsManifest(): FunctionsManifest {
const functions = [] as FunctionsManifest
for (const functionInfo of store.getState().functions.values()) {
const pathToEntryPoint = posix.join(
`.cache`,
`functions`,
functionInfo.relativeCompiledFilePath
)
const relativePathWithoutFileExtension = posix.join(
posix.parse(functionInfo.originalRelativeFilePath).dir,
posix.parse(functionInfo.originalRelativeFilePath).name
)
functions.push({
functionId: functionInfo.functionId,
name: `/api/${relativePathWithoutFileExtension}`,
pathToEntryPoint,
requiredFiles: [pathToEntryPoint],
})
}
if (shouldGenerateEngines()) {
function getFilesFrom(dir: string): Array<string> {
return globSync(`**/**`, {
cwd: posix.join(process.cwd(), dir),
nodir: true,
dot: true,
}).map(file => posix.join(dir, file))
}
functions.push({
functionId: `ssr-engine`,
pathToEntryPoint: posix.join(`.cache`, `page-ssr`, `lambda.js`),
name: `SSR & DSG`,
requiredFiles: [
`public/404.html`,
`public/500.html`,
...(shouldBundleDatastore()
? getFilesFrom(posix.join(`.cache`, `data`, `datastore`))
: []),
...getFilesFrom(posix.join(`.cache`, `page-ssr`)),
...getFilesFrom(posix.join(`.cache`, `query-engine`)),
],
})
}
return functions
}
export { getRoutesManifest, getFunctionsManifest }