From 71be9ac9128f13edbd2040503fab8ff456d7936f Mon Sep 17 00:00:00 2001 From: Inesh Bose Date: Mon, 13 Jan 2025 12:23:36 +0000 Subject: [PATCH] fix(injectPosition): resolve file paths to determine position --- src/module.ts | 9 +-------- src/resolvers.ts | 21 +++++++++++++-------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/module.ts b/src/module.ts index ffdc03d0..cb75b7f9 100644 --- a/src/module.ts +++ b/src/module.ts @@ -71,14 +71,7 @@ export default defineNuxtModule({ // inject only if this file isn't listed already by user if (resolvedCss && !resolvedNuxtCss.includes(resolvedCss)) { - let injectPosition: number - try { - injectPosition = resolvers.resolveInjectPosition(nuxt.options.css, cssPathConfig?.injectPosition) - } - catch (e: any) { - throw new Error('failed to resolve Tailwind CSS injection position: ' + e.message) - } - + const injectPosition = await resolvers.resolveInjectPosition(resolvedNuxtCss, cssPathConfig?.injectPosition) nuxt.options.css.splice(injectPosition, 0, resolvedCss) } diff --git a/src/resolvers.ts b/src/resolvers.ts index 7d71136a..0dbb0414 100644 --- a/src/resolvers.ts +++ b/src/resolvers.ts @@ -47,7 +47,7 @@ export const resolveEditorSupportConfig = (config: ModuleOptions['editorSupport' * * @returns index in the css array */ -export function resolveInjectPosition(css: string[], position: InjectPosition = 'first') { +export async function resolveInjectPosition(css: string[], position: InjectPosition = 'first') { if (typeof (position) === 'number') { return ~~Math.min(position, css.length + 1) } @@ -56,18 +56,23 @@ export function resolveInjectPosition(css: string[], position: InjectPosition = switch (position) { case 'first': return 0 case 'last': return css.length - default: throw new Error('invalid literal: ' + position) } } - if (position.after !== undefined) { - const index = css.indexOf(position.after) - if (index === -1) { - throw new Error('`after` position specifies a file which does not exists on CSS stack: ' + position.after) + if (typeof (position) === 'object') { + const minIndex = 'after' in position ? css.indexOf(await resolvePath(position.after)) + 1 : 0 + const maxIndex = 'before' in position ? css.indexOf(await resolvePath(position.before as string)) : css.length + + if ([minIndex, maxIndex].includes(-1) || ('after' in position && minIndex === 0)) { + throw new Error(`\`injectPosition\` specifies a file which does not exists on CSS stack: ` + JSON.stringify(position)) + } + + if (minIndex > maxIndex) { + throw new Error(`\`injectPosition\` specifies a relative location \`${minIndex}\` that cannot be resolved (i.e., \`after\` orders \`before\` may be reversed): ` + JSON.stringify(position)) } - return index + 1 + return 'after' in position ? minIndex : maxIndex } - throw new Error('invalid position: ' + JSON.stringify(position)) + throw new Error('invalid `injectPosition`: ' + JSON.stringify(position)) }