@canopycanopycanopy/b-ber-tasks 3.0.8-nav-memo.4 → 3.0.8-next.96

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.
package/dist/index.js CHANGED
@@ -1,182 +1,2115 @@
1
- "use strict";
2
-
3
- var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
- var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
5
- _Object$defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- _Object$defineProperty(exports, "clean", {
9
- enumerable: true,
10
- get: function () {
11
- return _clean.default;
12
- }
13
- });
14
- _Object$defineProperty(exports, "container", {
15
- enumerable: true,
16
- get: function () {
17
- return _container.default;
18
- }
19
- });
20
- _Object$defineProperty(exports, "copy", {
21
- enumerable: true,
22
- get: function () {
23
- return _copy.default;
24
- }
25
- });
26
- _Object$defineProperty(exports, "cover", {
27
- enumerable: true,
28
- get: function () {
29
- return _cover.default;
30
- }
31
- });
32
- _Object$defineProperty(exports, "deploy", {
33
- enumerable: true,
34
- get: function () {
35
- return _deploy.default;
36
- }
37
- });
38
- _Object$defineProperty(exports, "epub", {
39
- enumerable: true,
40
- get: function () {
41
- return _epub.default;
42
- }
43
- });
44
- _Object$defineProperty(exports, "footnotes", {
45
- enumerable: true,
46
- get: function () {
47
- return _footnotes.default;
48
- }
49
- });
50
- _Object$defineProperty(exports, "generate", {
51
- enumerable: true,
52
- get: function () {
53
- return _generate.default;
54
- }
55
- });
56
- _Object$defineProperty(exports, "init", {
57
- enumerable: true,
58
- get: function () {
59
- return _init.default;
60
- }
61
- });
62
- _Object$defineProperty(exports, "inject", {
63
- enumerable: true,
64
- get: function () {
65
- return _inject.default;
66
- }
67
- });
68
- _Object$defineProperty(exports, "loi", {
69
- enumerable: true,
70
- get: function () {
71
- return _loi.default;
72
- }
73
- });
74
- _Object$defineProperty(exports, "mobi", {
75
- enumerable: true,
76
- get: function () {
77
- return _mobi.default;
78
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ let _canopycanopycanopy_b_ber_lib_State = require("@canopycanopycanopy/b-ber-lib/State");
34
+ _canopycanopycanopy_b_ber_lib_State = __toESM(_canopycanopycanopy_b_ber_lib_State);
35
+ let _canopycanopycanopy_b_ber_logger = require("@canopycanopycanopy/b-ber-logger");
36
+ _canopycanopycanopy_b_ber_logger = __toESM(_canopycanopycanopy_b_ber_logger);
37
+ let fs_extra = require("fs-extra");
38
+ fs_extra = __toESM(fs_extra);
39
+ let path = require("path");
40
+ path = __toESM(path);
41
+ let _canopycanopycanopy_b_ber_templates_Xml = require("@canopycanopycanopy/b-ber-templates/Xml");
42
+ _canopycanopycanopy_b_ber_templates_Xml = __toESM(_canopycanopycanopy_b_ber_templates_Xml);
43
+ let lodash_isArray_js = require("lodash/isArray.js");
44
+ lodash_isArray_js = __toESM(lodash_isArray_js);
45
+ let _canopycanopycanopy_b_ber_lib = require("@canopycanopycanopy/b-ber-lib");
46
+ let _canopycanopycanopy_b_ber_lib_utils = require("@canopycanopycanopy/b-ber-lib/utils");
47
+ let _canopycanopycanopy_b_ber_templates_Xhtml = require("@canopycanopycanopy/b-ber-templates/Xhtml");
48
+ _canopycanopycanopy_b_ber_templates_Xhtml = __toESM(_canopycanopycanopy_b_ber_templates_Xhtml);
49
+ let crypto = require("crypto");
50
+ crypto = __toESM(crypto);
51
+ let image_size = require("image-size");
52
+ image_size = __toESM(image_size);
53
+ let pureimage = require("pureimage");
54
+ pureimage = __toESM(pureimage);
55
+ let _canopycanopycanopy_b_ber_lib_YamlAdaptor = require("@canopycanopycanopy/b-ber-lib/YamlAdaptor");
56
+ _canopycanopycanopy_b_ber_lib_YamlAdaptor = __toESM(_canopycanopycanopy_b_ber_lib_YamlAdaptor);
57
+ let child_process = require("child_process");
58
+ let readline = require("readline");
59
+ readline = __toESM(readline);
60
+ let epub_zipper = require("epub-zipper");
61
+ epub_zipper = __toESM(epub_zipper);
62
+ let _canopycanopycanopy_b_ber_shapes_sequences_sequences = require("@canopycanopycanopy/b-ber-shapes-sequences/sequences");
63
+ _canopycanopycanopy_b_ber_shapes_sequences_sequences = __toESM(_canopycanopycanopy_b_ber_shapes_sequences_sequences);
64
+ let _canopycanopycanopy_b_ber_lib_Theme = require("@canopycanopycanopy/b-ber-lib/Theme");
65
+ _canopycanopycanopy_b_ber_lib_Theme = __toESM(_canopycanopycanopy_b_ber_lib_Theme);
66
+ let _canopycanopycanopy_b_ber_resources = require("@canopycanopycanopy/b-ber-resources");
67
+ _canopycanopycanopy_b_ber_resources = __toESM(_canopycanopycanopy_b_ber_resources);
68
+ let _canopycanopycanopy_b_ber_templates_Project = require("@canopycanopycanopy/b-ber-templates/Project");
69
+ _canopycanopycanopy_b_ber_templates_Project = __toESM(_canopycanopycanopy_b_ber_templates_Project);
70
+ let vinyl = require("vinyl");
71
+ vinyl = __toESM(vinyl);
72
+ let _canopycanopycanopy_b_ber_templates_figures = require("@canopycanopycanopy/b-ber-templates/figures");
73
+ _canopycanopycanopy_b_ber_templates_figures = __toESM(_canopycanopycanopy_b_ber_templates_figures);
74
+ let lodash_sortBy_js = require("lodash/sortBy.js");
75
+ lodash_sortBy_js = __toESM(lodash_sortBy_js);
76
+ let _canopycanopycanopy_b_ber_lib_EbookConvert = require("@canopycanopycanopy/b-ber-lib/EbookConvert");
77
+ _canopycanopycanopy_b_ber_lib_EbookConvert = __toESM(_canopycanopycanopy_b_ber_lib_EbookConvert);
78
+ let css = require("css");
79
+ css = __toESM(css);
80
+ let _canopycanopycanopy_b_ber_templates_Opf_Manifest = require("@canopycanopycanopy/b-ber-templates/Opf/Manifest");
81
+ _canopycanopycanopy_b_ber_templates_Opf_Manifest = __toESM(_canopycanopycanopy_b_ber_templates_Opf_Manifest);
82
+ let _canopycanopycanopy_b_ber_templates_Opf_Metadata = require("@canopycanopycanopy/b-ber-templates/Opf/Metadata");
83
+ _canopycanopycanopy_b_ber_templates_Opf_Metadata = __toESM(_canopycanopycanopy_b_ber_templates_Opf_Metadata);
84
+ let layouts = require("layouts");
85
+ layouts = __toESM(layouts);
86
+ let lodash_has_js = require("lodash/has.js");
87
+ lodash_has_js = __toESM(lodash_has_js);
88
+ let recursive_readdir = require("recursive-readdir");
89
+ recursive_readdir = __toESM(recursive_readdir);
90
+ let _canopycanopycanopy_b_ber_templates_Ncx = require("@canopycanopycanopy/b-ber-templates/Ncx");
91
+ _canopycanopycanopy_b_ber_templates_Ncx = __toESM(_canopycanopycanopy_b_ber_templates_Ncx);
92
+ let _canopycanopycanopy_b_ber_templates_Opf_Guide = require("@canopycanopycanopy/b-ber-templates/Opf/Guide");
93
+ _canopycanopycanopy_b_ber_templates_Opf_Guide = __toESM(_canopycanopycanopy_b_ber_templates_Opf_Guide);
94
+ let _canopycanopycanopy_b_ber_templates_Opf_Spine = require("@canopycanopycanopy/b-ber-templates/Opf/Spine");
95
+ _canopycanopycanopy_b_ber_templates_Opf_Spine = __toESM(_canopycanopycanopy_b_ber_templates_Opf_Spine);
96
+ let _canopycanopycanopy_b_ber_templates_Toc = require("@canopycanopycanopy/b-ber-templates/Toc");
97
+ _canopycanopycanopy_b_ber_templates_Toc = __toESM(_canopycanopycanopy_b_ber_templates_Toc);
98
+ let glob = require("glob");
99
+ glob = __toESM(glob);
100
+ let lodash_difference_js = require("lodash/difference.js");
101
+ lodash_difference_js = __toESM(lodash_difference_js);
102
+ let lodash_find_js = require("lodash/find.js");
103
+ lodash_find_js = __toESM(lodash_find_js);
104
+ let lodash_remove_js = require("lodash/remove.js");
105
+ lodash_remove_js = __toESM(lodash_remove_js);
106
+ let _canopycanopycanopy_b_ber_templates_Opf_Pkg = require("@canopycanopycanopy/b-ber-templates/Opf/Pkg");
107
+ _canopycanopycanopy_b_ber_templates_Opf_Pkg = __toESM(_canopycanopycanopy_b_ber_templates_Opf_Pkg);
108
+ let lodash_kebabCase_js = require("lodash/kebabCase.js");
109
+ lodash_kebabCase_js = __toESM(lodash_kebabCase_js);
110
+ let _canopycanopycanopy_b_ber_markdown_renderer = require("@canopycanopycanopy/b-ber-markdown-renderer");
111
+ _canopycanopycanopy_b_ber_markdown_renderer = __toESM(_canopycanopycanopy_b_ber_markdown_renderer);
112
+ let autoprefixer = require("autoprefixer");
113
+ autoprefixer = __toESM(autoprefixer);
114
+ let postcss = require("postcss");
115
+ postcss = __toESM(postcss);
116
+ let sass = require("sass");
117
+ sass = __toESM(sass);
118
+ let uglify_js = require("uglify-js");
119
+ uglify_js = __toESM(uglify_js);
120
+ let _canopycanopycanopy_b_ber_validator = require("@canopycanopycanopy/b-ber-validator");
121
+ _canopycanopycanopy_b_ber_validator = __toESM(_canopycanopycanopy_b_ber_validator);
122
+ let cheerio = require("cheerio");
123
+ cheerio = __toESM(cheerio);
124
+ let lodash_findIndex_js = require("lodash/findIndex.js");
125
+ lodash_findIndex_js = __toESM(lodash_findIndex_js);
126
+ let _canopycanopycanopy_b_ber_lib_HtmlToXml = require("@canopycanopycanopy/b-ber-lib/HtmlToXml");
127
+ _canopycanopycanopy_b_ber_lib_HtmlToXml = __toESM(_canopycanopycanopy_b_ber_lib_HtmlToXml);
128
+ let lodash_isPlainObject_js = require("lodash/isPlainObject.js");
129
+ lodash_isPlainObject_js = __toESM(lodash_isPlainObject_js);
130
+ let lodash_isString_js = require("lodash/isString.js");
131
+ lodash_isString_js = __toESM(lodash_isString_js);
132
+ let browser_sync = require("browser-sync");
133
+ let lodash_debounce_js = require("lodash/debounce.js");
134
+ lodash_debounce_js = __toESM(lodash_debounce_js);
135
+ //#region src/clean/index.ts
136
+ const clean = () => {
137
+ const projectRoot = path.default.dirname(_canopycanopycanopy_b_ber_lib_State.default.distDir);
138
+ const fileType = `.${_canopycanopycanopy_b_ber_lib_State.default.build}`;
139
+ const promises = fs_extra.default.readdirSync(projectRoot).filter((a) => path.default.extname(a) === fileType).map((b) => fs_extra.default.remove(path.default.join(projectRoot, b)).then(() => _canopycanopycanopy_b_ber_logger.default.info("clean remove [%s]", b)));
140
+ return Promise.all(promises).then(() => fs_extra.default.remove(_canopycanopycanopy_b_ber_lib_State.default.distDir).then(() => _canopycanopycanopy_b_ber_logger.default.info("clean remove [%s]", _canopycanopycanopy_b_ber_lib_State.default.distDir)));
141
+ };
142
+ var clean_default = () => clean().catch(_canopycanopycanopy_b_ber_logger.default.error);
143
+ //#endregion
144
+ //#region src/container/index.ts
145
+ var Container = class {
146
+ get dirs() {
147
+ return [_canopycanopycanopy_b_ber_lib_State.default.dist.ops(), _canopycanopycanopy_b_ber_lib_State.default.dist.root("META-INF")];
148
+ }
149
+ constructor() {
150
+ this.init = this.init.bind(this);
151
+ }
152
+ write() {
153
+ const promises = [{
154
+ path: path.default.join("META-INF", "container.xml"),
155
+ content: _canopycanopycanopy_b_ber_templates_Xml.default.container()
156
+ }, {
157
+ path: "mimetype",
158
+ content: _canopycanopycanopy_b_ber_templates_Xml.default.mimetype()
159
+ }].map((file) => fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.root(file.path), file.content).then(() => _canopycanopycanopy_b_ber_logger.default.info("container emit [%s]", file.path)));
160
+ return Promise.all(promises);
161
+ }
162
+ makedirs() {
163
+ const promises = this.dirs.map((dir) => fs_extra.default.mkdirs(dir).then(() => _canopycanopycanopy_b_ber_logger.default.info("container emit [%s]", dir)));
164
+ return Promise.all(promises);
165
+ }
166
+ init() {
167
+ return this.makedirs().then(() => this.write()).catch(_canopycanopycanopy_b_ber_logger.default.error);
168
+ }
169
+ };
170
+ var container_default = new Container().init;
171
+ //#endregion
172
+ //#region src/copy/index.ts
173
+ const FILE_SIZE_WARNING_LIMIT = 15e5;
174
+ const cwd$1 = process.cwd();
175
+ const copy = () => {
176
+ const ignoreMap = ((0, lodash_isArray_js.default)(_canopycanopycanopy_b_ber_lib_State.default.config.ignore) ? _canopycanopycanopy_b_ber_lib_State.default.config.ignore : []).reduce((acc, curr) => {
177
+ acc[path.default.resolve(cwd$1, curr)] = true;
178
+ return acc;
179
+ }, {});
180
+ const promises = [
181
+ {
182
+ from: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.src.images()),
183
+ to: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.dist.images())
184
+ },
185
+ {
186
+ from: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.src.fonts()),
187
+ to: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.dist.fonts())
188
+ },
189
+ {
190
+ from: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.src.media()),
191
+ to: path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.dist.media())
192
+ }
193
+ ].filter((dir) => !ignoreMap[dir.from]).map((dir) => fs_extra.default.mkdirp(dir.to).then(() => fs_extra.default.mkdirp(dir.from)).then(() => fs_extra.default.copy(dir.from, dir.to, {
194
+ overwrite: false,
195
+ filter: (file) => path.default.basename(file).charAt(0) !== "." && !ignoreMap[file]
196
+ })).then(() => fs_extra.default.readdir(dir.to)).then((files) => {
197
+ const baseTo = `${path.default.basename(dir.to)}`;
198
+ files.forEach((file) => {
199
+ const { size } = fs_extra.default.statSync(path.default.join(dir.to, file));
200
+ _canopycanopycanopy_b_ber_logger.default.info("copy [%s - {%d}]", `${baseTo}/${file}`, size);
201
+ if (size > FILE_SIZE_WARNING_LIMIT) _canopycanopycanopy_b_ber_logger.default.warn("copy [%s - {%d}] Large file sizes may cause performance issues in some output formats", file, size);
202
+ });
203
+ }));
204
+ return Promise.all(promises).catch(_canopycanopycanopy_b_ber_logger.default.error);
205
+ };
206
+ //#endregion
207
+ //#region src/cover/index.ts
208
+ var Cover = class {
209
+ metadata;
210
+ metadataYAML;
211
+ coverPrefix;
212
+ coverXHTMLContent;
213
+ coverEntry;
214
+ coverImagePath;
215
+ width;
216
+ height;
217
+ fontSize;
218
+ lineHeight;
219
+ marginLeft;
220
+ marginTop;
221
+ colorBackground;
222
+ colorText;
223
+ fontName;
224
+ fontFile;
225
+ posY;
226
+ constructor() {
227
+ const defaultMetadata = {
228
+ title: "",
229
+ creator: "",
230
+ "date-modified": String(/* @__PURE__ */ new Date()),
231
+ identifier: ""
232
+ };
233
+ const fileMetadata = this.YAMLToObject();
234
+ this.metadata = {
235
+ ...defaultMetadata,
236
+ ...fileMetadata
237
+ };
238
+ this.metadataYAML = _canopycanopycanopy_b_ber_lib_State.default.src.root("metadata.yml");
239
+ this.coverPrefix = "__bber_cover__";
240
+ this.coverXHTMLContent = "";
241
+ this.coverEntry = "";
242
+ this.coverImagePath = "";
243
+ this.width = 1600;
244
+ this.height = 2400;
245
+ this.fontSize = 45;
246
+ this.lineHeight = this.fontSize * 1.35;
247
+ this.marginLeft = this.fontSize * 2;
248
+ this.marginTop = this.fontSize * 2;
249
+ this.colorBackground = "#5050c5";
250
+ this.colorText = "#ffffff";
251
+ this.fontName = "Free Universal";
252
+ this.fontFile = "freeuniversal-bold-webfont.ttf";
253
+ this.posY = 0;
254
+ }
255
+ getPosY = () => {
256
+ this.posY = this.posY ? this.posY + this.lineHeight : this.marginTop + this.fontSize;
257
+ return this.posY;
258
+ };
259
+ loadInitialState = async () => {
260
+ this.posY = 0;
261
+ this.coverXHTMLContent = "";
262
+ this.coverEntry = "";
263
+ this.coverImagePath = "";
264
+ };
265
+ YAMLToObject() {
266
+ return _canopycanopycanopy_b_ber_lib_State.default.metadata.json().reduce((acc, curr) => {
267
+ if (curr.term && curr.value) acc[curr.term] = curr.value;
268
+ return acc;
269
+ }, {});
270
+ }
271
+ removeDefaultCovers() {
272
+ const imageDir = _canopycanopycanopy_b_ber_lib_State.default.src.images();
273
+ const covers = fs_extra.default.readdirSync(imageDir).filter((file) => path.default.basename(file).match(new RegExp(this.coverPrefix)));
274
+ if (!covers.length) return Promise.resolve();
275
+ const promises = covers.map((file) => fs_extra.default.remove(path.default.join(imageDir, file)).then(() => _canopycanopycanopy_b_ber_logger.default.info("cover remove outdated cover image [%s]", file)));
276
+ return Promise.all(promises);
277
+ }
278
+ wrapText(ctx, text) {
279
+ const maxWidth = this.width - this.marginLeft * 2;
280
+ const words = text.split(" ");
281
+ let line = "";
282
+ for (let n = 0; n < words.length; n++) {
283
+ const testLine = `${line}${words[n]} `;
284
+ if (ctx.measureText(testLine).width > maxWidth && n > 0) {
285
+ ctx.fillText(line, this.marginLeft, this.getPosY());
286
+ line = `${words[n]} `;
287
+ } else line = testLine;
288
+ }
289
+ ctx.fillText(line, this.marginLeft, this.getPosY());
290
+ }
291
+ generateDefaultCoverImage() {
292
+ return new Promise((resolve) => {
293
+ const img = pureimage.default.make(this.width, this.height);
294
+ const ctx = img.getContext("2d");
295
+ return pureimage.default.registerFont(path.default.join(__dirname, this.fontFile), this.fontName).load(() => {
296
+ ctx.fillStyle = this.colorBackground;
297
+ ctx.fillRect(0, 0, this.width, this.height);
298
+ ctx.font = `${this.fontSize}px '${this.fontName}'`;
299
+ ctx.fillStyle = this.colorText;
300
+ ctx.fillText("Title", this.marginLeft, this.getPosY());
301
+ ctx.fillText(this.metadata.title, this.marginLeft, this.getPosY());
302
+ ctx.fillText("", this.marginLeft, this.getPosY());
303
+ ctx.fillText("Creator", this.marginLeft, this.getPosY());
304
+ ctx.fillText(this.metadata.creator, this.marginLeft, this.getPosY());
305
+ ctx.fillText("", this.marginLeft, this.getPosY());
306
+ ctx.fillText("Publisher", this.marginLeft, this.getPosY());
307
+ ctx.fillText(this.metadata.publisher, this.marginLeft, this.getPosY());
308
+ ctx.fillText("", this.marginLeft, this.getPosY());
309
+ ctx.fillText("Description", this.marginLeft, this.getPosY());
310
+ this.wrapText(ctx, this.metadata.description);
311
+ ctx.fillText("", this.marginLeft, this.getPosY());
312
+ ctx.fillText("b-ber version", this.marginLeft, this.getPosY());
313
+ ctx.fillText(_canopycanopycanopy_b_ber_lib_State.default.version, this.marginLeft, this.getPosY());
314
+ return pureimage.default.encodeJPEGToStream(img, fs_extra.default.createWriteStream(this.coverImagePath)).then(() => {
315
+ _canopycanopycanopy_b_ber_logger.default.info("cover generated image [%s]", this.coverImagePath);
316
+ resolve();
317
+ }).catch(_canopycanopycanopy_b_ber_logger.default.error);
318
+ });
319
+ });
320
+ }
321
+ writeCoverXHTML = async () => {
322
+ if (_canopycanopycanopy_b_ber_lib_State.default.build === "pdf") return;
323
+ const textDir = _canopycanopycanopy_b_ber_lib_State.default.dist.text();
324
+ const coverFilePath = _canopycanopycanopy_b_ber_lib_State.default.dist.text("cover.xhtml");
325
+ await fs_extra.default.mkdirp(textDir);
326
+ await fs_extra.default.writeFile(coverFilePath, this.coverXHTMLContent);
327
+ _canopycanopycanopy_b_ber_logger.default.info("cover wrote XML [cover.xhtml]");
328
+ };
329
+ generateCoverXHTML() {
330
+ const { width, height } = (0, image_size.default)(this.coverImagePath);
331
+ const href = `images/${encodeURIComponent(this.coverEntry)}`;
332
+ const svg = _canopycanopycanopy_b_ber_templates_Xhtml.default.cover({
333
+ width,
334
+ height,
335
+ href
336
+ });
337
+ this.coverXHTMLContent = _canopycanopycanopy_b_ber_lib.Template.render(svg, _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
338
+ _canopycanopycanopy_b_ber_logger.default.info("cover build [cover.xhtml]");
339
+ }
340
+ addCoverToMetadata() {
341
+ return fs_extra.default.writeFile(this.metadataYAML, _canopycanopycanopy_b_ber_lib_State.default.metadata.yaml());
342
+ }
343
+ createCoverImage() {
344
+ this.coverEntry = `${this.coverPrefix}${crypto.default.randomBytes(20).toString("hex")}.jpg`;
345
+ this.coverImagePath = _canopycanopycanopy_b_ber_lib_State.default.src.images(this.coverEntry);
346
+ const metadata = _canopycanopycanopy_b_ber_lib.YamlAdaptor.load(this.metadataYAML);
347
+ const coverListedInMetadata = (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("cover");
348
+ if (coverListedInMetadata) {
349
+ this.coverEntry = coverListedInMetadata.replace(/_jpg$/, ".jpg");
350
+ _canopycanopycanopy_b_ber_logger.default.info("cover verify image [%s]", this.coverEntry);
351
+ this.coverImagePath = _canopycanopycanopy_b_ber_lib_State.default.src.images(this.coverEntry);
352
+ if (!fs_extra.default.existsSync(this.coverImagePath)) _canopycanopycanopy_b_ber_logger.default.error("Cover image listed in metadata.yml cannot be found");
353
+ return this.generateCoverXHTML();
354
+ }
355
+ _canopycanopycanopy_b_ber_logger.default.info("cover generated image [%s]", this.coverEntry);
356
+ const coverMetadata = {
357
+ term: "cover",
358
+ value: this.coverEntry
359
+ };
360
+ _canopycanopycanopy_b_ber_lib_State.default.metadata.add(coverMetadata);
361
+ this.metadata = {
362
+ ...coverMetadata,
363
+ ...this.metadata,
364
+ ...metadata
365
+ };
366
+ return this.removeDefaultCovers().then(() => this.generateDefaultCoverImage()).then(() => this.generateCoverXHTML()).then(() => this.addCoverToMetadata()).catch(_canopycanopycanopy_b_ber_logger.default.error);
367
+ }
368
+ init = () => this.loadInitialState().then(() => this.createCoverImage()).then(() => this.writeCoverXHTML()).catch(_canopycanopycanopy_b_ber_logger.default.error);
369
+ };
370
+ var cover_default = new Cover().init;
371
+ //#endregion
372
+ //#region src/deploy/index.ts
373
+ const cwd = process.cwd();
374
+ const defaultBuilds = [
375
+ "epub",
376
+ "mobi",
377
+ "reader"
378
+ ];
379
+ const args = new Map([
380
+ ["epub", "--include \"*.epub\""],
381
+ ["mobi", "--include \"*.mobi\""],
382
+ ["pdf", "--include \"*.pdf\""],
383
+ ["xml", "--include \"*.xml\""],
384
+ ["reader", "--include \"project-reader/*\""],
385
+ ["web", "--include \"project-web/*\""]
386
+ ]);
387
+ const cacheArgsBucket = [
388
+ "--recursive",
389
+ "--acl public-read",
390
+ "--expires 2034-01-01T00:00:00Z",
391
+ "--cache-control max-age=31536000,public"
392
+ ];
393
+ const cacheArgsFiles = [
394
+ "--recursive",
395
+ "--exclude \"*\"",
396
+ "--include \"*.ncx\"",
397
+ "--include \"*.opf\"",
398
+ "--include \"*.json\"",
399
+ "--include \"*.epub\"",
400
+ "--include \"*.mobi\"",
401
+ "--include \"*.pdf\"",
402
+ "--include \"*.xml\"",
403
+ "--metadata-directive REPLACE",
404
+ "--acl public-read",
405
+ "--expires 1970-01-01T00:00:00Z",
406
+ "--cache-control max-age=0,public"
407
+ ];
408
+ const cacheArgsHTML = [
409
+ "--recursive",
410
+ "--exclude \"*\"",
411
+ "--include \"*.html\"",
412
+ "--include \"*.xhtml\"",
413
+ "--acl public-read",
414
+ "--metadata-directive REPLACE",
415
+ "--content-type text/html",
416
+ "--expires 1970-01-01T00:00:00Z",
417
+ "--cache-control max-age=0,public"
418
+ ];
419
+ async function ensureAwsCli() {
420
+ try {
421
+ (0, child_process.execSync)("aws --version > /dev/null 2>&1", { cwd });
422
+ } catch (err) {
423
+ console.log("AWS CLI must be installed to run deploy");
424
+ console.log("See installation instructions here: https://docs.aws.amazon.com/cli/latest/userguide/installing.html");
425
+ process.exit(0);
426
+ }
427
+ }
428
+ function run(command, callback) {
429
+ const proc = (0, child_process.exec)(command, { cwd });
430
+ proc.stdout?.on("data", (data) => console.log(String(data)));
431
+ proc.stderr?.on("data", (data) => console.log(String(data)));
432
+ proc.on("error", (err) => {
433
+ console.log("");
434
+ console.log("ERROR: aws encountered an error");
435
+ console.log(err.message);
436
+ console.log(err.stack);
437
+ });
438
+ proc.on("close", (code) => {
439
+ if (code !== 0) {
440
+ console.log("");
441
+ console.log(`ERROR: aws exited with code ${code}`);
442
+ }
443
+ if (callback) callback();
444
+ });
445
+ }
446
+ function deploy({ bucketURL, awsRegion, builds }) {
447
+ console.log("");
448
+ console.log("Uploading project files...");
449
+ return new Promise((resolve) => {
450
+ const commandParts = [
451
+ `aws s3 cp ${path.default.resolve(cwd, "./")} ${bucketURL}`,
452
+ "--recursive",
453
+ "--exclude \"*\"",
454
+ `--region ${awsRegion}`
455
+ ];
456
+ builds.forEach((arg) => {
457
+ const val = args.get(arg);
458
+ if (val) commandParts.push(val);
459
+ });
460
+ return run(commandParts.join(" "), () => resolve());
461
+ });
462
+ }
463
+ function ensureEnvVars() {
464
+ const { AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, BBER_BUCKET_REGION } = process.env;
465
+ if (!AWS_ACCESS_KEY_ID || !AWS_SECRET_ACCESS_KEY || !BBER_BUCKET_REGION) _canopycanopycanopy_b_ber_logger.default.error("[AWS_ACCESS_KEY_ID], [AWS_SECRET_ACCESS_KEY] and [BBER_BUCKET_REGION] must be set to deploy the project");
466
+ const configFile = path.default.resolve(cwd, "config.yml");
467
+ const { bucket_url: bucketURL } = _canopycanopycanopy_b_ber_lib_YamlAdaptor.default.load(configFile);
468
+ if (!bucketURL) _canopycanopycanopy_b_ber_logger.default.error("[bucketURL] must be set in config.yml to deploy the project");
469
+ return {
470
+ bucketURL,
471
+ awsRegion: BBER_BUCKET_REGION
472
+ };
473
+ }
474
+ function extractVars(config) {
475
+ const { bucketURL, awsRegion } = config;
476
+ let builds = config.builds && config.builds.length ? config.builds : defaultBuilds;
477
+ builds = builds.map((str) => str.toLowerCase()).filter((arg) => args.has(arg));
478
+ return {
479
+ bucketURL,
480
+ awsRegion,
481
+ builds
482
+ };
483
+ }
484
+ function deployWithPrompt(config) {
485
+ return new Promise((resolve) => {
486
+ const rl = readline.default.createInterface(process.stdin, process.stdout);
487
+ const { bucketURL, awsRegion, builds } = config;
488
+ console.log("");
489
+ console.log("Does the following look OK?");
490
+ console.log("");
491
+ console.log(` Bucket URL: ${bucketURL}`);
492
+ console.log(` AWS Region: ${awsRegion}`);
493
+ console.log(` Builds: ${builds.join(", ")}`);
494
+ console.log("");
495
+ rl.setPrompt(" [yN] ");
496
+ rl.prompt();
497
+ rl.on("line", (data) => {
498
+ if (data === "y" || data === "yes") return deploy({
499
+ bucketURL,
500
+ awsRegion,
501
+ builds
502
+ }).then(() => rl.close());
503
+ process.exit(0);
504
+ }).on("close", resolve);
505
+ });
506
+ }
507
+ function deployWithoutPrompt(config) {
508
+ _canopycanopycanopy_b_ber_logger.default.notice("Deploy command run with \"--yes\", skipping confirmation");
509
+ return deploy(config);
510
+ }
511
+ function setCachePolicy({ bucketURL, awsRegion }, cacheArgs) {
512
+ console.log("Setting cache policy...");
513
+ const command = [`aws s3 cp ${bucketURL} ${bucketURL}`, `--region ${awsRegion}`].concat(cacheArgs).join(" ");
514
+ return new Promise((resolve) => run(command, () => resolve()));
515
+ }
516
+ function main({ builds, yes }) {
517
+ let config = {};
518
+ return ensureAwsCli().then(ensureEnvVars).then((response) => {
519
+ config = extractVars({
520
+ ...response,
521
+ builds
522
+ });
523
+ if (yes) return deployWithoutPrompt(config);
524
+ return deployWithPrompt(config);
525
+ }).then(() => setCachePolicy(config, cacheArgsBucket)).then(() => setCachePolicy(config, cacheArgsFiles)).then(() => setCachePolicy(config, cacheArgsHTML)).catch(_canopycanopycanopy_b_ber_logger.default.error);
526
+ }
527
+ //#endregion
528
+ //#region src/epub/index.ts
529
+ const epub = () => process.argv.includes("--no-compile") ? Promise.resolve() : epub_zipper.default.create({
530
+ input: _canopycanopycanopy_b_ber_lib_State.default.distDir,
531
+ output: process.cwd(),
532
+ clean: true,
533
+ fileName: (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("identifier")
534
+ }).catch(_canopycanopycanopy_b_ber_logger.default.error);
535
+ //#endregion
536
+ //#region src/footnotes/index.ts
537
+ var Footnotes = class {
538
+ baseName;
539
+ get file() {
540
+ return {
541
+ name: this.baseName,
542
+ path: _canopycanopycanopy_b_ber_lib_State.default.dist.text(`${this.baseName}.xhtml`)
543
+ };
544
+ }
545
+ constructor() {
546
+ this.baseName = "notes";
547
+ this.init = this.init.bind(this);
548
+ }
549
+ async writeFootnotes() {
550
+ const notes = _canopycanopycanopy_b_ber_lib_State.default.footnotes.reduce((acc, cur) => acc.concat(cur.notes), "");
551
+ const markup = _canopycanopycanopy_b_ber_lib.Template.render(notes, _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
552
+ await fs_extra.default.writeFile(this.file.path, markup, "utf8");
553
+ const fileData = new _canopycanopycanopy_b_ber_lib.SpineItem({
554
+ fileName: this.file.name,
555
+ in_toc: false,
556
+ linear: false,
557
+ generated: true,
558
+ buildType: _canopycanopycanopy_b_ber_lib_State.default.build
559
+ });
560
+ _canopycanopycanopy_b_ber_lib_State.default.add("spine.flattened", fileData);
561
+ _canopycanopycanopy_b_ber_logger.default.info(`create default footnotes page [${this.file.name}.xhtml]`);
562
+ }
563
+ init() {
564
+ if (!_canopycanopycanopy_b_ber_lib_State.default.footnotes.length) {
565
+ _canopycanopycanopy_b_ber_logger.default.info("footnotes no footnotes found in source");
566
+ return Promise.resolve(_canopycanopycanopy_b_ber_lib_State.default.footnotes);
567
+ }
568
+ _canopycanopycanopy_b_ber_logger.default.info("footnotes generating links");
569
+ return this.writeFootnotes().catch(_canopycanopycanopy_b_ber_logger.default.error);
570
+ }
571
+ };
572
+ var footnotes_default = new Footnotes().init;
573
+ //#endregion
574
+ //#region src/generate/index.ts
575
+ var Generate = class {
576
+ constructor() {
577
+ this.init = this.init.bind(this);
578
+ }
579
+ createFile({ markdownDir, metadata }) {
580
+ const frontmatter = `---\n${Object.entries(metadata).reduce((acc, [k, v]) => v ? acc.concat(`${k}: ${v}\n`) : acc, "")}---\n`;
581
+ const { title } = metadata;
582
+ const fileName = `${title.replace(/[^a-z0-9_-]/gi, "-")}.md`;
583
+ const filePath = path.default.join(markdownDir, fileName);
584
+ if (fs_extra.default.existsSync(filePath)) _canopycanopycanopy_b_ber_logger.default.error(`_markdown${path.default.sep}${fileName} already exists, aborting`);
585
+ return fs_extra.default.writeFile(filePath, frontmatter).then(() => ({ fileName }));
586
+ }
587
+ writePageMeta({ fileName }) {
588
+ const tocFile = _canopycanopycanopy_b_ber_lib_State.default.src.root("toc.yml");
589
+ const index = (_canopycanopycanopy_b_ber_lib_YamlAdaptor.default.load(tocFile) || []).indexOf(fileName);
590
+ const content = `\n- ${path.default.basename(fileName, ".md")}`;
591
+ if (index > -1) throw new Error(`${fileName} already exists in [${path.default.basename(tocFile)}]. Aborting`);
592
+ const promises = [fs_extra.default.appendFile(tocFile, content)];
593
+ Object.keys(_canopycanopycanopy_b_ber_shapes_sequences_sequences.default).reduce((acc, curr) => fs_extra.default.existsSync(_canopycanopycanopy_b_ber_lib_State.default.src.root(`${curr}.yml`)) ? acc.concat(fs_extra.default.appendFile(_canopycanopycanopy_b_ber_lib_State.default.src.root(`${curr}.yml`), content)) : acc, promises);
594
+ return Promise.all(promises).then(() => ({ fileName }));
595
+ }
596
+ init(metadata) {
597
+ const markdownDir = _canopycanopycanopy_b_ber_lib_State.default.src.markdown();
598
+ return fs_extra.default.mkdirp(markdownDir).then(() => this.createFile({
599
+ markdownDir,
600
+ metadata
601
+ })).then((resp) => this.writePageMeta(resp)).then(({ fileName }) => _canopycanopycanopy_b_ber_logger.default.notice(`Generated new page [${fileName}]`)).catch(_canopycanopycanopy_b_ber_logger.default.error);
602
+ }
603
+ };
604
+ const generate = new Generate().init;
605
+ //#endregion
606
+ //#region src/init/index.ts
607
+ var Initializer = class {
608
+ src;
609
+ dist;
610
+ name;
611
+ config;
612
+ path;
613
+ builds;
614
+ constructor({ name = "", config } = {}) {
615
+ this.src = "_project";
616
+ this.dist = "project";
617
+ this.name = name;
618
+ this.config = config || {};
619
+ this.path = path.default.join(name, this.src);
620
+ this.builds = Object.keys(_canopycanopycanopy_b_ber_shapes_sequences_sequences.default);
621
+ if (fs_extra.default.existsSync(this.path)) _canopycanopycanopy_b_ber_logger.default.error(`Project [${name}] already exits, aborting`);
622
+ }
623
+ createAssets = () => {
624
+ return (0, _canopycanopycanopy_b_ber_lib_utils.ensure)({
625
+ files: [
626
+ _canopycanopycanopy_b_ber_templates_Project.default.tocYAML(this.path),
627
+ _canopycanopycanopy_b_ber_templates_Project.default.configYAML(this.path, this.config),
628
+ _canopycanopycanopy_b_ber_templates_Project.default.metadataYAML(this.path),
629
+ ..._canopycanopycanopy_b_ber_templates_Project.default.javascripts(this.path),
630
+ ..._canopycanopycanopy_b_ber_templates_Project.default.stylesheets(),
631
+ ..._canopycanopycanopy_b_ber_templates_Project.default.markdown(this.path),
632
+ _canopycanopycanopy_b_ber_templates_Project.default.readme(this.path),
633
+ _canopycanopycanopy_b_ber_templates_Project.default.gitignore(this.path)
634
+ ],
635
+ dirs: _canopycanopycanopy_b_ber_templates_Project.default.directories(this.path),
636
+ prefix: this.name
637
+ });
638
+ };
639
+ copyImages() {
640
+ return (0, _canopycanopycanopy_b_ber_resources.default)().then((assets) => {
641
+ const { "b-ber-logo": bberLogo, "default-publishers-logo": publishersLogo } = assets;
642
+ const images = [bberLogo, publishersLogo];
643
+ _canopycanopycanopy_b_ber_logger.default.info("Copying development assets");
644
+ const promises = images.map((a) => fs_extra.default.copy(a, path.default.join(this.path, "_images", path.default.basename(a))));
645
+ return Promise.all(promises);
646
+ });
647
+ }
648
+ setTheme() {
649
+ const { theme } = _canopycanopycanopy_b_ber_lib_State.default.config;
650
+ process.chdir(this.name);
651
+ return _canopycanopycanopy_b_ber_lib_Theme.default.set(theme, true);
652
+ }
653
+ start() {
654
+ this.createAssets().then(() => this.copyImages()).then(() => this.setTheme()).then(() => _canopycanopycanopy_b_ber_logger.default.notice(`Created new project [${this.name}]`)).catch(_canopycanopycanopy_b_ber_logger.default.error);
655
+ }
656
+ };
657
+ //#endregion
658
+ //#region src/inject/index.ts
659
+ const getRemoteAssets = (type) => Promise.resolve(_canopycanopycanopy_b_ber_lib_State.default.config[`remote_${type}`] || []);
660
+ const getAssets = (type) => Promise.all([fs_extra.default.readdir(_canopycanopycanopy_b_ber_lib_State.default.dist.ops(type)), getRemoteAssets(type)]).then(([a, b]) => [...a, ...b]);
661
+ const getInlineScripts = () => [new vinyl.default({ contents: Buffer.from(`window.bber = window.bber || {}; window.bber.env = '${_canopycanopycanopy_b_ber_lib_State.default.build}';`) })];
662
+ const ensureString = (objectOrString) => objectOrString instanceof vinyl.default ? objectOrString.contents?.toString() ?? "" : objectOrString;
663
+ const relative = (from, to) => path.default.relative(path.default.join(...from), path.default.join(...to));
664
+ const render$1 = ({ file, basePath, stylesheets, javascripts, inlineStylesheets, inlineJavascripts, metadata }) => {
665
+ const stylesheets_ = stylesheets.map(ensureString).map((f) => _canopycanopycanopy_b_ber_lib.Template.render(relative([basePath], ["stylesheets", f]), _canopycanopycanopy_b_ber_templates_Xhtml.default.stylesheet())).join("");
666
+ const inlineStylesheets_ = inlineStylesheets.map(ensureString).map((f) => _canopycanopycanopy_b_ber_lib.Template.render(f, _canopycanopycanopy_b_ber_templates_Xhtml.default.stylesheet(true))).join("");
667
+ const javascripts_ = javascripts.map(ensureString).map((f) => _canopycanopycanopy_b_ber_lib.Template.render(relative([basePath], ["javascripts", f]), _canopycanopycanopy_b_ber_templates_Xhtml.default.javascript())).join("");
668
+ const inlineJavascripts_ = inlineJavascripts.map(ensureString).map((f) => _canopycanopycanopy_b_ber_lib.Template.render(f, _canopycanopycanopy_b_ber_templates_Xhtml.default.javascript(true))).join("");
669
+ const metadata_ = metadata.map(ensureString).map((f) => _canopycanopycanopy_b_ber_lib.Template.render(f, _canopycanopycanopy_b_ber_templates_Xhtml.default.jsonLD())).join("");
670
+ return `${_canopycanopycanopy_b_ber_lib.Template.render(`${stylesheets_}${inlineStylesheets_}`, _canopycanopycanopy_b_ber_templates_Xhtml.default.head())}${file instanceof vinyl.default ? file.contents?.toString() ?? "" : fs_extra.default.readFileSync(_canopycanopycanopy_b_ber_lib_State.default.dist.ops(basePath, file), "utf8")}${_canopycanopycanopy_b_ber_lib.Template.render(`${javascripts_}${inlineJavascripts_}${metadata_}`, _canopycanopycanopy_b_ber_templates_Xhtml.default.tail())}`;
671
+ };
672
+ const writeAll = (files) => Promise.all(files.map((file) => fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.text(file.fileName), file.contents)));
673
+ const getFileObjects = async (files, basePath = "") => {
674
+ const stylesheets = await getAssets("stylesheets");
675
+ const javascripts = await getAssets("javascripts");
676
+ const inlineStylesheets = [];
677
+ const inlineJavascripts = getInlineScripts();
678
+ const metadata = [];
679
+ return files.map((file) => ({
680
+ fileName: file.name,
681
+ contents: render$1({
682
+ file: file.data,
683
+ basePath,
684
+ stylesheets,
685
+ javascripts,
686
+ inlineStylesheets,
687
+ inlineJavascripts,
688
+ metadata
689
+ })
690
+ }));
691
+ };
692
+ const inject = async () => {
693
+ const basePath = "text";
694
+ return writeAll(await getFileObjects(fs_extra.default.readdirSync(_canopycanopycanopy_b_ber_lib_State.default.dist.ops(basePath)).map((file) => ({
695
+ name: file,
696
+ data: file
697
+ })), basePath)).catch(_canopycanopycanopy_b_ber_logger.default.error);
698
+ };
699
+ //#endregion
700
+ //#region src/loi/index.ts
701
+ const createLOILeader = () => {
702
+ const baseName = "figures-titlepage";
703
+ const fileName = `${baseName}.xhtml`;
704
+ const markup = _canopycanopycanopy_b_ber_lib.Template.render(_canopycanopycanopy_b_ber_templates_Xhtml.default.loi(), _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
705
+ const guideItem = new _canopycanopycanopy_b_ber_lib.GuideItem({
706
+ fileName,
707
+ title: "Figures",
708
+ type: "loi"
709
+ });
710
+ _canopycanopycanopy_b_ber_lib_State.default.add("guide", guideItem);
711
+ if (_canopycanopycanopy_b_ber_lib_State.default.indexOf("spine.flattened", (item) => item.fileName === baseName) < 0) {
712
+ const item = {
713
+ fileName: baseName,
714
+ in_toc: true,
715
+ ref: null,
716
+ pageOrder: -1,
717
+ generated: true
718
+ };
719
+ _canopycanopycanopy_b_ber_lib_State.default.add("spine.entries", baseName);
720
+ _canopycanopycanopy_b_ber_lib_State.default.add("spine.nested", new _canopycanopycanopy_b_ber_lib.SpineItem(item));
721
+ _canopycanopycanopy_b_ber_lib_State.default.add("spine.flattened", item);
722
+ }
723
+ _canopycanopycanopy_b_ber_logger.default.info(`loi emit default figures titlepage [${fileName}]`);
724
+ return fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.text(fileName), markup, "utf8");
725
+ };
726
+ const createLOIAsSingleHTMLFile = () => {
727
+ const classes = (item) => item.classes ? item.classes.replace(/small/g, "inline") : "";
728
+ const figuresPage = _canopycanopycanopy_b_ber_lib_State.default.figures.reduce((acc, curr) => acc.concat((0, _canopycanopycanopy_b_ber_templates_figures.default)({
729
+ ...curr,
730
+ classes: classes(curr)
731
+ }, _canopycanopycanopy_b_ber_lib_State.default.build)), _canopycanopycanopy_b_ber_templates_Xhtml.default.loi());
732
+ const fileName = "figures-titlepage.xhtml";
733
+ const markup = _canopycanopycanopy_b_ber_lib.Template.render(figuresPage, _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
734
+ const guideItem = new _canopycanopycanopy_b_ber_lib.GuideItem({
735
+ fileName,
736
+ title: "Figures",
737
+ type: "loi"
738
+ });
739
+ _canopycanopycanopy_b_ber_lib_State.default.add("guide", guideItem);
740
+ _canopycanopycanopy_b_ber_logger.default.info(`loi emit figures titlepage [${fileName}]`);
741
+ return fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.text(fileName), markup, "utf8");
742
+ };
743
+ const createLOIAsSeparateHTMLFiles = () => {
744
+ const promises = _canopycanopycanopy_b_ber_lib_State.default.figures.map((data) => {
745
+ const figures = (0, _canopycanopycanopy_b_ber_templates_figures.default)(data, _canopycanopycanopy_b_ber_lib_State.default.build);
746
+ const markup = _canopycanopycanopy_b_ber_lib.Template.render(figures, _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
747
+ const { page: fileName, ref, pageOrder } = data;
748
+ const in_toc = false;
749
+ const buildType = _canopycanopycanopy_b_ber_lib_State.default.build;
750
+ const spineItem = new _canopycanopycanopy_b_ber_lib.SpineItem({
751
+ fileName,
752
+ in_toc,
753
+ ref,
754
+ pageOrder,
755
+ buildType
756
+ });
757
+ _canopycanopycanopy_b_ber_lib_State.default.add("loi", spineItem);
758
+ _canopycanopycanopy_b_ber_logger.default.info(`loi linking [${data.source}] to [${data.page}]`);
759
+ return fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.text(data.page), markup, "utf8");
760
+ });
761
+ return Promise.all(promises).then(() => _canopycanopycanopy_b_ber_lib_State.default.update("loi", (0, lodash_sortBy_js.default)(_canopycanopycanopy_b_ber_lib_State.default.loi, "pageOrder")));
762
+ };
763
+ const loi = () => {
764
+ if (!_canopycanopycanopy_b_ber_lib_State.default.figures.length) return Promise.resolve();
765
+ if (_canopycanopycanopy_b_ber_lib_State.default.build === "reader") return createLOIAsSingleHTMLFile().catch(_canopycanopycanopy_b_ber_logger.default.error);
766
+ return createLOILeader().then(createLOIAsSeparateHTMLFiles).catch(_canopycanopycanopy_b_ber_logger.default.error);
767
+ };
768
+ //#endregion
769
+ //#region src/mobi/index.ts
770
+ const pageBreakBeforeXPATH = () => [
771
+ "//h:*[@class=\"figure__large figure__inline\"]",
772
+ "//h:*[@class=\"figure__large figure__inline\"]/following::h:p[1]",
773
+ "//h:*[contains(@class, \"break-before\")]",
774
+ "//h:*[@data-gallery-item]"
775
+ ].join("|");
776
+ const mobi = () => process.argv.includes("--no-compile") ? Promise.resolve() : _canopycanopycanopy_b_ber_lib_EbookConvert.default.convert({
777
+ inputPath: _canopycanopycanopy_b_ber_lib_State.default.dist.ops("content.opf"),
778
+ outputPath: process.cwd(),
779
+ fileType: "mobi",
780
+ fileName: (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("identifier"),
781
+ flags: [
782
+ "--mobi-file-type=both",
783
+ "--disable-font-rescaling",
784
+ "--no-inline-toc",
785
+ "--chapter=\"/\"",
786
+ "--chapter-mark=none",
787
+ "--disable-remove-fake-margins",
788
+ `--page-breaks-before='${pageBreakBeforeXPATH()}'`
789
+ ]
790
+ }).catch(_canopycanopycanopy_b_ber_logger.default.error);
791
+ //#endregion
792
+ //#region src/mobi/mobi-css.ts
793
+ const blackListedPrefixes = ["epub|"];
794
+ const blackListedTypes = ["namespace"];
795
+ const blackListedProperties = [
796
+ "line-height",
797
+ "-webkit-hyphens",
798
+ "-epub-hyphens",
799
+ "adobe-hyphenate",
800
+ "-moz-hyphens",
801
+ "-ms-hyphens",
802
+ "hyphens",
803
+ "word-break",
804
+ "word-break",
805
+ "widows",
806
+ "orphans",
807
+ "text-rendering",
808
+ "-webkit-font-smoothing",
809
+ "-moz-osx-font-smoothing",
810
+ "-webkit-text-fill-color"
811
+ ];
812
+ const write$1 = ({ file, content }) => fs_extra.default.writeFile(file, content, "utf8").then(() => _canopycanopycanopy_b_ber_logger.default.info(`mobiCSS write [${path.default.basename(file)}]`));
813
+ const process$1 = (file) => fs_extra.default.readFile(file, "utf8").then((data) => {
814
+ const ast = css.default.parse(data);
815
+ let i = ast.stylesheet.rules.length - 1;
816
+ while (i >= 0) {
817
+ const rule = ast.stylesheet.rules[i];
818
+ if (rule.selectors) {
819
+ let j = rule.selectors.length - 1;
820
+ while (j >= 0) {
821
+ let jj = 0;
822
+ while (jj < blackListedPrefixes.length) {
823
+ if (rule.selectors[j].slice(0, blackListedPrefixes[jj].length) === blackListedPrefixes[jj]) {
824
+ _canopycanopycanopy_b_ber_logger.default.info("mobiCSS remove selector", rule.selectors[j]);
825
+ rule.selectors.splice(j, 1);
826
+ }
827
+ jj++;
828
+ }
829
+ j--;
830
+ }
831
+ }
832
+ if (blackListedTypes.indexOf(rule.type) > -1) {
833
+ _canopycanopycanopy_b_ber_logger.default.info(`mobiCSS remove ${rule.type} [${rule[rule.type]}]`);
834
+ ast.stylesheet.rules.splice(i, 1);
835
+ }
836
+ if (ast.stylesheet.rules[i]) {
837
+ const { declarations } = ast.stylesheet.rules[i];
838
+ if (declarations) {
839
+ let a = declarations.length - 1;
840
+ while (a >= 0) {
841
+ if (blackListedProperties.indexOf(declarations[a].property) > -1) {
842
+ _canopycanopycanopy_b_ber_logger.default.info(`mobiCSS remove property [${declarations[a].property}]`);
843
+ declarations.splice(a, 1);
844
+ }
845
+ a--;
846
+ }
847
+ }
848
+ }
849
+ i--;
850
+ }
851
+ return {
852
+ file,
853
+ content: css.default.stringify(ast)
854
+ };
79
855
  });
80
- _Object$defineProperty(exports, "mobiCSS", {
81
- enumerable: true,
82
- get: function () {
83
- return _mobiCss.default;
84
- }
856
+ const mobiCSS = () => {
857
+ const stylesheetsPath = _canopycanopycanopy_b_ber_lib_State.default.dist.stylesheets();
858
+ return fs_extra.default.readdir(stylesheetsPath).then((files) => Promise.all(files.map((stylesheet) => {
859
+ const file = _canopycanopycanopy_b_ber_lib_State.default.dist.stylesheets(stylesheet);
860
+ _canopycanopycanopy_b_ber_logger.default.info(`mobiCSS process [${path.default.basename(file)}]`);
861
+ return process$1(file).then(write$1);
862
+ })).catch(_canopycanopycanopy_b_ber_logger.default.error));
863
+ };
864
+ //#endregion
865
+ //#region src/opf/helpers.ts
866
+ const isRemote = (file) => /^http/.test(file);
867
+ const pathInfoFromFile = (file, dest) => {
868
+ if (isRemote(file)) return {
869
+ absolutePath: file,
870
+ opsPath: file,
871
+ name: file,
872
+ extension: "",
873
+ remote: true
874
+ };
875
+ return {
876
+ absolutePath: file,
877
+ opsPath: (0, _canopycanopycanopy_b_ber_lib_utils.opsPath)(file, dest),
878
+ name: path.default.basename(file),
879
+ extension: path.default.extname(file),
880
+ remote: false
881
+ };
882
+ };
883
+ const pathInfoFromFiles = (arr, dest) => arr.map((file) => pathInfoFromFile(file, dest));
884
+ //#endregion
885
+ //#region src/opf/ManifestAndMetadata.ts
886
+ var ManifestAndMetadata = class {
887
+ bookmeta;
888
+ constructor() {
889
+ this.bookmeta = [];
890
+ }
891
+ async loadMetadata() {
892
+ this.bookmeta = _canopycanopycanopy_b_ber_lib_State.default.metadata.json();
893
+ }
894
+ async createManifestObjectFromAssets() {
895
+ let files = await (0, recursive_readdir.default)(_canopycanopycanopy_b_ber_lib_State.default.dist.ops());
896
+ files = [..._canopycanopycanopy_b_ber_lib_State.default.remoteAssets, ...files.filter((file) => path.default.basename(file).charAt(0) !== ".")];
897
+ return pathInfoFromFiles(files, _canopycanopycanopy_b_ber_lib_State.default.distDir);
898
+ }
899
+ createManifestAndMetadataFromTemplates(files) {
900
+ const manifest = files.map((file) => _canopycanopycanopy_b_ber_templates_Opf_Manifest.default.item(file));
901
+ const specifiedFonts = (0, lodash_has_js.default)(_canopycanopycanopy_b_ber_lib_State.default.config, "ibooks_specified_fonts") && _canopycanopycanopy_b_ber_lib_State.default.config.ibooks_specified_fonts === true;
902
+ const modified = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
903
+ const generator = `b-ber@${_canopycanopycanopy_b_ber_lib_State.default.version}`;
904
+ return {
905
+ manifest,
906
+ bookmeta: [
907
+ ...this.bookmeta.map((value) => _canopycanopycanopy_b_ber_templates_Opf_Metadata.default.meta(value)).filter(Boolean),
908
+ `<meta property="ibooks:specified-fonts">${specifiedFonts}</meta>`,
909
+ `<meta property="dcterms:modified">${modified}</meta>`,
910
+ `<meta name="generator" content="${generator}" />`
911
+ ]
912
+ };
913
+ }
914
+ createManifestAndMetadataXML(resp) {
915
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [metadata]");
916
+ const metadata = (0, layouts.default)(new vinyl.default({
917
+ path: ".tmp",
918
+ layout: "body",
919
+ contents: Buffer.from(resp.bookmeta.join(""))
920
+ }), { body: _canopycanopycanopy_b_ber_templates_Opf_Metadata.default.body() }).contents?.toString() ?? "";
921
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [manifest]");
922
+ return {
923
+ metadata,
924
+ manifest: (0, layouts.default)(new vinyl.default({
925
+ path: ".tmp",
926
+ layout: "body",
927
+ contents: Buffer.from(resp.manifest.filter(Boolean).join(""))
928
+ }), { body: _canopycanopycanopy_b_ber_templates_Opf_Manifest.default.body() }).contents?.toString() ?? ""
929
+ };
930
+ }
931
+ init() {
932
+ return this.loadMetadata().then(() => this.createManifestObjectFromAssets()).then((resp) => this.createManifestAndMetadataFromTemplates(resp)).then((resp) => this.createManifestAndMetadataXML(resp)).catch(_canopycanopycanopy_b_ber_logger.default.error);
933
+ }
934
+ };
935
+ //#endregion
936
+ //#region src/opf/Navigation.ts
937
+ var Navigation = class Navigation {
938
+ static createEmptyNavDocuments() {
939
+ const navDocs = ["toc.ncx", "toc.xhtml"];
940
+ _canopycanopycanopy_b_ber_logger.default.info(`opf build navigation documents [${navDocs.join(", ")}]`);
941
+ const promises = navDocs.map((doc) => fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.ops(doc), ""));
942
+ return Promise.all(promises);
943
+ }
944
+ static compareXhtmlWithYaml() {
945
+ const files = glob.default.sync(_canopycanopycanopy_b_ber_lib_State.default.dist.ops("**", "*.xhtml")).map((file) => path.default.basename(file, ".xhtml"));
946
+ const promises = [Promise.resolve()];
947
+ const missing = [];
948
+ const redundant = [];
949
+ const tocFile = fs_extra.default.existsSync(_canopycanopycanopy_b_ber_lib_State.default.src.root(`${_canopycanopycanopy_b_ber_lib_State.default.build}.yml`)) ? _canopycanopycanopy_b_ber_lib_State.default.src.root(`${_canopycanopycanopy_b_ber_lib_State.default.build}.yml`) : _canopycanopycanopy_b_ber_lib_State.default.src.root("toc.yml");
950
+ const tocEntries = _canopycanopycanopy_b_ber_lib_State.default.spine.flattenYAML(_canopycanopycanopy_b_ber_lib.YamlAdaptor.load(tocFile));
951
+ (0, lodash_difference_js.default)(files, tocEntries).forEach((name) => {
952
+ if (_canopycanopycanopy_b_ber_lib_State.default.contains("loi", { name })) return;
953
+ const entry = _canopycanopycanopy_b_ber_lib_State.default.find("spine.flattened", { name });
954
+ let yamlString = `\n- ${name}`;
955
+ if (entry) {
956
+ const { linear, in_toc } = entry;
957
+ const attributes = {};
958
+ if (linear === false) attributes.linear = false;
959
+ if (in_toc === false) attributes.in_toc = false;
960
+ if (Object.keys(attributes).length) {
961
+ const space = "\n ";
962
+ yamlString += ":";
963
+ yamlString = Object.entries(attributes).reduce((acc, [key, val]) => acc.concat(`${space}${key}: ${val}`), yamlString);
964
+ }
965
+ }
966
+ missing.push(name);
967
+ promises.push(fs_extra.default.appendFile(tocFile, yamlString));
968
+ });
969
+ const redundantEntries = (0, lodash_difference_js.default)(tocEntries, files);
970
+ if (_canopycanopycanopy_b_ber_lib_State.default.build === "pdf") {
971
+ const coverIndex = redundantEntries.indexOf("cover");
972
+ if (coverIndex > -1) redundantEntries.splice(coverIndex, 1);
973
+ }
974
+ redundantEntries.forEach((name) => redundant.push(name));
975
+ if (missing.length) missing.forEach((name) => _canopycanopycanopy_b_ber_logger.default.warn("opf [%s] was not declared in the TOC. Adding [%s] to [%s]", name, name, path.default.basename(tocFile)));
976
+ if (redundant.length) {
977
+ let message = "Files declared in the TOC do not exist in the _markdown directory";
978
+ message += `\nThe following entries must be removed manually from [${path.default.basename(tocFile)}]:`;
979
+ message += `\n${redundant.map((name) => `[${name}]`).join("\n")}`;
980
+ _canopycanopycanopy_b_ber_logger.default.error(message);
981
+ }
982
+ return Promise.all(promises);
983
+ }
984
+ static async createTocStringsFromTemplate() {
985
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [toc.xhtml]");
986
+ const { toc } = _canopycanopycanopy_b_ber_lib_State.default;
987
+ const [{ contents }] = await getFileObjects([{
988
+ name: "toc.xhtml",
989
+ data: new vinyl.default({ contents: Buffer.from(_canopycanopycanopy_b_ber_lib.Template.render(_canopycanopycanopy_b_ber_templates_Toc.default.items(toc), _canopycanopycanopy_b_ber_templates_Toc.default.body())) })
990
+ }]);
991
+ return contents;
992
+ }
993
+ static createNcxStringsFromTemplate() {
994
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [toc.ncx]");
995
+ const { toc } = _canopycanopycanopy_b_ber_lib_State.default;
996
+ const ncxXML = _canopycanopycanopy_b_ber_templates_Ncx.default.navPoints(toc);
997
+ return _canopycanopycanopy_b_ber_lib.Template.render(ncxXML, _canopycanopycanopy_b_ber_templates_Ncx.default.document());
998
+ }
999
+ static createGuideStringsFromTemplate() {
1000
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [guide]");
1001
+ const guideXML = _canopycanopycanopy_b_ber_templates_Opf_Guide.default.items(_canopycanopycanopy_b_ber_lib_State.default.guide);
1002
+ return _canopycanopycanopy_b_ber_lib.Template.render(guideXML, _canopycanopycanopy_b_ber_templates_Opf_Guide.default.body());
1003
+ }
1004
+ static createSpineStringsFromTemplate() {
1005
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [spine]");
1006
+ const { flattened } = _canopycanopycanopy_b_ber_lib_State.default.spine;
1007
+ (0, lodash_remove_js.default)(flattened, (file) => file.generated === true).forEach((file) => {
1008
+ if (!(0, lodash_find_js.default)(flattened, { fileName: file.fileName })) flattened.push(file);
1009
+ });
1010
+ const spineXML = _canopycanopycanopy_b_ber_templates_Opf_Spine.default.items(flattened);
1011
+ return _canopycanopycanopy_b_ber_lib.Template.render(spineXML, _canopycanopycanopy_b_ber_templates_Opf_Spine.default.body());
1012
+ }
1013
+ static writeTocXhtmlFile(toc) {
1014
+ const filepath = _canopycanopycanopy_b_ber_lib_State.default.dist.ops("toc.xhtml");
1015
+ _canopycanopycanopy_b_ber_logger.default.info(`opf emit toc.xhtml [${filepath}]`);
1016
+ return fs_extra.default.writeFile(filepath, toc);
1017
+ }
1018
+ static writeTocNcxFile(ncx) {
1019
+ const filepath = _canopycanopycanopy_b_ber_lib_State.default.dist.ops("toc.ncx");
1020
+ _canopycanopycanopy_b_ber_logger.default.info(`opf emit toc.ncx [${filepath}]`);
1021
+ return fs_extra.default.writeFile(filepath, ncx);
1022
+ }
1023
+ static async writeFiles([toc, ncx, guide, spine]) {
1024
+ await Promise.all([Navigation.writeTocXhtmlFile(toc), Navigation.writeTocNcxFile(ncx)]);
1025
+ return {
1026
+ spine,
1027
+ guide
1028
+ };
1029
+ }
1030
+ static init() {
1031
+ return Navigation.createEmptyNavDocuments().then(() => Navigation.compareXhtmlWithYaml()).then(() => Promise.all([
1032
+ Navigation.createTocStringsFromTemplate(),
1033
+ Navigation.createNcxStringsFromTemplate(),
1034
+ Navigation.createGuideStringsFromTemplate(),
1035
+ Navigation.createSpineStringsFromTemplate()
1036
+ ])).then((resp) => Navigation.writeFiles(resp)).catch(_canopycanopycanopy_b_ber_logger.default.error);
1037
+ }
1038
+ };
1039
+ //#endregion
1040
+ //#region src/opf/index.ts
1041
+ const opf = class Opf {
1042
+ static createOpf() {
1043
+ const manifestAndMetadata = new ManifestAndMetadata();
1044
+ return Promise.all([manifestAndMetadata.init(), Navigation.init()]).then(Opf.createOpfPackageString).then(Opf.writeOPF).catch(_canopycanopycanopy_b_ber_logger.default.error);
1045
+ }
1046
+ static writeOPF(contents) {
1047
+ const opsPath = _canopycanopycanopy_b_ber_lib_State.default.dist.ops("content.opf");
1048
+ _canopycanopycanopy_b_ber_logger.default.info(`opf emit content.opf [${opsPath}]`);
1049
+ return fs_extra.default.writeFile(opsPath, contents);
1050
+ }
1051
+ static createOpfPackageString([manifestAndMetadataXML, navigationXML]) {
1052
+ _canopycanopycanopy_b_ber_logger.default.info("opf build [package]");
1053
+ const { metadata, manifest } = manifestAndMetadataXML;
1054
+ const { guide, spine } = navigationXML;
1055
+ return (0, layouts.default)(new vinyl.default({
1056
+ path: ".tmp",
1057
+ layout: "body",
1058
+ contents: Buffer.from(`
1059
+ ${metadata}
1060
+ ${manifest}
1061
+ ${spine}
1062
+ ${guide}
1063
+ `)
1064
+ }), { body: _canopycanopycanopy_b_ber_templates_Opf_Pkg.default.body() }).contents?.toString() ?? "";
1065
+ }
1066
+ }.createOpf;
1067
+ //#endregion
1068
+ //#region src/pdf/index.ts
1069
+ const booleans = new Set([
1070
+ "pdf_mark_links",
1071
+ "preserve_cover_aspect_ratio",
1072
+ "pretty_print",
1073
+ "uncompressed_pdf",
1074
+ "pdf_page_numbers",
1075
+ "pdf_add_toc",
1076
+ "use_profile_size",
1077
+ "disable_font_rescaling",
1078
+ "subset_embedded_fonts",
1079
+ "embed_all_fonts ",
1080
+ "linearize_tables",
1081
+ "expand_css",
1082
+ "smarten_punctuation",
1083
+ "unsmarten_punctuation",
1084
+ "insert_blank_line",
1085
+ "remove_paragraph_spacing",
1086
+ "asciiize",
1087
+ "keep_ligatures",
1088
+ "enable_heuristics",
1089
+ "disable_markup_chapter_headings",
1090
+ "disable_italicize_common_cases",
1091
+ "disable_fix_indents",
1092
+ "disable_unwrap_lines",
1093
+ "disable_delete_blank_paragraphs",
1094
+ "disable_format_scene_breaks",
1095
+ "disable_dehyphenate",
1096
+ "disable_renumber_headings",
1097
+ "prefer_metadata_cover",
1098
+ "remove_first_image",
1099
+ "insert_metadata ",
1100
+ "disable_remove_fake_margins",
1101
+ "no_chapters_in_toc",
1102
+ "use_auto_toc",
1103
+ "duplicate_links_in_toc"
1104
+ ]);
1105
+ const settings = new Set([
1106
+ "u",
1107
+ "unit",
1108
+ "m",
1109
+ "read_metadata_from_opf",
1110
+ "from_opf",
1111
+ "custom_size",
1112
+ "pdf_standard_font",
1113
+ "pdf_page_margin_top",
1114
+ "pdf_page_margin_right",
1115
+ "toc_title",
1116
+ "pdf_serif_family",
1117
+ "pdf_mono_font_size",
1118
+ "pdf_page_margin_left",
1119
+ "pdf_page_margin_bottom",
1120
+ "pdf_footer_template",
1121
+ "pdf_default_font_size",
1122
+ "pdf_sans_family",
1123
+ "pdf_mono_family",
1124
+ "paper_size",
1125
+ "pdf_header_template",
1126
+ "base_font_size",
1127
+ "font_size_mapping",
1128
+ "embed_font_family",
1129
+ "line_height",
1130
+ "minimum_line_height",
1131
+ "extra_css",
1132
+ "filter_css",
1133
+ "transform_css_rules",
1134
+ "margin_top",
1135
+ "margin_left",
1136
+ "margin_right",
1137
+ "margin_bottom",
1138
+ "change_justification",
1139
+ "insert_blank_line_size",
1140
+ "remove_paragraph_spacing_indent_size",
1141
+ "html_unwrap_factor",
1142
+ "replace_scene_breaks",
1143
+ "sr1_search",
1144
+ "sr1_replace",
1145
+ "sr2_search",
1146
+ "sr2_replace",
1147
+ "sr3_search",
1148
+ "sr3_replace",
1149
+ "search_replace",
1150
+ "chapter",
1151
+ "chapter_mark",
1152
+ "page_breaks_before",
1153
+ "start_reading_at",
1154
+ "level1_toc",
1155
+ "level2_toc",
1156
+ "level3_toc",
1157
+ "toc_threshold",
1158
+ "max_toc_links",
1159
+ "toc_filter",
1160
+ "title",
1161
+ "authors",
1162
+ "title_sort",
1163
+ "author_sort",
1164
+ "cover",
1165
+ "comments",
1166
+ "publisher",
1167
+ "series",
1168
+ "series_index",
1169
+ "rating",
1170
+ "isbn",
1171
+ "tags",
1172
+ "book_producer",
1173
+ "language",
1174
+ "pubdate",
1175
+ "timestamp"
1176
+ ]);
1177
+ const toArg = (key, val) => {
1178
+ if (typeof val === "undefined") return `--${(0, lodash_kebabCase_js.default)(key)}`;
1179
+ return `--${(0, lodash_kebabCase_js.default)(key)}=${val}`;
1180
+ };
1181
+ const getPDFFlags = (options) => {
1182
+ if (Object.keys(options).length < 1) return [];
1183
+ return Object.entries(options).reduce((acc, [key, val]) => {
1184
+ if (booleans.has(key)) return acc.concat(toArg(key));
1185
+ if (settings.has(key)) return acc.concat(toArg(key, val));
1186
+ return acc;
1187
+ }, []);
1188
+ };
1189
+ const pdf = () => {
1190
+ const opsPath = _canopycanopycanopy_b_ber_lib_State.default.dist.ops();
1191
+ const inputPath = path.default.join(opsPath, "content.opf");
1192
+ const flags = getPDFFlags(_canopycanopycanopy_b_ber_lib_State.default.config.pdf_options || {});
1193
+ const tocPath = path.default.join(opsPath, "toc.xhtml");
1194
+ return fs_extra.default.remove(tocPath).then(() => process.argv.includes("--no-compile") ? Promise.resolve() : _canopycanopycanopy_b_ber_lib_EbookConvert.default.convert({
1195
+ inputPath,
1196
+ outputPath: process.cwd(),
1197
+ fileType: "pdf",
1198
+ fileName: (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("identifier"),
1199
+ flags
1200
+ }).catch(_canopycanopycanopy_b_ber_logger.default.error));
1201
+ };
1202
+ //#endregion
1203
+ //#region src/reader/index.ts
1204
+ var Reader = class {
1205
+ outputDirName;
1206
+ outputDir;
1207
+ apiDir;
1208
+ epubAssets;
1209
+ readerModuleName;
1210
+ readerModuleDistDir;
1211
+ readerAppPath;
1212
+ constructor() {
1213
+ this.outputDirName = "epub";
1214
+ this.outputDir = _canopycanopycanopy_b_ber_lib_State.default.dist.root(this.outputDirName);
1215
+ this.apiDir = _canopycanopycanopy_b_ber_lib_State.default.dist.root("api");
1216
+ this.epubAssets = [
1217
+ "META-INF",
1218
+ "OPS",
1219
+ "mimetype"
1220
+ ];
1221
+ this.readerModuleName = "@canopycanopycanopy/b-ber-reader";
1222
+ this.readerModuleDistDir = "dist";
1223
+ this.readerAppPath = null;
1224
+ return this.createOutputDirs().then(() => this.ensureReaderModuleExists()).then(() => this.copyEpubToOutputDir()).then(() => this.writeBookManifest()).then(() => this.writeWebpubManifest()).then(() => this.copyReaderAppToOutputDir()).then(() => this.injectServerDataIntoTemplate()).then(() => this.updateAssetURLsWithAbsolutePaths()).then(() => this.injectWebpubManifestLink()).catch(_canopycanopycanopy_b_ber_logger.default.error);
1225
+ }
1226
+ get remoteURL() {
1227
+ if (process.env.NODE_ENV === "production" && (!_canopycanopycanopy_b_ber_lib_State.default.config || !_canopycanopycanopy_b_ber_lib_State.default.config.remote_url || /^http/.test(_canopycanopycanopy_b_ber_lib_State.default.config.remote_url) === false)) throw new Error("Task [build/reader] requires a remote_url to be set in config.yml");
1228
+ return _canopycanopycanopy_b_ber_lib_State.default.config.remote_url || "http://localhost:4000/";
1229
+ }
1230
+ createDirname(s) {
1231
+ if (!s || typeof s !== "string") return crypto.default.randomBytes(20).toString("hex");
1232
+ return s.replace(/[^0-9a-zA-Z-]/g, "-");
1233
+ }
1234
+ ensureReaderModuleExists() {
1235
+ try {
1236
+ this.readerAppPath = path.default.join(path.default.dirname(path.default.join(require.resolve(this.readerModuleName))), this.readerModuleDistDir);
1237
+ return;
1238
+ } catch (err) {
1239
+ _canopycanopycanopy_b_ber_logger.default.warn(`Could not find globally installed module ${this.readerModuleName}`);
1240
+ }
1241
+ const { paths } = module;
1242
+ let modulePath;
1243
+ for (let i = 0; i < paths.length; i++) {
1244
+ const _path = path.default.resolve(paths[i], this.readerModuleName);
1245
+ if (fs_extra.default.existsSync(_path)) {
1246
+ modulePath = _path;
1247
+ break;
1248
+ }
1249
+ }
1250
+ if (!modulePath) _canopycanopycanopy_b_ber_logger.default.error(`Cannot find module ${this.readerModuleName}. Try running npm i -S ${this.readerModuleName}`);
1251
+ try {
1252
+ this.readerAppPath = fs_extra.default.realpathSync(path.default.join(modulePath, this.readerModuleDistDir));
1253
+ const pkg = fs_extra.default.readJsonSync(path.default.join(modulePath, this.readerModuleDistDir, "package.json"));
1254
+ _canopycanopycanopy_b_ber_logger.default.warn(`Loaded ${this.readerModuleName} v${pkg.version}`);
1255
+ return;
1256
+ } catch (err) {
1257
+ _canopycanopycanopy_b_ber_logger.default.error(`
1258
+ A symlinked version of ${this.readerModuleName} was found but is inaccessible.
1259
+ Try running npm i -S ${this.readerModuleName}, or rebuilding the reader package if running this command in a development environment
1260
+ `);
1261
+ process.exit(1);
1262
+ }
1263
+ }
1264
+ createOutputDirs() {
1265
+ return fs_extra.default.ensureDir(this.outputDir).then(() => fs_extra.default.ensureDir(this.apiDir));
1266
+ }
1267
+ copyEpubToOutputDir() {
1268
+ const epubDir = this.createDirname(this.getBookMetadata("identifier"));
1269
+ const promises = this.epubAssets.map((item) => fs_extra.default.move(_canopycanopycanopy_b_ber_lib_State.default.dist.root(item), path.default.join(this.outputDir, epubDir, item)));
1270
+ return Promise.all(promises);
1271
+ }
1272
+ getBookMetadata(term) {
1273
+ if (!term) return _canopycanopycanopy_b_ber_lib_State.default.metadata.json();
1274
+ const entry = (0, lodash_find_js.default)(_canopycanopycanopy_b_ber_lib_State.default.metadata.json(), { term });
1275
+ if (entry && entry.value) return entry.value;
1276
+ _canopycanopycanopy_b_ber_logger.default.warn(`Could not find metadata value for ${term}`);
1277
+ return "";
1278
+ }
1279
+ getProjectConfig(term) {
1280
+ if (!term) return _canopycanopycanopy_b_ber_lib_State.default.config;
1281
+ if (!(0, lodash_has_js.default)(_canopycanopycanopy_b_ber_lib_State.default.config, term)) _canopycanopycanopy_b_ber_logger.default.warn(`Invalid property for config: ${term}`);
1282
+ return _canopycanopycanopy_b_ber_lib_State.default.config[term];
1283
+ }
1284
+ writeBookManifest() {
1285
+ const id = this.getBookMetadata("identifier");
1286
+ const title = this.getBookMetadata("title");
1287
+ const url = `${_canopycanopycanopy_b_ber_lib.Url.trimSlashes(this.remoteURL)}/${this.outputDirName}/${this.createDirname(id)}`;
1288
+ const cover = `${url}/OPS/images/${this.getBookMetadata("cover")}`;
1289
+ const { downloads, ui_options, layout } = this.getProjectConfig();
1290
+ const manifest = [{
1291
+ title,
1292
+ url,
1293
+ cover,
1294
+ id,
1295
+ downloads,
1296
+ ui_options,
1297
+ layout
1298
+ }];
1299
+ return fs_extra.default.writeJson(path.default.join(this.apiDir, "books.json"), manifest);
1300
+ }
1301
+ writeWebpubManifest() {
1302
+ return (0, recursive_readdir.default)(path.default.join(process.cwd(), this.outputDir, this.getBookMetadata("identifier"), "OPS")).then((files) => {
1303
+ const manifest = (0, _canopycanopycanopy_b_ber_lib_utils.generateWebpubManifest)(files);
1304
+ fs_extra.default.writeJson(_canopycanopycanopy_b_ber_lib_State.default.dist.root("manifest.json"), manifest);
1305
+ });
1306
+ }
1307
+ injectWebpubManifestLink() {
1308
+ const indexHTML = _canopycanopycanopy_b_ber_lib_State.default.dist.root("index.html");
1309
+ const readerURL = _canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(this.getProjectConfig("reader_url"));
1310
+ let contents;
1311
+ contents = fs_extra.default.readFileSync(indexHTML, "utf8");
1312
+ contents = contents.replace(/<\/head>/, `<link rel="manifest" type="application/webpub+json" href="${readerURL}manifest.json"></head>`);
1313
+ return fs_extra.default.writeFile(indexHTML, contents);
1314
+ }
1315
+ copyReaderAppToOutputDir() {
1316
+ const promises = fs_extra.default.readdirSync(this.readerAppPath).map((file) => fs_extra.default.copy(path.default.join(this.readerAppPath, file), path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.dist.root(file))));
1317
+ return Promise.all(promises);
1318
+ }
1319
+ injectServerDataIntoTemplate() {
1320
+ const indexHTML = _canopycanopycanopy_b_ber_lib_State.default.dist.root("index.html");
1321
+ const bookURL = `${_canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(this.getProjectConfig("reader_url"))}epub/${this.getBookMetadata("identifier")}`;
1322
+ const serverData = {
1323
+ books: [{
1324
+ title: this.getBookMetadata("title"),
1325
+ url: bookURL,
1326
+ cover: this.getBookMetadata("cover")
1327
+ }],
1328
+ bookURL,
1329
+ projectURL: _canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(this.getProjectConfig("remote_url")),
1330
+ downloads: this.getProjectConfig("downloads"),
1331
+ basePath: _canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(this.getProjectConfig("base_path")),
1332
+ loadRemoteLibrary: false,
1333
+ uiOptions: this.getProjectConfig("ui_options"),
1334
+ cache: this.getProjectConfig("cache"),
1335
+ layout: this.getProjectConfig("layout")
1336
+ };
1337
+ let contents;
1338
+ contents = fs_extra.default.readFileSync(indexHTML, "utf8");
1339
+ contents = contents.replace(/__SERVER_DATA__ = {}/, `__SERVER_DATA__ = ${JSON.stringify(serverData)}`);
1340
+ return fs_extra.default.writeFile(indexHTML, contents);
1341
+ }
1342
+ updateLinkedResourcesWithAbsolutePaths() {
1343
+ const versionHash = fs_extra.default.readFileSync(_canopycanopycanopy_b_ber_lib_State.default.dist.root("index.html"), "utf8").match(/link href="\/(\w+\.css)"/)?.[1] ?? "";
1344
+ const stylesheet = _canopycanopycanopy_b_ber_lib_State.default.dist.root(versionHash);
1345
+ const readerURL = _canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(this.getProjectConfig("reader_url"));
1346
+ let contents;
1347
+ contents = fs_extra.default.readFileSync(stylesheet, "utf8");
1348
+ contents = contents.replace(/url\(\//g, `url(${readerURL}`);
1349
+ return fs_extra.default.writeFile(stylesheet, contents);
1350
+ }
1351
+ updateAssetURLsWithAbsolutePaths() {
1352
+ const indexHTML = _canopycanopycanopy_b_ber_lib_State.default.dist.root("index.html");
1353
+ const readerURL = _canopycanopycanopy_b_ber_lib.Url.removeTrailingSlash(this.getProjectConfig("reader_url"));
1354
+ let contents;
1355
+ contents = fs_extra.default.readFileSync(indexHTML, "utf8");
1356
+ contents = contents.replace(/(src|href)="(\/[^"]+?)"/g, `$1="${readerURL}$2"`);
1357
+ return fs_extra.default.writeFile(indexHTML, contents);
1358
+ }
1359
+ };
1360
+ const main$1 = () => new Reader();
1361
+ //#endregion
1362
+ //#region src/render/index.ts
1363
+ const writeMarkupToFile = (fname, markup) => {
1364
+ fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.text(`${fname}.xhtml`), markup).then(() => _canopycanopycanopy_b_ber_logger.default.info(`render xhtml [${path.default.basename(fname)}.xhtml]`));
1365
+ };
1366
+ const createPageLayout = (fileName, data) => {
1367
+ const textDir = _canopycanopycanopy_b_ber_lib_State.default.dist.text();
1368
+ const body = _canopycanopycanopy_b_ber_markdown_renderer.default.render(fileName, data);
1369
+ const markup = _canopycanopycanopy_b_ber_lib.Template.render(body, _canopycanopycanopy_b_ber_templates_Xhtml.default.body());
1370
+ return fs_extra.default.mkdirp(textDir).then(() => writeMarkupToFile(fileName, markup)).catch(_canopycanopycanopy_b_ber_logger.default.error);
1371
+ };
1372
+ const createXTHMLFile = (fpath) => fs_extra.default.readFile(fpath, "utf8").then((data) => createPageLayout(path.default.basename(fpath, ".md"), data)).catch(_canopycanopycanopy_b_ber_logger.default.error);
1373
+ function render() {
1374
+ const markdownDir = _canopycanopycanopy_b_ber_lib_State.default.src.markdown();
1375
+ return fs_extra.default.readdir(markdownDir).then((files) => {
1376
+ return files.filter((a) => a.charAt(0) !== ".").sort((a, b) => {
1377
+ const fileNameA = path.default.basename(a, ".md");
1378
+ const fileNameB = path.default.basename(b, ".md");
1379
+ const indexA = _canopycanopycanopy_b_ber_lib_State.default.indexOf("spine.flattened", { fileName: fileNameA });
1380
+ const indexB = _canopycanopycanopy_b_ber_lib_State.default.indexOf("spine.flattened", { fileName: fileNameB });
1381
+ return indexA < indexB ? -1 : indexA > indexB ? 1 : 0;
1382
+ }).reduce((acc, curr) => acc.then(() => createXTHMLFile(path.default.join(markdownDir, curr)).then(() => _canopycanopycanopy_b_ber_logger.default.info(`render markdown [${path.default.basename(curr)}]`))), Promise.resolve()).catch(_canopycanopycanopy_b_ber_logger.default.error);
1383
+ });
1384
+ }
1385
+ //#endregion
1386
+ //#region src/sample/index.ts
1387
+ const sample = () => Promise.resolve();
1388
+ //#endregion
1389
+ //#region src/sass/index.ts
1390
+ const ASSET_DIRNAMES = ["fonts", "images"];
1391
+ const autoprefixerOptions = _canopycanopycanopy_b_ber_lib_State.default.config.autoprefixer_options || {
1392
+ overrideBrowserslist: [
1393
+ "defaults",
1394
+ "> 1%",
1395
+ "not dead",
1396
+ "not IE 11"
1397
+ ],
1398
+ flexbox: "no-2009"
1399
+ };
1400
+ const createSCSSString = () => {
1401
+ const chunks = [];
1402
+ const { theme } = _canopycanopycanopy_b_ber_lib_State.default;
1403
+ const themeName = theme.name;
1404
+ const themeSettingsPath = _canopycanopycanopy_b_ber_lib_State.default.src.stylesheets(themeName, "_settings.scss");
1405
+ const themeOverridesPath = _canopycanopycanopy_b_ber_lib_State.default.src.stylesheets(themeName, "_overrides.scss");
1406
+ const themeStylesPath = theme.entry;
1407
+ if (fs_extra.default.existsSync(themeSettingsPath)) {
1408
+ const variableOverrides = fs_extra.default.readFileSync(themeSettingsPath);
1409
+ _canopycanopycanopy_b_ber_logger.default.info(`sass use overrides [${path.default.basename(themeSettingsPath)}]`);
1410
+ _canopycanopycanopy_b_ber_logger.default.info("sass prepend overrides");
1411
+ chunks.push(variableOverrides);
1412
+ }
1413
+ if (fs_extra.default.existsSync(themeStylesPath)) {
1414
+ const themeStyles = fs_extra.default.readFileSync(themeStylesPath);
1415
+ _canopycanopycanopy_b_ber_logger.default.info(`sass attempt build with [${themeName}] theme`);
1416
+ chunks.push(themeStyles);
1417
+ }
1418
+ if (fs_extra.default.existsSync(themeOverridesPath)) {
1419
+ const styleOverrides = fs_extra.default.readFileSync(themeOverridesPath);
1420
+ _canopycanopycanopy_b_ber_logger.default.info(`sass use user-defined styles [${path.default.basename(themeOverridesPath)}]`);
1421
+ _canopycanopycanopy_b_ber_logger.default.info("sass append user-defined styles");
1422
+ chunks.push(styleOverrides);
1423
+ }
1424
+ if (chunks.length < 1) _canopycanopycanopy_b_ber_logger.default.error("No readable stylesheets were found");
1425
+ return Buffer.concat(chunks);
1426
+ };
1427
+ const ensureCSSDir = () => fs_extra.default.mkdirp(_canopycanopycanopy_b_ber_lib_State.default.dist.stylesheets());
1428
+ const copyThemeAssets = () => {
1429
+ const { theme } = _canopycanopycanopy_b_ber_lib_State.default;
1430
+ const promises = ASSET_DIRNAMES.reduce((acc, curr) => {
1431
+ const themePath = path.default.resolve(path.default.dirname(theme.entry), curr);
1432
+ const srcPath = _canopycanopycanopy_b_ber_lib_State.default.src.root(`_${curr}`);
1433
+ fs_extra.default.mkdirpSync(srcPath);
1434
+ try {
1435
+ fs_extra.default.lstatSync(themePath).isDirectory();
1436
+ } catch (err) {
1437
+ if (err.code === "ENOENT") return acc;
1438
+ throw new Error(`There was a problem copying [${themePath}] to [${srcPath}]`);
1439
+ }
1440
+ const data = fs_extra.default.readdirSync(themePath).filter((a) => a.charAt(0) !== ".").map((fileName) => ({
1441
+ input: path.default.join(themePath, fileName),
1442
+ output: path.default.join(srcPath, fileName)
1443
+ }));
1444
+ return acc.concat(data);
1445
+ }, []).map(({ input, output }) => fs_extra.default.copy(input, output, {
1446
+ overwrite: false,
1447
+ errorOnExist: false
1448
+ }));
1449
+ return Promise.all(promises);
1450
+ };
1451
+ function resolveImportedModule(importPath) {
1452
+ let importTree = importPath.slice(1).split(path.default.sep);
1453
+ importTree = importTree.filter(Boolean);
1454
+ let moduleScope = "";
1455
+ let moduleName = importTree.shift();
1456
+ if (moduleName[0] === "@") {
1457
+ moduleScope = moduleName;
1458
+ moduleName = importTree.shift();
1459
+ }
1460
+ const moduleNameWithScope = path.default.join(moduleScope, moduleName);
1461
+ const modulePath = require.resolve(moduleNameWithScope, { paths: [path.default.join(path.default.dirname(_canopycanopycanopy_b_ber_lib_State.default.theme.entry))] });
1462
+ if (!importTree.length) return modulePath;
1463
+ const moduleIndex = modulePath.indexOf(moduleName) + moduleName.length;
1464
+ const packagePath = modulePath.slice(0, moduleIndex);
1465
+ return path.default.join(packagePath, ...importTree);
1466
+ }
1467
+ const renderCSS = (scssString) => new Promise((resolve) => {
1468
+ sass.default.render({
1469
+ importer: (url, _file, done) => {
1470
+ return done({ file: url[0] === "~" ? resolveImportedModule(url) : url });
1471
+ },
1472
+ data: `$build: "${_canopycanopycanopy_b_ber_lib_State.default.build}";${scssString}`,
1473
+ includePaths: [
1474
+ _canopycanopycanopy_b_ber_lib_State.default.src.stylesheets(),
1475
+ path.default.dirname(_canopycanopycanopy_b_ber_lib_State.default.theme.entry),
1476
+ path.default.dirname(path.default.dirname(_canopycanopycanopy_b_ber_lib_State.default.theme.entry))
1477
+ ],
1478
+ outputStyle: _canopycanopycanopy_b_ber_lib_State.default.env === "production" ? "compressed" : "expanded",
1479
+ errLogToConsole: true
1480
+ }, (err, result) => {
1481
+ if (err) throw err;
1482
+ resolve(result);
1483
+ });
85
1484
  });
86
- _Object$defineProperty(exports, "opf", {
87
- enumerable: true,
88
- get: function () {
89
- return _opf.default;
90
- }
1485
+ const applyPostProcessing = ({ css }) => (0, postcss.default)((0, autoprefixer.default)(autoprefixerOptions)).process(css, { from: void 0 });
1486
+ const writeCSSFile = ({ css }) => {
1487
+ const fileName = _canopycanopycanopy_b_ber_lib_State.default.env === "production" ? `${_canopycanopycanopy_b_ber_lib_State.default.hash}.css` : "application.css";
1488
+ return fs_extra.default.writeFile(_canopycanopycanopy_b_ber_lib_State.default.dist.stylesheets(fileName), css);
1489
+ };
1490
+ const sass$1 = () => ensureCSSDir().then(copyThemeAssets).then(createSCSSString).then(renderCSS).then(applyPostProcessing).then(writeCSSFile).catch(_canopycanopycanopy_b_ber_logger.default.error);
1491
+ //#endregion
1492
+ //#region src/scripts/index.ts
1493
+ const uglifyOptions = _canopycanopycanopy_b_ber_lib_State.default.config.uglify_options || { compress: {
1494
+ dead_code: true,
1495
+ conditionals: true,
1496
+ booleans: true
1497
+ } };
1498
+ const uglify = (contents) => {
1499
+ const result = uglify_js.default.minify(contents, uglifyOptions);
1500
+ if (result.error) throw result.error;
1501
+ if (result.warnings) _canopycanopycanopy_b_ber_logger.default.warn(result.warnings);
1502
+ return result.code;
1503
+ };
1504
+ const optimized = (files) => {
1505
+ const js = uglify(files.map((file) => fs_extra.default.readFileSync(path.default.resolve(_canopycanopycanopy_b_ber_lib_State.default.src.javascripts(file)), "utf8")).join(""));
1506
+ const { hash } = _canopycanopycanopy_b_ber_lib_State.default;
1507
+ const out = _canopycanopycanopy_b_ber_lib_State.default.dist.javascripts(`${hash}.js`);
1508
+ return fs_extra.default.writeFile(out, js).then(() => _canopycanopycanopy_b_ber_logger.default.info("scripts emit [%s]", `javascripts${path.default.sep}${path.default.basename(out)}`));
1509
+ };
1510
+ const unoptimized = (files) => {
1511
+ const promises = files.map((file) => {
1512
+ const input = _canopycanopycanopy_b_ber_lib_State.default.src.javascripts(file);
1513
+ const output = _canopycanopycanopy_b_ber_lib_State.default.dist.javascripts(file);
1514
+ return fs_extra.default.copy(input, output).then(() => _canopycanopycanopy_b_ber_logger.default.info("scripts emit [%s]", `javascripts${path.default.sep}${path.default.basename(output)}`));
1515
+ });
1516
+ return Promise.all(promises);
1517
+ };
1518
+ const write = () => fs_extra.default.readdir(_canopycanopycanopy_b_ber_lib_State.default.src.javascripts()).then((_files) => {
1519
+ const files = _files.filter((a) => path.default.extname(a) === ".js");
1520
+ return (_canopycanopycanopy_b_ber_lib_State.default.env === "production" ? optimized : unoptimized)(files);
91
1521
  });
92
- _Object$defineProperty(exports, "pdf", {
93
- enumerable: true,
94
- get: function () {
95
- return _pdf.default;
96
- }
97
- });
98
- _Object$defineProperty(exports, "reader", {
99
- enumerable: true,
100
- get: function () {
101
- return _reader.default;
102
- }
103
- });
104
- _Object$defineProperty(exports, "render", {
105
- enumerable: true,
106
- get: function () {
107
- return _render.default;
108
- }
109
- });
110
- _Object$defineProperty(exports, "sample", {
111
- enumerable: true,
112
- get: function () {
113
- return _sample.default;
114
- }
115
- });
116
- _Object$defineProperty(exports, "sass", {
117
- enumerable: true,
118
- get: function () {
119
- return _sass.default;
120
- }
121
- });
122
- _Object$defineProperty(exports, "scripts", {
123
- enumerable: true,
124
- get: function () {
125
- return _scripts.default;
126
- }
127
- });
128
- _Object$defineProperty(exports, "serialize", {
129
- enumerable: true,
130
- get: function () {
131
- return _serialize.default;
132
- }
133
- });
134
- _Object$defineProperty(exports, "serve", {
135
- enumerable: true,
136
- get: function () {
137
- return _serve.default;
138
- }
139
- });
140
- _Object$defineProperty(exports, "validate", {
141
- enumerable: true,
142
- get: function () {
143
- return _validate.default;
144
- }
1522
+ const ensureDir = () => fs_extra.default.mkdirp(_canopycanopycanopy_b_ber_lib_State.default.dist.javascripts());
1523
+ const scripts = () => ensureDir().then(write).catch(_canopycanopycanopy_b_ber_logger.default.error);
1524
+ //#endregion
1525
+ //#region src/validate/index.ts
1526
+ const validate = async ({ project }) => {
1527
+ const markdownPath = path.default.resolve(process.cwd(), project, _canopycanopycanopy_b_ber_lib_State.default.src.markdown());
1528
+ if (!fs_extra.default.pathExists(markdownPath)) _canopycanopycanopy_b_ber_logger.default.error("Project path does not exist, aborting");
1529
+ const files = (await fs_extra.default.readdir(markdownPath)).filter((f) => f.slice(-2).toLowerCase() === "md").map((f) => path.default.join(markdownPath, f));
1530
+ const errors = [];
1531
+ const check = files.map(async (file) => {
1532
+ const res = (0, _canopycanopycanopy_b_ber_validator.default)({
1533
+ text: await fs_extra.default.readFile(file, "utf8"),
1534
+ index: 0
1535
+ });
1536
+ if (res.success === false) {
1537
+ (0, _canopycanopycanopy_b_ber_validator.report)(path.default.basename(file), res);
1538
+ errors.push(res);
1539
+ } else _canopycanopycanopy_b_ber_logger.default.info("Syntax valid %s", path.default.basename(file));
1540
+ });
1541
+ await Promise.all(check);
1542
+ if (!errors.length) _canopycanopycanopy_b_ber_logger.default.info("Directives valid");
1543
+ _canopycanopycanopy_b_ber_logger.default.info(errors);
1544
+ };
1545
+ //#endregion
1546
+ //#region src/web/Template.ts
1547
+ var Template = class {
1548
+ static header(title) {
1549
+ return `
1550
+ <header class="publication__header" role="navigation">
1551
+ <div class="header__item header__item__toggle header__item__toggle--toc">
1552
+ <button class="material-icons">view_list</button>
1553
+ </div>
1554
+
1555
+ <div class="header__item header__item__title">
1556
+ <h1>${title}</h1>
1557
+ </div>
1558
+
1559
+ <div class="header__item publication__search">
1560
+ <button class="material-icons publication__search__button publication__search__button--open">search</button>
1561
+ <input type="text" disabled="disabled" class="publication__search__input" placeholder="" name="s" value="" />
1562
+ <button class="material-icons publication__search__button publication__search__button--close">close</button>
1563
+ </div>
1564
+
1565
+ <div class="header__item header__item__toggle header__item__toggle--info">
1566
+ <button class="material-icons">info</button>
1567
+ </div>
1568
+ </header>
1569
+ `;
1570
+ }
1571
+ static metadata(data) {
1572
+ return `
1573
+ <dl>
1574
+ ${data.reduce((acc, curr) => acc.concat(`
1575
+ <dt>${curr.term}</dt>
1576
+ <dd>${curr.value}</dd>
1577
+ `), "")}
1578
+ </dl>
1579
+ `;
1580
+ }
1581
+ static toc(baseURL, title, content) {
1582
+ return `
1583
+ <nav class="publication__toc" role="navigation">
1584
+ <div class="publication__title">
1585
+ <a href="${baseURL}">${title}</a>
1586
+ </div>
1587
+ ${content}
1588
+ </nav>
1589
+ `;
1590
+ }
1591
+ static info(content) {
1592
+ return `
1593
+ <nav class="publication__info" role="navigation">
1594
+ ${content}
1595
+ </nav>
1596
+ `;
1597
+ }
1598
+ static prev(baseURL, href) {
1599
+ return `
1600
+ <div class="publication__nav__prev">
1601
+ <a class="publication__nav__link" href="${baseURL}text/${href}">
1602
+ <i class="material-icons">arrow_back</i>
1603
+ </a>
1604
+ </div>
1605
+ `;
1606
+ }
1607
+ static next(baseURL, href) {
1608
+ return `
1609
+ <div class="publication__nav__next">
1610
+ <a class="publication__nav__link" href="${baseURL}text/${href}">
1611
+ <i class="material-icons">arrow_forward</i>
1612
+ </a>
1613
+ </div>
1614
+ `;
1615
+ }
1616
+ static pagination(prev, next) {
1617
+ return `
1618
+ <nav class="publication__nav" role="navigation">
1619
+ ${prev}
1620
+ ${next}
1621
+ </nav>
1622
+ `;
1623
+ }
1624
+ static styles() {
1625
+ return `
1626
+ <style>
1627
+ body { opacity: 0; transition: opacity 250ms ease; }
1628
+ body.ready { opacity: 1 !important; }
1629
+ </style>
1630
+ `;
1631
+ }
1632
+ static scripts(content) {
1633
+ return `
1634
+ <script type="text/javascript">
1635
+ // <![CDATA[
1636
+ ${content}
1637
+ // ]]>
1638
+ <\/script>
1639
+ `;
1640
+ }
1641
+ static cover(firstPage, coverImageSrc) {
1642
+ return `
1643
+ <a class="cover__image__link" href="${firstPage}">
1644
+ <img class="cover__image" src="${coverImageSrc}" alt="Cover" />
1645
+ </a>
1646
+ `;
1647
+ }
1648
+ static robots(isPrivate) {
1649
+ return isPrivate ? "<meta name=\"robots\" content=\"noindex,nofollow\"/>" : "<meta name=\"robots\" content=\"index,follow\"/>";
1650
+ }
1651
+ static body(styleBlock, headerElement) {
1652
+ return `
1653
+ <body style="opacity: 0;">
1654
+ ${styleBlock}
1655
+ <div class="publication">
1656
+ ${headerElement}
1657
+ <div class="publication__contents">
1658
+ `;
1659
+ }
1660
+ static footer(pageNavigation, tocElement, infoElement, navigationToggleScript, webWorkerScript, evenHandlerScript) {
1661
+ return `
1662
+ </div> <!-- / .publication__contents -->
1663
+ ${pageNavigation}
1664
+ </div> <!-- / .publication -->
1665
+ ${tocElement}
1666
+ ${infoElement}
1667
+ ${navigationToggleScript}
1668
+ ${webWorkerScript}
1669
+ ${evenHandlerScript}
1670
+ $1
1671
+ `;
1672
+ }
1673
+ static index(baseURL, robotsMeta, title, styleBlock, tocElement, infoElement, headerElement, coverImage, navigationToggleScript, webWorkerScript) {
1674
+ return `
1675
+ <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1676
+ <html xmlns="http://www.w3.org/1999/xhtml"
1677
+ xmlns:epub="http://www.idpf.org/2007/ops"
1678
+ xmlns:ibooks="http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0"
1679
+ epub:prefix="ibooks: http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0">
1680
+ <meta http-equiv="default-style" content="text/html charset=utf-8"/>
1681
+ ${robotsMeta}
1682
+ <link rel="manifest" type="application/webpub+json" href="${baseURL}manifest.json">
1683
+ <link rel="stylesheet" type="text/css" href="${baseURL}stylesheets/application.css"/>
1684
+
1685
+ <head>
1686
+ <title>${title}</title>
1687
+ ${styleBlock}
1688
+ </head>
1689
+ <body style="opacity: 0;">
1690
+ ${tocElement}
1691
+ ${infoElement}
1692
+ <div class="publication">
1693
+ ${headerElement}
1694
+ <div class="publication__contents">
1695
+ <section>
1696
+ ${coverImage}
1697
+ </section>
1698
+ </div>
1699
+ </div>
1700
+ ${navigationToggleScript}
1701
+ ${webWorkerScript}
1702
+ </body>
1703
+ </html>
1704
+ `;
1705
+ }
1706
+ };
1707
+ //#endregion
1708
+ //#region src/web/index.ts
1709
+ let ASSETS_TO_UNLINK;
1710
+ let DIST_PATH;
1711
+ let OPS_PATH;
1712
+ let OMIT_FROM_SEARCH;
1713
+ let BASE_URL;
1714
+ let flow;
1715
+ var WebFlow = class {
1716
+ spine;
1717
+ loi;
1718
+ constructor({ spine, loi }) {
1719
+ this.spine = spine;
1720
+ this.loi = loi;
1721
+ this.prepareLoi();
1722
+ this.addFiguresToSpine();
1723
+ this.removeNonLinearEntriesFromSpine();
1724
+ this.removeTocFromSpine();
1725
+ }
1726
+ prepareLoi() {
1727
+ this.loi = this.loi.map((a) => {
1728
+ const b = { ...a };
1729
+ b.fileName = b.fileName.replace(/\.xhtml$/, "");
1730
+ b.relativePath = b.relativePath.replace(/\.xhtml$/, "");
1731
+ return b;
1732
+ });
1733
+ }
1734
+ getFiguresPageIndex() {
1735
+ return (0, lodash_findIndex_js.default)(this.spine.flattened, { fileName: "figures-titlepage" });
1736
+ }
1737
+ addFiguresToSpine() {
1738
+ if (!this.loi.length) return;
1739
+ const figuresPageIndex = this.getFiguresPageIndex();
1740
+ if (figuresPageIndex < 0) return;
1741
+ this.spine.flattened.splice(figuresPageIndex + 1, 0, ...this.loi);
1742
+ }
1743
+ removeNonLinearEntriesFromSpine() {
1744
+ this.spine = this.spine.flattened.filter((a) => a.linear);
1745
+ }
1746
+ removeTocFromSpine() {
1747
+ this.spine = this.spine.filter((a) => a.fileName !== "toc");
1748
+ }
1749
+ };
1750
+ async function initialize() {
1751
+ DIST_PATH = _canopycanopycanopy_b_ber_lib_State.default.distDir;
1752
+ OPS_PATH = path.default.join(DIST_PATH, "OPS");
1753
+ BASE_URL = _canopycanopycanopy_b_ber_lib.Url.addTrailingSlash(_canopycanopycanopy_b_ber_lib_State.default.config.base_url);
1754
+ ASSETS_TO_UNLINK = [
1755
+ path.default.join(DIST_PATH, "mimetype"),
1756
+ path.default.join(DIST_PATH, "META-INF"),
1757
+ path.default.join(DIST_PATH, "OPS/content.opf"),
1758
+ path.default.join(DIST_PATH, "OPS/toc.ncx")
1759
+ ];
1760
+ OMIT_FROM_SEARCH = ["toc"];
1761
+ const { spine, loi } = _canopycanopycanopy_b_ber_lib_State.default;
1762
+ flow = new WebFlow({
1763
+ spine,
1764
+ loi
1765
+ });
1766
+ }
1767
+ async function moveAssetsToRootDirctory() {
1768
+ const promises = fs_extra.default.readdirSync(OPS_PATH).filter((file) => file.charAt(0) !== "." && fs_extra.default.statSync(path.default.join(OPS_PATH, file)).isDirectory()).map((dir) => {
1769
+ const from = path.default.join(OPS_PATH, dir);
1770
+ const to = path.default.join(DIST_PATH, dir);
1771
+ _canopycanopycanopy_b_ber_logger.default.info("Moving [%s]", dir);
1772
+ return fs_extra.default.move(from, to);
1773
+ });
1774
+ await Promise.all(promises);
1775
+ return fs_extra.default.remove(OPS_PATH);
1776
+ }
1777
+ function unlinkRedundantAssets() {
1778
+ const promises = ASSETS_TO_UNLINK.map((file) => {
1779
+ _canopycanopycanopy_b_ber_logger.default.info("Removing [%s]", path.default.basename(file));
1780
+ return fs_extra.default.remove(file);
1781
+ });
1782
+ return Promise.all(promises);
1783
+ }
1784
+ function getProjectTitle() {
1785
+ let title = "";
1786
+ const titleEntry = (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("title");
1787
+ if (titleEntry) title = titleEntry;
1788
+ return title;
1789
+ }
1790
+ function getChapterTitle(fileName) {
1791
+ if (typeof fileName !== "string") return getProjectTitle();
1792
+ const meta = _canopycanopycanopy_b_ber_lib_State.default.spine.frontMatter.get(fileName);
1793
+ if (!meta?.title) return getProjectTitle();
1794
+ return meta.title;
1795
+ }
1796
+ function getProjectMetadataHTML() {
1797
+ return Template.metadata(_canopycanopycanopy_b_ber_lib_State.default.metadata.json());
1798
+ }
1799
+ function getHeaderElement(fileName) {
1800
+ const title = getChapterTitle(fileName) ?? "";
1801
+ return Template.header(title);
1802
+ }
1803
+ function createNavigationElement() {
1804
+ const { toc: prevToc } = _canopycanopycanopy_b_ber_lib_State.default;
1805
+ const toc = prevToc.filter((item) => item.fileName !== "toc");
1806
+ const tocHTML = _canopycanopycanopy_b_ber_templates_Toc.default.items(toc).replace(/a href="/g, `a href="${BASE_URL}`);
1807
+ const metadataHTML = getProjectMetadataHTML();
1808
+ const title = getProjectTitle();
1809
+ return {
1810
+ tocElement: Template.toc(BASE_URL, title, tocHTML),
1811
+ infoElement: Template.info(metadataHTML)
1812
+ };
1813
+ }
1814
+ function buttonPrev(filePath) {
1815
+ const fileName = path.default.basename(filePath, ".xhtml");
1816
+ const index = (0, lodash_findIndex_js.default)(flow.spine, { fileName });
1817
+ const prevIndex = index - 1;
1818
+ let html = "";
1819
+ if (index > -1 && flow.spine[prevIndex]) {
1820
+ const href = `${flow.spine[prevIndex].fileName}.xhtml`;
1821
+ html = Template.prev(BASE_URL, href);
1822
+ }
1823
+ return html;
1824
+ }
1825
+ function buttonNext(filePath) {
1826
+ const fileName = path.default.basename(filePath, ".xhtml");
1827
+ const index = (0, lodash_findIndex_js.default)(flow.spine, { fileName });
1828
+ const nextIndex = index + 1;
1829
+ let html = "";
1830
+ if (index > -1 && flow.spine[nextIndex]) {
1831
+ const href = `${flow.spine[nextIndex].fileName}.xhtml`;
1832
+ html = Template.next(BASE_URL, href);
1833
+ }
1834
+ return html;
1835
+ }
1836
+ function paginate(filePath) {
1837
+ return {
1838
+ prev: buttonPrev(filePath),
1839
+ next: buttonNext(filePath)
1840
+ };
1841
+ }
1842
+ function paginationNavigation(filePath) {
1843
+ const { prev, next } = paginate(filePath);
1844
+ return Template.pagination(prev, next);
1845
+ }
1846
+ function injectBaseURL(script) {
1847
+ const script_ = typeof script === "string" ? script : String(script);
1848
+ return Buffer.from(script_.replace(/%BASE_URL%/g, BASE_URL));
1849
+ }
1850
+ function getStyleBlock() {
1851
+ return Template.styles();
1852
+ }
1853
+ function getNavigationToggleScript() {
1854
+ const content = injectBaseURL(fs_extra.default.readFileSync(path.default.join(__dirname, "navigation.js")));
1855
+ return Template.scripts(content);
1856
+ }
1857
+ function getWebWorkerScript() {
1858
+ const content = injectBaseURL(fs_extra.default.readFileSync(path.default.join(__dirname, "search.js")));
1859
+ return Template.scripts(content);
1860
+ }
1861
+ function getEventHandlerScript() {
1862
+ const content = injectBaseURL(fs_extra.default.readFileSync(path.default.join(__dirname, "event-handlers.js")));
1863
+ return Template.scripts(content);
1864
+ }
1865
+ function injectPageElementsIntoFile(filePath) {
1866
+ const { tocElement, infoElement } = createNavigationElement();
1867
+ const pageNavigation = paginationNavigation(filePath);
1868
+ const styleBlock = getStyleBlock();
1869
+ const navigationToggleScript = getNavigationToggleScript();
1870
+ const webWorkerScript = getWebWorkerScript();
1871
+ const evenHandlerScript = getEventHandlerScript();
1872
+ const headerElement = getHeaderElement(path.default.basename(filePath, path.default.extname(filePath)));
1873
+ _canopycanopycanopy_b_ber_logger.default.info(`Adding pagination to ${path.default.basename(filePath)}`);
1874
+ const data = fs_extra.default.readFileSync(filePath, "utf8");
1875
+ let contents;
1876
+ contents = data.replace(/(<body[^>]*?>)/, Template.body(styleBlock, headerElement));
1877
+ contents = contents.replace(/(<\/body>)/, Template.footer(pageNavigation, tocElement, infoElement, navigationToggleScript, webWorkerScript, evenHandlerScript));
1878
+ _canopycanopycanopy_b_ber_logger.default.info(`web writing ${path.default.basename(filePath)}`);
1879
+ return fs_extra.default.writeFile(filePath, contents);
1880
+ }
1881
+ function injectPageElementsIntoFiles(elements) {
1882
+ const textPath = path.default.join(DIST_PATH, "text");
1883
+ const promises = fs_extra.default.readdirSync(textPath).filter((file) => path.default.extname(file) === ".xhtml").map((file) => {
1884
+ return injectPageElementsIntoFile(path.default.resolve(textPath, file));
1885
+ });
1886
+ return Promise.all(promises).then(() => elements);
1887
+ }
1888
+ function indexPageContent() {
1889
+ const { spine } = flow;
1890
+ const records = [];
1891
+ let fileIndex = -1;
1892
+ const promises = spine.filter((a) => OMIT_FROM_SEARCH.indexOf(a.fileName) < 0).map((entry) => fs_extra.default.readFile(path.default.join(OPS_PATH, `${entry.relativePath}.xhtml`), "utf8").then((data) => {
1893
+ const $ = cheerio.default.load(data);
1894
+ const title = $("h1,h2,h3,h4,h5,h6").first().text();
1895
+ const body = $("body").text();
1896
+ const url = `${BASE_URL}text/${entry.fileName}.xhtml`;
1897
+ fileIndex += 1;
1898
+ records.push({
1899
+ id: fileIndex,
1900
+ title,
1901
+ body,
1902
+ url
1903
+ });
1904
+ }));
1905
+ return Promise.all(promises).then(() => JSON.stringify(records));
1906
+ }
1907
+ function writeJSONPageData(json) {
1908
+ return fs_extra.default.writeFile(path.default.join(DIST_PATH, "search-index.json"), json);
1909
+ }
1910
+ function importVendorScripts() {
1911
+ const lunrPath = require.resolve("lunr");
1912
+ const outputPath = path.default.join(DIST_PATH, "lunr.js");
1913
+ return fs_extra.default.copy(lunrPath, outputPath);
1914
+ }
1915
+ function writeWebWorker() {
1916
+ const worker = injectBaseURL(fs_extra.default.readFileSync(path.default.join(__dirname, "worker.js")));
1917
+ return fs_extra.default.writeFile(path.default.join(DIST_PATH, "worker.js"), worker);
1918
+ }
1919
+ function writeWebpubManifest() {
1920
+ return new Promise((resolve, reject) => {
1921
+ (0, recursive_readdir.default)(_canopycanopycanopy_b_ber_lib_State.default.distDir, (err1, files) => {
1922
+ if (err1) reject(err1);
1923
+ const manifest = (0, _canopycanopycanopy_b_ber_lib_utils.generateWebpubManifest)(files);
1924
+ fs_extra.default.writeJson(path.default.join(DIST_PATH, "manifest.json"), manifest).then(resolve);
1925
+ });
1926
+ });
1927
+ }
1928
+ function getPage(_n = -1) {
1929
+ const n = _n - 1;
1930
+ return `${BASE_URL}text/${flow.spine[n].fileName}.xhtml`;
1931
+ }
1932
+ function getFirstPage() {
1933
+ return getPage(1);
1934
+ }
1935
+ function getCoverImage() {
1936
+ const coverEntry = (0, lodash_find_js.default)(_canopycanopycanopy_b_ber_lib_State.default.metadata.json(), { term: "cover" });
1937
+ const firstPage = getFirstPage();
1938
+ let coverImageSrc = "images/";
1939
+ if (coverEntry && (0, lodash_has_js.default)(coverEntry, "value")) coverImageSrc += coverEntry.value;
1940
+ return Template.cover(firstPage, coverImageSrc);
1941
+ }
1942
+ function createIndexHTML() {
1943
+ const { tocElement, infoElement } = createNavigationElement();
1944
+ const title = getProjectTitle();
1945
+ const coverImage = getCoverImage();
1946
+ const navigationToggleScript = getNavigationToggleScript();
1947
+ const webWorkerScript = getWebWorkerScript();
1948
+ const headerElement = getHeaderElement();
1949
+ const styleBlock = getStyleBlock();
1950
+ const robotsMeta = Template.robots(_canopycanopycanopy_b_ber_lib_State.default.config.private);
1951
+ const indexHTML = Template.index(BASE_URL, robotsMeta, title, styleBlock, tocElement, infoElement, headerElement, coverImage, navigationToggleScript, webWorkerScript);
1952
+ return fs_extra.default.writeFile(path.default.resolve(DIST_PATH, "index.html"), indexHTML);
1953
+ }
1954
+ const web = () => initialize().then(unlinkRedundantAssets).then(indexPageContent).then(writeJSONPageData).then(moveAssetsToRootDirctory).then(injectPageElementsIntoFiles).then(createIndexHTML).then(importVendorScripts).then(writeWebpubManifest).then(writeWebWorker).catch(_canopycanopycanopy_b_ber_logger.default.error);
1955
+ //#endregion
1956
+ //#region src/xml/index.ts
1957
+ const fileExtension = ".xhtml";
1958
+ const writeXML = (str) => {
1959
+ const cwd = process.cwd();
1960
+ const uuid = (0, _canopycanopycanopy_b_ber_lib_utils.getBookMetadata)("identifier");
1961
+ const filePath = path.default.join(cwd, `${uuid}.xml`);
1962
+ return fs_extra.default.writeFile(filePath, str, "utf8");
1963
+ };
1964
+ const parseHTMLFiles = (files) => new Promise((resolve) => {
1965
+ new _canopycanopycanopy_b_ber_lib_HtmlToXml.default({
1966
+ content: files.reduce((acc, curr) => {
1967
+ const filePath = (0, lodash_isPlainObject_js.default)(curr) ? Object.keys(curr)[0] : (0, lodash_isString_js.default)(curr) ? curr : null;
1968
+ if (!filePath) return acc;
1969
+ const data = fs_extra.default.readFileSync(filePath, "utf8");
1970
+ return acc.concat(`${data}`);
1971
+ }, []).join("<pagebreak></pagebreak>"),
1972
+ onEndCallback: resolve
1973
+ }).parse();
145
1974
  });
146
- _Object$defineProperty(exports, "web", {
147
- enumerable: true,
148
- get: function () {
149
- return _web.default;
150
- }
1975
+ const xml = () => {
1976
+ const spineFiles = [..._canopycanopycanopy_b_ber_lib_State.default.spine.flattened];
1977
+ const figuresTitlePageIndex = (0, lodash_findIndex_js.default)(spineFiles, { fileName: "figures-titlepage" });
1978
+ const files = spineFiles.map((entry) => `${entry.absolutePath}${fileExtension}`);
1979
+ if (figuresTitlePageIndex > -1 && _canopycanopycanopy_b_ber_lib_State.default.loi.length) {
1980
+ const loi = _canopycanopycanopy_b_ber_lib_State.default.loi.map((entry) => entry.absolutePath);
1981
+ files.splice(figuresTitlePageIndex + 1, 0, ...loi);
1982
+ }
1983
+ return parseHTMLFiles(files).then(writeXML).catch(_canopycanopycanopy_b_ber_logger.default.error);
1984
+ };
1985
+ //#endregion
1986
+ //#region src/task-handlers.ts
1987
+ var task_handlers_exports = /* @__PURE__ */ __exportAll({
1988
+ clean: () => clean_default,
1989
+ container: () => container_default,
1990
+ copy: () => copy,
1991
+ cover: () => cover_default,
1992
+ deploy: () => main,
1993
+ epub: () => epub,
1994
+ footnotes: () => footnotes_default,
1995
+ generate: () => generate,
1996
+ init: () => Initializer,
1997
+ inject: () => inject,
1998
+ loi: () => loi,
1999
+ mobi: () => mobi,
2000
+ mobiCSS: () => mobiCSS,
2001
+ opf: () => opf,
2002
+ pdf: () => pdf,
2003
+ reader: () => main$1,
2004
+ render: () => render,
2005
+ sample: () => sample,
2006
+ sass: () => sass$1,
2007
+ scripts: () => scripts,
2008
+ validate: () => validate,
2009
+ web: () => web,
2010
+ xml: () => xml
151
2011
  });
152
- _Object$defineProperty(exports, "xml", {
153
- enumerable: true,
154
- get: function () {
155
- return _xml.default;
156
- }
2012
+ //#endregion
2013
+ //#region src/serialize.ts
2014
+ function validate$1(fn) {
2015
+ if (typeof fn !== "function") throw new Error(`async#serialize: Invalid parameter [${fn}] is [${typeof fn}], expected [function]`);
2016
+ }
2017
+ const done = (resp) => {
2018
+ _canopycanopycanopy_b_ber_logger.default.notify("done", { state: _canopycanopycanopy_b_ber_lib_State.default });
2019
+ return resp;
2020
+ };
2021
+ const taskReducer = (acc, curr) => {
2022
+ const fn = (typeof curr === "string" ? task_handlers_exports[curr] : curr) ?? curr;
2023
+ validate$1(fn);
2024
+ return acc.then((resp) => {
2025
+ _canopycanopycanopy_b_ber_logger.default.notify("start", curr);
2026
+ return fn(resp).then((resp2) => {
2027
+ _canopycanopycanopy_b_ber_logger.default.notify("stop", curr);
2028
+ return resp2;
2029
+ });
2030
+ });
2031
+ };
2032
+ const serialize = (sequence) => sequence.reduce(taskReducer, Promise.resolve(void 0)).then(done).catch(_canopycanopycanopy_b_ber_logger.default.error);
2033
+ //#endregion
2034
+ //#region src/serve/index.ts
2035
+ const browserSync = (0, browser_sync.create)();
2036
+ const port = 4e3;
2037
+ const debounceSpeed = 500;
2038
+ const config = (build) => (url) => () => {
2039
+ _canopycanopycanopy_b_ber_lib_State.default.update("build", build);
2040
+ _canopycanopycanopy_b_ber_lib_State.default.update("footnotes", []);
2041
+ _canopycanopycanopy_b_ber_lib_State.default.update("config.base_url", "/");
2042
+ _canopycanopycanopy_b_ber_lib_State.default.update("config.base_path", "/");
2043
+ _canopycanopycanopy_b_ber_lib_State.default.update("config.remote_url", url);
2044
+ _canopycanopycanopy_b_ber_lib_State.default.update("config.reader_url", url);
2045
+ return serialize(_canopycanopycanopy_b_ber_shapes_sequences_sequences.default[build]);
2046
+ };
2047
+ let update = async () => {};
2048
+ const reload = () => update().then(() => browserSync.reload());
2049
+ const browserSyncPlugins = [{
2050
+ module: "bs-html-injector",
2051
+ options: { files: [{
2052
+ match: [
2053
+ path.default.resolve("_project", "**", "*.scss"),
2054
+ path.default.resolve("_project", "**", "*.js"),
2055
+ path.default.resolve("_project", "**", "*.md")
2056
+ ],
2057
+ fn: (0, lodash_debounce_js.default)(() => reload(), debounceSpeed, {
2058
+ leading: false,
2059
+ trailing: true
2060
+ })
2061
+ }] }
2062
+ }];
2063
+ const browserSyncMiddleware = (req, res, next) => {
2064
+ if (/\.xhtml$/.test(req.url)) res.setHeader("Content-Type", "text/html; charset=UTF-8");
2065
+ next();
2066
+ };
2067
+ const init = (build) => new Promise((resolve) => {
2068
+ const options = {
2069
+ port,
2070
+ open: false,
2071
+ server: {
2072
+ baseDir: path.default.resolve(`project-${build}`),
2073
+ middleware: browserSyncMiddleware
2074
+ },
2075
+ plugins: browserSyncPlugins
2076
+ };
2077
+ browserSync.init(options, () => resolve());
157
2078
  });
158
- var _clean = _interopRequireDefault(require("./clean"));
159
- var _container = _interopRequireDefault(require("./container"));
160
- var _copy = _interopRequireDefault(require("./copy"));
161
- var _cover = _interopRequireDefault(require("./cover"));
162
- var _deploy = _interopRequireDefault(require("./deploy"));
163
- var _epub = _interopRequireDefault(require("./epub"));
164
- var _footnotes = _interopRequireDefault(require("./footnotes"));
165
- var _generate = _interopRequireDefault(require("./generate"));
166
- var _init = _interopRequireDefault(require("./init"));
167
- var _inject = _interopRequireDefault(require("./inject"));
168
- var _loi = _interopRequireDefault(require("./loi"));
169
- var _mobi = _interopRequireDefault(require("./mobi"));
170
- var _mobiCss = _interopRequireDefault(require("./mobi/mobi-css"));
171
- var _opf = _interopRequireDefault(require("./opf"));
172
- var _pdf = _interopRequireDefault(require("./pdf"));
173
- var _render = _interopRequireDefault(require("./render"));
174
- var _sample = _interopRequireDefault(require("./sample"));
175
- var _sass = _interopRequireDefault(require("./sass"));
176
- var _scripts = _interopRequireDefault(require("./scripts"));
177
- var _serve = _interopRequireDefault(require("./serve"));
178
- var _web = _interopRequireDefault(require("./web"));
179
- var _xml = _interopRequireDefault(require("./xml"));
180
- var _serialize = _interopRequireDefault(require("./serialize"));
181
- var _reader = _interopRequireDefault(require("./reader"));
182
- var _validate = _interopRequireDefault(require("./validate"));
2079
+ const serve = async ({ build: buildOption, external }) => {
2080
+ const location = external ? "external" : "local";
2081
+ const build = buildOption || "reader";
2082
+ await init(build);
2083
+ const url = browserSync.getOption("urls").get(location);
2084
+ update = config(build)(url);
2085
+ await update();
2086
+ const bs = browserSync;
2087
+ bs.instance.setOption("open", location);
2088
+ bs.instance.utils.openBrowser(url, bs.instance.options, bs.instance);
2089
+ };
2090
+ //#endregion
2091
+ exports.clean = clean_default;
2092
+ exports.container = container_default;
2093
+ exports.copy = copy;
2094
+ exports.cover = cover_default;
2095
+ exports.deploy = main;
2096
+ exports.epub = epub;
2097
+ exports.footnotes = footnotes_default;
2098
+ exports.generate = generate;
2099
+ exports.init = Initializer;
2100
+ exports.inject = inject;
2101
+ exports.loi = loi;
2102
+ exports.mobi = mobi;
2103
+ exports.mobiCSS = mobiCSS;
2104
+ exports.opf = opf;
2105
+ exports.pdf = pdf;
2106
+ exports.reader = main$1;
2107
+ exports.render = render;
2108
+ exports.sample = sample;
2109
+ exports.sass = sass$1;
2110
+ exports.scripts = scripts;
2111
+ exports.serialize = serialize;
2112
+ exports.serve = serve;
2113
+ exports.validate = validate;
2114
+ exports.web = web;
2115
+ exports.xml = xml;