-
-
Notifications
You must be signed in to change notification settings - Fork 331
/
getVikeConfig.ts
1335 lines (1250 loc) 路 49.4 KB
/
getVikeConfig.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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export { getVikeConfig }
export { reloadVikeConfig }
export { vikeConfigDependencies }
export { isVikeConfigFile }
export { isV1Design }
export type { VikeConfigObject }
export type { InterfaceValueFile }
import {
assertPosixPath,
assert,
isObject,
assertUsage,
assertWarning,
objectEntries,
hasProp,
arrayIncludes,
assertIsNotProductionRuntime,
getMostSimilar,
joinEnglish,
lowerFirst,
getOutDirs,
assertKeys,
objectKeys,
objectFromEntries,
makeFirst,
isNpmPackageImport,
reverse
} from '../../../utils.js'
import path from 'path'
import type {
PageConfigGlobalBuildTime,
ConfigEnvInternal,
ConfigValueSource,
ConfigValueSources,
PageConfigBuildTime,
ConfigValues,
DefinedAtFilePath,
DefinedAtFile,
ConfigValuesComputed
} from '../../../../../shared/page-configs/PageConfig.js'
import type { Config } from '../../../../../shared/page-configs/Config.js'
import {
configDefinitionsBuiltIn,
configDefinitionsBuiltInGlobal,
type ConfigDefinitions,
type ConfigDefinitionInternal,
type ConfigNameGlobal
} from './getVikeConfig/configDefinitionsBuiltIn.js'
import {
type LocationId,
getLocationId,
getFilesystemRouteString,
getFilesystemRouteDefinedBy,
isInherited,
sortAfterInheritanceOrder,
isGlobalLocation,
applyFilesystemRoutingRootEffect
} from './getVikeConfig/filesystemRouting.js'
import { isTemporaryBuildFile } from './getVikeConfig/transpileAndExecuteFile.js'
import { isConfigInvalid, isConfigInvalid_set } from '../../../../runtime/renderPage/isConfigInvalid.js'
import { getViteDevServer } from '../../../../runtime/globalContext.js'
import { logConfigError, logConfigErrorRecover } from '../../../shared/loggerNotProd.js'
import {
removeSuperfluousViteLog_enable,
removeSuperfluousViteLog_disable
} from '../../../shared/loggerVite/removeSuperfluousViteLog.js'
import pc from '@brillout/picocolors'
import { getConfigDefinedAt } from '../../../../../shared/page-configs/getConfigDefinedAt.js'
import type { ResolvedConfig } from 'vite'
import { assertConfigValueIsSerializable } from './getConfigValuesSerialized.js'
import { crawlPlusFiles } from './getVikeConfig/crawlPlusFiles.js'
import { getConfigFileExport } from './getConfigFileExport.js'
import {
type ConfigFile,
ImportedFilesLoaded,
loadConfigFile,
loadImportedFile,
loadValueFile
} from './getVikeConfig/loadFileAtConfigTime.js'
import { clearFilesEnvMap, resolvePointerImportOfConfig } from './getVikeConfig/resolvePointerImport.js'
import { getFilePathResolved } from '../../../shared/getFilePath.js'
import type { FilePathResolved } from '../../../../../shared/page-configs/FilePath.js'
assertIsNotProductionRuntime()
type InterfaceFile = InterfaceConfigFile | InterfaceValueFile
type InterfaceFileCommons = {
locationId: LocationId
filePath: FilePathResolved
fileExportsByConfigName: Record<ConfigName, { configValue?: unknown }>
}
// +config.js
type InterfaceConfigFile = InterfaceFileCommons & {
isConfigFile: true
isValueFile: false
extendsFilePaths: string[]
isConfigExtend: boolean
}
// +{configName}.js
type InterfaceValueFile = InterfaceFileCommons & {
isConfigFile: false
isValueFile: true
configName: string
}
type ConfigName = string
type InterfaceFilesByLocationId = Record<LocationId, InterfaceFile[]>
type VikeConfigObject = {
pageConfigs: PageConfigBuildTime[]
pageConfigGlobal: PageConfigGlobalBuildTime
globalVikeConfig: Record<string, unknown>
}
let devServerIsCorrupt = false
let wasConfigInvalid: boolean | null = null
let vikeConfigPromise: Promise<VikeConfigObject> | null = null
const vikeConfigDependencies: Set<string> = new Set()
function reloadVikeConfig(userRootDir: string, outDirRoot: string) {
vikeConfigDependencies.clear()
clearFilesEnvMap()
vikeConfigPromise = loadVikeConfig_withErrorHandling(userRootDir, outDirRoot, true, true)
handleReloadSideEffects()
}
async function handleReloadSideEffects() {
wasConfigInvalid = isConfigInvalid
const vikeConfigPromisePrevious = vikeConfigPromise
try {
await vikeConfigPromise
} catch (err) {
// handleReloadSideEffects() is only called in dev.
// In dev, if loadVikeConfig_withErrorHandling() throws an error, then it's a vike bug.
console.error(err)
assert(false)
}
if (vikeConfigPromise !== vikeConfigPromisePrevious) {
// Let the next handleReloadSideEffects() call handle side effects
return
}
if (!isConfigInvalid) {
if (wasConfigInvalid) {
wasConfigInvalid = false
logConfigErrorRecover()
}
if (devServerIsCorrupt) {
devServerIsCorrupt = false
const viteDevServer = getViteDevServer()
assert(viteDevServer)
removeSuperfluousViteLog_enable()
await viteDevServer.restart(true)
removeSuperfluousViteLog_disable()
}
}
}
async function getVikeConfig(
config: ResolvedConfig,
isDev: boolean,
tolerateInvalidConfig?: true
): Promise<VikeConfigObject> {
const { outDirRoot } = getOutDirs(config)
const userRootDir = config.root
if (!vikeConfigPromise) {
vikeConfigPromise = loadVikeConfig_withErrorHandling(userRootDir, outDirRoot, isDev, tolerateInvalidConfig)
}
return await vikeConfigPromise
}
async function isV1Design(config: ResolvedConfig, isDev: boolean): Promise<boolean> {
const vikeConfig = await getVikeConfig(config, isDev)
const { pageConfigs } = vikeConfig
const isV1Design = pageConfigs.length > 0
return isV1Design
}
async function loadInterfaceFiles(
userRootDir: string,
outDirRoot: string,
isDev: boolean
): Promise<InterfaceFilesByLocationId> {
const plusFiles = await findPlusFiles(userRootDir, outDirRoot, isDev)
const configFiles: FilePathResolved[] = []
const valueFiles: FilePathResolved[] = []
plusFiles.forEach((f) => {
if (getConfigName(f.filePathAbsoluteFilesystem) === 'config') {
configFiles.push(f)
} else {
valueFiles.push(f)
}
})
let interfaceFilesByLocationId: InterfaceFilesByLocationId = {}
await Promise.all([
// Config files
...configFiles.map(async (filePath) => {
const { filePathAbsoluteUserRootDir } = filePath
assert(filePathAbsoluteUserRootDir)
const { configFile, extendsConfigs } = await loadConfigFile(filePath, userRootDir, [], false)
assert(filePath.filePathAbsoluteUserRootDir)
const locationId = getLocationId(filePathAbsoluteUserRootDir)
const interfaceFile = getInterfaceFileFromConfigFile(configFile, false, locationId)
interfaceFilesByLocationId[locationId] = interfaceFilesByLocationId[locationId] ?? []
interfaceFilesByLocationId[locationId]!.push(interfaceFile)
extendsConfigs.forEach((extendsConfig) => {
/* We purposely use the same locationId because the Vike extension's config should only apply to where it's being extended from, for example:
```js
// /pages/admin/+config.js
import vikeVue from 'vike-vue/config'
// Should only apply to /pages/admin/**
export default { extends: [vikeVue] }
```
```js
// /pages/marketing/+config.js
import vikeReact from 'vike-react/config'
// Should only apply to /pages/marketing/**
export default { extends: [vikeReact] }
```
*/
const interfaceFile = getInterfaceFileFromConfigFile(extendsConfig, true, locationId)
{
const alreadyMigrated = [
'vike-react',
'vike-react-query',
'vike-react-zustand',
'vike-vue',
'vike-pinia',
'vike-solid'
]
assert(extendsConfig.filePath.importPathAbsolute)
const extensionName = extendsConfig.filePath.importPathAbsolute.split('/')[0]!
const warnMsg = alreadyMigrated.includes(extensionName)
? `You're using a deprecated version of the Vike extension ${extensionName}, update ${extensionName} to its latest version.`
: `The config of the Vike extension ${extensionName} should set a ${pc.cyan('name')} value`
const isNameDefined = interfaceFile.fileExportsByConfigName.name?.configValue
if (alreadyMigrated) {
// Eventually always make it a assertUsage()
assertWarning(isNameDefined, warnMsg, { onlyOnce: true })
} else {
assertUsage(isNameDefined, warnMsg)
}
}
interfaceFilesByLocationId[locationId]!.push(interfaceFile)
})
}),
// Value files
...valueFiles.map(async (filePath) => {
const { filePathAbsoluteUserRootDir } = filePath
assert(filePathAbsoluteUserRootDir)
const configName = getConfigName(filePathAbsoluteUserRootDir)
assert(configName)
const locationId = getLocationId(filePathAbsoluteUserRootDir)
const interfaceFile: InterfaceValueFile = {
locationId,
filePath,
fileExportsByConfigName: {
[configName]: {}
},
isConfigFile: false,
isValueFile: true,
configName
}
{
// We don't have access to the custom config definitions defined by the user yet.
// - If `configDef` is `undefined` => we load the file +{configName}.js later.
// - We already need to load +meta.js here (to get the custom config definitions defined by the user)
const configDef = getConfigDefinitionOptional(configDefinitionsBuiltIn, configName)
if (configDef && isConfigEnv(configDef, configName)) {
await loadValueFile(interfaceFile, configName, userRootDir)
}
}
{
interfaceFilesByLocationId[locationId] = interfaceFilesByLocationId[locationId] ?? []
interfaceFilesByLocationId[locationId]!.push(interfaceFile)
}
})
])
assertAllConfigsAreKnown(interfaceFilesByLocationId)
return interfaceFilesByLocationId
}
function getInterfaceFileFromConfigFile(
configFile: ConfigFile,
isConfigExtend: boolean,
locationId: LocationId
): InterfaceFile {
const { fileExports, filePath, extendsFilePaths } = configFile
const interfaceFile: InterfaceConfigFile = {
locationId,
filePath,
fileExportsByConfigName: {},
isConfigFile: true,
isValueFile: false,
isConfigExtend,
extendsFilePaths
}
const fileExport = getConfigFileExport(fileExports, filePath.filePathToShowToUser)
Object.entries(fileExport).forEach(([configName, configValue]) => {
interfaceFile.fileExportsByConfigName[configName] = { configValue }
})
return interfaceFile
}
/** Show error message upon unknown config */
function assertAllConfigsAreKnown(interfaceFilesByLocationId: InterfaceFilesByLocationId) {
objectEntries(interfaceFilesByLocationId).forEach(([locationId, interfaceFiles]) => {
const interfaceFilesRelevant = getInterfaceFilesRelevant(interfaceFilesByLocationId, locationId)
const configDefinitions = getConfigDefinitions(interfaceFilesRelevant)
interfaceFiles.forEach((interfaceFile) => {
Object.keys(interfaceFile.fileExportsByConfigName).forEach((configName) => {
assertConfigExists(configName, Object.keys(configDefinitions), interfaceFile.filePath.filePathToShowToUser)
})
})
})
}
async function loadVikeConfig_withErrorHandling(
userRootDir: string,
outDirRoot: string,
isDev: boolean,
tolerateInvalidConfig?: boolean
): Promise<VikeConfigObject> {
let hasError = false
let ret: VikeConfigObject | undefined
let err: unknown
try {
ret = await loadVikeConfig(userRootDir, outDirRoot, isDev)
} catch (err_) {
hasError = true
err = err_
}
if (!hasError) {
assert(ret)
assert(err === undefined)
isConfigInvalid_set(false)
return ret
} else {
assert(ret === undefined)
assert(err)
isConfigInvalid_set(true)
if (!isDev) {
assert(getViteDevServer() === null)
throw err
} else {
logConfigError(err)
if (!tolerateInvalidConfig) {
devServerIsCorrupt = true
}
const dummyData: VikeConfigObject = {
pageConfigs: [],
pageConfigGlobal: {
configValueSources: {}
},
globalVikeConfig: {}
}
return dummyData
}
}
}
async function loadVikeConfig(userRootDir: string, outDirRoot: string, isDev: boolean): Promise<VikeConfigObject> {
const interfaceFilesByLocationId = await loadInterfaceFiles(userRootDir, outDirRoot, isDev)
const importedFilesLoaded: ImportedFilesLoaded = {}
const { globalVikeConfig, pageConfigGlobal } = await getGlobalConfigs(
interfaceFilesByLocationId,
userRootDir,
importedFilesLoaded
)
const pageConfigs: PageConfigBuildTime[] = await Promise.all(
objectEntries(interfaceFilesByLocationId)
.filter(([_pageId, interfaceFiles]) => isDefiningPage(interfaceFiles))
.map(async ([locationId]) => {
const interfaceFilesRelevant = getInterfaceFilesRelevant(interfaceFilesByLocationId, locationId)
const configDefinitions = getConfigDefinitions(interfaceFilesRelevant)
// Load value files of custom config-only configs
await Promise.all(
getInterfaceFileList(interfaceFilesRelevant).map(async (interfaceFile) => {
if (!interfaceFile.isValueFile) return
const { configName } = interfaceFile
if (isGlobalConfig(configName)) return
const configDef = getConfigDefinition(
configDefinitions,
configName,
interfaceFile.filePath.filePathToShowToUser
)
if (!isConfigEnv(configDef, configName)) return
const isAlreadyLoaded = interfacefileIsAlreaydLoaded(interfaceFile)
if (isAlreadyLoaded) return
// Value files of built-in configs should have already been loaded at loadInterfaceFiles()
assert(!(configName in configDefinitionsBuiltIn))
await loadValueFile(interfaceFile, configName, userRootDir)
})
)
let configValueSources: ConfigValueSources = {}
await Promise.all(
objectEntries(configDefinitions)
.filter(([configName]) => !isGlobalConfig(configName))
.map(async ([configName, configDef]) => {
const sources = await resolveConfigValueSources(
configName,
configDef,
interfaceFilesRelevant,
userRootDir,
importedFilesLoaded
)
if (sources.length === 0) return
configValueSources[configName] = sources
})
)
configValueSources = sortConfigValueSources(configValueSources, locationId)
const { routeFilesystem, isErrorPage } = determineRouteFilesystem(locationId, configValueSources)
applyEffectsAll(configValueSources, configDefinitions)
const configValuesComputed = getComputed(configValueSources, configDefinitions)
const configValues = getConfigValues(configValueSources, configValuesComputed, configDefinitions)
const pageConfig: PageConfigBuildTime = {
pageId: locationId,
isErrorPage,
routeFilesystem,
configValueSources,
configValuesComputed,
configValues
}
return pageConfig
})
)
assertPageConfigs(pageConfigs)
return { pageConfigs, pageConfigGlobal, globalVikeConfig }
}
function deriveConfigEnvFromFileName(env: ConfigEnvInternal, fileName: string) {
env = { ...env }
if (fileName.includes('.server.')) {
env.server = true
env.client = false
} else if (fileName.includes('.client.')) {
env.client = true
env.server = false
} else if (fileName.includes('.shared.')) {
env.server = true
env.client = true
}
return env
}
function assertPageConfigs(pageConfigs: PageConfigBuildTime[]) {
pageConfigs.forEach((pageConfig) => {
assertOnBeforeRenderEnv(pageConfig)
})
}
function assertOnBeforeRenderEnv(pageConfig: PageConfigBuildTime) {
const onBeforeRenderConfig = pageConfig.configValueSources.onBeforeRender?.[0]
if (!onBeforeRenderConfig) return
const onBeforeRenderEnv = onBeforeRenderConfig.configEnv
const isClientRouting = !!pageConfig.configValues.clientRouting?.value
// When using Server Routing, loading a onBeforeRender() hook on the client-side hasn't any effect (the Server Routing's client runtime never calls it); it unnecessarily bloats client bundle sizes
assertUsage(
!(onBeforeRenderEnv.client && !isClientRouting),
`Page ${pageConfig.pageId} has an onBeforeRender() hook with env ${pc.cyan(
JSON.stringify(onBeforeRenderEnv)
)} which doesn't make sense because the page is using Server Routing: onBeforeRender() can be run in the client only when using Client Routing.`
)
}
function interfacefileIsAlreaydLoaded(interfaceFile: InterfaceFile): boolean {
const configMapValues = Object.values(interfaceFile.fileExportsByConfigName)
const isAlreadyLoaded = configMapValues.some((conf) => 'configValue' in conf)
if (isAlreadyLoaded) {
assert(configMapValues.every((conf) => 'configValue' in conf))
}
return isAlreadyLoaded
}
function getInterfaceFilesRelevant(
interfaceFilesByLocationId: InterfaceFilesByLocationId,
locationIdPage: LocationId
): InterfaceFilesByLocationId {
const interfaceFilesRelevant = Object.fromEntries(
objectEntries(interfaceFilesByLocationId)
.filter(([locationId]) => {
return isInherited(locationId, locationIdPage)
})
.sort(([locationId1], [locationId2]) => sortAfterInheritanceOrder(locationId1, locationId2, locationIdPage))
)
return interfaceFilesRelevant
}
function getInterfaceFileList(interfaceFilesByLocationId: InterfaceFilesByLocationId): InterfaceFile[] {
const interfaceFiles: InterfaceFile[] = []
Object.values(interfaceFilesByLocationId).forEach((interfaceFiles_) => {
interfaceFiles.push(...interfaceFiles_)
})
return interfaceFiles
}
async function getGlobalConfigs(
interfaceFilesByLocationId: InterfaceFilesByLocationId,
userRootDir: string,
importedFilesLoaded: ImportedFilesLoaded
) {
const locationIds = objectKeys(interfaceFilesByLocationId)
const interfaceFilesGlobal = objectFromEntries(
objectEntries(interfaceFilesByLocationId).filter(([locationId]) => {
return isGlobalLocation(locationId, locationIds)
})
)
// Validate that global configs live in global interface files
{
const interfaceFilesGlobalPaths: string[] = []
objectEntries(interfaceFilesGlobal).forEach(([locationId, interfaceFiles]) => {
assert(isGlobalLocation(locationId, locationIds))
interfaceFiles.forEach(({ filePath: { filePathAbsoluteUserRootDir } }) => {
if (filePathAbsoluteUserRootDir) {
interfaceFilesGlobalPaths.push(filePathAbsoluteUserRootDir)
}
})
})
const globalPaths = Array.from(new Set(interfaceFilesGlobalPaths.map((p) => path.posix.dirname(p))))
objectEntries(interfaceFilesByLocationId).forEach(([locationId, interfaceFiles]) => {
interfaceFiles.forEach((interfaceFile) => {
Object.keys(interfaceFile.fileExportsByConfigName).forEach((configName) => {
if (!isGlobalLocation(locationId, locationIds) && isGlobalConfig(configName)) {
assertUsage(
false,
[
`${interfaceFile.filePath.filePathToShowToUser} defines the config ${pc.cyan(
configName
)} which is global:`,
globalPaths.length
? `define ${pc.cyan(configName)} in ${joinEnglish(globalPaths, 'or')} instead`
: `create a global config (e.g. /pages/+config.js) and define ${pc.cyan(configName)} there instead`
].join(' ')
)
}
})
})
})
}
const globalVikeConfig: Record<string, unknown> = {}
const pageConfigGlobal: PageConfigGlobalBuildTime = {
configValueSources: {}
}
await Promise.all(
objectEntries(configDefinitionsBuiltInGlobal).map(async ([configName, configDef]) => {
const sources = await resolveConfigValueSources(
configName,
configDef,
interfaceFilesGlobal,
userRootDir,
importedFilesLoaded
)
const configValueSource = sources[0]
if (!configValueSource) return
if (configName === 'onBeforeRoute' || configName === 'onPrerenderStart') {
assert(!('value' in configValueSource))
pageConfigGlobal.configValueSources[configName] = [configValueSource]
} else {
assert('value' in configValueSource)
if (configName === 'prerender' && typeof configValueSource.value === 'boolean') return
const { filePathToShowToUser } = configValueSource.definedAtFilePath
assertWarning(
false,
`Being able to define config ${pc.cyan(
configName
)} in ${filePathToShowToUser} is experimental and will likely be removed. Define the config ${pc.cyan(
configName
)} in Vike's Vite plugin options instead.`,
{ onlyOnce: true }
)
globalVikeConfig[configName] = configValueSource.value
}
})
)
return { pageConfigGlobal, globalVikeConfig }
}
async function resolveConfigValueSources(
configName: string,
configDef: ConfigDefinitionInternal,
interfaceFilesRelevant: InterfaceFilesByLocationId,
userRootDir: string,
importedFilesLoaded: ImportedFilesLoaded
): Promise<ConfigValueSource[]> {
const sourcesInfo: Parameters<typeof getConfigValueSource>[] = []
// interfaceFilesRelevant is sorted by sortAfterInheritanceOrder()
for (const interfaceFiles of Object.values(interfaceFilesRelevant)) {
const interfaceFilesDefiningConfig = interfaceFiles.filter(
(interfaceFile) => interfaceFile.fileExportsByConfigName[configName]
)
if (interfaceFilesDefiningConfig.length === 0) continue
const visited = new WeakSet<InterfaceFile>()
const add = (interfaceFile: InterfaceFile) => {
assert(!visited.has(interfaceFile))
visited.add(interfaceFile)
sourcesInfo.push([configName, interfaceFile, configDef, userRootDir, importedFilesLoaded])
}
// Main resolution logic
{
const interfaceValueFiles = interfaceFilesDefiningConfig
.filter(
(interfaceFile) =>
interfaceFile.isValueFile &&
// We consider side-effect configs (e.g. `export { frontmatter }` of .mdx files) later (i.e. with less priority)
interfaceFile.configName === configName
)
.sort(makeOrderDeterministic)
const interfaceConfigFiles = interfaceFilesDefiningConfig
.filter(
(interfaceFile) =>
interfaceFile.isConfigFile &&
// We consider value from extended configs (e.g. vike-react) later (i.e. with less priority)
!interfaceFile.isConfigExtend
)
.sort(makeOrderDeterministic)
const interfaceValueFile = interfaceValueFiles[0]
const interfaceConfigFile = interfaceConfigFiles[0]
// Make this value:
// /pages/some-page/+{configName}.js > `export default`
// override that value:
// /pages/some-page/+config.js > `export default { someConfig }`
const interfaceFileWinner = interfaceValueFile ?? interfaceConfigFile
if (interfaceFileWinner) {
const interfaceFilesOverriden = [...interfaceValueFiles, ...interfaceConfigFiles].filter(
(f) => f !== interfaceFileWinner
)
// A user-land conflict of interfaceFiles with the same locationId means that the user has superfluously defined the config twice; the user should remove such redundancy making things unnecessarily ambiguous
warnOverridenConfigValues(interfaceFileWinner, interfaceFilesOverriden, configName)
;[interfaceFileWinner, ...interfaceFilesOverriden].forEach((interfaceFile) => {
add(interfaceFile)
})
}
}
// Side-effect configs such as `export { frontmatter }` in .mdx files
interfaceFilesDefiningConfig
.filter(
(interfaceFile) =>
interfaceFile.isValueFile &&
// Is side-effect config
interfaceFile.configName !== configName
)
.forEach((interfaceValueFileSideEffect) => {
add(interfaceValueFileSideEffect)
})
// extends
interfaceFilesDefiningConfig
.filter((interfaceFile) => interfaceFile.isConfigFile && interfaceFile.isConfigExtend)
// extended config files are already sorted by inheritance order
.forEach((interfaceFile) => {
add(interfaceFile)
})
interfaceFilesDefiningConfig.forEach((interfaceFile) => {
assert(visited.has(interfaceFile))
})
}
const sources: ConfigValueSource[] = await Promise.all(
sourcesInfo.map(async (args) => await getConfigValueSource(...args))
)
return sources
}
function makeOrderDeterministic(interfaceFile1: InterfaceFile, interfaceFile2: InterfaceFile): 0 | -1 | 1 {
return lowerFirst<InterfaceFile>((interfaceFile) => {
const { filePathAbsoluteUserRootDir } = interfaceFile.filePath
assert(isInterfaceFileUserLand(interfaceFile))
assert(filePathAbsoluteUserRootDir)
return filePathAbsoluteUserRootDir.length
})(interfaceFile1, interfaceFile2)
}
function warnOverridenConfigValues(
interfaceFileWinner: InterfaceFile,
interfaceFilesOverriden: InterfaceFile[],
configName: string
) {
interfaceFilesOverriden.forEach((interfaceFileLoser) => {
const loserFilePath = interfaceFileLoser.filePath.filePathToShowToUser
const winnerFilePath = interfaceFileWinner.filePath.filePathToShowToUser
const confName = pc.cyan(configName)
assertWarning(
false,
`The value of the config ${confName} defined at ${loserFilePath} is always overwritten by the value defined at ${winnerFilePath}, remove the superfluous value defined at ${loserFilePath}`,
{ onlyOnce: true }
)
})
}
function isInterfaceFileUserLand(interfaceFile: InterfaceFile) {
return (interfaceFile.isConfigFile && !interfaceFile.isConfigExtend) || interfaceFile.isValueFile
}
async function getConfigValueSource(
configName: string,
interfaceFile: InterfaceFile,
configDef: ConfigDefinitionInternal,
userRootDir: string,
importedFilesLoaded: ImportedFilesLoaded
): Promise<ConfigValueSource> {
const conf = interfaceFile.fileExportsByConfigName[configName]
assert(conf)
const configEnv = deriveConfigEnvFromFileName(configDef.env, interfaceFile.filePath.fileName)
const { locationId } = interfaceFile
const definedAtFilePath_: DefinedAtFilePath = {
...interfaceFile.filePath,
fileExportPathToShowToUser: ['default', configName]
}
// +client.js
if (configDef._valueIsFilePath) {
let definedAtFilePath: DefinedAtFilePath
let valueFilePath: string
if (interfaceFile.isConfigFile) {
const { configValue } = conf
const pointerImport = resolvePointerImportOfConfig(
configValue,
interfaceFile.filePath,
userRootDir,
configEnv,
configName
)
const configDefinedAt = getConfigDefinedAt('Config', configName, definedAtFilePath_)
assertUsage(pointerImport, `${configDefinedAt} should be an import`)
valueFilePath = pointerImport.filePathAbsoluteVite
definedAtFilePath = pointerImport
} else {
assert(interfaceFile.isValueFile)
valueFilePath = interfaceFile.filePath.filePathAbsoluteVite
definedAtFilePath = {
...interfaceFile.filePath,
fileExportPathToShowToUser: []
}
}
const configValueSource: ConfigValueSource = {
locationId,
value: valueFilePath,
valueIsFilePath: true,
configEnv,
valueIsImportedAtRuntime: true,
valueIsDefinedByValueFile: false,
definedAtFilePath
}
return configValueSource
}
// +config.js
if (interfaceFile.isConfigFile) {
assert('configValue' in conf)
const { configValue } = conf
// Pointer import
const pointerImport = resolvePointerImportOfConfig(
configValue,
interfaceFile.filePath,
userRootDir,
configEnv,
configName
)
if (pointerImport) {
const configValueSource: ConfigValueSource = {
locationId,
configEnv,
valueIsImportedAtRuntime: true,
valueIsDefinedByValueFile: false,
definedAtFilePath: pointerImport
}
// Load fake import
if (
isConfigEnv(configDef, configName) &&
// The value of `extends` was already loaded and already used: we don't need the value of `extends` anymore
configName !== 'extends'
) {
if (pointerImport.filePathAbsoluteFilesystem) {
const fileExport = await loadImportedFile(pointerImport, userRootDir, importedFilesLoaded)
configValueSource.value = fileExport
} else {
const configDefinedAt = getConfigDefinedAt('Config', configName, configValueSource.definedAtFilePath)
assertUsage(!configDef.cumulative, `${configDefinedAt} cannot be defined over an aliased import`)
}
}
return configValueSource
}
// Defined by config file, i.e. +config.js file
const configValueSource: ConfigValueSource = {
locationId,
value: configValue,
configEnv,
valueIsImportedAtRuntime: false,
valueIsDefinedByValueFile: false,
definedAtFilePath: definedAtFilePath_
}
return configValueSource
}
// Defined by value file, i.e. +{configName}.js
if (interfaceFile.isValueFile) {
const valueAlreadyLoaded = 'configValue' in conf
assert(valueAlreadyLoaded === !!configEnv.config)
const configValueSource: ConfigValueSource = {
locationId,
configEnv,
valueIsImportedAtRuntime: !valueAlreadyLoaded,
valueIsDefinedByValueFile: true,
definedAtFilePath: {
...interfaceFile.filePath,
fileExportPathToShowToUser:
configName === interfaceFile.configName
? []
: // Side-effect config (e.g. `export { frontmatter }` of .md files)
[configName]
}
}
if (valueAlreadyLoaded) {
configValueSource.value = conf.configValue
}
return configValueSource
}
assert(false)
}
function isDefiningPage(interfaceFiles: InterfaceFile[]): boolean {
for (const interfaceFile of interfaceFiles) {
const configNames = Object.keys(interfaceFile.fileExportsByConfigName)
if (configNames.some((configName) => isDefiningPageConfig(configName))) {
return true
}
}
return false
}
function isDefiningPageConfig(configName: string): boolean {
return ['Page', 'route'].includes(configName)
}
function getConfigDefinitions(interfaceFilesRelevant: InterfaceFilesByLocationId): ConfigDefinitions {
const configDefinitionsMerged: ConfigDefinitions = { ...configDefinitionsBuiltIn }
Object.entries(interfaceFilesRelevant)
.reverse()
.forEach(([_locationId, interfaceFiles]) => {
interfaceFiles.forEach((interfaceFile) => {
const configMeta = interfaceFile.fileExportsByConfigName['meta']
if (!configMeta) return
const meta = configMeta.configValue
assertMetaValue(meta, `Config ${pc.cyan('meta')} defined at ${interfaceFile.filePath.filePathToShowToUser}`)
// Set configDef._userEffectDefinedAtFilePath
Object.entries(meta).forEach(([configName, configDef]) => {
if (!configDef.effect) return
assert(interfaceFile.isConfigFile)
configDef._userEffectDefinedAtFilePath = {
...interfaceFile.filePath,
fileExportPathToShowToUser: ['default', 'meta', configName, 'effect']
}
})
objectEntries(meta).forEach(([configName, configDefinition]) => {
// User can override an existing config definition
configDefinitionsMerged[configName] = {
...configDefinitionsMerged[configName],
...configDefinition
}
})
})
})
const configDefinitions = configDefinitionsMerged
return configDefinitions
}
function assertMetaValue(
metaVal: unknown,
metaConfigDefinedAt: `Config meta${string}` | null
): asserts metaVal is ConfigDefinitions {
if (!isObject(metaVal)) {
assert(metaConfigDefinedAt) // We expect internal effects to return a valid meta value
assertUsage(
false,
`${metaConfigDefinedAt} has an invalid type ${pc.cyan(typeof metaVal)}: it should be an object instead.`
)
}
objectEntries(metaVal).forEach(([configName, def]) => {
if (!isObject(def)) {
assert(metaConfigDefinedAt) // We expect internal effects to return a valid meta value
assertUsage(
false,
`${metaConfigDefinedAt} sets ${pc.cyan(`meta.${configName}`)} to a value with an invalid type ${pc.cyan(
typeof def
)}: it should be an object instead.`
)
}
// env
let configEnv: ConfigEnvInternal
{
assert(metaConfigDefinedAt) // We expect internal effects to return a valid meta value
if (!('env' in def)) {
assertUsage(false, `${metaConfigDefinedAt} doesn't set ${pc.cyan(`meta.${configName}.env`)} but it's required.`)
}
configEnv = getConfigEnvValue(def.env, `${metaConfigDefinedAt} sets ${pc.cyan(`meta.${configName}.env`)} to`)
// Overwrite deprecated value with valid value
// TODO/v1-release: remove once support for the deprecated values is removed
if (typeof def.env === 'string') def.env = configEnv
}
// effect
if ('effect' in def) {
if (!hasProp(def, 'effect', 'function')) {
assert(metaConfigDefinedAt) // We expect internal effects to return a valid meta value
assertUsage(
false,
`${metaConfigDefinedAt} sets ${pc.cyan(`meta.${configName}.effect`)} to an invalid type ${pc.cyan(
typeof def.effect
)}: it should be a function instead`
)
}
if (!configEnv.config) {
assert(metaConfigDefinedAt) // We expect internal effects to return a valid meta value
assertUsage(
false,
`${metaConfigDefinedAt} sets ${pc.cyan(
`meta.${configName}.effect`
)} but it's only supported if meta.${configName}.env has ${pc.cyan('{ config: true }')} (but it's ${pc.cyan(
JSON.stringify(configEnv)
)} instead)`
)
}
}
})
}
function applyEffectsAll(configValueSources: ConfigValueSources, configDefinitions: ConfigDefinitions) {
objectEntries(configDefinitions).forEach(([configName, configDef]) => {
if (!configDef.effect) return
// The value needs to be loaded at config time, that's why we only support effect for configs that are config-only for now.
// (We could support effect for non config-only by always loading its value at config time, regardless of the config's `env` value.)
assertUsage(
configDef.env.config,
[
`Cannot add effect to ${pc.cyan(configName)} because its ${pc.cyan('env')} is ${pc.cyan(
JSON.stringify(configDef.env)
)}: effects can only be added to configs with an ${pc.cyan('env')} with ${pc.cyan('{ config: true }')}.`
].join(' ')
)
const source = configValueSources[configName]?.[0]
if (!source) return
// The config value is eagerly loaded since `configDef.env === 'config-only``
assert('value' in source)
// Call effect
const configModFromEffect = configDef.effect({
configValue: source.value,
configDefinedAt: getConfigDefinedAt('Config', configName, source.definedAtFilePath)
})
if (!configModFromEffect) return
assert(hasProp(source, 'value')) // We need to assume that the config value is loaded at build-time
applyEffect(configModFromEffect, configValueSources, configDef)
})
}
function applyEffect(
configModFromEffect: Config,
configValueSources: ConfigValueSources,
configDefEffect: ConfigDefinitionInternal
) {
const notSupported = `Effects currently only supports modifying the the ${pc.cyan('env')} of a config.` as const
objectEntries(configModFromEffect).forEach(([configName, configValue]) => {
if (configName === 'meta') {
let configDefinedAt: Parameters<typeof assertMetaValue>[1]
if (configDefEffect._userEffectDefinedAtFilePath) {
configDefinedAt = getConfigDefinedAt('Config', configName, configDefEffect._userEffectDefinedAtFilePath)
} else {
configDefinedAt = null
}
assertMetaValue(configValue, configDefinedAt)
objectEntries(configValue).forEach(([configTargetName, configTargetDef]) => {
{
const keys = Object.keys(configTargetDef)
assertUsage(keys.includes('env'), notSupported)
assertUsage(keys.length === 1, notSupported)
}