feat: stack resolve 全面插件化——alias/relative 拆为内置插件,alias 补 tsconfig paths (#42)
Build Tutorial / Build @stack/tutorial (kaniko) (push) Successful in 5m40s
Build Tutorial / Build @stack/tutorial (kaniko) (push) Successful in 5m40s
## 背景 resolve 链此前是半插件化:包查找已由 pkgResolve 插件承接(package.json → node_modules 上溯 → 内存缓存),但 alias 与相对路径两级兜底仍是 engine 内建——applyAlias 前缀替换发生在插件链之前、相对/绝对 probe 与裸说明符 root 兜底发生在插件链之后,用户插件无法插手这三段,也无法替换或禁用。另外 alias 只认 config.alias,不读 tsconfig paths;且 applyAlias 的 startsWith 无边界检查(alias `@utils` 会误伤 `@utils-extra`)。 ## 变更内容 - **engine.resolveDemand 瘦身为纯插件链**:applyAlias、相对/绝对 probe、裸说明符 root 兜底三段内建逻辑全部撤出,链空即 external(入口报错单点留 resolveEntry);顺带修 alias 无边界误伤,新匹配要求 exact 或 `/` 边界。 - **ResolveContext 增 resolve 再派发**:插件命中后把映射目标交还剩余插件链。alias 插件因此零 probe——`./x` 走 relative、裸名走 pkg/root 兜底,`react→preact` 型包别名依旧成立。 - **新增 aliasResolve**:config.alias 前缀映射 + tsconfig `compilerOptions.paths`(锚定 root,baseUrl 缺省即 tsconfig 目录;exact 优先、最长前缀星模式、多目标按序试解);命中后全走剩余链,全失败响亮报错不静默外化(承接原 aliased-miss throw 语义)。 - **新增 relativeResolve**:`./ ../ /` 相对与绝对 probe + 裸说明符 root 兜底——入口 `src/app.ts` 这类根相对路径依赖此路径,不可删只可搬;相对 miss 报错文案与原 engine 逐字一致。 - **新增 tsconfigJson 叶子**:JSONC 剥离状态机(字符串感知,吃注释/尾逗号/BOM)。esbuild json loader 拒注释与尾逗号,故自写;aliasResolve 不再依赖 esbuild-wasm。 - **默认装配下沉 core/defaults.ts**:withDefaultHooks 默认链 `[imports, …用户 hooks, alias, pkg, relative]`,build() 与 CLI 共用同一套链(CLI withDefaults 只剩 fs 注入)。链序三保:vendor(用户钩)先于 alias/pkg 保住 vendor 优先 node_modules;pkg 先于 relative 保住 browser-field 对相对导入的 remap;relative 收尾。 - **builtins 导出**:aliasResolve / relativeResolve / withDefaultHooks,pkgResolve 未动(三张内存缓存即 stack 的解析缓存,vendor 预包作为用户钩继续先于它)。 ## 自测结果 - 全量测试 72/72 绿:66 旧例零改动全过(行为保持),新增 resolvePlugins.spec 6 例——alias 边界不误伤+未命中外化、tsconfig paths 锚定 root、JSONC 容错、包名再派发+边界、alias miss 响亮报错、裸说明符 root 兜底。 - typecheck / biome / strip-comments(0 条注释)全净。 - stack-demo 真实工程构建冒烟:`@/` alias 与 esm/min/bundle 三份产物照常落位。 --------- Co-authored-by: cqh963852 <cqh963852@hotmail.com> Reviewed-on: #42
This commit was merged in pull request #42.
This commit is contained in:
1 parent
2be8dc6578
commit
20728a4039
11 files changed
+462
-70
No files matched your search
@@ -1,4 +1,6 @@
|
||||
export { type AliasResolveOptions, aliasResolve } from './core/aliasResolve.ts'
|
||||
export { type BundleOptions, bundle, moduleRuntime } from './core/bundle.ts'
|
||||
export { withDefaultHooks } from './core/defaults.ts'
|
||||
export { type ImportsOptions, imports } from './core/imports.ts'
|
||||
export { type InlineScriptOptions, inlineScript } from './core/inlineScript.ts'
|
||||
export { type MinifyOptions, minify } from './core/minify.ts'
|
||||
@@ -9,5 +11,6 @@ export {
|
||||
type PkgStrategy,
|
||||
} from './core/pkgJson.ts'
|
||||
export { type PkgResolveOptions, pkgResolve } from './core/pkgResolve.ts'
|
||||
export { type RelativeResolveOptions, relativeResolve } from './core/relativeResolve.ts'
|
||||
export { stronglyConnected } from './core/scc.ts'
|
||||
export { type VendorOptions, vendor } from './core/vendor.ts'
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { ResolveContext, ResolveResult, StackHook } from './hooks.ts'
|
||||
import { dirnamePath, joinPath, normalizePath } from './pathUtil.ts'
|
||||
import { parseTsconfigJson } from './tsconfigJson.ts'
|
||||
|
||||
export interface AliasResolveOptions {
|
||||
name?: string
|
||||
alias?: Record<string, string>
|
||||
tsconfig?: boolean | string
|
||||
}
|
||||
|
||||
interface TsRuleSet {
|
||||
base: string
|
||||
exact: Map<string, string[]>
|
||||
stars: { prefix: string; suffix: string; targets: string[] }[]
|
||||
}
|
||||
|
||||
export function aliasResolve(options: AliasResolveOptions = {}): StackHook {
|
||||
const name = options.name ?? 'config'
|
||||
const aliasEntries = Object.entries(options.alias ?? {})
|
||||
const tsconfigEnabled = options.tsconfig !== false
|
||||
const tsconfigPathOf = (root: string): string =>
|
||||
typeof options.tsconfig === 'string'
|
||||
? joinPath(root, options.tsconfig)
|
||||
: joinPath(root, 'tsconfig.json')
|
||||
|
||||
let rootSeen: string | null = null
|
||||
let cachedRules: TsRuleSet | null = null
|
||||
|
||||
const resolve = async (
|
||||
specifier: string,
|
||||
importer: string,
|
||||
ctx: ResolveContext,
|
||||
): Promise<ResolveResult | null> => {
|
||||
const aliasMapped = aliasMapOf(specifier)
|
||||
if (aliasMapped !== null) return dispatchMapped(aliasMapped, specifier, importer, ctx)
|
||||
if (!tsconfigEnabled) return null
|
||||
const rules = await rulesAt(ctx)
|
||||
if (rules === null) return null
|
||||
const targets = tsTargetsOf(rules, specifier)
|
||||
if (targets.length === 0) return null
|
||||
for (const target of targets) {
|
||||
const mapped = normalizePath(joinPath(rules.base, target))
|
||||
const result = await ctx.resolve(mapped, importer)
|
||||
if (result !== null) return result
|
||||
}
|
||||
return unresolved(specifier, importer, ctx)
|
||||
}
|
||||
|
||||
const dispatchMapped = async (
|
||||
mapped: string,
|
||||
specifier: string,
|
||||
importer: string,
|
||||
ctx: ResolveContext,
|
||||
): Promise<ResolveResult | null> => {
|
||||
const result = await ctx.resolve(mapped, importer)
|
||||
return result ?? unresolved(specifier, importer, ctx)
|
||||
}
|
||||
|
||||
const unresolved = (specifier: string, importer: string, ctx: ResolveContext): never => {
|
||||
throw new Error(
|
||||
`[stack] cannot resolve import "${specifier}" from ${importer} (root=${ctx.root})`,
|
||||
)
|
||||
}
|
||||
|
||||
const aliasMapOf = (specifier: string): string | null => {
|
||||
for (const [key, target] of aliasEntries) {
|
||||
if (specifier === key) return target
|
||||
if (
|
||||
specifier.startsWith(key) &&
|
||||
(key.endsWith('/') || specifier.charAt(key.length) === '/')
|
||||
) {
|
||||
return `${target}${specifier.slice(key.length)}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const rulesAt = async (ctx: ResolveContext): Promise<TsRuleSet | null> => {
|
||||
if (rootSeen === ctx.root) return cachedRules
|
||||
rootSeen = ctx.root
|
||||
cachedRules = await loadRules(ctx)
|
||||
return cachedRules
|
||||
}
|
||||
|
||||
const loadRules = async (ctx: ResolveContext): Promise<TsRuleSet | null> => {
|
||||
const path = tsconfigPathOf(ctx.root)
|
||||
let text: string
|
||||
try {
|
||||
text = await ctx.fs.readFile(path)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const parsed = parseTsconfigJson(text)
|
||||
const compilerOptions = recordOf(parsed.compilerOptions)
|
||||
const rawPaths = recordOf(compilerOptions?.paths)
|
||||
if (compilerOptions === null || rawPaths === null) return null
|
||||
const ruleSet: TsRuleSet = {
|
||||
base:
|
||||
typeof compilerOptions.baseUrl === 'string'
|
||||
? normalizePath(joinPath(dirnamePath(path), compilerOptions.baseUrl))
|
||||
: dirnamePath(path),
|
||||
exact: new Map(),
|
||||
stars: [],
|
||||
}
|
||||
for (const [pattern, targets] of Object.entries(rawPaths)) {
|
||||
if (!Array.isArray(targets)) continue
|
||||
const valid = targets.filter((target): target is string => typeof target === 'string')
|
||||
if (valid.length === 0) continue
|
||||
const star = pattern.indexOf('*')
|
||||
if (star === -1) ruleSet.exact.set(pattern, valid)
|
||||
else {
|
||||
ruleSet.stars.push({
|
||||
prefix: pattern.slice(0, star),
|
||||
suffix: pattern.slice(star + 1),
|
||||
targets: valid,
|
||||
})
|
||||
}
|
||||
}
|
||||
ruleSet.stars.sort((left, right) => right.prefix.length - left.prefix.length)
|
||||
return ruleSet
|
||||
}
|
||||
|
||||
return {
|
||||
name: `alias:${name}`,
|
||||
resolve,
|
||||
}
|
||||
}
|
||||
|
||||
const tsTargetsOf = (rules: TsRuleSet, specifier: string): string[] => {
|
||||
const exact = rules.exact.get(specifier)
|
||||
if (exact !== undefined) return exact
|
||||
for (const star of rules.stars) {
|
||||
const middle = starMatchOf(star.prefix, star.suffix, specifier)
|
||||
if (middle === null) continue
|
||||
return star.targets.map((target) => target.replace('*', middle))
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
const starMatchOf = (prefix: string, suffix: string, specifier: string): string | null => {
|
||||
if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) return null
|
||||
if (specifier.length < prefix.length + suffix.length) return null
|
||||
return specifier.slice(prefix.length, specifier.length - suffix.length)
|
||||
}
|
||||
|
||||
const recordOf = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { StackConfig } from './config.ts'
|
||||
import { withDefaultHooks } from './defaults.ts'
|
||||
import { DemandEngine } from './engine.ts'
|
||||
import type { BuildResult } from './hooks.ts'
|
||||
import { CORE_PRODUCER } from './hooks.ts'
|
||||
@@ -10,12 +11,13 @@ export { DEFAULT_DIST }
|
||||
export async function build(config: StackConfig): Promise<BuildResult> {
|
||||
if (config.fs === undefined) {
|
||||
throw new Error(
|
||||
'[stack] 需要注入 fs:node 宿主用 nodeFs()(@idealjs/stack/node),浏览器/测试用 memoryFs()',
|
||||
'[stack] fs is required: node hosts use nodeFs() (@idealjs/stack/node), browser/tests use memoryFs()',
|
||||
)
|
||||
}
|
||||
if ((config.inputs ?? []).length === 0) throw new Error('[stack] config.inputs 至少需要一个入口')
|
||||
if ((config.inputs ?? []).length === 0)
|
||||
throw new Error('[stack] config.inputs requires at least one entry')
|
||||
const startedAt = Date.now()
|
||||
const engine = new DemandEngine(config)
|
||||
const engine = new DemandEngine(withDefaultHooks(config))
|
||||
try {
|
||||
for (const input of config.inputs) {
|
||||
await engine.resolveEntry(input)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { aliasResolve } from './aliasResolve.ts'
|
||||
import type { StackConfig } from './config.ts'
|
||||
import type { StackHook } from './hooks.ts'
|
||||
import { imports } from './imports.ts'
|
||||
import { pkgResolve } from './pkgResolve.ts'
|
||||
import { relativeResolve } from './relativeResolve.ts'
|
||||
|
||||
export const withDefaultHooks = (config: StackConfig): StackConfig => ({
|
||||
...config,
|
||||
hooks: [
|
||||
...(hasHookPrefix(config.hooks, 'imports:') ? [] : [imports()]),
|
||||
...(config.hooks ?? []),
|
||||
...(hasHookPrefix(config.hooks, 'alias:') ? [] : [aliasResolve({ alias: config.alias })]),
|
||||
...(hasHookPrefix(config.hooks, 'pkg:') ? [] : [pkgResolve()]),
|
||||
...(hasHookPrefix(config.hooks, 'relative:') ? [] : [relativeResolve()]),
|
||||
],
|
||||
})
|
||||
|
||||
const hasHookPrefix = (hooks: StackHook[] | undefined, prefix: string): boolean =>
|
||||
(hooks ?? []).some((hook) => hook.name.startsWith(prefix))
|
||||
@@ -16,38 +16,20 @@ import type {
|
||||
Resolution,
|
||||
ResolveContext,
|
||||
ResolveHook,
|
||||
ResolveResult,
|
||||
StackHook,
|
||||
WatchHook,
|
||||
} from './hooks.ts'
|
||||
import { hookProducer } from './hooks.ts'
|
||||
import { createLoading } from './loading.ts'
|
||||
import { parseModuleImports } from './parse.ts'
|
||||
import {
|
||||
dirnamePath,
|
||||
isRelativeSpecifier,
|
||||
joinPath,
|
||||
moduleCandidates,
|
||||
normalizePath,
|
||||
} from './pathUtil.ts'
|
||||
import { normalizePath } from './pathUtil.ts'
|
||||
import {
|
||||
type ResourceRuntime,
|
||||
loweringBindImportFrom as resourcesBindImports,
|
||||
loweringImportFrom as resourcesLoweringImport,
|
||||
} from './resources.ts'
|
||||
|
||||
const applyAlias = (
|
||||
source: string,
|
||||
alias: Record<string, string> | undefined,
|
||||
): { source: string; aliased: boolean } => {
|
||||
if (alias === undefined) return { source, aliased: false }
|
||||
for (const [prefix, target] of Object.entries(alias)) {
|
||||
if (source === prefix || source.startsWith(prefix)) {
|
||||
return { source: `${target}${source.slice(prefix.length)}`, aliased: true }
|
||||
}
|
||||
}
|
||||
return { source, aliased: false }
|
||||
}
|
||||
|
||||
export class DemandEngine {
|
||||
readonly detector = new CycleDetector()
|
||||
readonly channel: OutputChannel
|
||||
@@ -66,7 +48,7 @@ export class DemandEngine {
|
||||
readonly #runtime: ResourceRuntime
|
||||
readonly #queue: QueueTask[] = []
|
||||
readonly #idleWaiters: (() => void)[] = []
|
||||
readonly #resolveContext: ResolveContext
|
||||
readonly #resolveContexts: ResolveContext[] = []
|
||||
#pendingTasks = 0
|
||||
#failure: { error: unknown } | null = null
|
||||
|
||||
@@ -98,7 +80,6 @@ export class DemandEngine {
|
||||
knownModule: (id) => this.#registry.has(id),
|
||||
bindModule: (id, into) => this.#bindModule(id, into),
|
||||
}
|
||||
this.#resolveContext = { root: this.root, fs: this.readOnlyFs }
|
||||
this.channel = new OutputChannel({
|
||||
watchHooks: this.watchHooks,
|
||||
contextFor: (hookName) => this.outputContext(hookName),
|
||||
@@ -117,44 +98,52 @@ export class DemandEngine {
|
||||
}
|
||||
|
||||
async resolveEntry(input: StackInput): Promise<void> {
|
||||
const resolution = await this.resolveDemand(input.path, `${this.root}/`, { entry: true })
|
||||
const resolution = await this.resolveDemand(input.path, `${this.root}/`)
|
||||
if (resolution.kind === 'external') {
|
||||
throw new Error(`[stack] 无法解析入口 "${input.path}"(root=${this.root})`)
|
||||
throw new Error(`[stack] cannot resolve entry "${input.path}" (root=${this.root})`)
|
||||
}
|
||||
this.#kindOverrides.set(resolution.id, inputKindOf(input.path, input.type))
|
||||
this.entries.push({ name: input.name, id: resolution.id })
|
||||
await this.ensureLifecycle(resolution.id)
|
||||
}
|
||||
|
||||
async resolveDemand(
|
||||
rawSource: string,
|
||||
importer: string,
|
||||
options: { entry?: boolean } = {},
|
||||
): Promise<Resolution> {
|
||||
const { source, aliased } = applyAlias(rawSource, this.#config.alias)
|
||||
for (const hook of this.resolveHooks) {
|
||||
const result = await hook.resolve(source, importer, this.#resolveContext)
|
||||
if (result != null) {
|
||||
if (result.content !== undefined) this.#loading.seed(result.id, result.content)
|
||||
return { kind: 'module', id: result.id }
|
||||
}
|
||||
}
|
||||
if (isRelativeSpecifier(rawSource) || rawSource.startsWith('/')) {
|
||||
const base = rawSource.startsWith('/')
|
||||
? rawSource
|
||||
: joinPath(dirnamePath(importer), rawSource)
|
||||
const id = await this.#loading.probe(moduleCandidates(base))
|
||||
if (id !== null) return { kind: 'module', id }
|
||||
throw new Error(`[stack] 无法解析导入 "${rawSource}"(来自 ${importer})`)
|
||||
}
|
||||
const rootRelative = await this.#loading.probe(moduleCandidates(joinPath(this.root, source)))
|
||||
if (rootRelative !== null) return { kind: 'module', id: rootRelative }
|
||||
if (options.entry === true || aliased) {
|
||||
throw new Error(`[stack] 无法解析导入 "${rawSource}"(来自 ${importer},root=${this.root})`)
|
||||
async resolveDemand(rawSource: string, importer: string): Promise<Resolution> {
|
||||
const result = await this.#dispatchFrom(0, rawSource, importer)
|
||||
if (result !== null) {
|
||||
if (result.content !== undefined) this.#loading.seed(result.id, result.content)
|
||||
return { kind: 'module', id: result.id }
|
||||
}
|
||||
return { kind: 'external', specifier: rawSource }
|
||||
}
|
||||
|
||||
async #dispatchFrom(
|
||||
start: number,
|
||||
specifier: string,
|
||||
importer: string,
|
||||
): Promise<ResolveResult | null> {
|
||||
for (let index = start; index < this.resolveHooks.length; index += 1) {
|
||||
const result = await this.resolveHooks[index].resolve(
|
||||
specifier,
|
||||
importer,
|
||||
this.#resolveContextAt(index),
|
||||
)
|
||||
if (result != null) return result
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
#resolveContextAt(index: number): ResolveContext {
|
||||
const cached = this.#resolveContexts[index]
|
||||
if (cached !== undefined) return cached
|
||||
const context: ResolveContext = {
|
||||
root: this.root,
|
||||
fs: this.readOnlyFs,
|
||||
resolve: (specifier, importer) => this.#dispatchFrom(index + 1, specifier, importer),
|
||||
}
|
||||
this.#resolveContexts[index] = context
|
||||
return context
|
||||
}
|
||||
|
||||
kindOf(id: string): StackInputKind {
|
||||
return this.#kindOverrides.get(id) ?? inputKindOf(id)
|
||||
}
|
||||
@@ -315,7 +304,7 @@ export class DemandEngine {
|
||||
|
||||
async #runLifecycle(id: string): Promise<FinalModule> {
|
||||
const entry = this.#registry.get(id)
|
||||
if (entry === undefined) throw new Error(`[stack] 内部错误:模块未注册:${id}`)
|
||||
if (entry === undefined) throw new Error(`[stack] internal error: module not registered: ${id}`)
|
||||
if (entry.final !== null) return entry.final
|
||||
const kind = entry.kind
|
||||
const raw = await this.#loading.loadForLifecycle(id)
|
||||
@@ -371,7 +360,9 @@ export class DemandEngine {
|
||||
#requireFs(): StackFs {
|
||||
const fs = this.#config.fs
|
||||
if (fs === undefined) {
|
||||
throw new Error('[stack] 需要注入 fs:node 宿主用 nodeFs(),浏览器/测试用 memoryFs()')
|
||||
throw new Error(
|
||||
'[stack] fs is required: node hosts use nodeFs(), browser/tests use memoryFs()',
|
||||
)
|
||||
}
|
||||
return fs
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export interface ResolveResult {
|
||||
export interface ResolveContext {
|
||||
readonly root: string
|
||||
readonly fs: ReadOnlyFs
|
||||
resolve(specifier: string, importer: string): Promise<ResolveResult | null>
|
||||
}
|
||||
|
||||
export type ResolveHook = (
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReadOnlyFs, StackHook } from './hooks.ts'
|
||||
import { dirnamePath, isRelativeSpecifier, joinPath, moduleCandidates } from './pathUtil.ts'
|
||||
|
||||
export interface RelativeResolveOptions {
|
||||
name?: string
|
||||
}
|
||||
|
||||
export function relativeResolve(options: RelativeResolveOptions = {}): StackHook {
|
||||
const name = options.name ?? 'fs'
|
||||
|
||||
const resolve = async (
|
||||
specifier: string,
|
||||
importer: string,
|
||||
ctx: { root: string; fs: ReadOnlyFs },
|
||||
): Promise<{ id: string } | null> => {
|
||||
if (isRelativeSpecifier(specifier) || specifier.startsWith('/')) {
|
||||
const base = specifier.startsWith('/')
|
||||
? specifier
|
||||
: joinPath(dirnamePath(importer), specifier)
|
||||
const id = await probeFirst(ctx.fs, moduleCandidates(base))
|
||||
if (id !== null) return { id }
|
||||
throw new Error(`[stack] cannot resolve import "${specifier}" from ${importer}`)
|
||||
}
|
||||
const rooted = await probeFirst(ctx.fs, moduleCandidates(joinPath(ctx.root, specifier)))
|
||||
if (rooted !== null) return { id: rooted }
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
name: `relative:${name}`,
|
||||
resolve,
|
||||
}
|
||||
}
|
||||
|
||||
const probeFirst = async (fs: ReadOnlyFs, candidates: string[]): Promise<string | null> => {
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await fs.readFile(candidate)
|
||||
return candidate
|
||||
} catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export const parseTsconfigJson = (text: string): Record<string, unknown> => {
|
||||
const clean = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
|
||||
try {
|
||||
return JSON.parse(clean) as Record<string, unknown>
|
||||
} catch {
|
||||
try {
|
||||
return JSON.parse(stripJsonc(clean)) as Record<string, unknown>
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stripJsonc = (text: string): string => {
|
||||
let result = ''
|
||||
let index = 0
|
||||
let inString = false
|
||||
while (index < text.length) {
|
||||
const char = text[index]
|
||||
if (inString) {
|
||||
result += char
|
||||
if (char === '\\') {
|
||||
result += text[index + 1] ?? ''
|
||||
index += 2
|
||||
continue
|
||||
}
|
||||
if (char === '"') inString = false
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
inString = true
|
||||
result += char
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
if (char === '/' && text[index + 1] === '/') {
|
||||
while (index < text.length && text[index] !== '\n') index += 1
|
||||
continue
|
||||
}
|
||||
if (char === '/' && text[index + 1] === '*') {
|
||||
index += 2
|
||||
while (index < text.length && !(text[index] === '*' && text[index + 1] === '/')) index += 1
|
||||
index += 2
|
||||
continue
|
||||
}
|
||||
if (char === ',') {
|
||||
let lookahead = index + 1
|
||||
while (lookahead < text.length && /\s/.test(text[lookahead])) lookahead += 1
|
||||
const next = text[lookahead]
|
||||
if (next === '}' || next === ']') {
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
result += char
|
||||
index += 1
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -3,9 +3,8 @@ import { networkInterfaces } from 'node:os'
|
||||
import { extname, relative, resolve as resolvePath } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { cac } from 'cac'
|
||||
import { imports, pkgResolve } from '../builtins.ts'
|
||||
import { type BuildResult, build, type StackConfig, type StackHook } from '../index.ts'
|
||||
import { MIME, startDevServer, type ServedFile } from './dev.ts'
|
||||
import { type BuildResult, build, type StackConfig } from '../index.ts'
|
||||
import { MIME, type ServedFile, startDevServer } from './dev.ts'
|
||||
import { createDevBuildQueue } from './devBuild.ts'
|
||||
import { nodeFs } from './fs.ts'
|
||||
|
||||
@@ -91,20 +90,9 @@ export async function loadConfig(configPath: string): Promise<StackConfig> {
|
||||
return config
|
||||
}
|
||||
|
||||
const hasImportsHook = (hooks: StackHook[] | undefined): boolean =>
|
||||
(hooks ?? []).some((hook) => hook.name.startsWith('imports:'))
|
||||
|
||||
const hasPkgResolveHook = (hooks: StackHook[] | undefined): boolean =>
|
||||
(hooks ?? []).some((hook) => hook.name.startsWith('pkg:'))
|
||||
|
||||
const withDefaults = (config: StackConfig): StackConfig => ({
|
||||
...config,
|
||||
fs: config.fs ?? nodeFs(),
|
||||
hooks: [
|
||||
...(hasImportsHook(config.hooks) ? [] : [imports()]),
|
||||
...(config.hooks ?? []),
|
||||
...(hasPkgResolveHook(config.hooks) ? [] : [pkgResolve()]),
|
||||
],
|
||||
})
|
||||
|
||||
async function writeOutputs(config: StackConfig, result: BuildResult): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { imports } from '../src/builtins.ts'
|
||||
import { memoryFs } from '../src/core/memoryFs.ts'
|
||||
import { type BuildResult, build } from '../src/index.ts'
|
||||
|
||||
const pkgJsonOf = (json: Record<string, unknown>): string => JSON.stringify(json)
|
||||
|
||||
const codeOf = (result: BuildResult, path: string): string => {
|
||||
const output = result.outputs.find((candidate) => candidate.name === 'default')
|
||||
assert.ok(output !== undefined, 'missing default output')
|
||||
const file = output.files.find((candidate) => candidate.path === path)
|
||||
assert.ok(
|
||||
file !== undefined,
|
||||
`missing output file ${path} (existing: ${output.files.map((f) => f.path).join(', ')})`,
|
||||
)
|
||||
return file.code
|
||||
}
|
||||
|
||||
test('config.alias prefix rewrite goes through the plugin: boundary-safe, unmatched alias stays external', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': [
|
||||
`import { info } from '@/info'`,
|
||||
`import { thing } from '@utils/thing'`,
|
||||
`import { extra } from '@utils-extra/pkg'`,
|
||||
`export const all = [info, thing, extra]`,
|
||||
].join('\n'),
|
||||
'src/info.ts': `export const info = 'info'`,
|
||||
'src/utils/thing.ts': `export const thing = 'thing'`,
|
||||
}
|
||||
const result = await build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
alias: { '@/': 'src/', '@utils': 'src/utils' },
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
})
|
||||
assert.equal(result.moduleCount, 3)
|
||||
const app = codeOf(result, 'app.js')
|
||||
assert.match(app, /from "\.\/info\.js"/)
|
||||
assert.match(app, /from "\.\/utils\/thing\.js"/)
|
||||
assert.match(app, /from "@utils-extra\/pkg"/)
|
||||
})
|
||||
|
||||
test('tsconfig paths: maps without config.alias, anchored at the project root', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': `import { info } from '@/info'\nimport { inner } from '@/nested/inner'\nexport const all = [info, inner]`,
|
||||
'src/info.ts': `export const info = 'info'`,
|
||||
'src/nested/inner.ts': `export const inner = 'inner'`,
|
||||
'tsconfig.json': pkgJsonOf({
|
||||
compilerOptions: { paths: { '@/*': ['./src/*'] } },
|
||||
}),
|
||||
}
|
||||
const result = await build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
})
|
||||
assert.equal(result.moduleCount, 3)
|
||||
const app = codeOf(result, 'app.js')
|
||||
assert.match(app, /from "\.\/info\.js"/)
|
||||
assert.match(app, /from "\.\/nested\/inner\.js"/)
|
||||
})
|
||||
|
||||
test('tsconfig with comments and trailing commas parses as JSONC, paths still work', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': `import { info } from '@/info'\nexport const all = [info]`,
|
||||
'src/info.ts': `export const info = 'info'`,
|
||||
'tsconfig.json': [
|
||||
`{`,
|
||||
` // editor experience only, compilation does not read this`,
|
||||
` "compilerOptions": {`,
|
||||
` "paths": { "@/*": ["./src/*"] },`,
|
||||
` }`,
|
||||
`}`,
|
||||
].join('\n'),
|
||||
}
|
||||
const result = await build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
})
|
||||
assert.equal(result.moduleCount, 2)
|
||||
assert.match(codeOf(result, 'app.js'), /from "\.\/info\.js"/)
|
||||
})
|
||||
|
||||
test('alias target as package name re-dispatches the chain: react lands on preact, boundary does not swallow react-dom', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': [
|
||||
`import { render } from 'react'`,
|
||||
`import { dom } from 'react-dom'`,
|
||||
`export const all = [render, dom]`,
|
||||
].join('\n'),
|
||||
'node_modules/preact/package.json': pkgJsonOf({ name: 'preact', main: './preact.js' }),
|
||||
'node_modules/preact/preact.js': `export const render = 'preact-render'`,
|
||||
}
|
||||
const result = await build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
alias: { react: 'preact' },
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
})
|
||||
assert.equal(result.moduleCount, 2)
|
||||
const app = codeOf(result, 'app.js')
|
||||
assert.match(app, /from "\.\/__shared\/preact\.js"/)
|
||||
assert.match(app, /from "react-dom"/)
|
||||
assert.match(codeOf(result, '__shared/preact.js'), /preact-render/)
|
||||
})
|
||||
|
||||
test('alias hit but target unresolvable: throws loudly instead of silently externalizing', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': `import { gone } from '@/missing'\nexport const all = [gone]`,
|
||||
'src/info.ts': `export const info = 'info'`,
|
||||
}
|
||||
await assert.rejects(
|
||||
build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
alias: { '@/': 'src/' },
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
}),
|
||||
/cannot resolve import "@\/missing"/,
|
||||
)
|
||||
})
|
||||
|
||||
test('bare specifier root fallback: project-root-relative paths are owned by the relative plugin', async () => {
|
||||
const files: Record<string, string> = {
|
||||
'src/app.ts': `import { label } from 'src/label'\nexport const all = [label]`,
|
||||
'src/label.ts': `export const label = 'page'`,
|
||||
}
|
||||
const result = await build({
|
||||
inputs: [{ name: 'app', path: 'src/app.ts' }],
|
||||
fs: memoryFs(files),
|
||||
hooks: [imports()],
|
||||
})
|
||||
assert.equal(result.moduleCount, 2)
|
||||
assert.match(codeOf(result, 'app.js'), /from "\.\/label\.js"/)
|
||||
})
|
||||
@@ -243,7 +243,7 @@ export const SCENARIOS: Scenario[] = [
|
||||
inputs: [{ name: 'main', path: 'src/main.ts' }],
|
||||
hooks: [imports()],
|
||||
},
|
||||
expected: { error: '无法解析导入 "./missing"' },
|
||||
expected: { error: 'cannot resolve import "./missing"' },
|
||||
},
|
||||
{
|
||||
name: 'imports() 声明的 A↔B 图环:自身闭环捕获降级为边数据,双向说明符重写',
|
||||
@@ -880,7 +880,7 @@ export const SCENARIOS: Scenario[] = [
|
||||
inputs: [{ name: 'page', path: 'src/index.html' }],
|
||||
hooks: [imports()],
|
||||
},
|
||||
expected: { error: '无法解析导入 "./missing.ts"' },
|
||||
expected: { error: 'cannot resolve import "./missing.ts"' },
|
||||
},
|
||||
{
|
||||
name: 'html 内 script src 走 alias:重写指向 alias 解析后的最终落位',
|
||||
|
||||
Reference in new issue
Block a user