rspress-plugin-typesense 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Typesense
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # Rspress Plugin Typesense 🦀🔎⚡️
2
+
3
+ A plugin that brings lightning-fast, typo-tolerant search powered by Typesense to your Rspress site.
4
+
5
+ ## Getting started
6
+
7
+ Install dependencies:
8
+
9
+ ```bash
10
+ npm install rspress-plugin-typesense
11
+ ```
12
+
13
+ ## About Typesense & Rspress
14
+
15
+ [**Typesense**](https://typesense.org/) is an open-source, lightning-fast search engine that delivers instant, typo-tolerant results with minimal setup. It's an open source alternative to Algolia and an easier-to-use alternative to ElasticSearch.
16
+
17
+ [**Rspress**](https://rspress.rs/) is a high-performance static site generator for documentation websites. Built with Rust, it offers a modern development experience and produces blazing-fast static sites.
18
+
19
+ Together, **Typesense** and **Rspress** provide a seamless way to add powerful, blazingly-fast search to modern documentation websites.
20
+
21
+ ## License
22
+
23
+ Licensed under the Apache 2.0 License, Copyright © Typesense.
24
+
25
+ See [LICENSE](../../LICENSE) for more information.
@@ -0,0 +1,12 @@
1
+ import type { RspressPlugin } from '@rspress/core';
2
+ import type { ConfigurationOptions } from 'typesense/lib/Typesense/Configuration';
3
+ import type { CustomCollectionSettingsConfig } from './types.js';
4
+ import { getDefaultCollectionFields } from './typesenseHelper.js';
5
+ export type { CustomCollectionSettings, CustomCollectionSettingsConfig, } from './types.js';
6
+ export { getDefaultCollectionFields };
7
+ export interface TypesensePluginOptions {
8
+ typesenseOptions: ConfigurationOptions;
9
+ collectionName: string;
10
+ customCollectionSettings?: CustomCollectionSettingsConfig;
11
+ }
12
+ export declare function pluginTypesense(options: TypesensePluginOptions): RspressPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,110 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+ import { TypesenseHelper, getDefaultCollectionFields } from "./typesenseHelper.js";
4
+ import { IndexFromHtml } from "./indexFromHtml.js";
5
+ function pluginTypesense(options) {
6
+ let generatedRoutes = [];
7
+ return {
8
+ name: 'rspress-plugin-typesense',
9
+ config (config) {
10
+ return config;
11
+ },
12
+ async routeGenerated (routes) {
13
+ generatedRoutes = routes;
14
+ },
15
+ async afterBuild (config, isProd) {
16
+ if (!isProd) return;
17
+ const outDir = config.outDir || 'doc_build';
18
+ const defaultLang = config.lang || 'en';
19
+ const isVersioned = config.search?.versioned ?? true;
20
+ const defaultVersion = config.multiVersion?.default || '';
21
+ if (0 === generatedRoutes.length) return void console.warn(`\n\x1b[33m⚠ [TypesensePlugin] No routes generated.\x1b[0m \x1b[90mSkipping indexing.\x1b[0m\n`);
22
+ const routeGroups = {};
23
+ for (const route of generatedRoutes){
24
+ const possibleHomePages = [
25
+ 'index',
26
+ route.lang ? `${route.lang}_index` : '',
27
+ route.version ? `${route.version}_index` : '',
28
+ route.version && route.lang ? `${route.version}_${route.lang}_index` : ''
29
+ ];
30
+ if (possibleHomePages.includes(route.pageName)) continue;
31
+ const locale = route.lang || defaultLang;
32
+ const groupKey = locale;
33
+ if (!routeGroups[groupKey]) routeGroups[groupKey] = {
34
+ locale,
35
+ routes: []
36
+ };
37
+ routeGroups[groupKey].routes.push(route);
38
+ }
39
+ if (0 === Object.keys(routeGroups).length) return void console.warn(`\n\x1b[33m⚠ [TypesensePlugin] No routes found for indexing.\x1b[0m \x1b[90mSkipping indexing process.\x1b[0m\n`);
40
+ const extractor = new IndexFromHtml();
41
+ for(const groupKey in routeGroups){
42
+ const { locale, routes } = routeGroups[groupKey];
43
+ const aliasName = `${options.collectionName}_${locale}`;
44
+ const collectionNameTmp = `${aliasName}_${Date.now()}`;
45
+ const maxRouteLength = routes.reduce((max, r)=>Math.max(max, r.routePath.length), 0);
46
+ const padLength = Math.max(maxRouteLength + 4, 30);
47
+ console.log(`\n\x1b[1m\x1b[36m[TypesensePlugin]\x1b[0m \x1b[1mProcessing group:\x1b[0m \x1b[35m${aliasName}\x1b[0m \x1b[90m(${routes.length} routes)\x1b[0m`);
48
+ const localizedCustomSettings = resolveCustomSettings(options.customCollectionSettings, locale);
49
+ const helper = new TypesenseHelper({
50
+ config: options.typesenseOptions,
51
+ aliasName,
52
+ collectionNameTmp,
53
+ customSettings: localizedCustomSettings,
54
+ locale,
55
+ isVersioned
56
+ });
57
+ await helper.init();
58
+ await helper.createTmpCollection();
59
+ let totalRecords = 0;
60
+ for (const route of routes){
61
+ const version = route.version || defaultVersion;
62
+ let normalizedRoute = route.routePath.replace(/^\//, '');
63
+ if (defaultVersion && normalizedRoute.startsWith(`${defaultVersion}/`)) normalizedRoute = normalizedRoute.substring(defaultVersion.length + 1);
64
+ if (defaultLang && normalizedRoute.startsWith(`${defaultLang}/`)) normalizedRoute = normalizedRoute.substring(defaultLang.length + 1);
65
+ let htmlPath = path.join(outDir, normalizedRoute);
66
+ let fileFound = false;
67
+ if (fs.existsSync(htmlPath + '.html')) {
68
+ htmlPath += '.html';
69
+ fileFound = true;
70
+ } else if (fs.existsSync(path.join(htmlPath, 'index.html'))) {
71
+ htmlPath = path.join(htmlPath, 'index.html');
72
+ fileFound = true;
73
+ }
74
+ if (!fileFound) {
75
+ const fillerLength = Math.max(2, padLength - route.routePath.length);
76
+ const filler = '\x1b[90m' + '.'.repeat(fillerLength) + '\x1b[0m';
77
+ console.warn(` \x1b[33m⚠\x1b[0m \x1b[37m${route.routePath}\x1b[0m ${filler} \x1b[33mskipped\x1b[0m \x1b[90m(HTML not found)\x1b[0m`);
78
+ continue;
79
+ }
80
+ try {
81
+ const htmlContent = fs.readFileSync(htmlPath, 'utf-8');
82
+ const records = extractor.getRecords(htmlContent, route.routePath, locale);
83
+ if (isVersioned && version) records.forEach((r)=>r.version = version);
84
+ if (records.length > 0) totalRecords += await helper.addRecords(records, route.routePath, false, padLength);
85
+ } catch (error) {
86
+ const fillerLength = Math.max(2, padLength - route.routePath.length);
87
+ const filler = '\x1b[90m' + '.'.repeat(fillerLength) + '\x1b[0m';
88
+ console.error(` \x1b[31m✖\x1b[0m \x1b[37m${route.routePath}\x1b[0m ${filler} \x1b[31m failed\x1b[0m \x1b[90m(Processing error)\x1b[0m`);
89
+ console.error(` \x1b[31m↳ ${error instanceof Error ? error.message : error}\x1b[0m`);
90
+ }
91
+ }
92
+ try {
93
+ await helper.commitTmpCollection();
94
+ console.log(`\x1b[32m✔ Indexing complete for\x1b[0m \x1b[35m${aliasName}\x1b[0m \x1b[90m—\x1b[0m \x1b[33m${totalRecords}\x1b[0m \x1b[90mtotal records!\x1b[0m`);
95
+ } catch (error) {
96
+ console.error(`[TypesensePlugin] Failed to commit collection ${aliasName}:`, error);
97
+ throw error;
98
+ }
99
+ }
100
+ }
101
+ };
102
+ }
103
+ function resolveCustomSettings(settings, locale) {
104
+ if (!settings) return null;
105
+ const isGlobalConfig = 'token_separators' in settings || 'symbols_to_index' in settings || 'field_definitions' in settings || 'enable_nested_fields' in settings;
106
+ if (isGlobalConfig) return settings;
107
+ const perLangSettings = settings;
108
+ return perLangSettings[locale] || null;
109
+ }
110
+ export { getDefaultCollectionFields, pluginTypesense };
@@ -0,0 +1,16 @@
1
+ import type { DocSearchRecord } from './types.js';
2
+ export declare class IndexFromHtml {
3
+ private levels;
4
+ private selectors;
5
+ getRecords(html: string, url: string, lang?: string): DocSearchRecord[];
6
+ private getLevelFromTag;
7
+ private generateEmptyHierarchy;
8
+ private getHierarchyRadio;
9
+ private getAnchor;
10
+ private getClosestAnchor;
11
+ private getObjectID;
12
+ /**
13
+ * Removes anchor links and invisible characters
14
+ */
15
+ private cleanText;
16
+ }
@@ -0,0 +1,196 @@
1
+ import crypto_0 from "crypto";
2
+ import * as __rspack_external_cheerio from "cheerio";
3
+ class IndexFromHtml {
4
+ levels = [
5
+ 'lvl0',
6
+ 'lvl1',
7
+ 'lvl2',
8
+ 'lvl3',
9
+ 'lvl4',
10
+ 'lvl5',
11
+ 'lvl6'
12
+ ];
13
+ selectors = {
14
+ lvl0: {
15
+ selector: '.rp-nav-menu__item--active',
16
+ global: true
17
+ },
18
+ lvl1: {
19
+ selector: '.rp-doc h1',
20
+ global: false
21
+ },
22
+ lvl2: {
23
+ selector: '.rp-doc h2',
24
+ global: false
25
+ },
26
+ lvl3: {
27
+ selector: '.rp-doc h3',
28
+ global: false
29
+ },
30
+ lvl4: {
31
+ selector: '.rp-doc h4',
32
+ global: false
33
+ },
34
+ lvl5: {
35
+ selector: '.rp-doc h5',
36
+ global: false
37
+ },
38
+ lvl6: {
39
+ selector: '.rp-doc h6',
40
+ global: false
41
+ },
42
+ content: {
43
+ selector: '.rp-doc p, .rp-doc li, .rp-doc table, .rp-doc .rp-callout, .rp-doc .rp-codeblock__content .rp-codeblock__content__scroll-container',
44
+ global: false
45
+ }
46
+ };
47
+ getRecords(html, url, lang) {
48
+ const $ = __rspack_external_cheerio.load(html);
49
+ const records = [];
50
+ const getGlobalText = (selector)=>{
51
+ const el = $(selector).first();
52
+ return el.length ? this.cleanText(el) : null;
53
+ };
54
+ const globalHierarchy = {
55
+ lvl0: getGlobalText(this.selectors.lvl0.selector) || getGlobalText(this.selectors.lvl1.selector) || getGlobalText('.rp-sidebar-item--active .rp-sidebar-item__left') || $('title').text().trim() || 'Documentation'
56
+ };
57
+ const selectorString = Object.values(this.selectors).filter((s)=>!s.global).map((s)=>s.selector).join(', ');
58
+ const nodes = $(selectorString);
59
+ let previousHierarchy = this.generateEmptyHierarchy();
60
+ previousHierarchy.lvl0 = globalHierarchy.lvl0 || null;
61
+ const anchors = this.generateEmptyHierarchy();
62
+ nodes.each((index, element)=>{
63
+ const el = $(element);
64
+ const isNestedMatch = el.parents(selectorString).length > 0;
65
+ if (isNestedMatch) return;
66
+ const tagName = element.tagName.toLowerCase();
67
+ const currentLevel = this.getLevelFromTag(tagName);
68
+ const hierarchy = {
69
+ ...previousHierarchy
70
+ };
71
+ const currentLevelInt = this.levels.indexOf(currentLevel);
72
+ if ('content' !== currentLevel) {
73
+ const text = this.cleanText(el);
74
+ hierarchy[currentLevel] = text;
75
+ anchors[currentLevel] = this.getAnchor(el);
76
+ for(let i = currentLevelInt + 1; i < 7; i++){
77
+ const lvlKey = `lvl${i}`;
78
+ hierarchy[lvlKey] = null;
79
+ anchors[lvlKey] = null;
80
+ }
81
+ previousHierarchy = {
82
+ ...hierarchy
83
+ };
84
+ }
85
+ let content = null;
86
+ if ('content' === currentLevel) {
87
+ content = this.cleanText(el);
88
+ if (!content) return;
89
+ }
90
+ if (currentLevel.startsWith('lvl') && !hierarchy[currentLevel]) return;
91
+ const resolvedAnchor = this.getClosestAnchor(anchors);
92
+ let levelWeight;
93
+ if ('content' !== currentLevel) levelWeight = 100 - 10 * currentLevelInt;
94
+ else {
95
+ const isCodeBlock = el.hasClass('rp-codeblock__content__scroll-container') || el.parents('.rp-codeblock, pre').length > 0;
96
+ levelWeight = isCodeBlock ? 0 : 10;
97
+ }
98
+ const weight = {
99
+ page_rank: 0,
100
+ level: levelWeight,
101
+ position: index,
102
+ position_descending: nodes.length - index
103
+ };
104
+ const record = {
105
+ objectID: '',
106
+ url_without_anchor: url,
107
+ url: resolvedAnchor ? `${url}#${resolvedAnchor}` : url,
108
+ anchor: resolvedAnchor,
109
+ content: content,
110
+ hierarchy: hierarchy,
111
+ hierarchy_radio: this.getHierarchyRadio(hierarchy, currentLevel),
112
+ type: currentLevel,
113
+ weight: weight,
114
+ language: lang
115
+ };
116
+ record.objectID = this.getObjectID(record);
117
+ records.push(record);
118
+ });
119
+ return records;
120
+ }
121
+ getLevelFromTag(tagName) {
122
+ if ([
123
+ 'h1',
124
+ 'h2',
125
+ 'h3',
126
+ 'h4',
127
+ 'h5',
128
+ 'h6'
129
+ ].includes(tagName)) return `lvl${tagName.replace('h', '')}`;
130
+ return 'content';
131
+ }
132
+ generateEmptyHierarchy() {
133
+ return {
134
+ lvl0: null,
135
+ lvl1: null,
136
+ lvl2: null,
137
+ lvl3: null,
138
+ lvl4: null,
139
+ lvl5: null,
140
+ lvl6: null
141
+ };
142
+ }
143
+ getHierarchyRadio(hierarchy, currentLevel) {
144
+ const radio = this.generateEmptyHierarchy();
145
+ let isFound = false;
146
+ for(let i = 6; i >= 0; i--){
147
+ const level = `lvl${i}`;
148
+ const value = hierarchy[level];
149
+ if (!isFound && null !== value) {
150
+ if ('content' === currentLevel || level === currentLevel) {
151
+ radio[level] = value;
152
+ isFound = true;
153
+ continue;
154
+ }
155
+ }
156
+ radio[level] = null;
157
+ }
158
+ return radio;
159
+ }
160
+ getAnchor(el) {
161
+ const id = el.attr('id');
162
+ return id || null;
163
+ }
164
+ getClosestAnchor(anchors) {
165
+ for(let i = 6; i >= 0; i--){
166
+ const val = anchors[`lvl${i}`];
167
+ if (val) return val;
168
+ }
169
+ return null;
170
+ }
171
+ getObjectID(record) {
172
+ const hierarchyToHash = {};
173
+ Object.keys(record.hierarchy).forEach((k)=>{
174
+ const val = record.hierarchy[k];
175
+ if (val) hierarchyToHash[k] = val;
176
+ });
177
+ const payload = {
178
+ hierarchy: hierarchyToHash,
179
+ url: record.url_without_anchor,
180
+ position: record.weight.position
181
+ };
182
+ const jsonStr = JSON.stringify(payload, Object.keys(payload).sort());
183
+ return crypto_0.createHash('sha1').update(jsonStr).digest('hex');
184
+ }
185
+ cleanText(el) {
186
+ const clone = el.clone();
187
+ clone.find('.rp-header-anchor').remove();
188
+ clone.find('br').replaceWith(' ');
189
+ clone.find('li, p, div, tr').append(' ');
190
+ let text = clone.text();
191
+ text = text.replace(/\u00A0/g, ' ').replace(/[\u200B-\u200D\uFEFF]/g, '').replace(/\s+/g, ' ').trim();
192
+ if (text.length > 10000) text = text.slice(0, 10000) + '...';
193
+ return text;
194
+ }
195
+ }
196
+ export { IndexFromHtml };
@@ -0,0 +1,10 @@
1
+ import type { DocSearchProps } from 'typesense-docsearch-react';
2
+ import type { Locales } from './locales.js';
3
+ type SearchProps = {
4
+ docSearchProps: Omit<DocSearchProps, 'translations'>;
5
+ locales?: Locales;
6
+ versionedSearch?: boolean;
7
+ };
8
+ declare function Search({ locales, versionedSearch, docSearchProps: { typesenseCollectionName, transformItems, typesenseSearchParameters, ...docSearchProps }, }: SearchProps): import("react/jsx-runtime").JSX.Element;
9
+ export type { SearchProps };
10
+ export default Search;
@@ -0,0 +1,55 @@
1
+ import { Fragment, jsx } from "react/jsx-runtime";
2
+ import { DocSearch } from "typesense-docsearch-react";
3
+ import { useLang, useNavigate, useVersion } from "@rspress/core/runtime";
4
+ import { Link } from "@theme";
5
+ const Hit = ({ hit, children })=>/*#__PURE__*/ jsx(Link, {
6
+ href: hit.url,
7
+ children: children
8
+ });
9
+ const safeEscapeHighlights = (str)=>{
10
+ if (!str) return str;
11
+ return str.replace(/<(?!mark>|\/mark>)/gi, '&lt;').replace(/(?<!<mark|<\/mark)>/gi, '&gt;');
12
+ };
13
+ function Search({ locales = {}, versionedSearch = true, docSearchProps: { typesenseCollectionName, transformItems, typesenseSearchParameters, ...docSearchProps } }) {
14
+ const navigate = useNavigate();
15
+ const version = useVersion();
16
+ const lang = useLang() || 'en';
17
+ const { translations, placeholder } = locales?.[lang] ?? {};
18
+ const resolvedCollectionName = `${typesenseCollectionName}_${lang}`;
19
+ const searchParams = {
20
+ ...typesenseSearchParameters || {}
21
+ };
22
+ const filters = [];
23
+ if (searchParams.filter_by) filters.push(`(${searchParams.filter_by})`);
24
+ if (versionedSearch && version) filters.push(`version:=\`${version}\``);
25
+ if (filters.length > 0) searchParams.filter_by = filters.join(' && ');
26
+ return /*#__PURE__*/ jsx(Fragment, {
27
+ children: /*#__PURE__*/ jsx(DocSearch, {
28
+ typesenseCollectionName: resolvedCollectionName,
29
+ typesenseSearchParameters: searchParams,
30
+ placeholder: placeholder,
31
+ translations: translations,
32
+ transformItems: (items)=>{
33
+ const transformedItems = items.map((item)=>{
34
+ const transformed = structuredClone(item);
35
+ if (transformed._snippetResult?.content?.value) transformed._snippetResult.content.value = safeEscapeHighlights(transformed._snippetResult.content.value);
36
+ if (transformed._highlightResult?.hierarchy) Object.values(transformed._highlightResult.hierarchy).forEach((level)=>{
37
+ if (level?.value) level.value = safeEscapeHighlights(level.value);
38
+ });
39
+ return transformed;
40
+ });
41
+ if (transformItems) return transformItems(transformedItems);
42
+ return transformedItems;
43
+ },
44
+ navigator: {
45
+ navigate ({ itemUrl }) {
46
+ navigate(itemUrl);
47
+ }
48
+ },
49
+ hitComponent: Hit,
50
+ ...docSearchProps
51
+ })
52
+ });
53
+ }
54
+ const RealSearch = Search;
55
+ export default RealSearch;
@@ -0,0 +1,76 @@
1
+ [class*="DocSearch"] {
2
+ --docsearch-searchbox-shadow: inset 0 0 0 2px var(--rp-c-brand);
3
+ --docsearch-primary-color: var(--rp-c-brand);
4
+ --docsearch-text-color: var(--rp-c-text-1);
5
+ --docsearch-secondary-text-color: var(--rp-c-text-2);
6
+ --docsearch-muted-color: var(--rp-c-text-2);
7
+ --docsearch-subtle-color: var(--rp-c-divider-light);
8
+ --docsearch-container-background: #3c3c3c66;
9
+ --docsearch-modal-background: var(--rp-c-bg);
10
+ --docsearch-search-button-background: color-mix(in srgb,
11
+ var(--rp-c-bg) 30%,
12
+ transparent);
13
+ --docsearch-search-button-text-color: var(--rp-c-text-2);
14
+ --docsearch-searchbox-background: color-mix(in srgb,
15
+ var(--rp-c-bg) 30%,
16
+ transparent);
17
+ --docsearch-searchbox-focus-background: color-mix(in srgb,
18
+ var(--rp-c-bg) 30%,
19
+ transparent);
20
+ --docsearch-hit-highlight-color: var(--rp-c-brand-tint);
21
+ --docsearch-hit-color: var(--rp-c-text-1);
22
+ --docsearch-hit-background: var(--rp-c-bg-soft);
23
+ --docsearch-hit-shadow: var(--rp-shadow-2);
24
+ --docsearch-footer-background: var(--rp-c-bg);
25
+ --docsearch-key-background: var(--rp-c-bg-mute);
26
+ --docsearch-key-color: var(--rp-c-text-2);
27
+ --docsearch-highlight-color: var(--rp-c-brand);
28
+ --docsearch-icon-color: var(--rp-c-text-1);
29
+ --docsearch-background-color: var(--rp-c-bg-mute);
30
+ --docsearch-focus-color: var(--rp-c-brand);
31
+ --docsearch-dropdown-menu-background: var(--rp-c-bg-soft);
32
+ --docsearch-dropdown-menu-item-hover-background: var(--rp-c-bg);
33
+ }
34
+
35
+ html.dark {
36
+ --docsearch-text-color: #f5f6f7;
37
+ --docsearch-container-background: #090a11cc;
38
+ --docsearch-modal-background: #15172a;
39
+ --docsearch-modal-shadow: inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309;
40
+ --docsearch-searchbox-background: #090a11;
41
+ --docsearch-searchbox-focus-background: #000;
42
+ --docsearch-hit-color: #bec3c9;
43
+ --docsearch-hit-shadow: none;
44
+ --docsearch-hit-background: #090a11;
45
+ --docsearch-key-gradient: linear-gradient(-26.5deg,
46
+ #565872 0%,
47
+ #31355b 100%);
48
+ --docsearch-key-shadow: inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d,
49
+ 0 2px 2px 0 #0304094d;
50
+ --docsearch-footer-background: #1e2136;
51
+ --docsearch-footer-shadow: inset 0 1px 0 0 #494c6a80, 0 -4px 8px 0 #0003;
52
+ --docsearch-logo-color: #fff;
53
+ --docsearch-muted-color: #7f8497;
54
+ }
55
+
56
+ .DocSearch {
57
+ border-radius: var(--rp-radius-small);
58
+ }
59
+
60
+ .DocSearch-Button-Container > .DocSearch-Button-Placeholder {
61
+ font-size: .825rem;
62
+ }
63
+
64
+ .DocSearch-Button {
65
+ border: 1px solid var(--docsearch-subtle-color);
66
+ }
67
+
68
+ .DocSearch-Button:hover {
69
+ box-shadow: none;
70
+ color: var(--docsearch-search-button-text-color);
71
+ }
72
+
73
+ .DocSearch-Screen-Icon svg {
74
+ margin: auto;
75
+ }
76
+
@@ -0,0 +1,5 @@
1
+ import type { SearchProps } from './RealSearch.js';
2
+ import 'typesense-docsearch-css';
3
+ import './Search.css';
4
+ export declare function Search(props: SearchProps): import("react/jsx-runtime").JSX.Element;
5
+ export type { SearchProps };
@@ -0,0 +1,131 @@
1
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
+ import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
3
+ import "typesense-docsearch-css";
4
+ import "./Search.css";
5
+ import { useLang } from "@rspress/core/runtime";
6
+ const RealSearch = /*#__PURE__*/ lazy(()=>import("./RealSearch.js"));
7
+ function Search(props) {
8
+ const [isLoaded, setIsLoaded] = useState(false);
9
+ const isLoadedRef = useRef(false);
10
+ const triggerRef = useRef(null);
11
+ const lang = useLang() || 'en';
12
+ const placeholder = props.locales?.[lang]?.placeholder || 'Search';
13
+ const loadSearch = useCallback((trigger)=>{
14
+ if (!triggerRef.current) triggerRef.current = trigger;
15
+ if (!isLoadedRef.current) {
16
+ isLoadedRef.current = true;
17
+ setIsLoaded(true);
18
+ }
19
+ }, []);
20
+ useEffect(()=>{
21
+ let idleHandle;
22
+ idleHandle = 'requestIdleCallback' in window ? window.requestIdleCallback(()=>loadSearch('idle')) : setTimeout(()=>loadSearch('idle'), 2000);
23
+ const handleKeyDown = (event)=>{
24
+ const target = event.target;
25
+ if ('INPUT' === target.tagName || 'TEXTAREA' === target.tagName || target.isContentEditable) return;
26
+ const isCmdK = (event.metaKey || event.ctrlKey) && 'k' === event.key.toLowerCase();
27
+ const isSlash = '/' === event.key;
28
+ if (isCmdK || isSlash) {
29
+ if (!isLoadedRef.current) {
30
+ event.preventDefault();
31
+ loadSearch('keyboard');
32
+ }
33
+ }
34
+ };
35
+ window.addEventListener('keydown', handleKeyDown);
36
+ return ()=>{
37
+ if ('requestIdleCallback' in window) window.cancelIdleCallback(idleHandle);
38
+ else clearTimeout(idleHandle);
39
+ window.removeEventListener('keydown', handleKeyDown);
40
+ };
41
+ }, [
42
+ loadSearch
43
+ ]);
44
+ useEffect(()=>{
45
+ if (isLoaded && 'keyboard' === triggerRef.current) {
46
+ const interval = setInterval(()=>{
47
+ const button = document.querySelector('.DocSearch-Button:not(.DocSearch-Fake-Button)');
48
+ if (button) {
49
+ button.click();
50
+ clearInterval(interval);
51
+ triggerRef.current = null;
52
+ }
53
+ }, 50);
54
+ const timeout = setTimeout(()=>clearInterval(interval), 5000);
55
+ return ()=>{
56
+ clearInterval(interval);
57
+ clearTimeout(timeout);
58
+ };
59
+ }
60
+ }, [
61
+ isLoaded
62
+ ]);
63
+ return /*#__PURE__*/ jsx(Fragment, {
64
+ children: isLoaded ? /*#__PURE__*/ jsx(Suspense, {
65
+ fallback: /*#__PURE__*/ jsx(FakeSearchButton, {
66
+ placeholder: placeholder,
67
+ onMouseEnter: ()=>loadSearch('hover')
68
+ }),
69
+ children: /*#__PURE__*/ jsx(RealSearch, {
70
+ ...props
71
+ })
72
+ }) : /*#__PURE__*/ jsx(FakeSearchButton, {
73
+ placeholder: placeholder,
74
+ onClick: ()=>loadSearch('hover'),
75
+ onMouseEnter: ()=>loadSearch('hover')
76
+ })
77
+ });
78
+ }
79
+ function FakeSearchButton({ onClick, onMouseEnter, placeholder = 'Search' }) {
80
+ const [modifierKey, setModifierKey] = useState(null);
81
+ useEffect(()=>{
82
+ const isMac = /(Mac|iPhone|iPod|iPad)/i.test("u" > typeof navigator ? navigator.platform : '');
83
+ setModifierKey(isMac ? '⌘' : 'Ctrl');
84
+ }, []);
85
+ return /*#__PURE__*/ jsxs("button", {
86
+ type: "button",
87
+ className: "DocSearch DocSearch-Button DocSearch-Fake-Button",
88
+ "aria-label": "Search",
89
+ onClick: onClick,
90
+ onMouseEnter: onMouseEnter,
91
+ children: [
92
+ /*#__PURE__*/ jsxs("span", {
93
+ className: "DocSearch-Button-Container",
94
+ children: [
95
+ /*#__PURE__*/ jsx("svg", {
96
+ width: "20",
97
+ height: "20",
98
+ className: "DocSearch-Search-Icon",
99
+ viewBox: "0 0 20 20",
100
+ children: /*#__PURE__*/ jsx("path", {
101
+ d: "M14.386 14.386l4.0877 4.0877-4.0877-4.0877c-2.9418 2.9419-7.7115 2.9419-10.6533 0-2.9419-2.9418-2.9419-7.7115 0-10.6533 2.9418-2.9419 7.7115-2.9419 10.6533 0 2.9419 2.9418 2.9419 7.7115 0 10.6533z",
102
+ stroke: "currentColor",
103
+ fill: "none",
104
+ fillRule: "evenodd",
105
+ strokeLinecap: "round",
106
+ strokeLinejoin: "round"
107
+ })
108
+ }),
109
+ /*#__PURE__*/ jsx("span", {
110
+ className: "DocSearch-Button-Placeholder",
111
+ children: placeholder
112
+ })
113
+ ]
114
+ }),
115
+ /*#__PURE__*/ jsxs("span", {
116
+ className: "DocSearch-Button-Keys",
117
+ children: [
118
+ /*#__PURE__*/ jsx("kbd", {
119
+ className: "DocSearch-Button-Key",
120
+ children: modifierKey
121
+ }),
122
+ /*#__PURE__*/ jsx("kbd", {
123
+ className: "DocSearch-Button-Key",
124
+ children: "K"
125
+ })
126
+ ]
127
+ })
128
+ ]
129
+ });
130
+ }
131
+ export { Search };
@@ -0,0 +1,2 @@
1
+ export { type Locales, RU_LOCALES, ZH_LOCALES } from './locales.js';
2
+ export { Search, type SearchProps } from './Search.js';
@@ -0,0 +1,2 @@
1
+ export { RU_LOCALES, ZH_LOCALES } from "./locales.js";
2
+ export { Search } from "./Search.js";
@@ -0,0 +1,7 @@
1
+ import type { DocSearchProps } from 'typesense-docsearch-react';
2
+ export type Locales = Record<string, {
3
+ translations: DocSearchProps['translations'];
4
+ placeholder: string;
5
+ }>;
6
+ export declare const ZH_LOCALES: Locales;
7
+ export declare const RU_LOCALES: Locales;
@@ -0,0 +1,87 @@
1
+ const ZH_LOCALES = {
2
+ zh: {
3
+ placeholder: '搜索文档',
4
+ translations: {
5
+ button: {
6
+ buttonText: '搜索',
7
+ buttonAriaLabel: '搜索'
8
+ },
9
+ modal: {
10
+ searchBox: {
11
+ resetButtonTitle: '清除查询条件',
12
+ resetButtonAriaLabel: '清除查询条件',
13
+ cancelButtonText: '取消',
14
+ cancelButtonAriaLabel: '取消'
15
+ },
16
+ startScreen: {
17
+ recentSearchesTitle: '搜索历史',
18
+ noRecentSearchesText: '没有搜索历史',
19
+ saveRecentSearchButtonTitle: '保存至搜索历史',
20
+ removeRecentSearchButtonTitle: '从搜索历史中移除',
21
+ favoriteSearchesTitle: '收藏',
22
+ removeFavoriteSearchButtonTitle: '从收藏中移除'
23
+ },
24
+ errorScreen: {
25
+ titleText: '无法获取结果',
26
+ helpText: '你可能需要检查你的网络连接'
27
+ },
28
+ footer: {
29
+ selectText: '选择',
30
+ navigateText: '切换',
31
+ closeText: '关闭',
32
+ searchByText: '搜索提供者'
33
+ },
34
+ noResultsScreen: {
35
+ noResultsText: '无法找到相关结果',
36
+ suggestedQueryText: '你可以尝试查询',
37
+ reportMissingResultsText: '你认为该查询应该有结果?',
38
+ reportMissingResultsLinkText: '点击反馈'
39
+ }
40
+ }
41
+ }
42
+ }
43
+ };
44
+ const RU_LOCALES = {
45
+ ru: {
46
+ placeholder: 'Поиск в документации',
47
+ translations: {
48
+ button: {
49
+ buttonText: 'Поиск',
50
+ buttonAriaLabel: 'Поиск'
51
+ },
52
+ modal: {
53
+ searchBox: {
54
+ resetButtonTitle: 'Очистить поиск',
55
+ resetButtonAriaLabel: 'Очистить поиск',
56
+ cancelButtonText: 'Закрыть',
57
+ cancelButtonAriaLabel: 'Закрыть'
58
+ },
59
+ startScreen: {
60
+ recentSearchesTitle: 'История поиска',
61
+ noRecentSearchesText: 'Нет истории поиска',
62
+ saveRecentSearchButtonTitle: 'Сохранить в истории поиска',
63
+ removeRecentSearchButtonTitle: 'Удалить из истории поиска',
64
+ favoriteSearchesTitle: 'Избранное',
65
+ removeFavoriteSearchButtonTitle: 'Удалить из избранного'
66
+ },
67
+ errorScreen: {
68
+ titleText: 'Невозможно получить результаты',
69
+ helpText: 'Проверьте подключение к Интернету'
70
+ },
71
+ footer: {
72
+ selectText: 'выбрать',
73
+ navigateText: 'перейти',
74
+ closeText: 'закрыть',
75
+ searchByText: 'поиск от'
76
+ },
77
+ noResultsScreen: {
78
+ noResultsText: 'Ничего не найдено',
79
+ suggestedQueryText: 'Попробуйте изменить запрос',
80
+ reportMissingResultsText: 'Считаете, что результаты должны быть?',
81
+ reportMissingResultsLinkText: 'Сообщите об этом'
82
+ }
83
+ }
84
+ }
85
+ }
86
+ };
87
+ export { RU_LOCALES, ZH_LOCALES };
@@ -0,0 +1,42 @@
1
+ import type { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections';
2
+ export interface Hierarchy {
3
+ [key: string]: string | null | undefined;
4
+ lvl0: string | null;
5
+ lvl1: string | null;
6
+ lvl2: string | null;
7
+ lvl3: string | null;
8
+ lvl4: string | null;
9
+ lvl5: string | null;
10
+ lvl6: string | null;
11
+ }
12
+ export interface RecordWeight {
13
+ page_rank: number;
14
+ level: number;
15
+ position: number;
16
+ position_descending: number;
17
+ }
18
+ export interface DocSearchRecord {
19
+ objectID: string;
20
+ url: string;
21
+ url_without_anchor: string;
22
+ anchor: string | null;
23
+ content: string | null;
24
+ hierarchy: Hierarchy;
25
+ hierarchy_radio: Hierarchy;
26
+ type: string;
27
+ weight: RecordWeight;
28
+ version?: string;
29
+ language?: string;
30
+ [key: string]: any;
31
+ }
32
+ export interface FieldsParams {
33
+ locale: string;
34
+ isVersioned: boolean;
35
+ }
36
+ export interface CustomCollectionSettings {
37
+ token_separators?: CollectionCreateSchema['token_separators'];
38
+ symbols_to_index?: CollectionCreateSchema['symbols_to_index'];
39
+ fields?: (params: FieldsParams) => CollectionCreateSchema['fields'];
40
+ enable_nested_fields?: CollectionCreateSchema['enable_nested_fields'];
41
+ }
42
+ export type CustomCollectionSettingsConfig = CustomCollectionSettings | Record<string, CustomCollectionSettings>;
package/dist/types.js ADDED
File without changes
@@ -0,0 +1,50 @@
1
+ import type { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections';
2
+ import type { ConfigurationOptions } from 'typesense/lib/Typesense/Configuration';
3
+ import type { DocSearchRecord, CustomCollectionSettings, FieldsParams } from './types.js';
4
+ export interface TypesenseHelperOptions {
5
+ config: ConfigurationOptions;
6
+ aliasName: string;
7
+ collectionNameTmp: string;
8
+ customSettings: CustomCollectionSettings | null;
9
+ locale: string;
10
+ isVersioned: boolean;
11
+ }
12
+ export declare class TypesenseHelper {
13
+ private typesenseClient;
14
+ private aliasName;
15
+ private collectionNameTmp;
16
+ private collectionLocale;
17
+ private customSettings;
18
+ private isVersioned;
19
+ private typesenseVersion;
20
+ constructor(options: TypesenseHelperOptions);
21
+ init(): Promise<void>;
22
+ createTmpCollection(): Promise<void>;
23
+ addRecords(records: DocSearchRecord[], fileName: string, fromSitemap: boolean, padLength?: number): Promise<number>;
24
+ commitTmpCollection(): Promise<void>;
25
+ static transformRecord(record: DocSearchRecord, isVersioned: boolean): any;
26
+ private getOldCollectionName;
27
+ private transferSynonyms;
28
+ private transferOverrides;
29
+ }
30
+ /**
31
+ * Returns the default collection fields used when creating a Typesense collection.
32
+ *
33
+ * Use this when you need to customize specific fields without redefining the entire schema.
34
+ * The `version` field is automatically included when `isVersioned` is `true`.
35
+ *
36
+ * @param locale - The locale used for text fields (e.g. `'en'`, `'zh'`).
37
+ * @param isVersioned - When `true`, appends the `version` field to the returned fields.
38
+ *
39
+ * @example
40
+ * // Adding a custom field while keeping defaults:
41
+ * customLocaleCollectionSettings: {
42
+ * en: {
43
+ * fields: (params) => [
44
+ * ...getDefaultCollectionFields(params),
45
+ * { name: 'my_custom_field', type: 'string', locale },
46
+ * ],
47
+ * },
48
+ * }
49
+ */
50
+ export declare function getDefaultCollectionFields({ locale, isVersioned, }: FieldsParams): CollectionCreateSchema['fields'];
@@ -0,0 +1,204 @@
1
+ import { Client } from "typesense";
2
+ class TypesenseHelper {
3
+ typesenseClient;
4
+ aliasName;
5
+ collectionNameTmp;
6
+ collectionLocale;
7
+ customSettings;
8
+ isVersioned;
9
+ typesenseVersion = 0;
10
+ constructor(options){
11
+ const clientConfig = {
12
+ ...options.config
13
+ };
14
+ clientConfig.connectionTimeoutSeconds = clientConfig.connectionTimeoutSeconds || 1800;
15
+ clientConfig.retryIntervalSeconds = clientConfig.retryIntervalSeconds || 1;
16
+ clientConfig.numRetries = clientConfig.numRetries || 3;
17
+ clientConfig.healthcheckIntervalSeconds = clientConfig.healthcheckIntervalSeconds || 60;
18
+ clientConfig.logLevel = clientConfig.logLevel || 'error';
19
+ this.typesenseClient = new Client(clientConfig);
20
+ this.aliasName = options.aliasName;
21
+ this.collectionNameTmp = options.collectionNameTmp;
22
+ this.collectionLocale = options.locale || process.env.TYPESENSE_COLLECTION_LOCALE || 'en';
23
+ this.customSettings = options.customSettings;
24
+ this.isVersioned = options.isVersioned;
25
+ }
26
+ async init() {
27
+ const debugInfo = await this.typesenseClient.debug.retrieve();
28
+ const version = debugInfo.version;
29
+ if ('nightly' === version) this.typesenseVersion = 30;
30
+ else this.typesenseVersion = parseInt(version.split('.')[0], 10);
31
+ }
32
+ async createTmpCollection() {
33
+ if (0 === this.typesenseVersion) await this.init();
34
+ try {
35
+ await this.typesenseClient.collections(this.collectionNameTmp).delete();
36
+ } catch (error) {
37
+ if (error?.httpStatus !== 404) {
38
+ console.error('[TypesensePlugin] Error:');
39
+ throw error;
40
+ }
41
+ }
42
+ const schema = {
43
+ name: this.collectionNameTmp,
44
+ fields: getDefaultCollectionFields({
45
+ locale: this.collectionLocale,
46
+ isVersioned: this.isVersioned
47
+ }),
48
+ default_sorting_field: 'item_priority',
49
+ token_separators: [
50
+ '_',
51
+ '-'
52
+ ]
53
+ };
54
+ if (this.customSettings) {
55
+ if (this.customSettings.token_separators) schema.token_separators = this.customSettings.token_separators;
56
+ if (this.customSettings.fields) schema.fields = this.customSettings.fields({
57
+ locale: this.collectionLocale,
58
+ isVersioned: this.isVersioned
59
+ });
60
+ if (this.customSettings.symbols_to_index) schema.symbols_to_index = this.customSettings.symbols_to_index;
61
+ if (void 0 !== this.customSettings.enable_nested_fields) schema.enable_nested_fields = this.customSettings.enable_nested_fields;
62
+ }
63
+ await this.typesenseClient.collections().create(schema);
64
+ }
65
+ async addRecords(records, fileName, fromSitemap, padLength = 40) {
66
+ const transformedRecords = records.map((r)=>TypesenseHelper.transformRecord(r, this.isVersioned));
67
+ const recordCount = transformedRecords.length;
68
+ const results = await this.typesenseClient.collections(this.collectionNameTmp).documents().import(transformedRecords, {
69
+ action: 'create'
70
+ });
71
+ const failedItems = results.filter((r)=>false === r.success);
72
+ if (failedItems.length > 0) {
73
+ console.error('Typesense Import Failed:', JSON.stringify(failedItems, null, 2));
74
+ throw new Error('Failed to import some records');
75
+ }
76
+ const iconColor = fromSitemap ? '\x1b[36m' : '\x1b[32m';
77
+ const fillerLength = Math.max(2, padLength - fileName.length);
78
+ const filler = '\x1b[90m' + '.'.repeat(fillerLength) + '\x1b[0m';
79
+ const paddedCount = recordCount.toString().padStart(4, ' ');
80
+ console.log(` ${iconColor}✔\x1b[0m \x1b[37m${fileName}\x1b[0m ${filler} \x1b[33m${paddedCount}\x1b[0m \x1b[90mrecords\x1b[0m`);
81
+ return recordCount;
82
+ }
83
+ async commitTmpCollection() {
84
+ const oldCollectionName = await this.getOldCollectionName();
85
+ if (oldCollectionName) {
86
+ await this.transferSynonyms(oldCollectionName);
87
+ await this.transferOverrides(oldCollectionName);
88
+ }
89
+ await this.typesenseClient.aliases().upsert(this.aliasName, {
90
+ collection_name: this.collectionNameTmp
91
+ });
92
+ if (oldCollectionName) await this.typesenseClient.collections(oldCollectionName).delete();
93
+ }
94
+ static transformRecord(record, isVersioned) {
95
+ const transformedRecord = {};
96
+ const excludeKeys = [
97
+ 'weight',
98
+ 'language',
99
+ 'tags',
100
+ '.*_tag'
101
+ ];
102
+ for(const key in record)if (null !== record[key] && void 0 !== record[key] && !excludeKeys.includes(key)) transformedRecord[key] = record[key];
103
+ if (record.weight) transformedRecord['item_priority'] = 1000000000 * record.weight.page_rank + 1000 * record.weight.level + record.weight.position_descending;
104
+ else transformedRecord['item_priority'] = 0;
105
+ for(let x = 0; x < 7; x++){
106
+ const lvlKey = `lvl${x}`;
107
+ if (record.hierarchy && null != record.hierarchy[lvlKey]) transformedRecord[`hierarchy.lvl${x}`] = record.hierarchy[lvlKey];
108
+ if (record.hierarchy_radio && null != record.hierarchy_radio[lvlKey]) transformedRecord[`hierarchy_radio.lvl${x}`] = record.hierarchy_radio[lvlKey];
109
+ }
110
+ if (isVersioned && record.version && 'string' == typeof record.version) transformedRecord['version'] = record.version.split(',');
111
+ else if (!isVersioned) delete transformedRecord['version'];
112
+ return transformedRecord;
113
+ }
114
+ async getOldCollectionName() {
115
+ try {
116
+ const alias = await this.typesenseClient.aliases(this.aliasName).retrieve();
117
+ return alias.collection_name;
118
+ } catch (error) {
119
+ if (error?.httpStatus === 404) return null;
120
+ throw error;
121
+ }
122
+ }
123
+ async transferSynonyms(oldCollectionName) {
124
+ if (this.typesenseVersion >= 30) {
125
+ const oldCollection = await this.typesenseClient.collections(oldCollectionName).retrieve();
126
+ const synonyms = oldCollection.synonym_sets || [];
127
+ for (const syn of synonyms)await this.typesenseClient.collections(this.collectionNameTmp).synonyms().upsert(syn.id, syn);
128
+ return;
129
+ }
130
+ const result = await this.typesenseClient.collections(oldCollectionName).synonyms().retrieve();
131
+ const synonyms = result.synonyms || [];
132
+ for (const synonym of synonyms){
133
+ const { id, ...synonymKeys } = synonym;
134
+ await this.typesenseClient.collections(this.collectionNameTmp).synonyms().upsert(synonym.id, synonymKeys);
135
+ }
136
+ }
137
+ async transferOverrides(oldCollectionName) {
138
+ if (this.typesenseVersion >= 30) {
139
+ const oldCollection = await this.typesenseClient.collections(oldCollectionName).retrieve();
140
+ const curations = oldCollection.curation_sets || [];
141
+ for (const cur of curations)await this.typesenseClient.collections(this.collectionNameTmp).overrides().upsert(cur.id, cur);
142
+ return;
143
+ }
144
+ const result = await this.typesenseClient.collections(oldCollectionName).overrides().retrieve();
145
+ const overrides = result.overrides || [];
146
+ for (const override of overrides){
147
+ const { id, ...overrideKeys } = override;
148
+ await this.typesenseClient.collections(this.collectionNameTmp).overrides().upsert(override.id, overrideKeys);
149
+ }
150
+ }
151
+ }
152
+ function getDefaultCollectionFields({ locale, isVersioned }) {
153
+ const baseFields = [
154
+ {
155
+ name: 'anchor',
156
+ type: 'string',
157
+ optional: true
158
+ },
159
+ {
160
+ name: 'content',
161
+ type: 'string',
162
+ locale,
163
+ optional: true
164
+ },
165
+ {
166
+ name: 'url',
167
+ type: 'string',
168
+ facet: true
169
+ },
170
+ {
171
+ name: 'url_without_anchor',
172
+ type: 'string',
173
+ facet: true,
174
+ optional: true
175
+ },
176
+ ...Array.from({
177
+ length: 7
178
+ }).map((_, i)=>({
179
+ name: `hierarchy.lvl${i}`,
180
+ type: 'string',
181
+ facet: true,
182
+ locale,
183
+ optional: true
184
+ })),
185
+ {
186
+ name: 'type',
187
+ type: 'string',
188
+ facet: true,
189
+ optional: true
190
+ },
191
+ {
192
+ name: 'item_priority',
193
+ type: 'int64'
194
+ }
195
+ ];
196
+ if (isVersioned) baseFields.push({
197
+ name: 'version',
198
+ type: 'string',
199
+ facet: true,
200
+ optional: true
201
+ });
202
+ return baseFields;
203
+ }
204
+ export { TypesenseHelper, getDefaultCollectionFields };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "rspress-plugin-typesense",
3
+ "description": "A plugin to add Typesense-powered search to your Rspress site",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ },
11
+ "./runtime": {
12
+ "types": "./dist/runtime/index.d.ts",
13
+ "default": "./dist/runtime/index.js"
14
+ }
15
+ },
16
+ "types": "./dist/index.d.ts",
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "scripts": {
21
+ "build": "rslib build",
22
+ "dev": "rslib build --watch"
23
+ },
24
+ "devDependencies": {
25
+ "@rslib/core": "^0.20.1",
26
+ "@types/node": "^24.12.0",
27
+ "rsbuild-plugin-publint": "^0.3.4",
28
+ "typescript": "^6.0.2"
29
+ },
30
+ "peerDependencies": {
31
+ "@rspress/core": "^2.0.8"
32
+ },
33
+ "dependencies": {
34
+ "cheerio": "^1.2.0",
35
+ "typesense-docsearch-css": "^0.4.1",
36
+ "typesense-docsearch-react": "^3.4.1"
37
+ },
38
+ "keywords": [
39
+ "typesense",
40
+ "documentation-search",
41
+ "search",
42
+ "rspress-plugin",
43
+ "rspress",
44
+ "plugin"
45
+ ],
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/typesense/rspress-plugin-typesense.git"
49
+ },
50
+ "bugs": "https://github.com/typesense/rspress-plugin-typesense/issues",
51
+ "license": "Apache-2.0",
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }