@rubixstudios/payload-typesense 1.6.13 → 1.8.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.
Files changed (186) hide show
  1. package/README.md +109 -114
  2. package/dist/components/ThemeProvider.d.ts +4 -3
  3. package/dist/components/ThemeProvider.d.ts.map +1 -1
  4. package/dist/components/ThemeProvider.js +15 -5
  5. package/dist/components/icons/clockIcon.d.ts +2 -0
  6. package/dist/components/icons/clockIcon.d.ts.map +1 -0
  7. package/dist/components/icons/clockIcon.js +16 -0
  8. package/dist/components/icons/collectionIcon.d.ts +2 -0
  9. package/dist/components/icons/collectionIcon.d.ts.map +1 -0
  10. package/dist/components/icons/collectionIcon.js +16 -0
  11. package/dist/components/icons/errorIcon.d.ts +2 -0
  12. package/dist/components/icons/errorIcon.d.ts.map +1 -0
  13. package/dist/components/icons/errorIcon.js +16 -0
  14. package/dist/components/icons/index.d.ts +7 -0
  15. package/dist/components/icons/index.d.ts.map +1 -0
  16. package/dist/components/icons/index.js +6 -0
  17. package/dist/components/icons/noResultsIcon.d.ts +4 -0
  18. package/dist/components/icons/noResultsIcon.d.ts.map +1 -0
  19. package/dist/components/icons/noResultsIcon.js +19 -0
  20. package/dist/components/icons/searchIcon.d.ts +4 -0
  21. package/dist/components/icons/searchIcon.d.ts.map +1 -0
  22. package/dist/components/icons/searchIcon.js +16 -0
  23. package/dist/components/icons/xIcon.d.ts +2 -0
  24. package/dist/components/icons/xIcon.d.ts.map +1 -0
  25. package/dist/components/icons/xIcon.js +17 -0
  26. package/dist/components/index.d.ts +10 -5
  27. package/dist/components/index.d.ts.map +1 -1
  28. package/dist/components/index.js +6 -3
  29. package/dist/components/render/Content.d.ts +26 -0
  30. package/dist/components/render/Content.d.ts.map +1 -0
  31. package/dist/components/render/Content.js +144 -0
  32. package/dist/components/render/Dialog.d.ts +20 -0
  33. package/dist/components/render/Dialog.d.ts.map +1 -0
  34. package/dist/components/render/Dialog.js +43 -0
  35. package/dist/components/render/Header.d.ts +4 -4
  36. package/dist/components/render/Header.d.ts.map +1 -1
  37. package/dist/components/render/Header.js +20 -39
  38. package/dist/components/render/Highlight.d.ts +3 -0
  39. package/dist/components/render/Highlight.d.ts.map +1 -0
  40. package/dist/components/render/Highlight.js +22 -0
  41. package/dist/components/render/NoResults.d.ts +4 -4
  42. package/dist/components/render/NoResults.d.ts.map +1 -1
  43. package/dist/components/render/NoResults.js +21 -45
  44. package/dist/components/render/ResultError.d.ts +4 -4
  45. package/dist/components/render/ResultError.d.ts.map +1 -1
  46. package/dist/components/render/ResultError.js +14 -38
  47. package/dist/components/render/Results.d.ts +7 -6
  48. package/dist/components/render/Results.d.ts.map +1 -1
  49. package/dist/components/render/Results.js +70 -141
  50. package/dist/components/render/index.d.ts +7 -4
  51. package/dist/components/render/index.d.ts.map +1 -1
  52. package/dist/components/render/index.js +7 -4
  53. package/dist/components/search/HeadlessDialog.d.ts +5 -0
  54. package/dist/components/search/HeadlessDialog.d.ts.map +1 -0
  55. package/dist/components/search/HeadlessDialog.js +254 -0
  56. package/dist/components/search/HeadlessInput.d.ts +5 -0
  57. package/dist/components/search/HeadlessInput.d.ts.map +1 -0
  58. package/dist/components/search/HeadlessInput.js +193 -0
  59. package/dist/components/search/SearchStyles.d.ts +8 -0
  60. package/dist/components/search/SearchStyles.d.ts.map +1 -0
  61. package/dist/components/search/SearchStyles.js +9 -0
  62. package/dist/components/themes/constant.d.ts +3 -0
  63. package/dist/components/themes/constant.d.ts.map +1 -0
  64. package/dist/components/themes/constant.js +75 -0
  65. package/dist/components/themes/hooks.d.ts +4 -42
  66. package/dist/components/themes/hooks.d.ts.map +1 -1
  67. package/dist/components/themes/hooks.js +35 -95
  68. package/dist/components/themes/index.d.ts +1 -0
  69. package/dist/components/themes/index.d.ts.map +1 -1
  70. package/dist/components/themes/index.js +1 -0
  71. package/dist/components/themes/themes.d.ts.map +1 -1
  72. package/dist/components/themes/themes.js +66 -27
  73. package/dist/components/themes/types.d.ts +62 -2
  74. package/dist/components/themes/types.d.ts.map +1 -1
  75. package/dist/components/themes/utils.d.ts +13 -18
  76. package/dist/components/themes/utils.d.ts.map +1 -1
  77. package/dist/components/themes/utils.js +466 -344
  78. package/dist/components/utils/decodeEntities.d.ts +2 -0
  79. package/dist/components/utils/decodeEntities.d.ts.map +1 -0
  80. package/dist/components/utils/decodeEntities.js +23 -0
  81. package/dist/components/utils/index.d.ts +4 -0
  82. package/dist/components/utils/index.d.ts.map +1 -0
  83. package/dist/components/utils/index.js +3 -0
  84. package/dist/components/utils/toKebab.d.ts +2 -0
  85. package/dist/components/utils/toKebab.d.ts.map +1 -0
  86. package/dist/components/utils/toKebab.js +3 -0
  87. package/dist/components/utils/toText.d.ts +2 -0
  88. package/dist/components/utils/toText.d.ts.map +1 -0
  89. package/dist/components/utils/toText.js +3 -0
  90. package/dist/endpoints/handler/createAdvancedSearch.d.ts +1 -1
  91. package/dist/endpoints/handler/createAdvancedSearch.d.ts.map +1 -1
  92. package/dist/endpoints/handler/createAdvancedSearch.js +133 -11
  93. package/dist/endpoints/handler/createCollections.d.ts +1 -1
  94. package/dist/endpoints/handler/createCollections.d.ts.map +1 -1
  95. package/dist/endpoints/handler/createCollections.js +8 -8
  96. package/dist/endpoints/handler/createSearch.d.ts +1 -1
  97. package/dist/endpoints/handler/createSearch.d.ts.map +1 -1
  98. package/dist/endpoints/handler/createSearch.js +85 -110
  99. package/dist/endpoints/handler/createSuggest.d.ts +1 -1
  100. package/dist/endpoints/handler/createSuggest.d.ts.map +1 -1
  101. package/dist/endpoints/handler/createSuggest.js +39 -22
  102. package/dist/endpoints/health.d.ts +2 -2
  103. package/dist/endpoints/health.d.ts.map +1 -1
  104. package/dist/endpoints/health.js +58 -52
  105. package/dist/endpoints/search.d.ts +2 -9
  106. package/dist/endpoints/search.d.ts.map +1 -1
  107. package/dist/endpoints/search.js +17 -16
  108. package/dist/{utils → hooks}/useDebounce.d.ts.map +1 -1
  109. package/dist/{utils → hooks}/useDebounce.js +2 -2
  110. package/dist/hooks/useSearch.d.ts +21 -0
  111. package/dist/hooks/useSearch.d.ts.map +1 -0
  112. package/dist/hooks/useSearch.js +126 -0
  113. package/dist/index.d.ts.map +1 -1
  114. package/dist/index.js +45 -34
  115. package/dist/lib/cache.d.ts.map +1 -1
  116. package/dist/lib/cache.js +54 -25
  117. package/dist/lib/client.d.ts +1 -1
  118. package/dist/lib/client.d.ts.map +1 -1
  119. package/dist/lib/client.js +35 -31
  120. package/dist/lib/hooks.d.ts +3 -11
  121. package/dist/lib/hooks.d.ts.map +1 -1
  122. package/dist/lib/hooks.js +15 -45
  123. package/dist/lib/initialization.d.ts +1 -1
  124. package/dist/lib/initialization.d.ts.map +1 -1
  125. package/dist/lib/initialization.js +54 -52
  126. package/dist/lib/schema-mapper.d.ts +3 -6
  127. package/dist/lib/schema-mapper.d.ts.map +1 -1
  128. package/dist/lib/schema-mapper.js +90 -84
  129. package/dist/lib/search-dialog.d.ts +169 -0
  130. package/dist/lib/search-dialog.d.ts.map +1 -0
  131. package/dist/lib/search-dialog.js +4 -0
  132. package/dist/lib/search-input.d.ts +93 -0
  133. package/dist/lib/search-input.d.ts.map +1 -0
  134. package/dist/lib/search-pagination.d.ts +38 -0
  135. package/dist/lib/search-pagination.d.ts.map +1 -0
  136. package/dist/lib/search-pagination.js +4 -0
  137. package/dist/lib/search.d.ts +25 -0
  138. package/dist/lib/search.d.ts.map +1 -0
  139. package/dist/lib/search.js +59 -0
  140. package/dist/lib/validation.d.ts +57 -39
  141. package/dist/lib/validation.d.ts.map +1 -1
  142. package/dist/lib/validation.js +92 -66
  143. package/dist/types.d.ts +193 -127
  144. package/dist/types.d.ts.map +1 -1
  145. package/dist/types.js +1 -1
  146. package/dist/utils/buildError.d.ts +1 -1
  147. package/dist/utils/buildError.d.ts.map +1 -1
  148. package/dist/utils/buildError.js +2 -2
  149. package/dist/utils/ensureCollection.d.ts +2 -2
  150. package/dist/utils/ensureCollection.d.ts.map +1 -1
  151. package/dist/utils/ensureCollection.js +138 -22
  152. package/dist/utils/extractText.d.ts.map +1 -1
  153. package/dist/utils/extractText.js +11 -8
  154. package/dist/utils/getCacheStats.d.ts.map +1 -1
  155. package/dist/utils/getCacheStats.js +1 -8
  156. package/dist/utils/getCollectionInfo.d.ts.map +1 -1
  157. package/dist/utils/getCollectionInfo.js +1 -1
  158. package/dist/utils/getCollections.d.ts +11 -0
  159. package/dist/utils/getCollections.d.ts.map +1 -0
  160. package/dist/utils/getCollections.js +152 -0
  161. package/dist/utils/keyboard.d.ts +4 -4
  162. package/dist/utils/keyboard.d.ts.map +1 -1
  163. package/dist/utils/keyboard.js +21 -23
  164. package/dist/utils/sortResults.d.ts +3 -0
  165. package/dist/utils/sortResults.d.ts.map +1 -0
  166. package/dist/utils/sortResults.js +103 -0
  167. package/dist/utils/testConnection.d.ts +1 -1
  168. package/dist/utils/testConnection.d.ts.map +1 -1
  169. package/dist/utils/testConnection.js +2 -2
  170. package/dist/utils/vectorSearch.d.ts +2 -5
  171. package/dist/utils/vectorSearch.d.ts.map +1 -1
  172. package/dist/utils/vectorSearch.js +24 -12
  173. package/package.json +16 -15
  174. package/dist/components/HeadlessSearchInput.d.ts +0 -5
  175. package/dist/components/HeadlessSearchInput.d.ts.map +0 -1
  176. package/dist/components/HeadlessSearchInput.js +0 -204
  177. package/dist/lib/headlessSearch.d.ts +0 -86
  178. package/dist/lib/headlessSearch.d.ts.map +0 -1
  179. package/dist/utils/getAllCollections.d.ts +0 -11
  180. package/dist/utils/getAllCollections.d.ts.map +0 -1
  181. package/dist/utils/getAllCollections.js +0 -103
  182. package/dist/utils/useSearch.d.ts +0 -18
  183. package/dist/utils/useSearch.d.ts.map +0 -1
  184. package/dist/utils/useSearch.js +0 -66
  185. /package/dist/{utils → hooks}/useDebounce.d.ts +0 -0
  186. /package/dist/lib/{headlessSearch.js → search-input.js} +0 -0
@@ -1,6 +1,6 @@
1
- export const buildError = (isTypesenseHealthy, hasCollections)=>{
1
+ export const buildError = (health, hasCollections)=>{
2
2
  const errors = [];
3
- if (!isTypesenseHealthy) {
3
+ if (!health) {
4
4
  errors.push('Typesense connection failed');
5
5
  }
6
6
  if (!hasCollections) {
@@ -1,4 +1,4 @@
1
1
  import type Typesense from 'typesense';
2
- import { type CollectionSchema, type TypesenseConfig } from '../types.js';
3
- export declare const ensureCollection: (typesenseClient: Typesense.Client, collectionSlug: string, schema: CollectionSchema, vector?: NonNullable<TypesenseConfig['vectorSearch']>) => Promise<boolean>;
2
+ import { type CollectionSchema, type Readiness, type TypesenseConfig } from '../types.js';
3
+ export declare function ensureCollection(client: Typesense.Client, slug: string, schema: CollectionSchema, vector?: NonNullable<TypesenseConfig['vectorSearch']>, reconcile?: boolean): Promise<Readiness>;
4
4
  //# sourceMappingURL=ensureCollection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ensureCollection.d.ts","sourceRoot":"","sources":["../../src/utils/ensureCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAA;AAEzE,eAAO,MAAM,gBAAgB,oBACV,SAAS,CAAC,MAAM,kBACjB,MAAM,UACd,gBAAgB,WACf,WAAW,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,KACpD,OAAO,CAAC,OAAO,CAqCjB,CAAA"}
1
+ {"version":3,"file":"ensureCollection.d.ts","sourceRoot":"","sources":["../../src/utils/ensureCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAGtC,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,SAAS,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAA;AAEzF,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,SAAS,CAAC,MAAM,EACxB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,gBAAgB,EACxB,MAAM,CAAC,EAAE,WAAW,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,EACrD,SAAS,UAAQ,GAChB,OAAO,CAAC,SAAS,CAAC,CAuKpB"}
@@ -1,30 +1,146 @@
1
- export const ensureCollection = async (typesenseClient, collectionSlug, schema, vector)=>{
1
+ export async function ensureCollection(client, slug, schema, vector, reconcile = false) {
2
+ let existing;
2
3
  try {
3
- const existing = await typesenseClient.collections(collectionSlug).retrieve();
4
- if (vector?.enabled) {
5
- const hasEmbeddingField = existing.fields?.some((f)=>f.name === 'embedding');
6
- if (!hasEmbeddingField) {
7
- const embeddingField = schema.fields.find((f)=>f.name === 'embedding');
8
- if (embeddingField) {
9
- try {
10
- await typesenseClient.collections(collectionSlug).update({
11
- fields: [
12
- embeddingField
13
- ]
14
- });
15
- } catch (patchError) {
16
- console.warn(`Could not add embedding field to collection ${collectionSlug}: ${patchError instanceof Error ? patchError.message : 'Unknown error'}`);
17
- }
4
+ existing = await client.collections(slug).retrieve();
5
+ } catch (error) {
6
+ if (!error || typeof error !== 'object' || !('httpStatus' in error) || error.httpStatus !== 404) {
7
+ return {
8
+ available: false,
9
+ embedding: false
10
+ };
11
+ }
12
+ try {
13
+ existing = await client.collections().create(schema);
14
+ } catch (error) {
15
+ if (vector?.enabled) {
16
+ try {
17
+ await client.collections().create({
18
+ ...schema,
19
+ fields: schema.fields.filter((field)=>field.name !== 'embedding')
20
+ });
21
+ console.warn(`Created keyword collection ${slug} without embedding support`);
22
+ return {
23
+ available: true,
24
+ embedding: false
25
+ };
26
+ } catch {
27
+ // Another request may have created the collection.
18
28
  }
19
29
  }
30
+ try {
31
+ existing = await client.collections(slug).retrieve();
32
+ } catch {
33
+ console.warn(`Could not create collection ${slug}: ${error instanceof Error ? error.message : 'Unknown error'}`);
34
+ return {
35
+ available: false,
36
+ embedding: false
37
+ };
38
+ }
20
39
  }
21
- return true;
22
- } catch {
40
+ }
41
+ if (reconcile) {
42
+ const fields = [];
43
+ for (const field of schema.fields){
44
+ if (field.name === 'embedding' || field.name === 'id') continue;
45
+ const current = existing.fields.find((item)=>item.name === field.name);
46
+ if (!current) {
47
+ fields.push({
48
+ ...field,
49
+ optional: true
50
+ });
51
+ continue;
52
+ }
53
+ const facetChanged = Boolean(current.facet) !== Boolean(field.facet);
54
+ const sortChanged = field.sort !== undefined && Boolean(current.sort) !== field.sort;
55
+ if (!facetChanged && !sortChanged) continue;
56
+ fields.push({
57
+ name: field.name,
58
+ drop: true
59
+ }, {
60
+ ...current,
61
+ facet: field.facet ?? false,
62
+ ...field.sort !== undefined && {
63
+ sort: field.sort
64
+ }
65
+ });
66
+ }
67
+ if (fields.length) {
68
+ try {
69
+ existing = await client.collections(slug).update({
70
+ fields
71
+ });
72
+ } catch (error) {
73
+ console.warn(`Could not reconcile collection ${slug}: ${error instanceof Error ? error.message : 'Unknown error'}`);
74
+ }
75
+ }
76
+ }
77
+ function isIndexed(field) {
78
+ return field?.type === 'float[]' && (field.num_dim ?? 0) > 0 && field.index !== false;
79
+ }
80
+ const current = existing.fields.find((field)=>field.name === 'embedding');
81
+ if (!vector?.enabled) {
82
+ return {
83
+ available: true,
84
+ embedding: isIndexed(current)
85
+ };
86
+ }
87
+ const desired = schema.fields.find((field)=>field.name === 'embedding');
88
+ if (!desired) {
89
+ return {
90
+ available: true,
91
+ embedding: false
92
+ };
93
+ }
94
+ const expectedEmbedding = desired.embed;
95
+ const expectedDimensions = desired.num_dim;
96
+ function isReady(field) {
97
+ if (!field || !isIndexed(field)) return false;
98
+ if (expectedDimensions !== undefined && field.num_dim !== expectedDimensions) {
99
+ return false;
100
+ }
101
+ if (!expectedEmbedding) return true;
102
+ const actualEmbedding = field.embed;
103
+ if (!actualEmbedding) return false;
104
+ return actualEmbedding.model_config?.model_name === expectedEmbedding.model_config.model_name && actualEmbedding.from.length === expectedEmbedding.from.length && actualEmbedding.from.every((source, index)=>source === expectedEmbedding.from[index]);
105
+ }
106
+ if (isReady(current)) {
107
+ return {
108
+ available: true,
109
+ embedding: true
110
+ };
111
+ }
112
+ const fields = [];
113
+ if (current) {
114
+ fields.push({
115
+ name: 'embedding',
116
+ drop: true
117
+ });
118
+ }
119
+ fields.push(desired);
120
+ try {
121
+ existing = await client.collections(slug).update({
122
+ fields
123
+ });
124
+ return {
125
+ available: true,
126
+ embedding: isReady(existing.fields.find((field)=>field.name === 'embedding'))
127
+ };
128
+ } catch (error) {
23
129
  try {
24
- await typesenseClient.collections().create(schema);
25
- return true;
130
+ existing = await client.collections(slug).retrieve();
131
+ if (isReady(existing.fields.find((field)=>field.name === 'embedding'))) {
132
+ return {
133
+ available: true,
134
+ embedding: true
135
+ };
136
+ }
26
137
  } catch {
27
- return false;
138
+ // Preserve the original alteration error for logging.
28
139
  }
140
+ console.warn(`Could not configure embedding field for collection ${slug}: ${error instanceof Error ? error.message : 'Unknown error'}`);
141
+ return {
142
+ available: true,
143
+ embedding: false
144
+ };
29
145
  }
30
- };
146
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"extractText.d.ts","sourceRoot":"","sources":["../../src/utils/extractText.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,aAAc,OAAO,KAAG,MAsB/C,CAAA"}
1
+ {"version":3,"file":"extractText.d.ts","sourceRoot":"","sources":["../../src/utils/extractText.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,aAAc,OAAO,KAAG,MA2B/C,CAAA"}
@@ -4,15 +4,18 @@ export const extractText = (richText)=>{
4
4
  }
5
5
  const extract = (node)=>{
6
6
  if (typeof node === 'string') return node;
7
- if (node && typeof node === 'object') {
8
- if ('text' in node && typeof node.text === 'string') {
9
- return node.text;
10
- }
11
- if ('children' in node && Array.isArray(node.children)) {
12
- return node.children.map(extract).join('');
13
- }
7
+ if (!node || typeof node !== 'object') return '';
8
+ if ('type' in node && node.type === 'linebreak') {
9
+ return '\n';
10
+ }
11
+ if ('text' in node && typeof node.text === 'string') {
12
+ return node.text;
13
+ }
14
+ if ('children' in node && Array.isArray(node.children)) {
15
+ const separator = 'type' in node && (node.type === 'root' || node.type === 'list') ? '\n' : '';
16
+ return node.children.map(extract).filter(Boolean).join(separator);
14
17
  }
15
18
  return '';
16
19
  };
17
- return extract(richText.root);
20
+ return extract(richText.root).trim();
18
21
  };
@@ -1 +1 @@
1
- {"version":3,"file":"getCacheStats.d.ts","sourceRoot":"","sources":["../../src/utils/getCacheStats.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa;IAGtB,OAAO;IACP,OAAO;IACP,IAAI;CAEP,CAAA"}
1
+ {"version":3,"file":"getCacheStats.d.ts","sourceRoot":"","sources":["../../src/utils/getCacheStats.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa;;;;CAA+B,CAAA"}
@@ -1,9 +1,2 @@
1
1
  import { searchCache } from '../lib/cache.js';
2
- export const getCacheStats = ()=>{
3
- const stats = searchCache.getStats();
4
- return {
5
- hitRate: stats.hitRate || 0,
6
- maxSize: stats.maxSize,
7
- size: stats.size
8
- };
9
- };
2
+ export const getCacheStats = ()=>searchCache.getStats();
@@ -1 +1 @@
1
- {"version":3,"file":"getCollectionInfo.d.ts","sourceRoot":"","sources":["../../src/utils/getCollectionInfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,eAAO,MAAM,iBAAiB,WAAkB,SAAS,CAAC,MAAM,KAAG,OAAO,CAAC,MAAM,EAAE,CAOlF,CAAA"}
1
+ {"version":3,"file":"getCollectionInfo.d.ts","sourceRoot":"","sources":["../../src/utils/getCollectionInfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,eAAO,MAAM,iBAAiB,WAAkB,SAAS,CAAC,MAAM,KAAG,OAAO,CAAC,MAAM,EAAE,CAQlF,CAAA"}
@@ -1,7 +1,7 @@
1
1
  export const getCollectionInfo = async (client)=>{
2
2
  try {
3
3
  const collections = await client.collections().retrieve();
4
- return collections.map((c)=>c.name);
4
+ return collections.map((collection)=>collection.name);
5
5
  } catch {
6
6
  return [];
7
7
  }
@@ -0,0 +1,11 @@
1
+ import type Typesense from 'typesense';
2
+ import { type SearchParams, type TypesenseConfig } from '../types.js';
3
+ export declare const getCollections: (client: Typesense.Client, config: TypesenseConfig, query: string, options: Omit<SearchParams, 'q'> & {
4
+ collections?: string[];
5
+ filters: Record<string, unknown>;
6
+ page: number;
7
+ per_page: number;
8
+ sort_by?: string;
9
+ vector?: boolean;
10
+ }) => Promise<Response>;
11
+ //# sourceMappingURL=getCollections.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getCollections.d.ts","sourceRoot":"","sources":["../../src/utils/getCollections.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAItC,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAA;AAGrE,eAAO,MAAM,cAAc,WACjB,SAAS,CAAC,MAAM,UAChB,eAAe,SAChB,MAAM,WACJ,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,GAAG;IACjC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;IACtB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB,sBA8KF,CAAA"}
@@ -0,0 +1,152 @@
1
+ import { searchCache } from '../lib/cache.js';
2
+ import { buildParameters, getSearchMode } from '../lib/search.js';
3
+ import { getCompare } from './sortResults.js';
4
+ export const getCollections = async (client, config, query, options)=>{
5
+ try {
6
+ const enabledCollections = Object.entries(config.collections ?? {}).filter(([slug, collection])=>collection.enabled && (!options.collections?.length || options.collections.includes(slug)));
7
+ if (!enabledCollections.length) {
8
+ return Response.json({
9
+ error: 'No collections enabled for search'
10
+ }, {
11
+ status: 400
12
+ });
13
+ }
14
+ const multiple = enabledCollections.length > 1;
15
+ const mode = getSearchMode(config, options);
16
+ let compare;
17
+ if (multiple) {
18
+ try {
19
+ compare = getCompare(options.sort_by, mode);
20
+ } catch (error) {
21
+ return Response.json({
22
+ error: error instanceof Error ? error.message : 'Invalid sort_by parameter'
23
+ }, {
24
+ status: 400
25
+ });
26
+ }
27
+ }
28
+ const limit = multiple ? options.page * options.per_page : options.per_page;
29
+ const perPage = Math.min(limit, 250);
30
+ const cacheKey = {
31
+ ...options,
32
+ settings: config.settings,
33
+ vectorSearch: config.vectorSearch && {
34
+ enabled: config.vectorSearch.enabled,
35
+ alpha: config.vectorSearch.alpha,
36
+ k: config.vectorSearch.k,
37
+ distanceThreshold: config.vectorSearch.distanceThreshold
38
+ },
39
+ fields: enabledCollections.map(([slug, collection])=>[
40
+ slug,
41
+ collection.searchFields
42
+ ]),
43
+ collections: enabledCollections.map(([slug])=>slug).sort().join(',')
44
+ };
45
+ const cached = searchCache.get(query, 'universal', cacheKey);
46
+ if (cached) {
47
+ return Response.json(cached);
48
+ }
49
+ const searches = enabledCollections.map(async ([slug, collection])=>{
50
+ const displayName = collection.displayName || slug;
51
+ const icon = collection.icon || '📄';
52
+ try {
53
+ const fields = collection.searchFields?.length ? collection.searchFields : [
54
+ 'title',
55
+ 'content',
56
+ 'description'
57
+ ];
58
+ const search = (page)=>client.collections(slug).documents().search(buildParameters(config, fields, {
59
+ ...options,
60
+ page,
61
+ per_page: perPage,
62
+ q: query,
63
+ search_mode: mode
64
+ }));
65
+ let page = multiple ? 1 : options.page;
66
+ const results = await search(page);
67
+ const hits = [
68
+ ...results.hits ?? []
69
+ ];
70
+ let cutoff = results.search_cutoff;
71
+ let time = results.search_time_ms;
72
+ while(multiple && hits.length < Math.min(limit, results.found) && !cutoff){
73
+ const next = await search(++page);
74
+ const batch = next.hits ?? [];
75
+ cutoff ||= next.search_cutoff;
76
+ time += next.search_time_ms;
77
+ hits.push(...batch);
78
+ if (batch.length < perPage) break;
79
+ }
80
+ return {
81
+ collection: slug,
82
+ displayName,
83
+ found: results.found,
84
+ hits: hits.slice(0, limit).map((hit)=>({
85
+ ...hit,
86
+ collection: slug,
87
+ displayName,
88
+ icon
89
+ })),
90
+ icon,
91
+ search_cutoff: cutoff,
92
+ search_time_ms: time
93
+ };
94
+ } catch (error) {
95
+ return {
96
+ collection: slug,
97
+ displayName,
98
+ error: error instanceof Error ? error.message : 'Unknown error',
99
+ found: 0,
100
+ hits: [],
101
+ icon,
102
+ search_cutoff: false,
103
+ search_time_ms: 0
104
+ };
105
+ }
106
+ });
107
+ const results = await Promise.all(searches);
108
+ if (results.every((result)=>'error' in result)) {
109
+ return Response.json({
110
+ error: 'All collection searches failed',
111
+ collections: results
112
+ }, {
113
+ status: 500
114
+ });
115
+ }
116
+ const hits = results.flatMap((result)=>result.hits);
117
+ const found = results.reduce((total, result)=>total + result.found, 0);
118
+ if (compare) hits.sort(compare);
119
+ const offset = multiple ? (options.page - 1) * options.per_page : 0;
120
+ const response = {
121
+ collections: results.map((result)=>({
122
+ collection: result.collection,
123
+ displayName: result.displayName,
124
+ error: 'error' in result ? result.error : undefined,
125
+ found: result.found,
126
+ icon: result.icon
127
+ })),
128
+ found,
129
+ hits: hits.slice(offset, offset + options.per_page),
130
+ page: options.page,
131
+ request_params: {
132
+ page: options.page,
133
+ per_page: options.per_page,
134
+ q: query,
135
+ sort_by: options.sort_by
136
+ },
137
+ search_cutoff: results.some((result)=>result.search_cutoff),
138
+ search_time_ms: Math.max(...results.map((result)=>result.search_time_ms))
139
+ };
140
+ if (results.every((result)=>!('error' in result))) {
141
+ searchCache.set(query, response, 'universal', cacheKey);
142
+ }
143
+ return Response.json(response);
144
+ } catch (error) {
145
+ return Response.json({
146
+ details: error instanceof Error ? error.message : 'Unknown error',
147
+ error: 'Universal search failed'
148
+ }, {
149
+ status: 500
150
+ });
151
+ }
152
+ };
@@ -1,8 +1,8 @@
1
- import type React from 'react';
2
- export declare function handleKeyboard(e: React.KeyboardEvent, options: {
3
- inputRef: React.RefObject<HTMLInputElement | null>;
1
+ import { type KeyboardEvent, type RefObject } from 'react';
2
+ export declare function handleKeyboard(event: KeyboardEvent, options: {
3
+ inputRef: RefObject<HTMLInputElement | null>;
4
4
  isOpen: boolean;
5
5
  results: unknown;
6
- resultsRef: React.RefObject<HTMLDivElement | null>;
6
+ resultsRef: RefObject<HTMLDivElement | null>;
7
7
  }): void;
8
8
  //# sourceMappingURL=keyboard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"keyboard.d.ts","sourceRoot":"","sources":["../../src/utils/keyboard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,wBAAgB,cAAc,CAC5B,CAAC,EAAE,KAAK,CAAC,aAAa,EACtB,OAAO,EAAE;IACP,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAA;IAClD,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,OAAO,CAAA;IAChB,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC,CAAA;CACnD,QAyCF"}
1
+ {"version":3,"file":"keyboard.d.ts","sourceRoot":"","sources":["../../src/utils/keyboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAE1D,wBAAgB,cAAc,CAC5B,KAAK,EAAE,aAAa,EACpB,OAAO,EAAE;IACP,QAAQ,EAAE,SAAS,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAA;IAC5C,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,OAAO,CAAA;IAChB,UAAU,EAAE,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC,CAAA;CAC7C,GACA,IAAI,CA+CN"}
@@ -1,38 +1,36 @@
1
- export function handleKeyboard(e, options) {
1
+ export function handleKeyboard(event, options) {
2
2
  const { inputRef, isOpen, results, resultsRef } = options;
3
+ if (event.key === 'Escape') {
4
+ if (isOpen) {
5
+ inputRef.current?.blur();
6
+ }
7
+ return;
8
+ }
3
9
  if (!isOpen || !results) return;
4
- const resultItems = resultsRef.current?.querySelectorAll('[data-result-item]');
5
- if (!resultItems) return;
6
- const items = Array.from(resultItems);
7
- const activeElement = document.activeElement;
8
- const currentIndex = activeElement ? items.indexOf(activeElement) : -1;
9
- switch(e.key){
10
+ const items = Array.from(resultsRef.current?.querySelectorAll('[data-result-item]') ?? []);
11
+ if (!items.length) return;
12
+ const active = document.activeElement;
13
+ const current = active instanceof HTMLElement ? items.indexOf(active) : -1;
14
+ switch(event.key){
10
15
  case 'ArrowDown':
11
16
  {
12
- e.preventDefault();
13
- const nextIndex = currentIndex < resultItems.length - 1 ? currentIndex + 1 : 0;
14
- resultItems[nextIndex]?.focus();
17
+ event.preventDefault();
18
+ const nextIndex = current < items.length - 1 ? current + 1 : 0;
19
+ items[nextIndex]?.focus();
15
20
  break;
16
21
  }
17
22
  case 'ArrowUp':
18
23
  {
19
- e.preventDefault();
20
- const prevIndex = currentIndex > 0 ? currentIndex - 1 : resultItems.length - 1;
21
- resultItems[prevIndex]?.focus();
24
+ event.preventDefault();
25
+ const previousIndex = current > 0 ? current - 1 : items.length - 1;
26
+ items[previousIndex]?.focus();
22
27
  break;
23
28
  }
24
29
  case 'Enter':
25
30
  {
26
- e.preventDefault();
27
- if (currentIndex >= 0 && resultItems[currentIndex]) {
28
- ;
29
- resultItems[currentIndex]?.click();
30
- }
31
- break;
32
- }
33
- case 'Escape':
34
- {
35
- inputRef.current?.blur();
31
+ if (current < 0) return;
32
+ event.preventDefault();
33
+ items[current]?.click();
36
34
  break;
37
35
  }
38
36
  }
@@ -0,0 +1,3 @@
1
+ import { type Hit, type SearchMode } from '../types.js';
2
+ export declare function getCompare(sortBy?: string, mode?: SearchMode | boolean): (a: Hit, b: Hit) => number;
3
+ //# sourceMappingURL=sortResults.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sortResults.d.ts","sourceRoot":"","sources":["../../src/utils/sortResults.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,UAAU,EAAa,MAAM,aAAa,CAAA;AA6HlE,wBAAgB,UAAU,CACxB,MAAM,CAAC,EAAE,MAAM,EACf,IAAI,GAAE,UAAU,GAAG,OAAmB,GACrC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,MAAM,CAc5B"}
@@ -0,0 +1,103 @@
1
+ const SORT_PATTERN = /^([\w.]+)(?:\(missing_values:\s*(first|last)\))?\s*:\s*(asc|desc)$/;
2
+ const SCORE_FIELDS = new Set([
3
+ '_text_match',
4
+ '_vector_distance'
5
+ ]);
6
+ function parseSorts(sortBy) {
7
+ if (!sortBy?.trim()) return [];
8
+ const sorts = [];
9
+ for (const part of sortBy.split(',')){
10
+ const match = part.trim().match(SORT_PATTERN);
11
+ const field = match?.[1];
12
+ if (!field || field.startsWith('_') && !SCORE_FIELDS.has(field)) {
13
+ throw new Error('Multi-collection sorting supports field names, _text_match and _vector_distance');
14
+ }
15
+ sorts.push({
16
+ direction: match[3] === 'asc' ? 1 : -1,
17
+ field,
18
+ missing: match[2]
19
+ });
20
+ }
21
+ if (sorts.length > 3) {
22
+ throw new Error('A maximum of three sort fields is supported');
23
+ }
24
+ return sorts;
25
+ }
26
+ function getSorts(sortBy, vector) {
27
+ const sorts = parseSorts(sortBy);
28
+ const field = vector ? '_vector_distance' : '_text_match';
29
+ if (sorts.length < 3 && !sorts.some((sort)=>sort.field === field)) {
30
+ sorts.push({
31
+ direction: vector ? 1 : -1,
32
+ field
33
+ });
34
+ }
35
+ return sorts;
36
+ }
37
+ function getValue(hit, field) {
38
+ if (field === '_text_match') {
39
+ return hit.text_match_info?.score ?? hit.text_match ?? 0;
40
+ }
41
+ if (field === '_vector_distance') return hit.vector_distance;
42
+ const document = hit.document;
43
+ if (Object.hasOwn(document, field)) return document[field];
44
+ return field.split('.').reduce((value, part)=>{
45
+ if (!value || typeof value !== 'object' || !Object.hasOwn(value, part)) {
46
+ return undefined;
47
+ }
48
+ return value[part];
49
+ }, document);
50
+ }
51
+ function getSortValue(hit, field, hybrid) {
52
+ if (hybrid && field === '_text_match') {
53
+ return hit.hybrid_search_info?.rank_fusion_score ?? 0;
54
+ }
55
+ return getValue(hit, field);
56
+ }
57
+ function isMissing(value) {
58
+ return value === undefined || value === null || value === '';
59
+ }
60
+ function compareMissing(left, right, sort) {
61
+ const leftMissing = isMissing(left);
62
+ const rightMissing = isMissing(right);
63
+ if (!leftMissing && !rightMissing) return undefined;
64
+ if (leftMissing === rightMissing) return 0;
65
+ const stringField = typeof (leftMissing ? right : left) === 'string' && sort.field !== '_text_match';
66
+ const first = sort.missing === 'first' || !sort.missing && stringField && sort.direction < 0;
67
+ return leftMissing === first ? -1 : 1;
68
+ }
69
+ function compareValues(left, right, field, hybrid) {
70
+ if (field === '_text_match' && !hybrid) {
71
+ const a = BigInt(left);
72
+ const b = BigInt(right);
73
+ return a < b ? -1 : a > b ? 1 : 0;
74
+ }
75
+ if (typeof left === 'number' && typeof right === 'number') {
76
+ return left - right;
77
+ }
78
+ if (typeof left === 'boolean' && typeof right === 'boolean') {
79
+ return Number(left) - Number(right);
80
+ }
81
+ const a = String(left);
82
+ const b = String(right);
83
+ return a < b ? -1 : a > b ? 1 : 0;
84
+ }
85
+ function compareSort(a, b, sort, hybrid) {
86
+ const left = getSortValue(a, sort.field, hybrid);
87
+ const right = getSortValue(b, sort.field, hybrid);
88
+ const missing = compareMissing(left, right, sort);
89
+ if (missing !== undefined) return missing;
90
+ return compareValues(left, right, sort.field, hybrid) * sort.direction;
91
+ }
92
+ export function getCompare(sortBy, mode = 'keyword') {
93
+ const vector = mode === true || mode === 'semantic';
94
+ const hybrid = mode === 'hybrid';
95
+ const sorts = getSorts(sortBy, vector);
96
+ return (a, b)=>{
97
+ for (const sort of sorts){
98
+ const result = compareSort(a, b, sort, hybrid);
99
+ if (result !== 0) return result;
100
+ }
101
+ return 0;
102
+ };
103
+ }
@@ -1,3 +1,3 @@
1
1
  import type Typesense from 'typesense';
2
- export declare const testConnection: (client: Typesense.Client) => Promise<boolean>;
2
+ export declare function testConnection(client: Typesense.Client): Promise<boolean>;
3
3
  //# sourceMappingURL=testConnection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"testConnection.d.ts","sourceRoot":"","sources":["../../src/utils/testConnection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,eAAO,MAAM,cAAc,WAAkB,SAAS,CAAC,MAAM,KAAG,OAAO,CAAC,OAAO,CAO9E,CAAA"}
1
+ {"version":3,"file":"testConnection.d.ts","sourceRoot":"","sources":["../../src/utils/testConnection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,wBAAsB,cAAc,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ/E"}
@@ -1,8 +1,8 @@
1
- export const testConnection = async (client)=>{
1
+ export async function testConnection(client) {
2
2
  try {
3
3
  const health = await client.health.retrieve();
4
4
  return health.ok === true;
5
5
  } catch {
6
6
  return false;
7
7
  }
8
- };
8
+ }
@@ -1,7 +1,4 @@
1
1
  import type Typesense from 'typesense';
2
- export declare function vectorSearch(typesenseClient: Typesense.Client, query: string, options: {
3
- collection: string;
4
- page: number;
5
- per_page: number;
6
- }): Promise<any>;
2
+ import { type VectorOptions } from '../types.js';
3
+ export declare function vectorSearch(client: Typesense.Client, query: string, options: VectorOptions): Promise<Typesense.SearchResponse<object>>;
7
4
  //# sourceMappingURL=vectorSearch.d.ts.map