-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
103 lines (90 loc) · 2.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { fixPages } from "./lib.js";
import { createReadStream, createWriteStream, statSync } from "fs";
import { pipeline } from "stream";
import glob from "tiny-glob";
import { promisify } from "util";
import zlib from "zlib";
const pipe = promisify(pipeline);
/** @type {import('.')} */
export default function ({
pages = "build",
assets = pages,
fallback,
precompress = false,
callbacks = undefined,
copyBeforeSourceMapRemoval = undefined,
removeSourceMap = false,
removeBuiltInServiceWorkerRegistration = false,
injectPagesInServiceWorker = false,
injectDebugConsole = false,
} = {}) {
const adapter = {
name: "sveltejs-adapter-ipfs",
async adapt(builder) {
builder.rimraf(assets);
builder.rimraf(pages);
builder.writeStatic(assets);
builder.writeClient(assets);
builder.writePrerendered(pages, { fallback });
// before compress or after ?
await fixPages({
pages,
assets,
callbacks,
copyBeforeSourceMapRemoval,
removeSourceMap,
removeBuiltInServiceWorkerRegistration,
injectPagesInServiceWorker,
injectDebugConsole,
});
if (precompress) {
if (pages === assets) {
builder.log.minor("Compressing assets and pages");
await compress(assets);
} else {
builder.log.minor("Compressing assets");
await compress(assets);
builder.log.minor("Compressing pages");
await compress(pages);
}
}
},
};
return adapter;
}
/**
* @param {string} directory
*/
async function compress(directory) {
const files = await glob("**/*.{html,js,json,css,svg,xml}", {
cwd: directory,
dot: true,
absolute: true,
filesOnly: true,
});
await Promise.all(
files.map((file) =>
Promise.all([compress_file(file, "gz"), compress_file(file, "br")])
)
);
}
/**
* @param {string} file
* @param {'gz' | 'br'} format
*/
async function compress_file(file, format = "gz") {
const compress =
format == "br"
? zlib.createBrotliCompress({
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]:
zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size,
},
})
: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });
const source = createReadStream(file);
const destination = createWriteStream(`${file}.${format}`);
await pipe(source, compress, destination);
}