Skip to content
Open
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
Binary file modified bun.lockb
Binary file not shown.
3 changes: 0 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,6 @@ interface CompressOptions {
*/
brotli?: boolean;

/**
* @default html,js,json,css,svg,xml,wasm
*/
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why you removed this comment?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why you removed this comment?

because its way more than those anymore

files?: string[];
}

Expand Down
82 changes: 28 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@ import {
writeFileSync,
} from "fs";
import { pipeline } from "stream";
import glob from "tiny-glob";
import { fileURLToPath } from "url";
import { promisify } from "util";
import zlib from "zlib";
import db from "mime-db";

const pipe = promisify(pipeline);

const files = fileURLToPath(new URL("./files", import.meta.url).href);

/** @type {import('.').default} */
export default function (opts = {}) {
/** @type {import('.').default} */ export default function (opts = {}) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here

const {
out = "build",
precompress = false,
Expand All @@ -32,33 +30,26 @@ export default function (opts = {}) {
async adapt(builder) {
builder.rimraf(out);
builder.mkdirp(out);

builder.log.minor("Copying assets");
builder.writeClient(`${out}/client${builder.config.kit.paths.base}`);
builder.writePrerendered(`${out}/prerendered${builder.config.kit.paths.base}`);

if (precompress) {
builder.log.minor("Compressing assets");
await Promise.all([
compress(`${out}/client`, precompress),
compress(`${out}/prerendered`, precompress),
]);
}

builder.log.minor("Building server");
builder.writeServer(`${out}/server`);

writeFileSync(
`${out}/manifest.js`,
`export const manifest = ${builder.generateManifest({ relativePath: "./server" })};\n\n` +
`export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n`,
);

builder.log.minor("Patching server (websocket support)");
patchServerWebsocketHandler(`${out}/server`);

const pkg = JSON.parse(readFileSync("package.json", "utf8"));

builder.copy(files, out, {
replace: {
SERVER: "./server/index.js",
Expand All @@ -68,77 +59,68 @@ export default function (opts = {}) {
BUILD_OPTIONS: JSON.stringify({ development, dynamic_origin, xff_depth, assets }),
},
});

let package_data = {
name: "bun-sveltekit-app",
version: "0.0.0",
type: "module",
private: true,
main: "index.js",
scripts: {
start: "bun ./index.js",
},
scripts: { start: "bun ./index.js" },
dependencies: { cookie: "latest", devalue: "latest", "set-cookie-parser": "latest" },
};

try {
pkg.name && (package_data.name = pkg.name);
pkg.version && (package_data.version = pkg.version);
pkg.dependencies &&
(package_data.dependencies = {
...pkg.dependencies,
...package_data.dependencies,
});
(package_data.dependencies = { ...pkg.dependencies, ...package_data.dependencies });
} catch (error) {
builder.log.warn(`Parse package.json error: ${error.message}`);
}

writeFileSync(`${out}/package.json`, JSON.stringify(package_data, null, "\t"));

builder.log.success(`Start server with: bun ./${out}/index.js`);
},
};
}

/**
* @param {string} directory
* @param {import('.').CompressOptions} options
*/
async function compress(directory, options) {
/*** @param {string} directory* @param {import('.').CompressOptions} options*/ async function compress(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here

directory,
options,
) {
if (!existsSync(directory)) {
return;
}

let files_ext = options.files ?? ["html", "js", "json", "css", "svg", "xml", "wasm"];
const files = await glob(`**/*.{${files_ext.join()}}`, {
cwd: directory,
dot: true,
absolute: true,
filesOnly: true,
});

let files_ext =
options.files ??
Object.entries(db)
.filter(mime => mime[1].compressible)
.map(mime => mime[1].extensions)
.flat(1)
.filter(Boolean);
const files = [
...new Bun.Glob(`**/*.{${files_ext.join()}}`).scanSync({
cwd: directory,
dot: true,
absolute: true,
onlyFiles: true,
}),
];
let doBr = false,
doGz = false;

if (options === true) {
doBr = doGz = true;
} else if (typeof options == "object") {
doBr = options.brotli ?? false;
doGz = options.gzip ?? false;
}

await Promise.all(
files.map(file =>
Promise.all([doGz && compress_file(file, "gz"), doBr && compress_file(file, "br")]),
),
);
}

/**
* @param {string} file
* @param {'gz' | 'br'} format
*/
async function compress_file(file, format = "gz") {
/*** @param {string} file* @param {'gz' | 'br'} format*/ async function compress_file(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good but there are some formatting issues

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good but there are some formatting issues

i ran bun format before every commit

file,
format = "gz",
) {
const compress =
format == "br"
? zlib.createBrotliCompress({
Expand All @@ -149,25 +131,17 @@ async function compress_file(file, format = "gz") {
},
})
: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

const source = createReadStream(file);
const destination = createWriteStream(`${file}.${format}`);

await pipe(source, compress, destination);
}

/**
* @param {string} out
*/
function patchServerWebsocketHandler(out) {
/*** @param {string} out*/ function patchServerWebsocketHandler(out) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here

let src = readFileSync(`${out}/index.js`, "utf8");
const regex_gethook = /(this\.#options\.hooks\s+=\s+{)\s+(handle:)/gm;
const substr_gethook = `$1 \nhandleWebsocket: module.handleWebsocket || null,\n$2`;
const result1 = src.replace(regex_gethook, substr_gethook);

const regex_sethook = /(this\.#options\s+=\s+options;)/gm;
const substr_sethook = `$1\nthis.websocket = ()=>this.#options.hooks.handleWebsocket;`;
const result = result1.replace(regex_sethook, substr_sethook);

writeFileSync(`${out}/index.js`, result, "utf8");
}
53 changes: 26 additions & 27 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,51 +1,50 @@
{
"name": "svelte-adapter-bun",
"version": "0.5.2",
"description": "Adapter for SvelteKit apps that generates a standalone Bun.js server.",
"author": "Volodymyr Palamar <@gornostay25>",
"repository": {
"type": "git",
"url": "git+https://github.com/gornostay25/svelte-adapter-bun.git"
},
"main": "index.js",
"types": "index.d.ts",
"type": "module",
"devDependencies": {
"@sveltejs/kit": "^1.30.4",
"@types/mime-db": "^1.43.5",
"bun-types": "latest",
"mime-db": "^1.53.0",
"mrmime": "^2.0.0",
"prettier": "^3.2.5",
"totalist": "^3.0.1"
},
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.js"
},
"./package.json": "./package.json"
},
"bugs": {
"url": "https://github.com/gornostay25/svelte-adapter-bun/issues"
},
"description": "Adapter for SvelteKit apps that generates a standalone Bun.js server.",
"files": [
"files",
"index.d.ts"
],
"scripts": {
"build": "rm -fr files && bun run build.js",
"prepare": "bun run build",
"lint": "prettier --check .",
"format": "prettier --write ."
},
"repository": {
"type": "git",
"url": "git+https://github.com/gornostay25/svelte-adapter-bun.git"
},
"homepage": "https://github.com/gornostay25/svelte-adapter-bun#readme",
"keywords": [
"svelte",
"sveltekit",
"sveltekit-adapter",
"bun"
],
"author": "Volodymyr Palamar <@gornostay25>",
"license": "MIT",
"bugs": {
"url": "https://github.com/gornostay25/svelte-adapter-bun/issues"
},
"homepage": "https://github.com/gornostay25/svelte-adapter-bun#readme",
"devDependencies": {
"@sveltejs/kit": "^1.30.4",
"bun-types": "latest",
"mrmime": "^2.0.0",
"prettier": "^3.2.5",
"totalist": "^3.0.1"
"scripts": {
"build": "rm -fr files && bun run build.js",
"prepare": "bun run build",
"lint": "prettier --check .",
"format": "prettier --write ."
},
"dependencies": {
"tiny-glob": "^0.2.9"
}
"type": "module",
"types": "index.d.ts"
}
17 changes: 10 additions & 7 deletions src/sirv.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,14 @@ function viaLocal(dir, isEtag, uri, extns) {
}
}

const notFound = {
status: 404,
};

const notModified = { status: 304 };

function is404(req) {
return new Response(null, {
status: 404,
statusText: "404",
});
return new Response(null, notFound);
}
/**
*
Expand Down Expand Up @@ -228,14 +231,14 @@ export default function (dir, opts = {}) {
if (!data) return next ? next() : isNotFound(req);

if (isEtag && req.headers.get("if-none-match") === data.headers.get("ETag")) {
return new Response(null, { status: 304 });
return new Response(null, notModified);
}

data = {
...data,
// clone a new headers to prevent the cached one getting modified
headers: new Headers(data.headers)
}
headers: new Headers(data.headers),
};

if (gzips || brots) {
data.headers.append("Vary", "Accept-Encoding");
Expand Down