File size: 16,090 Bytes
1e92f2d |
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 |
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
*
* It will be prepended to the runtime code of each runtime.
*/
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-types.d.ts" />
type EsmNamespaceObject = Record<string, any>
// @ts-ignore Defined in `dev-base.ts`
declare function getOrInstantiateModuleFromParent<M>(
id: ModuleId,
sourceModule: M
): M
const REEXPORTED_OBJECTS = Symbol('reexported objects')
/**
* Constructs the `__turbopack_context__` object for a module.
*/
function Context(this: TurbopackBaseContext<Module>, module: Module) {
this.m = module
this.e = module.exports
}
const contextPrototype = Context.prototype as TurbopackBaseContext<Module>
type ModuleContextMap = Record<ModuleId, ModuleContextEntry>
interface ModuleContextEntry {
id: () => ModuleId
module: () => any
}
interface ModuleContext {
// require call
(moduleId: ModuleId): Exports | EsmNamespaceObject
// async import call
import(moduleId: ModuleId): Promise<Exports | EsmNamespaceObject>
keys(): ModuleId[]
resolve(moduleId: ModuleId): ModuleId
}
type GetOrInstantiateModuleFromParent<M extends Module> = (
moduleId: M['id'],
parentModule: M
) => M
declare function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): Module
const hasOwnProperty = Object.prototype.hasOwnProperty
const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag
function defineProp(
obj: any,
name: PropertyKey,
options: PropertyDescriptor & ThisType<any>
) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options)
}
function getOverwrittenModule(
moduleCache: ModuleCache<Module>,
id: ModuleId
): Module {
let module = moduleCache[id]
if (!module) {
// This is invoked when a module is merged into another module, thus it wasn't invoked via
// instantiateModule and the cache entry wasn't created yet.
module = createModuleObject(id)
moduleCache[id] = module
}
return module
}
/**
* Creates the module object. Only done here to ensure all module objects have the same shape.
*/
function createModuleObject(id: ModuleId): Module {
return {
exports: {},
error: undefined,
loaded: false,
id,
namespaceObject: undefined,
[REEXPORTED_OBJECTS]: undefined,
}
}
/**
* Adds the getters to the exports object.
*/
function esm(
exports: Exports,
getters: Record<string, (() => any) | [() => any, (v: any) => void]>
) {
defineProp(exports, '__esModule', { value: true })
if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' })
for (const key in getters) {
const item = getters[key]
if (Array.isArray(item)) {
defineProp(exports, key, {
get: item[0],
set: item[1],
enumerable: true,
})
} else {
defineProp(exports, key, { get: item, enumerable: true })
}
}
Object.seal(exports)
}
/**
* Makes the module an ESM with exports
*/
function esmExport(
this: TurbopackBaseContext<Module>,
getters: Record<string, () => any>,
id: ModuleId | undefined
) {
let module = this.m
let exports = this.e
if (id != null) {
module = getOverwrittenModule(this.c, id)
exports = module.exports
}
module.namespaceObject = module.exports
esm(exports, getters)
}
contextPrototype.s = esmExport
function ensureDynamicExports(module: Module, exports: Exports) {
let reexportedObjects = module[REEXPORTED_OBJECTS]
if (!reexportedObjects) {
reexportedObjects = module[REEXPORTED_OBJECTS] = []
module.exports = module.namespaceObject = new Proxy(exports, {
get(target, prop) {
if (
hasOwnProperty.call(target, prop) ||
prop === 'default' ||
prop === '__esModule'
) {
return Reflect.get(target, prop)
}
for (const obj of reexportedObjects!) {
const value = Reflect.get(obj, prop)
if (value !== undefined) return value
}
return undefined
},
ownKeys(target) {
const keys = Reflect.ownKeys(target)
for (const obj of reexportedObjects!) {
for (const key of Reflect.ownKeys(obj)) {
if (key !== 'default' && !keys.includes(key)) keys.push(key)
}
}
return keys
},
})
}
}
/**
* Dynamically exports properties from an object
*/
function dynamicExport(
this: TurbopackBaseContext<Module>,
object: Record<string, any>,
id: ModuleId | undefined
) {
let module = this.m
let exports = this.e
if (id != null) {
module = getOverwrittenModule(this.c, id)
exports = module.exports
}
ensureDynamicExports(module, exports)
if (typeof object === 'object' && object !== null) {
module[REEXPORTED_OBJECTS]!.push(object)
}
}
contextPrototype.j = dynamicExport
function exportValue(
this: TurbopackBaseContext<Module>,
value: any,
id: ModuleId | undefined
) {
let module = this.m
if (id != null) {
module = getOverwrittenModule(this.c, id)
}
module.exports = value
}
contextPrototype.v = exportValue
function exportNamespace(
this: TurbopackBaseContext<Module>,
namespace: any,
id: ModuleId | undefined
) {
let module = this.m
if (id != null) {
module = getOverwrittenModule(this.c, id)
}
module.exports = module.namespaceObject = namespace
}
contextPrototype.n = exportNamespace
function createGetter(obj: Record<string | symbol, any>, key: string | symbol) {
return () => obj[key]
}
/**
* @returns prototype of the object
*/
const getProto: (obj: any) => any = Object.getPrototypeOf
? (obj) => Object.getPrototypeOf(obj)
: (obj) => obj.__proto__
/** Prototypes that are not expanded for exports */
const LEAF_PROTOTYPES = [null, getProto({}), getProto([]), getProto(getProto)]
/**
* @param raw
* @param ns
* @param allowExportDefault
* * `false`: will have the raw module as default export
* * `true`: will have the default property as default export
*/
function interopEsm(
raw: Exports,
ns: EsmNamespaceObject,
allowExportDefault?: boolean
) {
const getters: { [s: string]: () => any } = Object.create(null)
for (
let current = raw;
(typeof current === 'object' || typeof current === 'function') &&
!LEAF_PROTOTYPES.includes(current);
current = getProto(current)
) {
for (const key of Object.getOwnPropertyNames(current)) {
getters[key] = createGetter(raw, key)
}
}
// this is not really correct
// we should set the `default` getter if the imported module is a `.cjs file`
if (!(allowExportDefault && 'default' in getters)) {
getters['default'] = () => raw
}
esm(ns, getters)
return ns
}
function createNS(raw: Module['exports']): EsmNamespaceObject {
if (typeof raw === 'function') {
return function (this: any, ...args: any[]) {
return raw.apply(this, args)
}
} else {
return Object.create(null)
}
}
function esmImport(
this: TurbopackBaseContext<Module>,
id: ModuleId
): Exclude<Module['namespaceObject'], undefined> {
const module = getOrInstantiateModuleFromParent(id, this.m)
if (module.error) throw module.error
// any ES module has to have `module.namespaceObject` defined.
if (module.namespaceObject) return module.namespaceObject
// only ESM can be an async module, so we don't need to worry about exports being a promise here.
const raw = module.exports
return (module.namespaceObject = interopEsm(
raw,
createNS(raw),
raw && (raw as any).__esModule
))
}
contextPrototype.i = esmImport
function asyncLoader(
this: TurbopackBaseContext<Module>,
moduleId: ModuleId
): Promise<Exports> {
const loader = this.r(moduleId) as (
importFunction: EsmImport
) => Promise<Exports>
return loader(this.i.bind(this))
}
contextPrototype.A = asyncLoader
// Add a simple runtime require so that environments without one can still pass
// `typeof require` CommonJS checks so that exports are correctly registered.
const runtimeRequire =
// @ts-ignore
typeof require === 'function'
? // @ts-ignore
require
: function require() {
throw new Error('Unexpected use of runtime require')
}
contextPrototype.t = runtimeRequire
function commonJsRequire(
this: TurbopackBaseContext<Module>,
id: ModuleId
): Exports {
const module = getOrInstantiateModuleFromParent(id, this.m)
if (module.error) throw module.error
return module.exports
}
contextPrototype.r = commonJsRequire
/**
* `require.context` and require/import expression runtime.
*/
function moduleContext(map: ModuleContextMap): ModuleContext {
function moduleContext(id: ModuleId): Exports {
if (hasOwnProperty.call(map, id)) {
return map[id].module()
}
const e = new Error(`Cannot find module '${id}'`)
;(e as any).code = 'MODULE_NOT_FOUND'
throw e
}
moduleContext.keys = (): ModuleId[] => {
return Object.keys(map)
}
moduleContext.resolve = (id: ModuleId): ModuleId => {
if (hasOwnProperty.call(map, id)) {
return map[id].id()
}
const e = new Error(`Cannot find module '${id}'`)
;(e as any).code = 'MODULE_NOT_FOUND'
throw e
}
moduleContext.import = async (id: ModuleId) => {
return await (moduleContext(id) as Promise<Exports>)
}
return moduleContext
}
contextPrototype.f = moduleContext
/**
* Returns the path of a chunk defined by its data.
*/
function getChunkPath(chunkData: ChunkData): ChunkPath {
return typeof chunkData === 'string' ? chunkData : chunkData.path
}
function isPromise<T = any>(maybePromise: any): maybePromise is Promise<T> {
return (
maybePromise != null &&
typeof maybePromise === 'object' &&
'then' in maybePromise &&
typeof maybePromise.then === 'function'
)
}
function isAsyncModuleExt<T extends {}>(obj: T): obj is AsyncModuleExt & T {
return turbopackQueues in obj
}
function createPromise<T>() {
let resolve: (value: T | PromiseLike<T>) => void
let reject: (reason?: any) => void
const promise = new Promise<T>((res, rej) => {
reject = rej
resolve = res
})
return {
promise,
resolve: resolve!,
reject: reject!,
}
}
// everything below is adapted from webpack
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
const turbopackQueues = Symbol('turbopack queues')
const turbopackExports = Symbol('turbopack exports')
const turbopackError = Symbol('turbopack error')
const enum QueueStatus {
Unknown = -1,
Unresolved = 0,
Resolved = 1,
}
type AsyncQueueFn = (() => void) & { queueCount: number }
type AsyncQueue = AsyncQueueFn[] & {
status: QueueStatus
}
function resolveQueue(queue?: AsyncQueue) {
if (queue && queue.status !== QueueStatus.Resolved) {
queue.status = QueueStatus.Resolved
queue.forEach((fn) => fn.queueCount--)
queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))
}
}
type Dep = Exports | AsyncModulePromise | Promise<Exports>
type AsyncModuleExt = {
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void
[turbopackExports]: Exports
[turbopackError]?: any
}
type AsyncModulePromise<T = Exports> = Promise<T> & AsyncModuleExt
function wrapDeps(deps: Dep[]): AsyncModuleExt[] {
return deps.map((dep): AsyncModuleExt => {
if (dep !== null && typeof dep === 'object') {
if (isAsyncModuleExt(dep)) return dep
if (isPromise(dep)) {
const queue: AsyncQueue = Object.assign([], {
status: QueueStatus.Unresolved,
})
const obj: AsyncModuleExt = {
[turbopackExports]: {},
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),
}
dep.then(
(res) => {
obj[turbopackExports] = res
resolveQueue(queue)
},
(err) => {
obj[turbopackError] = err
resolveQueue(queue)
}
)
return obj
}
}
return {
[turbopackExports]: dep,
[turbopackQueues]: () => {},
}
})
}
function asyncModule(
this: TurbopackBaseContext<Module>,
body: (
handleAsyncDependencies: (
deps: Dep[]
) => Exports[] | Promise<() => Exports[]>,
asyncResult: (err?: any) => void
) => void,
hasAwait: boolean
) {
const module = this.m
const queue: AsyncQueue | undefined = hasAwait
? Object.assign([], { status: QueueStatus.Unknown })
: undefined
const depQueues: Set<AsyncQueue> = new Set()
const { resolve, reject, promise: rawPromise } = createPromise<Exports>()
const promise: AsyncModulePromise = Object.assign(rawPromise, {
[turbopackExports]: module.exports,
[turbopackQueues]: (fn) => {
queue && fn(queue)
depQueues.forEach(fn)
promise['catch'](() => {})
},
} satisfies AsyncModuleExt)
const attributes: PropertyDescriptor = {
get(): any {
return promise
},
set(v: any) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v
}
},
}
Object.defineProperty(module, 'exports', attributes)
Object.defineProperty(module, 'namespaceObject', attributes)
function handleAsyncDependencies(deps: Dep[]) {
const currentDeps = wrapDeps(deps)
const getResult = () =>
currentDeps.map((d) => {
if (d[turbopackError]) throw d[turbopackError]
return d[turbopackExports]
})
const { promise, resolve } = createPromise<() => Exports[]>()
const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {
queueCount: 0,
})
function fnQueue(q: AsyncQueue) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q)
if (q && q.status === QueueStatus.Unresolved) {
fn.queueCount++
q.push(fn)
}
}
}
currentDeps.map((dep) => dep[turbopackQueues](fnQueue))
return fn.queueCount ? promise : getResult()
}
function asyncResult(err?: any) {
if (err) {
reject((promise[turbopackError] = err))
} else {
resolve(promise[turbopackExports])
}
resolveQueue(queue)
}
body(handleAsyncDependencies, asyncResult)
if (queue && queue.status === QueueStatus.Unknown) {
queue.status = QueueStatus.Unresolved
}
}
contextPrototype.a = asyncModule
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/
const relativeURL = function relativeURL(this: any, inputUrl: string) {
const realUrl = new URL(inputUrl, 'x:/')
const values: Record<string, any> = {}
for (const key in realUrl) values[key] = (realUrl as any)[key]
values.href = inputUrl
values.pathname = inputUrl.replace(/[?#].*/, '')
values.origin = values.protocol = ''
values.toString = values.toJSON = (..._args: Array<any>) => inputUrl
for (const key in values)
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key],
})
}
relativeURL.prototype = URL.prototype
contextPrototype.U = relativeURL
/**
* 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)}`)
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/
function requireStub(_moduleId: ModuleId): never {
throw new Error('dynamic usage of require is not supported')
}
contextPrototype.z = requireStub
type ContextConstructor<M> = {
new (module: Module): TurbopackBaseContext<M>
}
|