@wovvmap/map-data 0.0.0-stage → 1.2.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 (98) hide show
  1. package/README.md +65 -2
  2. package/dist/adapters/index.d.ts +12 -0
  3. package/dist/adapters/index.d.ts.map +1 -0
  4. package/dist/adapters/index.js +16 -0
  5. package/dist/adapters/sdkApiAdapter.d.ts +20 -0
  6. package/dist/adapters/sdkApiAdapter.d.ts.map +1 -0
  7. package/dist/adapters/sdkApiAdapter.js +31 -0
  8. package/dist/adapters/types.d.ts +84 -0
  9. package/dist/adapters/types.d.ts.map +1 -0
  10. package/dist/adapters/types.js +8 -0
  11. package/dist/cache/mallMapCache.types.d.ts +32 -0
  12. package/dist/cache/mallMapCache.types.d.ts.map +1 -0
  13. package/dist/cache/mallMapCache.types.js +1 -0
  14. package/dist/cache/memoryMallMapCache.d.ts +37 -0
  15. package/dist/cache/memoryMallMapCache.d.ts.map +1 -0
  16. package/dist/cache/memoryMallMapCache.js +44 -0
  17. package/dist/catalog/catalogIndexReadPort.d.ts +35 -0
  18. package/dist/catalog/catalogIndexReadPort.d.ts.map +1 -0
  19. package/dist/catalog/catalogIndexReadPort.js +1 -0
  20. package/dist/catalog/catalogReader.d.ts +496 -0
  21. package/dist/catalog/catalogReader.d.ts.map +1 -0
  22. package/dist/catalog/catalogReader.js +1799 -0
  23. package/dist/catalog/index.d.ts +9 -0
  24. package/dist/catalog/index.d.ts.map +1 -0
  25. package/dist/catalog/index.js +6 -0
  26. package/dist/catalog/offerAvailability.d.ts +25 -0
  27. package/dist/catalog/offerAvailability.d.ts.map +1 -0
  28. package/dist/catalog/offerAvailability.js +107 -0
  29. package/dist/controllers/mallController.d.ts +69 -0
  30. package/dist/controllers/mallController.d.ts.map +1 -0
  31. package/dist/controllers/mallController.js +92 -0
  32. package/dist/controllers/mallController.types.d.ts +10 -0
  33. package/dist/controllers/mallController.types.d.ts.map +1 -0
  34. package/dist/controllers/mallController.types.js +1 -0
  35. package/dist/index.d.ts +26 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +22 -0
  38. package/dist/indexer/nodeDataIndexer.types.d.ts +16 -0
  39. package/dist/indexer/nodeDataIndexer.types.d.ts.map +1 -0
  40. package/dist/indexer/nodeDataIndexer.types.js +1 -0
  41. package/dist/models/catalog.d.ts +2 -0
  42. package/dist/models/catalog.d.ts.map +1 -0
  43. package/dist/models/catalog.js +1 -0
  44. package/dist/models/floor.d.ts +16 -0
  45. package/dist/models/floor.d.ts.map +1 -0
  46. package/dist/models/floor.js +1 -0
  47. package/dist/models/mall.d.ts +29 -0
  48. package/dist/models/mall.d.ts.map +1 -0
  49. package/dist/models/mall.js +1 -0
  50. package/dist/parser/index.d.ts +3 -0
  51. package/dist/parser/index.d.ts.map +1 -0
  52. package/dist/parser/index.js +1 -0
  53. package/dist/parser/mapParser.types.d.ts +34 -0
  54. package/dist/parser/mapParser.types.d.ts.map +1 -0
  55. package/dist/parser/mapParser.types.js +1 -0
  56. package/dist/parser/mapParserService.d.ts +8 -0
  57. package/dist/parser/mapParserService.d.ts.map +1 -0
  58. package/dist/parser/mapParserService.js +61 -0
  59. package/dist/prepared/index.d.ts +3 -0
  60. package/dist/prepared/index.d.ts.map +1 -0
  61. package/dist/prepared/index.js +2 -0
  62. package/dist/prepared/preparedGeometryValidation.d.ts +6 -0
  63. package/dist/prepared/preparedGeometryValidation.d.ts.map +1 -0
  64. package/dist/prepared/preparedGeometryValidation.js +76 -0
  65. package/dist/prepared/preparedMapFields.d.ts +36 -0
  66. package/dist/prepared/preparedMapFields.d.ts.map +1 -0
  67. package/dist/prepared/preparedMapFields.js +205 -0
  68. package/dist/prepared/preparedMapReader.d.ts +68 -0
  69. package/dist/prepared/preparedMapReader.d.ts.map +1 -0
  70. package/dist/prepared/preparedMapReader.js +231 -0
  71. package/dist/prepared/preparedMapValidation.d.ts +23 -0
  72. package/dist/prepared/preparedMapValidation.d.ts.map +1 -0
  73. package/dist/prepared/preparedMapValidation.js +216 -0
  74. package/dist/search/catalogEndpointLookup.d.ts +23 -0
  75. package/dist/search/catalogEndpointLookup.d.ts.map +1 -0
  76. package/dist/search/catalogEndpointLookup.js +56 -0
  77. package/dist/search/catalogSearchService.d.ts +182 -0
  78. package/dist/search/catalogSearchService.d.ts.map +1 -0
  79. package/dist/search/catalogSearchService.js +653 -0
  80. package/dist/search/searchProfiles.d.ts +240 -0
  81. package/dist/search/searchProfiles.d.ts.map +1 -0
  82. package/dist/search/searchProfiles.js +364 -0
  83. package/dist/services/mallService.d.ts +82 -0
  84. package/dist/services/mallService.d.ts.map +1 -0
  85. package/dist/services/mallService.js +230 -0
  86. package/dist/services/mallService.types.d.ts +51 -0
  87. package/dist/services/mallService.types.d.ts.map +1 -0
  88. package/dist/services/mallService.types.js +1 -0
  89. package/dist/transport/fetchHttpClient.d.ts +25 -0
  90. package/dist/transport/fetchHttpClient.d.ts.map +1 -0
  91. package/dist/transport/fetchHttpClient.js +170 -0
  92. package/dist/transport/httpClient.types.d.ts +26 -0
  93. package/dist/transport/httpClient.types.d.ts.map +1 -0
  94. package/dist/transport/httpClient.types.js +1 -0
  95. package/dist/transport/httpTransportError.d.ts +25 -0
  96. package/dist/transport/httpTransportError.d.ts.map +1 -0
  97. package/dist/transport/httpTransportError.js +16 -0
  98. package/package.json +33 -3
@@ -0,0 +1,653 @@
1
+ /**
2
+ * @file catalogSearchService.ts
3
+ * @description Portable catalog/search composition shared by direct viewers and private HTTP endpoint resolution.
4
+ * Composes `CatalogReader` (`@wovvmap/map-data`), prepared `SearchIndex` instances (`@wovvmap/search-core`),
5
+ * and shared WovVMap search profiles (`searchProfiles.ts`) behind a single revision-safe owner.
6
+ *
7
+ * Hinglish: Har map ka common catalog aur search owner jo `CatalogReader`, prepared `SearchIndex`
8
+ * instances aur shared `searchProfiles` ko compose karke `getCatalog` aur `search` serve karti hai.
9
+ */
10
+ import { CatalogReadError, CatalogReader, clonePublicAmenityData, clonePublicCategoryData, clonePublicSubCategoryData, DEFAULT_CATALOG_PAGE_LIMIT, MAX_CATALOG_PAGE_LIMIT, } from '../catalog/index.js';
11
+ import { createAmenitySearchIndex, createCategorySearchIndex, createStoreSearchIndex, createSubCategorySearchIndex, executeGroupedStoreSearch, } from './searchProfiles.js';
12
+ const SUPPORTED_TARGETS = new Set([
13
+ 'stores',
14
+ 'categories',
15
+ 'subcategories',
16
+ 'amenities',
17
+ 'offers',
18
+ ]);
19
+ const STORE_SUPPORTED_SORT_MODES = new Set([
20
+ 'default',
21
+ 'relevance',
22
+ 'asc',
23
+ 'desc',
24
+ 'floor_proximity',
25
+ 'paid_promotion_asc',
26
+ 'paid_promotion_desc',
27
+ 'paid_promotion_weight',
28
+ 'paid_promotion_floor',
29
+ ]);
30
+ const TAXONOMY_SUPPORTED_SORT_MODES = new Set(['default', 'relevance', 'asc', 'desc']);
31
+ const SUPPORTED_FLOOR_SECONDARY_SORT_MODES = new Set(['relevance', 'asc', 'desc']);
32
+ function hasNonEmptyLookupKey(value) {
33
+ if (value === undefined || value === null)
34
+ return false;
35
+ if (typeof value === 'number')
36
+ return Number.isFinite(value);
37
+ if (typeof value === 'string')
38
+ return value.trim() !== '';
39
+ return false;
40
+ }
41
+ function hasFilterCriteria(filter) {
42
+ if (!filter || typeof filter !== 'object')
43
+ return false;
44
+ if (hasNonEmptyLookupKey(filter.categoryCode))
45
+ return true;
46
+ if (hasNonEmptyLookupKey(filter.subCategoryCode))
47
+ return true;
48
+ if (hasNonEmptyLookupKey(filter.amenityId))
49
+ return true;
50
+ if (typeof filter.floorIndex === 'number' && Number.isInteger(filter.floorIndex))
51
+ return true;
52
+ if (filter.offersOnly === true)
53
+ return true;
54
+ return false;
55
+ }
56
+ function resolveBoundedPagination(index, pagination, maxLimit) {
57
+ const rawOffset = pagination?.offset;
58
+ const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) && rawOffset > 0
59
+ ? Math.floor(rawOffset)
60
+ : 0;
61
+ const rawLimit = pagination?.limit;
62
+ if (rawLimit === undefined) {
63
+ const resolved = index.resolvePagination({ offset });
64
+ return {
65
+ offset: resolved.offset,
66
+ limit: Math.min(resolved.limit, maxLimit),
67
+ };
68
+ }
69
+ if (typeof rawLimit !== 'number' || !Number.isFinite(rawLimit) || rawLimit <= 0) {
70
+ return { offset, limit: 0 };
71
+ }
72
+ return {
73
+ offset,
74
+ limit: Math.min(Math.floor(rawLimit), maxLimit),
75
+ };
76
+ }
77
+ /**
78
+ * Per-viewer service owning the committed catalog revision and prepared search indexes.
79
+ * Ensures search indexes are built once per committed revision (never per keystroke, floor switch,
80
+ * or camera move) and that failed or superseded map loads never corrupt the committed catalog.
81
+ *
82
+ * Hinglish: Per-viewer service jo committed catalog revision aur prepared search indexes own karti hai;
83
+ * har keystroke, floor switch ya camera move par index rebuild nahi karti aur failed/superseded map load
84
+ * par purana committed catalog safe rakhti hai.
85
+ */
86
+ export class CatalogSearchService {
87
+ reader;
88
+ committedState = null;
89
+ defaultPageLimit;
90
+ maxPageLimit;
91
+ constructor(options) {
92
+ const rawDefault = options?.defaultPageLimit ?? DEFAULT_CATALOG_PAGE_LIMIT;
93
+ const rawMax = options?.maxPageLimit ?? MAX_CATALOG_PAGE_LIMIT;
94
+ this.maxPageLimit =
95
+ typeof rawMax === 'number' && Number.isFinite(rawMax) && rawMax > 0
96
+ ? Math.floor(rawMax)
97
+ : MAX_CATALOG_PAGE_LIMIT;
98
+ this.defaultPageLimit =
99
+ typeof rawDefault === 'number' && Number.isFinite(rawDefault) && rawDefault >= 0
100
+ ? Math.min(Math.floor(rawDefault), this.maxPageLimit)
101
+ : Math.min(DEFAULT_CATALOG_PAGE_LIMIT, this.maxPageLimit);
102
+ this.reader = new CatalogReader({
103
+ defaultPageLimit: this.defaultPageLimit > 0 ? this.defaultPageLimit : DEFAULT_CATALOG_PAGE_LIMIT,
104
+ maxPageLimit: this.maxPageLimit,
105
+ });
106
+ if (options?.parsedMap) {
107
+ this.commitMap(options.parsedMap, options.revision);
108
+ }
109
+ }
110
+ /**
111
+ * Prepares a candidate catalog state and all four candidate search indexes (`stores`,
112
+ * `categories`, `subcategories`, `amenities`) WITHOUT mutating `this.reader` or `this.committedState`.
113
+ * Allows callers (`WovvMapViewer`) to verify that catalog and search preparation succeeds
114
+ * before clearing or replacing old 3D scene elements.
115
+ *
116
+ * Hinglish: Active catalog ya search state ko mutate kiye bina candidate catalog aur chaaro
117
+ * search indexes prepare karta hai, taaki old 3D scene elements clear karne se pehle preparation verify ho sake.
118
+ */
119
+ prepareMapCommit(source, revision) {
120
+ const readerCandidate = this.reader.prepareCommitCandidate(source, revision);
121
+ const storeKeys = source.indexer.getStoreNodeKeys();
122
+ const storeDocs = [];
123
+ for (let i = 0; i < storeKeys.length; i++) {
124
+ const pub = source.indexer.getPublicNodeByKey(storeKeys[i]);
125
+ if (pub) {
126
+ storeDocs.push(pub);
127
+ }
128
+ }
129
+ const taxonomyDocs = this.reader.getCandidateTaxonomySummaries(readerCandidate);
130
+ const candidateStoreIndex = createStoreSearchIndex(storeDocs, {
131
+ defaultLimit: this.defaultPageLimit,
132
+ });
133
+ const candidateCategoryIndex = createCategorySearchIndex(taxonomyDocs.categories, {
134
+ defaultLimit: this.defaultPageLimit,
135
+ });
136
+ const candidateSubCategoryIndex = createSubCategorySearchIndex(taxonomyDocs.subCategories, {
137
+ defaultLimit: this.defaultPageLimit,
138
+ });
139
+ const candidateAmenityIndex = createAmenitySearchIndex(taxonomyDocs.amenities, {
140
+ defaultLimit: this.defaultPageLimit,
141
+ });
142
+ return {
143
+ readerCandidate,
144
+ source,
145
+ storeIndex: candidateStoreIndex,
146
+ categoryIndex: candidateCategoryIndex,
147
+ subCategoryIndex: candidateSubCategoryIndex,
148
+ amenityIndex: candidateAmenityIndex,
149
+ };
150
+ }
151
+ /**
152
+ * Atomically swaps the active catalog and search state to a previously prepared candidate.
153
+ *
154
+ * Hinglish: Pehle se prepared candidate catalog aur search indexes ko ek saath active state me swap karta hai.
155
+ */
156
+ applyPreparedMapCommit(candidate) {
157
+ const committed = this.reader.applyCommitCandidate(candidate.readerCandidate);
158
+ this.committedState = {
159
+ mallId: committed.mallId,
160
+ revision: committed.revision,
161
+ indexer: candidate.source.indexer,
162
+ storeIndex: candidate.storeIndex,
163
+ categoryIndex: candidate.categoryIndex,
164
+ subCategoryIndex: candidate.subCategoryIndex,
165
+ amenityIndex: candidate.amenityIndex,
166
+ };
167
+ return committed;
168
+ }
169
+ /**
170
+ * Atomically prepares a candidate catalog state and all four candidate search indexes (`stores`,
171
+ * `categories`, `subcategories`, `amenities`) BEFORE swapping the active catalog and search state.
172
+ * If any document extraction or search index preparation step fails, both `this.reader` and
173
+ * `this.committedState` remain untouched on the previous committed map revision.
174
+ *
175
+ * Hinglish: Candidate catalog state aur chaaro candidate search indexes pehle prepare karta hai
176
+ * aur sab kuch succeed hone ke baad hi active catalog aur search state ko ek saath swap karta hai.
177
+ * Agar beech me koi bhi step fail ho to purana committed catalog aur search state safe rehta hai.
178
+ */
179
+ commitMap(source, revision) {
180
+ const candidate = this.prepareMapCommit(source, revision);
181
+ return this.applyPreparedMapCommit(candidate);
182
+ }
183
+ /**
184
+ * Releases the committed catalog state and clears all owned search indexes on viewer teardown.
185
+ *
186
+ * Hinglish: Viewer teardown par committed catalog aur saare owned search indexes clear karta hai.
187
+ */
188
+ clear() {
189
+ this.reader.clear();
190
+ if (this.committedState) {
191
+ this.committedState.storeIndex.clear();
192
+ this.committedState.categoryIndex.clear();
193
+ this.committedState.subCategoryIndex.clear();
194
+ this.committedState.amenityIndex.clear();
195
+ this.committedState = null;
196
+ }
197
+ }
198
+ /**
199
+ * Returns the currently committed `{ mallId, revision }` or `null` when no map is committed.
200
+ *
201
+ * Hinglish: Currently committed `{ mallId, revision }` return karta hai (map commit na hone par `null`).
202
+ */
203
+ getRevision() {
204
+ return this.reader.getRevision();
205
+ }
206
+ /**
207
+ * Reads a bounded public catalog page for `stores`, `categories`, `subcategories`, `amenities`, or `offers`.
208
+ * Uses `CatalogReader` source order when `sortBy` is omitted or `'default'`, and delegates to the prepared
209
+ * search/sort pipeline when an explicit supported sort mode is requested.
210
+ *
211
+ * Hinglish: Requested target ke liye bounded public catalog page return karta hai; default source order ke liye
212
+ * `CatalogReader` use karta hai aur explicit supported sort mode hone par prepared search/sort pipeline chalata hai.
213
+ */
214
+ getCatalog(request, fallbackActiveFloorIndex) {
215
+ if (!request || typeof request !== 'object' || !SUPPORTED_TARGETS.has(String(request.target))) {
216
+ throw new CatalogReadError('UNSUPPORTED_FILTER_COMBINATION', `[ViewerCatalogSearchService] Unsupported catalog target: "${String(request?.target)}".`);
217
+ }
218
+ const state = this.assertValidCommittedState(request.mallId, request.expectedRevision);
219
+ const effectiveRequest = request.activeFloorIndex === undefined &&
220
+ typeof fallbackActiveFloorIndex === 'number' &&
221
+ Number.isFinite(fallbackActiveFloorIndex)
222
+ ? { ...request, activeFloorIndex: fallbackActiveFloorIndex }
223
+ : request;
224
+ const sortBy = effectiveRequest.sortBy;
225
+ if (sortBy === undefined || sortBy === 'default') {
226
+ if (effectiveRequest.floorSecondarySortBy !== undefined &&
227
+ effectiveRequest.floorSecondarySortBy !== 'relevance') {
228
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Secondary floor sort "${String(effectiveRequest.floorSecondarySortBy)}" requires "floor_proximity" or "paid_promotion_floor".`, {
229
+ sortBy: sortBy ?? 'default',
230
+ floorSecondarySortBy: effectiveRequest.floorSecondarySortBy,
231
+ });
232
+ }
233
+ if (this.defaultPageLimit === 0 && effectiveRequest.pagination?.limit === undefined) {
234
+ return this.reader.readCatalog({
235
+ ...effectiveRequest,
236
+ pagination: { ...effectiveRequest.pagination, limit: 0 },
237
+ });
238
+ }
239
+ return this.reader.readCatalog(effectiveRequest);
240
+ }
241
+ if (effectiveRequest.target === 'offers') {
242
+ return this.reader.readCatalog(effectiveRequest);
243
+ }
244
+ this.validateTargetSortCombination(effectiveRequest.target, sortBy, effectiveRequest.floorSecondarySortBy);
245
+ return this.executeTargetSearch(state, {
246
+ ...effectiveRequest,
247
+ query: '',
248
+ });
249
+ }
250
+ /**
251
+ * Executes a bounded, ordered public search across `stores`, `categories`, `subcategories`, or `amenities`
252
+ * using the committed revision's prepared search indexes and canonical multi-location grouping pipeline.
253
+ *
254
+ * Hinglish: Committed revision ke prepared search indexes aur canonical grouping pipeline se
255
+ * `stores`, `categories`, `subcategories` ya `amenities` par bounded public search run karta hai.
256
+ */
257
+ search(request, fallbackActiveFloorIndex) {
258
+ if (!request || typeof request !== 'object' || !SUPPORTED_TARGETS.has(String(request.target))) {
259
+ throw new CatalogReadError('UNSUPPORTED_FILTER_COMBINATION', `[ViewerCatalogSearchService] Unsupported search target: "${String(request?.target)}".`);
260
+ }
261
+ const state = this.assertValidCommittedState(request.mallId, request.expectedRevision);
262
+ const effectiveRequest = request.activeFloorIndex === undefined &&
263
+ typeof fallbackActiveFloorIndex === 'number' &&
264
+ Number.isFinite(fallbackActiveFloorIndex)
265
+ ? { ...request, activeFloorIndex: fallbackActiveFloorIndex }
266
+ : request;
267
+ if (effectiveRequest.target === 'offers') {
268
+ throw new CatalogReadError('UNSUPPORTED_SEARCH_QUERY', '[ViewerCatalogSearchService] Offer-title search is not supported. Use getCatalog({ target: "offers" }) for offer summaries or search({ target: "stores", filter: { offersOnly: true } }) for eligible stores.', { target: effectiveRequest.target, query: effectiveRequest.query });
269
+ }
270
+ this.validateTargetSortCombination(effectiveRequest.target, effectiveRequest.sortBy, effectiveRequest.floorSecondarySortBy);
271
+ const rawQuery = typeof effectiveRequest.query === 'string' ? effectiveRequest.query : '';
272
+ if (rawQuery.trim() === '' && effectiveRequest.sortBy === 'default') {
273
+ if (this.defaultPageLimit === 0 && effectiveRequest.pagination?.limit === undefined) {
274
+ return this.reader.readCatalog({
275
+ ...effectiveRequest,
276
+ pagination: { ...effectiveRequest.pagination, limit: 0 },
277
+ });
278
+ }
279
+ return this.reader.readCatalog(effectiveRequest);
280
+ }
281
+ return this.executeTargetSearch(state, effectiveRequest);
282
+ }
283
+ /**
284
+ * Resolves a multi-location store group summary by `groupId` from the committed catalog.
285
+ *
286
+ * Hinglish: Committed catalog se `groupId` ke aadhar par multi-location store group summary return karta hai.
287
+ */
288
+ getStoreGroupById(groupId, options) {
289
+ return this.reader.getStoreGroupById(groupId, options);
290
+ }
291
+ /**
292
+ * Reads a bounded page of `PublicNodeData` members for a multi-location store group.
293
+ * When a search `query`, `mode === 'search'`, or non-default `sortBy` is supplied, resolves
294
+ * eligible group keys from the canonical group index and evaluates/orders them through the
295
+ * prepared store `SearchIndex` (supporting fuzzy matching, field weights, paid promotions,
296
+ * and floor-proximity sorting) without scanning the full map.
297
+ *
298
+ * Hinglish: Multi-location store group ke members ka bounded public page return karta hai;
299
+ * `query` ya `sortBy` hone par canonical group index ke eligible keys par prepared store `SearchIndex`
300
+ * (fuzzy match, field weights, paid promotions aur floor sorting ke saath) run karta hai bina full-map scan ke.
301
+ */
302
+ getGroupMembers(request, fallbackActiveFloorIndex) {
303
+ const keys = this.resolveGroupMemberKeys(request, fallbackActiveFloorIndex);
304
+ if (!keys)
305
+ return null;
306
+ return this.reader.buildGroupMembersPageFromKeys(request.groupId, keys, request);
307
+ }
308
+ /** Delegate persistent category membership to the shared catalog evaluator.
309
+ * Hinglish: Filter ke liye catalog ka wahi evaluator use ho; duplicate lookup logic nahi. */
310
+ resolveDiscoveryFilter(request, activeFloorIndex) {
311
+ return this.reader.resolveDiscoveryFilter(request, activeFloorIndex);
312
+ }
313
+ /** Reuse the exact member-read scope, materializing only a compact public selection summary.
314
+ * Hinglish: Wahi query/filter wale keys use hon; saare public member objects banane ki zarurat nahi. */
315
+ resolveGroupSelection(request, fallbackActiveFloorIndex) {
316
+ this.assertValidCommittedState(request.mallId, request.expectedRevision);
317
+ const keys = this.resolveGroupMemberKeys(request, fallbackActiveFloorIndex);
318
+ if (!keys)
319
+ return null;
320
+ const row = this.reader.resolvePublicStoreRow({ kind: 'group', groupId: request.groupId, memberKeys: keys }, { ...request, activeFloorIndex: request.activeFloorIndex ?? fallbackActiveFloorIndex });
321
+ if (!row)
322
+ return null;
323
+ const representative = row.kind === 'group' ? row.group.representative : row.node;
324
+ return {
325
+ keys,
326
+ selection: {
327
+ groupId: request.groupId,
328
+ name: row.kind === 'group'
329
+ ? row.group.name
330
+ : (representative.assets.locationName?.text ?? request.groupId),
331
+ memberCount: keys.length,
332
+ availableFloors: row.kind === 'group' ? row.group.availableFloors : [representative.floorIndex],
333
+ representative,
334
+ },
335
+ };
336
+ }
337
+ /** Read and select share indexed eligibility; pagination affects public details, never membership.
338
+ * Hinglish: Read/select ka eligibility logic ek hai; page size sirf details ko limit karta hai. */
339
+ resolveGroupMemberKeys(request, fallbackActiveFloorIndex) {
340
+ if (!request || typeof request !== 'object') {
341
+ return null;
342
+ }
343
+ const effectiveActiveFloorIndex = request.activeFloorIndex !== undefined
344
+ ? request.activeFloorIndex
345
+ : typeof fallbackActiveFloorIndex === 'number' && Number.isFinite(fallbackActiveFloorIndex)
346
+ ? fallbackActiveFloorIndex
347
+ : undefined;
348
+ const rawQuery = typeof request.query === 'string' ? request.query.trim() : '';
349
+ const hasExplicitSort = request.sortBy !== undefined && request.sortBy !== 'default';
350
+ const shouldUseSearchPipeline = rawQuery !== '' ||
351
+ hasExplicitSort ||
352
+ (request.mode === 'search' && request.sortBy !== 'default');
353
+ if (!shouldUseSearchPipeline) {
354
+ if (request.floorSecondarySortBy !== undefined &&
355
+ request.floorSecondarySortBy !== 'relevance') {
356
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Secondary floor sort "${String(request.floorSecondarySortBy)}" requires "floor_proximity" or "paid_promotion_floor".`, {
357
+ sortBy: request.sortBy ?? 'default',
358
+ floorSecondarySortBy: request.floorSecondarySortBy,
359
+ });
360
+ }
361
+ return this.reader.getEligibleGroupMemberKeys(request.groupId, {
362
+ mallId: request.mallId,
363
+ expectedRevision: request.expectedRevision,
364
+ filter: request.filter,
365
+ activeFloorIndex: effectiveActiveFloorIndex,
366
+ });
367
+ }
368
+ this.validateTargetSortCombination('stores', request.sortBy, request.floorSecondarySortBy);
369
+ if (!this.committedState || !this.reader.isRevisionMatch(request)) {
370
+ return null;
371
+ }
372
+ const state = this.committedState;
373
+ const eligibleGroupKeys = this.reader.getEligibleGroupMemberKeys(request.groupId, {
374
+ mallId: request.mallId,
375
+ expectedRevision: request.expectedRevision,
376
+ filter: request.filter,
377
+ activeFloorIndex: effectiveActiveFloorIndex,
378
+ });
379
+ if (!eligibleGroupKeys || eligibleGroupKeys.length === 0) {
380
+ return null;
381
+ }
382
+ const effectiveSortBy = request.sortBy === undefined || request.sortBy === 'default'
383
+ ? 'relevance'
384
+ : request.sortBy;
385
+ const eligibleIdSet = new Set(eligibleGroupKeys);
386
+ const matched = state.storeIndex.searchAll(rawQuery, {
387
+ sortBy: effectiveSortBy,
388
+ floorSecondarySortBy: request.floorSecondarySortBy,
389
+ activeFloorIndex: effectiveActiveFloorIndex,
390
+ eligibleIds: eligibleIdSet,
391
+ });
392
+ if (matched.items.length === 0) {
393
+ return null;
394
+ }
395
+ return matched.items.map((item) => item.id);
396
+ }
397
+ /**
398
+ * Evaluates indexed floor availability for an amenity relative to `activeFloorIndex`.
399
+ *
400
+ * Hinglish: `activeFloorIndex` ke hisab se amenity ki floor availability return karta hai.
401
+ */
402
+ getAmenityFloorAvailability(amenityId, options) {
403
+ return this.reader.getAmenityFloorAvailability(amenityId, options);
404
+ }
405
+ assertValidCommittedState(expectedMallId, expectedRevision) {
406
+ // Delegate O(1) identity and revision validation to CatalogReader without resolving or copying store keys.
407
+ this.reader.assertCommittedIdentity({
408
+ mallId: expectedMallId,
409
+ expectedRevision,
410
+ });
411
+ return this.committedState;
412
+ }
413
+ validateTargetSortCombination(target, sortBy, floorSecondarySortBy) {
414
+ const effectiveSort = sortBy ?? 'relevance';
415
+ if (target === 'stores') {
416
+ if (!STORE_SUPPORTED_SORT_MODES.has(String(effectiveSort))) {
417
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Unsupported sort mode "${String(sortBy)}" for target "stores".`, { target, sortBy });
418
+ }
419
+ }
420
+ else if (target === 'categories' || target === 'subcategories' || target === 'amenities') {
421
+ if (!TAXONOMY_SUPPORTED_SORT_MODES.has(String(effectiveSort))) {
422
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Sort mode "${String(sortBy)}" is not supported for target "${target}". Supported sort modes for "${target}" are: default, relevance, asc, desc.`, { target, sortBy });
423
+ }
424
+ }
425
+ else {
426
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Sort mode "${String(sortBy)}" is not supported for target "${target}".`, { target, sortBy });
427
+ }
428
+ if (floorSecondarySortBy !== undefined) {
429
+ if (!SUPPORTED_FLOOR_SECONDARY_SORT_MODES.has(String(floorSecondarySortBy))) {
430
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Unsupported floorSecondarySortBy "${String(floorSecondarySortBy)}".`, { target, sortBy, floorSecondarySortBy });
431
+ }
432
+ if (floorSecondarySortBy !== 'relevance' &&
433
+ effectiveSort !== 'floor_proximity' &&
434
+ effectiveSort !== 'paid_promotion_floor') {
435
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[ViewerCatalogSearchService] Secondary floor sort "${floorSecondarySortBy}" is only supported with "floor_proximity" or "paid_promotion_floor" (received sortBy="${String(effectiveSort)}").`, { target, sortBy: effectiveSort, floorSecondarySortBy });
436
+ }
437
+ }
438
+ }
439
+ executeTargetSearch(state, request) {
440
+ const effectiveSortBy = request.sortBy === undefined || request.sortBy === 'default'
441
+ ? 'relevance'
442
+ : request.sortBy;
443
+ const rawQuery = typeof request.query === 'string' ? request.query : '';
444
+ switch (request.target) {
445
+ case 'stores':
446
+ return this.executeStoresSearch(state, request, rawQuery, effectiveSortBy);
447
+ case 'categories':
448
+ return this.executeTaxonomySearch(state, 'categories', state.categoryIndex, this.reader.getPreparedCategoriesSummary(request.filter, {
449
+ mallId: request.mallId,
450
+ expectedRevision: request.expectedRevision,
451
+ }), clonePublicCategoryData, request, rawQuery, effectiveSortBy);
452
+ case 'subcategories':
453
+ return this.executeTaxonomySearch(state, 'subcategories', state.subCategoryIndex, this.reader.getPreparedSubCategoriesSummary(request.filter, {
454
+ mallId: request.mallId,
455
+ expectedRevision: request.expectedRevision,
456
+ }), clonePublicSubCategoryData, request, rawQuery, effectiveSortBy);
457
+ case 'amenities':
458
+ return this.executeTaxonomySearch(state, 'amenities', state.amenityIndex, this.reader.getPreparedAmenitiesSummary(request.filter, {
459
+ mallId: request.mallId,
460
+ expectedRevision: request.expectedRevision,
461
+ }), clonePublicAmenityData, request, rawQuery, effectiveSortBy);
462
+ default:
463
+ throw new CatalogReadError('UNSUPPORTED_SEARCH_QUERY', `[ViewerCatalogSearchService] Target "${String(request.target)}" does not support search in Phase 3.`, { target: request.target });
464
+ }
465
+ }
466
+ executeStoresSearch(state, request, query, sortBy) {
467
+ const { offset, limit } = resolveBoundedPagination(state.storeIndex, request.pagination, this.maxPageLimit);
468
+ let eligibleIds;
469
+ if (hasFilterCriteria(request.filter)) {
470
+ const candidateKeys = this.reader.getCandidateStoreKeys(request.filter, {
471
+ mallId: request.mallId,
472
+ expectedRevision: request.expectedRevision,
473
+ });
474
+ if (candidateKeys.length === 0) {
475
+ return {
476
+ target: 'stores',
477
+ mallId: state.mallId,
478
+ revision: state.revision,
479
+ items: [],
480
+ totalRows: 0,
481
+ totalMemberCount: 0,
482
+ offset,
483
+ limit,
484
+ hasMore: false,
485
+ nextOffset: null,
486
+ availableFloors: [],
487
+ };
488
+ }
489
+ eligibleIds = new Set(candidateKeys);
490
+ }
491
+ const groupedPage = executeGroupedStoreSearch(state.storeIndex, query, {
492
+ sortBy,
493
+ floorSecondarySortBy: request.floorSecondarySortBy,
494
+ activeFloorIndex: request.activeFloorIndex,
495
+ groupMultiLocation: request.groupMultiLocation ?? true,
496
+ eligibleIds,
497
+ offset,
498
+ limit,
499
+ getGroupId: (nodeKey) => state.indexer.getGroupIdByNodeKey(nodeKey),
500
+ });
501
+ const items = [];
502
+ for (let i = 0; i < groupedPage.items.length; i++) {
503
+ const entry = groupedPage.items[i];
504
+ if (entry.kind === 'store') {
505
+ const row = this.reader.resolvePublicStoreRow({ kind: 'store', key: entry.nodeKey }, {
506
+ mallId: state.mallId,
507
+ expectedRevision: state.revision,
508
+ activeFloorIndex: request.activeFloorIndex,
509
+ });
510
+ if (row) {
511
+ items.push(row);
512
+ }
513
+ }
514
+ else {
515
+ const row = this.reader.resolvePublicStoreRow({
516
+ kind: 'group',
517
+ groupId: entry.groupId,
518
+ memberKeys: entry.memberKeys,
519
+ representativeKey: entry.representativeKey,
520
+ availableFloors: entry.availableFloors,
521
+ }, {
522
+ mallId: state.mallId,
523
+ expectedRevision: state.revision,
524
+ activeFloorIndex: request.activeFloorIndex,
525
+ });
526
+ if (row) {
527
+ items.push(row);
528
+ }
529
+ }
530
+ }
531
+ return {
532
+ target: 'stores',
533
+ mallId: state.mallId,
534
+ revision: state.revision,
535
+ items,
536
+ totalRows: groupedPage.totalRows,
537
+ totalMemberCount: groupedPage.totalMemberCount,
538
+ offset: groupedPage.offset,
539
+ limit: groupedPage.limit,
540
+ hasMore: groupedPage.hasMore,
541
+ nextOffset: groupedPage.nextOffset,
542
+ availableFloors: groupedPage.availableFloors,
543
+ };
544
+ }
545
+ /**
546
+ * Shared typed taxonomy search helper for `categories`, `subcategories`, and `amenities`.
547
+ * Reuses the cached `PreparedTaxonomySummary` (`eligibleIdSet` and `recordsById`) without copying
548
+ * membership arrays (`nodePointsKey` / `memberKeys`), and clones public summary DTOs ONLY for the
549
+ * final paginated slice (`offset` to `offset + limit`).
550
+ *
551
+ * Hinglish: `categories`, `subcategories` aur `amenities` ke liye shared typed search helper;
552
+ * ye cached `eligibleIdSet` aur `recordsById` reuse karta hai bina membership arrays copy kiye,
553
+ * aur sirf final paginated slice ke items ko clone karta hai.
554
+ */
555
+ executeTaxonomySearch(state, target, index, prepared, cloneSummary, request, query, sortBy) {
556
+ const { offset, limit } = resolveBoundedPagination(index, request.pagination, this.maxPageLimit);
557
+ if (prepared.totalRows === 0) {
558
+ return {
559
+ target,
560
+ mallId: state.mallId,
561
+ revision: state.revision,
562
+ items: [],
563
+ totalRows: 0,
564
+ totalMemberCount: 0,
565
+ offset,
566
+ limit,
567
+ hasMore: false,
568
+ nextOffset: null,
569
+ availableFloors: [],
570
+ };
571
+ }
572
+ const isFiltered = hasFilterCriteria(request.filter);
573
+ const allMatched = index.searchAll(query, {
574
+ sortBy,
575
+ ...(isFiltered ? { eligibleIds: prepared.eligibleIdSet } : {}),
576
+ });
577
+ const matchedRecords = [];
578
+ for (let i = 0; i < allMatched.items.length; i++) {
579
+ const record = prepared.recordsById.get(allMatched.items[i].id.trim());
580
+ if (record) {
581
+ matchedRecords.push(record);
582
+ }
583
+ }
584
+ const totalRows = matchedRecords.length;
585
+ if (totalRows === 0) {
586
+ return {
587
+ target,
588
+ mallId: state.mallId,
589
+ revision: state.revision,
590
+ items: [],
591
+ totalRows: 0,
592
+ totalMemberCount: 0,
593
+ offset,
594
+ limit,
595
+ hasMore: false,
596
+ nextOffset: null,
597
+ availableFloors: [],
598
+ };
599
+ }
600
+ let totalMemberCount;
601
+ let availableFloors;
602
+ if (totalRows === prepared.totalRows) {
603
+ totalMemberCount = prepared.totalMemberCount;
604
+ availableFloors = [...prepared.availableFloors];
605
+ }
606
+ else if (totalRows === 1) {
607
+ const single = matchedRecords[0];
608
+ totalMemberCount = single.memberKeys.length;
609
+ availableFloors = [...single.availableFloors];
610
+ }
611
+ else {
612
+ const uniqueMemberKeys = new Set();
613
+ const floorSet = new Set();
614
+ for (let i = 0; i < matchedRecords.length; i++) {
615
+ const rec = matchedRecords[i];
616
+ for (let k = 0; k < rec.memberKeys.length; k++) {
617
+ uniqueMemberKeys.add(rec.memberKeys[k]);
618
+ }
619
+ for (let f = 0; f < rec.availableFloors.length; f++) {
620
+ floorSet.add(rec.availableFloors[f]);
621
+ }
622
+ }
623
+ totalMemberCount = uniqueMemberKeys.size;
624
+ availableFloors = Array.from(floorSet).sort((a, b) => a - b);
625
+ }
626
+ const items = limit > 0
627
+ ? matchedRecords.slice(offset, offset + limit).map((rec) => cloneSummary(rec.summary))
628
+ : [];
629
+ const hasMore = limit === 0 ? totalRows > offset : offset + items.length < totalRows;
630
+ const nextOffset = limit > 0 && hasMore ? offset + items.length : null;
631
+ return {
632
+ target,
633
+ mallId: state.mallId,
634
+ revision: state.revision,
635
+ items,
636
+ totalRows,
637
+ totalMemberCount,
638
+ offset,
639
+ limit,
640
+ hasMore,
641
+ nextOffset,
642
+ availableFloors,
643
+ };
644
+ }
645
+ }
646
+ /**
647
+ * Factory creating the shared `CatalogSearchService` instance; legacy viewer options keep their public name.
648
+ *
649
+ * Hinglish: Shared catalog/search owner ki factory; existing viewer option type ka naam compatible hai.
650
+ */
651
+ export function createCatalogSearchService(options) {
652
+ return new CatalogSearchService(options);
653
+ }