-
Notifications
You must be signed in to change notification settings - Fork 201
/
index.ts
232 lines (204 loc) · 7.52 KB
/
index.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
import type { E } from '@contentlayer/utils/effect'
import { Array, Chunk, O, OT, pipe, S, T } from '@contentlayer/utils/effect'
import type { GetContentlayerVersionError } from '@contentlayer/utils/node'
import { fs } from '@contentlayer/utils/node'
import * as path from 'node:path'
import type { HasCwd } from '../cwd.js'
import { getCwd } from '../cwd.js'
import type { EsbuildBinNotFoundError } from '../errors.js'
import { ConfigNoDefaultExportError, ConfigReadError, NoConfigFoundError } from '../errors.js'
import { ArtifactsDir } from '../index.js'
import type { SourcePlugin } from '../plugin.js'
import * as esbuild from './esbuild.js'
type GetConfigError =
| esbuild.EsbuildError
| NoConfigFoundError
| fs.StatError
| fs.UnknownFSError
| fs.MkdirError
| EsbuildBinNotFoundError
| ConfigReadError
| ConfigNoDefaultExportError
| GetContentlayerVersionError
export type Config = {
source: SourcePlugin
esbuildHash: string
}
export const getConfig = ({
configPath,
}: {
configPath?: string
}): T.Effect<OT.HasTracer & HasCwd, GetConfigError, Config> =>
pipe(
getConfigWatch({ configPath }),
S.take(1),
S.runCollect,
T.map(Chunk.unsafeHead),
T.rightOrFail,
OT.withSpan('@contentlayer/core/getConfig:getConfig', { attributes: { configPath } }),
)
export const getConfigWatch = ({
configPath: configPath_,
}: {
configPath?: string
}): S.Stream<OT.HasTracer & HasCwd, never, E.Either<GetConfigError, Config>> => {
const resolveParams = pipe(
T.structPar({ configPath: resolveConfigPath({ configPath: configPath_ }), cwd: getCwd }),
T.chainMergeObject(() => makeTmpDirAndResolveEntryPoint),
T.either,
)
return pipe(
S.fromEffect(resolveParams),
S.chainMapEitherRight(({ configPath, outfilePath, cwd }) =>
pipe(
esbuild.makeAndSubscribe({
entryPoints: [configPath],
entryNames: '[name]-[hash]',
outfile: outfilePath,
sourcemap: true,
platform: 'node',
target: 'es2020',
format: 'esm',
// needed in case models are co-located with React components
jsx: 'transform',
bundle: true,
logLevel: 'silent',
metafile: true,
absWorkingDir: cwd,
plugins: [contentlayerGenPlugin(), makeAllPackagesExternalPlugin(configPath)],
}),
S.mapEffectEitherRight((result) => getConfigFromResult({ result, configPath })),
),
),
)
}
const resolveConfigPath = ({
configPath,
}: {
configPath?: string
}): T.Effect<HasCwd & OT.HasTracer, NoConfigFoundError | fs.StatError, string> =>
T.gen(function* ($) {
const cwd = yield* $(getCwd)
if (configPath) {
if (path.isAbsolute(configPath)) {
return configPath
}
return path.join(cwd, configPath)
}
const defaultFilePaths = [path.join(cwd, 'contentlayer.config.ts'), path.join(cwd, 'contentlayer.config.js')]
const foundDefaultFiles = yield* $(pipe(defaultFilePaths, T.forEachPar(fs.fileOrDirExists), T.map(Chunk.toArray)))
const foundDefaultFile = defaultFilePaths[foundDefaultFiles.findIndex((_) => _)]
if (foundDefaultFile) {
return foundDefaultFile
}
return yield* $(T.fail(new NoConfigFoundError({ cwd, configPath })))
})
const makeTmpDirAndResolveEntryPoint = pipe(
ArtifactsDir.mkdirCache,
T.map((cacheDir) => ({ outfilePath: path.join(cacheDir, 'compiled-contentlayer-config.mjs') })),
)
const getConfigFromResult = ({
result,
configPath,
}: {
result: esbuild.BuildResult
/** configPath only needed for error message */
configPath: string
}): T.Effect<OT.HasTracer & HasCwd, never, E.Either<ConfigReadError | ConfigNoDefaultExportError, Config>> =>
pipe(
T.gen(function* ($) {
const unknownWarnings = result.warnings.filter(
(warning) =>
warning.text.match(
/Import \".*\" will always be undefined because the file \"contentlayer-gen:.contentlayer\/(data|types)\" has no exports/,
) === null,
)
if (unknownWarnings.length > 0) {
console.error(`Contentlayer esbuild warnings:`)
console.error(unknownWarnings)
}
const cwd = yield* $(getCwd)
// Deriving the exact outfilePath here since it's suffixed with a hash
const outfilePath = pipe(
Object.keys(result.metafile!.outputs),
// Will look like `path.join(cacheDir, 'compiled-contentlayer-config-[SOME_HASH].mjs')
Array.find((_) => _.match(/compiled-contentlayer-config-.+.mjs$/) !== null),
// Needs to be absolute path for ESM import to work
O.map((_) => path.join(cwd, _)),
O.getUnsafe,
)
const esbuildHash = outfilePath.match(/compiled-contentlayer-config-(.+).mjs$/)![1]!
// TODO make a simple OT call via `addAttributes`
yield* $(OT.addAttribute('outfilePath', outfilePath))
yield* $(OT.addAttribute('esbuildHash', esbuildHash))
// Needed in order for source maps of dynamic file to work
yield* $(
pipe(
T.tryCatchPromise(
async () => (await import('source-map-support')).install(),
(error) => new ConfigReadError({ error, configPath }),
),
OT.withSpan('load-source-map-support'),
),
)
// NOTES:
// 1) `?x=` suffix needed in case of re-loading when watching the config file for changes
// 2) `file://` prefix is needed for Windows to work properly
const importFresh = async (modulePath: string) => import(`file://${modulePath}?x=${new Date()}`)
const exports = yield* $(
pipe(
T.tryCatchPromise(
() => importFresh(outfilePath),
(error) => new ConfigReadError({ error, configPath }),
),
OT.withSpan('import-compiled-contentlayer-config'),
),
)
if (!('default' in exports)) {
return yield* $(T.fail(new ConfigNoDefaultExportError({ configPath, availableExports: Object.keys(exports) })))
}
// Note currently `makeSource` returns a Promise but we should reconsider that design decision
const source: SourcePlugin = yield* $(
pipe(
T.tryCatchPromise(
async () => exports.default,
(error) => new ConfigReadError({ error, configPath }),
),
OT.withSpan('resolve-source-plugin-promise'),
),
)
return { source, esbuildHash }
}),
OT.withSpan('@contentlayer/core/getConfig:getConfigFromResult', { attributes: { configPath } }),
T.either,
)
/**
* This esbuild plugin is needed in some cases where users import code that imports from '.contentlayer/*'
* (e.g. when co-locating document type definitions with React components).
*/
const contentlayerGenPlugin = (): esbuild.Plugin => ({
name: 'contentlayer-gen',
setup(build) {
build.onResolve({ filter: /contentlayer\/generated/ }, (args) => ({
path: args.path,
namespace: 'contentlayer-gen',
}))
build.onLoad({ filter: /.*/, namespace: 'contentlayer-gen' }, () => ({
contents: '// empty',
}))
},
})
// TODO also take tsconfig.json `paths` mapping into account
const makeAllPackagesExternalPlugin = (configPath: string): esbuild.Plugin => ({
name: 'make-all-packages-external',
setup: (build) => {
const filter = /^[^.\/]|^\.[^.\/]|^\.\.[^\/]/ // Must not start with "/" or "./" or "../"
build.onResolve({ filter }, (args) => {
// avoid marking config file as external
if (args.path.includes(configPath)) {
return { path: args.path, external: false }
}
return { path: args.path, external: true }
})
},
})