@dogsbay/format-html 0.2.0-beta.181 → 0.2.0-beta.182

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.
@@ -24,7 +24,8 @@ export interface ImportBookOptions {
24
24
  fetch: (url: string, key: string, signal?: AbortSignal) => Promise<string | null>;
25
25
  /**
26
26
  * An image's bytes, or null when it cannot be had (or is not an image). When given, the pages'
27
- * images on the site's own host are saved in the book (`content/assets/`, in `binaries`) and
27
+ * images on the site's own host are saved in the book (`content/assets/`, in `binaries` or handed
28
+ * to `onBinary`) and
28
29
  * the pages point at them; an image that cannot be had, or of a kind not known (neither its
29
30
  * bytes nor its URL say png, jpg, gif, webp, avif, svg or ico), keeps its URL. Without it,
30
31
  * every image keeps its URL on the site.
@@ -53,6 +54,13 @@ export interface ImportBookOptions {
53
54
  total: number;
54
55
  ok: boolean;
55
56
  }) => void;
57
+ /**
58
+ * Where a saved image goes, instead of `binaries`: called once per image, as soon as it is
59
+ * fetched and named (`path` is the project path, `content/assets/…`), and awaited before the
60
+ * next fetch, so a host can store each image as it comes and hold none of them (a book's images
61
+ * can be hundreds of MB). An error it throws ends the import. `binaries` stays empty.
62
+ */
63
+ onBinary?: (path: string, bytes: Uint8Array, signal?: AbortSignal) => void | Promise<void>;
56
64
  /** Progress: called once per image, after its fetch (`fetchBytes`). */
57
65
  onImage?: (image: {
58
66
  url: string;
@@ -86,8 +94,10 @@ export interface ImportBookResult {
86
94
  section?: string;
87
95
  /** Project files by path: content/*.md, content/nav.yml, dogsbay.config.yml, and data/*.json (records integration blocks held). */
88
96
  files: Record<string, string>;
89
- /** The images saved in the book, by path (content/assets/…): with `fetchBytes`. */
97
+ /** The images saved in the book, by path (content/assets/…): with `fetchBytes`, and empty with `onBinary`. */
90
98
  binaries: Record<string, Uint8Array>;
99
+ /** The paths of the images saved in the book (content/assets/…), in the order fetched: with or without `onBinary`. */
100
+ imagesSaved: string[];
91
101
  /** Images on the site's host that could not be had: their URLs, kept in the pages. */
92
102
  imagesMissing: string[];
93
103
  pages: PageReport[];
package/dist/site/book.js CHANGED
@@ -345,6 +345,7 @@ export async function importBook(opts) {
345
345
  }
346
346
  // 3. Images on the site's own host, saved in the book (one fetch per image, however many pages show it)
347
347
  const binaries = {};
348
+ const imagesSaved = [];
348
349
  const imagesMissing = [];
349
350
  if (opts.fetchBytes) {
350
351
  const origin = new URL(adapter.urlOf(planned.key)).origin;
@@ -378,7 +379,14 @@ export async function importBook(opts) {
378
379
  const kind = bytes && (sniff(bytes) ?? knownExtension(url));
379
380
  if (bytes && kind) {
380
381
  const path = assetName(url, names, kind);
381
- binaries[`content/${path}`] = bytes;
382
+ if (opts.onBinary) {
383
+ await opts.onBinary(`content/${path}`, bytes, opts.signal);
384
+ if (opts.signal?.aborted)
385
+ throw new Error("cancelled");
386
+ }
387
+ else
388
+ binaries[`content/${path}`] = bytes;
389
+ imagesSaved.push(`content/${path}`);
382
390
  wanted.set(url, path);
383
391
  }
384
392
  else if (!bytes)
@@ -490,6 +498,7 @@ export async function importBook(opts) {
490
498
  section,
491
499
  files: out,
492
500
  binaries,
501
+ imagesSaved,
493
502
  imagesMissing,
494
503
  pages,
495
504
  missing,
@@ -593,7 +602,9 @@ function assetName(url, taken, kind) {
593
602
  const last = decode(new URL(url).pathname).split("/").pop() || "image";
594
603
  const clean = last.replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/^\.+/, "") || "image";
595
604
  const dot = clean.lastIndexOf(".");
596
- const [stem, given] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""];
605
+ const [whole, given] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""];
606
+ // A file name a host can store (the import extension takes paths up to 512 characters)
607
+ const stem = whole.slice(0, 100);
597
608
  const same = kind === ".jpg" ? /^\.jpe?g$/i.test(given) : given.toLowerCase() === kind;
598
609
  const ext = same ? given : kind;
599
610
  let name = stem + ext;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @dogsbay/format-html/site/bytes: an image response's bytes, read with a ceiling. No cheerio,
3
+ * no fetching: the import extension's content script (kept small) and the CLI pass their
4
+ * fetch's Response.
5
+ */
6
+ /**
7
+ * The body of `res` if it is an OK image response (`image/*`, not SVG unless `svg`) of at most
8
+ * `max` bytes, else null. A `content-length` past `max` is refused before reading, and the body
9
+ * is read in chunks and dropped once it passes `max`, so a response without a length (or with a
10
+ * false one) cannot grow past it.
11
+ */
12
+ export declare function imageBytes(res: Response, max: number, opts?: {
13
+ svg?: boolean;
14
+ }): Promise<Uint8Array | null>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @dogsbay/format-html/site/bytes: an image response's bytes, read with a ceiling. No cheerio,
3
+ * no fetching: the import extension's content script (kept small) and the CLI pass their
4
+ * fetch's Response.
5
+ */
6
+ /**
7
+ * The body of `res` if it is an OK image response (`image/*`, not SVG unless `svg`) of at most
8
+ * `max` bytes, else null. A `content-length` past `max` is refused before reading, and the body
9
+ * is read in chunks and dropped once it passes `max`, so a response without a length (or with a
10
+ * false one) cannot grow past it.
11
+ */
12
+ export async function imageBytes(res, max, opts = {}) {
13
+ const type = res.headers.get("content-type") ?? "";
14
+ if (!res.ok || !/^image\//i.test(type) || (!opts.svg && /svg/i.test(type)))
15
+ return drop(res);
16
+ if (Number(res.headers.get("content-length") ?? 0) > max)
17
+ return drop(res);
18
+ if (!res.body)
19
+ return null;
20
+ const reader = res.body.getReader();
21
+ const parts = [];
22
+ let size = 0;
23
+ for (;;) {
24
+ const { done, value } = await reader.read();
25
+ if (done)
26
+ break;
27
+ size += value.length;
28
+ if (size > max) {
29
+ await reader.cancel().catch(() => { });
30
+ return null;
31
+ }
32
+ parts.push(value);
33
+ }
34
+ if (!size)
35
+ return null;
36
+ const out = new Uint8Array(size);
37
+ let at = 0;
38
+ for (const p of parts) {
39
+ out.set(p, at);
40
+ at += p.length;
41
+ }
42
+ return out;
43
+ }
44
+ async function drop(res) {
45
+ await res.body?.cancel().catch(() => { });
46
+ return null;
47
+ }
@@ -127,7 +127,9 @@ export function gitbookSite(origin, data) {
127
127
  // The space's address: its first page's (the one with an empty pathname); the published URL
128
128
  // can name another host (gitbook.io for a custom domain)
129
129
  const isRoot = (p) => Array.isArray(p.pathnames) && p.pathnames.includes("");
130
- const rootPage = data.pages.find((p) => p.type === "document" && isRoot(p));
130
+ // (at the top, or in a group when the space's top level is all groups: docs.prismacloud.io)
131
+ const rootPage = data.pages.find((p) => p.type === "document" && isRoot(p))
132
+ ?? data.pages.flatMap((p) => (p.type === "group" && Array.isArray(p.descendants) ? p.descendants : [])).find((p) => isGbPage(p) && p.type === "document" && isRoot(p));
131
133
  const base = rootPage ? hrefKey(origin, rootPage.href) ?? "" : "";
132
134
  // The tree as contents: the space's first page is the book, everything else under it
133
135
  const entryOf = (p, depth) => {
@@ -142,17 +144,39 @@ export function gitbookSite(origin, data) {
142
144
  if (!key)
143
145
  return null;
144
146
  // The `.md` of a space's first page is named by its slug (`<space>/<slug>.md`; `<space>.md` is a
145
- // soft 404); any other page's is its address + `.md`
146
- const slug = isRoot(p) ? p.pathnames.find((n) => typeof n === "string" && /^[^/?#\\]+$/.test(n)) : undefined;
147
- const md = slug ? `${key === "/" ? "" : key}/${encodeURIComponent(slug)}.md` : `${key}.md`;
147
+ // soft 404); any other page's is its address + `.md`. A slug may be a path (`get-started/readme`
148
+ // when the first page sits in a group): plain segments, each encoded, never `.` or `..`
149
+ const slug = isRoot(p) ? p.pathnames.find((n) => typeof n === "string" && n.length <= 512 && n.split("/").every((s) => /^[^/?#\\]+$/.test(s) && s !== "." && s !== "..")) : undefined;
150
+ const md = slug ? `${key === "/" ? "" : key}/${slug.split("/").map(encodeURIComponent).join("/")}.md` : `${key}.md`;
148
151
  const aliases = [`/pages/${encodeURIComponent(p.id)}`, ...(pathKey(md) !== key ? [pathKey(md)] : [])];
149
152
  return { title: p.title, key, aliases, fetchUrl: origin + md, children };
150
153
  };
151
154
  const top = data.pages.map((p) => entryOf(p, 0)).filter((e) => !!e);
152
- const first = top.find((e) => e.key) ?? null;
153
- const contents = first
154
- ? [{ ...first, title: data.title || first.title, children: [...first.children, ...top.filter((e) => e !== first)] }]
155
- : [];
155
+ let contents = [];
156
+ if (rootPage && !data.pages.includes(rootPage)) {
157
+ // The space's first page inside a group (docs.prismacloud.io, whose top level is all groups):
158
+ // it is the book, lifted out of its group (found by its id, not its address), everything else
159
+ // under it (a group left empty is left out)
160
+ const rootAlias = `/pages/${encodeURIComponent(rootPage.id)}`;
161
+ let book = null;
162
+ const lift = (es) => es.flatMap((e) => {
163
+ if (!book && e.aliases?.includes(rootAlias)) {
164
+ book = e;
165
+ return e.children;
166
+ }
167
+ const children = lift(e.children);
168
+ return e.key === null && !children.length ? [] : [{ ...e, children }];
169
+ });
170
+ const rest = lift(top);
171
+ const found = book;
172
+ if (found)
173
+ contents = [{ ...found, title: data.title || found.title, children: rest }];
174
+ }
175
+ if (!contents.length) {
176
+ const first = top.find((e) => e.key) ?? null;
177
+ if (first)
178
+ contents = [{ ...first, title: data.title || first.title, children: [...first.children, ...top.filter((e) => e !== first)] }];
179
+ }
156
180
  const site = {
157
181
  name: "gitbook",
158
182
  profile: "generic",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/format-html",
3
- "version": "0.2.0-beta.181",
3
+ "version": "0.2.0-beta.182",
4
4
  "description": "HTML importer for Dogsbay: semantic HTML to TreeNode[], generator profiles (DITA-OT HTML5 first), site adapters (docs.redhat.com first) and a per-page fidelity report. Never fetches; runs in Node, browsers and Workers.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -17,6 +17,10 @@
17
17
  "./site/sniff": {
18
18
  "types": "./dist/site/sniff.d.ts",
19
19
  "import": "./dist/site/sniff.js"
20
+ },
21
+ "./site/bytes": {
22
+ "types": "./dist/site/bytes.d.ts",
23
+ "import": "./dist/site/bytes.js"
20
24
  }
21
25
  },
22
26
  "files": [
@@ -30,9 +34,9 @@
30
34
  },
31
35
  "dependencies": {
32
36
  "cheerio": "^1.2.0",
33
- "@dogsbay/format-dogsbay-md": "0.2.0-beta.181",
34
- "@dogsbay/types": "0.2.0-beta.181",
35
- "@dogsbay/format-gitbook": "0.2.0-beta.181"
37
+ "@dogsbay/types": "0.2.0-beta.182",
38
+ "@dogsbay/format-dogsbay-md": "0.2.0-beta.182",
39
+ "@dogsbay/format-gitbook": "0.2.0-beta.182"
36
40
  },
37
41
  "license": "MIT",
38
42
  "repository": {