@serene-pub/docs 0.0.0-stage → 0.6.0-pr-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Syntax highlighting: ONE shiki highlighter per compile, carrying only the
3
+ * grammars the caller asked for.
4
+ *
5
+ * Both themes are baked into the same markup as `--shiki-light` /
6
+ * `--shiki-dark` CSS variables rather than two rendered copies, because the
7
+ * consumer already owns the light/dark decision (`[data-mode="dark"]`) and a
8
+ * docs page that re-derives it would disagree with the shell the first time
9
+ * someone toggles.
10
+ */
11
+ import { createHighlighter } from 'shiki';
12
+ export async function createDocsHighlighter(languages) {
13
+ let highlighter;
14
+ try {
15
+ highlighter = await createHighlighter({
16
+ themes: ['github-light', 'github-dark'],
17
+ langs: languages,
18
+ });
19
+ }
20
+ catch (cause) {
21
+ throw new Error(`Could not load the shiki grammars ${languages.map((l) => `\`${l}\``).join(', ')}: ` +
22
+ `${cause.message}`, { cause });
23
+ }
24
+ const loaded = new Set(highlighter.getLoadedLanguages());
25
+ return {
26
+ render(code, lang) {
27
+ if (!loaded.has(lang))
28
+ return null;
29
+ return highlighter.codeToHtml(code, {
30
+ lang,
31
+ themes: { light: 'github-light', dark: 'github-dark' },
32
+ defaultColor: false,
33
+ });
34
+ },
35
+ dispose() {
36
+ highlighter.dispose();
37
+ },
38
+ };
39
+ }
40
+ //# sourceMappingURL=highlight.js.map
@@ -0,0 +1,22 @@
1
+ export interface ConvertedAsset {
2
+ /** File name to write into the assets directory. */
3
+ file: string;
4
+ bytes: Buffer;
5
+ width?: number;
6
+ height?: number;
7
+ }
8
+ export interface ImageConvertOptions {
9
+ maxWidth: number;
10
+ quality: number;
11
+ }
12
+ /**
13
+ * One conversion cache per compile. Keyed by path plus mtime and size, so the
14
+ * same screenshot referenced from six pages is decoded once, and a file that
15
+ * changed mid-run is not served from a stale entry.
16
+ */
17
+ export declare class AssetConverter {
18
+ #private;
19
+ constructor(options: ImageConvertOptions);
20
+ convert(absPath: string): Promise<ConvertedAsset>;
21
+ }
22
+ //# sourceMappingURL=images.d.ts.map
package/dist/images.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Image conversion, held to the same rule the app's media stack is held to:
3
+ * zero native dependencies. Decode and resize are pure JS (jimp), the webp
4
+ * encoder and decoder are WASM (`@jsquash/webp`) — the pairing the app already
5
+ * proves on every platform it ships to (`src/lib/server/media/convert/codecs.ts`).
6
+ *
7
+ * `@jsquash`'s emscripten glue fetches its `.wasm`, which Node's undici refuses
8
+ * for `file://` URLs, so the module is compiled from disk and handed to
9
+ * `init()` explicitly — once per process, because a second copy would compile
10
+ * the same wasm again.
11
+ *
12
+ * Output names are the sha256 of the OUTPUT bytes, so the same picture at the
13
+ * same settings is the same file no matter which page referenced it first, and
14
+ * a rebuild that changes nothing rewrites nothing new.
15
+ */
16
+ import { createHash } from 'node:crypto';
17
+ import { readFile, stat } from 'node:fs/promises';
18
+ import { createRequire } from 'node:module';
19
+ import { extname } from 'node:path';
20
+ import { Jimp } from 'jimp';
21
+ const require = createRequire(import.meta.url);
22
+ let encoderReady = null;
23
+ let decoderReady = null;
24
+ /**
25
+ * The SIMD build is a large win on a docs run with real screenshots in it, and
26
+ * detecting it costs one `WebAssembly.validate` of the canonical probe module
27
+ * — which is cheaper than taking a dependency on `wasm-feature-detect` for the
28
+ * same twenty bytes.
29
+ */
30
+ const SIMD_PROBE = new Uint8Array([
31
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253,
32
+ 15, 253, 98, 11,
33
+ ]);
34
+ async function webpEncoder() {
35
+ if (!encoderReady) {
36
+ encoderReady = (async () => {
37
+ const enc = await import('@jsquash/webp/encode.js');
38
+ // init() picks the SIMD build when the runtime has it, so the
39
+ // module handed over has to be the matching one.
40
+ const file = WebAssembly.validate(SIMD_PROBE) ? 'webp_enc_simd.wasm' : 'webp_enc.wasm';
41
+ const wasmPath = require.resolve(`@jsquash/webp/codec/enc/${file}`);
42
+ await enc.init(await WebAssembly.compile(await readFile(wasmPath)));
43
+ return enc;
44
+ })();
45
+ }
46
+ return encoderReady;
47
+ }
48
+ async function webpDecoder() {
49
+ if (!decoderReady) {
50
+ decoderReady = (async () => {
51
+ const dec = await import('@jsquash/webp/decode.js');
52
+ const wasmPath = require.resolve('@jsquash/webp/codec/dec/webp_dec.wasm');
53
+ await dec.init(await WebAssembly.compile(await readFile(wasmPath)));
54
+ return dec;
55
+ })();
56
+ }
57
+ return decoderReady;
58
+ }
59
+ const hash16 = (bytes) => createHash('sha256').update(bytes).digest('hex').slice(0, 16);
60
+ /** `width="800"`, else the viewBox's third and fourth numbers. */
61
+ function svgDimensions(svg) {
62
+ const attr = (name) => {
63
+ const found = new RegExp(`\\b${name}\\s*=\\s*"([0-9.]+)(px)?"`, 'i').exec(svg);
64
+ return found ? Math.round(Number(found[1])) : undefined;
65
+ };
66
+ const width = attr('width');
67
+ const height = attr('height');
68
+ if (width && height)
69
+ return { width, height };
70
+ const box = /\bviewBox\s*=\s*"\s*[-0-9.]+\s+[-0-9.]+\s+([0-9.]+)\s+([0-9.]+)\s*"/i.exec(svg);
71
+ if (box)
72
+ return { width: Math.round(Number(box[1])), height: Math.round(Number(box[2])) };
73
+ return {};
74
+ }
75
+ /**
76
+ * One conversion cache per compile. Keyed by path plus mtime and size, so the
77
+ * same screenshot referenced from six pages is decoded once, and a file that
78
+ * changed mid-run is not served from a stale entry.
79
+ */
80
+ export class AssetConverter {
81
+ #cache = new Map();
82
+ #options;
83
+ constructor(options) {
84
+ this.#options = options;
85
+ }
86
+ async convert(absPath) {
87
+ const info = await stat(absPath);
88
+ const key = `${absPath}:${info.mtimeMs}:${info.size}`;
89
+ let pending = this.#cache.get(key);
90
+ if (!pending) {
91
+ pending = this.#convert(absPath);
92
+ this.#cache.set(key, pending);
93
+ }
94
+ return pending;
95
+ }
96
+ async #convert(absPath) {
97
+ const bytes = await readFile(absPath);
98
+ if (extname(absPath).toLowerCase() === '.svg') {
99
+ const text = bytes.toString('utf8');
100
+ return { file: `${hash16(bytes)}.svg`, bytes, ...svgDimensions(text) };
101
+ }
102
+ let image = await this.#decode(bytes, absPath);
103
+ if (image.bitmap.width > this.#options.maxWidth) {
104
+ image = image.resize({ w: this.#options.maxWidth });
105
+ }
106
+ const enc = await webpEncoder();
107
+ // The encoder's ImageData type pins the buffer to a plain ArrayBuffer;
108
+ // jimp hands back a view over a Node Buffer's pool, so copy rather than
109
+ // cast — the copy is what makes the type true.
110
+ const encoded = await enc.default({
111
+ data: Uint8ClampedArray.from(image.bitmap.data),
112
+ width: image.bitmap.width,
113
+ height: image.bitmap.height,
114
+ colorSpace: 'srgb',
115
+ }, { quality: this.#options.quality });
116
+ const out = Buffer.from(encoded);
117
+ return {
118
+ file: `${hash16(out)}.webp`,
119
+ bytes: out,
120
+ width: image.bitmap.width,
121
+ height: image.bitmap.height,
122
+ };
123
+ }
124
+ /** webp goes through jsquash; png, jpeg and gif (first frame) through jimp. */
125
+ async #decode(bytes, absPath) {
126
+ if (extname(absPath).toLowerCase() !== '.webp')
127
+ return Jimp.fromBuffer(bytes);
128
+ const dec = await webpDecoder();
129
+ const raw = await dec.default(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
130
+ return Jimp.fromBitmap({
131
+ data: Buffer.from(raw.data.buffer, raw.data.byteOffset, raw.data.byteLength),
132
+ width: raw.width,
133
+ height: raw.height,
134
+ });
135
+ }
136
+ }
137
+ //# sourceMappingURL=images.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `@serene-pub/docs` — the docs compiler.
3
+ *
4
+ * One reading order over documentation that comes from more than one place:
5
+ * the markdown a human wrote in the app repo, and the pages
6
+ * `@serene-pub/cli`'s `renderAnnouncementDocs()` renders out of a package's
7
+ * announcement. The compiler emits an article body per page, a manifest that
8
+ * is the nav, and a flat search index — and refuses to emit any of it while a
9
+ * link, an anchor or an image is broken.
10
+ *
11
+ * The heavy end of this package (marked, shiki, jimp, a wasm webp encoder) is
12
+ * build-time only. A consumer serves the output; it never imports this.
13
+ */
14
+ export { compileDocs } from './compile.js';
15
+ export { renderDocsGraph } from './graph.js';
16
+ export { specGraphOf } from './specGraph.js';
17
+ export { createDocsHighlighter, type DocsHighlighter } from './highlight.js';
18
+ export { AssetConverter, type ConvertedAsset, type ImageConvertOptions } from './images.js';
19
+ export { navOrder, type SourcePage } from './manifest.js';
20
+ export { loadMarkdownDir, type LoadMarkdownDirOptions } from './sources.js';
21
+ export { docTitle, escapeHtml, renderMarkdown, resolveDocLink, rewriteDocHref, slugifyHeading, stripInlineMarkdown, type AdmonitionKind, type DocHeading, type DocHrefContext, type DocImageAsset, type DocLinkRef, type RenderedMarkdown, type RenderMarkdownOptions, type ResolvedDocLink, } from './dialect.js';
22
+ export { DEFAULT_ASSET_BUDGET_BYTES, DEFAULT_DOC_LANGUAGES, DEFAULT_LINK_BASE, DEFAULT_MAX_WIDTH, DEFAULT_QUALITY, type CompileDocsOptions, type CompileDocsReport, type DocsManifest, type DocsOrderGroup, type DocsGraph, type DocsGraphEdge, type DocsGraphNode, type DocsPageMeta, type DocsSearchEntry, type DocsSource, } from './types.js';
23
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `@serene-pub/docs` — the docs compiler.
3
+ *
4
+ * One reading order over documentation that comes from more than one place:
5
+ * the markdown a human wrote in the app repo, and the pages
6
+ * `@serene-pub/cli`'s `renderAnnouncementDocs()` renders out of a package's
7
+ * announcement. The compiler emits an article body per page, a manifest that
8
+ * is the nav, and a flat search index — and refuses to emit any of it while a
9
+ * link, an anchor or an image is broken.
10
+ *
11
+ * The heavy end of this package (marked, shiki, jimp, a wasm webp encoder) is
12
+ * build-time only. A consumer serves the output; it never imports this.
13
+ */
14
+ export { compileDocs } from './compile.js';
15
+ export { renderDocsGraph } from './graph.js';
16
+ export { specGraphOf } from './specGraph.js';
17
+ export { createDocsHighlighter } from './highlight.js';
18
+ export { AssetConverter } from './images.js';
19
+ export { navOrder } from './manifest.js';
20
+ export { loadMarkdownDir } from './sources.js';
21
+ export { docTitle, escapeHtml, renderMarkdown, resolveDocLink, rewriteDocHref, slugifyHeading, stripInlineMarkdown, } from './dialect.js';
22
+ export { DEFAULT_ASSET_BUDGET_BYTES, DEFAULT_DOC_LANGUAGES, DEFAULT_LINK_BASE, DEFAULT_MAX_WIDTH, DEFAULT_QUALITY, } from './types.js';
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Reading order.
3
+ *
4
+ * A docs site's nav is an editorial decision, not an alphabetical accident —
5
+ * which is why `order` is explicit and why a page missing from it is a WARNING
6
+ * rather than a silent tail entry. The app learned this the expensive way:
7
+ * `indexOf` returns -1 for an unlisted doc, so "android" and "troubleshooting"
8
+ * sorted *ahead* of "getting-started" and that is what a new reader saw first.
9
+ */
10
+ import type { DocsSource } from './types.js';
11
+ export interface SourcePage {
12
+ source: DocsSource;
13
+ /** Path inside the source, posix, e.g. 'pipelines/core_spec_respond.md'. */
14
+ path: string;
15
+ /** Slug without the source's prefix — what `order` is written in. */
16
+ bareSlug: string;
17
+ /** Full slug, prefix included. */
18
+ slug: string;
19
+ markdown: string;
20
+ /** Absolute path on disk for a `dir` source; images resolve against its folder. */
21
+ file?: string;
22
+ }
23
+ /** One settled nav group: a heading and its pages, in reading order. */
24
+ export interface SettledGroup {
25
+ group: string;
26
+ pages: SourcePage[];
27
+ }
28
+ /**
29
+ * Settle a source's reading order: its pages in order, and the nav groups
30
+ * they fall into.
31
+ *
32
+ * A flat `order` (or none) gives one group headed `source.group`. A grouped
33
+ * `order` gives one group per declared group, in declaration order; a group
34
+ * none of whose pages exist is left out of the nav (each missing slug still
35
+ * warns). Unlisted pages are appended alphabetically, with a warning, to the
36
+ * group headed `source.group` — a declared one of that name, or a new
37
+ * trailing one — so they land at the end and say so.
38
+ */
39
+ export declare function navOrder(source: DocsSource, pages: SourcePage[]): {
40
+ ordered: SourcePage[];
41
+ groups: SettledGroup[];
42
+ warnings: string[];
43
+ };
44
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1,72 @@
1
+ const byBareSlug = (a, b) => (a.bareSlug < b.bareSlug ? -1 : 1);
2
+ /** A flat `order` is one group headed by the source's own `group`. */
3
+ function orderGroups(source) {
4
+ const order = source.order ?? [];
5
+ if (order.every((entry) => typeof entry === 'string'))
6
+ return [{ group: source.group, pages: order }];
7
+ if (order.some((entry) => typeof entry === 'string'))
8
+ throw new Error(`\`order\` for source \`${source.id}\` mixes slugs and groups — ` +
9
+ `it is either a list of slugs or a list of groups.`);
10
+ const seen = new Set();
11
+ for (const { group } of order) {
12
+ if (seen.has(group))
13
+ throw new Error(`\`order\` for source \`${source.id}\` declares the group \`${group}\` twice.`);
14
+ seen.add(group);
15
+ }
16
+ return order;
17
+ }
18
+ /**
19
+ * Settle a source's reading order: its pages in order, and the nav groups
20
+ * they fall into.
21
+ *
22
+ * A flat `order` (or none) gives one group headed `source.group`. A grouped
23
+ * `order` gives one group per declared group, in declaration order; a group
24
+ * none of whose pages exist is left out of the nav (each missing slug still
25
+ * warns). Unlisted pages are appended alphabetically, with a warning, to the
26
+ * group headed `source.group` — a declared one of that name, or a new
27
+ * trailing one — so they land at the end and say so.
28
+ */
29
+ export function navOrder(source, pages) {
30
+ if (!source.order?.length) {
31
+ const ordered = [...pages].sort(byBareSlug);
32
+ return { ordered, groups: [{ group: source.group, pages: ordered }], warnings: [] };
33
+ }
34
+ const remaining = new Map(pages.map((page) => [page.bareSlug, page]));
35
+ const listed = new Set();
36
+ const groups = [];
37
+ const warnings = [];
38
+ for (const declared of orderGroups(source)) {
39
+ const settled = { group: declared.group, pages: [] };
40
+ for (const slug of declared.pages) {
41
+ if (listed.has(slug)) {
42
+ warnings.push(`\`order\` for source \`${source.id}\` lists \`${slug}\` more than once; ` +
43
+ `the first place wins.`);
44
+ continue;
45
+ }
46
+ listed.add(slug);
47
+ const page = remaining.get(slug);
48
+ if (!page) {
49
+ warnings.push(`\`order\` for source \`${source.id}\` lists \`${slug}\`, which has no page.`);
50
+ continue;
51
+ }
52
+ remaining.delete(slug);
53
+ settled.pages.push(page);
54
+ }
55
+ groups.push(settled);
56
+ }
57
+ const appended = [...remaining.values()].sort(byBareSlug);
58
+ for (const page of appended) {
59
+ warnings.push(`\`${page.bareSlug}\` (source \`${source.id}\`) is missing from \`order\` — ` +
60
+ `appended alphabetically.`);
61
+ }
62
+ if (appended.length) {
63
+ const home = groups.find((g) => g.group === source.group);
64
+ if (home)
65
+ home.pages.push(...appended);
66
+ else
67
+ groups.push({ group: source.group, pages: appended });
68
+ }
69
+ const nonEmpty = groups.filter((g) => g.pages.length > 0);
70
+ return { ordered: nonEmpty.flatMap((g) => g.pages), groups: nonEmpty, warnings };
71
+ }
72
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,15 @@
1
+ export interface LoadMarkdownDirOptions {
2
+ /** Prepended to every page path, e.g. `'api'` → `'api/index.md'`. */
3
+ prefix?: string;
4
+ }
5
+ /**
6
+ * Every `.md` under `dir`, recursively, as pages a `DocsSource` accepts.
7
+ *
8
+ * Paths are relative to `dir`, `/`-separated whatever the platform, and sorted
9
+ * — the reading order a source's `order` then overrides.
10
+ */
11
+ export declare function loadMarkdownDir(dir: string, options?: LoadMarkdownDirOptions): Promise<{
12
+ path: string;
13
+ markdown: string;
14
+ }[]>;
15
+ //# sourceMappingURL=sources.d.ts.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Loading a tree of markdown somebody else generated.
3
+ *
4
+ * `DocsSource.dir` already reads a directory, but it reads it as *the* source:
5
+ * one directory, one group, one reading order. A generator's output is not
6
+ * that — the TypeDoc API reference lands under `docs/generated/api` in the SDK
7
+ * repo and has to be handed to a source that also has a prefix, a banner and a
8
+ * repo link the generator knows nothing about. So this returns the pages and
9
+ * stops, and the caller says what they are.
10
+ *
11
+ * It does not check that the directory exists. A caller who wants a missing
12
+ * directory to be survivable (a fresh checkout that has not built the SDK yet)
13
+ * should test for it and say so in its own words; swallowing ENOENT here would
14
+ * make "the generator never ran" indistinguishable from "it generated nothing".
15
+ */
16
+ import { readdir, readFile } from 'node:fs/promises';
17
+ import { join, resolve, sep } from 'node:path';
18
+ /**
19
+ * Every `.md` under `dir`, recursively, as pages a `DocsSource` accepts.
20
+ *
21
+ * Paths are relative to `dir`, `/`-separated whatever the platform, and sorted
22
+ * — the reading order a source's `order` then overrides.
23
+ */
24
+ export async function loadMarkdownDir(dir, options = {}) {
25
+ const root = resolve(dir);
26
+ const prefix = options.prefix?.replace(/^\/+|\/+$/g, '') ?? '';
27
+ const pages = [];
28
+ for (const file of await markdownFilesIn(root)) {
29
+ const relative = file
30
+ .slice(root.length + 1)
31
+ .split(sep)
32
+ .join('/');
33
+ pages.push({
34
+ path: prefix ? `${prefix}/${relative}` : relative,
35
+ markdown: await readFile(file, 'utf8'),
36
+ });
37
+ }
38
+ return pages;
39
+ }
40
+ async function markdownFilesIn(dir) {
41
+ const found = [];
42
+ const entries = await readdir(dir, { withFileTypes: true });
43
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
44
+ const full = join(dir, entry.name);
45
+ if (entry.isDirectory())
46
+ found.push(...(await markdownFilesIn(full)));
47
+ else if (entry.name.toLowerCase().endsWith('.md'))
48
+ found.push(full);
49
+ }
50
+ return found;
51
+ }
52
+ //# sourceMappingURL=sources.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The bridge from a compiled pipeline to a drawing of it.
3
+ *
4
+ * This package lays graphs out and knows nothing about pipelines; the SDK
5
+ * compiles pipelines and knows nothing about drawings. This is the one place
6
+ * the two vocabularies meet, and it translates rather than merges: a
7
+ * `DocsGraphNode`'s kind travels as an opaque token the page styles, and an
8
+ * edge's ports do not travel at all.
9
+ *
10
+ * It lives here rather than in `@serene-pub/cli` — which is where it was
11
+ * written and which still re-exports it — because it is pure and the browser
12
+ * playground needs it: the cli is Node-only, and a `DocsGraph` is the only
13
+ * thing `renderDocsGraph` accepts. The `SpecDocument` import is type-only, so
14
+ * nothing about the one-way arrow in `types.ts` changes — at runtime this file
15
+ * imports nothing at all.
16
+ */
17
+ import type { SpecDocument } from '@serene-pub/sdk';
18
+ import type { DocsGraph } from './types.js';
19
+ /**
20
+ * One compiled spec → the flat graph the docs compiler draws.
21
+ *
22
+ * Node labels are the keys, because the key is what the rest of the page and
23
+ * every error message calls that step; the type id rides underneath it.
24
+ *
25
+ * Edges are de-duplicated by endpoint pair. A spec's `edges` are 1:1 with
26
+ * `pipeline_edges` rows, so two `$ref`s from the same upstream node into two
27
+ * different config paths are two rows and the same line — drawn twice, it is
28
+ * the same line, slightly fatter, for no reader's benefit.
29
+ * @internal
30
+ */
31
+ export declare function specGraphOf(doc: SpecDocument, opts?: {
32
+ title?: string;
33
+ }): DocsGraph;
34
+ //# sourceMappingURL=specGraph.d.ts.map
Binary file