Skip to content

Commit

Permalink
fix importAttributes is not avaliable in old node versions
Browse files Browse the repository at this point in the history
  • Loading branch information
yesmeck committed Oct 11, 2024
1 parent 24440fa commit 913e6ae
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
25 changes: 20 additions & 5 deletions src/language-server/config/cache-busting-resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ const { pathToFileURL } = require("node:url");

/** @import { ResolveContext, ResolutionResult, LoadResult, ImportContext } from "./cache-busting-resolver.types" */

/**
* importAssertions was renamed to importAttributes in newer versions of Node.js.
*
* @param {ResolveContext|ImportContext} context
* @returns {"importAttributes"|"importAssertions"}
*/
function importAttributesKeyName(context) {
if (!("importAttributes" in context) && "importAssertions" in context) {
return "importAssertions";
}
return "importAttributes";
}

/**
* @param {string} specifier
* @returns {string}
Expand All @@ -21,14 +34,15 @@ function bustFileName(specifier) {
* @returns {Promise<ResolutionResult>}
*/
async function resolve(specifier, context, nextResolve) {
if (context.importAttributes.as !== "cachebust") {
const importAttributesKey = importAttributesKeyName(context);
if (context[importAttributesKey].as !== "cachebust") {
return nextResolve(specifier, context);
}
// no need to resolve at all, we have all necessary information
return {
url: bustFileName(specifier),
format: context.importAttributes.format,
importAttributes: context.importAttributes,
format: context[importAttributesKey].format,
[importAttributesKey]: context[importAttributesKey],
shortCircuit: true,
};
}
Expand All @@ -41,13 +55,14 @@ async function resolve(specifier, context, nextResolve) {
* @returns {Promise<LoadResult>}
*/
async function load(url, context, nextLoad) {
if (context.importAttributes.as !== "cachebust") {
const importAttributesKey = importAttributesKeyName(context);
if (context[importAttributesKey].as !== "cachebust") {
return nextLoad(url, context);
}
return {
format: context.format || "module",
shortCircuit: true,
source: context.importAttributes.contents,
source: context[importAttributesKey].contents,
};
}

Expand Down
6 changes: 4 additions & 2 deletions src/language-server/config/cache-busting-resolver.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ type Format =

export interface ResolveContext {
conditions: string[];
importAttributes: ImportAttributes;
importAttributes?: ImportAttributes;
importAssertions: ImportAttributes;
parentURL?: string;
}

export interface ImportContext {
conditions: string[];
importAttributes: ImportAttributes;
importAttributes?: ImportAttributes;
importAssertions: ImportAttributes;
format: Format;
}

Expand Down

0 comments on commit 913e6ae

Please sign in to comment.