Skip to content

Commit

Permalink
feat: use jsr instead and remove vendor
Browse files Browse the repository at this point in the history
  • Loading branch information
mindon committed Aug 21, 2024
1 parent 0fe4e2c commit 86d29b4
Show file tree
Hide file tree
Showing 38 changed files with 213 additions and 1,893 deletions.
7 changes: 5 additions & 2 deletions bundle_util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function bundleByEsbuild(
plugins?: Plugin[],
): Promise<string> {
const importMapFile = getImportMap();
let importMapURL: URL;
let importMapURL: URL | null = null;
if (importMapFile) {
importMapURL = toFileUrl(resolve(importMapFile));
}
Expand Down Expand Up @@ -60,7 +60,7 @@ export async function bundleByEsbuild(
if (!plugins) plugins = [];
plugins.push(npmLocal.resolve);
plugins.push(denoResolverPlugin({
importMapURL,
importMapURL: importMapURL?.toString(),
}));
plugins = plugins.concat(denoPlugins());
const entryPoint = /^https?:\/\//.test(path)
Expand All @@ -81,6 +81,9 @@ export async function bundleByEsbuild(
jsxImportSource,
format: "esm",
platform: "browser",
supported: {
decorators: false,
},
...(options || {}),
});
return bundle.outputFiles![0].text;
Expand Down
30 changes: 20 additions & 10 deletions bundlet.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import { basename, dirname, ensureDir, join, relative } from "./deps.ts";
import {
basename,
BuildOptions,
denoPlugins,
dirname,
ensureDir,
join,
OnResolveArgs,
Plugin,
PluginBuild,
relative,
} from "./deps.ts";
import { md5 } from "./util.ts";
import { logger } from "./logger_util.ts";
import { byteSize } from "./util.ts";
import { bundleByEsbuild } from "./bundle_util.ts";
import { denoPlugin } from "./vendor/esbuild_deno_loader/mod.ts";
import * as esbuild from "https://deno.land/x/[email protected]/mod.js";
import * as npmLocal from "./npm_local.ts";

const bx =
Expand Down Expand Up @@ -96,7 +105,8 @@ export async function confRules(
let data = "";
let { options, plugins } = await bundlet(src, pathPrefix, distDir, mx);
if (!plugins) plugins = [];
plugins.concat(npmLocal.resolve, denoPlugin());
plugins = plugins.concat(npmLocal.resolve);
plugins = plugins.concat(denoPlugins());
data = await bundleByEsbuild(src, options, plugins);

let base = join(
Expand Down Expand Up @@ -153,7 +163,7 @@ export const bundlet = async function (
pathPrefix: string,
distDir?: string,
mappings?: { [name: string]: string },
): Promise<{ options?: esbuild.BuildOptions; plugins?: esbuild.Plugin[] }> {
): Promise<{ options?: BuildOptions; plugins?: Plugin[] }> {
if (!distDir) {
return {};
}
Expand All @@ -165,7 +175,7 @@ export const bundlet = async function (
body.replace(
/((?:^|\n)[ \t]*(?:export|import)[^"']+["'])([a-zA-Z][^"':]+)(["']\s*;)/g,
(s, a, b, c) => {
if (b.startsWith(".") || urlpath.test(b) || npmpath.test(b)) {
if (b.startsWith(".") || urlpath.test(b)) {
return s;
}
return `${a}${base}/${b}${c}`;
Expand All @@ -175,7 +185,7 @@ export const bundlet = async function (
body = await Deno.readTextFile(flpath);
}

const options: esbuild.BuildOptions = { platform: "browser", format: "esm" };
const options: BuildOptions = { platform: "browser", format: "esm" };
if (!distDir) distDir = "dist";
const { x, dirs, names } = await confRules(body, {
flpath,
Expand Down Expand Up @@ -204,12 +214,12 @@ export const bundlet = async function (
return t;
};

const ignores = (): esbuild.Plugin => ({
const ignores = (): Plugin => ({
name: "bundlet-keep-imports",
setup(build: esbuild.PluginBuild) {
setup(build: PluginBuild) {
build.onResolve({
filter: namesFilter(names),
}, (args: esbuild.OnResolveArgs) => {
}, (args: OnResolveArgs) => {
let target = args.path;
const name = basename(target);
const key = name.replace(
Expand Down
2 changes: 1 addition & 1 deletion cli_test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
import { assertEquals } from "./test_deps.ts";
import { main } from "./cli.ts";

Deno.test("cli.ts -h, --help -- returns 0", async () => {
Expand Down
34 changes: 15 additions & 19 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
{
"lock": false,
"fmt": {
"files": {
"exclude": [
"docs",
"dist",
"vendor",
"coverage",
".git"
]
}
"exclude": [
"docs",
"dist",
"vendor",
"coverage",
".git"
]
},
"lint": {
"files": {
"exclude": [
"examples",
"docs",
"dist",
"vendor",
"coverage",
".git"
]
}
"exclude": [
"examples",
"docs",
"dist",
"vendor",
"coverage",
".git"
]
}
}
51 changes: 25 additions & 26 deletions deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,43 @@ export {
relative,
resolve,
toFileUrl,
} from "https://deno.land/std/path/mod.ts";
import { join } from "https://deno.land/[email protected]/path/posix.ts";
export { join as posixPathJoin };
export { ensureDir } from "https://deno.land/std/fs/ensure_dir.ts";
export { parse as parseJsonC } from "https://deno.land/std/jsonc/mod.ts";
export { parse as parseFlags } from "https://deno.land/std/flags/mod.ts";
export { red } from "https://deno.land/std/fmt/colors.ts";
export { MuxAsyncIterator } from "https://deno.land/std/async/mux_async_iterator.ts";
export { walk } from "https://deno.land/std/fs/walk.ts";
} from "jsr:@std/path";
export { join as posixPathJoin } from "jsr:@std/path/posix";
export { ensureDir, exists } from "jsr:@std/fs";
export { parse as parseJsonC } from "jsr:@std/jsonc";
export { parse as parseFlags } from "jsr:@std/flags";
export { red } from "jsr:@std/fmt/colors";
export { MuxAsyncIterator } from "jsr:@std/async";
export { walk } from "jsr:@std/fs/walk";
export {
denoLoaderPlugin,
denoPlugins,
denoResolverPlugin,
} from "https://deno.land/x/esbuild_deno_loader/mod.ts";
export { build, stop } from "https://deno.land/x/esbuild@v0.17.19/mod.js";
export type { CommonOptions, Plugin } from "https://deno.land/x/esbuild/mod.js";
export { exists } from "https://deno.land/std/fs/mod.ts";

export {
Document,
DOMParser,
Element,
} from "https://deno.land/x/[email protected]/deno-dom-wasm.ts";
} from "jsr:@luca/esbuild-deno-loader";
export { build, stop } from "https://deno.land/x/esbuild@v0.23.1/mod.js";
export type {
BuildOptions,
CommonOptions,
OnResolveArgs,
Plugin,
PluginBuild,
} from "https://deno.land/x/[email protected]/mod.js";
export { Document, DOMParser, Element } from "jsr:@b-fuze/deno-dom/wasm";

export { opn } from "https://raw.githubusercontent.com/hashrock/deno-opn/b358e4c7df5d1c6d5e634d2730ca491ba6062782/opn.ts";
export { serve as serveIterable } from "https://deno.land/x/[email protected]/mod.ts";

export const NAME = "packup";
export const VERSION = "v0.2.6";

export { crypto } from "https://deno.land/std/crypto/mod.ts";
export { encodeHex } from "https://deno.land/std/encoding/hex.ts";
export { crypto } from "jsr:@std/crypto";
import { encodeHex } from "jsr:@std/encoding";
export { encodeHex };

export const md5sum = async function (data: string | ArrayBuffer) {
return encodeHex(
await crypto.subtle.digest(
"MD5",
typeof data === "string" ? new TextEncoder().encode(data) : data,
),
const d = await crypto.subtle.digest(
"MD5",
typeof data === "string" ? new TextEncoder().encode(data) : data,
);
return await encodeHex(d);
};
51 changes: 29 additions & 22 deletions generate_assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*/
import {
basename,
BuildOptions,
dirname,
Document,
DOMParser,
Expand All @@ -31,7 +32,6 @@ import { bundleByEsbuild } from "./bundle_util.ts";
import { logger } from "./logger_util.ts";
import { compile as compileSass } from "./sass_util.ts";
import { bundlet } from "./bundlet.ts";
import * as esbuild from "https://deno.land/x/[email protected]/mod.js";

// get name and prefix from src
function namePrefix(
Expand Down Expand Up @@ -158,7 +158,7 @@ export async function* watchAndGenAssets(
const pure = /.*\/([^/]+)\.[a-z\d]{32}(\.[a-z\d]{2,})$/;
const jsext = /\.js$/i;
while (true) {
const c = {};
const c: any = {};
for await (const file of assets) {
c[file.name.replace(pure, "$1$2")] = true;
yield file;
Expand All @@ -169,7 +169,7 @@ export async function* watchAndGenAssets(
if (!jsext.test(name) || c[name.substring(i < 0 ? 0 : i + 1)]) {
continue;
}
const files = await new ScriptAsset(relative("src", name), null)
const files = await new ScriptAsset(relative("src", name))
.createFileObject(jsopts);
for (let i = 0, imax = files.length; i < imax; i++) {
if (files[i]?.name) {
Expand All @@ -195,7 +195,7 @@ type CreateFileObjectParams = {
base: string;
pathPrefix: string;
distDir?: string;
options?: esbuild.BuildOptions;
options?: BuildOptions;
};

type Asset = {
Expand Down Expand Up @@ -241,7 +241,10 @@ class HtmlAsset implements Asset {
createFileObject(_params: CreateFileObjectParams) {
const { name } = namePrefix(this.base, this.#path);
return Promise.resolve([Object.assign(
new Blob([docType, encoder.encode(this.#doc.documentElement!.outerHTML)]),
new Blob([
docType,
encoder.encode(this.#doc.documentElement!.outerHTML),
]) as any,
{
name,
lastModified: (Deno.statSync(this.#path).mtime?.getTime() ?? 0) / 1000,
Expand Down Expand Up @@ -307,7 +310,7 @@ class CssAsset implements Asset {
this._dest = `${name}.${await md5(data)}.css`;
this._el.setAttribute("href", join(prefix || pathPrefix, this._dest));
return [
Object.assign(new Blob([data]), {
Object.assign(new Blob([data]) as any, {
name: this._dest,
lastModified: (info.mtime?.getTime() ?? 0) / 1000,
}),
Expand All @@ -328,10 +331,15 @@ class ScssAsset extends CssAsset {
const { name, prefix } = namePrefix(base, flpath);
this._dest = `${name}.${await md5(scss)}.css`;
this._el.setAttribute("href", join(prefix || pathPrefix, this._dest));
return [Object.assign(new Blob([await compileSass(decoder.decode(scss))]), {
name: this._dest,
lastModified: (info.mtime?.getTime() ?? 0) / 1000,
})];
return [
Object.assign(
new Blob([await compileSass(decoder.decode(scss))]) as any,
{
name: this._dest,
lastModified: (info.mtime?.getTime() ?? 0) / 1000,
},
),
];
}
}

Expand All @@ -353,17 +361,16 @@ class ScriptAsset implements Asset {

#src: string;
#dest?: string;
#el: Element;
#el?: Element;

constructor(src: string, script: Element) {
constructor(src: string, script?: Element) {
this.#src = src;
this.#el = script;
}

async getWatchPaths(base: string): Promise<string[]> {
let src = this.#src;
const i = src.indexOf("?");
const search = i > -1 ? src.substring(i) : "";
if (i > -1) {
src = src.substring(0, i);
}
Expand Down Expand Up @@ -392,7 +399,7 @@ class ScriptAsset implements Asset {
}

const flpath = join(base, src);
let info = {};
let info: any = {};
try {
info = await Deno.stat(flpath);
} catch (err) {
Expand All @@ -403,13 +410,13 @@ class ScriptAsset implements Asset {
const { options, plugins } = await bundlet(flpath, pathPrefix, distDir);
const data = await bundleByEsbuild(flpath, options, plugins);
const { name, prefix } = namePrefix(base, flpath);
this.#dest = `${name}.${await md5(data)}.js`;
this.#dest = `${name}.${md5(data)}.js`;
this.#el?.setAttribute(
"src",
join(prefix || pathPrefix, this.#dest) + search,
);
return [
Object.assign(new Blob([data]), {
Object.assign(new Blob([data]) as any, {
name: this.#dest,
lastModified: (info.mtime?.getTime() ?? 0) / 1000,
}),
Expand All @@ -433,19 +440,19 @@ class ImageAsset implements Asset {
if (src && isLocalUrl(src) && !src.startsWith("data:")) sources.push(src);
if (srcset) {
sources.push(
...srcset.filter((src) => !src.startsWith("data:"))
...srcset
.split(",") // Separate the different srcset
.filter(Boolean) // Remove empty strings
.map((src) => src.trim()) // Remove white spaces
.map((src) => src.split(" ")[0]) // Separate the source from the size
.filter((src: string) => src && !src.startsWith("data:")) // Remove empty strings
.map((src: string) => src.trim()) // Remove white spaces
.map((src: string) => src.split(" ")[0]) // Separate the source from the size
.filter(isLocalUrl), // Remove external references
);
}

// Remove duplicates
sources = [
...new Set(
sources.filter((d) =>
sources.filter((src) =>
!src.startsWith("data:") && src.indexOf("{{") < 0
),
),
Expand Down Expand Up @@ -529,7 +536,7 @@ class ImageAsset implements Asset {

const info = await Deno.stat(flpath);
files.push(
Object.assign(new Blob([data]), {
Object.assign(new Blob([data]) as any, {
name: dest,
lastModified: (info.mtime?.getTime() ?? 0) / 1000,
}),
Expand Down
Loading

0 comments on commit 86d29b4

Please sign in to comment.