first commit

This commit is contained in:
becarta
2025-05-16 00:17:42 +02:00
parent ea5c866137
commit bacf566ec9
6020 changed files with 1715262 additions and 0 deletions

18
node_modules/vitefu/src/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,18 @@
// CJS -> ESM proxy file
// Reference: https://github.com/vitejs/vite/blob/9f268dad2e82c0f1276b1098c0a28f1cf245aa50/packages/vite/index.cjs
module.exports = require('./sync.cjs')
// redirect async functions to ESM
const asyncFunctions = [
'crawlFrameworkPkgs',
'findDepPkgJsonPath',
'findClosestPkgJsonPath',
'pkgNeedsOptimization'
]
for (const fn of asyncFunctions) {
module.exports[fn] = function () {
return import('./index.js').then((mod) => mod[fn].apply(this, arguments))
}
}

58
node_modules/vitefu/src/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,58 @@
// CJS types like `index.d.ts` but dumbed down and doesn't import from `vite`. Thanks TypeScript.
export interface CrawlFrameworkPkgsOptions {
root: string
isBuild: boolean
viteUserConfig?: any
isFrameworkPkgByJson?: (pkgJson: Record<string, any>) => boolean
isFrameworkPkgByName?: (pkgName: string) => boolean | undefined
isSemiFrameworkPkgByJson?: (pkgJson: Record<string, any>) => boolean
isSemiFrameworkPkgByName?: (pkgName: string) => boolean | undefined
}
export interface CrawlFrameworkPkgsResult {
optimizeDeps: {
include: string[]
exclude: string[]
}
ssr: {
noExternal: string[]
external: string[]
}
}
export declare function crawlFrameworkPkgs(
options: CrawlFrameworkPkgsOptions
): Promise<CrawlFrameworkPkgsResult>
export declare function findDepPkgJsonPath(
dep: string,
parent: string
): Promise<string | undefined>
export declare function findClosestPkgJsonPath(
dir: string,
predicate?: (pkgJsonPath: string) => boolean | Promise<boolean>
): Promise<string | undefined>
export declare function pkgNeedsOptimization(
pkgJson: Record<string, any>,
pkgJsonPath: string
): Promise<boolean>
export declare function isDepExcluded(
dep: string,
optimizeDepsExclude: any
): boolean
export declare function isDepIncluded(
dep: string,
optimizeDepsInclude: any
): boolean
export declare function isDepNoExternaled(
dep: string,
ssrNoExternal: any
): boolean
export declare function isDepExternaled(dep: string, ssrExternal: any): boolean

178
node_modules/vitefu/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,178 @@
import type { DepOptimizationOptions, SSROptions, UserConfig } from 'vite'
export interface CrawlFrameworkPkgsOptions {
/**
* Path to the root of the project that contains the `package.json`
*/
root: string
/**
* Whether we're currently in a Vite build
*/
isBuild: boolean
/**
* Optional. If a Vite user config is passed, the output Vite config will respect the
* set `optimizeDeps` and `ssr` options so it doesn't override it
*/
viteUserConfig?: UserConfig
/**
* Whether this is a framework package by checking it's `package.json`.
* A framework package is one that exports special files that can't be processed
* by esbuild natively. For example, exporting `.framework` files.
*
* @example
* ```ts
* return pkgJson.keywords?.includes('my-framework')
* ```
*/
isFrameworkPkgByJson?: (pkgJson: Record<string, any>) => boolean
/**
* Whether this is a framework package by checking it's name. This is
* usually used as a fast path. Return `true` or `false` if you know 100%
* if it's a framework package or not. Return `undefined` to fallback to
* `isFrameworkPkgByJson`.
*
* @example
* ```ts
* return SPECIAL_PACKAGES.includes(pkgName) || undefined
* ```
*/
isFrameworkPkgByName?: (pkgName: string) => boolean | undefined
/**
* Whether this is a semi-framework package by checking it's `package.json`.
* A semi-framework package is one that **doesn't** export special files but
* consumes other APIs of the framework. For example, it only does
* `import { debounce } from 'my-framework/utils'`.
*
* @example
* ```ts
* return Object.keys(pkgJson.dependencies || {}).includes('my-framework')
* ```
*/
isSemiFrameworkPkgByJson?: (pkgJson: Record<string, any>) => boolean
/**
* Whether this is a semi-framework package by checking it's name. This is
* usually used as a fast path. Return `true` or `false` if you know 100%
* if it's a semi-framework package or not. Return `undefined` to fallback to
* `isSemiFrameworkPkgByJson`.
*
* @example
* ```ts
* return SPECIAL_SEMI_PACKAGES.includes(pkgName) || undefined
* ```
*/
isSemiFrameworkPkgByName?: (pkgName: string) => boolean | undefined
}
export interface CrawlFrameworkPkgsResult {
optimizeDeps: {
include: string[]
exclude: string[]
}
ssr: {
noExternal: string[]
external: string[]
}
}
/**
* Crawls for framework packages starting from `<root>/package.json` to build
* out a partial Vite config. See the source code for details of how this is built.
*/
export declare function crawlFrameworkPkgs(
options: CrawlFrameworkPkgsOptions
): Promise<CrawlFrameworkPkgsResult>
/**
* Find the `package.json` of a dep, starting from the parent, e.g. `process.cwd()`.
* A simplified implementation of https://nodejs.org/api/esm.html#resolver-algorithm-specification
* (PACKAGE_RESOLVE) for `package.json` specifically.
*/
export declare function findDepPkgJsonPath(
dep: string,
parent: string
): Promise<string | undefined>
/**
* Find the closest `package.json` path by walking `dir` upwards.
*
* Pass a function to `predicate` to check if the current `package.json` is the
* one you're looking for. For example, finding `package.json` that has the
* `name` field only. Throwing inside the `predicate` is safe and acts the same
* as returning false.
*/
export declare function findClosestPkgJsonPath(
dir: string,
predicate?: (pkgJsonPath: string) => boolean | Promise<boolean>
): Promise<string | undefined>
/**
* Check if a package needs to be optimized by Vite, aka if it's CJS-only
*/
export declare function pkgNeedsOptimization(
pkgJson: Record<string, any>,
pkgJsonPath: string
): Promise<boolean>
/**
* Check if a dependency is part of an existing `optimizeDeps.exclude` config
* @param dep Dependency to be included
* @param optimizeDepsExclude Existing `optimizeDeps.exclude` config
* @example
* ```ts
* optimizeDeps: {
* include: includesToAdd.filter((dep) => !isDepExcluded(dep, existingExclude))
* }
* ```
*/
export declare function isDepExcluded(
dep: string,
optimizeDepsExclude: NonNullable<DepOptimizationOptions['exclude']>
): boolean
/**
* Check if a dependency is part of an existing `optimizeDeps.include` config
* @param dep Dependency to be excluded
* @param optimizeDepsInclude Existing `optimizeDeps.include` config
* @example
* ```ts
* optimizeDeps: {
* exclude: excludesToAdd.filter((dep) => !isDepIncluded(dep, existingInclude))
* }
* ```
*/
export declare function isDepIncluded(
dep: string,
optimizeDepsInclude: NonNullable<DepOptimizationOptions['include']>
): boolean
/**
* Check if a dependency is part of an existing `ssr.noExternal` config
* @param dep Dependency to be excluded
* @param ssrNoExternal Existing `ssr.noExternal` config
* @example
* ```ts
* ssr: {
* external: externalsToAdd.filter((dep) => !isDepNoExternal(dep, existingNoExternal))
* }
* ```
*/
export declare function isDepNoExternaled(
dep: string,
ssrNoExternal: NonNullable<SSROptions['noExternal']>
): boolean
/**
* Check if a dependency is part of an existing `ssr.external` config
* @param dep Dependency to be noExternaled
* @param ssrExternal Existing `ssr.external` config
* @example
* ```ts
* ssr: {
* noExternal: noExternalsToAdd.filter((dep) => !isDepExternal(dep, existingExternal))
* }
* ```
*/
export declare function isDepExternaled(
dep: string,
ssrExternal: NonNullable<SSROptions['external']>
): boolean

268
node_modules/vitefu/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,268 @@
import fs from 'node:fs/promises'
import fsSync from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import {
isDepIncluded,
isDepExcluded,
isDepNoExternaled,
isDepExternaled
} from './sync.cjs'
/** @type {import('pnpapi')} */
let pnp
if (process.versions.pnp) {
try {
pnp = createRequire(import.meta.url)('pnpapi')
} catch {}
}
export { isDepIncluded, isDepExcluded, isDepNoExternaled, isDepExternaled }
/** @type {import('./index.d.ts').crawlFrameworkPkgs} */
export async function crawlFrameworkPkgs(options) {
const pkgJsonPath = await findClosestPkgJsonPath(options.root)
if (!pkgJsonPath) {
// don't throw as package.json is not required
return {
optimizeDeps: { include: [], exclude: [] },
ssr: { noExternal: [], external: [] }
}
}
const pkgJson = await readJson(pkgJsonPath).catch((e) => {
throw new Error(`Unable to read ${pkgJsonPath}`, { cause: e })
})
/** @type {string[]} */
let optimizeDepsInclude = []
/** @type {string[]} */
let optimizeDepsExclude = []
/** @type {string[]} */
let ssrNoExternal = []
/** @type {string[]} */
let ssrExternal = []
await crawl(pkgJsonPath, pkgJson)
// respect vite user config
if (options.viteUserConfig) {
// remove includes that are explicitly excluded in optimizeDeps
const _optimizeDepsExclude = options.viteUserConfig?.optimizeDeps?.exclude
if (_optimizeDepsExclude) {
optimizeDepsInclude = optimizeDepsInclude.filter(
(dep) => !isDepExcluded(dep, _optimizeDepsExclude)
)
}
// remove excludes that are explicitly included in optimizeDeps
const _optimizeDepsInclude = options.viteUserConfig?.optimizeDeps?.include
if (_optimizeDepsInclude) {
optimizeDepsExclude = optimizeDepsExclude.filter(
(dep) => !isDepIncluded(dep, _optimizeDepsInclude)
)
}
// remove noExternals that are explicitly externalized
const _ssrExternal = options.viteUserConfig?.ssr?.external
if (_ssrExternal) {
ssrNoExternal = ssrNoExternal.filter(
(dep) => !isDepExternaled(dep, _ssrExternal)
)
}
// remove externals that are explicitly noExternal
const _ssrNoExternal = options.viteUserConfig?.ssr?.noExternal
if (_ssrNoExternal) {
ssrExternal = ssrExternal.filter(
(dep) => !isDepNoExternaled(dep, _ssrNoExternal)
)
}
}
return {
optimizeDeps: {
include: optimizeDepsInclude,
exclude: optimizeDepsExclude
},
ssr: {
noExternal: ssrNoExternal,
external: ssrExternal
}
}
/**
* crawl the package.json dependencies for framework packages. rules:
* 1. a framework package should be `optimizeDeps.exclude` and `ssr.noExternal`.
* 2. the deps of the framework package should be `optimizeDeps.include` and `ssr.external`
* unless the dep is also a framework package, in which case do no1 & no2 recursively.
* 3. any non-framework packages that aren't imported by a framework package can be skipped entirely.
* 4. a semi-framework package is like a framework package, except it isn't `optimizeDeps.exclude`,
* but only applies `ssr.noExternal`.
* @param {string} pkgJsonPath
* @param {Record<string, any>} pkgJson
* @param {string[]} [parentDepNames]
*/
async function crawl(pkgJsonPath, pkgJson, parentDepNames = []) {
const isRoot = parentDepNames.length === 0
/** @type {string[]} */
let deps = [
...Object.keys(pkgJson.dependencies || {}),
...(isRoot ? Object.keys(pkgJson.devDependencies || {}) : [])
]
deps = deps.filter((dep) => {
// skip circular deps
if (parentDepNames.includes(dep)) {
return false
}
const isFrameworkPkg = options.isFrameworkPkgByName?.(dep)
const isSemiFrameworkPkg = options.isSemiFrameworkPkgByName?.(dep)
if (isFrameworkPkg) {
// framework packages should be excluded from optimization as esbuild can't handle them.
// otherwise it'll cause https://github.com/vitejs/vite/issues/3910
optimizeDepsExclude.push(dep)
// framework packages should be noExternal so that they go through vite's transformation
// pipeline, since nodejs can't support them.
ssrNoExternal.push(dep)
} else if (isSemiFrameworkPkg) {
// semi-framework packages should do the same except for optimization exclude as they
// aren't needed to work (they don't contain raw framework components)
ssrNoExternal.push(dep)
}
// only those that are explictly false can skip crawling since we don't need to do anything
// special for them
if (isFrameworkPkg === false || isSemiFrameworkPkg === false) {
return false
}
// if `true`, we need to crawl the nested deps to deep include and ssr externalize them in dev.
// if `undefined`, it's the same as "i don't know". we need to crawl and find the package.json
// to find out.
else {
return true
}
})
const promises = deps.map(async (dep) => {
const depPkgJsonPath = await findDepPkgJsonPath(dep, pkgJsonPath)
if (!depPkgJsonPath) return
const depPkgJson = await readJson(depPkgJsonPath).catch(() => {})
if (!depPkgJson) return
// fast path if this dep is already a framework dep based on the filter condition above
const cachedIsFrameworkPkg = ssrNoExternal.includes(dep)
if (cachedIsFrameworkPkg) {
return crawl(depPkgJsonPath, depPkgJson, parentDepNames.concat(dep))
}
// check if this dep is a framework dep, if so, track and crawl it
const isFrameworkPkg = options.isFrameworkPkgByJson?.(depPkgJson)
const isSemiFrameworkPkg = options.isSemiFrameworkPkgByJson?.(depPkgJson)
if (isFrameworkPkg || isSemiFrameworkPkg) {
// see explanation in filter condition above
if (isFrameworkPkg) {
optimizeDepsExclude.push(dep)
ssrNoExternal.push(dep)
} else if (isSemiFrameworkPkg) {
ssrNoExternal.push(dep)
}
return crawl(depPkgJsonPath, depPkgJson, parentDepNames.concat(dep))
}
// if we're crawling in a non-root state, the parent is 100% a framework package
// because of the above if block. in this case, if it's dep of a non-framework
// package, handle special cases for them.
if (!isRoot) {
// deep include it if it's a CJS package, so it becomes ESM and vite is happy.
if (await pkgNeedsOptimization(depPkgJson, depPkgJsonPath)) {
optimizeDepsInclude.push(parentDepNames.concat(dep).join(' > '))
}
// also externalize it in dev so it doesn't trip vite's SSR transformation.
// we do in dev only as build cannot access deep external packages in strict
// dependency installations, such as pnpm.
if (!options.isBuild && !ssrExternal.includes(dep)) {
ssrExternal.push(dep)
}
}
})
await Promise.all(promises)
}
}
/** @type {import('./index.d.ts').findDepPkgJsonPath} */
export async function findDepPkgJsonPath(dep, parent) {
if (pnp) {
try {
const depRoot = pnp.resolveToUnqualified(dep, parent)
if (!depRoot) return undefined
return path.join(depRoot, 'package.json')
} catch {
return undefined
}
}
let root = parent
while (root) {
const pkg = path.join(root, 'node_modules', dep, 'package.json')
try {
await fs.access(pkg)
// use 'node:fs' version to match 'vite:resolve' and avoid realpath.native quirk
// https://github.com/sveltejs/vite-plugin-svelte/issues/525#issuecomment-1355551264
return fsSync.realpathSync(pkg)
} catch {}
const nextRoot = path.dirname(root)
if (nextRoot === root) break
root = nextRoot
}
return undefined
}
/** @type {import('./index.d.ts').findClosestPkgJsonPath} */
export async function findClosestPkgJsonPath(dir, predicate = undefined) {
if (dir.endsWith('package.json')) {
dir = path.dirname(dir)
}
while (dir) {
const pkg = path.join(dir, 'package.json')
try {
const stat = await fs.stat(pkg)
if (stat.isFile() && (!predicate || (await predicate(pkg)))) {
return pkg
}
} catch {}
const nextDir = path.dirname(dir)
if (nextDir === dir) break
dir = nextDir
}
return undefined
}
/** @type {import('./index.d.ts').pkgNeedsOptimization} */
export async function pkgNeedsOptimization(pkgJson, pkgJsonPath) {
// only optimize if is cjs, using the below as heuristic
// see https://github.com/sveltejs/vite-plugin-svelte/issues/162
if (pkgJson.module || pkgJson.exports) return false
// if have main, ensure entry is js so vite can prebundle it
// see https://github.com/sveltejs/vite-plugin-svelte/issues/233
if (pkgJson.main) {
const entryExt = path.extname(pkgJson.main)
return !entryExt || entryExt === '.js' || entryExt === '.cjs'
}
// check if has implicit index.js entrypoint to prebundle
// see https://github.com/sveltejs/vite-plugin-svelte/issues/281
// see https://github.com/solidjs/vite-plugin-solid/issues/70#issuecomment-1306488154
try {
await fs.access(path.join(path.dirname(pkgJsonPath), 'index.js'))
return true
} catch {
return false
}
}
/**
* @param {string} findDepPkgJsonPath
* @returns {Promise<Record<string, any>>}
*/
async function readJson(findDepPkgJsonPath) {
return JSON.parse(await fs.readFile(findDepPkgJsonPath, 'utf8'))
}

66
node_modules/vitefu/src/sync.cjs generated vendored Normal file
View File

@@ -0,0 +1,66 @@
// contains synchronous API only so it can be exported as CJS and ESM
/** @type {import('./index.d.ts').isDepIncluded} */
function isDepIncluded(dep, optimizeDepsInclude) {
return optimizeDepsInclude.some((id) => parseIncludeStr(id) === dep)
}
/** @type {import('./index.d.ts').isDepExcluded} */
function isDepExcluded(dep, optimizeDepsExclude) {
dep = parseIncludeStr(dep)
return optimizeDepsExclude.some(
(id) => id === dep || dep.startsWith(`${id}/`)
)
}
/** @type {import('./index.d.ts').isDepNoExternaled} */
function isDepNoExternaled(dep, ssrNoExternal) {
if (ssrNoExternal === true) {
return true
} else {
return isMatch(dep, ssrNoExternal)
}
}
/** @type {import('./index.d.ts').isDepExternaled} */
function isDepExternaled(dep, ssrExternal) {
// If `ssrExternal` is `true`, it just means that all linked
// dependencies should also be externalized by default. It doesn't
// mean that a dependency is being explicitly externalized. So we
// return `false` in this case.
// @ts-expect-error can be true in Vite 6
if (ssrExternal === true) {
return false
} else {
return ssrExternal.includes(dep)
}
}
/**
* @param {string} raw could be "foo" or "foo > bar" etc
*/
function parseIncludeStr(raw) {
const lastArrow = raw.lastIndexOf('>')
return lastArrow === -1 ? raw : raw.slice(lastArrow + 1).trim()
}
/**
* @param {string} target
* @param {string | RegExp | (string | RegExp)[]} pattern
*/
function isMatch(target, pattern) {
if (Array.isArray(pattern)) {
return pattern.some((p) => isMatch(target, p))
} else if (typeof pattern === 'string') {
return target === pattern
} else if (pattern instanceof RegExp) {
return pattern.test(target)
}
}
module.exports = {
isDepIncluded,
isDepExcluded,
isDepNoExternaled,
isDepExternaled
}