From bf6ef0edf4a32c4e745e32b16b267cab865ad038 Mon Sep 17 00:00:00 2001 From: Okiki Date: Sat, 11 Mar 2023 00:15:50 +0000 Subject: [PATCH] chore: save... --- packages/core/repl.ts | 2 +- packages/core/src/build.ts | 11 ++- packages/core/src/plugins/cdn.ts | 2 +- packages/core/src/plugins/http.ts | 1 + packages/core/src/utils/parse-package-name.ts | 12 ++-- packages/edge/bundle.ts | 30 ++++++-- packages/edge/generate-result.ts | 72 +++++++++++++++---- packages/edge/gist.ts | 27 ++++--- packages/edge/mod.ts | 10 +-- 9 files changed, 120 insertions(+), 47 deletions(-) diff --git a/packages/core/repl.ts b/packages/core/repl.ts index 34115e1..2068b5b 100644 --- a/packages/core/repl.ts +++ b/packages/core/repl.ts @@ -5,7 +5,7 @@ const fs = await TheFileSystem; console.log("\n"); await setFile(fs, "/index.tsx", `\ export * as Other from "/new.tsx"; -export * from "@okikio/animate";`); +export * from "spring-easing";`); await setFile(fs, "/new.tsx", "export * from \"@okikio/native\";"); await setFile(fs, "/other.tsx", `\ export * as Other from "/index.tsx"; diff --git a/packages/core/src/build.ts b/packages/core/src/build.ts index 1de5a5f..7c845ea 100644 --- a/packages/core/src/build.ts +++ b/packages/core/src/build.ts @@ -29,6 +29,11 @@ export type LocalState = { */ assets?: ESBUILD.OutputFile[], + /** + * Versions + */ + versions?: Map, + /** * Array storing the [getter, setter] of the global state */ @@ -153,20 +158,20 @@ export async function build(opts: BuildConfig = {}, filesystem = TheFileSystem): } catch (e) { if (e.errors) { // Log errors with added color info. to the virtual console - const ansiMsgs = [...await createNotice(e.errors, "error", false)]; + const ansiMsgs = await createNotice(e.errors, "error", false) ?? []; dispatchEvent(LOGGER_ERROR, new Error(ansiMsgs.join("\n"))); const message = (ansiMsgs.length > 1 ? `${ansiMsgs.length} error(s) ` : "") + "(if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundlejs)"; dispatchEvent(LOGGER_ERROR, new Error(message)); - const htmlMsgs = [...await createNotice(e.errors, "error")]; + const htmlMsgs = await createNotice(e.errors, "error") ?? []; throw { msgs: htmlMsgs }; } else throw e; } if (result.warnings) { // Log errors with added color info. to the virtual console - const ansiMsgs = [...await createNotice(result.warnings, "warning", false)]; + const ansiMsgs = await createNotice(result.warnings, "warning", false) ?? []; dispatchEvent(LOGGER_WARN, ansiMsgs.join("\n")); const message = `${ansiMsgs.length} warning(s) `; diff --git a/packages/core/src/plugins/cdn.ts b/packages/core/src/plugins/cdn.ts index cfb2bac..d6f0405 100644 --- a/packages/core/src/plugins/cdn.ts +++ b/packages/core/src/plugins/cdn.ts @@ -6,7 +6,7 @@ import { dispatchEvent, LOGGER_WARN } from "../configs/events.ts"; import { determineExtension, HTTP_NAMESPACE } from "./http.ts"; import { resolve, legacy } from "resolve.exports"; -import { parsePackageName as parsePackageName } from "../utils/parse-package-name.ts"; +import { parsePackageName } from "../utils/parse-package-name.ts"; import { extname, isBareImport } from "../utils/path.ts"; import { getRequest } from "../utils/fetch-and-cache.ts"; diff --git a/packages/core/src/plugins/http.ts b/packages/core/src/plugins/http.ts index 4737bb2..4eec2a3 100644 --- a/packages/core/src/plugins/http.ts +++ b/packages/core/src/plugins/http.ts @@ -8,6 +8,7 @@ import { dispatchEvent, LOGGER_ERROR, LOGGER_INFO, LOGGER_WARN } from "../config import { CDN_RESOLVE } from "./cdn.ts"; import { getRequest } from "../utils/fetch-and-cache.ts"; import { decode } from "../utils/encode-decode.ts"; +import { parsePackageName } from "../utils/parse-package-name.ts"; import { getCDNUrl, DEFAULT_CDN_HOST, getCDNStyle } from "../utils/util-cdn.ts"; import { inferLoader } from "../utils/loader.ts"; diff --git a/packages/core/src/utils/parse-package-name.ts b/packages/core/src/utils/parse-package-name.ts index 2768d28..f67d630 100644 --- a/packages/core/src/utils/parse-package-name.ts +++ b/packages/core/src/utils/parse-package-name.ts @@ -8,17 +8,17 @@ export const RE_SCOPED = /^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/; /** Parsed a non-scoped package name into name, version, path */ export const RE_NON_SCOPED = /^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/; -export function parsePackageName(input: string) { +export function parsePackageName(input: string, ignoreError = false) { const m = RE_SCOPED.exec(input) || RE_NON_SCOPED.exec(input); - if (!m) { + if (!m && !ignoreError) { throw new Error(`[parse-package-name] invalid package name: ${input}`); } - + return { - name: m[1] || "", - version: m[2] || "latest", - path: m[3] || "", + name: m?.[1] || "", + version: m?.[2] || "latest", + path: m?.[3] || "", }; } diff --git a/packages/edge/bundle.ts b/packages/edge/bundle.ts index cc3322a..c44302f 100644 --- a/packages/edge/bundle.ts +++ b/packages/edge/bundle.ts @@ -10,7 +10,7 @@ import type { Config } from "./mod.ts"; import { headers } from "./mod.ts"; import { setFile as setGist } from "./gist.ts"; -import { build, setFile, useFileSystem, createConfig, compress } from "@bundlejs/core/src/index.ts"; +import { build, setFile, useFileSystem, createConfig, compress, resolveVersion } from "@bundlejs/core/src/index.ts"; import { createNotice } from "@bundlejs/core/src/utils/create-notice.ts"; @@ -25,6 +25,8 @@ export type BundleResult = { rawQuery: string, config: Config input: string, + version?: string, + versions?: string[], size: Omit>, "content">, time: string, rawTime: number, @@ -35,7 +37,7 @@ export type BundleResult = { } export const inputModelResetValue = [ - 'export * from "@okikio/animate";' + 'export * from "spring-easing";' ].join("\n"); export async function bundle(url: URL, initialValue: string, configObj: Config) { @@ -68,13 +70,31 @@ export async function bundle(url: URL, initialValue: string, configObj: Config) const { init: _init, ...printableConfig } = createConfig("build", configObj); const duration = (end - start); - - if (!resultText) { resultText = result.contents[0].text; } - const fileId = await setGist(url.href, resultText); + const fileId = await setGist(url.href, result.outputs); + const allPkgs = ( + ( + url.searchParams.get("q") || + url.searchParams.get("query") + ) ?? "spring-easing" + ).split(","); + const versionsList = await Promise.allSettled( + allPkgs + .filter(x => !/^https?\:\/\//.exec(x)) + .map(x => resolveVersion(x)) + ); + + const versions = []; + for (const version of versionsList) { + if (version.status === "fulfilled" && version.value) { + versions.push(version.value); + } + } + const finalResult: BundleResult = { query: decodeURIComponent(url.search), rawQuery: encodeURIComponent(url.search), + ...(versions.length === 1 ? { version: versions[0] } : versions), config: printableConfig, input: initialValue, size, diff --git a/packages/edge/generate-result.ts b/packages/edge/generate-result.ts index 1a801ba..4bd2134 100644 --- a/packages/edge/generate-result.ts +++ b/packages/edge/generate-result.ts @@ -4,6 +4,7 @@ import type { BundleResult } from "./bundle.ts"; import { LOGGER_INFO, dispatchEvent } from "@bundlejs/core/src/index.ts"; import { getFile } from "./gist.ts"; import { headers } from "./mod.ts"; +import styleText from "./style.ts"; export const timeFormatter = new Intl.RelativeTimeFormat("en", { style: "narrow", @@ -11,24 +12,31 @@ export const timeFormatter = new Intl.RelativeTimeFormat("en", { }) export const docs = { + docs: `/?docs - Takes you to some docs for the API`, examples: [ "(new) /?badge or /?badge=detailed", "(new) /?badge-style=for-the-badge", "(new) /?file", "(new) /?metafile", "(new) /?polyfill", - `/?q=(import)@okikio/emitter,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,@okikio/animate,typescript@beta,vue,react`, - `/?treeshake=[T],[{ animate }],[{ animate as B }],[* as TR],[{ type animate }],[*],[*],[*],[*]`, + `(new) /?warnings`, + `(new) /?raw`, + "~~~", + `/?q=spring-easing,(import)@okikio/emitter,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,@okikio/animate,typescript@beta,vue,react`, + `/?treeshake=[SpringEasing],[T],[{ animate }],[{ animate as B }],[* as TR],[{ type animate }],[*],[*],[*],[*]`, `/?text="export * as PR18 from \"@okikio/animate\";\nexport { animate as animate2 } from \"@okikio/animate\";"`, `/?share=MYewdgziA2CmB00QHMAUAiAwiG6CUQA`, `/?config={"cdn":"skypack","compression":"brotli","esbuild":{"format":"cjs","minify":false,"treeShaking":false}}`, ], - docs: [ + basics: [ `(new) /?badge - Generates a badge (if you want more details, set \`?badge=detailed\` you will get the uncompressed size and the mobules being bundled listed)`, `(new) /?badge-style - Various badge styles supported by http://shields.io (https://shields.io/#:~:text=PREFIX%3E%26suffix%3D%3CSUFFIX%3E-,Styles,-The%20following%20styles)`, `(new) /?file - Resulting bundled code(you can actually import this into your javascript file and start using it https://stackblitz.com/edit/vitejs-vite-iquaht?file=src%2Fmain.ts&terminal=dev)`, `(new) /?metafile - Esbuild bundle metafile which can be used w / https://esbuild.github.io/analyze/ (hoping to have this built-in in the future)`, `(new) /?polyfill - Polyfill Node built-ins`, + `(new) /?warnings - Lists warning for a particular bundle`, + `(new) /?raw - The raw result of the bundle (meant for experiments and/or testing)`, + "~~~", `/?q or /?query - Represents the module, e.g. react, vue, etc... You can add (import) in-front of a specific module to make it an import instead of an export`, `/?treeshake - Represents the export/imports to treeshake. The treeshake syntax allows for specifying multiple exports per package (check the example above). The square brackets represent seperate packages, and everything inside the square brackets, are the exported methods, types, etc...`, `/?text - Represents the input code as a string (it's meant for short strings, we recommend using \`/?share\` for longer strings)`, @@ -41,6 +49,9 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: const metafileQuery = url.searchParams.has("metafile"); const fileQuery = url.searchParams.has("file"); const badgeQuery = url.searchParams.has("badge"); + const warningsQuery = url.searchParams.has("warnings") || url.searchParams.has("warning"); + const docsQuery = url.searchParams.has("docs"); + const rawQuery = url.searchParams.has("raw"); const badgeResult = url.searchParams.get("badge"); const badgeStyle = url.searchParams.get("badge-style"); @@ -48,11 +59,8 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: if (badgeQuery) { const { size } = value; const detailedBadge = badgeResult?.includes("detail"); - console.log({ - detailedBadge - }) const urlQuery = encodeURIComponent(`https://bundlejs.com/${url.search}`); - const query = url.searchParams.get("q") ?? "@okikio/animate"; + const query = url.searchParams.get("q") ?? "spring-easing"; const detailBadgeText = ( detailedBadge ? `${encodeURIComponent(`${size.uncompressedSize} `)}->${encodeURIComponent(` `)}` : @@ -63,9 +71,8 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: `https://img.shields.io/badge/${detailBadgeName}-${detailBadgeText}${encodeURIComponent(`${size.compressedSize} (gzip)`) }-blue?link=${urlQuery}` ); - if (badgeStyle) { - imgUrl.searchParams.append("style", badgeStyle); - } + + if (badgeStyle) { imgUrl.searchParams.append("style", badgeStyle); } dispatchEvent(LOGGER_INFO, imgUrl.href) const imgFetch = await fetch(imgUrl); @@ -78,7 +85,7 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: status: 200, headers: [ ...headers, - ['Cache-Control', 'max-age=30, s-maxage=30, public'], + ['Cache-Control', 'max-age=7200, s-maxage=30, public'], ['Content-Type', 'image/svg+xml'] ], }) @@ -91,7 +98,7 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: status: 200, headers: [ ...headers, - ['Cache-Control', 'max-age=30, s-maxage=30, public'], + ['Cache-Control', 'max-age=3600, s-maxage=30, public'], ['Content-Type', 'text/javascript'] ], }) @@ -102,16 +109,44 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: status: 200, headers: [ ...headers, - ['Cache-Control', 'max-age=30, s-maxage=30, public'], + ['Cache-Control', 'max-age=3600, s-maxage=30, public'], ['Content-Type', 'application/json'] ], }) } - const { rawFile: _rawFile, metafile: _metafile, ...usefulInfo } = value; + if (warningsQuery) { + return new Response(generateHTMLMessages(value.warnings ?? ["No warnings for this bundle"]), + { + status: 200, + headers: [ + ...headers, + ['Cache-Control', 'max-age=3600, s-maxage=30, public'], + ['Content-Type', 'text/html'] + ] + } + ) + } + + if (docsQuery) { + return Response.redirect("https://blog.okikio.dev/documenting-an-online-bundler-bundlejs#heading-configuration"); + } + + if (rawQuery) { + return new Response(JSON.stringify(value), { + status: 200, + headers: [ + ...headers, + ['Cache-Control', 'max-age=30, s-maxage=30, public'], + ['Content-Type', 'application/json'] + ], + }); + } + + const { rawFile: _rawFile, metafile: _metafile, warnings: _warnings, ...usefulInfo } = value; const finalResult = { ...usefulInfo, - ...docs, + ...(url.search === "" ? docs : ""), ...( cached ? { time: timeFormatter.format(duration / 1000, "seconds"), @@ -128,4 +163,11 @@ export async function generateResult(badgeKey: string, value: BundleResult, url: ['Content-Type', 'application/json'] ], }) +} + +export function generateHTMLMessages(msgs: string[]) { + return [ + ``, + `
${msgs.join("\n")}
` + ].join(""); } \ No newline at end of file diff --git a/packages/edge/gist.ts b/packages/edge/gist.ts index 445f7cd..3b1b312 100644 --- a/packages/edge/gist.ts +++ b/packages/edge/gist.ts @@ -1,6 +1,7 @@ import { Octokit } from "npm:octokit"; import { dispatchEvent, LOGGER_ERROR, LOGGER_WARN } from "@bundlejs/core/src/index.ts"; import { Velo } from "https://deno.land/x/velo/mod.ts"; +import { ESBUILD } from "../core/src/types.ts"; export const GIST_CACHE = Velo.builder().capacity(10).lru().ttl(120_000).build(); export const octokit = new Octokit({ @@ -8,19 +9,26 @@ export const octokit = new Octokit({ }) export const BUNDLE_FILE_PATH = "index.js"; -export async function setFile(url: string, text: string) { +export async function setFile(url: string, files: ESBUILD.OutputFile[]) { const newUrl = new URL(url); newUrl.hostname = "deno.bundlejs.dev"; try { - const fileId = ( + const filesObj = Object.fromEntries( + files.map(x => [ + x.path.replace(/^\.|\//g, "").replace(/[^\w-_.]/g, ""), + { content: x.text ?? "[bundlejs] Empty file..." } + ]) + ); + const result = ( await octokit.request('POST /gists', { description: `Result of ${newUrl.href}`, 'public': true, files: { - [BUNDLE_FILE_PATH]: { - content: text - }, + ...filesObj, + // [BUNDLE_FILE_PATH]: { + // content: text + // }, 'README.md': { content: `Hey 👋, this is a gist which stores the final bundle results of the bundlejs api, learn more on the website https://bundlejs.com. This is the result of ${newUrl.href}.` } @@ -29,8 +37,10 @@ export async function setFile(url: string, text: string) { 'X-GitHub-Api-Version': '2022-11-28' }, }) - ).data.id; - if (fileId) GIST_CACHE.set(fileId, text); + ).data; + console.log({ gistURl: result.html_url }) + const fileId = result.id; + if (fileId) GIST_CACHE.set(fileId, filesObj[BUNDLE_FILE_PATH].content); return fileId; } catch(e) { dispatchEvent(LOGGER_ERROR, e); @@ -68,8 +78,7 @@ export async function getFile(id: string) { } export function deleteFile(id: string) { - const rawFile = GIST_CACHE.has(id); - if (rawFile) GIST_CACHE.remove(id); + if (GIST_CACHE.has(id)) GIST_CACHE.remove(id); return octokit.request('DELETE /gists/{gist_id}', { gist_id: id, headers: { diff --git a/packages/edge/mod.ts b/packages/edge/mod.ts index c49ef51..9a47891 100644 --- a/packages/edge/mod.ts +++ b/packages/edge/mod.ts @@ -16,8 +16,7 @@ import { deepAssign, createConfig, lzstring, dispatchEvent, LOGGER_INFO, BUILD_C import ESBUILD_WASM from "@bundlejs/core/src/wasm.ts"; import { parseShareURLQuery, parseConfig } from "./parse-query.ts"; -import { generateResult } from "./generate-result.ts"; -import styleText from "./style.ts"; +import { generateHTMLMessages, generateResult } from "./generate-result.ts"; import { bundle, inputModelResetValue } from "./bundle.ts"; import { clearFiles as clearGists, deleteFile as deleteGist } from "./gist.ts"; @@ -176,13 +175,10 @@ serve(async (req: Request) => { return await generateResult(badgeKey, value, url, redis, false, Date.now() - start); } catch (e) { - if ("msgs" in e) { + if ("msgs" in e && e.msgs) { try { return new Response( - [ - ``, - `
${e.msgs.join("\n")}
` - ].join(""), + generateHTMLMessages(e.msgs as string[]), { status: 404, headers: [ -- knotmirror 0.0.1