Move core files to src folder and move JS files to TypeScript (#44405)

This commit is contained in:
Tim Neutkens 2023-01-03 10:05:50 +01:00 committed by GitHub
parent 00d7a35ed7
commit efcec4c1e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1267 changed files with 1052 additions and 960 deletions

View file

@ -11,9 +11,9 @@ examples/with-flow/**
examples/with-jest/** examples/with-jest/**
examples/with-mobx-state-tree/** examples/with-mobx-state-tree/**
examples/with-mobx/** examples/with-mobx/**
packages/next/bundles/webpack/packages/*.runtime.js packages/next/src/bundles/webpack/packages/*.runtime.js
packages/next/bundles/webpack/packages/lazy-compilation-*.js packages/next/src/bundles/webpack/packages/lazy-compilation-*.js
packages/next/compiled/**/* packages/next/src/compiled/**/*
packages/react-refresh-utils/**/*.js packages/react-refresh-utils/**/*.js
packages/react-dev-overlay/lib/** packages/react-dev-overlay/lib/**
**/__tmp__/** **/__tmp__/**

View file

@ -2,9 +2,9 @@ node_modules
**/.next/** **/.next/**
**/_next/** **/_next/**
**/dist/** **/dist/**
packages/next/bundles/webpack/packages/*.runtime.js packages/next/src/bundles/webpack/packages/*.runtime.js
packages/next/bundles/webpack/packages/lazy-compilation-*.js packages/next/src/bundles/webpack/packages/lazy-compilation-*.js
packages/next/compiled/** packages/next/src/compiled/**
packages/react-refresh-utils/**/*.js packages/react-refresh-utils/**/*.js
packages/react-refresh-utils/**/*.d.ts packages/react-refresh-utils/**/*.d.ts
packages/react-dev-overlay/lib/** packages/react-dev-overlay/lib/**

View file

@ -1,4 +0,0 @@
/* globals self */
var fetch = self.fetch.bind(self)
module.exports = fetch
module.exports.default = module.exports

View file

@ -1,13 +0,0 @@
export function isWasm(): Promise<boolean>
export function transform(src: string, options?: any): Promise<any>
export function transformSync(src: string, options?: any): any
export function minify(src: string, options: any): Promise<string>
export function minifySync(src: string, options: any): string
export function parse(src: string, options: any): any
export const lockfilePatchPromise: { cur?: Promise<void> }
export function initCustomTraceSubscriber(traceFileName?: string): void
export function teardownTraceSubscriber(): void
export function teardownCrashReporter(): void
export function loadBindings(): Promise<void>
export function __isCustomTurbopackBinary(): Promise<boolean>

View file

@ -1,7 +0,0 @@
export function getParserOptions(options: {
filename: string
jsConfig?: any
[key: string]: any
}): any
export function getJestSWCOptions(...args: any[]): any
export function getLoaderSWCOptions(...args: any[]): any

View file

@ -1 +0,0 @@
export default function formatWebpackMessages(json: any, verbose?: boolean): any

View file

@ -1,3 +0,0 @@
import m from 'path'
export = m

View file

@ -40,7 +40,7 @@ import {
import { getPageStaticInfo } from './analysis/get-page-static-info' import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { ServerRuntime } from '../types' import { ServerRuntime } from '../../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'

View file

@ -27,7 +27,7 @@ SOFTWARE.
export default new Proxy( export default new Proxy(
{}, {},
{ {
get: function getter(target, key) { get: function getter(_target, key) {
if (key === '__esModule') { if (key === '__esModule') {
return false return false
} }

View file

@ -0,0 +1,4 @@
/* globals self */
const fetchModule = self.fetch.bind(self)
module.exports = fetchModule
module.exports.default = module.exports

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import path from 'path' import path from 'path'
import { pathToFileURL } from 'url' import { pathToFileURL } from 'url'
import { platform, arch } from 'os' import { platform, arch } from 'os'
@ -7,7 +8,8 @@ import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure' import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile' import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadWasmSwc } from '../../lib/download-wasm-swc' import { downloadWasmSwc } from '../../lib/download-wasm-swc'
import { version as nextVersion } from 'next/package.json'
const nextVersion = process.env.__NEXT_VERSION as string
const ArchName = arch() const ArchName = arch()
const PlatformName = platform() const PlatformName = platform()
@ -23,7 +25,7 @@ const __INTERNAL_CUSTOM_TURBOPACK_BINARY =
process.env.__INTERNAL_CUSTOM_TURBOPACK_BINARY process.env.__INTERNAL_CUSTOM_TURBOPACK_BINARY
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS = const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS =
process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS
export const __isCustomTurbopackBinary = async () => { export const __isCustomTurbopackBinary = async (): Promise<boolean> => {
if ( if (
!!__INTERNAL_CUSTOM_TURBOPACK_BINARY && !!__INTERNAL_CUSTOM_TURBOPACK_BINARY &&
!!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS
@ -51,20 +53,20 @@ const knownDefaultWasmFallbackTriples = [
'i686-pc-windows-msvc', 'i686-pc-windows-msvc',
] ]
let nativeBindings let nativeBindings: any
let wasmBindings let wasmBindings: any
let downloadWasmPromise let downloadWasmPromise: any
let pendingBindings let pendingBindings: any
let swcTraceFlushGuard let swcTraceFlushGuard: any
let swcCrashReporterFlushGuard let swcCrashReporterFlushGuard: any
export const lockfilePatchPromise = {} export const lockfilePatchPromise: { cur?: Promise<void> } = {}
export async function loadBindings() { export async function loadBindings(): Promise<any> {
if (pendingBindings) { if (pendingBindings) {
return pendingBindings return pendingBindings
} }
const isCustomTurbopack = await __isCustomTurbopackBinary() const isCustomTurbopack = await __isCustomTurbopackBinary()
pendingBindings = new Promise(async (resolve, reject) => { pendingBindings = new Promise(async (resolve, _reject) => {
if (!lockfilePatchPromise.cur) { if (!lockfilePatchPromise.cur) {
// always run lockfile check once so that it gets patched // always run lockfile check once so that it gets patched
// even if it doesn't fail to load locally // even if it doesn't fail to load locally
@ -73,9 +75,9 @@ export async function loadBindings() {
) )
} }
let attempts = [] let attempts: any[] = []
const shouldLoadWasmFallbackFirst = triples.some( const shouldLoadWasmFallbackFirst = triples.some(
(triple) => (triple: any) =>
!!triple?.raw && knownDefaultWasmFallbackTriples.includes(triple.raw) !!triple?.raw && knownDefaultWasmFallbackTriples.includes(triple.raw)
) )
@ -105,9 +107,10 @@ export async function loadBindings() {
return pendingBindings return pendingBindings
} }
async function tryLoadWasmWithFallback(attempts) { async function tryLoadWasmWithFallback(attempts: any) {
try { try {
let bindings = await loadWasm() let bindings = await loadWasm()
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({ wasm: 'enabled' }) eventSwcLoadFailure({ wasm: 'enabled' })
return bindings return bindings
} catch (a) { } catch (a) {
@ -128,6 +131,7 @@ async function tryLoadWasmWithFallback(attempts) {
} }
await downloadWasmPromise await downloadWasmPromise
let bindings = await loadWasm(pathToFileURL(wasmDirectory).href) let bindings = await loadWasm(pathToFileURL(wasmDirectory).href)
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({ wasm: 'fallback' }) eventSwcLoadFailure({ wasm: 'fallback' })
// still log native load attempts so user is // still log native load attempts so user is
@ -142,7 +146,7 @@ async function tryLoadWasmWithFallback(attempts) {
} }
function loadBindingsSync() { function loadBindingsSync() {
let attempts = [] let attempts: any[] = []
try { try {
return loadNative() return loadNative()
} catch (a) { } catch (a) {
@ -160,7 +164,7 @@ function loadBindingsSync() {
let loggingLoadFailure = false let loggingLoadFailure = false
function logLoadFailure(attempts, triedWasm = false) { function logLoadFailure(attempts: any, triedWasm = false) {
// make sure we only emit the event and log the failure once // make sure we only emit the event and log the failure once
if (loggingLoadFailure) return if (loggingLoadFailure) return
loggingLoadFailure = true loggingLoadFailure = true
@ -169,6 +173,7 @@ function logLoadFailure(attempts, triedWasm = false) {
Log.warn(attempt) Log.warn(attempt)
} }
// @ts-expect-error TODO: this event has a wrong type.
eventSwcLoadFailure({ wasm: triedWasm ? 'failed' : undefined }) eventSwcLoadFailure({ wasm: triedWasm ? 'failed' : undefined })
.then(() => lockfilePatchPromise.cur || Promise.resolve()) .then(() => lockfilePatchPromise.cur || Promise.resolve())
.finally(() => { .finally(() => {
@ -203,29 +208,29 @@ async function loadWasm(importPath = '') {
// interface coereces to sync interfaces. // interface coereces to sync interfaces.
wasmBindings = { wasmBindings = {
isWasm: true, isWasm: true,
transform(src, options) { transform(src: string, options: any) {
// TODO: we can remove fallback to sync interface once new stable version of next-swc gets published (current v12.2) // TODO: we can remove fallback to sync interface once new stable version of next-swc gets published (current v12.2)
return bindings?.transform return bindings?.transform
? bindings.transform(src.toString(), options) ? bindings.transform(src.toString(), options)
: Promise.resolve(bindings.transformSync(src.toString(), options)) : Promise.resolve(bindings.transformSync(src.toString(), options))
}, },
transformSync(src, options) { transformSync(src: string, options: any) {
return bindings.transformSync(src.toString(), options) return bindings.transformSync(src.toString(), options)
}, },
minify(src, options) { minify(src: string, options: any) {
return bindings?.minify return bindings?.minify
? bindings.minify(src.toString(), options) ? bindings.minify(src.toString(), options)
: Promise.resolve(bindings.minifySync(src.toString(), options)) : Promise.resolve(bindings.minifySync(src.toString(), options))
}, },
minifySync(src, options) { minifySync(src: string, options: any) {
return bindings.minifySync(src.toString(), options) return bindings.minifySync(src.toString(), options)
}, },
parse(src, options) { parse(src: string, options: any) {
return bindings?.parse return bindings?.parse
? bindings.parse(src.toString(), options) ? bindings.parse(src.toString(), options)
: Promise.resolve(bindings.parseSync(src.toString(), options)) : Promise.resolve(bindings.parseSync(src.toString(), options))
}, },
parseSync(src, options) { parseSync(src: string, options: any) {
const astStr = bindings.parseSync(src.toString(), options) const astStr = bindings.parseSync(src.toString(), options)
return astStr return astStr
}, },
@ -241,12 +246,14 @@ async function loadWasm(importPath = '') {
}, },
}, },
mdx: { mdx: {
compile: (src, options) => bindings.mdxCompile(src, options), compile: (src: string, options: any) =>
compileSync: (src, options) => bindings.mdxCompileSync(src, options), bindings.mdxCompile(src, options),
compileSync: (src: string, options: any) =>
bindings.mdxCompileSync(src, options),
}, },
} }
return wasmBindings return wasmBindings
} catch (e) { } catch (e: any) {
// Only log attempts for loading wasm when loading as fallback // Only log attempts for loading wasm when loading as fallback
if (importPath) { if (importPath) {
if (e?.code === 'ERR_MODULE_NOT_FOUND') { if (e?.code === 'ERR_MODULE_NOT_FOUND') {
@ -268,8 +275,8 @@ function loadNative(isCustomTurbopack = false) {
return nativeBindings return nativeBindings
} }
let bindings let bindings: any
let attempts = [] let attempts: any[] = []
for (const triple of triples) { for (const triple of triples) {
try { try {
@ -285,7 +292,7 @@ function loadNative(isCustomTurbopack = false) {
try { try {
bindings = require(pkg) bindings = require(pkg)
break break
} catch (e) { } catch (e: any) {
if (e?.code === 'MODULE_NOT_FOUND') { if (e?.code === 'MODULE_NOT_FOUND') {
attempts.push(`Attempted to load ${pkg}, but it was not installed`) attempts.push(`Attempted to load ${pkg}, but it was not installed`)
} else { } else {
@ -312,7 +319,7 @@ function loadNative(isCustomTurbopack = false) {
nativeBindings = { nativeBindings = {
isWasm: false, isWasm: false,
transform(src, options) { transform(src: string, options: any) {
const isModule = const isModule =
typeof src !== undefined && typeof src !== undefined &&
typeof src !== 'string' && typeof src !== 'string' &&
@ -330,7 +337,7 @@ function loadNative(isCustomTurbopack = false) {
) )
}, },
transformSync(src, options) { transformSync(src: string, options: any) {
if (typeof src === undefined) { if (typeof src === undefined) {
throw new Error( throw new Error(
"transformSync doesn't implement reading the file from filesystem" "transformSync doesn't implement reading the file from filesystem"
@ -354,15 +361,15 @@ function loadNative(isCustomTurbopack = false) {
) )
}, },
minify(src, options) { minify(src: string, options: any) {
return bindings.minify(toBuffer(src), toBuffer(options ?? {})) return bindings.minify(toBuffer(src), toBuffer(options ?? {}))
}, },
minifySync(src, options) { minifySync(src: string, options: any) {
return bindings.minifySync(toBuffer(src), toBuffer(options ?? {})) return bindings.minifySync(toBuffer(src), toBuffer(options ?? {}))
}, },
parse(src, options) { parse(src: string, options: any) {
return bindings.parse(src, toBuffer(options ?? {})) return bindings.parse(src, toBuffer(options ?? {}))
}, },
@ -371,7 +378,7 @@ function loadNative(isCustomTurbopack = false) {
teardownTraceSubscriber: bindings.teardownTraceSubscriber, teardownTraceSubscriber: bindings.teardownTraceSubscriber,
teardownCrashReporter: bindings.teardownCrashReporter, teardownCrashReporter: bindings.teardownCrashReporter,
turbo: { turbo: {
startDev: (options) => { startDev: (options: any) => {
const devOptions = { const devOptions = {
...options, ...options,
noOpen: options.noOpen ?? true, noOpen: options.noOpen ?? true,
@ -386,7 +393,7 @@ function loadNative(isCustomTurbopack = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const spawn = require('next/dist/compiled/cross-spawn') const spawn = require('next/dist/compiled/cross-spawn')
const args = [] const args: any[] = []
Object.entries(devOptions).forEach(([key, value]) => { Object.entries(devOptions).forEach(([key, value]) => {
let cli_key = `--${key.replace( let cli_key = `--${key.replace(
@ -410,10 +417,10 @@ function loadNative(isCustomTurbopack = false) {
...process.env, ...process.env,
}, },
}) })
child.on('message', (message) => { child.on('message', (message: any) => {
console.log(message) console.log(message)
}) })
child.on('close', (code) => { child.on('close', (code: any) => {
if (code !== 0) { if (code !== 0) {
reject({ reject({
command: `${__INTERNAL_CUSTOM_TURBOPACK_BINARY} ${args.join( command: `${__INTERNAL_CUSTOM_TURBOPACK_BINARY} ${args.join(
@ -438,9 +445,9 @@ function loadNative(isCustomTurbopack = false) {
bindings.runTurboTracing(toBuffer({ exact: true, ...options })), bindings.runTurboTracing(toBuffer({ exact: true, ...options })),
}, },
mdx: { mdx: {
compile: (src, options) => compile: (src: string, options: any) =>
bindings.mdxCompile(src, toBuffer(options ?? {})), bindings.mdxCompile(src, toBuffer(options ?? {})),
compileSync: (src, options) => compileSync: (src: string, options: any) =>
bindings.mdxCompileSync(src, toBuffer(options ?? {})), bindings.mdxCompileSync(src, toBuffer(options ?? {})),
}, },
} }
@ -450,39 +457,41 @@ function loadNative(isCustomTurbopack = false) {
throw attempts throw attempts
} }
function toBuffer(t) { function toBuffer(t: any) {
return Buffer.from(JSON.stringify(t)) return Buffer.from(JSON.stringify(t))
} }
export async function isWasm() { export async function isWasm(): Promise<boolean> {
let bindings = await loadBindings() let bindings = await loadBindings()
return bindings.isWasm return bindings.isWasm
} }
export async function transform(src, options) { export async function transform(src: string, options?: any): Promise<any> {
let bindings = await loadBindings() let bindings = await loadBindings()
return bindings.transform(src, options) return bindings.transform(src, options)
} }
export function transformSync(src, options) { export function transformSync(src: string, options?: any): any {
let bindings = loadBindingsSync() let bindings = loadBindingsSync()
return bindings.transformSync(src, options) return bindings.transformSync(src, options)
} }
export async function minify(src, options) { export async function minify(src: string, options: any): Promise<string> {
let bindings = await loadBindings() let bindings = await loadBindings()
return bindings.minify(src, options) return bindings.minify(src, options)
} }
export function minifySync(src, options) { export function minifySync(src: string, options: any): string {
let bindings = loadBindingsSync() let bindings = loadBindingsSync()
return bindings.minifySync(src, options) return bindings.minifySync(src, options)
} }
export async function parse(src, options) { export async function parse(src: string, options: any): Promise<any> {
let bindings = await loadBindings() let bindings = await loadBindings()
let parserOptions = getParserOptions(options) let parserOptions = getParserOptions(options)
return bindings.parse(src, parserOptions).then((astStr) => JSON.parse(astStr)) return bindings
.parse(src, parserOptions)
.then((astStr: any) => JSON.parse(astStr))
} }
export function getBinaryMetadata() { export function getBinaryMetadata() {
@ -502,15 +511,13 @@ export function getBinaryMetadata() {
* Initialize trace subscriber to emit traces. * Initialize trace subscriber to emit traces.
* *
*/ */
export const initCustomTraceSubscriber = (() => { export const initCustomTraceSubscriber = (traceFileName?: string): void => {
return (filename) => { if (!swcTraceFlushGuard) {
if (!swcTraceFlushGuard) { // Wasm binary doesn't support trace emission
// Wasm binary doesn't support trace emission let bindings = loadNative()
let bindings = loadNative() swcTraceFlushGuard = bindings.initCustomTraceSubscriber(traceFileName)
swcTraceFlushGuard = bindings.initCustomTraceSubscriber(filename)
}
} }
})() }
/** /**
* Teardown swc's trace subscriber if there's an initialized flush guard exists. * Teardown swc's trace subscriber if there's an initialized flush guard exists.
@ -523,7 +530,7 @@ export const initCustomTraceSubscriber = (() => {
*/ */
export const teardownTraceSubscriber = (() => { export const teardownTraceSubscriber = (() => {
let flushed = false let flushed = false
return () => { return (): void => {
if (!flushed) { if (!flushed) {
flushed = true flushed = true
try { try {
@ -540,7 +547,7 @@ export const teardownTraceSubscriber = (() => {
export const teardownCrashReporter = (() => { export const teardownCrashReporter = (() => {
let flushed = false let flushed = false
return () => { return (): void => {
if (!flushed) { if (!flushed) {
flushed = true flushed = true
try { try {

View file

@ -34,9 +34,26 @@ import { getJestSWCOptions } from './options'
// see https://github.com/facebook/jest/issues/9430 // see https://github.com/facebook/jest/issues/9430
const isSupportEsm = 'Module' in vm const isSupportEsm = 'Module' in vm
function getJestConfig(jestConfig: any) {
return 'config' in jestConfig
? // jest 27
jestConfig.config
: // jest 26
jestConfig
}
function isEsm(isEsmProject: boolean, filename: any, jestConfig: any) {
return (
(/\.jsx?$/.test(filename) && isEsmProject) ||
jestConfig.extensionsToTreatAsEsm?.find((ext: any) =>
filename.endsWith(ext)
)
)
}
module.exports = { module.exports = {
createTransformer: (inputOptions) => ({ createTransformer: (inputOptions: any) => ({
process(src, filename, jestOptions) { process(src: any, filename: any, jestOptions: any) {
const jestConfig = getJestConfig(jestOptions) const jestConfig = getJestConfig(jestOptions)
let swcTransformOpts = getJestSWCOptions({ let swcTransformOpts = getJestSWCOptions({
@ -58,18 +75,3 @@ module.exports = {
}, },
}), }),
} }
function getJestConfig(jestConfig) {
return 'config' in jestConfig
? // jest 27
jestConfig.config
: // jest 26
jestConfig
}
function isEsm(isEsmProject, filename, jestConfig) {
return (
(/\.jsx?$/.test(filename) && isEsmProject) ||
jestConfig.extensionsToTreatAsEsm?.find((ext) => filename.endsWith(ext))
)
}

View file

@ -5,7 +5,7 @@ const regeneratorRuntimePath = require.resolve(
'next/dist/compiled/regenerator-runtime' 'next/dist/compiled/regenerator-runtime'
) )
export function getParserOptions({ filename, jsConfig, ...rest }) { export function getParserOptions({ filename, jsConfig, ...rest }: any) {
const isTSFile = filename.endsWith('.ts') const isTSFile = filename.endsWith('.ts')
const isTypeScript = isTSFile || filename.endsWith('.tsx') const isTypeScript = isTSFile || filename.endsWith('.tsx')
const enableDecorators = Boolean( const enableDecorators = Boolean(
@ -34,7 +34,7 @@ function getBaseSWCOptions({
swcCacheDir, swcCacheDir,
isServerLayer, isServerLayer,
hasServerComponents, hasServerComponents,
}) { }: any) {
const parserConfig = getParserOptions({ filename, jsConfig }) const parserConfig = getParserOptions({ filename, jsConfig })
const paths = jsConfig?.compilerOptions?.paths const paths = jsConfig?.compilerOptions?.paths
const enableDecorators = Boolean( const enableDecorators = Boolean(
@ -48,7 +48,7 @@ function getBaseSWCOptions({
) )
const plugins = (nextConfig?.experimental?.swcPlugins ?? []) const plugins = (nextConfig?.experimental?.swcPlugins ?? [])
.filter(Array.isArray) .filter(Array.isArray)
.map(([name, options]) => [require.resolve(name), options]) .map(([name, options]: any) => [require.resolve(name), options])
return { return {
jsc: { jsc: {
@ -121,7 +121,9 @@ function getBaseSWCOptions({
styledJsx: true, styledJsx: true,
// Disable css-in-js libs (without client-only integration) transform on server layer for server components // Disable css-in-js libs (without client-only integration) transform on server layer for server components
...(!isServerLayer && { ...(!isServerLayer && {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
emotion: getEmotionOptions(nextConfig, development), emotion: getEmotionOptions(nextConfig, development),
// eslint-disable-next-line @typescript-eslint/no-use-before-define
styledComponents: getStyledComponentsOptions(nextConfig, development), styledComponents: getStyledComponentsOptions(nextConfig, development),
}), }),
serverComponents: hasServerComponents serverComponents: hasServerComponents
@ -132,7 +134,7 @@ function getBaseSWCOptions({
} }
} }
function getStyledComponentsOptions(nextConfig, development) { function getStyledComponentsOptions(nextConfig: any, development: any) {
let styledComponentsOptions = nextConfig?.compiler?.styledComponents let styledComponentsOptions = nextConfig?.compiler?.styledComponents
if (!styledComponentsOptions) { if (!styledComponentsOptions) {
return null return null
@ -144,7 +146,7 @@ function getStyledComponentsOptions(nextConfig, development) {
} }
} }
function getEmotionOptions(nextConfig, development) { function getEmotionOptions(nextConfig: any, development: any) {
if (!nextConfig?.compiler?.emotion) { if (!nextConfig?.compiler?.emotion) {
return null return null
} }
@ -180,9 +182,9 @@ export function getJestSWCOptions({
jsConfig, jsConfig,
pagesDir, pagesDir,
hasServerComponents, hasServerComponents,
// This is not passed yet as "paths" resolving needs a test first }: // This is not passed yet as "paths" resolving needs a test first
// resolvedBaseUrl, // resolvedBaseUrl,
}) { any) {
let baseOptions = getBaseSWCOptions({ let baseOptions = getBaseSWCOptions({
filename, filename,
jest: true, jest: true,
@ -228,10 +230,10 @@ export function getLoaderSWCOptions({
swcCacheDir, swcCacheDir,
relativeFilePathFromRoot, relativeFilePathFromRoot,
hasServerComponents, hasServerComponents,
// This is not passed yet as "paths" resolving is handled by webpack currently. }: // This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl, // resolvedBaseUrl,
}) { any) {
let baseOptions = getBaseSWCOptions({ let baseOptions: any = getBaseSWCOptions({
filename, filename,
development, development,
globalWindow: !isServer, globalWindow: !isServer,
@ -248,7 +250,7 @@ export function getLoaderSWCOptions({
if (nextConfig?.experimental?.fontLoaders && relativeFilePathFromRoot) { if (nextConfig?.experimental?.fontLoaders && relativeFilePathFromRoot) {
baseOptions.fontLoaders = { baseOptions.fontLoaders = {
fontLoaders: nextConfig.experimental.fontLoaders.map( fontLoaders: nextConfig.experimental.fontLoaders.map(
({ loader }) => loader ({ loader }: any) => loader
), ),
relativeFilePathFromRoot, relativeFilePathFromRoot,
} }

View file

@ -1,5 +1,6 @@
export default class CssSyntaxError extends Error { export default class CssSyntaxError extends Error {
constructor(error) { stack: any
constructor(error: any) {
super(error) super(error)
const { reason, line, column } = error const { reason, line, column } = error

View file

@ -10,7 +10,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
const preserveCamelCase = (string, locale) => { const preserveCamelCase = (string: string, locale: string) => {
let isLastCharLower = false let isLastCharLower = false
let isLastCharUpper = false let isLastCharUpper = false
let isLastLastCharUpper = false let isLastLastCharUpper = false
@ -47,11 +47,11 @@ const preserveCamelCase = (string, locale) => {
return string return string
} }
const preserveConsecutiveUppercase = (input) => { const preserveConsecutiveUppercase = (input: string) => {
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, (m1) => m1.toLowerCase()) return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, (m1) => m1.toLowerCase())
} }
const postProcess = (input, options) => { const postProcess = (input: string, options: { locale: string }) => {
return input return input
.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => .replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) =>
p1.toLocaleUpperCase(options.locale) p1.toLocaleUpperCase(options.locale)
@ -61,7 +61,7 @@ const postProcess = (input, options) => {
) )
} }
const camelCase = (input, options) => { const camelCase = (input: string | string[], options?: any) => {
if (!(typeof input === 'string' || Array.isArray(input))) { if (!(typeof input === 'string' || Array.isArray(input))) {
throw new TypeError('Expected the input to be `string | string[]`') throw new TypeError('Expected the input to be `string | string[]`')
} }

View file

@ -8,7 +8,7 @@ import { stringifyRequest } from '../../../stringify-request'
const moduleRegExp = /\.module\.\w+$/i const moduleRegExp = /\.module\.\w+$/i
function getModulesOptions(rawOptions, loaderContext) { function getModulesOptions(rawOptions: any, loaderContext: any) {
const { resourcePath } = loaderContext const { resourcePath } = loaderContext
if (typeof rawOptions.modules === 'undefined') { if (typeof rawOptions.modules === 'undefined') {
@ -24,7 +24,7 @@ function getModulesOptions(rawOptions, loaderContext) {
return false return false
} }
let modulesOptions = { let modulesOptions: any = {
compileType: rawOptions.icss ? 'icss' : 'module', compileType: rawOptions.icss ? 'icss' : 'module',
auto: true, auto: true,
mode: 'local', mode: 'local',
@ -100,7 +100,7 @@ function getModulesOptions(rawOptions, loaderContext) {
return modulesOptions return modulesOptions
} }
function normalizeOptions(rawOptions, loaderContext) { function normalizeOptions(rawOptions: any, loaderContext: any) {
if (rawOptions.icss) { if (rawOptions.icss) {
loaderContext.emitWarning( loaderContext.emitWarning(
new Error( new Error(
@ -131,17 +131,22 @@ function normalizeOptions(rawOptions, loaderContext) {
} }
} }
export default async function loader(content, map, meta) { export default async function loader(
this: any,
content: string,
map: any,
meta: any
) {
const rawOptions = this.getOptions() const rawOptions = this.getOptions()
const plugins = [] const plugins: any[] = []
const callback = this.async() const callback = this.async()
const loaderSpan = this.currentTraceSpan.traceChild('css-loader') const loaderSpan = this.currentTraceSpan.traceChild('css-loader')
loaderSpan loaderSpan
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
let options let options: any
try { try {
options = normalizeOptions(rawOptions, this) options = normalizeOptions(rawOptions, this)
@ -168,7 +173,7 @@ export default async function loader(content, map, meta) {
const { icssParser, importParser, urlParser } = require('./plugins') const { icssParser, importParser, urlParser } = require('./plugins')
const replacements = [] const replacements: any[] = []
// if it's a font loader next-font-loader will have exports that should be exported as is // if it's a font loader next-font-loader will have exports that should be exported as is
const exports = options.fontLoader ? meta.exports : [] const exports = options.fontLoader ? meta.exports : []
@ -176,8 +181,8 @@ export default async function loader(content, map, meta) {
plugins.push(...getModulesPlugins(options, this, meta)) plugins.push(...getModulesPlugins(options, this, meta))
} }
const importPluginImports = [] const importPluginImports: any[] = []
const importPluginApi = [] const importPluginApi: any[] = []
if (shouldUseImportPlugin(options)) { if (shouldUseImportPlugin(options)) {
const resolver = this.getResolve({ const resolver = this.getResolve({
@ -196,7 +201,7 @@ export default async function loader(content, map, meta) {
rootContext: this.rootContext, rootContext: this.rootContext,
filter: getFilter(options.import, this.resourcePath), filter: getFilter(options.import, this.resourcePath),
resolver, resolver,
urlHandler: (url) => urlHandler: (url: any) =>
stringifyRequest( stringifyRequest(
this, this,
getPreRequester(this)(options.importLoaders) + url getPreRequester(this)(options.importLoaders) + url
@ -205,7 +210,7 @@ export default async function loader(content, map, meta) {
) )
} }
const urlPluginImports = [] const urlPluginImports: any[] = []
if (shouldUseURLPlugin(options)) { if (shouldUseURLPlugin(options)) {
const urlResolver = this.getResolve({ const urlResolver = this.getResolve({
@ -223,13 +228,13 @@ export default async function loader(content, map, meta) {
rootContext: this.rootContext, rootContext: this.rootContext,
filter: getFilter(options.url, this.resourcePath), filter: getFilter(options.url, this.resourcePath),
resolver: urlResolver, resolver: urlResolver,
urlHandler: (url) => stringifyRequest(this, url), urlHandler: (url: string) => stringifyRequest(this, url),
}) })
) )
} }
const icssPluginImports = [] const icssPluginImports: any[] = []
const icssPluginApi = [] const icssPluginApi: any[] = []
if (shouldUseIcssPlugin(options)) { if (shouldUseIcssPlugin(options)) {
const icssResolver = this.getResolve({ const icssResolver = this.getResolve({
@ -248,7 +253,7 @@ export default async function loader(content, map, meta) {
context: this.context, context: this.context,
rootContext: this.rootContext, rootContext: this.rootContext,
resolver: icssResolver, resolver: icssResolver,
urlHandler: (url) => urlHandler: (url: string) =>
stringifyRequest( stringifyRequest(
this, this,
getPreRequester(this)(options.importLoaders) + url getPreRequester(this)(options.importLoaders) + url
@ -284,7 +289,7 @@ export default async function loader(content, map, meta) {
} }
: false, : false,
}) })
} catch (error) { } catch (error: any) {
if (error.file) { if (error.file) {
this.addDependency(error.file) this.addDependency(error.file)
} }
@ -298,13 +303,13 @@ export default async function loader(content, map, meta) {
this.emitWarning(new Warning(warning)) this.emitWarning(new Warning(warning))
} }
const imports = [] const imports = [
.concat(icssPluginImports.sort(sort)) ...icssPluginImports.sort(sort),
.concat(importPluginImports.sort(sort)) ...importPluginImports.sort(sort),
.concat(urlPluginImports.sort(sort)) ...urlPluginImports.sort(sort),
const api = [] ]
.concat(importPluginApi.sort(sort))
.concat(icssPluginApi.sort(sort)) const api = [...importPluginApi.sort(sort), ...icssPluginApi.sort(sort)]
if (options.modules.exportOnlyLocals !== true) { if (options.modules.exportOnlyLocals !== true) {
imports.unshift({ imports.unshift({
@ -320,10 +325,10 @@ export default async function loader(content, map, meta) {
return `${importCode}${moduleCode}${exportCode}` return `${importCode}${moduleCode}${exportCode}`
}) })
.then( .then(
(code) => { (code: string) => {
callback(null, code) callback(null, code)
}, },
(err) => { (err: Error) => {
callback(err) callback(err)
} }
) )

View file

@ -6,10 +6,10 @@ import {
import { normalizeUrl, resolveRequests, requestify } from '../utils' import { normalizeUrl, resolveRequests, requestify } from '../utils'
const plugin = (options = {}) => { const plugin = (options: any = {}) => {
return { return {
postcssPlugin: 'postcss-icss-parser', postcssPlugin: 'postcss-icss-parser',
async OnceExit(root) { async OnceExit(root: any) {
const importReplacements = Object.create(null) const importReplacements = Object.create(null)
const { icssImports, icssExports } = extractICSS(root) const { icssImports, icssExports } = extractICSS(root)
const imports = new Map() const imports = new Map()
@ -30,7 +30,7 @@ const plugin = (options = {}) => {
const queryParts = normalizedUrl.split('!') const queryParts = normalizedUrl.split('!')
if (queryParts.length > 1) { if (queryParts.length > 1) {
normalizedUrl = queryParts.pop() normalizedUrl = queryParts.pop()!
prefix = queryParts.join('!') prefix = queryParts.join('!')
} }

View file

@ -5,10 +5,11 @@ import {
resolveRequests, resolveRequests,
isUrlRequestable, isUrlRequestable,
requestify, requestify,
// @ts-expect-error TODO: this export doesn't exist? Double check.
WEBPACK_IGNORE_COMMENT_REGEXP, WEBPACK_IGNORE_COMMENT_REGEXP,
} from '../utils' } from '../utils'
function parseNode(atRule, key) { function parseNode(atRule: any, key: any) {
// Convert only top-level @import // Convert only top-level @import
if (atRule.parent.type !== 'root') { if (atRule.parent.type !== 'root') {
return return
@ -41,7 +42,7 @@ function parseNode(atRule, key) {
// Nodes do not exists - `@import url('http://') :root {}` // Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) { if (atRule.nodes) {
const error = new Error( const error: any = new Error(
"It looks like you didn't end your @import statement correctly. Child nodes are attached to it." "It looks like you didn't end your @import statement correctly. Child nodes are attached to it."
) )
@ -58,7 +59,7 @@ function parseNode(atRule, key) {
paramsNodes.length === 0 || paramsNodes.length === 0 ||
(paramsNodes[0].type !== 'string' && paramsNodes[0].type !== 'function') (paramsNodes[0].type !== 'string' && paramsNodes[0].type !== 'function')
) { ) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`) const error: any = new Error(`Unable to find uri in "${atRule.toString()}"`)
error.node = atRule error.node = atRule
@ -66,7 +67,7 @@ function parseNode(atRule, key) {
} }
let isStringValue let isStringValue
let url let url: any
if (paramsNodes[0].type === 'string') { if (paramsNodes[0].type === 'string') {
isStringValue = true isStringValue = true
@ -74,7 +75,9 @@ function parseNode(atRule, key) {
} else { } else {
// Invalid function - `@import nourl(test.css);` // Invalid function - `@import nourl(test.css);`
if (paramsNodes[0].value.toLowerCase() !== 'url') { if (paramsNodes[0].value.toLowerCase() !== 'url') {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`) const error: any = new Error(
`Unable to find uri in "${atRule.toString()}"`
)
error.node = atRule error.node = atRule
@ -105,7 +108,7 @@ function parseNode(atRule, key) {
// Empty url - `@import "";` or `@import url();` // Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) { if (url.trim().length === 0) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`) const error: any = new Error(`Unable to find uri in "${atRule.toString()}"`)
error.node = atRule error.node = atRule
@ -123,20 +126,21 @@ function parseNode(atRule, key) {
return { atRule, prefix, url, media, isRequestable } return { atRule, prefix, url, media, isRequestable }
} }
const plugin = (options = {}) => { const plugin = (options: any = {}) => {
return { return {
postcssPlugin: 'postcss-import-parser', postcssPlugin: 'postcss-import-parser',
prepare(result) { prepare(result: any) {
const parsedAtRules = [] const parsedAtRules: any[] = []
return { return {
AtRule: { AtRule: {
import(atRule) { import(atRule: any) {
let parsedAtRule let parsedAtRule
try { try {
// @ts-expect-error TODO: there is no third argument?
parsedAtRule = parseNode(atRule, 'params', result) parsedAtRule = parseNode(atRule, 'params', result)
} catch (error) { } catch (error: any) {
result.warn(error.message, { node: error.node }) result.warn(error.message, { node: error.node })
} }

View file

@ -6,6 +6,7 @@ import {
requestify, requestify,
isUrlRequestable, isUrlRequestable,
isDataUrl, isDataUrl,
// @ts-expect-error TODO: this export doesn't exist? Double check.
WEBPACK_IGNORE_COMMENT_REGEXP, WEBPACK_IGNORE_COMMENT_REGEXP,
} from '../utils' } from '../utils'
@ -13,11 +14,11 @@ const isUrlFunc = /url/i
const isImageSetFunc = /^(?:-webkit-)?image-set$/i const isImageSetFunc = /^(?:-webkit-)?image-set$/i
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i
function getNodeFromUrlFunc(node) { function getNodeFromUrlFunc(node: any) {
return node.nodes && node.nodes[0] return node.nodes && node.nodes[0]
} }
function getWebpackIgnoreCommentValue(index, nodes, inBetween) { function getWebpackIgnoreCommentValue(index: any, nodes: any, inBetween?: any) {
if (index === 0 && typeof inBetween !== 'undefined') { if (index === 0 && typeof inBetween !== 'undefined') {
return inBetween return inBetween
} }
@ -48,7 +49,12 @@ function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
return matched && matched[2] === 'true' return matched && matched[2] === 'true'
} }
function shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL) { function shouldHandleURL(
url: any,
declaration: any,
result: any,
isSupportDataURLInNewURL: any
) {
if (url.length === 0) { if (url.length === 0) {
result.warn(`Unable to find uri in '${declaration.toString()}'`, { result.warn(`Unable to find uri in '${declaration.toString()}'`, {
node: declaration, node: declaration,
@ -74,7 +80,12 @@ function shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL) {
return true return true
} }
function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) { function parseDeclaration(
declaration: any,
key: any,
result: any,
isSupportDataURLInNewURL: any
) {
if (!needParseDeclaration.test(declaration[key])) { if (!needParseDeclaration.test(declaration[key])) {
return return
} }
@ -85,7 +96,7 @@ function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
: declaration[key] : declaration[key]
) )
let inBetween let inBetween: any
if (declaration.raws && declaration.raws.between) { if (declaration.raws && declaration.raws.between) {
const lastCommentIndex = declaration.raws.between.lastIndexOf('/*') const lastCommentIndex = declaration.raws.between.lastIndexOf('/*')
@ -113,9 +124,9 @@ function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
let needIgnore let needIgnore
const parsedURLs = [] const parsedURLs: any[] = []
parsed.walk((valueNode, index, valueNodes) => { parsed.walk((valueNode: any, index: any, valueNodes: any) => {
if (valueNode.type !== 'function') { if (valueNode.type !== 'function') {
return return
} }
@ -248,7 +259,7 @@ function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
let prefix let prefix
if (queryParts.length > 1) { if (queryParts.length > 1) {
url = queryParts.pop() url = queryParts.pop()!
prefix = queryParts.join('!') prefix = queryParts.join('!')
} }
@ -273,14 +284,14 @@ function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
return parsedURLs return parsedURLs
} }
const plugin = (options = {}) => { const plugin = (options: any = {}) => {
return { return {
postcssPlugin: 'postcss-url-parser', postcssPlugin: 'postcss-url-parser',
prepare(result) { prepare(result: any) {
const parsedDeclarations = [] const parsedDeclarations: any[] = []
return { return {
Declaration(declaration) { Declaration(declaration: any) {
const { isSupportDataURLInNewURL } = options const { isSupportDataURLInNewURL } = options
const parsedURL = parseDeclaration( const parsedURL = parseDeclaration(
declaration, declaration,
@ -328,6 +339,7 @@ const plugin = (options = {}) => {
const request = requestify( const request = requestify(
pathname, pathname,
rootContext, rootContext,
// @ts-expect-error TODO: only 2 arguments allowed.
needToResolveURL needToResolveURL
) )

View file

@ -4,11 +4,12 @@
*/ */
// css base code, injected by the css-loader // css base code, injected by the css-loader
// eslint-disable-next-line func-names // eslint-disable-next-line func-names
module.exports = function (useSourceMap) { module.exports = function (useSourceMap: any) {
var list = [] // return the list of modules as css string var list: any[] = [] // return the list of modules as css string
list.toString = function toString() { list.toString = function toString() {
return this.map(function (item) { return this.map(function (item) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
var content = cssWithMappingToString(item, useSourceMap) var content = cssWithMappingToString(item, useSourceMap)
if (item[2]) { if (item[2]) {
@ -20,13 +21,14 @@ module.exports = function (useSourceMap) {
} // import a list of modules into the list } // import a list of modules into the list
// eslint-disable-next-line func-names // eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) { // @ts-expect-error TODO: fix type
list.i = function (modules: any, mediaQuery: any, dedupe: any) {
if (typeof modules === 'string') { if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']] modules = [[null, modules, '']]
} }
var alreadyImportedModules = {} var alreadyImportedModules: any = {}
if (dedupe) { if (dedupe) {
for (var i = 0; i < this.length; i++) { for (var i = 0; i < this.length; i++) {
@ -40,7 +42,7 @@ module.exports = function (useSourceMap) {
} }
for (var _i = 0; _i < modules.length; _i++) { for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]) var item: any = [].concat(modules[_i])
if (dedupe && alreadyImportedModules[item[0]]) { if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue // eslint-disable-next-line no-continue
@ -62,7 +64,7 @@ module.exports = function (useSourceMap) {
return list return list
} }
function cssWithMappingToString(item, useSourceMap) { function cssWithMappingToString(item: any, useSourceMap: any) {
var content = item[1] || '' // eslint-disable-next-line prefer-destructuring var content = item[1] || '' // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3] var cssMapping = item[3]
@ -72,8 +74,9 @@ function cssWithMappingToString(item, useSourceMap) {
} }
if (useSourceMap && typeof btoa === 'function') { if (useSourceMap && typeof btoa === 'function') {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
var sourceMapping = toComment(cssMapping) var sourceMapping = toComment(cssMapping)
var sourceURLs = cssMapping.sources.map(function (source) { var sourceURLs = cssMapping.sources.map(function (source: string) {
return '/*# sourceURL=' return '/*# sourceURL='
.concat(cssMapping.sourceRoot || '') .concat(cssMapping.sourceRoot || '')
.concat(source, ' */') .concat(source, ' */')
@ -84,7 +87,7 @@ function cssWithMappingToString(item, useSourceMap) {
return [content].join('\n') return [content].join('\n')
} // Adapted from convert-source-map (MIT) } // Adapted from convert-source-map (MIT)
function toComment(sourceMap) { function toComment(sourceMap: any) {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))))
var data = var data =

View file

@ -1,4 +1,4 @@
module.exports = function (url, options) { module.exports = function (url: any, options: any) {
if (!options) { if (!options) {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
options = {} options = {}

View file

@ -19,9 +19,9 @@ const unescapeRegExp = new RegExp(
) )
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i
function unescape(str) { function unescape(str: string) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => { return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
const high = `0x${escaped}` - 0x10000 const high = (`0x${escaped}` as any) - 0x10000
/* eslint-disable line-comment-position */ /* eslint-disable line-comment-position */
// NaN means non-codepoint // NaN means non-codepoint
@ -39,15 +39,15 @@ function unescape(str) {
}) })
} }
function normalizePath(file) { function normalizePath(file: string) {
return path.sep === '\\' ? file.replace(/\\/g, '/') : file return path.sep === '\\' ? file.replace(/\\/g, '/') : file
} }
function fixedEncodeURIComponent(str) { function fixedEncodeURIComponent(str: string) {
return str.replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16)}`) return str.replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16)}`)
} }
function normalizeUrl(url, isStringValue) { function normalizeUrl(url: string, isStringValue: boolean) {
let normalizedUrl = url let normalizedUrl = url
if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) { if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
@ -66,6 +66,7 @@ function normalizeUrl(url, isStringValue) {
normalizedUrl = unescape(normalizedUrl) normalizedUrl = unescape(normalizedUrl)
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (isDataUrl(url)) { if (isDataUrl(url)) {
return fixedEncodeURIComponent(normalizedUrl) return fixedEncodeURIComponent(normalizedUrl)
} }
@ -79,7 +80,7 @@ function normalizeUrl(url, isStringValue) {
return normalizedUrl return normalizedUrl
} }
function requestify(url, rootContext) { function requestify(url: string, rootContext: string) {
if (/^file:/i.test(url)) { if (/^file:/i.test(url)) {
return fileURLToPath(url) return fileURLToPath(url)
} }
@ -93,8 +94,8 @@ function requestify(url, rootContext) {
: urlToRequest(url) : urlToRequest(url)
} }
function getFilter(filter, resourcePath) { function getFilter(filter: any, resourcePath: string) {
return (...args) => { return (...args: any[]) => {
if (typeof filter === 'function') { if (typeof filter === 'function') {
return filter(...args, resourcePath) return filter(...args, resourcePath)
} }
@ -103,7 +104,7 @@ function getFilter(filter, resourcePath) {
} }
} }
function shouldUseImportPlugin(options) { function shouldUseImportPlugin(options: any) {
if (options.modules.exportOnlyLocals) { if (options.modules.exportOnlyLocals) {
return false return false
} }
@ -115,7 +116,7 @@ function shouldUseImportPlugin(options) {
return true return true
} }
function shouldUseURLPlugin(options) { function shouldUseURLPlugin(options: any) {
if (options.modules.exportOnlyLocals) { if (options.modules.exportOnlyLocals) {
return false return false
} }
@ -127,15 +128,15 @@ function shouldUseURLPlugin(options) {
return true return true
} }
function shouldUseModulesPlugins(options) { function shouldUseModulesPlugins(options: any) {
return options.modules.compileType === 'module' return options.modules.compileType === 'module'
} }
function shouldUseIcssPlugin(options) { function shouldUseIcssPlugin(options: any) {
return options.icss === true || Boolean(options.modules) return options.icss === true || Boolean(options.modules)
} }
function getModulesPlugins(options, loaderContext, meta) { function getModulesPlugins(options: any, loaderContext: any, meta: any) {
const { const {
mode, mode,
getLocalIdent, getLocalIdent,
@ -145,7 +146,7 @@ function getModulesPlugins(options, loaderContext, meta) {
localIdentRegExp, localIdentRegExp,
} = options.modules } = options.modules
let plugins = [] let plugins: any[] = []
try { try {
plugins = [ plugins = [
@ -153,7 +154,7 @@ function getModulesPlugins(options, loaderContext, meta) {
localByDefault({ mode }), localByDefault({ mode }),
extractImports(), extractImports(),
modulesScope({ modulesScope({
generateScopedName(exportName) { generateScopedName(exportName: any) {
return getLocalIdent( return getLocalIdent(
loaderContext, loaderContext,
localIdentName, localIdentName,
@ -179,7 +180,7 @@ function getModulesPlugins(options, loaderContext, meta) {
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i
function getURLType(source) { function getURLType(source: string) {
if (source[0] === '/') { if (source[0] === '/') {
if (source[1] === '/') { if (source[1] === '/') {
return 'scheme-relative' return 'scheme-relative'
@ -195,7 +196,7 @@ function getURLType(source) {
return ABSOLUTE_SCHEME.test(source) ? 'absolute' : 'path-relative' return ABSOLUTE_SCHEME.test(source) ? 'absolute' : 'path-relative'
} }
function normalizeSourceMap(map, resourcePath) { function normalizeSourceMap(map: any, resourcePath: string) {
let newMap = map let newMap = map
// Some loader emit source map as string // Some loader emit source map as string
@ -213,7 +214,7 @@ function normalizeSourceMap(map, resourcePath) {
if (newMap.sources) { if (newMap.sources) {
// Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91) // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map // We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
newMap.sources = newMap.sources.map((source) => { newMap.sources = newMap.sources.map((source: string) => {
// Non-standard syntax from `postcss` // Non-standard syntax from `postcss`
if (source.indexOf('<') === 0) { if (source.indexOf('<') === 0) {
return source return source
@ -238,10 +239,10 @@ function normalizeSourceMap(map, resourcePath) {
return newMap return newMap
} }
function getPreRequester({ loaders, loaderIndex }) { function getPreRequester({ loaders, loaderIndex }: any) {
const cache = Object.create(null) const cache = Object.create(null)
return (number) => { return (number: any) => {
if (cache[number]) { if (cache[number]) {
return cache[number] return cache[number]
} }
@ -254,7 +255,7 @@ function getPreRequester({ loaders, loaderIndex }) {
loaderIndex, loaderIndex,
loaderIndex + 1 + (typeof number !== 'number' ? 0 : number) loaderIndex + 1 + (typeof number !== 'number' ? 0 : number)
) )
.map((x) => x.request) .map((x: any) => x.request)
.join('!') .join('!')
cache[number] = `-!${loadersRequest}!` cache[number] = `-!${loadersRequest}!`
@ -264,7 +265,7 @@ function getPreRequester({ loaders, loaderIndex }) {
} }
} }
function getImportCode(imports, options) { function getImportCode(imports: any, options: any) {
let code = '' let code = ''
for (const item of imports) { for (const item of imports) {
@ -286,7 +287,7 @@ function getImportCode(imports, options) {
return code ? `// Imports\n${code}` : '' return code ? `// Imports\n${code}` : ''
} }
function normalizeSourceMapForRuntime(map, loaderContext) { function normalizeSourceMapForRuntime(map: any, loaderContext: any) {
const resultMap = map ? map.toJSON() : null const resultMap = map ? map.toJSON() : null
if (resultMap) { if (resultMap) {
@ -294,7 +295,7 @@ function normalizeSourceMapForRuntime(map, loaderContext) {
resultMap.sourceRoot = '' resultMap.sourceRoot = ''
resultMap.sources = resultMap.sources.map((source) => { resultMap.sources = resultMap.sources.map((source: string) => {
// Non-standard syntax from `postcss` // Non-standard syntax from `postcss`
if (source.indexOf('<') === 0) { if (source.indexOf('<') === 0) {
return source return source
@ -319,7 +320,16 @@ function normalizeSourceMapForRuntime(map, loaderContext) {
return JSON.stringify(resultMap) return JSON.stringify(resultMap)
} }
function getModuleCode(result, api, replacements, options, loaderContext) { function getModuleCode(
result: { map: any; css: any },
api: any,
replacements: any,
options: {
modules: { exportOnlyLocals: boolean; namedExport: any }
sourceMap: any
},
loaderContext: any
) {
if (options.modules.exportOnlyLocals === true) { if (options.modules.exportOnlyLocals === true) {
return '' return ''
} }
@ -356,9 +366,10 @@ function getModuleCode(result, api, replacements, options, loaderContext) {
) )
} else { } else {
const { hash, needQuotes } = item const { hash, needQuotes } = item
const getUrlOptions = [] const getUrlOptions = [
.concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []) ...(hash ? [`hash: ${JSON.stringify(hash)}`] : []),
.concat(needQuotes ? 'needQuotes: true' : []) ...(needQuotes ? 'needQuotes: true' : []),
]
const preparedOptions = const preparedOptions =
getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '' getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : ''
@ -373,17 +384,28 @@ function getModuleCode(result, api, replacements, options, loaderContext) {
return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n` return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`
} }
function dashesCamelCase(str) { function dashesCamelCase(str: string) {
return str.replace(/-+(\w)/g, (match, firstLetter) => return str.replace(/-+(\w)/g, (_match: any, firstLetter: string) =>
firstLetter.toUpperCase() firstLetter.toUpperCase()
) )
} }
function getExportCode(exports, replacements, options) { function getExportCode(
exports: any,
replacements: any,
options: {
modules: {
namedExport: any
exportLocalsConvention: any
exportOnlyLocals: any
}
esModule: any
}
) {
let code = '// Exports\n' let code = '// Exports\n'
let localsCode = '' let localsCode = ''
const addExportToLocalsCode = (name, value) => { const addExportToLocalsCode = (name: string, value: any) => {
if (options.modules.namedExport) { if (options.modules.namedExport) {
localsCode += `export const ${camelCase(name)} = ${JSON.stringify( localsCode += `export const ${camelCase(name)} = ${JSON.stringify(
value value
@ -482,12 +504,16 @@ function getExportCode(exports, replacements, options) {
return code return code
} }
async function resolveRequests(resolve, context, possibleRequests) { async function resolveRequests(
resolve: (arg0: any, arg1: any) => Promise<any>,
context: any,
possibleRequests: any[]
): Promise<any> {
return resolve(context, possibleRequests[0]) return resolve(context, possibleRequests[0])
.then((result) => { .then((result: any) => {
return result return result
}) })
.catch((error) => { .catch((error: any) => {
const [, ...tailPossibleRequests] = possibleRequests const [, ...tailPossibleRequests] = possibleRequests
if (tailPossibleRequests.length === 0) { if (tailPossibleRequests.length === 0) {
@ -498,7 +524,7 @@ async function resolveRequests(resolve, context, possibleRequests) {
}) })
} }
function isUrlRequestable(url) { function isUrlRequestable(url: string) {
// Protocol-relative URLs // Protocol-relative URLs
if (/^\/\//.test(url)) { if (/^\/\//.test(url)) {
return false return false
@ -522,11 +548,11 @@ function isUrlRequestable(url) {
return true return true
} }
function sort(a, b) { function sort(a: { index: number }, b: { index: number }) {
return a.index - b.index return a.index - b.index
} }
function isDataUrl(url) { function isDataUrl(url: string) {
if (/^data:/i.test(url)) { if (/^data:/i.test(url)) {
return true return true
} }

View file

@ -1,4 +1,4 @@
import type { FontLoader } from '../../../../font' import type { FontLoader } from '../../../../../font'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import path from 'path' import path from 'path'

View file

@ -1,4 +1,4 @@
import type { AdjustFontFallback } from '../../../../font' import type { AdjustFontFallback } from '../../../../../font'
import postcss, { Declaration } from 'postcss' import postcss, { Declaration } from 'postcss'
const postcssNextFontPlugin = ({ const postcssNextFontPlugin = ({

Some files were not shown because too many files have changed in this diff Show more