@epubook/core 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,461 @@
1
+ import { XMLBuilder } from 'fast-xml-parser';
2
+ import * as path from 'pathe';
3
+ import { promises, existsSync, mkdirSync } from 'node:fs';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { createDefu } from 'defu';
6
+ import { strToU8 } from 'fflate';
7
+
8
+ const MIMETYPE = "application/epub+zip";
9
+ const ImageJpeg = "image/jpeg";
10
+ const ImagePng = "image/png";
11
+ const ImageWebp = "image/webp";
12
+ const TextCSS = "text/css";
13
+ const XHTML = "application/xhtml+xml";
14
+
15
+ const builder = new XMLBuilder({
16
+ format: true,
17
+ ignoreAttributes: false,
18
+ suppressUnpairedNode: false,
19
+ unpairedTags: ["link"]
20
+ });
21
+ class XHTMLBuilder {
22
+ constructor() {
23
+ this.info = {
24
+ language: "en",
25
+ title: ""
26
+ };
27
+ this._head = [];
28
+ this._body = [];
29
+ }
30
+ language(value) {
31
+ this.info.language = value;
32
+ return this;
33
+ }
34
+ title(value) {
35
+ this.info.title = value;
36
+ return this;
37
+ }
38
+ style(href) {
39
+ this._head.push({
40
+ tag: "link",
41
+ attrs: {
42
+ href,
43
+ rel: "stylesheet",
44
+ type: TextCSS
45
+ },
46
+ children: [""]
47
+ });
48
+ return this;
49
+ }
50
+ body(node) {
51
+ this._body.push(node);
52
+ return this;
53
+ }
54
+ build() {
55
+ function build(node) {
56
+ const attrs = Object.fromEntries(
57
+ Object.entries(node.attrs ?? {}).map(([key, value]) => ["@_" + key, value])
58
+ );
59
+ const obj = {
60
+ ...attrs
61
+ };
62
+ if (Array.isArray(node.children)) {
63
+ const text = node.children.filter((c) => typeof c === "string");
64
+ const nodes = node.children.filter((c) => typeof c !== "string");
65
+ if (text.length > 0) {
66
+ obj["#text"] = text[0];
67
+ }
68
+ Object.assign(obj, list(nodes));
69
+ }
70
+ return obj;
71
+ }
72
+ function list(nodes) {
73
+ const obj = {};
74
+ for (const c of nodes) {
75
+ if (c.tag in obj) {
76
+ obj[c.tag].push(build(c));
77
+ } else {
78
+ obj[c.tag] = [build(c)];
79
+ }
80
+ }
81
+ return obj;
82
+ }
83
+ return builder.build({
84
+ html: {
85
+ "@_xmlns": "http://www.w3.org/1999/xhtml",
86
+ "@_xmlns:epub": "http://www.idpf.org/2007/ops",
87
+ "@_lang": this.info.language,
88
+ "@_xml:lang": this.info.language,
89
+ head: {
90
+ title: this.info.title,
91
+ ...list(this._head)
92
+ },
93
+ body: list(this._body)
94
+ }
95
+ });
96
+ }
97
+ }
98
+ const Fragment = "Fragment";
99
+ function h(tag, attrs = {}, ...children) {
100
+ const sub = children.flatMap(
101
+ (c) => typeof c === "object" && !Array.isArray(c) && c.tag === Fragment ? c.children ?? [] : c
102
+ ).filter((c) => c !== void 0 && c !== null && c !== false);
103
+ const o = {
104
+ tag,
105
+ attrs: attrs ?? {},
106
+ children: sub
107
+ };
108
+ return o;
109
+ }
110
+
111
+ function buildTocNav(nav) {
112
+ const builder = new XHTMLBuilder();
113
+ const root = {
114
+ tag: "nav",
115
+ attrs: {
116
+ "epub:type": "toc"
117
+ },
118
+ children: []
119
+ };
120
+ if (nav.title && nav.heading) {
121
+ root.children.push(h("h" + nav.heading, {}, nav.title));
122
+ }
123
+ root.children.push(/* @__PURE__ */ h("ol", null, list(nav.list)));
124
+ return builder.title(nav.title ?? "Toc").body(root);
125
+ function list(items) {
126
+ return items.map((i) => /* @__PURE__ */ h("li", null, i.href ? /* @__PURE__ */ h("a", { href: i.href }, i.text) : /* @__PURE__ */ h("span", null, i.text), "list" in i && i.list && /* @__PURE__ */ h("ol", null, list(i.list))));
127
+ }
128
+ }
129
+
130
+ class ManifestItem {
131
+ constructor(href, id) {
132
+ this.optional = {};
133
+ this._href = href;
134
+ this._id = id;
135
+ }
136
+ update(info) {
137
+ for (const [key, value] of Object.entries(info)) {
138
+ if (!!value) {
139
+ this.optional[key] = value;
140
+ }
141
+ }
142
+ return this;
143
+ }
144
+ href() {
145
+ return this._href;
146
+ }
147
+ id() {
148
+ return this._id;
149
+ }
150
+ fallback() {
151
+ return this.optional.fallback;
152
+ }
153
+ mediaOverlay() {
154
+ return this.optional.mediaOverlay;
155
+ }
156
+ mediaType() {
157
+ return this.optional.mediaType;
158
+ }
159
+ properties() {
160
+ return this.optional.properties;
161
+ }
162
+ ref() {
163
+ return new ManifestItemRef(this._id);
164
+ }
165
+ }
166
+ class ManifestItemRef {
167
+ constructor(idref) {
168
+ this.optional = {};
169
+ this._idref = idref;
170
+ }
171
+ update(info) {
172
+ for (const [key, value] of Object.entries(info)) {
173
+ if (!!value) {
174
+ this.optional[key] = value;
175
+ }
176
+ }
177
+ return this;
178
+ }
179
+ idref() {
180
+ return this._idref;
181
+ }
182
+ id() {
183
+ return this.optional.id;
184
+ }
185
+ linear() {
186
+ return this.optional.linear;
187
+ }
188
+ properties() {
189
+ return this.optional.properties;
190
+ }
191
+ }
192
+ class Item {
193
+ constructor(file, mediaType) {
194
+ this.file = file;
195
+ this.mediaType = mediaType;
196
+ }
197
+ filename() {
198
+ return this.file;
199
+ }
200
+ update(info) {
201
+ if (info.properties) {
202
+ this._properties = info.properties;
203
+ }
204
+ return this;
205
+ }
206
+ id() {
207
+ return this.file.replace(/\/|\\/g, "_").replace(/\.[\w]+$/, "");
208
+ }
209
+ manifest() {
210
+ return new ManifestItem(this.file, this.id()).update({
211
+ mediaType: this.mediaType,
212
+ properties: this._properties
213
+ });
214
+ }
215
+ itemref() {
216
+ return this.manifest().ref();
217
+ }
218
+ }
219
+ class Html extends Item {
220
+ constructor(file, content) {
221
+ super(file, XHTML);
222
+ this.content = content;
223
+ }
224
+ static async read(src, dst) {
225
+ if (!src.endsWith(".xhtml")) {
226
+ return void 0;
227
+ }
228
+ const content = await promises.readFile(src, "utf-8");
229
+ return new Html(dst, content);
230
+ }
231
+ async bundle() {
232
+ return strToU8(this.content);
233
+ }
234
+ }
235
+ class Style extends Item {
236
+ constructor(file, content) {
237
+ super(file, TextCSS);
238
+ this.content = content;
239
+ }
240
+ static async read(src, dst) {
241
+ if (!src.endsWith(".css")) {
242
+ return void 0;
243
+ }
244
+ const content = await promises.readFile(src, "utf-8");
245
+ return new Style(dst, content);
246
+ }
247
+ async bundle() {
248
+ return strToU8(this.content);
249
+ }
250
+ }
251
+ class Image extends Item {
252
+ constructor(file, type, data) {
253
+ super(file, type);
254
+ this.data = data;
255
+ }
256
+ static async read(src, dst) {
257
+ const content = await promises.readFile(src);
258
+ const media = this.getExtMediaType(src);
259
+ if (media) {
260
+ return new Image(dst, media, content);
261
+ } else {
262
+ return void 0;
263
+ }
264
+ }
265
+ async bundle() {
266
+ return this.data;
267
+ }
268
+ static getExtMediaType(file) {
269
+ const ext = path.extname(file);
270
+ if (ext === "jpg" || ext === "jpeg") {
271
+ return ImageJpeg;
272
+ } else if (ext === "png") {
273
+ return ImagePng;
274
+ } else if (ext === "webp") {
275
+ return ImageWebp;
276
+ } else {
277
+ return void 0;
278
+ }
279
+ }
280
+ }
281
+
282
+ const defu = createDefu((obj, key, value) => {
283
+ if (obj[key] instanceof Date && value instanceof Date) {
284
+ obj[key] = value;
285
+ return true;
286
+ }
287
+ });
288
+ class PackageDocument {
289
+ constructor(file) {
290
+ this.SpecVersion = "3.0";
291
+ this._uniqueIdentifier = "uuid";
292
+ this._identifier = randomUUID();
293
+ this._metadata = {
294
+ title: "",
295
+ language: "zh-CN",
296
+ contributor: [],
297
+ coverage: "",
298
+ creator: {
299
+ name: "unknown",
300
+ uid: "creator"
301
+ },
302
+ date: /* @__PURE__ */ new Date(),
303
+ description: "",
304
+ format: "",
305
+ publisher: "",
306
+ relation: "",
307
+ rights: "",
308
+ source: "",
309
+ subject: "",
310
+ type: "",
311
+ lastModified: /* @__PURE__ */ new Date()
312
+ };
313
+ this._items = [];
314
+ this._spine = [];
315
+ this.file = file;
316
+ }
317
+ filename() {
318
+ return this.file;
319
+ }
320
+ version() {
321
+ return this.SpecVersion;
322
+ }
323
+ // --- metadata ---
324
+ update(info) {
325
+ this._metadata = defu(info, this._metadata);
326
+ return this;
327
+ }
328
+ title() {
329
+ return this._metadata.title;
330
+ }
331
+ language() {
332
+ return this._metadata.language;
333
+ }
334
+ creator() {
335
+ return this._metadata.creator;
336
+ }
337
+ metadata() {
338
+ return this._metadata;
339
+ }
340
+ // --- manifest ---
341
+ addItem(item) {
342
+ this._items.push(item);
343
+ return this;
344
+ }
345
+ items() {
346
+ const l = [...this._items];
347
+ if (this._toc) {
348
+ l.push(this._toc);
349
+ }
350
+ return l;
351
+ }
352
+ manifest() {
353
+ return this.items().map((i) => i.manifest());
354
+ }
355
+ setSpine(items) {
356
+ this._spine.splice(0, this._spine.length, ...items.map((i) => i.itemref()));
357
+ return this;
358
+ }
359
+ spine() {
360
+ return this._spine;
361
+ }
362
+ // --- navigation ---
363
+ toc(nav, title) {
364
+ const content = buildTocNav({
365
+ heading: 2,
366
+ title,
367
+ list: nav.map(
368
+ (i) => Array.isArray(i.item) ? { text: i.text, list: i.item.map((i2) => ({ href: i2.item.filename(), text: i2.text })) } : { href: i.item.filename(), text: i.text }
369
+ )
370
+ }).language(this._metadata.language).build();
371
+ this._toc = new Html("nav.xhtml", content).update({ properties: "nav" });
372
+ return this;
373
+ }
374
+ // --- identifier ---
375
+ uniqueIdentifier() {
376
+ return this._uniqueIdentifier;
377
+ }
378
+ identifier() {
379
+ return this._identifier;
380
+ }
381
+ setIdentifier(identifier, uniqueIdentifier = "uuid") {
382
+ this._identifier = identifier;
383
+ this._uniqueIdentifier = uniqueIdentifier;
384
+ }
385
+ }
386
+
387
+ class Epub {
388
+ constructor(meta = {}) {
389
+ /**
390
+ * See: https://www.w3.org/TR/epub-33/#sec-package-doc
391
+ *
392
+ * Now, it only supports single opf (OEBPS/content.opf)
393
+ *
394
+ * @returns list of package documents
395
+ */
396
+ this.opfs = [new PackageDocument("OEBPS/content.opf")];
397
+ this.opfs[0].update(meta);
398
+ }
399
+ packages() {
400
+ return this.opfs;
401
+ }
402
+ main() {
403
+ return this.opfs[0];
404
+ }
405
+ addItem(...items) {
406
+ for (const item of items) {
407
+ this.opfs[0].addItem(item);
408
+ }
409
+ return this;
410
+ }
411
+ toc(nav, title) {
412
+ this.opfs[0].toc(nav, title);
413
+ return this;
414
+ }
415
+ spine(...items) {
416
+ this.opfs[0].setSpine(items);
417
+ return this;
418
+ }
419
+ async bundle() {
420
+ const { bundle } = await import('../chunks/index.mjs');
421
+ return await bundle(this);
422
+ }
423
+ async writeFile(file) {
424
+ const buffer = await this.bundle();
425
+ const dir = path.dirname(file);
426
+ if (!existsSync(dir)) {
427
+ mkdirSync(dir, { recursive: true });
428
+ }
429
+ await promises.writeFile(file, buffer);
430
+ }
431
+ }
432
+
433
+ class BundleError extends Error {
434
+ constructor(msg) {
435
+ super(msg);
436
+ }
437
+ }
438
+
439
+ const EsbuildOptions = {
440
+ jsxFactory: "h",
441
+ jsxFragment: "fragment",
442
+ loaders: {
443
+ ".js": "js",
444
+ ".ts": "ts",
445
+ ".jsx": "jsx",
446
+ ".tsx": "tsx"
447
+ }
448
+ };
449
+ function Rollup() {
450
+ return {
451
+ name: "epubook:inject-tsx",
452
+ transform(code, id) {
453
+ if (id.endsWith(".tsx")) {
454
+ return `import { h, fragment } from '@epubook/core';
455
+ ` + code;
456
+ }
457
+ }
458
+ };
459
+ }
460
+
461
+ export { BundleError as B, Epub as E, Fragment as F, Html as H, Item as I, MIMETYPE as M, PackageDocument as P, Rollup as R, Style as S, XHTMLBuilder as X, ManifestItem as a, ManifestItemRef as b, Image as c, EsbuildOptions as d, h };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@epubook/core",
3
+ "version": "0.0.2",
4
+ "description": "",
5
+ "keywords": [
6
+ "ebook",
7
+ "epub",
8
+ "epub-generator",
9
+ "epubook"
10
+ ],
11
+ "homepage": "https://github.com/yjl9903/epubook#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/yjl9903/epubook/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/yjl9903/epubook.git"
18
+ },
19
+ "license": "MIT",
20
+ "author": "XLor",
21
+ "sideEffects": false,
22
+ "exports": {
23
+ ".": {
24
+ "require": "./dist/index.cjs",
25
+ "import": "./dist/index.mjs",
26
+ "types": "./dist/index.d.ts"
27
+ }
28
+ },
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.mjs",
31
+ "types": "./dist/index.d.ts",
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "dependencies": {
36
+ "defu": "^6.1.2",
37
+ "fast-xml-parser": "^4.1.3",
38
+ "fflate": "^0.7.4",
39
+ "pathe": "^1.1.0"
40
+ },
41
+ "devDependencies": {
42
+ "rollup": "^3.17.3",
43
+ "vitest": "^0.29.2"
44
+ },
45
+ "engines": {
46
+ "node": ">=v16.19.0"
47
+ },
48
+ "scripts": {
49
+ "build": "unbuild",
50
+ "format": "prettier --write src/**/*.ts test/**/*.ts",
51
+ "test": "vitest",
52
+ "test:ci": "vitest --run",
53
+ "typecheck": "tsc --noEmit"
54
+ }
55
+ }