@volvel/docs-engine 0.0.0-stage → 0.7.0

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,197 @@
1
+ import MiniSearch from "minisearch";
2
+ /** Whether a page is reference, which a search shows after pages that explain, unless it is asked for by name. */
3
+ export function isReference(path, type) {
4
+ return type === "reference" || path.split("/").slice(0, -1).includes("reference");
5
+ }
6
+ /** How many pages a search shows when it is not told: the server and the help panel answer alike. */
7
+ export const RESULT_LIMIT = 12;
8
+ export const OPTIONS = {
9
+ fields: ["title", "description", "headings", "heading", "text"],
10
+ storeFields: [
11
+ "kind",
12
+ "path",
13
+ "url",
14
+ "title",
15
+ "description",
16
+ "collection",
17
+ "docType",
18
+ "generated",
19
+ "heading",
20
+ "anchor",
21
+ "passage",
22
+ ],
23
+ searchOptions: {
24
+ boost: { title: 4, heading: 3, headings: 2, description: 2 },
25
+ prefix: true,
26
+ fuzzy: 0.15,
27
+ combineWith: "AND",
28
+ },
29
+ };
30
+ function excerpt(text, terms) {
31
+ const flat = text.replace(/\s+/g, " ");
32
+ const lower = flat.toLowerCase();
33
+ let at = -1;
34
+ for (const term of terms) {
35
+ at = lower.indexOf(term.toLowerCase());
36
+ if (at !== -1)
37
+ break;
38
+ }
39
+ if (at === -1)
40
+ return flat.slice(0, 160).trim();
41
+ const start = Math.max(0, flat.lastIndexOf(" ", Math.max(0, at - 60)));
42
+ const piece = flat.slice(start, start + 160).trim();
43
+ return `${start > 0 ? "… " : ""}${piece}${start + 160 < flat.length ? " …" : ""}`;
44
+ }
45
+ /** The sentence around the first word asked for: what a result shows under its page. */
46
+ function sentence(text, terms) {
47
+ const flat = text.replace(/\s+/g, " ").trim();
48
+ const lower = flat.toLowerCase();
49
+ let at = -1;
50
+ for (const term of terms) {
51
+ at = lower.indexOf(term.toLowerCase());
52
+ if (at !== -1)
53
+ break;
54
+ }
55
+ if (at === -1)
56
+ return flat.slice(0, 120);
57
+ const before = flat.slice(0, at);
58
+ const lastStop = before.lastIndexOf(". ");
59
+ const start = lastStop === -1 ? 0 : lastStop + 2;
60
+ const stop = flat.indexOf(". ", at);
61
+ const end = stop === -1 ? flat.length : stop + 1;
62
+ const piece = flat.slice(start, end);
63
+ if (piece.length <= 140)
64
+ return piece;
65
+ const from = Math.max(0, at - start - 50);
66
+ return `${from > 0 ? "… " : ""}${piece.slice(from, from + 130).trim()} …`;
67
+ }
68
+ /** Marks every word of a text that begins with a term asked for. */
69
+ export function mark(text, terms) {
70
+ const wanted = [...new Set(terms.map((term) => term.toLowerCase()).filter(Boolean))].sort((a, b) => b.length - a.length);
71
+ if (wanted.length === 0 || text === "")
72
+ return [{ text }];
73
+ const escaped = wanted.map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
74
+ const pattern = new RegExp(`(${escaped.join("|")})`, "gi");
75
+ const out = [];
76
+ let last = 0;
77
+ for (const found of text.matchAll(pattern)) {
78
+ const at = found.index ?? 0;
79
+ if (at > last)
80
+ out.push({ text: text.slice(last, at) });
81
+ out.push({ text: found[0], hit: true });
82
+ last = at + found[0].length;
83
+ }
84
+ if (last < text.length)
85
+ out.push({ text: text.slice(last) });
86
+ return out;
87
+ }
88
+ /** What an index kept of a hit's words: a passage, or in an older index the whole text. */
89
+ function passageOf(hit) {
90
+ const own = hit.kind === "section" ? hit.text : hit.intro;
91
+ // An index built before passages were cleaned of list markers may start with one.
92
+ return String(hit.passage ?? own ?? hit.text ?? "").replace(/^\s*(?:[-*+\u2022]|\d+[.)]|#{1,6}|>)\s+/, "");
93
+ }
94
+ /** Reads an index back, to ask it questions. */
95
+ export function loadSearchIndex(json) {
96
+ const index = MiniSearch.loadJSON(json, OPTIONS);
97
+ const titleOf = (path) => String(index.getStoredFields(path)?.title ?? "");
98
+ /**
99
+ * Hits, best first. A page of reference comes after pages that explain, unless
100
+ * what was typed is its title, or a heading on it, in full.
101
+ */
102
+ const found = (query, filter) => {
103
+ const asked = query.trim().toLowerCase();
104
+ return index
105
+ .search(query, filter ? { filter } : {})
106
+ .map((hit) => {
107
+ const path = hit.path;
108
+ const exact = titleOf(path).toLowerCase() === asked ||
109
+ String(hit.heading ?? "").toLowerCase() === asked;
110
+ const own = index.getStoredFields(path);
111
+ // Where the set says which pages are generated, those come after every page written,
112
+ // unless asked for by name: a page written keeps its weight, reference or not.
113
+ // Otherwise reference is marked down.
114
+ const tier = own?.generated === "1" && !exact ? 1 : 0;
115
+ const down = own?.generated === undefined && isReference(path, own?.docType) && !exact;
116
+ return { hit, tier, score: down ? hit.score * 0.6 : hit.score };
117
+ })
118
+ .sort((a, b) => a.tier - b.tier || b.score - a.score)
119
+ .map((one) => one.hit);
120
+ };
121
+ return {
122
+ search(query, limit = 20, options = {}) {
123
+ if (query.trim() === "")
124
+ return [];
125
+ const pages = new Map();
126
+ // A page is found by its own words or by those of a section of it.
127
+ for (const hit of found(query, options.type !== undefined ? (hit) => hit.docType === options.type : undefined)) {
128
+ const path = hit.path;
129
+ if (pages.has(path) || pages.size >= limit)
130
+ continue;
131
+ const own = index.getStoredFields(path);
132
+ pages.set(path, {
133
+ path,
134
+ url: hit.url,
135
+ title: String(own?.title ?? hit.title ?? ""),
136
+ description: String(own?.description ?? hit.description ?? ""),
137
+ excerpt: excerpt(passageOf(hit), hit.terms),
138
+ });
139
+ }
140
+ return [...pages.values()];
141
+ },
142
+ grouped(query, options = {}) {
143
+ const asked = query.trim();
144
+ if (asked === "")
145
+ return [];
146
+ const words = asked.split(/\s+/);
147
+ const hits = found(asked, options.collection !== undefined || options.type !== undefined
148
+ ? (hit) => (options.collection === undefined || hit.collection === options.collection) &&
149
+ (options.type === undefined || hit.docType === options.type)
150
+ : undefined);
151
+ const pages = new Map();
152
+ for (const hit of hits) {
153
+ const path = hit.path;
154
+ let page = pages.get(path);
155
+ if (!page) {
156
+ if (pages.size >= (options.limit ?? RESULT_LIMIT))
157
+ continue;
158
+ // The page's own title, from whichever of its hits came first.
159
+ const own = hit.kind === "page" ? hit : index.getStoredFields(path);
160
+ const terms = [...words, ...hit.terms];
161
+ page = {
162
+ path,
163
+ url: hit.url,
164
+ title: mark(String(own?.title ?? ""), terms),
165
+ description: String(own?.description ?? ""),
166
+ collection: hit.collection,
167
+ score: hit.score,
168
+ ...(hit.docType ? { docType: hit.docType } : {}),
169
+ places: [],
170
+ };
171
+ pages.set(path, page);
172
+ }
173
+ if (page.places.length >= 3)
174
+ continue;
175
+ const terms = [...words, ...hit.terms];
176
+ const url = hit.kind === "section" ? `${hit.url}#${hit.anchor}` : hit.url;
177
+ const heading = String(hit.heading ?? "");
178
+ const inHeading = hit.kind === "section" &&
179
+ terms.some((term) => heading.toLowerCase().includes(term.toLowerCase()));
180
+ if (inHeading) {
181
+ page.places.push({ type: "heading", url, words: mark(heading, terms) });
182
+ continue;
183
+ }
184
+ const text = passageOf(hit);
185
+ const lower = text.toLowerCase();
186
+ // A section found by words beyond its passage still shows how it begins.
187
+ if (hit.kind !== "section" && !terms.some((term) => lower.includes(term.toLowerCase())))
188
+ continue;
189
+ if (text === "")
190
+ continue;
191
+ page.places.push({ type: "text", url, words: mark(sentence(text, terms), terms) });
192
+ }
193
+ return [...pages.values()];
194
+ },
195
+ };
196
+ }
197
+ //# sourceMappingURL=search-query.js.map
@@ -0,0 +1,17 @@
1
+ import { type DocSet } from "./set.js";
2
+ export type { Marked, PageHit, PlaceHit, SearchHit } from "./search-query.js";
3
+ export { loadSearchIndex, mark, RESULT_LIMIT } from "./search-query.js";
4
+ /** The most characters of a page's or a section's words an index keeps for a result's snippet. */
5
+ export declare const PASSAGE_LENGTH = 400;
6
+ /** A line of words without what marks it as a list item, a heading or a quote. */
7
+ export declare function unmarked(text: string): string;
8
+ /**
9
+ * Builds a set's search index, as text to store or send. The index holds the
10
+ * words of every page of the set, so it is given only to someone who may open
11
+ * the whole set.
12
+ */
13
+ export declare function buildSearchIndex(set: DocSet, options?: {
14
+ productName?: string;
15
+ generated?: ReadonlySet<string>;
16
+ }): string;
17
+ //# sourceMappingURL=search.d.ts.map
package/dist/search.js ADDED
@@ -0,0 +1,98 @@
1
+ import { plain, renderText, TREE_VERSION, walk } from "@volvel/markup";
2
+ import MiniSearch from "minisearch";
3
+ import { OPTIONS } from "./search-query.js";
4
+ import { pagesInOrder, urlOf } from "./set.js";
5
+ export { loadSearchIndex, mark, RESULT_LIMIT } from "./search-query.js";
6
+ /** The most characters of a page's or a section's words an index keeps for a result's snippet. */
7
+ export const PASSAGE_LENGTH = 400;
8
+ /** A line of words without what marks it as a list item, a heading or a quote. */
9
+ export function unmarked(text) {
10
+ return text
11
+ .split("\n")
12
+ .map((line) => line.replace(/^\s*(?:[-*+\u2022]|\d+[.)]|#{1,6}|>)\s+/, ""))
13
+ .join("\n");
14
+ }
15
+ /** Words clipped to a length at the end of a word. */
16
+ function clip(text) {
17
+ const flat = unmarked(text).replace(/\s+/g, " ").trim();
18
+ if (flat.length <= PASSAGE_LENGTH)
19
+ return flat;
20
+ const cut = flat.slice(0, PASSAGE_LENGTH);
21
+ return cut.slice(0, Math.max(cut.lastIndexOf(" "), PASSAGE_LENGTH / 2));
22
+ }
23
+ /** The parts of a page under each of its headings of the first three levels, with what comes before them. */
24
+ function sections(tree) {
25
+ const out = [{ nodes: [] }];
26
+ for (const node of tree.children) {
27
+ if (node.type === "heading" && node.depth <= 3) {
28
+ out.push({ heading: { id: node.id, text: plain(node) }, nodes: [] });
29
+ }
30
+ else
31
+ out.at(-1).nodes.push(node);
32
+ }
33
+ return out;
34
+ }
35
+ /**
36
+ * Builds a set's search index, as text to store or send. The index holds the
37
+ * words of every page of the set, so it is given only to someone who may open
38
+ * the whole set.
39
+ */
40
+ export function buildSearchIndex(set, options = {}) {
41
+ const index = new MiniSearch(OPTIONS);
42
+ const order = pagesInOrder(set.nav).map((page) => page.path);
43
+ const rest = [...set.pages.keys()].filter((path) => !order.includes(path)).sort();
44
+ const text = (nodes) => renderText({ type: "root", v: TREE_VERSION, children: nodes }, options.productName ? { productName: options.productName } : {});
45
+ for (const path of [...order, ...rest]) {
46
+ const entry = set.pages.get(path);
47
+ if (!entry)
48
+ continue;
49
+ const headings = [];
50
+ for (const { node } of walk(entry.tree)) {
51
+ if (node.type === "heading")
52
+ headings.push(plain(node));
53
+ }
54
+ const url = urlOf(path);
55
+ const collection = path.includes("/") ? path.split("/")[0] : "";
56
+ const base = {
57
+ path,
58
+ url,
59
+ title: entry.frontmatter.title,
60
+ description: entry.frontmatter.description ?? "",
61
+ collection,
62
+ docType: set.types[path] ?? "",
63
+ ...(options.generated ? { generated: options.generated.has(path) ? "1" : "0" } : {}),
64
+ };
65
+ const parts = sections(entry.tree);
66
+ // A page's own words are those before its first heading: the rest is its sections'.
67
+ const intro = text(parts[0]?.nodes ?? []);
68
+ index.add({
69
+ ...base,
70
+ id: path,
71
+ kind: "page",
72
+ headings: headings.join("\n"),
73
+ heading: "",
74
+ anchor: "",
75
+ text: intro,
76
+ passage: clip(intro),
77
+ });
78
+ for (const part of parts.slice(1)) {
79
+ if (!part.heading)
80
+ continue;
81
+ const words = text(part.nodes);
82
+ index.add({
83
+ ...base,
84
+ id: `${path}#${part.heading.id}`,
85
+ kind: "section",
86
+ headings: "",
87
+ // A section is found by its own words, not by its page's title.
88
+ title: "",
89
+ heading: part.heading.text,
90
+ anchor: part.heading.id,
91
+ text: words,
92
+ passage: clip(words),
93
+ });
94
+ }
95
+ }
96
+ return JSON.stringify(index);
97
+ }
98
+ //# sourceMappingURL=search.js.map
package/dist/set.d.ts ADDED
@@ -0,0 +1,198 @@
1
+ import { type DocType } from "./diataxis.js";
2
+ import { type DocEntry, type DocIssue } from "./page.js";
3
+ import { type AboutKind, type TermDefinition } from "./schema.js";
4
+ /**
5
+ * A set of pages, and everything worked out across them. All of a set's
6
+ * structure comes from its pages' paths and from what a folder's own page
7
+ * says of the order of what is in it:
8
+ *
9
+ * index the home page
10
+ * <page> a page of the "Uncategorized" collection
11
+ * <folder>/index what a folder is called, its icon, and the order of what is in it (`pages:`)
12
+ * <folder>/<page>
13
+ * <folder>/<folder>/… folders inside folders, to any depth
14
+ *
15
+ * A folder of the set's own folder is a collection.
16
+ */
17
+ export interface PageRef {
18
+ type: "page";
19
+ path: string;
20
+ /** The page's address under the set's own: the path, without a last `index`. */
21
+ url: string;
22
+ title: string;
23
+ description?: string;
24
+ /** The page's type, when it has one: never for a folder's index. */
25
+ docType?: DocType;
26
+ }
27
+ export interface Folder {
28
+ type: "folder";
29
+ /** The folder's name, the last part of its path. Empty for the pages that are in no folder. */
30
+ id: string;
31
+ /** The folder's path under the set's own. Empty for the pages that are in no folder. */
32
+ path: string;
33
+ title: string;
34
+ icon?: string;
35
+ description?: string;
36
+ /** The folder's own page, when it has one. */
37
+ index?: PageRef;
38
+ items: (PageRef | Folder)[];
39
+ }
40
+ /** A folder of the set's own folder. */
41
+ export type Collection = Folder;
42
+ export interface Nav {
43
+ home?: PageRef;
44
+ collections: Folder[];
45
+ }
46
+ /** A glossary term, and the page that defines it. */
47
+ export interface Term extends TermDefinition {
48
+ path: string;
49
+ }
50
+ export interface DocSet {
51
+ pages: ReadonlyMap<string, DocEntry>;
52
+ nav: Nav;
53
+ /** Topic to the path of the page that has it. */
54
+ topics: Record<string, string>;
55
+ terms: Record<string, Term>;
56
+ /** A resource, as `<kind>:<path>`, to the paths of the pages that say they document it. */
57
+ attachments: Record<string, string[]>;
58
+ /** A topic of the product's help to the paths of the pages that add notes to it. */
59
+ extensions: Record<string, string[]>;
60
+ /** A typed page's path to its type: its own, or its folder's. Empty when the site has no types. */
61
+ types: Record<string, DocType>;
62
+ /** A subject to the paths of the pages that name it. */
63
+ subjects: Record<string, string[]>;
64
+ /** A path a page used to have, to the path it has now. */
65
+ redirects: Record<string, string>;
66
+ }
67
+ /** Every new term and topic of the product's own help starts with this, so none of a tenant's can collide with it. */
68
+ export declare const PRODUCT_PREFIX = "volvel-";
69
+ export declare const UNCATEGORIZED = "Uncategorized";
70
+ export interface BuildOptions {
71
+ /** Term ids that belong to the product. A page may not define one of them. */
72
+ reservedTerms?: Iterable<string>;
73
+ /** Topics that belong to the product. A page may not take one of them, and may extend one. */
74
+ reservedTopics?: Iterable<string>;
75
+ /**
76
+ * Names that begin with this are the product's too, whether or not this version of it has one:
77
+ * the product starts every new term and topic with it, so a tenant's can never collide.
78
+ */
79
+ reservedPrefix?: string;
80
+ /** Terms defined somewhere else that a page here may use: another layer's. */
81
+ knownTerms?: Iterable<string>;
82
+ /** Whether a file beside the pages is there, by its path under the docs root. Left out, pictures are not checked. */
83
+ asset?: (path: string) => boolean;
84
+ /**
85
+ * Whether a resource is there. Left out, resources are not checked: a set
86
+ * built where nobody knows the workspace cannot say.
87
+ */
88
+ resource?: (kind: AboutKind, path: string, column?: string) => boolean;
89
+ }
90
+ /** A page's address under its set's: `guides/index` is `guides`, and `index` is the set's own. */
91
+ export declare function urlOf(path: string): string;
92
+ /** The name an item is listed by in its folder's `pages:`: a page's file name, or a folder's own. */
93
+ export declare function nameOf(item: PageRef | Folder): string;
94
+ /**
95
+ * Puts a folder's items in order: those its own page lists, as listed, and
96
+ * then the rest by title.
97
+ */
98
+ export declare function ordered<Item extends PageRef | Folder>(items: readonly Item[], listed: readonly string[] | undefined): Item[];
99
+ /** Where a link written on one page leads, within a set. */
100
+ export type Target = {
101
+ path: string;
102
+ anchor?: string;
103
+ } | {
104
+ missing: "page" | "topic" | "outside";
105
+ wanted: string;
106
+ };
107
+ /**
108
+ * Works out which page a link goes to. A link is written from where its file
109
+ * is: on `guides/refunds`, `returns` is `guides/returns` and `../index` is the
110
+ * home page. `.md` on the end is allowed, and a folder means its index.
111
+ */
112
+ export declare function resolveLink(set: {
113
+ pages: {
114
+ has(path: string): boolean;
115
+ };
116
+ topics: Record<string, string>;
117
+ }, from: string, href: string): Target;
118
+ /** Where a picture written on one page is, as a path under the docs root. */
119
+ export declare function resolveAsset(from: string, src: string): string | undefined;
120
+ /** A resource as an attachment names it. */
121
+ export declare function resourceKey(kind: string, path: string): string;
122
+ /** What a page's links, pictures and terms are checked against: the pages around it. */
123
+ export interface Around {
124
+ /** The pages there are, by path. Only whether a path is there is asked. */
125
+ pages: {
126
+ has(path: string): boolean;
127
+ };
128
+ topics: Record<string, string>;
129
+ /** What each page's headings are addressed by. */
130
+ headingsOf: (path: string) => ReadonlySet<string>;
131
+ knownTerms: ReadonlySet<string>;
132
+ asset?: (path: string) => boolean;
133
+ resource?: (kind: AboutKind, path: string, column?: string) => boolean;
134
+ }
135
+ /** What is wrong with one page's links, pictures and terms, beside the pages around it. */
136
+ export declare function crossIssues(entry: DocEntry, around: Around): DocIssue[];
137
+ /** Builds a set from pages already read, and says what is wrong across them. */
138
+ export declare function buildDocSet(entries: readonly DocEntry[], options?: BuildOptions): {
139
+ set: DocSet;
140
+ issues: DocIssue[];
141
+ };
142
+ /** Every page of a navigation, in the order a reader meets them. */
143
+ export declare function pagesInOrder(nav: Nav): PageRef[];
144
+ /**
145
+ * The page before and the page after one, in the order of its collection: the first page of a
146
+ * collection has no page before it, and the last none after, so a reader is never carried into
147
+ * another collection by "Next". The home page, which is in none, goes on to the first of all.
148
+ * The one function the served site's pager and the console's help panel both use.
149
+ */
150
+ export declare function neighboursOf(nav: Nav, path: string): {
151
+ before?: PageRef;
152
+ after?: PageRef;
153
+ };
154
+ /** The folders from a collection down to a page, outermost first. Empty when the page is in none. */
155
+ export declare function trailOf(nav: Nav, path: string): Folder[];
156
+ /**
157
+ * What a page's folder holds, for `::pages`: for a folder's own page, that
158
+ * folder; for any other page, the folder it is in. For the home page, the
159
+ * collections and the pages in no folder.
160
+ */
161
+ export declare function folderItems(nav: Nav, path: string): (PageRef | Folder)[];
162
+ /**
163
+ * The terms `::glossary` lists on a page: those defined by the pages of the
164
+ * page's collection, or by every page of the set. A page in no collection, and
165
+ * the home page, list the set's.
166
+ */
167
+ export declare function glossaryOf(set: DocSet, path: string, scope: "collection" | "site"): Term[];
168
+ /** The most related pages shown of one type. */
169
+ export declare const RELATED_PER_TYPE = 4;
170
+ /**
171
+ * The pages of other types that are about the same things as a page: those
172
+ * that share its `subjects`, or the resources it is `about`. For each type,
173
+ * the pages with the most in common first, then those in the page's own
174
+ * collection, then in the order of the navigation. An untyped page, and a
175
+ * folder's index, have none.
176
+ */
177
+ export declare function relatedTo(set: Pick<DocSet, "pages" | "nav" | "types">, path: string): Partial<Record<DocType, PageRef[]>>;
178
+ /** A card of a collection's own page: one type, and where it starts. */
179
+ export interface TypeCard {
180
+ type: DocType;
181
+ title: string;
182
+ summary: string;
183
+ count: number;
184
+ /** The first page of that type, in the order of the navigation. */
185
+ first: PageRef;
186
+ }
187
+ /**
188
+ * On a collection's own page, when its pages are of two types or more: a card for each, so that a
189
+ * reader says what they are doing and is taken to the first page that does it. Nothing for any
190
+ * other page. The served site and the editor's preview both draw these.
191
+ */
192
+ export declare function typeCardsOf(set: Pick<DocSet, "nav" | "types">, path: string): TypeCard[];
193
+ /**
194
+ * The same cards for a site's home page: one for each type that the site's pages have, when it has
195
+ * two or more, taken to the first page of that type in the order of the whole site.
196
+ */
197
+ export declare function homeTypeCardsOf(set: Pick<DocSet, "nav" | "types">): TypeCard[];
198
+ //# sourceMappingURL=set.d.ts.map