-
Notifications
You must be signed in to change notification settings - Fork 27.2k
/
index.ts
1632 lines (1471 loc) · 46 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
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
/* eslint-disable @typescript-eslint/no-use-before-define */
import path from 'path'
import { pathToFileURL } from 'url'
import { arch, platform } from 'os'
import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples'
import * as Log from '../output/log'
import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type {
TurboRuleConfigItem,
NextConfigComplete,
TurboLoaderItem,
TurboRuleConfigItemOrShortcut,
TurboRuleConfigItemOptions,
} from '../../server/config-shared'
import { isDeepStrictEqual } from 'util'
import type { DefineEnvPluginOptions } from '../webpack/plugins/define-env-plugin'
import { getDefineEnv } from '../webpack/plugins/define-env-plugin'
import type { PageExtensions } from '../page-extensions-type'
const nextVersion = process.env.__NEXT_VERSION as string
const ArchName = arch()
const PlatformName = platform()
const infoLog = (...args: any[]) => {
if (process.env.NEXT_PRIVATE_BUILD_WORKER) {
return
}
if (process.env.DEBUG) {
Log.info(...args)
}
}
/**
* Based on napi-rs's target triples, returns triples that have corresponding next-swc binaries.
*/
export const getSupportedArchTriples: () => Record<string, any> = () => {
const { darwin, win32, linux, freebsd, android } = platformArchTriples
return {
darwin,
win32: {
arm64: win32.arm64,
ia32: win32.ia32.filter(
(triple: { abi: string }) => triple.abi === 'msvc'
),
x64: win32.x64.filter((triple: { abi: string }) => triple.abi === 'msvc'),
},
linux: {
// linux[x64] includes `gnux32` abi, with x64 arch.
x64: linux.x64.filter(
(triple: { abi: string }) => triple.abi !== 'gnux32'
),
arm64: linux.arm64,
// This target is being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
arm: linux.arm,
},
// Below targets are being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
freebsd: {
x64: freebsd.x64,
},
android: {
arm64: android.arm64,
arm: android.arm,
},
}
}
const triples = (() => {
const supportedArchTriples = getSupportedArchTriples()
const targetTriple = supportedArchTriples[PlatformName]?.[ArchName]
// If we have supported triple, return it right away
if (targetTriple) {
return targetTriple
}
// If there isn't corresponding target triple in `supportedArchTriples`, check if it's excluded from original raw triples
// Otherwise, it is completely unsupported platforms.
let rawTargetTriple = platformArchTriples[PlatformName]?.[ArchName]
if (rawTargetTriple) {
Log.warn(
`Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support`
)
} else {
Log.warn(
`Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}`
)
}
return []
})()
// Allow to specify an absolute path to the custom turbopack binary to load.
// If one of env variables is set, `loadNative` will try to use any turbo-* interfaces from specified
// binary instead. This will not affect existing swc's transform, or other interfaces. This is thin,
// naive interface - `loadBindings` will not validate neither path nor the binary.
//
// Note these are internal flag: there's no stability, feature guarantee.
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS =
process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS
function checkVersionMismatch(pkgData: any) {
const version = pkgData.version
if (version && version !== nextVersion) {
Log.warn(
`Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match`
)
}
}
// These are the platforms we'll try to load wasm bindings first,
// only try to load native bindings if loading wasm binding somehow fails.
// Fallback to native binding is for migration period only,
// once we can verify loading-wasm-first won't cause visible regressions,
// we'll not include native bindings for these platform at all.
const knownDefaultWasmFallbackTriples = [
'x86_64-unknown-freebsd',
'aarch64-linux-android',
'arm-linux-androideabi',
'armv7-unknown-linux-gnueabihf',
'i686-pc-windows-msvc',
// WOA targets are TBD, while current userbase is small we may support it in the future
//'aarch64-pc-windows-msvc',
]
// The last attempt's error code returned when cjs require to native bindings fails.
// If node.js throws an error without error code, this should be `unknown` instead of undefined.
// For the wasm-first targets (`knownDefaultWasmFallbackTriples`) this will be `unsupported_target`.
let lastNativeBindingsLoadErrorCode:
| 'unknown'
| 'unsupported_target'
| string
| undefined = undefined
let nativeBindings: any
let wasmBindings: any
let downloadWasmPromise: any
let pendingBindings: any
let swcTraceFlushGuard: any
let swcHeapProfilerFlushGuard: any
let downloadNativeBindingsPromise: Promise<void> | undefined = undefined
export const lockfilePatchPromise: { cur?: Promise<void> } = {}
export interface Binding {
isWasm: boolean
turbo: {
startTrace: any
nextBuild?: any
createTurboTasks?: any
entrypoints: {
stream: any
get: any
}
mdx: {
compile: any
compileSync: any
}
createProject: (
options: ProjectOptions,
turboEngineOptions?: TurboEngineOptions
) => Promise<Project>
}
minify: any
minifySync: any
transform: any
transformSync: any
parse: any
parseSync: any
getTargetTriple(): string | undefined
initCustomTraceSubscriber?: any
teardownTraceSubscriber?: any
initHeapProfiler?: any
teardownHeapProfiler?: any
css: {
lightning: {
transform(transformOptions: any): Promise<any>
transformStyleAttr(attrOptions: any): Promise<any>
}
}
}
export async function loadBindings(
useWasmBinary: boolean = false
): Promise<Binding> {
// Increase Rust stack size as some npm packages being compiled need more than the default.
if (!process.env.RUST_MIN_STACK) {
process.env.RUST_MIN_STACK = '8388608'
}
if (pendingBindings) {
return pendingBindings
}
// rust needs stdout to be blocking, otherwise it will throw an error (on macOS at least) when writing a lot of data (logs) to it
// see https://github.com/napi-rs/napi-rs/issues/1630
// and https://github.com/nodejs/node/blob/main/doc/api/process.md#a-note-on-process-io
if (process.stdout._handle != null) {
// @ts-ignore
process.stdout._handle.setBlocking?.(true)
}
if (process.stderr._handle != null) {
// @ts-ignore
process.stderr._handle.setBlocking?.(true)
}
pendingBindings = new Promise(async (resolve, _reject) => {
if (!lockfilePatchPromise.cur) {
// always run lockfile check once so that it gets patched
// even if it doesn't fail to load locally
lockfilePatchPromise.cur = patchIncorrectLockfile(process.cwd()).catch(
console.error
)
}
let attempts: any[] = []
const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM
const unsupportedPlatform = triples.some(
(triple: any) =>
!!triple?.raw && knownDefaultWasmFallbackTriples.includes(triple.raw)
)
const isWebContainer = process.versions.webcontainer
const shouldLoadWasmFallbackFirst =
(!disableWasmFallback && unsupportedPlatform && useWasmBinary) ||
isWebContainer
if (!unsupportedPlatform && useWasmBinary) {
Log.warn(
`experimental.useWasmBinary is not an option for supported platform ${PlatformName}/${ArchName} and will be ignored.`
)
}
if (shouldLoadWasmFallbackFirst) {
lastNativeBindingsLoadErrorCode = 'unsupported_target'
const fallbackBindings = await tryLoadWasmWithFallback(attempts)
if (fallbackBindings) {
return resolve(fallbackBindings)
}
}
// Trickle down loading `fallback` bindings:
//
// - First, try to load native bindings installed in node_modules.
// - If that fails with `ERR_MODULE_NOT_FOUND`, treat it as case of https://github.com/npm/cli/issues/4828
// that host system where generated package lock is not matching to the guest system running on, try to manually
// download corresponding target triple and load it. This won't be triggered if native bindings are failed to load
// with other reasons than `ERR_MODULE_NOT_FOUND`.
// - Lastly, falls back to wasm binding where possible.
try {
return resolve(loadNative())
} catch (a) {
if (
Array.isArray(a) &&
a.every((m) => m.includes('it was not installed'))
) {
let fallbackBindings = await tryLoadNativeWithFallback(attempts)
if (fallbackBindings) {
return resolve(fallbackBindings)
}
}
attempts = attempts.concat(a)
}
logLoadFailure(attempts, true)
})
return pendingBindings
}
async function tryLoadNativeWithFallback(attempts: Array<string>) {
const nativeBindingsDirectory = path.join(
path.dirname(require.resolve('next/package.json')),
'next-swc-fallback'
)
if (!downloadNativeBindingsPromise) {
downloadNativeBindingsPromise = downloadNativeNextSwc(
nextVersion,
nativeBindingsDirectory,
triples.map((triple: any) => triple.platformArchABI)
)
}
await downloadNativeBindingsPromise
try {
let bindings = loadNative(nativeBindingsDirectory)
return bindings
} catch (a: any) {
attempts.concat(a)
}
return undefined
}
async function tryLoadWasmWithFallback(attempts: any) {
try {
let bindings = await loadWasm('')
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: 'enabled',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
return bindings
} catch (a) {
attempts = attempts.concat(a)
}
try {
// if not installed already download wasm package on-demand
// we download to a custom directory instead of to node_modules
// as node_module import attempts are cached and can't be re-attempted
// x-ref: https://github.com/nodejs/modules/issues/307
const wasmDirectory = path.join(
path.dirname(require.resolve('next/package.json')),
'wasm'
)
if (!downloadWasmPromise) {
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory)
}
await downloadWasmPromise
let bindings = await loadWasm(pathToFileURL(wasmDirectory).href)
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: 'fallback',
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
// still log native load attempts so user is
// aware it failed and should be fixed
for (const attempt of attempts) {
Log.warn(attempt)
}
return bindings
} catch (a) {
attempts = attempts.concat(a)
}
}
function loadBindingsSync() {
let attempts: any[] = []
try {
return loadNative()
} catch (a) {
attempts = attempts.concat(a)
}
// we can leverage the wasm bindings if they are already
// loaded
if (wasmBindings) {
return wasmBindings
}
logLoadFailure(attempts)
}
let loggingLoadFailure = false
function logLoadFailure(attempts: any, triedWasm = false) {
// make sure we only emit the event and log the failure once
if (loggingLoadFailure) return
loggingLoadFailure = true
for (let attempt of attempts) {
Log.warn(attempt)
}
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({
wasm: triedWasm ? 'failed' : undefined,
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode,
})
.then(() => lockfilePatchPromise.cur || Promise.resolve())
.finally(() => {
Log.error(
`Failed to load SWC binary for ${PlatformName}/${ArchName}, see more info here: https://nextjs.org/docs/messages/failed-loading-swc`
)
process.exit(1)
})
}
export interface ProjectOptions {
/**
* A root path from which all files must be nested under. Trying to access
* a file outside this root will fail. Think of this as a chroot.
*/
rootPath: string
/**
* A path inside the root_path which contains the app/pages directories.
*/
projectPath: string
/**
* The next.config.js contents.
*/
nextConfig: NextConfigComplete
/**
* Jsconfig, or tsconfig contents.
*
* Next.js implicitly requires to read it to support few options
* https://nextjs.org/docs/architecture/nextjs-compiler#legacy-decorators
* https://nextjs.org/docs/architecture/nextjs-compiler#importsource
*/
jsConfig: {
compilerOptions: object
}
/**
* A map of environment variables to use when compiling code.
*/
env: Record<string, string>
defineEnv: DefineEnv
/**
* Whether to watch the filesystem for file changes.
*/
watch: boolean
/**
* The mode in which Next.js is running.
*/
dev: boolean
}
type RustifiedEnv = { name: string; value: string }[]
export interface DefineEnv {
client: RustifiedEnv
edge: RustifiedEnv
nodejs: RustifiedEnv
}
export function createDefineEnv({
isTurbopack,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
middlewareMatchers,
}: Omit<
DefineEnvPluginOptions,
'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer'
>): DefineEnv {
let defineEnv: DefineEnv = {
client: [],
edge: [],
nodejs: [],
}
for (const variant of Object.keys(defineEnv) as (keyof typeof defineEnv)[]) {
defineEnv[variant] = rustifyEnv(
getDefineEnv({
isTurbopack,
clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix,
hasRewrites,
isClient: variant === 'client',
isEdgeServer: variant === 'edge',
isNodeOrEdgeCompilation: variant === 'nodejs' || variant === 'edge',
isNodeServer: variant === 'nodejs',
middlewareMatchers,
})
)
}
return defineEnv
}
export interface TurboEngineOptions {
/**
* An upper bound of memory that turbopack will attempt to stay under.
*/
memoryLimit?: number
}
export type StyledString =
| {
type: 'text'
value: string
}
| {
type: 'code'
value: string
}
| {
type: 'strong'
value: string
}
| {
type: 'stack'
value: StyledString[]
}
| {
type: 'line'
value: StyledString[]
}
export interface Issue {
severity: string
stage: string
filePath: string
title: StyledString
description?: StyledString
detail?: StyledString
source?: {
source: {
ident: string
content?: string
}
range?: {
start: {
// 0-indexed
line: number
// 0-indexed
column: number
}
end: {
// 0-indexed
line: number
// 0-indexed
column: number
}
}
}
documentationLink: string
subIssues: Issue[]
}
export interface Diagnostics {
category: string
name: string
payload: unknown
}
export type TurbopackResult<T = {}> = T & {
issues: Issue[]
diagnostics: Diagnostics[]
}
export interface Middleware {
endpoint: Endpoint
}
export interface Instrumentation {
nodeJs: Endpoint
edge: Endpoint
}
export interface Entrypoints {
routes: Map<string, Route>
middleware?: Middleware
instrumentation?: Instrumentation
pagesDocumentEndpoint: Endpoint
pagesAppEndpoint: Endpoint
pagesErrorEndpoint: Endpoint
}
interface BaseUpdate {
resource: {
headers: unknown
path: string
}
diagnostics: unknown[]
issues: Issue[]
}
interface IssuesUpdate extends BaseUpdate {
type: 'issues'
}
interface EcmascriptMergedUpdate {
type: 'EcmascriptMergedUpdate'
chunks: { [moduleName: string]: { type: 'partial' } }
entries: { [moduleName: string]: { code: string; map: string; url: string } }
}
interface PartialUpdate extends BaseUpdate {
type: 'partial'
instruction: {
type: 'ChunkListUpdate'
merged: EcmascriptMergedUpdate[] | undefined
}
}
export type Update = IssuesUpdate | PartialUpdate
export interface HmrIdentifiers {
identifiers: string[]
}
/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/packages/next-swc/crates/napi/src/next_api/project.rs#L824-L833 */
export interface TurbopackStackFrame {
isServer: boolean
isInternal?: boolean
file: string
/** 1-indexed, unlike source map tokens */
line?: number
/** 1-indexed, unlike source map tokens */
column?: number | null
methodName?: string
}
export type UpdateMessage =
| {
updateType: 'start'
}
| {
updateType: 'end'
value: UpdateInfo
}
export interface UpdateInfo {
duration: number
tasks: number
}
export interface Project {
update(options: Partial<ProjectOptions>): Promise<void>
entrypointsSubscribe(): AsyncIterableIterator<TurbopackResult<Entrypoints>>
hmrEvents(identifier: string): AsyncIterableIterator<TurbopackResult<Update>>
hmrIdentifiersSubscribe(): AsyncIterableIterator<
TurbopackResult<HmrIdentifiers>
>
getSourceForAsset(filePath: string): Promise<string | null>
traceSource(
stackFrame: TurbopackStackFrame
): Promise<TurbopackStackFrame | null>
updateInfoSubscribe(
aggregationMs: number
): AsyncIterableIterator<TurbopackResult<UpdateMessage>>
}
export type Route =
| {
type: 'conflict'
}
| {
type: 'app-page'
pages: {
originalName: string
htmlEndpoint: Endpoint
rscEndpoint: Endpoint
}[]
}
| {
type: 'app-route'
originalName: string
endpoint: Endpoint
}
| {
type: 'page'
htmlEndpoint: Endpoint
dataEndpoint: Endpoint
}
| {
type: 'page-api'
endpoint: Endpoint
}
export interface Endpoint {
/** Write files for the endpoint to disk. */
writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>>
/**
* Listen to client-side changes to the endpoint.
* After clientChanged() has been awaited it will listen to changes.
* The async iterator will yield for each change.
*/
clientChanged(): Promise<AsyncIterableIterator<TurbopackResult>>
/**
* Listen to server-side changes to the endpoint.
* After serverChanged() has been awaited it will listen to changes.
* The async iterator will yield for each change.
*/
serverChanged(
includeIssues: boolean
): Promise<AsyncIterableIterator<TurbopackResult>>
}
interface EndpointConfig {
dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
dynamicParams?: boolean
revalidate?: 'never' | 'force-cache' | number
fetchCache?:
| 'auto'
| 'default-cache'
| 'only-cache'
| 'force-cache'
| 'default-no-store'
| 'only-no-store'
| 'force-no-store'
runtime?: 'nodejs' | 'edge'
preferredRegion?: string
}
export type ServerPath = {
path: string
contentHash: string
}
export type WrittenEndpoint =
| {
type: 'nodejs'
/** The entry path for the endpoint. */
entryPath: string
/** All client paths that have been written for the endpoint. */
clientPaths: string[]
/** All server paths that have been written for the endpoint. */
serverPaths: ServerPath[]
config: EndpointConfig
}
| {
type: 'edge'
/** All client paths that have been written for the endpoint. */
clientPaths: string[]
/** All server paths that have been written for the endpoint. */
serverPaths: ServerPath[]
config: EndpointConfig
}
function rustifyEnv(env: Record<string, string>): RustifiedEnv {
return Object.entries(env)
.filter(([_, value]) => value != null)
.map(([name, value]) => ({
name,
value,
}))
}
// TODO(sokra) Support wasm option.
function bindingToApi(binding: any, _wasm: boolean) {
type NativeFunction<T> = (
callback: (err: Error, value: T) => void
) => Promise<{ __napiType: 'RootTask' }>
const cancel = new (class Cancel extends Error {})()
/**
* Utility function to ensure all variants of an enum are handled.
*/
function invariant(
never: never,
computeMessage: (arg: any) => string
): never {
throw new Error(`Invariant: ${computeMessage(never)}`)
}
async function withErrorCause<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn()
} catch (nativeError: any) {
throw new Error(nativeError.message, { cause: nativeError })
}
}
/**
* Calls a native function and streams the result.
* If useBuffer is true, all values will be preserved, potentially buffered
* if consumed slower than produced. Else, only the latest value will be
* preserved.
*/
function subscribe<T>(
useBuffer: boolean,
nativeFunction: NativeFunction<T>
): AsyncIterableIterator<T> {
type BufferItem =
| { err: Error; value: undefined }
| { err: undefined; value: T }
// A buffer of produced items. This will only contain values if the
// consumer is slower than the producer.
let buffer: BufferItem[] = []
// A deferred value waiting for the next produced item. This will only
// exist if the consumer is faster than the producer.
let waiting:
| {
resolve: (value: T) => void
reject: (error: Error) => void
}
| undefined
let canceled = false
// The native function will call this every time it emits a new result. We
// either need to notify a waiting consumer, or buffer the new result until
// the consumer catches up.
const emitResult = (err: Error | undefined, value: T | undefined) => {
if (waiting) {
let { resolve, reject } = waiting
waiting = undefined
if (err) reject(err)
else resolve(value!)
} else {
const item = { err, value } as BufferItem
if (useBuffer) buffer.push(item)
else buffer[0] = item
}
}
const iterator = (async function* () {
const task = await withErrorCause(() => nativeFunction(emitResult))
try {
while (!canceled) {
if (buffer.length > 0) {
const item = buffer.shift()!
if (item.err) throw item.err
yield item.value
} else {
// eslint-disable-next-line no-loop-func
yield new Promise<T>((resolve, reject) => {
waiting = { resolve, reject }
})
}
}
} catch (e) {
if (e === cancel) return
throw e
} finally {
binding.rootTaskDispose(task)
}
})()
iterator.return = async () => {
canceled = true
if (waiting) waiting.reject(cancel)
return { value: undefined, done: true } as IteratorReturnResult<never>
}
return iterator
}
async function rustifyProjectOptions(
options: Partial<ProjectOptions>
): Promise<any> {
return {
...options,
nextConfig:
options.nextConfig &&
(await serializeNextConfig(options.nextConfig, options.projectPath!)),
jsConfig: options.jsConfig && JSON.stringify(options.jsConfig),
env: options.env && rustifyEnv(options.env),
defineEnv: options.defineEnv,
}
}
class ProjectImpl implements Project {
private _nativeProject: { __napiType: 'Project' }
constructor(nativeProject: { __napiType: 'Project' }) {
this._nativeProject = nativeProject
}
async update(options: Partial<ProjectOptions>) {
await withErrorCause(async () =>
binding.projectUpdate(
this._nativeProject,
await rustifyProjectOptions(options)
)
)
}
entrypointsSubscribe() {
type NapiEndpoint = { __napiType: 'Endpoint' }
type NapiEntrypoints = {
routes: NapiRoute[]
middleware?: NapiMiddleware
instrumentation?: NapiInstrumentation
pagesDocumentEndpoint: NapiEndpoint
pagesAppEndpoint: NapiEndpoint
pagesErrorEndpoint: NapiEndpoint
}
type NapiMiddleware = {
endpoint: NapiEndpoint
runtime: 'nodejs' | 'edge'
matcher?: string[]
}
type NapiInstrumentation = {
nodeJs: NapiEndpoint
edge: NapiEndpoint
}
type NapiRoute = {
pathname: string
} & (
| {
type: 'page'
htmlEndpoint: NapiEndpoint
dataEndpoint: NapiEndpoint
}
| {
type: 'page-api'
endpoint: NapiEndpoint
}
| {
type: 'app-page'
pages: {
originalName: string
htmlEndpoint: NapiEndpoint
rscEndpoint: NapiEndpoint
}[]
}
| {
type: 'app-route'
originalName: string
endpoint: NapiEndpoint
}
| {
type: 'conflict'
}
)
const subscription = subscribe<TurbopackResult<NapiEntrypoints>>(
false,
async (callback) =>
binding.projectEntrypointsSubscribe(this._nativeProject, callback)
)
return (async function* () {
for await (const entrypoints of subscription) {
const routes = new Map()
for (const { pathname, ...nativeRoute } of entrypoints.routes) {
let route: Route
const routeType = nativeRoute.type
switch (routeType) {
case 'page':
route = {
type: 'page',
htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint),
dataEndpoint: new EndpointImpl(nativeRoute.dataEndpoint),
}
break
case 'page-api':
route = {
type: 'page-api',
endpoint: new EndpointImpl(nativeRoute.endpoint),
}
break
case 'app-page':
route = {
type: 'app-page',
pages: nativeRoute.pages.map((page) => ({
originalName: page.originalName,
htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
rscEndpoint: new EndpointImpl(page.rscEndpoint),
})),
}
break
case 'app-route':
route = {
type: 'app-route',
originalName: nativeRoute.originalName,
endpoint: new EndpointImpl(nativeRoute.endpoint),
}
break
case 'conflict':
route = {
type: 'conflict',
}
break
default:
const _exhaustiveCheck: never = routeType
invariant(
nativeRoute,
() => `Unknown route type: ${_exhaustiveCheck}`
)
}
routes.set(pathname, route)
}
const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({
endpoint: new EndpointImpl(middleware.endpoint),
runtime: middleware.runtime,
matcher: middleware.matcher,
})
const middleware = entrypoints.middleware
? napiMiddlewareToMiddleware(entrypoints.middleware)
: undefined
const napiInstrumentationToInstrumentation = (
instrumentation: NapiInstrumentation
) => ({
nodeJs: new EndpointImpl(instrumentation.nodeJs),
edge: new EndpointImpl(instrumentation.edge),