code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function exportValue(module, value) { module.exports = value; }
Dynamically exports properties from an object
exportValue
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function exportNamespace(module, namespace) { module.exports = module.namespaceObject = namespace; }
Dynamically exports properties from an object
exportNamespace
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function createGetter(obj, key) { return ()=>obj[key]; }
Dynamically exports properties from an object
createGetter
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function interopEsm(raw, ns, allowExportDefault) { const getters = 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; }
@param raw @param ns @param allowExportDefault * `false`: will have the raw module as default export * `true`: will have the default property as default export
interopEsm
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function createNS(raw) { if (typeof raw === 'function') { return function(...args) { return raw.apply(this, args); }; } else { return Object.create(null); } }
@param raw @param ns @param allowExportDefault * `false`: will have the raw module as default export * `true`: will have the default property as default export
createNS
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function esmImport(sourceModule, id) { const module = getOrInstantiateModuleFromParent(id, sourceModule); 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.__esModule); }
@param raw @param ns @param allowExportDefault * `false`: will have the raw module as default export * `true`: will have the default property as default export
esmImport
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function commonJsRequire(sourceModule, id) { const module = getOrInstantiateModuleFromParent(id, sourceModule); if (module.error) throw module.error; return module.exports; }
@param raw @param ns @param allowExportDefault * `false`: will have the raw module as default export * `true`: will have the default property as default export
commonJsRequire
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function moduleContext(map) { function moduleContext(id) { if (hasOwnProperty.call(map, id)) { return map[id].module(); } const e = new Error(`Cannot find module '${id}'`); e.code = 'MODULE_NOT_FOUND'; throw e; } moduleContext.keys = ()=>{ return Object.keys(map); }; moduleContext.resolve = (id)=>{ if (hasOwnProperty.call(map, id)) { return map[id].id(); } const e = new Error(`Cannot find module '${id}'`); e.code = 'MODULE_NOT_FOUND'; throw e; }; moduleContext.import = async (id)=>{ return await moduleContext(id); }; return moduleContext; }
`require.context` and require/import expression runtime.
moduleContext
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function moduleContext(id) { if (hasOwnProperty.call(map, id)) { return map[id].module(); } const e = new Error(`Cannot find module '${id}'`); e.code = 'MODULE_NOT_FOUND'; throw e; }
`require.context` and require/import expression runtime.
moduleContext
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getChunkPath(chunkData) { return typeof chunkData === 'string' ? chunkData : chunkData.path; }
Returns the path of a chunk defined by its data.
getChunkPath
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function isPromise(maybePromise) { return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function'; }
Returns the path of a chunk defined by its data.
isPromise
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function isAsyncModuleExt(obj) { return turbopackQueues in obj; }
Returns the path of a chunk defined by its data.
isAsyncModuleExt
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function createPromise() { let resolve; let reject; const promise = new Promise((res, rej)=>{ reject = rej; resolve = res; }); return { promise, resolve: resolve, reject: reject }; }
Returns the path of a chunk defined by its data.
createPromise
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function resolveQueue(queue) { if (queue && queue.status !== 1) { queue.status = 1; queue.forEach((fn)=>fn.queueCount--); queue.forEach((fn)=>fn.queueCount-- ? fn.queueCount++ : fn()); } }
Returns the path of a chunk defined by its data.
resolveQueue
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function wrapDeps(deps) { return deps.map((dep)=>{ if (dep !== null && typeof dep === 'object') { if (isAsyncModuleExt(dep)) return dep; if (isPromise(dep)) { const queue = Object.assign([], { status: 0 }); const obj = { [turbopackExports]: {}, [turbopackQueues]: (fn)=>fn(queue) }; dep.then((res)=>{ obj[turbopackExports] = res; resolveQueue(queue); }, (err)=>{ obj[turbopackError] = err; resolveQueue(queue); }); return obj; } } return { [turbopackExports]: dep, [turbopackQueues]: ()=>{} }; }); }
Returns the path of a chunk defined by its data.
wrapDeps
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function asyncModule(module, body, hasAwait) { const queue = hasAwait ? Object.assign([], { status: -1 }) : undefined; const depQueues = new Set(); const { resolve, reject, promise: rawPromise } = createPromise(); const promise = Object.assign(rawPromise, { [turbopackExports]: module.exports, [turbopackQueues]: (fn)=>{ queue && fn(queue); depQueues.forEach(fn); promise['catch'](()=>{}); } }); const attributes = { get () { return promise; }, set (v) { // Calling `esmExport` leads to this. if (v !== promise) { promise[turbopackExports] = v; } } }; Object.defineProperty(module, 'exports', attributes); Object.defineProperty(module, 'namespaceObject', attributes); function handleAsyncDependencies(deps) { const currentDeps = wrapDeps(deps); const getResult = ()=>currentDeps.map((d)=>{ if (d[turbopackError]) throw d[turbopackError]; return d[turbopackExports]; }); const { promise, resolve } = createPromise(); const fn = Object.assign(()=>resolve(getResult), { queueCount: 0 }); function fnQueue(q) { if (q !== queue && !depQueues.has(q)) { depQueues.add(q); if (q && q.status === 0) { fn.queueCount++; q.push(fn); } } } currentDeps.map((dep)=>dep[turbopackQueues](fnQueue)); return fn.queueCount ? promise : getResult(); } function asyncResult(err) { if (err) { reject(promise[turbopackError] = err); } else { resolve(promise[turbopackExports]); } resolveQueue(queue); } body(handleAsyncDependencies, asyncResult); if (queue && queue.status === -1) { queue.status = 0; } }
Returns the path of a chunk defined by its data.
asyncModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
get () { return promise; }
Returns the path of a chunk defined by its data.
get
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
set (v) { // Calling `esmExport` leads to this. if (v !== promise) { promise[turbopackExports] = v; } }
Returns the path of a chunk defined by its data.
set
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function handleAsyncDependencies(deps) { const currentDeps = wrapDeps(deps); const getResult = ()=>currentDeps.map((d)=>{ if (d[turbopackError]) throw d[turbopackError]; return d[turbopackExports]; }); const { promise, resolve } = createPromise(); const fn = Object.assign(()=>resolve(getResult), { queueCount: 0 }); function fnQueue(q) { if (q !== queue && !depQueues.has(q)) { depQueues.add(q); if (q && q.status === 0) { fn.queueCount++; q.push(fn); } } } currentDeps.map((dep)=>dep[turbopackQueues](fnQueue)); return fn.queueCount ? promise : getResult(); }
Returns the path of a chunk defined by its data.
handleAsyncDependencies
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
getResult = ()=>currentDeps.map((d)=>{ if (d[turbopackError]) throw d[turbopackError]; return d[turbopackExports]; })
Returns the path of a chunk defined by its data.
getResult
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
getResult = ()=>currentDeps.map((d)=>{ if (d[turbopackError]) throw d[turbopackError]; return d[turbopackExports]; })
Returns the path of a chunk defined by its data.
getResult
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function fnQueue(q) { if (q !== queue && !depQueues.has(q)) { depQueues.add(q); if (q && q.status === 0) { fn.queueCount++; q.push(fn); } } }
Returns the path of a chunk defined by its data.
fnQueue
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function asyncResult(err) { if (err) { reject(promise[turbopackError] = err); } else { resolve(promise[turbopackExports]); } resolveQueue(queue); }
Returns the path of a chunk defined by its data.
asyncResult
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
relativeURL = function relativeURL(inputUrl) { const realUrl = new URL(inputUrl, 'x:/'); const values = {}; for(const key in realUrl)values[key] = realUrl[key]; values.href = inputUrl; values.pathname = inputUrl.replace(/[?#].*/, ''); values.origin = values.protocol = ''; values.toString = values.toJSON = (..._args)=>inputUrl; for(const key in values)Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] }); }
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
relativeURL
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
relativeURL = function relativeURL(inputUrl) { const realUrl = new URL(inputUrl, 'x:/'); const values = {}; for(const key in realUrl)values[key] = realUrl[key]; values.href = inputUrl; values.pathname = inputUrl.replace(/[?#].*/, ''); values.origin = values.protocol = ''; values.toString = values.toJSON = (..._args)=>inputUrl; for(const key in values)Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] }); }
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
relativeURL
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function invariant(never, computeMessage) { throw new Error(`Invariant: ${computeMessage(never)}`); }
Utility function to ensure all variants of an enum are handled.
invariant
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function requireStub(_moduleId) { throw new Error('dynamic usage of require is not supported'); }
A stub function to make `require` available but non-functional in ESM.
requireStub
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function loadChunk(source, chunkData) { if (typeof chunkData === 'string') { return loadChunkPath(source, chunkData); } const includedList = chunkData.included || []; const modulesPromises = includedList.map((included)=>{ if (moduleFactories[included]) return true; return availableModules.get(included); }); if (modulesPromises.length > 0 && modulesPromises.every((p)=>p)) { // When all included items are already loaded or loading, we can skip loading ourselves return Promise.all(modulesPromises); } const includedModuleChunksList = chunkData.moduleChunks || []; const moduleChunksPromises = includedModuleChunksList.map((included)=>{ // TODO(alexkirsz) Do we need this check? // if (moduleFactories[included]) return true; return availableModuleChunks.get(included); }).filter((p)=>p); let promise; if (moduleChunksPromises.length > 0) { // Some module chunks are already loaded or loading. if (moduleChunksPromises.length === includedModuleChunksList.length) { // When all included module chunks are already loaded or loading, we can skip loading ourselves return Promise.all(moduleChunksPromises); } const moduleChunksToLoad = new Set(); for (const moduleChunk of includedModuleChunksList){ if (!availableModuleChunks.has(moduleChunk)) { moduleChunksToLoad.add(moduleChunk); } } for (const moduleChunkToLoad of moduleChunksToLoad){ const promise = loadChunkPath(source, moduleChunkToLoad); availableModuleChunks.set(moduleChunkToLoad, promise); moduleChunksPromises.push(promise); } promise = Promise.all(moduleChunksPromises); } else { promise = loadChunkPath(source, chunkData.path); // Mark all included module chunks as loading if they are not already loaded or loading. for (const includedModuleChunk of includedModuleChunksList){ if (!availableModuleChunks.has(includedModuleChunk)) { availableModuleChunks.set(includedModuleChunk, promise); } } } for (const included of includedList){ if (!availableModules.has(included)) { // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier. // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway. availableModules.set(included, promise); } } return promise; }
Map from a chunk path to the chunk lists it belongs to.
loadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function loadChunkByUrl(source, chunkUrl) { try { await BACKEND.loadChunk(chunkUrl, source); } catch (error) { let loadReason; switch(source.type){ case 0: loadReason = `as a runtime dependency of chunk ${source.chunkPath}`; break; case 1: loadReason = `from module ${source.parentId}`; break; case 2: loadReason = 'from an HMR update'; break; default: invariant(source, (source)=>`Unknown source type: ${source?.type}`); } throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? { cause: error } : undefined); } }
Map from a chunk path to the chunk lists it belongs to.
loadChunkByUrl
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function loadChunkPath(source, chunkPath) { const url = getChunkRelativeUrl(chunkPath); return loadChunkByUrl(source, url); }
Map from a chunk path to the chunk lists it belongs to.
loadChunkPath
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function createResolvePathFromModule(resolver) { return function resolvePathFromModule(moduleId) { const exported = resolver(moduleId); return exported?.default ?? exported; }; }
Returns an absolute url to an asset.
createResolvePathFromModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function resolveAbsolutePath(modulePath) { return `/ROOT/${modulePath ?? ''}`; }
no-op for browser @param modulePath
resolveAbsolutePath
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getWorkerBlobURL(chunks) { // It is important to reverse the array so when bootstrapping we can infer what chunk is being // evaluated by poping urls off of this array. See `getPathFromScript` let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; let blob = new Blob([ bootstrap ], { type: 'text/javascript' }); return URL.createObjectURL(blob); }
Returns a blob URL for the worker. @param chunks list of chunks to load
getWorkerBlobURL
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getFirstModuleChunk(moduleId) { const moduleChunkPaths = moduleChunksMap.get(moduleId); if (moduleChunkPaths == null) { return null; } return moduleChunkPaths.values().next().value; }
Returns the first chunk that included a module. This is used by the Node.js backend, hence why it's marked as unused in this file.
getFirstModuleChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getChunkRelativeUrl(chunkPath) { return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX_PATH}`; }
Returns the URL relative to the origin where a chunk can be fetched from.
getChunkRelativeUrl
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getPathFromScript(chunkScript) { if (typeof chunkScript === 'string') { return chunkScript; } const chunkUrl = typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined' ? TURBOPACK_NEXT_CHUNK_URLS.pop() : chunkScript.getAttribute('src'); const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, '')); const path = src.startsWith(CHUNK_BASE_PATH) ? src.slice(CHUNK_BASE_PATH.length) : src; return path; }
Returns the URL relative to the origin where a chunk can be fetched from.
getPathFromScript
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function registerChunk([chunkScript, chunkModules, runtimeParams]) { const chunkPath = getPathFromScript(chunkScript); for (const [moduleId, moduleFactory] of Object.entries(chunkModules)){ if (!moduleFactories[moduleId]) { moduleFactories[moduleId] = moduleFactory; } addModuleToChunk(moduleId, chunkPath); } return BACKEND.registerChunk(chunkPath, runtimeParams); }
Marks a chunk list as a runtime chunk list. There can be more than one runtime chunk list. For instance, integration tests can have multiple chunk groups loaded at runtime, each with its own chunk list.
registerChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function isJs(chunkUrlOrPath) { return regexJsUrl.test(chunkUrlOrPath); }
Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
isJs
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function isCss(chunkUrl) { return regexCssUrl.test(chunkUrl); }
Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.
isCss
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
constructor(message, dependencyChain){ super(message); this.dependencyChain = dependencyChain; }
This file contains runtime types and functions that are shared between all Turbopack *development* ECMAScript runtimes. It will be appended to the runtime code of each runtime right after the shared runtime utils.
constructor
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
getOrInstantiateModuleFromParent = (id, sourceModule)=>{ if (!sourceModule.hot.active) { console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); } const module = devModuleCache[id]; if (sourceModule.children.indexOf(id) === -1) { sourceModule.children.push(id); } if (module) { if (module.parents.indexOf(sourceModule.id) === -1) { module.parents.push(sourceModule.id); } return module; } return instantiateModule(id, { type: SourceType.Parent, parentId: sourceModule.id }); }
Retrieves a module from the cache, or instantiate it if it is not cached.
getOrInstantiateModuleFromParent
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
getOrInstantiateModuleFromParent = (id, sourceModule)=>{ if (!sourceModule.hot.active) { console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); } const module = devModuleCache[id]; if (sourceModule.children.indexOf(id) === -1) { sourceModule.children.push(id); } if (module) { if (module.parents.indexOf(sourceModule.id) === -1) { module.parents.push(sourceModule.id); } return module; } return instantiateModule(id, { type: SourceType.Parent, parentId: sourceModule.id }); }
Retrieves a module from the cache, or instantiate it if it is not cached.
getOrInstantiateModuleFromParent
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function instantiateModule(id, source) { const moduleFactory = moduleFactories[id]; if (typeof moduleFactory !== 'function') { // This can happen if modules incorrectly handle HMR disposes/updates, // e.g. when they keep a `setTimeout` around which still executes old code // and contains e.g. a `require("something")` call. let instantiationReason; switch(source.type){ case SourceType.Runtime: instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`; break; case SourceType.Parent: instantiationReason = `because it was required from module ${source.parentId}`; break; case SourceType.Update: instantiationReason = 'because of an HMR update'; break; default: invariant(source, (source)=>`Unknown source type: ${source?.type}`); } throw new Error(`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`); } const hotData = moduleHotData.get(id); const { hot, hotState } = createModuleHot(id, hotData); let parents; switch(source.type){ case SourceType.Runtime: runtimeModules.add(id); parents = []; break; case SourceType.Parent: // No need to add this module as a child of the parent module here, this // has already been taken care of in `getOrInstantiateModuleFromParent`. parents = [ source.parentId ]; break; case SourceType.Update: parents = source.parents || []; break; default: invariant(source, (source)=>`Unknown source type: ${source?.type}`); } const module = { exports: {}, error: undefined, loaded: false, id, parents, children: [], namespaceObject: undefined, hot }; devModuleCache[id] = module; moduleHotState.set(module, hotState); // NOTE(alexkirsz) This can fail when the module encounters a runtime error. try { const sourceInfo = { type: SourceType.Parent, parentId: id }; runModuleExecutionHooks(module, (refresh)=>{ const r = commonJsRequire.bind(null, module); moduleFactory.call(module.exports, augmentContext({ a: asyncModule.bind(null, module), e: module.exports, r: commonJsRequire.bind(null, module), t: runtimeRequire, f: moduleContext, i: esmImport.bind(null, module), s: esmExport.bind(null, module, module.exports), j: dynamicExport.bind(null, module, module.exports), v: exportValue.bind(null, module), n: exportNamespace.bind(null, module), m: module, c: devModuleCache, M: moduleFactories, l: loadChunk.bind(null, sourceInfo), L: loadChunkByUrl.bind(null, sourceInfo), w: loadWebAssembly.bind(null, sourceInfo), u: loadWebAssemblyModule.bind(null, sourceInfo), P: resolveAbsolutePath, U: relativeURL, k: refresh, R: createResolvePathFromModule(r), b: getWorkerBlobURL, z: requireStub })); }); } catch (error) { module.error = error; throw error; } module.loaded = true; if (module.namespaceObject && module.exports !== module.namespaceObject) { // in case of a circular dependency: cjs1 -> esm2 -> cjs1 interopEsm(module.exports, module.namespaceObject); } return module; }
Retrieves a module from the cache, or instantiate it if it is not cached.
instantiateModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function runModuleExecutionHooks(module, executeModule) { if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') { const cleanupReactRefreshIntercept = globalThis.$RefreshInterceptModuleExecution$(module.id); try { executeModule({ register: globalThis.$RefreshReg$, signature: globalThis.$RefreshSig$, registerExports: registerExportsAndSetupBoundaryForReactRefresh }); } finally{ // Always cleanup the intercept, even if module execution failed. cleanupReactRefreshIntercept(); } } else { // If the react refresh hooks are not installed we need to bind dummy functions. // This is expected when running in a Web Worker. It is also common in some of // our test environments. executeModule({ register: (type, id)=>{}, signature: ()=>(type)=>{}, registerExports: (module, helpers)=>{} }); } }
NOTE(alexkirsz) Webpack has a "module execution" interception hook that Next.js' React Refresh runtime hooks into to add module context to the refresh registry.
runModuleExecutionHooks
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function registerExportsAndSetupBoundaryForReactRefresh(module, helpers) { const currentExports = module.exports; const prevExports = module.hot.data.prevExports ?? null; helpers.registerExportsForReactRefresh(currentExports, module.id); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (helpers.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update, so we can compare the boundary // signatures. module.hot.dispose((data)=>{ data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (helpers.shouldInvalidateReactRefreshBoundary(helpers.getRefreshBoundarySignature(prevExports), helpers.getRefreshBoundarySignature(currentExports))) { module.hot.invalidate(); } else { helpers.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). const isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
registerExportsAndSetupBoundaryForReactRefresh
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function formatDependencyChain(dependencyChain) { return `Dependency chain: ${dependencyChain.join(' -> ')}`; }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
formatDependencyChain
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function computeOutdatedModules(added, modified) { const newModuleFactories = new Map(); for (const [moduleId, entry] of added){ if (entry != null) { newModuleFactories.set(moduleId, _eval(entry)); } } const outdatedModules = computedInvalidatedModules(modified.keys()); for (const [moduleId, entry] of modified){ newModuleFactories.set(moduleId, _eval(entry)); } return { outdatedModules, newModuleFactories }; }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
computeOutdatedModules
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function computedInvalidatedModules(invalidated) { const outdatedModules = new Set(); for (const moduleId of invalidated){ const effect = getAffectedModuleEffects(moduleId); switch(effect.type){ case 'unaccepted': throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain); case 'self-declined': throw new UpdateApplyError(`cannot apply update: self-declined module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain); case 'accepted': for (const outdatedModuleId of effect.outdatedModules){ outdatedModules.add(outdatedModuleId); } break; // TODO(alexkirsz) Dependencies: handle dependencies effects. default: invariant(effect, (effect)=>`Unknown effect type: ${effect?.type}`); } } return outdatedModules; }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
computedInvalidatedModules
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function computeOutdatedSelfAcceptedModules(outdatedModules) { const outdatedSelfAcceptedModules = []; for (const moduleId of outdatedModules){ const module = devModuleCache[moduleId]; const hotState = moduleHotState.get(module); if (module && hotState.selfAccepted && !hotState.selfInvalidated) { outdatedSelfAcceptedModules.push({ moduleId, errorHandler: hotState.selfAccepted }); } } return outdatedSelfAcceptedModules; }
This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
computeOutdatedSelfAcceptedModules
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function updateChunksPhase(chunksAddedModules, chunksDeletedModules) { for (const [chunkPath, addedModuleIds] of chunksAddedModules){ for (const moduleId of addedModuleIds){ addModuleToChunk(moduleId, chunkPath); } } const disposedModules = new Set(); for (const [chunkPath, addedModuleIds] of chunksDeletedModules){ for (const moduleId of addedModuleIds){ if (removeModuleFromChunk(moduleId, chunkPath)) { disposedModules.add(moduleId); } } } return { disposedModules }; }
Adds, deletes, and moves modules between chunks. This must happen before the dispose phase as it needs to know which modules were removed from all chunks, which we can only compute *after* taking care of added and moved modules.
updateChunksPhase
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposePhase(outdatedModules, disposedModules) { for (const moduleId of outdatedModules){ disposeModule(moduleId, 'replace'); } for (const moduleId of disposedModules){ disposeModule(moduleId, 'clear'); } // Removing modules from the module cache is a separate step. // We also want to keep track of previous parents of the outdated modules. const outdatedModuleParents = new Map(); for (const moduleId of outdatedModules){ const oldModule = devModuleCache[moduleId]; outdatedModuleParents.set(moduleId, oldModule?.parents); delete devModuleCache[moduleId]; } // TODO(alexkirsz) Dependencies: remove outdated dependency from module // children. return { outdatedModuleParents }; }
Adds, deletes, and moves modules between chunks. This must happen before the dispose phase as it needs to know which modules were removed from all chunks, which we can only compute *after* taking care of added and moved modules.
disposePhase
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeModule(moduleId, mode) { const module = devModuleCache[moduleId]; if (!module) { return; } const hotState = moduleHotState.get(module); const data = {}; // Run the `hot.dispose` handler, if any, passing in the persistent // `hot.data` object. for (const disposeHandler of hotState.disposeHandlers){ disposeHandler(data); } // This used to warn in `getOrInstantiateModuleFromParent` when a disposed // module is still importing other modules. module.hot.active = false; moduleHotState.delete(module); // TODO(alexkirsz) Dependencies: delete the module from outdated deps. // Remove the disposed module from its children's parent list. // It will be added back once the module re-instantiates and imports its // children again. for (const childId of module.children){ const child = devModuleCache[childId]; if (!child) { continue; } const idx = child.parents.indexOf(module.id); if (idx >= 0) { child.parents.splice(idx, 1); } } switch(mode){ case 'clear': delete devModuleCache[module.id]; moduleHotData.delete(module.id); break; case 'replace': moduleHotData.set(module.id, data); break; default: invariant(mode, (mode)=>`invalid mode: ${mode}`); } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
disposeModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyPhase(outdatedSelfAcceptedModules, newModuleFactories, outdatedModuleParents, reportError) { // Update module factories. for (const [moduleId, factory] of newModuleFactories.entries()){ moduleFactories[moduleId] = factory; } // TODO(alexkirsz) Run new runtime entries here. // TODO(alexkirsz) Dependencies: call accept handlers for outdated deps. // Re-instantiate all outdated self-accepted modules. for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules){ try { instantiateModule(moduleId, { type: SourceType.Update, parents: outdatedModuleParents.get(moduleId) }); } catch (err) { if (typeof errorHandler === 'function') { try { errorHandler(err, { moduleId, module: devModuleCache[moduleId] }); } catch (err2) { reportError(err2); reportError(err); } } else { reportError(err); } } } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyPhase
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyUpdate(update) { switch(update.type){ case 'ChunkListUpdate': applyChunkListUpdate(update); break; default: invariant(update, (update)=>`Unknown update type: ${update.type}`); } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyUpdate
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyChunkListUpdate(update) { if (update.merged != null) { for (const merged of update.merged){ switch(merged.type){ case 'EcmascriptMergedUpdate': applyEcmascriptMergedUpdate(merged); break; default: invariant(merged, (merged)=>`Unknown merged type: ${merged.type}`); } } } if (update.chunks != null) { for (const [chunkPath, chunkUpdate] of Object.entries(update.chunks)){ const chunkUrl = getChunkRelativeUrl(chunkPath); switch(chunkUpdate.type){ case 'added': BACKEND.loadChunk(chunkUrl, { type: SourceType.Update }); break; case 'total': DEV_BACKEND.reloadChunk?.(chunkUrl); break; case 'deleted': DEV_BACKEND.unloadChunk?.(chunkUrl); break; case 'partial': invariant(chunkUpdate.instruction, (instruction)=>`Unknown partial instruction: ${JSON.stringify(instruction)}.`); break; default: invariant(chunkUpdate, (chunkUpdate)=>`Unknown chunk update type: ${chunkUpdate.type}`); } } } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyChunkListUpdate
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyEcmascriptMergedUpdate(update) { const { entries = {}, chunks = {} } = update; const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(entries, chunks); const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified); const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted); applyInternal(outdatedModules, disposedModules, newModuleFactories); }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyEcmascriptMergedUpdate
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyInvalidatedModules(outdatedModules) { if (queuedInvalidatedModules.size > 0) { computedInvalidatedModules(queuedInvalidatedModules).forEach((moduleId)=>{ outdatedModules.add(moduleId); }); queuedInvalidatedModules.clear(); } return outdatedModules; }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyInvalidatedModules
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function applyInternal(outdatedModules, disposedModules, newModuleFactories) { outdatedModules = applyInvalidatedModules(outdatedModules); const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules); const { outdatedModuleParents } = disposePhase(outdatedModules, disposedModules); // we want to continue on error and only throw the error after we tried applying all updates let error; function reportError(err) { if (!error) error = err; } applyPhase(outdatedSelfAcceptedModules, newModuleFactories, outdatedModuleParents, reportError); if (error) { throw error; } if (queuedInvalidatedModules.size > 0) { applyInternal(new Set(), [], new Map()); } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
applyInternal
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function reportError(err) { if (!error) error = err; }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
reportError
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function computeChangedModules(entries, updates) { const chunksAdded = new Map(); const chunksDeleted = new Map(); const added = new Map(); const modified = new Map(); const deleted = new Set(); for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates)){ switch(mergedChunkUpdate.type){ case 'added': { const updateAdded = new Set(mergedChunkUpdate.modules); for (const moduleId of updateAdded){ added.set(moduleId, entries[moduleId]); } chunksAdded.set(chunkPath, updateAdded); break; } case 'deleted': { // We could also use `mergedChunkUpdate.modules` here. const updateDeleted = new Set(chunkModulesMap.get(chunkPath)); for (const moduleId of updateDeleted){ deleted.add(moduleId); } chunksDeleted.set(chunkPath, updateDeleted); break; } case 'partial': { const updateAdded = new Set(mergedChunkUpdate.added); const updateDeleted = new Set(mergedChunkUpdate.deleted); for (const moduleId of updateAdded){ added.set(moduleId, entries[moduleId]); } for (const moduleId of updateDeleted){ deleted.add(moduleId); } chunksAdded.set(chunkPath, updateAdded); chunksDeleted.set(chunkPath, updateDeleted); break; } default: invariant(mergedChunkUpdate, (mergedChunkUpdate)=>`Unknown merged chunk update type: ${mergedChunkUpdate.type}`); } } // If a module was added from one chunk and deleted from another in the same update, // consider it to be modified, as it means the module was moved from one chunk to another // AND has new code in a single update. for (const moduleId of added.keys()){ if (deleted.has(moduleId)) { added.delete(moduleId); deleted.delete(moduleId); } } for (const [moduleId, entry] of Object.entries(entries)){ // Modules that haven't been added to any chunk but have new code are considered // to be modified. // This needs to be under the previous loop, as we need it to get rid of modules // that were added and deleted in the same update. if (!added.has(moduleId)) { modified.set(moduleId, entry); } } return { added, deleted, modified, chunksAdded, chunksDeleted }; }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
computeChangedModules
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getAffectedModuleEffects(moduleId) { const outdatedModules = new Set(); const queue = [ { moduleId, dependencyChain: [] } ]; let nextItem; while(nextItem = queue.shift()){ const { moduleId, dependencyChain } = nextItem; if (moduleId != null) { if (outdatedModules.has(moduleId)) { continue; } outdatedModules.add(moduleId); } // We've arrived at the runtime of the chunk, which means that nothing // else above can accept this update. if (moduleId === undefined) { return { type: 'unaccepted', dependencyChain }; } const module = devModuleCache[moduleId]; const hotState = moduleHotState.get(module); if (// The module is not in the cache. Since this is a "modified" update, // it means that the module was never instantiated before. !module || hotState.selfAccepted && !hotState.selfInvalidated) { continue; } if (hotState.selfDeclined) { return { type: 'self-declined', dependencyChain, moduleId }; } if (runtimeModules.has(moduleId)) { queue.push({ moduleId: undefined, dependencyChain: [ ...dependencyChain, moduleId ] }); continue; } for (const parentId of module.parents){ const parent = devModuleCache[parentId]; if (!parent) { continue; } // TODO(alexkirsz) Dependencies: check accepted and declined // dependencies here. queue.push({ moduleId: parentId, dependencyChain: [ ...dependencyChain, moduleId ] }); } } return { type: 'accepted', moduleId, outdatedModules }; }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
getAffectedModuleEffects
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function handleApply(chunkListPath, update) { switch(update.type){ case 'partial': { // This indicates that the update is can be applied to the current state of the application. applyUpdate(update.instruction); break; } case 'restart': { // This indicates that there is no way to apply the update to the // current state of the application, and that the application must be // restarted. DEV_BACKEND.restart(); break; } case 'notFound': { // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed, // or the page itself was deleted. // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to. // If it is a runtime chunk list, we restart the application. if (runtimeChunkLists.has(chunkListPath)) { DEV_BACKEND.restart(); } else { disposeChunkList(chunkListPath); } break; } default: throw new Error(`Unknown update type: ${update.type}`); } }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
handleApply
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function createModuleHot(moduleId, hotData) { const hotState = { selfAccepted: false, selfDeclined: false, selfInvalidated: false, disposeHandlers: [] }; const hot = { // TODO(alexkirsz) This is not defined in the HMR API. It was used to // decide whether to warn whenever an HMR-disposed module required other // modules. We might want to remove it. active: true, data: hotData ?? {}, // TODO(alexkirsz) Support full (dep, callback, errorHandler) form. accept: (modules, _callback, _errorHandler)=>{ if (modules === undefined) { hotState.selfAccepted = true; } else if (typeof modules === 'function') { hotState.selfAccepted = modules; } else { throw new Error('unsupported `accept` signature'); } }, decline: (dep)=>{ if (dep === undefined) { hotState.selfDeclined = true; } else { throw new Error('unsupported `decline` signature'); } }, dispose: (callback)=>{ hotState.disposeHandlers.push(callback); }, addDisposeHandler: (callback)=>{ hotState.disposeHandlers.push(callback); }, removeDisposeHandler: (callback)=>{ const idx = hotState.disposeHandlers.indexOf(callback); if (idx >= 0) { hotState.disposeHandlers.splice(idx, 1); } }, invalidate: ()=>{ hotState.selfInvalidated = true; queuedInvalidatedModules.add(moduleId); }, // NOTE(alexkirsz) This is part of the management API, which we don't // implement, but the Next.js React Refresh runtime uses this to decide // whether to schedule an update. status: ()=>'idle', // NOTE(alexkirsz) Since we always return "idle" for now, these are no-ops. addStatusHandler: (_handler)=>{}, removeStatusHandler: (_handler)=>{}, // NOTE(jridgewell) Check returns the list of updated modules, but we don't // want the webpack code paths to ever update (the turbopack paths handle // this already). check: ()=>Promise.resolve(null) }; return { hot, hotState }; }
Disposes of an instance of a module. Returns the persistent hot data that should be kept for the next module instance. NOTE: mode = "replace" will not remove modules from the devModuleCache This must be done in a separate step afterwards. This is important because all modules need to be disposed to update the parent/child relationships before they are actually removed from the devModuleCache. If this was done in this method, the following disposeModule calls won't find the module from the module id in the cache.
createModuleHot
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function removeModuleFromChunk(moduleId, chunkPath) { const moduleChunks = moduleChunksMap.get(moduleId); moduleChunks.delete(chunkPath); const chunkModules = chunkModulesMap.get(chunkPath); chunkModules.delete(moduleId); const noRemainingModules = chunkModules.size === 0; if (noRemainingModules) { chunkModulesMap.delete(chunkPath); } const noRemainingChunks = moduleChunks.size === 0; if (noRemainingChunks) { moduleChunksMap.delete(moduleId); } return noRemainingChunks; }
Removes a module from a chunk. Returns `true` if there are no remaining chunks including this module.
removeModuleFromChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeChunkList(chunkListPath) { const chunkPaths = chunkListChunksMap.get(chunkListPath); if (chunkPaths == null) { return false; } chunkListChunksMap.delete(chunkListPath); for (const chunkPath of chunkPaths){ const chunkChunkLists = chunkChunkListsMap.get(chunkPath); chunkChunkLists.delete(chunkListPath); if (chunkChunkLists.size === 0) { chunkChunkListsMap.delete(chunkPath); disposeChunk(chunkPath); } } // We must also dispose of the chunk list's chunk itself to ensure it may // be reloaded properly in the future. const chunkListUrl = getChunkRelativeUrl(chunkListPath); DEV_BACKEND.unloadChunk?.(chunkListUrl); return true; }
Disposes of a chunk list and its corresponding exclusive chunks.
disposeChunkList
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function disposeChunk(chunkPath) { const chunkUrl = getChunkRelativeUrl(chunkPath); // This should happen whether the chunk has any modules in it or not. // For instance, CSS chunks have no modules in them, but they still need to be unloaded. DEV_BACKEND.unloadChunk?.(chunkUrl); const chunkModules = chunkModulesMap.get(chunkPath); if (chunkModules == null) { return false; } chunkModules.delete(chunkPath); for (const moduleId of chunkModules){ const moduleChunks = moduleChunksMap.get(moduleId); moduleChunks.delete(chunkPath); const noRemainingChunks = moduleChunks.size === 0; if (noRemainingChunks) { moduleChunksMap.delete(moduleId); disposeModule(moduleId, 'clear'); availableModules.delete(moduleId); } } return true; }
Disposes of a chunk and its corresponding exclusive modules. @returns Whether the chunk was disposed of.
disposeChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function registerChunkList(chunkList) { const chunkListScript = chunkList.script; const chunkListPath = getPathFromScript(chunkListScript); // The "chunk" is also registered to finish the loading in the backend BACKEND.registerChunk(chunkListPath); globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS.push([ chunkListPath, handleApply.bind(null, chunkListPath) ]); // Adding chunks to chunk lists and vice versa. const chunkPaths = new Set(chunkList.chunks.map(getChunkPath)); chunkListChunksMap.set(chunkListPath, chunkPaths); for (const chunkPath of chunkPaths){ let chunkChunkLists = chunkChunkListsMap.get(chunkPath); if (!chunkChunkLists) { chunkChunkLists = new Set([ chunkListPath ]); chunkChunkListsMap.set(chunkPath, chunkChunkLists); } else { chunkChunkLists.add(chunkListPath); } } if (chunkList.source === 'entry') { markChunkListAsRuntime(chunkListPath); } }
Subscribes to chunk list updates from the update server and applies them.
registerChunkList
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function augmentContext(context) { return context; }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
augmentContext
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function fetchWebAssembly(wasmChunkPath) { return fetch(getChunkRelativeUrl(wasmChunkPath)); }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
fetchWebAssembly
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function loadWebAssembly(_source, wasmChunkPath, _edgeModule, importsObj) { const req = fetchWebAssembly(wasmChunkPath); const { instance } = await WebAssembly.instantiateStreaming(req, importsObj); return instance.exports; }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
loadWebAssembly
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function loadWebAssemblyModule(_source, wasmChunkPath, _edgeModule) { const req = fetchWebAssembly(wasmChunkPath); return await WebAssembly.compileStreaming(req); }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
loadWebAssemblyModule
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async registerChunk (chunkPath, params) { const chunkUrl = getChunkRelativeUrl(chunkPath); const resolver = getOrCreateResolver(chunkUrl); resolver.resolve(); if (params == null) { return; } for (const otherChunkData of params.otherChunks){ const otherChunkPath = getChunkPath(otherChunkData); const otherChunkUrl = getChunkRelativeUrl(otherChunkPath); // Chunk might have started loading, so we want to avoid triggering another load. getOrCreateResolver(otherChunkUrl); } // This waits for chunks to be loaded, but also marks included items as available. await Promise.all(params.otherChunks.map((otherChunkData)=>loadChunk({ type: SourceType.Runtime, chunkPath }, otherChunkData))); if (params.runtimeModuleIds.length > 0) { for (const moduleId of params.runtimeModuleIds){ getOrInstantiateRuntimeModule(moduleId, chunkPath); } } }
Maps chunk paths to the corresponding resolver.
registerChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
loadChunk (chunkUrl, source) { return doLoadChunk(chunkUrl, source); }
Loads the given chunk, and returns a promise that resolves once the chunk has been loaded.
loadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function getOrCreateResolver(chunkUrl) { let resolver = chunkResolvers.get(chunkUrl); if (!resolver) { let resolve; let reject; const promise = new Promise((innerResolve, innerReject)=>{ resolve = innerResolve; reject = innerReject; }); resolver = { resolved: false, loadingStarted: false, promise, resolve: ()=>{ resolver.resolved = true; resolve(); }, reject: reject }; chunkResolvers.set(chunkUrl, resolver); } return resolver; }
Loads the given chunk, and returns a promise that resolves once the chunk has been loaded.
getOrCreateResolver
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function doLoadChunk(chunkUrl, source) { const resolver = getOrCreateResolver(chunkUrl); if (resolver.loadingStarted) { return resolver.promise; } if (source.type === SourceType.Runtime) { // We don't need to load chunks references from runtime code, as they're already // present in the DOM. resolver.loadingStarted = true; if (isCss(chunkUrl)) { // CSS chunks do not register themselves, and as such must be marked as // loaded instantly. resolver.resolve(); } // We need to wait for JS chunks to register themselves within `registerChunk` // before we can start instantiating runtime modules, hence the absence of // `resolver.resolve()` in this branch. return resolver.promise; } if (typeof importScripts === 'function') { // We're in a web worker if (isCss(chunkUrl)) { // ignore } else if (isJs(chunkUrl)) { self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl); } else { throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); } } else { // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. const decodedChunkUrl = decodeURI(chunkUrl); if (isCss(chunkUrl)) { const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); if (previousLinks.length > 0) { // CSS chunks do not register themselves, and as such must be marked as // loaded instantly. resolver.resolve(); } else { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = chunkUrl; link.onerror = ()=>{ resolver.reject(); }; link.onload = ()=>{ // CSS chunks do not register themselves, and as such must be marked as // loaded instantly. resolver.resolve(); }; document.body.appendChild(link); } } else if (isJs(chunkUrl)) { const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); if (previousScripts.length > 0) { // There is this edge where the script already failed loading, but we // can't detect that. The Promise will never resolve in this case. for (const script of Array.from(previousScripts)){ script.addEventListener('error', ()=>{ resolver.reject(); }); } } else { const script = document.createElement('script'); script.src = chunkUrl; // We'll only mark the chunk as loaded once the script has been executed, // which happens in `registerChunk`. Hence the absence of `resolve()` in // this branch. script.onerror = ()=>{ resolver.reject(); }; document.body.appendChild(script); } } else { throw new Error(`can't infer type of chunk from URL ${chunkUrl}`); } } resolver.loadingStarted = true; return resolver.promise; }
Loads the given chunk, and returns a promise that resolves once the chunk has been loaded.
doLoadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
unloadChunk (chunkUrl) { deleteResolver(chunkUrl); // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. const decodedChunkUrl = decodeURI(chunkUrl); if (isCss(chunkUrl)) { const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } } else if (isJs(chunkUrl)) { // Unloading a JS chunk would have no effect, as it lives in the JS // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } } else { throw new Error(`can't infer type of chunk from URL ${chunkUrl}`); } }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
unloadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
reloadChunk (chunkUrl) { return new Promise((resolve, reject)=>{ if (!isCss(chunkUrl)) { reject(new Error('The DOM backend can only reload CSS chunks')); return; } const decodedChunkUrl = decodeURI(chunkUrl); const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; if (navigator.userAgent.includes('Firefox')) { // Firefox won't reload CSS files that were previously loaded on the current page, // we need to add a query param to make sure CSS is actually reloaded from the server. // // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // // Safari has a similar issue, but only if you have a `<link rel=preload ... />` tag // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 link.href = `${chunkUrl}?ts=${Date.now()}`; } else { link.href = chunkUrl; } link.onerror = ()=>{ reject(); }; link.onload = ()=>{ // First load the new CSS, then remove the old ones. This prevents visible // flickering that would happen in-between removing the previous CSS and // loading the new one. for (const previousLink of Array.from(previousLinks))previousLink.remove(); // CSS chunks do not register themselves, and as such must be marked as // loaded instantly. resolve(); }; // Make sure to insert the new CSS right after the previous one, so that // its precedence is higher. previousLinks[0].parentElement.insertBefore(link, previousLinks[0].nextSibling); }); }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
reloadChunk
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
function _eval({ code, url, map }) { code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX_PATH)}`; if (map) { code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences // See https://stackoverflow.com/a/26603875 unescape(encodeURIComponent(map)))}`; } // eslint-disable-next-line no-eval return eval(code); }
This file contains the runtime code specific to the Turbopack development ECMAScript DOM runtime. It will be appended to the base development runtime code.
_eval
javascript
vercel/next.js
turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js
MIT
async function dbConnect() { if (cached.conn) { return cached.conn } if (!cached.promise) { const opts = { bufferCommands: false, } cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { return mongoose }) } cached.conn = await cached.promise return cached.conn }
Global is used here to maintain a cached connection across hot reloads in development. This prevents connections growing exponentially during API Route usage.
dbConnect
javascript
vercel/next.js
turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/lib/dbConnect.js
https://github.com/vercel/next.js/blob/master/turbopack/packages/turbo-tracing-next-plugin/test/with-mongodb-mongoose/lib/dbConnect.js
MIT
function done(err) { if (!cbCalled) { cb(err); cbCalled = true; } }
This is the exposed module. This method facilitates copying a file. @param {String} fileSrc @param {String} fileDest @param {Function} cb @access public
done
javascript
aws/aws-iot-device-sdk-js
examples/lib/copy-file.js
https://github.com/aws/aws-iot-device-sdk-js/blob/master/examples/lib/copy-file.js
Apache-2.0
Unirest = function (method, uri, headers, body, callback) { var unirest = function (uri, headers, body, callback) { var $this = { /** * Stream Multipart form-data request * * @type {Boolean} */ _stream: false, /** * Container to hold multipart form data for processing upon request. * * @type {Array} * @private */ _multipart: [], /** * Container to hold form data for processing upon request. * * @type {Array} * @private */ _form: [], /** * Request option container for details about the request. * * @type {Object} */ options: { /** * Url obtained from request method arguments. * * @type {String} */ url: uri, /** * Method obtained from request method arguments. * * @type {String} */ method: method, /** * List of headers with case-sensitive fields. * * @type {Object} */ headers: {} }, hasHeader: function (name) { var headers var lowercaseHeaders name = name.toLowerCase() headers = Object.keys($this.options.headers) lowercaseHeaders = headers.map(function (header) { return header.toLowerCase() }) for (var i = 0; i < lowercaseHeaders.length; i++) { if (lowercaseHeaders[i] === name) { return headers[i] } } return false }, /** * Turn on multipart-form streaming * * @return {Object} */ stream: function () { $this._stream = true return this }, /** * Attaches a field to the multipart-form request, with pre-processing. * * @param {String} name * @param {String} value * @return {Object} */ field: function (name, value, options) { return handleField(name, value, options) }, /** * Attaches a file to the multipart-form request. * * @param {String} name * @param {String|Object} path * @return {Object} */ attach: function (name, path, options) { options = options || {} options.attachment = true return handleField(name, path, options) }, /** * Attaches field to the multipart-form request, with no pre-processing. * * @param {String} name * @param {String|Object} path * @param {Object} options * @return {Object} */ rawField: function (name, value, options) { $this._multipart.push({ name: name, value: value, options: options, attachment: options.attachment || false }) }, /** * Basic Header Authentication Method * * Supports user being an Object to reflect Request * Supports user, password to reflect SuperAgent * * @param {String|Object} user * @param {String} password * @param {Boolean} sendImmediately * @return {Object} */ auth: function (user, password, sendImmediately) { $this.options.auth = (is(user).a(Object)) ? user : { user: user, password: password, sendImmediately: sendImmediately } return $this }, /** * Sets header field to value * * @param {String} field Header field * @param {String} value Header field value * @return {Object} */ header: function (field, value) { if (is(field).a(Object)) { for (var key in field) { if (Object.prototype.hasOwnProperty.call(field, key)) { $this.header(key, field[key]) } } return $this } var existingHeaderName = $this.hasHeader(field) $this.options.headers[existingHeaderName || field] = value return $this }, /** * Serialize value as querystring representation, and append or set on `Request.options.url` * * @param {String|Object} value * @return {Object} */ query: function (value) { if (is(value).a(Object)) value = Unirest.serializers.form(value) if (!value.length) return $this $this.options.url += (does($this.options.url).contain('?') ? '&' : '?') + value return $this }, /** * Set _content-type_ header with type passed through `mime.getType()` when necessary. * * @param {String} type * @return {Object} */ type: function (type) { $this.header('Content-Type', does(type).contain('/') ? type : mime.getType(type)) return $this }, /** * Data marshalling for HTTP request body data * * Determines whether type is `form` or `json`. * For irregular mime-types the `.type()` method is used to infer the `content-type` header. * * When mime-type is `application/x-www-form-urlencoded` data is appended rather than overwritten. * * @param {Mixed} data * @return {Object} */ send: function (data) { var type = $this.options.headers[$this.hasHeader('content-type')] if ((is(data).a(Object) || is(data).a(Array)) && !Buffer.isBuffer(data)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] $this.options.body = Unirest.serializers.form(data) } else if (~type.indexOf('json')) { $this.options.json = true if ($this.options.body && is($this.options.body).a(Object)) { for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { $this.options.body[key] = data[key] } } } else { $this.options.body = data } } else { $this.options.body = Unirest.Request.serialize(data, type) } } else if (is(data).a(String)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] } if (type === 'application/x-www-form-urlencoded') { $this.options.body = $this.options.body ? $this.options.body + '&' + data : data } else { $this.options.body = ($this.options.body || '') + data } } else { $this.options.body = data } return $this }, /** * Takes multipart options and places them on `options.multipart` array. * Transforms body when an `Object` or _content-type_ is present. * * Example: * * Unirest.get('http://google.com').part({ * 'content-type': 'application/json', * body: { * phrase: 'Hello' * } * }).part({ * 'content-type': 'application/json', * body: { * phrase: 'World' * } * }).end(function (response) {}) * * @param {Object|String} options When an Object, headers should be placed directly on the object, * not under a child property. * @return {Object} */ part: function (options) { if (!$this._multipart) { $this.options.multipart = [] } if (is(options).a(Object)) { if (options['content-type']) { var type = Unirest.type(options['content-type'], true) if (type) options.body = Unirest.Response.parse(options.body) } else { if (is(options.body).a(Object)) { options.body = Unirest.serializers.json(options.body) } } $this.options.multipart.push(options) } else { $this.options.multipart.push({ body: options }) } return $this }, /** * Instructs the Request to be retried if specified error status codes (4xx, 5xx, ETIMEDOUT) are returned. * Retries are delayed with an exponential backoff. * * @param {(err: Error) => boolean} [callback] - Invoked on response error. Return false to stop next request. * @param {Object} [options] - Optional retry configuration to override defaults. * @param {number} [options.attempts=3] - The number of retry attempts. * @param {number} [options.delayInMs=250] - The delay in milliseconds (delayInMs *= delayMulti) * @param {number} [options.delayMulti=2] - The multiplier of delayInMs after each attempt. * @param {Array<string|number>} [options.statusCodes=["ETIMEDOUT", "5xx"]] - The status codes to retry on. * @return {Object} */ retry: function (callback, options) { $this.options.retry = { callback: typeof callback === "function" ? callback : null, attempts: options && +options.attempts || 3, delayInMs: options && +options.delayInMs || 250, delayMulti: options && +options.delayMulti || 2, statusCodes: (options && options.statusCodes || ["ETIMEDOUT", "5xx"]).slice(0) }; return $this }, /** * Proxies the call to end. This adds support for using promises as well as async/await. * * @param {Function} callback * @return {Promise} **/ then: function (callback) { return new Promise((resolve, reject) => { this.end(result => { try { resolve(callback(result)) } catch (err) { reject(err) } }) }) }, /** * Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. * Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. * * @param {Function} callback * @return {Object} */ end: function (callback) { var self = this var Request var header var parts var form function handleRetriableRequestResponse (result) { // If retries is not defined or all attempts tried, return true to invoke end's callback. if ($this.options.retry === undefined || $this.options.retry.attempts === 0) { return true } // If status code is not listed, abort with return true to invoke end's callback. var isStatusCodeDefined = (function (code, codes) { if (codes.indexOf(code) !== -1) { return true } return codes.reduce(function (p, c) { return p || String(code).split("").every(function (ch, i) { return ch === "x" || ch === c[i] }) }, false) }(result.code || result.error && result.error.code, $this.options.retry.statusCodes)) if (!isStatusCodeDefined) { return true } if ($this.options.retry.callback) { var isContinue = $this.options.retry.callback(result) // If retry callback returns false, stop retries and invoke end's callback. if (isContinue === false) { return true; } } setTimeout(function () { self.end(callback) }, $this.options.retry.delayInMs) $this.options.retry.attempts-- $this.options.retry.delayInMs *= $this.options.retry.delayMulti // Return false to not invoke end's callback. return false } function handleRequestResponse (error, response, body) { var result = {} var status var data var type // Handle pure error if (error && !response) { result.error = error if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Handle No Response... // This is weird. if (!response) { console.log('This is odd, report this action / request to: http://github.com/mashape/unirest-nodejs') result.error = { message: 'No response found.' } if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Create response reference result = response // Create response status reference status = response.statusCode // Normalize MSIE response to HTTP 204 status = (status === 1223 ? 204 : status) // Obtain status range typecode (1, 2, 3, 4, 5, etc.) type = status / 100 | 0 // Generate sugar helper properties for status information result.code = status result.status = status result.statusType = type result.info = type === 1 result.ok = type === 2 result.clientError = type === 4 result.serverError = type === 5 result.error = (type === 4 || type === 5) ? (function generateErrorMessage () { var msg = 'got ' + result.status + ' response' var err = new Error(msg) err.status = result.status return err })() : false // Iterate over Response Status Codes and generate more sugar for (var name in Unirest.Response.statusCodes) { result[name] = Unirest.Response.statusCodes[name] === status } // Cookie Holder result.cookies = {} // Cookie Sugar Method result.cookie = function (name) { return result.cookies[name] } function setCookie (cookie) { var crumbs = Unirest.trim(cookie).split('=') var key = Unirest.trim(crumbs[0]) var value = Unirest.trim(crumbs.slice(1).join('=')) if (crumbs[0] && crumbs[0] !== '') { result.cookies[key] = value === '' ? true : value } } if (response.cookies && is(response.cookies).a(Object) && Object.keys(response.cookies).length > 0) { result.cookies = response.cookies } else { // Handle cookies to be set var cookies = response.headers['set-cookie'] if (cookies && is(cookies).a(Array)) { for (var index = 0; index < cookies.length; index++) { var entry = cookies[index] if (is(entry).a(String) && does(entry).contain(';')) { entry.split(';').forEach(setCookie) } } } // Handle cookies that have been set cookies = response.headers.cookie if (cookies && is(cookies).a(String)) { cookies.split(';').forEach(setCookie) } } // Obtain response body body = body || response.body result.raw_body = body result.headers = response.headers // Handle Response Body if (body) { type = Unirest.type(result.headers['content-type'], true) if (type) data = Unirest.Response.parse(body, type) else data = body } result.body = data ;(handleRetriableRequestResponse(result)) && (callback) && callback(result) } function handleGZIPResponse (response) { if (/^(deflate|gzip)$/.test(response.headers['content-encoding'])) { var unzip = zlib.createUnzip() var stream = new Stream() var _on = response.on var decoder // Keeping node happy stream.req = response.req // Make sure we emit prior to processing unzip.on('error', function (error) { // Catch the parser error when there is no content if (error.errno === zlib.Z_BUF_ERROR || error.errno === zlib.Z_DATA_ERROR) { stream.emit('end') return } stream.emit('error', error) }) // Start the processing response.pipe(unzip) // Ensure encoding is captured response.setEncoding = function (type) { decoder = new StringDecoder(type) } // Capture decompression and decode with captured encoding unzip.on('data', function (buffer) { if (!decoder) return stream.emit('data', buffer) var string = decoder.write(buffer) if (string.length) stream.emit('data', string) }) // Emit yoself unzip.on('end', function () { stream.emit('end') }) response.on = function (type, next) { if (type === 'data' || type === 'end') { stream.on(type, next) } else if (type === 'error') { _on.call(response, type, next) } else { _on.call(response, type, next) } } } } function handleFormData (form) { for (var i = 0; i < $this._multipart.length; i++) { var item = $this._multipart[i] if (item.attachment && is(item.value).a(String)) { if (does(item.value).contain('http://') || does(item.value).contain('https://')) { item.value = Unirest.request(item.value) } else { item.value = fs.createReadStream(path.resolve(item.value)) } } form.append(item.name, item.value, item.options) } return form } if ($this._multipart.length && !$this._stream) { header = $this.options.headers[$this.hasHeader('content-type')] parts = URL.parse($this.options.url) form = new FormData() if (header) { $this.options.headers['content-type'] = header.split(';')[0] + '; boundary=' + form.getBoundary() } else { $this.options.headers['content-type'] = 'multipart/form-data; boundary=' + form.getBoundary() } function authn(auth) { if (!auth) return null; if (typeof auth === 'string') return auth; if (auth.user && auth.pass) return auth.user + ':' + auth.pass; return auth; } return handleFormData(form).submit({ protocol: parts.protocol, port: parts.port, // Formdata doesn't expect port to be included with host // so we use hostname rather than host host: parts.hostname, path: parts.path, method: $this.options.method, headers: $this.options.headers, auth: authn($this.options.auth || parts.auth) }, function (error, response) { var decoder = new StringDecoder('utf8') if (error) { return handleRequestResponse(error, response) } if (!response.body) { response.body = '' } // Node 10+ response.resume() // GZIP, Feel me? handleGZIPResponse(response) // Fallback response.on('data', function (chunk) { if (typeof chunk === 'string') response.body += chunk else response.body += decoder.write(chunk) }) // After all, we end up here response.on('end', function () { return handleRequestResponse(error, response) }) }) } Request = Unirest.request($this.options, handleRequestResponse) Request.on('response', handleGZIPResponse) if ($this._multipart.length && $this._stream) { handleFormData(Request.form()) } return Request } } /** * Alias for _.header_ * @type {Function} */ $this.headers = $this.header /** * Alias for _.header_ * * @type {Function} */ $this.set = $this.header /** * Alias for _.end_ * * @type {Function} */ $this.complete = $this.end /** * Aliases for _.end_ * * @type {Object} */ $this.as = { json: $this.end, binary: $this.end, string: $this.end } /** * Handles Multipart Field Processing * * @param {String} name * @param {Mixed} value * @param {Object} options */ function handleField (name, value, options) { var serialized var length var key var i options = options || { attachment: false } if (is(name).a(Object)) { for (key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) { handleField(key, name[key], options) } } } else { if (is(value).a(Array)) { for (i = 0, length = value.length; i < length; i++) { serialized = handleFieldValue(value[i]) if (serialized) { $this.rawField(name, serialized, options) } } } else if (value != null) { $this.rawField(name, handleFieldValue(value), options) } } return $this } /** * Handles Multipart Value Processing * * @param {Mixed} value */ function handleFieldValue (value) { if (!(value instanceof Buffer || typeof value === 'string')) { if (is(value).a(Object)) { if (value instanceof fs.FileReadStream) { return value } else { return Unirest.serializers.json(value) } } else { return value.toString() } } else return value } function setupOption (name, ref) { $this[name] = function (arg) { $this.options[ref || name] = arg return $this } } // Iterates over a list of option methods to generate the chaining // style of use you see in Superagent and jQuery. for (var x in Unirest.enum.options) { if (Object.prototype.hasOwnProperty.call(Unirest.enum.options, x)) { var option = Unirest.enum.options[x] var reference = null if (option.indexOf(':') > -1) { option = option.split(':') reference = option[1] option = option[0] } setupOption(option, reference) } } if (headers && typeof headers === 'function') { callback = headers headers = null } else if (body && typeof body === 'function') { callback = body body = null } if (headers) $this.set(headers) if (body) $this.send(body) return callback ? $this.end(callback) : $this } return uri ? unirest(uri, headers, body, callback) : unirest }
Initialize our Rest Container @type {Object}
Unirest
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
unirest = function (uri, headers, body, callback) { var $this = { /** * Stream Multipart form-data request * * @type {Boolean} */ _stream: false, /** * Container to hold multipart form data for processing upon request. * * @type {Array} * @private */ _multipart: [], /** * Container to hold form data for processing upon request. * * @type {Array} * @private */ _form: [], /** * Request option container for details about the request. * * @type {Object} */ options: { /** * Url obtained from request method arguments. * * @type {String} */ url: uri, /** * Method obtained from request method arguments. * * @type {String} */ method: method, /** * List of headers with case-sensitive fields. * * @type {Object} */ headers: {} }, hasHeader: function (name) { var headers var lowercaseHeaders name = name.toLowerCase() headers = Object.keys($this.options.headers) lowercaseHeaders = headers.map(function (header) { return header.toLowerCase() }) for (var i = 0; i < lowercaseHeaders.length; i++) { if (lowercaseHeaders[i] === name) { return headers[i] } } return false }, /** * Turn on multipart-form streaming * * @return {Object} */ stream: function () { $this._stream = true return this }, /** * Attaches a field to the multipart-form request, with pre-processing. * * @param {String} name * @param {String} value * @return {Object} */ field: function (name, value, options) { return handleField(name, value, options) }, /** * Attaches a file to the multipart-form request. * * @param {String} name * @param {String|Object} path * @return {Object} */ attach: function (name, path, options) { options = options || {} options.attachment = true return handleField(name, path, options) }, /** * Attaches field to the multipart-form request, with no pre-processing. * * @param {String} name * @param {String|Object} path * @param {Object} options * @return {Object} */ rawField: function (name, value, options) { $this._multipart.push({ name: name, value: value, options: options, attachment: options.attachment || false }) }, /** * Basic Header Authentication Method * * Supports user being an Object to reflect Request * Supports user, password to reflect SuperAgent * * @param {String|Object} user * @param {String} password * @param {Boolean} sendImmediately * @return {Object} */ auth: function (user, password, sendImmediately) { $this.options.auth = (is(user).a(Object)) ? user : { user: user, password: password, sendImmediately: sendImmediately } return $this }, /** * Sets header field to value * * @param {String} field Header field * @param {String} value Header field value * @return {Object} */ header: function (field, value) { if (is(field).a(Object)) { for (var key in field) { if (Object.prototype.hasOwnProperty.call(field, key)) { $this.header(key, field[key]) } } return $this } var existingHeaderName = $this.hasHeader(field) $this.options.headers[existingHeaderName || field] = value return $this }, /** * Serialize value as querystring representation, and append or set on `Request.options.url` * * @param {String|Object} value * @return {Object} */ query: function (value) { if (is(value).a(Object)) value = Unirest.serializers.form(value) if (!value.length) return $this $this.options.url += (does($this.options.url).contain('?') ? '&' : '?') + value return $this }, /** * Set _content-type_ header with type passed through `mime.getType()` when necessary. * * @param {String} type * @return {Object} */ type: function (type) { $this.header('Content-Type', does(type).contain('/') ? type : mime.getType(type)) return $this }, /** * Data marshalling for HTTP request body data * * Determines whether type is `form` or `json`. * For irregular mime-types the `.type()` method is used to infer the `content-type` header. * * When mime-type is `application/x-www-form-urlencoded` data is appended rather than overwritten. * * @param {Mixed} data * @return {Object} */ send: function (data) { var type = $this.options.headers[$this.hasHeader('content-type')] if ((is(data).a(Object) || is(data).a(Array)) && !Buffer.isBuffer(data)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] $this.options.body = Unirest.serializers.form(data) } else if (~type.indexOf('json')) { $this.options.json = true if ($this.options.body && is($this.options.body).a(Object)) { for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { $this.options.body[key] = data[key] } } } else { $this.options.body = data } } else { $this.options.body = Unirest.Request.serialize(data, type) } } else if (is(data).a(String)) { if (!type) { $this.type('form') type = $this.options.headers[$this.hasHeader('content-type')] } if (type === 'application/x-www-form-urlencoded') { $this.options.body = $this.options.body ? $this.options.body + '&' + data : data } else { $this.options.body = ($this.options.body || '') + data } } else { $this.options.body = data } return $this }, /** * Takes multipart options and places them on `options.multipart` array. * Transforms body when an `Object` or _content-type_ is present. * * Example: * * Unirest.get('http://google.com').part({ * 'content-type': 'application/json', * body: { * phrase: 'Hello' * } * }).part({ * 'content-type': 'application/json', * body: { * phrase: 'World' * } * }).end(function (response) {}) * * @param {Object|String} options When an Object, headers should be placed directly on the object, * not under a child property. * @return {Object} */ part: function (options) { if (!$this._multipart) { $this.options.multipart = [] } if (is(options).a(Object)) { if (options['content-type']) { var type = Unirest.type(options['content-type'], true) if (type) options.body = Unirest.Response.parse(options.body) } else { if (is(options.body).a(Object)) { options.body = Unirest.serializers.json(options.body) } } $this.options.multipart.push(options) } else { $this.options.multipart.push({ body: options }) } return $this }, /** * Instructs the Request to be retried if specified error status codes (4xx, 5xx, ETIMEDOUT) are returned. * Retries are delayed with an exponential backoff. * * @param {(err: Error) => boolean} [callback] - Invoked on response error. Return false to stop next request. * @param {Object} [options] - Optional retry configuration to override defaults. * @param {number} [options.attempts=3] - The number of retry attempts. * @param {number} [options.delayInMs=250] - The delay in milliseconds (delayInMs *= delayMulti) * @param {number} [options.delayMulti=2] - The multiplier of delayInMs after each attempt. * @param {Array<string|number>} [options.statusCodes=["ETIMEDOUT", "5xx"]] - The status codes to retry on. * @return {Object} */ retry: function (callback, options) { $this.options.retry = { callback: typeof callback === "function" ? callback : null, attempts: options && +options.attempts || 3, delayInMs: options && +options.delayInMs || 250, delayMulti: options && +options.delayMulti || 2, statusCodes: (options && options.statusCodes || ["ETIMEDOUT", "5xx"]).slice(0) }; return $this }, /** * Proxies the call to end. This adds support for using promises as well as async/await. * * @param {Function} callback * @return {Promise} **/ then: function (callback) { return new Promise((resolve, reject) => { this.end(result => { try { resolve(callback(result)) } catch (err) { reject(err) } }) }) }, /** * Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. * Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. * * @param {Function} callback * @return {Object} */ end: function (callback) { var self = this var Request var header var parts var form function handleRetriableRequestResponse (result) { // If retries is not defined or all attempts tried, return true to invoke end's callback. if ($this.options.retry === undefined || $this.options.retry.attempts === 0) { return true } // If status code is not listed, abort with return true to invoke end's callback. var isStatusCodeDefined = (function (code, codes) { if (codes.indexOf(code) !== -1) { return true } return codes.reduce(function (p, c) { return p || String(code).split("").every(function (ch, i) { return ch === "x" || ch === c[i] }) }, false) }(result.code || result.error && result.error.code, $this.options.retry.statusCodes)) if (!isStatusCodeDefined) { return true } if ($this.options.retry.callback) { var isContinue = $this.options.retry.callback(result) // If retry callback returns false, stop retries and invoke end's callback. if (isContinue === false) { return true; } } setTimeout(function () { self.end(callback) }, $this.options.retry.delayInMs) $this.options.retry.attempts-- $this.options.retry.delayInMs *= $this.options.retry.delayMulti // Return false to not invoke end's callback. return false } function handleRequestResponse (error, response, body) { var result = {} var status var data var type // Handle pure error if (error && !response) { result.error = error if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Handle No Response... // This is weird. if (!response) { console.log('This is odd, report this action / request to: http://github.com/mashape/unirest-nodejs') result.error = { message: 'No response found.' } if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Create response reference result = response // Create response status reference status = response.statusCode // Normalize MSIE response to HTTP 204 status = (status === 1223 ? 204 : status) // Obtain status range typecode (1, 2, 3, 4, 5, etc.) type = status / 100 | 0 // Generate sugar helper properties for status information result.code = status result.status = status result.statusType = type result.info = type === 1 result.ok = type === 2 result.clientError = type === 4 result.serverError = type === 5 result.error = (type === 4 || type === 5) ? (function generateErrorMessage () { var msg = 'got ' + result.status + ' response' var err = new Error(msg) err.status = result.status return err })() : false // Iterate over Response Status Codes and generate more sugar for (var name in Unirest.Response.statusCodes) { result[name] = Unirest.Response.statusCodes[name] === status } // Cookie Holder result.cookies = {} // Cookie Sugar Method result.cookie = function (name) { return result.cookies[name] } function setCookie (cookie) { var crumbs = Unirest.trim(cookie).split('=') var key = Unirest.trim(crumbs[0]) var value = Unirest.trim(crumbs.slice(1).join('=')) if (crumbs[0] && crumbs[0] !== '') { result.cookies[key] = value === '' ? true : value } } if (response.cookies && is(response.cookies).a(Object) && Object.keys(response.cookies).length > 0) { result.cookies = response.cookies } else { // Handle cookies to be set var cookies = response.headers['set-cookie'] if (cookies && is(cookies).a(Array)) { for (var index = 0; index < cookies.length; index++) { var entry = cookies[index] if (is(entry).a(String) && does(entry).contain(';')) { entry.split(';').forEach(setCookie) } } } // Handle cookies that have been set cookies = response.headers.cookie if (cookies && is(cookies).a(String)) { cookies.split(';').forEach(setCookie) } } // Obtain response body body = body || response.body result.raw_body = body result.headers = response.headers // Handle Response Body if (body) { type = Unirest.type(result.headers['content-type'], true) if (type) data = Unirest.Response.parse(body, type) else data = body } result.body = data ;(handleRetriableRequestResponse(result)) && (callback) && callback(result) } function handleGZIPResponse (response) { if (/^(deflate|gzip)$/.test(response.headers['content-encoding'])) { var unzip = zlib.createUnzip() var stream = new Stream() var _on = response.on var decoder // Keeping node happy stream.req = response.req // Make sure we emit prior to processing unzip.on('error', function (error) { // Catch the parser error when there is no content if (error.errno === zlib.Z_BUF_ERROR || error.errno === zlib.Z_DATA_ERROR) { stream.emit('end') return } stream.emit('error', error) }) // Start the processing response.pipe(unzip) // Ensure encoding is captured response.setEncoding = function (type) { decoder = new StringDecoder(type) } // Capture decompression and decode with captured encoding unzip.on('data', function (buffer) { if (!decoder) return stream.emit('data', buffer) var string = decoder.write(buffer) if (string.length) stream.emit('data', string) }) // Emit yoself unzip.on('end', function () { stream.emit('end') }) response.on = function (type, next) { if (type === 'data' || type === 'end') { stream.on(type, next) } else if (type === 'error') { _on.call(response, type, next) } else { _on.call(response, type, next) } } } } function handleFormData (form) { for (var i = 0; i < $this._multipart.length; i++) { var item = $this._multipart[i] if (item.attachment && is(item.value).a(String)) { if (does(item.value).contain('http://') || does(item.value).contain('https://')) { item.value = Unirest.request(item.value) } else { item.value = fs.createReadStream(path.resolve(item.value)) } } form.append(item.name, item.value, item.options) } return form } if ($this._multipart.length && !$this._stream) { header = $this.options.headers[$this.hasHeader('content-type')] parts = URL.parse($this.options.url) form = new FormData() if (header) { $this.options.headers['content-type'] = header.split(';')[0] + '; boundary=' + form.getBoundary() } else { $this.options.headers['content-type'] = 'multipart/form-data; boundary=' + form.getBoundary() } function authn(auth) { if (!auth) return null; if (typeof auth === 'string') return auth; if (auth.user && auth.pass) return auth.user + ':' + auth.pass; return auth; } return handleFormData(form).submit({ protocol: parts.protocol, port: parts.port, // Formdata doesn't expect port to be included with host // so we use hostname rather than host host: parts.hostname, path: parts.path, method: $this.options.method, headers: $this.options.headers, auth: authn($this.options.auth || parts.auth) }, function (error, response) { var decoder = new StringDecoder('utf8') if (error) { return handleRequestResponse(error, response) } if (!response.body) { response.body = '' } // Node 10+ response.resume() // GZIP, Feel me? handleGZIPResponse(response) // Fallback response.on('data', function (chunk) { if (typeof chunk === 'string') response.body += chunk else response.body += decoder.write(chunk) }) // After all, we end up here response.on('end', function () { return handleRequestResponse(error, response) }) }) } Request = Unirest.request($this.options, handleRequestResponse) Request.on('response', handleGZIPResponse) if ($this._multipart.length && $this._stream) { handleFormData(Request.form()) } return Request } } /** * Alias for _.header_ * @type {Function} */ $this.headers = $this.header /** * Alias for _.header_ * * @type {Function} */ $this.set = $this.header /** * Alias for _.end_ * * @type {Function} */ $this.complete = $this.end /** * Aliases for _.end_ * * @type {Object} */ $this.as = { json: $this.end, binary: $this.end, string: $this.end } /** * Handles Multipart Field Processing * * @param {String} name * @param {Mixed} value * @param {Object} options */ function handleField (name, value, options) { var serialized var length var key var i options = options || { attachment: false } if (is(name).a(Object)) { for (key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) { handleField(key, name[key], options) } } } else { if (is(value).a(Array)) { for (i = 0, length = value.length; i < length; i++) { serialized = handleFieldValue(value[i]) if (serialized) { $this.rawField(name, serialized, options) } } } else if (value != null) { $this.rawField(name, handleFieldValue(value), options) } } return $this } /** * Handles Multipart Value Processing * * @param {Mixed} value */ function handleFieldValue (value) { if (!(value instanceof Buffer || typeof value === 'string')) { if (is(value).a(Object)) { if (value instanceof fs.FileReadStream) { return value } else { return Unirest.serializers.json(value) } } else { return value.toString() } } else return value } function setupOption (name, ref) { $this[name] = function (arg) { $this.options[ref || name] = arg return $this } } // Iterates over a list of option methods to generate the chaining // style of use you see in Superagent and jQuery. for (var x in Unirest.enum.options) { if (Object.prototype.hasOwnProperty.call(Unirest.enum.options, x)) { var option = Unirest.enum.options[x] var reference = null if (option.indexOf(':') > -1) { option = option.split(':') reference = option[1] option = option[0] } setupOption(option, reference) } } if (headers && typeof headers === 'function') { callback = headers headers = null } else if (body && typeof body === 'function') { callback = body body = null } if (headers) $this.set(headers) if (body) $this.send(body) return callback ? $this.end(callback) : $this }
Initialize our Rest Container @type {Object}
unirest
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleRetriableRequestResponse (result) { // If retries is not defined or all attempts tried, return true to invoke end's callback. if ($this.options.retry === undefined || $this.options.retry.attempts === 0) { return true } // If status code is not listed, abort with return true to invoke end's callback. var isStatusCodeDefined = (function (code, codes) { if (codes.indexOf(code) !== -1) { return true } return codes.reduce(function (p, c) { return p || String(code).split("").every(function (ch, i) { return ch === "x" || ch === c[i] }) }, false) }(result.code || result.error && result.error.code, $this.options.retry.statusCodes)) if (!isStatusCodeDefined) { return true } if ($this.options.retry.callback) { var isContinue = $this.options.retry.callback(result) // If retry callback returns false, stop retries and invoke end's callback. if (isContinue === false) { return true; } } setTimeout(function () { self.end(callback) }, $this.options.retry.delayInMs) $this.options.retry.attempts-- $this.options.retry.delayInMs *= $this.options.retry.delayMulti // Return false to not invoke end's callback. return false }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
handleRetriableRequestResponse
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleRequestResponse (error, response, body) { var result = {} var status var data var type // Handle pure error if (error && !response) { result.error = error if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Handle No Response... // This is weird. if (!response) { console.log('This is odd, report this action / request to: http://github.com/mashape/unirest-nodejs') result.error = { message: 'No response found.' } if (handleRetriableRequestResponse(result) && callback) { callback(result) } return } // Create response reference result = response // Create response status reference status = response.statusCode // Normalize MSIE response to HTTP 204 status = (status === 1223 ? 204 : status) // Obtain status range typecode (1, 2, 3, 4, 5, etc.) type = status / 100 | 0 // Generate sugar helper properties for status information result.code = status result.status = status result.statusType = type result.info = type === 1 result.ok = type === 2 result.clientError = type === 4 result.serverError = type === 5 result.error = (type === 4 || type === 5) ? (function generateErrorMessage () { var msg = 'got ' + result.status + ' response' var err = new Error(msg) err.status = result.status return err })() : false // Iterate over Response Status Codes and generate more sugar for (var name in Unirest.Response.statusCodes) { result[name] = Unirest.Response.statusCodes[name] === status } // Cookie Holder result.cookies = {} // Cookie Sugar Method result.cookie = function (name) { return result.cookies[name] } function setCookie (cookie) { var crumbs = Unirest.trim(cookie).split('=') var key = Unirest.trim(crumbs[0]) var value = Unirest.trim(crumbs.slice(1).join('=')) if (crumbs[0] && crumbs[0] !== '') { result.cookies[key] = value === '' ? true : value } } if (response.cookies && is(response.cookies).a(Object) && Object.keys(response.cookies).length > 0) { result.cookies = response.cookies } else { // Handle cookies to be set var cookies = response.headers['set-cookie'] if (cookies && is(cookies).a(Array)) { for (var index = 0; index < cookies.length; index++) { var entry = cookies[index] if (is(entry).a(String) && does(entry).contain(';')) { entry.split(';').forEach(setCookie) } } } // Handle cookies that have been set cookies = response.headers.cookie if (cookies && is(cookies).a(String)) { cookies.split(';').forEach(setCookie) } } // Obtain response body body = body || response.body result.raw_body = body result.headers = response.headers // Handle Response Body if (body) { type = Unirest.type(result.headers['content-type'], true) if (type) data = Unirest.Response.parse(body, type) else data = body } result.body = data ;(handleRetriableRequestResponse(result)) && (callback) && callback(result) }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
handleRequestResponse
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function setCookie (cookie) { var crumbs = Unirest.trim(cookie).split('=') var key = Unirest.trim(crumbs[0]) var value = Unirest.trim(crumbs.slice(1).join('=')) if (crumbs[0] && crumbs[0] !== '') { result.cookies[key] = value === '' ? true : value } }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
setCookie
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleGZIPResponse (response) { if (/^(deflate|gzip)$/.test(response.headers['content-encoding'])) { var unzip = zlib.createUnzip() var stream = new Stream() var _on = response.on var decoder // Keeping node happy stream.req = response.req // Make sure we emit prior to processing unzip.on('error', function (error) { // Catch the parser error when there is no content if (error.errno === zlib.Z_BUF_ERROR || error.errno === zlib.Z_DATA_ERROR) { stream.emit('end') return } stream.emit('error', error) }) // Start the processing response.pipe(unzip) // Ensure encoding is captured response.setEncoding = function (type) { decoder = new StringDecoder(type) } // Capture decompression and decode with captured encoding unzip.on('data', function (buffer) { if (!decoder) return stream.emit('data', buffer) var string = decoder.write(buffer) if (string.length) stream.emit('data', string) }) // Emit yoself unzip.on('end', function () { stream.emit('end') }) response.on = function (type, next) { if (type === 'data' || type === 'end') { stream.on(type, next) } else if (type === 'error') { _on.call(response, type, next) } else { _on.call(response, type, next) } } } }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
handleGZIPResponse
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleFormData (form) { for (var i = 0; i < $this._multipart.length; i++) { var item = $this._multipart[i] if (item.attachment && is(item.value).a(String)) { if (does(item.value).contain('http://') || does(item.value).contain('https://')) { item.value = Unirest.request(item.value) } else { item.value = fs.createReadStream(path.resolve(item.value)) } } form.append(item.name, item.value, item.options) } return form }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
handleFormData
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function authn(auth) { if (!auth) return null; if (typeof auth === 'string') return auth; if (auth.user && auth.pass) return auth.user + ':' + auth.pass; return auth; }
Sends HTTP Request and awaits Response finalization. Request compression and Response decompression occurs here. Upon HTTP Response post-processing occurs and invokes `callback` with a single argument, the `[Response](#response)` object. @param {Function} callback @return {Object}
authn
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleField (name, value, options) { var serialized var length var key var i options = options || { attachment: false } if (is(name).a(Object)) { for (key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) { handleField(key, name[key], options) } } } else { if (is(value).a(Array)) { for (i = 0, length = value.length; i < length; i++) { serialized = handleFieldValue(value[i]) if (serialized) { $this.rawField(name, serialized, options) } } } else if (value != null) { $this.rawField(name, handleFieldValue(value), options) } } return $this }
Handles Multipart Field Processing @param {String} name @param {Mixed} value @param {Object} options
handleField
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function handleFieldValue (value) { if (!(value instanceof Buffer || typeof value === 'string')) { if (is(value).a(Object)) { if (value instanceof fs.FileReadStream) { return value } else { return Unirest.serializers.json(value) } } else { return value.toString() } } else return value }
Handles Multipart Value Processing @param {Mixed} value
handleFieldValue
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function setupOption (name, ref) { $this[name] = function (arg) { $this.options[ref || name] = arg return $this } }
Handles Multipart Value Processing @param {Mixed} value
setupOption
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function setupMethod (method) { Unirest[method] = Unirest(method) }
Generate sugar for request library. This allows us to mock super-agent chaining style while using request library under the hood.
setupMethod
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function is (value) { return { a: function (check) { if (check.prototype) check = check.prototype.constructor.name var type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase() return value != null && type === check.toLowerCase() } } }
Simple Utility Methods for checking information about a value. @param {Mixed} value Could be anything. @return {Object}
is
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function does (value) { var arrayIndexOf = (Array.indexOf ? function (arr, obj, from) { return arr.indexOf(obj, from) } : function (arr, obj, from) { var l = arr.length var i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0 i = i < 0 ? 0 : i for (; i < l; i++) if (i in arr && arr[i] === obj) return i return -1 }) return { startWith: function (string) { if (is(value).a(String)) return value.slice(0, string.length) === string if (is(value).a(Array)) return value[0] === string return false }, endWith: function (string) { if (is(value).a(String)) return value.slice(-string.length) === string if (is(value).a(Array)) return value[value.length - 1] === string return false }, contain: function (field) { if (is(value).a(String)) return value.indexOf(field) > -1 if (is(value).a(Object)) return Object.prototype.hasOwnProperty.call(value, field) if (is(value).a(Array)) return !!~arrayIndexOf(value, field) return false } } }
Simple Utility Methods for checking information about a value. @param {Mixed} value Could be anything. @return {Object}
does
javascript
Kong/unirest-nodejs
index.js
https://github.com/Kong/unirest-nodejs/blob/master/index.js
MIT
function getLogLevel(level, action, payload, type) { switch (typeof level) { case 'object': return typeof level[type] === 'function' ? level[type](...payload) : level[type]; case 'function': return level(action); default: return level; } }
Get log level string based on supplied params @param {string | function | object} level - console[level] @param {object} action - selected action @param {array} payload - selected payload @param {string} type - log entry type @returns {string} level
getLogLevel
javascript
LogRocket/redux-logger
src/core.js
https://github.com/LogRocket/redux-logger/blob/master/src/core.js
MIT
function defaultTitleFormatter(options) { const { timestamp, duration } = options; return (action, time, took) => { const parts = ['action']; parts.push(`%c${String(action.type)}`); if (timestamp) parts.push(`%c@ ${time}`); if (duration) parts.push(`%c(in ${took.toFixed(2)} ms)`); return parts.join(' '); }; }
Get log level string based on supplied params @param {string | function | object} level - console[level] @param {object} action - selected action @param {array} payload - selected payload @param {string} type - log entry type @returns {string} level
defaultTitleFormatter
javascript
LogRocket/redux-logger
src/core.js
https://github.com/LogRocket/redux-logger/blob/master/src/core.js
MIT
function createLogger(options = {}) { const loggerOptions = Object.assign({}, defaults, options); const { logger, stateTransformer, errorTransformer, predicate, logErrors, diffPredicate, } = loggerOptions; // Return if 'console' object is not defined if (typeof logger === 'undefined') { return () => next => action => next(action); } // Detect if 'createLogger' was passed directly to 'applyMiddleware'. if (options.getState && options.dispatch) { // eslint-disable-next-line no-console console.error(`[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware: // Logger with default options import { logger } from 'redux-logger' const store = createStore( reducer, applyMiddleware(logger) ) // Or you can create your own logger with custom options http://bit.ly/redux-logger-options import { createLogger } from 'redux-logger' const logger = createLogger({ // ...options }); const store = createStore( reducer, applyMiddleware(logger) ) `); return () => next => action => next(action); } const logBuffer = []; return ({ getState }) => next => (action) => { // Exit early if predicate function returns 'false' if (typeof predicate === 'function' && !predicate(getState, action)) { return next(action); } const logEntry = {}; logBuffer.push(logEntry); logEntry.started = timer.now(); logEntry.startedTime = new Date(); logEntry.prevState = stateTransformer(getState()); logEntry.action = action; let returnedValue; if (logErrors) { try { returnedValue = next(action); } catch (e) { logEntry.error = errorTransformer(e); } } else { returnedValue = next(action); } logEntry.took = timer.now() - logEntry.started; logEntry.nextState = stateTransformer(getState()); const diff = loggerOptions.diff && typeof diffPredicate === 'function' ? diffPredicate(getState, action) : loggerOptions.diff; printBuffer(logBuffer, Object.assign({}, loggerOptions, { diff })); logBuffer.length = 0; if (logEntry.error) throw logEntry.error; return returnedValue; }; }
Creates logger with following options @namespace @param {object} options - options for logger @param {string | function | object} options.level - console[level] @param {boolean} options.duration - print duration of each action? @param {boolean} options.timestamp - print timestamp with each action? @param {object} options.colors - custom colors @param {object} options.logger - implementation of the `console` API @param {boolean} options.logErrors - should errors in action execution be caught, logged, and re-thrown? @param {boolean} options.collapsed - is group collapsed? @param {boolean} options.predicate - condition which resolves logger behavior @param {function} options.stateTransformer - transform state before print @param {function} options.actionTransformer - transform action before print @param {function} options.errorTransformer - transform error before print @returns {function} logger middleware
createLogger
javascript
LogRocket/redux-logger
src/index.js
https://github.com/LogRocket/redux-logger/blob/master/src/index.js
MIT
defaultLogger = ({ dispatch, getState } = {}) => { if (typeof dispatch === 'function' || typeof getState === 'function') { return createLogger()({ dispatch, getState }); } // eslint-disable-next-line no-console console.error(` [redux-logger v3] BREAKING CHANGE [redux-logger v3] Since 3.0.0 redux-logger exports by default logger with default settings. [redux-logger v3] Change [redux-logger v3] import createLogger from 'redux-logger' [redux-logger v3] to [redux-logger v3] import { createLogger } from 'redux-logger' `); }
Creates logger with following options @namespace @param {object} options - options for logger @param {string | function | object} options.level - console[level] @param {boolean} options.duration - print duration of each action? @param {boolean} options.timestamp - print timestamp with each action? @param {object} options.colors - custom colors @param {object} options.logger - implementation of the `console` API @param {boolean} options.logErrors - should errors in action execution be caught, logged, and re-thrown? @param {boolean} options.collapsed - is group collapsed? @param {boolean} options.predicate - condition which resolves logger behavior @param {function} options.stateTransformer - transform state before print @param {function} options.actionTransformer - transform action before print @param {function} options.errorTransformer - transform error before print @returns {function} logger middleware
defaultLogger
javascript
LogRocket/redux-logger
src/index.js
https://github.com/LogRocket/redux-logger/blob/master/src/index.js
MIT
defaultLogger = ({ dispatch, getState } = {}) => { if (typeof dispatch === 'function' || typeof getState === 'function') { return createLogger()({ dispatch, getState }); } // eslint-disable-next-line no-console console.error(` [redux-logger v3] BREAKING CHANGE [redux-logger v3] Since 3.0.0 redux-logger exports by default logger with default settings. [redux-logger v3] Change [redux-logger v3] import createLogger from 'redux-logger' [redux-logger v3] to [redux-logger v3] import { createLogger } from 'redux-logger' `); }
Creates logger with following options @namespace @param {object} options - options for logger @param {string | function | object} options.level - console[level] @param {boolean} options.duration - print duration of each action? @param {boolean} options.timestamp - print timestamp with each action? @param {object} options.colors - custom colors @param {object} options.logger - implementation of the `console` API @param {boolean} options.logErrors - should errors in action execution be caught, logged, and re-thrown? @param {boolean} options.collapsed - is group collapsed? @param {boolean} options.predicate - condition which resolves logger behavior @param {function} options.stateTransformer - transform state before print @param {function} options.actionTransformer - transform action before print @param {function} options.errorTransformer - transform error before print @returns {function} logger middleware
defaultLogger
javascript
LogRocket/redux-logger
src/index.js
https://github.com/LogRocket/redux-logger/blob/master/src/index.js
MIT
function broadcast(data, channel) { for (var client of server.clients) { if (channel ? client.channel === channel : client.channel) { send(data, client) } } }
Sends data to all clients channel: if not null, restricts broadcast to clients in the channel
broadcast
javascript
AndrewBelt/hack.chat
server.js
https://github.com/AndrewBelt/hack.chat/blob/master/server.js
MIT