Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Run the code through prettier for smller diffs in PR's #368

Merged
merged 1 commit into from
Jul 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/common/fetch-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,13 @@ function sourceResponse(buffer: string | Buffer) {
return JSON.parse(buffer.toString());
},
arrayBuffer() {
if (typeof buffer === 'string')
if (typeof buffer === "string")
return new TextEncoder().encode(buffer.toString()).buffer;
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
return new Uint8Array(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength
);
},
};
}
Expand Down
8 changes: 4 additions & 4 deletions src/common/wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
//@ts-ignore
import { fetch } from '#fetch';
import { parse, init } from 'es-module-lexer';
import { fetch } from "#fetch";
import { parse, init } from "es-module-lexer";

export async function getMaybeWrapperUrl (moduleUrl, fetchOpts) {
export async function getMaybeWrapperUrl(moduleUrl, fetchOpts) {
await init;
const source = await (await fetch(moduleUrl, fetchOpts)).text();
const [imports,, facade] = parse(source);
const [imports, , facade] = parse(source);
if (facade && imports.length) {
try {
return new URL(imports[0].n, moduleUrl).href;
Expand Down
121 changes: 70 additions & 51 deletions src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { LockResolutions } from "./install/lock.js";
import { getDefaultProviderStrings, type Provider } from "./providers/index.js";
import * as nodemodules from "./providers/nodemodules.js";
import { Resolver } from "./trace/resolver.js";
import { getMaybeWrapperUrl } from './common/wrapper.js';
import { getMaybeWrapperUrl } from "./common/wrapper.js";

// Utility exports for users:
export { analyzeHtml };
Expand Down Expand Up @@ -297,7 +297,7 @@ export interface GeneratorOptions {
* Disabled by default.
*/
commonJS?: boolean;

/**
* Support tracing TypeScript dependencies when generating the import map.
* Disabled by default.
Expand All @@ -311,7 +311,14 @@ export interface GeneratorOptions {
}

export interface ModuleAnalysis {
format: "commonjs" | "esm" | "system" | "json" | "css" | "typescript" | "wasm";
format:
| "commonjs"
| "esm"
| "system"
| "json"
| "css"
| "typescript"
| "wasm";
staticDeps: string[];
dynamicDeps: string[];
cjsLazyDeps: string[] | null;
Expand Down Expand Up @@ -417,11 +424,9 @@ export class Generator {
timeout: 10000,
...fetchOptions,
headers: { "Accept-Encoding": "gzip, br" },
}
if (cache === "offline")
fetchOpts.cache = "force-cache"
else if (!cache)
fetchOpts.cache = "no-store";
};
if (cache === "offline") fetchOpts.cache = "force-cache";
else if (!cache) fetchOpts.cache = "no-store";

// Default logic for the mapUrl, baseUrl and rootUrl:
if (mapUrl && !baseUrl) {
Expand Down Expand Up @@ -461,7 +466,14 @@ export class Generator {
this.integrity = integrity;

// Initialise the resolver:
const resolver = new Resolver({ env, log, fetchOpts, preserveSymlinks: true, traceCjs: commonJS, traceTs: typeScript });
const resolver = new Resolver({
env,
log,
fetchOpts,
preserveSymlinks: true,
traceCjs: commonJS,
traceTs: typeScript,
});
if (customProviders) {
for (const provider of Object.keys(customProviders)) {
resolver.addCustomProvider(provider, customProviders[provider]);
Expand Down Expand Up @@ -495,16 +507,15 @@ export class Generator {
providers,
ignore,
resolutions,
commonJS
commonJS,
},
log,
resolver
);

// Reconstruct constraints and locks from the input map:
this.map = new ImportMap({ mapUrl: this.mapUrl, rootUrl: this.rootUrl });
if (!integrity)
this.map.integrity = {};
if (!integrity) this.map.integrity = {};
if (inputMap) this.addMappings(inputMap);
}

Expand Down Expand Up @@ -669,9 +680,7 @@ export class Generator {
" Generated by @jspm/generator - https://github.com/jspm/generator ";
if (typeof htmlUrl === "string") htmlUrl = new URL(htmlUrl);
if (this.installCnt !== 0)
throw new JspmError(
"htmlInject cannot run alongside other install ops"
);
throw new JspmError("htmlInject cannot run alongside other install ops");

const analysis = analyzeHtml(html, htmlUrl);

Expand All @@ -696,13 +705,16 @@ export class Generator {
);
}

const preloadDeps = preload === "all" ? [...new Set([...staticDeps, ...dynamicDeps])] : staticDeps;
const preloadDeps =
preload === "all"
? [...new Set([...staticDeps, ...dynamicDeps])]
: staticDeps;

const newlineTab = !whitespace
? analysis.newlineTab
: analysis.newlineTab.includes("\n")
? analysis.newlineTab
: "\n" + analysis.newlineTab;
? analysis.newlineTab
: "\n" + analysis.newlineTab;

const replacer = new Replacer(html);

Expand Down Expand Up @@ -740,7 +752,10 @@ export class Generator {
)) + "dist/es-module-shims.js";

// detect esmsUrl as a wrapper URL
esmsUrl = await getMaybeWrapperUrl(esmsUrl, this.traceMap.resolver.fetchOpts);
esmsUrl = await getMaybeWrapperUrl(
esmsUrl,
this.traceMap.resolver.fetchOpts
);

if (htmlUrl || rootUrl)
esmsUrl = relativeUrl(
Expand All @@ -749,12 +764,17 @@ export class Generator {
!!rootUrl
);

esms = `<script async src="${esmsUrl}" crossorigin="anonymous"${integrity
? ` integrity="${getIntegrity(
new Uint8Array(await (await fetch(esmsUrl, this.traceMap.resolver.fetchOpts)).arrayBuffer())
)}"`
: ""
}></script>${newlineTab}`;
esms = `<script async src="${esmsUrl}" crossorigin="anonymous"${
integrity
? ` integrity="${getIntegrity(
new Uint8Array(
await (
await fetch(esmsUrl, this.traceMap.resolver.fetchOpts)
).arrayBuffer()
)
)}"`
: ""
}></script>${newlineTab}`;

if (analysis.esModuleShims)
replacer.remove(
Expand All @@ -774,14 +794,11 @@ export class Generator {
for (let dep of preloadDeps.sort()) {
if (first || whitespace) preloads += newlineTab;
if (first) first = false;
preloads += `<link rel="modulepreload" href="${rootUrl || htmlUrl
? relativeUrl(
new URL(dep),
new URL(rootUrl || htmlUrl),
!!rootUrl
)
: dep
}" />`;
preloads += `<link rel="modulepreload" href="${
rootUrl || htmlUrl
? relativeUrl(new URL(dep), new URL(rootUrl || htmlUrl), !!rootUrl)
: dep
}" />`;
}
}

Expand All @@ -800,17 +817,17 @@ export class Generator {
analysis.map.start,
analysis.map.end,
(comment ? "<!--" + comment + "-->" + newlineTab : "") +
esms +
'<script type="importmap">' +
(whitespace ? newlineTab : "") +
JSON.stringify(map, null, whitespace ? 2 : 0).replace(
/\n/g,
newlineTab
) +
(whitespace ? newlineTab : "") +
"</script>" +
preloads +
(analysis.map.newScript ? newlineTab : "")
esms +
'<script type="importmap">' +
(whitespace ? newlineTab : "") +
JSON.stringify(map, null, whitespace ? 2 : 0).replace(
/\n/g,
newlineTab
) +
(whitespace ? newlineTab : "") +
"</script>" +
preloads +
(analysis.map.newScript ? newlineTab : "")
);

return replacer.source;
Expand Down Expand Up @@ -850,7 +867,6 @@ export class Generator {
install?: string | Install | (string | Install)[],
mode?: InstallMode
): Promise<void | { staticDeps: string[]; dynamicDeps: string[] }> {

// If there are no arguments, then we reinstall all the top-level locks:
if (install === null || install === undefined) {
await this.traceMap.processInputMap;
Expand Down Expand Up @@ -1097,7 +1113,8 @@ export class Generator {
}
this.traceMap.pins = pins;
if (--this.installCnt === 0) {
const { staticDeps, dynamicDeps, map } = await this.traceMap.finishInstall(this.traceMap.pins, this.integrity);
const { staticDeps, dynamicDeps, map } =
await this.traceMap.finishInstall(this.traceMap.pins, this.integrity);
this.map = map;
return { staticDeps, dynamicDeps };
}
Expand All @@ -1112,7 +1129,7 @@ export class Generator {
if (typeof mapUrl === "string") mapUrl = new URL(mapUrl, this.baseUrl);
if (typeof rootUrl === "string") rootUrl = new URL(rootUrl, this.baseUrl);
if (!Array.isArray(pins)) pins = [pins];
if (typeof integrity !== 'boolean') integrity = this.integrity;
if (typeof integrity !== "boolean") integrity = this.integrity;
if (this.installCnt++ !== 0)
throw new JspmError(`Cannot run extract map during installs`);
this.traceMap.startInstall();
Expand Down Expand Up @@ -1374,10 +1391,12 @@ async function installToTarget(
(install.subpath !== "." && !install.subpath.startsWith("./")))
)
throw new Error(
`Install subpath "${install.subpath
}" must be a string equal to "." or starting with "./".${typeof install.subpath === "string"
? `\nTry setting the subpath to "./${install.subpath}"`
: ""
`Install subpath "${
install.subpath
}" must be a string equal to "." or starting with "./".${
typeof install.subpath === "string"
? `\nTry setting the subpath to "./${install.subpath}"`
: ""
}`
);

Expand Down
2 changes: 1 addition & 1 deletion src/install/installer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export type InstallMode =

export type InstallTarget = {
pkgTarget: PackageTarget | URL;
installSubpath: null | '.' | `./${string}`;
installSubpath: null | "." | `./${string}`;
};

export interface InstallerOptions {
Expand Down
6 changes: 3 additions & 3 deletions src/install/lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export interface VersionConstraints {

export interface InstalledResolution {
installUrl: `${string}/`;
installSubpath: '.' | `./${string}` | null;
installSubpath: "." | `./${string}` | null;
}

export interface FlatInstalledResolution {
Expand Down Expand Up @@ -126,7 +126,7 @@ export function setResolution(
name: string,
installUrl: `${string}/`,
pkgScope: `${string}/` | null = null,
installSubpath: '.' | `./${string}` | null = null
installSubpath: "." | `./${string}` | null = null
) {
if (pkgScope && !pkgScope.endsWith("/")) throwInternalError(pkgScope);
if (pkgScope === null) {
Expand Down Expand Up @@ -513,7 +513,7 @@ export async function extractLockConstraintsAndMap(

// In the case of subpaths having diverging versions, we force convergence on one version
// Only scopes permit unpacking
let installSubpath: null | '.' | './' | `./${string}/` | false = null;
let installSubpath: null | "." | "./" | `./${string}/` | false = null;
if (parsedKey.subpath !== exportSubpath) {
if (parsedKey.subpath === ".") {
installSubpath = exportSubpath as `./${string}/`;
Expand Down
12 changes: 6 additions & 6 deletions src/providers/esmsh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export async function pkgToUrl(pkg: ExactPackage): Promise<`${string}/`> {
return `${cdnUrl}*${pkg.name}@${pkg.version}/`;
}

const exactPkgRegEx = /^(?:v\d+\/)?\*?((?:@[^/\\%@]+\/)?[^./\\%@][^/\\%@]*)@([^\/]+)(\/.*)?$/;
const exactPkgRegEx =
/^(?:v\d+\/)?\*?((?:@[^/\\%@]+\/)?[^./\\%@][^/\\%@]*)@([^\/]+)(\/.*)?$/;

export function parseUrlPkg(url: string) {
if (!url.startsWith(cdnUrl)) return;
Expand Down Expand Up @@ -54,17 +55,16 @@ export async function getPackageConfig(
if (pcfg.exports) {
// in the conditional expoort case, paths seem to work?
// so go with that
if (Object.keys(pcfg.exports).every(key => !key.startsWith('./'))) {
pcfg.exports['.'] = pcfg.exports;
}
else {
if (Object.keys(pcfg.exports).every((key) => !key.startsWith("./"))) {
pcfg.exports["."] = pcfg.exports;
} else {
// let esm.sh resolve conditions
for (const key of Object.keys(pcfg.exports)) {
pcfg.exports[key] = key;
}
}
// wildcard key for esmsh to do its own fallback resolution too
pcfg.exports['./*'] = './*';
pcfg.exports["./*"] = "./*";
}
if (pcfg.imports) {
for (const key of Object.keys(pcfg.imports)) {
Expand Down
2 changes: 1 addition & 1 deletion src/providers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const defaultProviders: Record<string, Provider> = {
skypack,
unpkg,
"esm.sh": esmsh,
"jspm.io": jspm
"jspm.io": jspm,
};

export function getProvider(name: string, providers: Record<string, Provider>) {
Expand Down
4 changes: 3 additions & 1 deletion src/providers/jspm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ async function lookupRange(
);
default:
throw new JspmError(
`Invalid status code ${res.status} looking up "${registry}:${name}" from ${url} - ${
`Invalid status code ${
res.status
} looking up "${registry}:${name}" from ${url} - ${
res.statusText
}${importedFrom(parentUrl)}`
);
Expand Down
3 changes: 1 addition & 2 deletions src/providers/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ export function resolveBuiltin(
}

// Strip the subpath for subpathed builtins
if (builtin.includes('/'))
builtin = builtin.split('/')[0];
if (builtin.includes("/")) builtin = builtin.split("/")[0];

return {
target: {
Expand Down
Loading
Loading