@wovvmap/map-data 0.0.0-stage → 1.2.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.
Files changed (98) hide show
  1. package/README.md +85 -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,1799 @@
1
+ /**
2
+ * @file catalogReader.ts
3
+ * @description Focused, read-only `CatalogReadPort` adapter backed by the committed `ParsedMapResult`
4
+ * and `NodeDataIndexerService`. Serves bounded public pages for stores, categories, subcategories,
5
+ * amenities, and offers, multi-location group summaries/members, and indexed amenity floor availability
6
+ * without introducing a second writable catalog store or repeating full-map node scans.
7
+ *
8
+ * Hinglish: Committed `ParsedMapResult` aur `NodeDataIndexerService` ke existing O(1) indexes ke upar
9
+ * bana read-only `CatalogReadPort` adapter. Ye bina naye global writable store ya full-map node scan ke
10
+ * bounded public catalog pages, multi-location group details aur amenity floor availability return karta hai.
11
+ */
12
+ import { freezeDiscoveryState, toPublicWeeklyHours } from '@wovvmap/contracts';
13
+ import { OfferAvailability } from './offerAvailability.js';
14
+ /**
15
+ * Default page size when `pagination.limit` is omitted.
16
+ * Jab `pagination.limit` na diya ho tab use hone wala default bounded page size.
17
+ */
18
+ export const DEFAULT_CATALOG_PAGE_LIMIT = 50;
19
+ /**
20
+ * Maximum bounded page size allowed in a single catalog or group-member read.
21
+ * Ek single catalog ya group-member read me allowed maximum bounded page size.
22
+ */
23
+ export const MAX_CATALOG_PAGE_LIMIT = 500;
24
+ const MAX_REVISION_QUERY_CACHE_ENTRIES = 64;
25
+ /**
26
+ * Deterministic error thrown when a catalog page read cannot be satisfied safely.
27
+ * Stale map revision, mall mismatch, unloaded catalog ya unsupported Phase 2 sort/search request par throw hone wala error.
28
+ */
29
+ export class CatalogReadError extends Error {
30
+ code;
31
+ details;
32
+ constructor(code, message, details) {
33
+ super(message);
34
+ this.name = 'CatalogReadError';
35
+ this.code = code;
36
+ if (details !== undefined) {
37
+ this.details = Object.freeze({ ...details });
38
+ }
39
+ }
40
+ }
41
+ function setBoundedCacheEntry(cache, key, value) {
42
+ if (!cache.has(key) && cache.size >= MAX_REVISION_QUERY_CACHE_ENTRIES) {
43
+ const oldestKey = cache.keys().next().value;
44
+ if (oldestKey !== undefined) {
45
+ cache.delete(oldestKey);
46
+ }
47
+ }
48
+ cache.set(key, value);
49
+ }
50
+ function normalizeLookupKey(value) {
51
+ if (value === undefined || value === null) {
52
+ return undefined;
53
+ }
54
+ if (typeof value === 'number') {
55
+ if (!Number.isFinite(value)) {
56
+ return undefined;
57
+ }
58
+ return String(value);
59
+ }
60
+ if (typeof value === 'string') {
61
+ const trimmed = value.trim();
62
+ return trimmed !== '' ? trimmed : undefined;
63
+ }
64
+ return undefined;
65
+ }
66
+ function normalizeFloorFilter(value) {
67
+ if (value === undefined) {
68
+ return undefined;
69
+ }
70
+ return typeof value === 'number' && Number.isInteger(value) ? value : undefined;
71
+ }
72
+ function normalizeFilterInput(filter) {
73
+ const categoryKey = normalizeLookupKey(filter?.categoryCode);
74
+ const subCategoryKey = normalizeLookupKey(filter?.subCategoryCode);
75
+ const amenityKey = normalizeLookupKey(filter?.amenityId);
76
+ const floorIndex = normalizeFloorFilter(filter?.floorIndex);
77
+ const offersOnly = filter?.offersOnly === true;
78
+ return {
79
+ ...(categoryKey !== undefined ? { categoryKey } : {}),
80
+ ...(subCategoryKey !== undefined ? { subCategoryKey } : {}),
81
+ ...(amenityKey !== undefined ? { amenityKey } : {}),
82
+ ...(floorIndex !== undefined ? { floorIndex } : {}),
83
+ offersOnly,
84
+ };
85
+ }
86
+ /**
87
+ * Builds an unambiguous JSON tuple cache key for normalized filter criteria so IDs containing
88
+ * delimiter characters (such as `|`) never collide across fields.
89
+ *
90
+ * Hinglish: Normalized filter criteria ke liye JSON tuple cache key banata hai taaki `|` jaise
91
+ * delimiter characters hone par bhi alag filters ki cache key kabhi collide na ho.
92
+ */
93
+ function buildCriteriaCacheKey(criteria, extra = '') {
94
+ return JSON.stringify([
95
+ criteria.categoryKey ?? null,
96
+ criteria.subCategoryKey ?? null,
97
+ criteria.amenityKey ?? null,
98
+ criteria.floorIndex ?? null,
99
+ criteria.offersOnly ? 1 : 0,
100
+ extra,
101
+ ]);
102
+ }
103
+ function normalizePagination(pagination, defaultLimit, maxLimit) {
104
+ const rawOffset = pagination?.offset;
105
+ const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) && rawOffset > 0
106
+ ? Math.floor(rawOffset)
107
+ : 0;
108
+ const rawLimit = pagination?.limit;
109
+ if (rawLimit === undefined) {
110
+ return { offset, limit: Math.min(defaultLimit, maxLimit) };
111
+ }
112
+ if (typeof rawLimit !== 'number' || !Number.isFinite(rawLimit) || rawLimit <= 0) {
113
+ return { offset, limit: 0 };
114
+ }
115
+ return {
116
+ offset,
117
+ limit: Math.min(Math.floor(rawLimit), maxLimit),
118
+ };
119
+ }
120
+ function clonePublicOffer(offer) {
121
+ return { ...offer };
122
+ }
123
+ /**
124
+ * Creates a fresh mutable plain-object copy of a cached `PublicNodeData` projection
125
+ * so external consumer mutations on returned catalog pages cannot corrupt cached or canonical state.
126
+ *
127
+ * Hinglish: Cached `PublicNodeData` projection ki fresh plain-object copy banata hai taaki
128
+ * caller dwara returned page items me kiya gaya koi bhi mutation internal state ko affect na kare.
129
+ */
130
+ function clonePublicNodeData(source) {
131
+ const cloned = {
132
+ key: source.key,
133
+ type: source.type,
134
+ floorIndex: source.floorIndex,
135
+ floorName: source.floorName,
136
+ ...(source.categoryCode !== undefined ? { categoryCode: source.categoryCode } : {}),
137
+ ...(source.subCategoryCode !== undefined ? { subCategoryCode: source.subCategoryCode } : {}),
138
+ ...(source.categoryName !== undefined ? { categoryName: source.categoryName } : {}),
139
+ ...(source.subCategoryName !== undefined ? { subCategoryName: source.subCategoryName } : {}),
140
+ ...(source.amenitiesId !== undefined ? { amenitiesId: source.amenitiesId } : {}),
141
+ contactInfo: {
142
+ description: source.contactInfo.description,
143
+ phone_no: source.contactInfo.phone_no,
144
+ website: source.contactInfo.website,
145
+ email: source.contactInfo.email,
146
+ address: source.contactInfo.address,
147
+ },
148
+ assets: {
149
+ locationName: source.assets.locationName ? { text: source.assets.locationName.text } : null,
150
+ logo: source.assets.logo,
151
+ brandLogo: source.assets.brandLogo,
152
+ brandImages: [...source.assets.brandImages],
153
+ },
154
+ };
155
+ if (source.offers && source.offers.length > 0) {
156
+ cloned.offers = source.offers.map(clonePublicOffer);
157
+ }
158
+ if (source.paidPromotion) {
159
+ cloned.paidPromotion = { ...source.paidPromotion };
160
+ }
161
+ const weeklyHours = toPublicWeeklyHours(source.weeklyHours);
162
+ if (weeklyHours)
163
+ cloned.weeklyHours = weeklyHours;
164
+ return cloned;
165
+ }
166
+ export function clonePublicCategoryData(source) {
167
+ return {
168
+ code: source.code,
169
+ name: source.name,
170
+ image: source.image,
171
+ subCategoryCodes: [...source.subCategoryCodes],
172
+ storeCount: source.storeCount,
173
+ ...(source.hasOffers !== undefined ? { hasOffers: source.hasOffers } : {}),
174
+ };
175
+ }
176
+ export function clonePublicSubCategoryData(source) {
177
+ return {
178
+ code: source.code,
179
+ name: source.name,
180
+ categoryCode: source.categoryCode,
181
+ image: source.image,
182
+ description: source.description,
183
+ storeCount: source.storeCount,
184
+ ...(source.hasOffers !== undefined ? { hasOffers: source.hasOffers } : {}),
185
+ };
186
+ }
187
+ export function clonePublicAmenityData(source) {
188
+ return {
189
+ id: source.id,
190
+ fieldCode: source.fieldCode,
191
+ name: source.name,
192
+ image: source.image,
193
+ status: source.status,
194
+ ...(source.wayfindingId !== undefined ? { wayfindingId: source.wayfindingId } : {}),
195
+ memberCount: source.memberCount,
196
+ availableFloors: [...source.availableFloors],
197
+ };
198
+ }
199
+ /**
200
+ * Resolves the recommended canonical floor index for an amenity using the current-floor-first policy
201
+ * and floor-context fallback order (active floor -> lower floors descending -> upper floors ascending).
202
+ * Preserves `0` (ground floor) as a valid floor index.
203
+ *
204
+ * Hinglish: Current-floor-first rule ke hisab se amenity ka recommended floor nikalta hai:
205
+ * agar active floor par amenity hai to wahi floor (`0` samet), warna pehle niche ke floors descending
206
+ * order me aur phir upar ke floors ascending order me check karta hai.
207
+ */
208
+ export function resolveRecommendedAmenityFloor(availableFloors, activeFloorIndex) {
209
+ if (availableFloors.length === 0) {
210
+ return null;
211
+ }
212
+ if (activeFloorIndex === undefined ||
213
+ typeof activeFloorIndex !== 'number' ||
214
+ !Number.isInteger(activeFloorIndex)) {
215
+ return availableFloors[0] ?? null;
216
+ }
217
+ if (availableFloors.includes(activeFloorIndex)) {
218
+ return activeFloorIndex;
219
+ }
220
+ let bestLowerFloor = null;
221
+ let bestUpperFloor = null;
222
+ for (const floor of availableFloors) {
223
+ if (floor < activeFloorIndex) {
224
+ if (bestLowerFloor === null || floor > bestLowerFloor) {
225
+ bestLowerFloor = floor;
226
+ }
227
+ }
228
+ else if (floor > activeFloorIndex) {
229
+ if (bestUpperFloor === null || floor < bestUpperFloor) {
230
+ bestUpperFloor = floor;
231
+ }
232
+ }
233
+ }
234
+ return bestLowerFloor ?? bestUpperFloor ?? availableFloors[0] ?? null;
235
+ }
236
+ /**
237
+ * Focused catalog read adapter implementing `CatalogReadPort` over a committed `ParsedMapResult`
238
+ * and `NodeDataIndexerService`.
239
+ *
240
+ * Hinglish: Committed `ParsedMapResult` aur `NodeDataIndexerService` ke indexes se public store,
241
+ * category, subcategory, amenity, offer aur group pages serve karne wala `CatalogReadPort` adapter.
242
+ */
243
+ export class CatalogReader {
244
+ committed = null;
245
+ now;
246
+ offerTimer;
247
+ offerHandler;
248
+ revisionSequence = 0;
249
+ lifecycleEpoch = 0;
250
+ defaultPageLimit;
251
+ maxPageLimit;
252
+ constructor(options) {
253
+ this.now = options?.now ?? (() => Date.now());
254
+ const rawDefault = options?.defaultPageLimit ?? DEFAULT_CATALOG_PAGE_LIMIT;
255
+ const rawMax = options?.maxPageLimit ?? MAX_CATALOG_PAGE_LIMIT;
256
+ this.maxPageLimit =
257
+ typeof rawMax === 'number' && Number.isFinite(rawMax) && rawMax > 0
258
+ ? Math.floor(rawMax)
259
+ : MAX_CATALOG_PAGE_LIMIT;
260
+ this.defaultPageLimit =
261
+ typeof rawDefault === 'number' && Number.isFinite(rawDefault) && rawDefault > 0
262
+ ? Math.min(Math.floor(rawDefault), this.maxPageLimit)
263
+ : Math.min(DEFAULT_CATALOG_PAGE_LIMIT, this.maxPageLimit);
264
+ if (options?.parsedMap) {
265
+ this.commitMap(options.parsedMap, options.revision);
266
+ }
267
+ }
268
+ /**
269
+ * Prepares a candidate catalog state and warms baseline taxonomy summaries WITHOUT mutating
270
+ * the currently active committed catalog or revision sequence. Used by `@wovvmap/sdk-web`
271
+ * to prepare candidate search indexes before atomically publishing the new map revision.
272
+ *
273
+ * Hinglish: Active committed catalog ya revision sequence ko mutate kiye bina candidate
274
+ * catalog state aur baseline taxonomy summaries prepare karta hai.
275
+ */
276
+ prepareCommitCandidate(source, revision) {
277
+ if (!source || typeof source !== 'object' || !source.indexer) {
278
+ throw new Error('[CatalogReader] Cannot commit an invalid map source without an indexer.');
279
+ }
280
+ const mallId = typeof source.mallId === 'string' ? source.mallId.trim() : '';
281
+ if (mallId === '') {
282
+ throw new Error('[CatalogReader] Cannot commit a map source with an empty mallId.');
283
+ }
284
+ const nextSequence = this.revisionSequence + 1;
285
+ let resolvedRevision = nextSequence;
286
+ if (revision !== undefined && revision !== null) {
287
+ if (typeof revision === 'number' && Number.isFinite(revision)) {
288
+ resolvedRevision = revision;
289
+ }
290
+ else if (typeof revision === 'string' && revision.trim() !== '') {
291
+ resolvedRevision = revision.trim();
292
+ }
293
+ }
294
+ const indexerContext = source.indexer.getContext({ includeMemberships: false });
295
+ const candidateState = {
296
+ mallId,
297
+ revision: resolvedRevision,
298
+ indexer: source.indexer,
299
+ offers: new OfferAvailability(source.indexer, this.now),
300
+ categories: indexerContext.categories ?? source.categories ?? null,
301
+ subCategories: indexerContext.subCategories ?? source.subCategories ?? null,
302
+ amenities: indexerContext.amenities ?? source.amenities ?? null,
303
+ amenityAliases: new Map(),
304
+ storesQueryCache: new Map(),
305
+ categoriesQueryCache: new Map(),
306
+ subCategoriesQueryCache: new Map(),
307
+ amenitiesQueryCache: new Map(),
308
+ offersQueryCache: new Map(),
309
+ };
310
+ // Index taxonomy aliases once per revision; amenity interactions never search all definitions/nodes.
311
+ // Hinglish: Chhoti amenity taxonomy ka alias index load par bane; click par dobara loop nahi.
312
+ for (const [key, amenity] of Object.entries(candidateState.amenities ?? {})) {
313
+ const canonicalKey = normalizeLookupKey(amenity.id) ?? key;
314
+ const entry = { canonicalKey, publicId: amenity.id, amenity };
315
+ for (const alias of [canonicalKey, normalizeLookupKey(amenity.fieldCode)]) {
316
+ if (alias !== undefined && !candidateState.amenityAliases.has(alias))
317
+ candidateState.amenityAliases.set(alias, entry);
318
+ }
319
+ }
320
+ return {
321
+ mallId,
322
+ revision: resolvedRevision,
323
+ nextSequence,
324
+ state: candidateState,
325
+ };
326
+ }
327
+ /**
328
+ * Returns baseline (unfiltered) taxonomy summary documents for a prepared candidate state
329
+ * so candidate `SearchIndex` instances can be built before `applyCommitCandidate` is called.
330
+ *
331
+ * Hinglish: Prepared candidate state ke liye baseline taxonomy summaries return karta hai
332
+ * taaki `applyCommitCandidate` call hone se pehle candidate search indexes ban sakein.
333
+ */
334
+ getCandidateTaxonomySummaries(candidate) {
335
+ const emptyCriteria = normalizeFilterInput(undefined);
336
+ const categoriesSummary = this.prepareCategoriesSummary(candidate.state, emptyCriteria);
337
+ const subCategoriesSummary = this.prepareSubCategoriesSummary(candidate.state, emptyCriteria);
338
+ const amenitiesSummary = this.prepareAmenitiesSummary(candidate.state, emptyCriteria);
339
+ return {
340
+ categories: categoriesSummary.records.map((r) => r.summary),
341
+ subCategories: subCategoriesSummary.records.map((r) => r.summary),
342
+ amenities: amenitiesSummary.records.map((r) => r.summary),
343
+ };
344
+ }
345
+ /**
346
+ * Atomically swaps the active committed catalog state to a previously prepared candidate.
347
+ *
348
+ * Hinglish: Pehle se prepare kiye gaye candidate state ko ek saath active committed catalog me swap karta hai.
349
+ */
350
+ applyCommitCandidate(candidate) {
351
+ this.lifecycleEpoch++;
352
+ if (candidate.nextSequence > this.revisionSequence) {
353
+ this.revisionSequence = candidate.nextSequence;
354
+ }
355
+ else {
356
+ this.revisionSequence++;
357
+ }
358
+ this.committed = candidate.state;
359
+ this.scheduleOfferChange();
360
+ return {
361
+ mallId: this.committed.mallId,
362
+ revision: this.committed.revision,
363
+ };
364
+ }
365
+ /**
366
+ * Atomically commits a parsed map result as the active catalog source and advances the revision.
367
+ * Reads taxonomy definitions without copying node membership arrays (`includeMemberships: false`)
368
+ * because membership lookups are served directly from `NodeDataIndexerService`.
369
+ *
370
+ * Hinglish: Successfully parsed map result ko active catalog source ke roop me commit karta hai
371
+ * aur map revision update karta hai (bina `nodePoints` ya `nodePointsKey` arrays dobara copy kiye).
372
+ */
373
+ commitMap(source, revision) {
374
+ const candidate = this.prepareCommitCandidate(source, revision);
375
+ return this.applyCommitCandidate(candidate);
376
+ }
377
+ /**
378
+ * Executes a replacement map load and swaps the committed catalog ONLY when the load succeeds
379
+ * and remains the active, un-cleared, un-superseded lifecycle epoch. Failed, aborted, cleared,
380
+ * or superseded loads retain the current committed state.
381
+ *
382
+ * Hinglish: Replacement map load execute karta hai aur sirf tab active catalog swap karta hai jab
383
+ * load succeed ho aur beech me `clear()`, `commitMap()`, ya naya `replaceFromLoad()` call na hua ho.
384
+ */
385
+ async replaceFromLoad(loadOperation, options) {
386
+ const operationEpoch = ++this.lifecycleEpoch;
387
+ if (options?.signal?.aborted) {
388
+ throw new Error('[CatalogReader] Replacement map load aborted before execution.');
389
+ }
390
+ if (options?.isValid && !options.isValid()) {
391
+ throw new Error('[CatalogReader] Replacement map load superseded before execution.');
392
+ }
393
+ const nextSource = await loadOperation();
394
+ if (this.lifecycleEpoch !== operationEpoch) {
395
+ throw new Error('[CatalogReader] Replacement map load superseded before commit.');
396
+ }
397
+ if (options?.signal?.aborted) {
398
+ throw new Error('[CatalogReader] Replacement map load aborted before commit.');
399
+ }
400
+ if (options?.isValid && !options.isValid()) {
401
+ throw new Error('[CatalogReader] Replacement map load superseded before commit.');
402
+ }
403
+ return this.commitMap(nextSource, options?.revision);
404
+ }
405
+ /**
406
+ * Clears the committed map reference on viewer teardown and invalidates any pending load continuation.
407
+ * Viewer teardown par committed catalog reference clear karta hai aur pending continuation invalidate karta hai.
408
+ */
409
+ clear() {
410
+ this.lifecycleEpoch++;
411
+ this.committed = null;
412
+ if (this.offerTimer !== undefined)
413
+ clearTimeout(this.offerTimer);
414
+ this.offerTimer = undefined;
415
+ }
416
+ /**
417
+ * Returns the currently committed mall identifier and map revision, or `null` when no map is loaded.
418
+ * Currently committed `mallId` aur `revision` return karta hai (map load na hone par `null`).
419
+ */
420
+ getRevision() {
421
+ if (!this.committed) {
422
+ return null;
423
+ }
424
+ return {
425
+ mallId: this.committed.mallId,
426
+ revision: this.committed.revision,
427
+ };
428
+ }
429
+ /**
430
+ * Checks whether the provided `mallId` and `expectedRevision` match the currently committed catalog.
431
+ * Check karta hai ki diye gaye `mallId` aur `expectedRevision` current committed catalog se match karte hain ya nahi.
432
+ */
433
+ isRevisionMatch(options) {
434
+ // Nullable group reads share expiry revalidation with throwing catalog reads.
435
+ // Hinglish: Group reads mein bhi timer ke bina current offer dates resolve hon.
436
+ this.refreshOffers();
437
+ if (!this.committed) {
438
+ return false;
439
+ }
440
+ if (options?.mallId !== undefined) {
441
+ if (options.mallId.trim() !== this.committed.mallId) {
442
+ return false;
443
+ }
444
+ }
445
+ if (options?.expectedRevision !== undefined) {
446
+ const expectedKey = normalizeLookupKey(options.expectedRevision);
447
+ const actualKey = normalizeLookupKey(this.committed.revision);
448
+ if (expectedKey === undefined || expectedKey !== actualKey) {
449
+ return false;
450
+ }
451
+ }
452
+ return true;
453
+ }
454
+ /**
455
+ * Validates in O(1) that a map is currently committed and matches optional `mallId` and `expectedRevision`
456
+ * without resolving or copying any store keys. Throws `CatalogReadError` (`NO_COMMITTED_MAP`,
457
+ * `MALL_MISMATCH`, or `STALE_REVISION`) on mismatch.
458
+ *
459
+ * Hinglish: Bina kisi store keys ko resolve ya copy kiye O(1) me committed map, `mallId` aur `expectedRevision`
460
+ * validate karta hai aur mismatch par `CatalogReadError` throw karta hai.
461
+ */
462
+ assertCommittedIdentity(options) {
463
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
464
+ return {
465
+ mallId: state.mallId,
466
+ revision: state.revision,
467
+ };
468
+ }
469
+ /** Resolve persistent membership through the same normalized indexes as catalog/search reads.
470
+ * Hinglish: List/search wale same evaluator se keys niklein; UI rows ya raw nodes scan na hon. */
471
+ resolveDiscoveryFilter(request, activeFloorIndex) {
472
+ const state = this.assertValidCommittedState(request.mallId, request.expectedRevision);
473
+ const criteria = normalizeFilterInput(request);
474
+ const { categoryKey, subCategoryKey, amenityKey, floorIndex, offersOnly } = criteria;
475
+ if (floorIndex !== undefined ||
476
+ (amenityKey !== undefined &&
477
+ (categoryKey !== undefined || subCategoryKey !== undefined || offersOnly)) ||
478
+ (subCategoryKey !== undefined &&
479
+ (categoryKey === undefined ||
480
+ !state.indexer.hasSubCategoryInCategory(categoryKey, subCategoryKey)))) {
481
+ throw new CatalogReadError('UNSUPPORTED_FILTER_COMBINATION', 'Discovery requires a matching category/subcategory pair or an amenity alone; persistent floor filters are unsupported.');
482
+ }
483
+ if (amenityKey !== undefined) {
484
+ const resolved = this.resolveCanonicalAmenityEntry(state, amenityKey);
485
+ if (!resolved)
486
+ throw new CatalogReadError('AMENITY_NOT_FOUND', `Amenity "${amenityKey}" is missing or disabled.`);
487
+ const keys = state.indexer.getNodeKeysByAmenity(resolved.canonicalKey);
488
+ const floors = state.indexer.getAmenityFloors(resolved.canonicalKey);
489
+ const source = resolved.amenity;
490
+ const amenity = {
491
+ id: resolved.publicId,
492
+ fieldCode: source?.fieldCode ?? resolved.publicId,
493
+ name: source?.name ?? String(resolved.publicId),
494
+ image: source?.image?.trim() || null,
495
+ status: source?.status ?? 1,
496
+ wayfindingId: source?.wayfinding_id ?? null,
497
+ memberCount: keys.length,
498
+ availableFloors: [...floors],
499
+ };
500
+ return {
501
+ keys,
502
+ state: freezeDiscoveryState({
503
+ mallId: state.mallId,
504
+ revision: state.revision,
505
+ filter: { amenityId: String(resolved.publicId) },
506
+ memberCount: keys.length,
507
+ category: null,
508
+ subcategory: null,
509
+ amenity,
510
+ }),
511
+ recommendedFloorIndex: keys.length === 0 ? null : resolveRecommendedAmenityFloor(floors, activeFloorIndex),
512
+ };
513
+ }
514
+ const filter = {
515
+ ...(categoryKey !== undefined ? { categoryCode: categoryKey } : {}),
516
+ ...(subCategoryKey !== undefined ? { subCategoryCode: subCategoryKey } : {}),
517
+ ...(offersOnly ? { offersOnly: true } : {}),
518
+ };
519
+ if (Object.keys(filter).length === 0)
520
+ return { state: null, keys: [] };
521
+ const keys = this.resolveFilteredStoreKeys(state, criteria);
522
+ const category = categoryKey === undefined ? undefined : state.categories?.[categoryKey];
523
+ const subcategory = subCategoryKey === undefined ? undefined : state.subCategories?.[subCategoryKey];
524
+ return {
525
+ keys,
526
+ state: freezeDiscoveryState({
527
+ mallId: state.mallId,
528
+ revision: state.revision,
529
+ filter,
530
+ memberCount: keys.length,
531
+ category: categoryKey === undefined
532
+ ? null
533
+ : {
534
+ code: category?.code ?? categoryKey,
535
+ name: category?.name ?? categoryKey,
536
+ image: category?.image ?? null,
537
+ },
538
+ subcategory: subCategoryKey === undefined
539
+ ? null
540
+ : {
541
+ code: subcategory?.code ?? subCategoryKey,
542
+ name: subcategory?.name ?? subCategoryKey,
543
+ categoryCode: category?.code ?? categoryKey,
544
+ },
545
+ }),
546
+ };
547
+ }
548
+ /**
549
+ * Resolves candidate store node keys in deterministic map source order using `NodeDataIndexerService`
550
+ * membership indexes without scanning unrelated nodes. Shared by catalog store reads, group reads,
551
+ * and future Phase 2 search candidate preparation.
552
+ *
553
+ * Hinglish: `NodeDataIndexerService` ke O(1) membership indexes se map source order me matching
554
+ * store node keys return karta hai (bina full-map scan ke). Future search queries bhi yahi candidate keys reuse karengi.
555
+ */
556
+ getCandidateStoreKeys(filter, options) {
557
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
558
+ return [...this.resolveFilteredStoreKeys(state, normalizeFilterInput(filter))];
559
+ }
560
+ /**
561
+ * Returns the cached lightweight `PreparedTaxonomySummary<PublicCategoryData>` for the given filter
562
+ * without cloning summaries or membership arrays. Used by `@wovvmap/sdk-web` taxonomy search
563
+ * so only the final paginated slice is cloned.
564
+ *
565
+ * Hinglish: Filter ke liye cached lightweight `PreparedTaxonomySummary<PublicCategoryData>` return karta hai
566
+ * bina summaries ya membership arrays clone kiye.
567
+ */
568
+ getPreparedCategoriesSummary(filter, options) {
569
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
570
+ return this.prepareCategoriesSummary(state, normalizeFilterInput(filter));
571
+ }
572
+ /**
573
+ * Returns the cached lightweight `PreparedTaxonomySummary<PublicSubCategoryData>` for the given filter
574
+ * without cloning summaries or membership arrays. Used by `@wovvmap/sdk-web` taxonomy search
575
+ * so only the final paginated slice is cloned.
576
+ *
577
+ * Hinglish: Filter ke liye cached lightweight `PreparedTaxonomySummary<PublicSubCategoryData>` return karta hai
578
+ * bina summaries ya membership arrays clone kiye.
579
+ */
580
+ getPreparedSubCategoriesSummary(filter, options) {
581
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
582
+ return this.prepareSubCategoriesSummary(state, normalizeFilterInput(filter));
583
+ }
584
+ /**
585
+ * Returns the cached lightweight `PreparedTaxonomySummary<PublicAmenityData>` for the given filter
586
+ * without cloning summaries or membership arrays. Used by `@wovvmap/sdk-web` taxonomy search
587
+ * so only the final paginated slice is cloned.
588
+ *
589
+ * Hinglish: Filter ke liye cached lightweight `PreparedTaxonomySummary<PublicAmenityData>` return karta hai
590
+ * bina summaries ya membership arrays clone kiye.
591
+ */
592
+ getPreparedAmenitiesSummary(filter, options) {
593
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
594
+ return this.prepareAmenitiesSummary(state, normalizeFilterInput(filter));
595
+ }
596
+ /**
597
+ * Returns all eligible public category summaries for the given filter without page-size truncation,
598
+ * reusing the revision-scoped taxonomy query cache. Used by SDK search index preparation and filtered category search.
599
+ *
600
+ * Hinglish: Bina page-size truncation ke filter ke matching public category summaries return karta hai
601
+ * (revision-scoped taxonomy cache reuse karte hue).
602
+ */
603
+ getEligibleCategories(filter, options) {
604
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
605
+ const prepared = this.prepareCategoriesSummary(state, normalizeFilterInput(filter));
606
+ return prepared.records.map((r) => clonePublicCategoryData(r.summary));
607
+ }
608
+ /**
609
+ * Returns all eligible public subcategory summaries for the given filter without page-size truncation,
610
+ * reusing the revision-scoped taxonomy query cache. Used by SDK search index preparation and filtered subcategory search.
611
+ *
612
+ * Hinglish: Bina page-size truncation ke filter ke matching public subcategory summaries return karta hai
613
+ * (revision-scoped taxonomy cache reuse karte hue).
614
+ */
615
+ getEligibleSubCategories(filter, options) {
616
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
617
+ const prepared = this.prepareSubCategoriesSummary(state, normalizeFilterInput(filter));
618
+ return prepared.records.map((r) => clonePublicSubCategoryData(r.summary));
619
+ }
620
+ /**
621
+ * Returns all eligible public amenity summaries for the given filter without page-size truncation,
622
+ * reusing the revision-scoped taxonomy query cache. Used by SDK search index preparation and filtered amenity search.
623
+ *
624
+ * Hinglish: Bina page-size truncation ke filter ke matching public amenity summaries return karta hai
625
+ * (revision-scoped taxonomy cache reuse karte hue).
626
+ */
627
+ getEligibleAmenities(filter, options) {
628
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
629
+ const prepared = this.prepareAmenitiesSummary(state, normalizeFilterInput(filter));
630
+ return prepared.records.map((r) => clonePublicAmenityData(r.summary));
631
+ }
632
+ /**
633
+ * Resolves a cloned public `CatalogStoreRow` (`store` or `group`) for a single store key or a ranked
634
+ * multi-location group descriptor without repeating full-map scans or duplicating projection logic.
635
+ * Group rows in list/search pages use compact summaries (omitting unbounded `memberKeys` and `members`).
636
+ *
637
+ * Hinglish: Single store key ya ranked multi-location group descriptor ke liye fresh cloned public
638
+ * `CatalogStoreRow` (`store` ya `group`) resolve karta hai (compact group summary ke saath).
639
+ */
640
+ resolvePublicStoreRow(descriptor, options) {
641
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
642
+ if (descriptor.kind === 'store') {
643
+ const pub = state.offers.publicNode(descriptor.key);
644
+ return pub ? { kind: 'store', node: clonePublicNodeData(pub) } : null;
645
+ }
646
+ if (descriptor.memberKeys.length === 1) {
647
+ const pub = state.offers.publicNode(descriptor.memberKeys[0]);
648
+ return pub ? { kind: 'store', node: clonePublicNodeData(pub) } : null;
649
+ }
650
+ const groupData = this.buildPublicNodeGroupData(state, descriptor.groupId, descriptor.memberKeys, options?.activeFloorIndex, descriptor.representativeKey, false, descriptor.availableFloors);
651
+ return groupData ? { kind: 'group', group: groupData } : null;
652
+ }
653
+ /**
654
+ * Collects sorted unique canonical floor indices for the given node keys using the committed indexer.
655
+ *
656
+ * Hinglish: Diye gaye node keys ke sorted unique canonical floor indices return karta hai.
657
+ */
658
+ collectSortedFloorsForNodeKeys(keys, options) {
659
+ const state = this.assertValidCommittedState(options?.mallId, options?.expectedRevision);
660
+ return this.collectSortedFloorsForKeys(state.indexer, keys);
661
+ }
662
+ /**
663
+ * Reads a bounded page of public items for the requested catalog target.
664
+ * Preserves map source order as the deterministic baseline and rejects stale map revisions
665
+ * or unimplemented Phase 2 sort/search options rather than silently ignoring them.
666
+ *
667
+ * Hinglish: Requested catalog target ke liye bounded public page return karta hai.
668
+ * Map source order ko baseline rakhta hai aur stale revision ya Phase 2 sort/search options ko silently ignore karne ke bajay reject karta hai.
669
+ */
670
+ readCatalog(request) {
671
+ const state = this.assertValidCommittedState(request.mallId, request.expectedRevision);
672
+ this.assertSupportedPhase1BaselineRequest(request);
673
+ const pagination = normalizePagination(request.pagination, this.defaultPageLimit, this.maxPageLimit);
674
+ const criteria = normalizeFilterInput(request.filter);
675
+ switch (request.target) {
676
+ case 'stores':
677
+ return this.readStoresPage(state, request, criteria, pagination);
678
+ case 'categories':
679
+ return this.readCategoriesPage(state, criteria, pagination);
680
+ case 'subcategories':
681
+ return this.readSubCategoriesPage(state, criteria, pagination);
682
+ case 'amenities':
683
+ return this.readAmenitiesPage(state, criteria, pagination);
684
+ case 'offers':
685
+ return this.readOffersPage(state, criteria, pagination);
686
+ default: {
687
+ const exhaustiveCheck = request.target;
688
+ throw new Error(`[CatalogReader] Unsupported catalog target: ${String(exhaustiveCheck)}`);
689
+ }
690
+ }
691
+ }
692
+ /**
693
+ * Resolves a multi-location store group summary by its stable `groupId`, scoped by optional
694
+ * revision, filter, and active floor. Returns `null` on revision mismatch or when no eligible
695
+ * store members match. Never reintroduces filtered-out members.
696
+ *
697
+ * Hinglish: Stable `groupId` se multi-location store group ka public summary return karta hai.
698
+ * Filter lagne par excluded members ko wapas include nahi karta aur stale revision par `null` deta hai.
699
+ */
700
+ getStoreGroupById(groupId, options) {
701
+ if (!this.isRevisionMatch(options)) {
702
+ return null;
703
+ }
704
+ const state = this.committed;
705
+ if (!groupId || groupId.trim() === '') {
706
+ return null;
707
+ }
708
+ const eligibleGroupKeys = this.resolveEligibleGroupMemberKeys(state, groupId, options?.filter ? normalizeFilterInput(options.filter) : undefined);
709
+ if (eligibleGroupKeys.length === 0) {
710
+ return null;
711
+ }
712
+ return this.buildPublicNodeGroupData(state, groupId, eligibleGroupKeys, options?.activeFloorIndex, undefined, true);
713
+ }
714
+ /**
715
+ * Resolves canonical group member keys filtered by optional `filter` criteria from the committed group index
716
+ * without scanning the full map. Returns `null` on revision mismatch or when no eligible members match.
717
+ *
718
+ * Hinglish: Committed canonical group index se filter-eligible member keys resolve karta hai
719
+ * (bina full-map scan ke); stale revision ya 0 matching members par `null` deta hai.
720
+ */
721
+ getEligibleGroupMemberKeys(groupId, options) {
722
+ if (!this.isRevisionMatch(options)) {
723
+ return null;
724
+ }
725
+ const state = this.committed;
726
+ if (!groupId || groupId.trim() === '') {
727
+ return null;
728
+ }
729
+ const eligibleKeys = this.resolveEligibleGroupMemberKeys(state, groupId, options?.filter ? normalizeFilterInput(options.filter) : undefined);
730
+ return eligibleKeys.length > 0 ? eligibleKeys : null;
731
+ }
732
+ /**
733
+ * Materializes a bounded `CatalogGroupMembersPage` (`[offset, offset + limit)`) from an ordered list
734
+ * of eligible group member keys while computing `totalMemberCount` and `availableFloors` across all
735
+ * provided eligible keys.
736
+ *
737
+ * Hinglish: Eligible group member keys ki ordered list se bounded `CatalogGroupMembersPage` banata hai
738
+ * (`[offset, offset + limit)` slice ke saath) aur poori eligible group ka `totalMemberCount` aur `availableFloors` rakhta hai.
739
+ */
740
+ buildGroupMembersPageFromKeys(groupId, eligibleGroupKeys, options) {
741
+ if (!this.isRevisionMatch(options)) {
742
+ return null;
743
+ }
744
+ const state = this.committed;
745
+ if (!groupId || groupId.trim() === '' || eligibleGroupKeys.length === 0) {
746
+ return null;
747
+ }
748
+ const availableFloors = this.collectSortedFloorsForKeys(state.indexer, eligibleGroupKeys);
749
+ const { offset, limit } = normalizePagination(options?.pagination, this.defaultPageLimit, this.maxPageLimit);
750
+ const slicedKeys = limit > 0 ? eligibleGroupKeys.slice(offset, offset + limit) : [];
751
+ const items = [];
752
+ const members = [];
753
+ const memberKeys = [];
754
+ for (const key of slicedKeys) {
755
+ const pub = state.offers.publicNode(key);
756
+ if (pub) {
757
+ items.push(clonePublicNodeData(pub));
758
+ members.push({
759
+ key: pub.key,
760
+ floorIndex: pub.floorIndex,
761
+ floorName: pub.floorName,
762
+ type: pub.type,
763
+ });
764
+ memberKeys.push(pub.key);
765
+ }
766
+ }
767
+ const totalMemberCount = eligibleGroupKeys.length;
768
+ const hasMore = limit === 0 ? totalMemberCount > offset : offset + items.length < totalMemberCount;
769
+ const nextOffset = hasMore ? offset + items.length : null;
770
+ return {
771
+ groupId,
772
+ mallId: state.mallId,
773
+ revision: state.revision,
774
+ items,
775
+ members,
776
+ memberKeys,
777
+ totalMemberCount,
778
+ offset,
779
+ limit,
780
+ hasMore,
781
+ nextOffset,
782
+ availableFloors,
783
+ };
784
+ }
785
+ /**
786
+ * Reads a bounded page of `PublicNodeData` member projections for a multi-location store group.
787
+ * Never reintroduces excluded members when a filter is supplied, and returns `null` on revision mismatch.
788
+ * `items`, `members`, and `memberKeys` are strictly bounded to `[offset, offset + limit)` while
789
+ * `totalMemberCount` and `availableFloors` reflect the complete eligible group.
790
+ * Note: Query-aware and sort-aware group member expansion belongs to `ViewerCatalogSearchService` (`@wovvmap/sdk-web`)
791
+ * using the prepared `@wovvmap/search-core` store index.
792
+ *
793
+ * Hinglish: Multi-location store group ke eligible members ka bounded `CatalogGroupMembersPage` return karta hai;
794
+ * filter me excluded members ko reintroduce nahi karta, `items`/`members`/`memberKeys` ko `[offset, offset + limit)`
795
+ * tak bounded rakhta hai aur stale revision par `null` deta hai.
796
+ */
797
+ getGroupMembers(request) {
798
+ if (typeof request.query === 'string' && request.query.trim() !== '') {
799
+ throw new CatalogReadError('UNSUPPORTED_SEARCH_QUERY', '[CatalogReader] Query-aware group member expansion requires @wovvmap/search-core via ViewerCatalogSearchService.', { groupId: request.groupId, query: request.query });
800
+ }
801
+ if (request.sortBy !== undefined && request.sortBy !== 'default') {
802
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[CatalogReader] Sort mode "${request.sortBy}" on getGroupMembers requires @wovvmap/search-core via ViewerCatalogSearchService.`, { groupId: request.groupId, sortBy: request.sortBy });
803
+ }
804
+ const eligibleGroupKeys = this.getEligibleGroupMemberKeys(request.groupId, request);
805
+ if (!eligibleGroupKeys) {
806
+ return null;
807
+ }
808
+ return this.buildGroupMembersPageFromKeys(request.groupId, eligibleGroupKeys, request);
809
+ }
810
+ /**
811
+ * Evaluates indexed floor availability for an amenity relative to `activeFloorIndex` in O(1) time.
812
+ * Uses the current-floor-first rule (keeping `activeFloorIndex` when available on that floor,
813
+ * including ground floor `0`) without mutating floor, selection, or camera state.
814
+ *
815
+ * Hinglish: Active floor (`0` samet) ke hisab se amenity ki floor availability aur recommended floor
816
+ * bina kisi side effect ya full node scan ke return karta hai.
817
+ */
818
+ getAmenityFloorAvailability(amenityId, options) {
819
+ if (!this.isRevisionMatch(options)) {
820
+ return null;
821
+ }
822
+ const state = this.committed;
823
+ const resolvedAmenity = this.resolveCanonicalAmenityEntry(state, amenityId);
824
+ if (!resolvedAmenity) {
825
+ return null;
826
+ }
827
+ const { canonicalKey, publicId } = resolvedAmenity;
828
+ const memberKeys = state.indexer.getNodeKeysByAmenity(canonicalKey);
829
+ const availableFloors = state.indexer.getAmenityFloors(canonicalKey);
830
+ const activeFloorIndex = normalizeFloorFilter(options?.activeFloorIndex);
831
+ const isAvailableOnActiveFloor = activeFloorIndex !== undefined
832
+ ? state.indexer.hasAmenityOnFloor(canonicalKey, activeFloorIndex)
833
+ : false;
834
+ const recommendedFloorIndex = isAvailableOnActiveFloor
835
+ ? activeFloorIndex
836
+ : resolveRecommendedAmenityFloor(availableFloors, activeFloorIndex);
837
+ return {
838
+ amenityId: publicId,
839
+ memberKeys: [...memberKeys],
840
+ availableFloors: [...availableFloors],
841
+ isAvailableOnActiveFloor,
842
+ recommendedFloorIndex,
843
+ };
844
+ }
845
+ /** Active public details share catalog eligibility; raw/pending offers stay in prepared metadata only.
846
+ * Hinglish: Selection/card ko wahi active public offers milein; second date logic nahi. */
847
+ getPublicNodeByKey(key) {
848
+ return this.assertValidCommittedState().offers.publicNode(key);
849
+ }
850
+ /** Existing indexed offer boundary, for time-sensitive result leases; does not create a timer or scan nodes.
851
+ * Hinglish: Offer-filtered route ki expiry wahi ready clock se mile; alag date logic/loop nahi. */
852
+ getNextOfferChangeAt() {
853
+ return this.assertValidCommittedState().offers.nextChangeAt;
854
+ }
855
+ /** One owner callback/timer for offer transitions, not a timer or watcher per component.
856
+ * Hinglish: SDK ek handler bind kare; dates badlein to sirf catalog/highlight update ho. */
857
+ setOfferChangeHandler(handler) {
858
+ this.offerHandler = handler;
859
+ this.scheduleOfferChange();
860
+ }
861
+ refreshOffers() {
862
+ const state = this.committed;
863
+ if (!state?.offers.refresh())
864
+ return;
865
+ state.storesQueryCache.clear();
866
+ state.categoriesQueryCache.clear();
867
+ state.subCategoriesQueryCache.clear();
868
+ state.amenitiesQueryCache.clear();
869
+ state.offersQueryCache.clear();
870
+ this.scheduleOfferChange();
871
+ this.offerHandler?.();
872
+ }
873
+ scheduleOfferChange() {
874
+ if (this.offerTimer !== undefined)
875
+ clearTimeout(this.offerTimer);
876
+ this.offerTimer = undefined;
877
+ const next = this.committed?.offers.nextChangeAt;
878
+ if (!this.offerHandler || next === undefined)
879
+ return;
880
+ this.offerTimer = setTimeout(() => {
881
+ this.offerTimer = undefined;
882
+ this.refreshOffers();
883
+ this.scheduleOfferChange();
884
+ }, Math.min(2_147_483_647, Math.max(1, Math.ceil(next - this.now()))));
885
+ }
886
+ // ---------------------------------------------------------------------------
887
+ // Private Validation & Resolution Helpers / Niji Validation aur Lookup Helpers
888
+ // ---------------------------------------------------------------------------
889
+ assertValidCommittedState(expectedMallId, expectedRevision) {
890
+ // Expiry callbacks may clear/replace the map; validate identity after that synchronous event.
891
+ // Hinglish: Expiry event se map badal sakta hai; uske baad current identity validate ho.
892
+ this.refreshOffers();
893
+ if (!this.committed) {
894
+ throw new CatalogReadError('NO_COMMITTED_MAP', '[CatalogReader] Cannot read catalog before a parsed map is committed.');
895
+ }
896
+ if (expectedMallId !== undefined && expectedMallId.trim() !== this.committed.mallId) {
897
+ throw new CatalogReadError('MALL_MISMATCH', `[CatalogReader] Stale catalog read for mall "${expectedMallId}"; active committed mall is "${this.committed.mallId}".`, {
898
+ expectedMallId,
899
+ actualMallId: this.committed.mallId,
900
+ actualRevision: this.committed.revision,
901
+ });
902
+ }
903
+ if (expectedRevision !== undefined) {
904
+ const expectedKey = normalizeLookupKey(expectedRevision);
905
+ const actualKey = normalizeLookupKey(this.committed.revision);
906
+ if (expectedKey === undefined || expectedKey !== actualKey) {
907
+ throw new CatalogReadError('STALE_REVISION', `[CatalogReader] Stale catalog read for revision "${String(expectedRevision)}"; active committed revision is "${String(this.committed.revision)}".`, {
908
+ expectedRevision,
909
+ actualRevision: this.committed.revision,
910
+ mallId: this.committed.mallId,
911
+ });
912
+ }
913
+ }
914
+ return this.committed;
915
+ }
916
+ assertSupportedPhase1BaselineRequest(request) {
917
+ if (request.sortBy !== undefined && request.sortBy !== 'default') {
918
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[CatalogReader] Sort mode "${request.sortBy}" is not supported by the Phase 1D source-order reader; sorting profiles belong to Phase 2 (@wovvmap/search-core).`, { sortBy: request.sortBy });
919
+ }
920
+ if (request.floorSecondarySortBy !== undefined &&
921
+ request.floorSecondarySortBy !== 'relevance') {
922
+ throw new CatalogReadError('UNSUPPORTED_SORT_MODE', `[CatalogReader] Secondary floor sort "${request.floorSecondarySortBy}" requires Phase 2 (@wovvmap/search-core).`, { floorSecondarySortBy: request.floorSecondarySortBy });
923
+ }
924
+ const maybeSearch = request;
925
+ if (typeof maybeSearch.query === 'string' && maybeSearch.query.trim() !== '') {
926
+ throw new CatalogReadError('UNSUPPORTED_SEARCH_QUERY', '[CatalogReader] Non-empty text search queries require Phase 2 (@wovvmap/search-core) and cannot be silently ignored by CatalogReader.', { query: maybeSearch.query });
927
+ }
928
+ }
929
+ resolveFilteredStoreKeys(state, criteria) {
930
+ const { indexer } = state;
931
+ const { categoryKey, subCategoryKey, amenityKey, floorIndex, offersOnly } = criteria;
932
+ // If both category and subcategory are specified, verify the subcategory is a child of the category when taxonomy is configured
933
+ if (categoryKey !== undefined && subCategoryKey !== undefined) {
934
+ const childSubCodes = indexer.getSubCategoryCodesByCategory(categoryKey);
935
+ if (childSubCodes.length > 0 &&
936
+ !indexer.hasSubCategoryInCategory(categoryKey, subCategoryKey)) {
937
+ return [];
938
+ }
939
+ }
940
+ const candidates = [];
941
+ if (subCategoryKey !== undefined && offersOnly) {
942
+ const keys = state.offers.keys(state.indexer.getOfferNodeKeysBySubCategory(subCategoryKey));
943
+ candidates.push({
944
+ count: keys.length,
945
+ resolveKeys: () => keys,
946
+ usedCategory: false,
947
+ usedSubCategory: true,
948
+ usedAmenity: false,
949
+ usedOffers: true,
950
+ usedFloor: false,
951
+ guaranteedEligibleStore: true,
952
+ });
953
+ }
954
+ else if (subCategoryKey !== undefined) {
955
+ const keys = indexer.getNodeKeysBySubCategory(subCategoryKey);
956
+ candidates.push({
957
+ count: keys.length,
958
+ resolveKeys: () => keys,
959
+ usedCategory: false,
960
+ usedSubCategory: true,
961
+ usedAmenity: false,
962
+ usedOffers: false,
963
+ usedFloor: false,
964
+ guaranteedEligibleStore: true,
965
+ });
966
+ }
967
+ if (categoryKey !== undefined && offersOnly) {
968
+ const keys = state.offers.keys(state.indexer.getOfferNodeKeysByCategory(categoryKey));
969
+ candidates.push({
970
+ count: keys.length,
971
+ resolveKeys: () => keys,
972
+ usedCategory: true,
973
+ usedSubCategory: false,
974
+ usedAmenity: false,
975
+ usedOffers: true,
976
+ usedFloor: false,
977
+ guaranteedEligibleStore: true,
978
+ });
979
+ }
980
+ else if (categoryKey !== undefined) {
981
+ const keys = indexer.getNodeKeysByCategory(categoryKey);
982
+ candidates.push({
983
+ count: keys.length,
984
+ resolveKeys: () => keys,
985
+ usedCategory: true,
986
+ usedSubCategory: false,
987
+ usedAmenity: false,
988
+ usedOffers: false,
989
+ usedFloor: false,
990
+ guaranteedEligibleStore: true,
991
+ });
992
+ }
993
+ if (amenityKey !== undefined) {
994
+ const resolvedAmenity = this.resolveCanonicalAmenityEntry(state, amenityKey);
995
+ const canonicalAmenityKey = resolvedAmenity?.canonicalKey ?? amenityKey;
996
+ const keys = indexer.getNodeKeysByAmenity(canonicalAmenityKey);
997
+ candidates.push({
998
+ count: keys.length,
999
+ resolveKeys: () => keys,
1000
+ usedCategory: false,
1001
+ usedSubCategory: false,
1002
+ usedAmenity: true,
1003
+ usedOffers: false,
1004
+ usedFloor: false,
1005
+ guaranteedEligibleStore: false,
1006
+ });
1007
+ }
1008
+ if (offersOnly && categoryKey === undefined && subCategoryKey === undefined) {
1009
+ const keys = state.offers.keys(state.indexer.getAllOfferNodeKeys());
1010
+ candidates.push({
1011
+ count: keys.length,
1012
+ resolveKeys: () => keys,
1013
+ usedCategory: false,
1014
+ usedSubCategory: false,
1015
+ usedAmenity: false,
1016
+ usedOffers: true,
1017
+ usedFloor: false,
1018
+ guaranteedEligibleStore: false,
1019
+ });
1020
+ }
1021
+ if (floorIndex !== undefined) {
1022
+ const floorNodes = indexer.getNodesByFloor(floorIndex);
1023
+ candidates.push({
1024
+ count: floorNodes.length,
1025
+ resolveKeys: () => floorNodes.map((node) => node.key),
1026
+ usedCategory: false,
1027
+ usedSubCategory: false,
1028
+ usedAmenity: false,
1029
+ usedOffers: false,
1030
+ usedFloor: true,
1031
+ guaranteedEligibleStore: false,
1032
+ });
1033
+ }
1034
+ let chosenSeed;
1035
+ if (candidates.length === 0) {
1036
+ const storeKeys = indexer.getStoreNodeKeys();
1037
+ chosenSeed = {
1038
+ count: storeKeys.length,
1039
+ resolveKeys: () => storeKeys,
1040
+ usedCategory: false,
1041
+ usedSubCategory: false,
1042
+ usedAmenity: false,
1043
+ usedOffers: false,
1044
+ usedFloor: false,
1045
+ guaranteedEligibleStore: true,
1046
+ };
1047
+ }
1048
+ else {
1049
+ chosenSeed = candidates[0];
1050
+ for (let i = 1; i < candidates.length; i++) {
1051
+ const current = candidates[i];
1052
+ if (current.count < chosenSeed.count) {
1053
+ chosenSeed = current;
1054
+ }
1055
+ }
1056
+ }
1057
+ if (chosenSeed.count === 0) {
1058
+ return [];
1059
+ }
1060
+ const baseKeys = chosenSeed.resolveKeys();
1061
+ const canonicalAmenityForCheck = amenityKey !== undefined && !chosenSeed.usedAmenity
1062
+ ? (this.resolveCanonicalAmenityEntry(state, amenityKey)?.canonicalKey ?? amenityKey)
1063
+ : amenityKey;
1064
+ const needsStoreCheck = !chosenSeed.guaranteedEligibleStore;
1065
+ const needsCategoryCheck = categoryKey !== undefined && !chosenSeed.usedCategory;
1066
+ const needsSubCategoryCheck = subCategoryKey !== undefined && !chosenSeed.usedSubCategory;
1067
+ const needsAmenityCheck = amenityKey !== undefined && !chosenSeed.usedAmenity;
1068
+ const needsOfferCheck = offersOnly && !chosenSeed.usedOffers;
1069
+ const needsFloorCheck = floorIndex !== undefined && !chosenSeed.usedFloor;
1070
+ if (!needsStoreCheck &&
1071
+ !needsCategoryCheck &&
1072
+ !needsSubCategoryCheck &&
1073
+ !needsAmenityCheck &&
1074
+ !needsOfferCheck &&
1075
+ !needsFloorCheck) {
1076
+ return baseKeys;
1077
+ }
1078
+ const matched = [];
1079
+ for (const key of baseKeys) {
1080
+ if (needsStoreCheck && !indexer.isIndexedStoreKey(key))
1081
+ continue;
1082
+ if (needsCategoryCheck && !indexer.hasNodeInCategory(categoryKey, key))
1083
+ continue;
1084
+ if (needsSubCategoryCheck && !indexer.hasNodeInSubCategory(subCategoryKey, key))
1085
+ continue;
1086
+ if (needsAmenityCheck && !indexer.hasNodeInAmenity(canonicalAmenityForCheck, key))
1087
+ continue;
1088
+ if (needsOfferCheck && !state.offers.has(key))
1089
+ continue;
1090
+ if (needsFloorCheck) {
1091
+ const node = indexer.getNodeByKey(key);
1092
+ if (!node || (node.floorIndex ?? 0) !== floorIndex)
1093
+ continue;
1094
+ }
1095
+ matched.push(key);
1096
+ }
1097
+ return matched;
1098
+ }
1099
+ readStoresPage(state, request, criteria, pagination) {
1100
+ const groupMultiLocation = request.groupMultiLocation ?? true;
1101
+ const cacheKey = buildCriteriaCacheKey(criteria, groupMultiLocation ? 'G1' : 'G0');
1102
+ let prepared = state.storesQueryCache.get(cacheKey);
1103
+ if (!prepared) {
1104
+ const filteredStoreKeys = this.resolveFilteredStoreKeys(state, criteria);
1105
+ const totalMemberCount = filteredStoreKeys.length;
1106
+ const availableFloors = this.collectSortedFloorsForKeys(state.indexer, filteredStoreKeys);
1107
+ const rowDescriptors = [];
1108
+ if (!groupMultiLocation) {
1109
+ for (const key of filteredStoreKeys) {
1110
+ rowDescriptors.push({ kind: 'store', key });
1111
+ }
1112
+ }
1113
+ else {
1114
+ const groupBuckets = new Map();
1115
+ for (const key of filteredStoreKeys) {
1116
+ const groupId = state.indexer.getGroupIdByNodeKey(key);
1117
+ if (!groupId) {
1118
+ rowDescriptors.push({ kind: 'store', key });
1119
+ continue;
1120
+ }
1121
+ let bucket = groupBuckets.get(groupId);
1122
+ if (!bucket) {
1123
+ bucket = [];
1124
+ groupBuckets.set(groupId, bucket);
1125
+ rowDescriptors.push({ kind: 'group', groupId, memberKeys: bucket });
1126
+ }
1127
+ bucket.push(key);
1128
+ }
1129
+ }
1130
+ prepared = {
1131
+ rowDescriptors,
1132
+ totalRows: rowDescriptors.length,
1133
+ totalMemberCount,
1134
+ availableFloors,
1135
+ };
1136
+ setBoundedCacheEntry(state.storesQueryCache, cacheKey, prepared);
1137
+ }
1138
+ const { totalRows, totalMemberCount, availableFloors, rowDescriptors } = prepared;
1139
+ const { offset, limit } = pagination;
1140
+ const slicedDescriptors = limit > 0 ? rowDescriptors.slice(offset, offset + limit) : [];
1141
+ const items = [];
1142
+ for (const desc of slicedDescriptors) {
1143
+ if (desc.kind === 'store') {
1144
+ const pub = state.offers.publicNode(desc.key);
1145
+ if (pub) {
1146
+ items.push({ kind: 'store', node: clonePublicNodeData(pub) });
1147
+ }
1148
+ }
1149
+ else if (desc.memberKeys.length === 1) {
1150
+ const singleKey = desc.memberKeys[0];
1151
+ const pub = state.offers.publicNode(singleKey);
1152
+ if (pub) {
1153
+ items.push({ kind: 'store', node: clonePublicNodeData(pub) });
1154
+ }
1155
+ }
1156
+ else {
1157
+ const groupData = this.buildPublicNodeGroupData(state, desc.groupId, desc.memberKeys, request.activeFloorIndex);
1158
+ if (groupData) {
1159
+ items.push({ kind: 'group', group: groupData });
1160
+ }
1161
+ }
1162
+ }
1163
+ const hasMore = offset + items.length < totalRows;
1164
+ const nextOffset = hasMore ? offset + items.length : null;
1165
+ return {
1166
+ target: 'stores',
1167
+ mallId: state.mallId,
1168
+ revision: state.revision,
1169
+ items,
1170
+ totalRows,
1171
+ totalMemberCount,
1172
+ offset,
1173
+ limit,
1174
+ hasMore,
1175
+ nextOffset,
1176
+ availableFloors: [...availableFloors],
1177
+ };
1178
+ }
1179
+ prepareCategoriesSummary(state, criteria) {
1180
+ const cacheKey = buildCriteriaCacheKey(criteria);
1181
+ let prepared = state.categoriesQueryCache.get(cacheKey);
1182
+ if (!prepared) {
1183
+ const categoriesMap = state.categories;
1184
+ const records = [];
1185
+ const recordsById = new Map();
1186
+ const eligibleIdSet = new Set();
1187
+ const uniqueMemberKeySet = new Set();
1188
+ const floorSet = new Set();
1189
+ const hasStoreFilter = criteria.subCategoryKey !== undefined ||
1190
+ criteria.amenityKey !== undefined ||
1191
+ criteria.floorIndex !== undefined ||
1192
+ criteria.offersOnly;
1193
+ if (categoriesMap && typeof categoriesMap === 'object') {
1194
+ for (const cat of Object.values(categoriesMap)) {
1195
+ if (!cat || typeof cat !== 'object')
1196
+ continue;
1197
+ const catKey = normalizeLookupKey(cat.code);
1198
+ if (catKey === undefined)
1199
+ continue;
1200
+ if (criteria.categoryKey !== undefined && criteria.categoryKey !== catKey) {
1201
+ continue;
1202
+ }
1203
+ if (criteria.subCategoryKey !== undefined &&
1204
+ !state.indexer.hasSubCategoryInCategory(catKey, criteria.subCategoryKey)) {
1205
+ continue;
1206
+ }
1207
+ const matchedStoreKeys = hasStoreFilter
1208
+ ? this.resolveFilteredStoreKeys(state, {
1209
+ ...criteria,
1210
+ categoryKey: catKey,
1211
+ })
1212
+ : state.indexer.getNodeKeysByCategory(catKey);
1213
+ if (hasStoreFilter && matchedStoreKeys.length === 0) {
1214
+ continue;
1215
+ }
1216
+ let matchedHasOffers = false;
1217
+ const itemFloorSet = new Set();
1218
+ for (const key of matchedStoreKeys) {
1219
+ uniqueMemberKeySet.add(key);
1220
+ if (hasStoreFilter && !matchedHasOffers && state.offers.has(key)) {
1221
+ matchedHasOffers = true;
1222
+ }
1223
+ const node = state.indexer.getNodeByKey(key);
1224
+ if (node) {
1225
+ const fl = node.floorIndex ?? 0;
1226
+ floorSet.add(fl);
1227
+ itemFloorSet.add(fl);
1228
+ }
1229
+ }
1230
+ const hasOffers = hasStoreFilter
1231
+ ? matchedHasOffers
1232
+ : state.offers.keys(state.indexer.getOfferNodeKeysByCategory(catKey)).length > 0;
1233
+ const indexedSubCodes = state.indexer.getSubCategoryCodesByCategory(catKey);
1234
+ const subCategoryCodes = Array.isArray(cat.subCategoryCodes) && cat.subCategoryCodes.length > 0
1235
+ ? [...cat.subCategoryCodes]
1236
+ : [...indexedSubCodes];
1237
+ const summary = {
1238
+ code: cat.code,
1239
+ name: cat.name,
1240
+ image: cat.image && cat.image.trim() !== '' ? cat.image : null,
1241
+ subCategoryCodes,
1242
+ storeCount: matchedStoreKeys.length,
1243
+ hasOffers,
1244
+ };
1245
+ const record = {
1246
+ id: catKey,
1247
+ summary,
1248
+ memberKeys: matchedStoreKeys,
1249
+ availableFloors: Array.from(itemFloorSet).sort((a, b) => a - b),
1250
+ };
1251
+ records.push(record);
1252
+ recordsById.set(catKey, record);
1253
+ eligibleIdSet.add(catKey);
1254
+ }
1255
+ }
1256
+ prepared = {
1257
+ records,
1258
+ recordsById,
1259
+ eligibleIdSet,
1260
+ totalRows: records.length,
1261
+ totalMemberCount: uniqueMemberKeySet.size,
1262
+ availableFloors: Array.from(floorSet).sort((a, b) => a - b),
1263
+ };
1264
+ setBoundedCacheEntry(state.categoriesQueryCache, cacheKey, prepared);
1265
+ }
1266
+ return prepared;
1267
+ }
1268
+ readCategoriesPage(state, criteria, pagination) {
1269
+ const prepared = this.prepareCategoriesSummary(state, criteria);
1270
+ const { totalRows, totalMemberCount, availableFloors } = prepared;
1271
+ const { offset, limit } = pagination;
1272
+ const items = limit > 0
1273
+ ? prepared.records
1274
+ .slice(offset, offset + limit)
1275
+ .map((record) => clonePublicCategoryData(record.summary))
1276
+ : [];
1277
+ const hasMore = offset + items.length < totalRows;
1278
+ const nextOffset = hasMore ? offset + items.length : null;
1279
+ return {
1280
+ target: 'categories',
1281
+ mallId: state.mallId,
1282
+ revision: state.revision,
1283
+ items,
1284
+ totalRows,
1285
+ totalMemberCount,
1286
+ offset,
1287
+ limit,
1288
+ hasMore,
1289
+ nextOffset,
1290
+ availableFloors: [...availableFloors],
1291
+ };
1292
+ }
1293
+ prepareSubCategoriesSummary(state, criteria) {
1294
+ const cacheKey = buildCriteriaCacheKey(criteria);
1295
+ let prepared = state.subCategoriesQueryCache.get(cacheKey);
1296
+ if (!prepared) {
1297
+ const subCategoriesMap = state.subCategories;
1298
+ const records = [];
1299
+ const recordsById = new Map();
1300
+ const eligibleIdSet = new Set();
1301
+ const uniqueMemberKeySet = new Set();
1302
+ const floorSet = new Set();
1303
+ const hasStoreFilter = criteria.amenityKey !== undefined ||
1304
+ criteria.floorIndex !== undefined ||
1305
+ criteria.offersOnly;
1306
+ if (subCategoriesMap && typeof subCategoriesMap === 'object') {
1307
+ for (const sub of Object.values(subCategoriesMap)) {
1308
+ if (!sub || typeof sub !== 'object')
1309
+ continue;
1310
+ const subKey = normalizeLookupKey(sub.code);
1311
+ const parentCatKey = normalizeLookupKey(sub.categoryCode);
1312
+ if (subKey === undefined || parentCatKey === undefined)
1313
+ continue;
1314
+ if (criteria.categoryKey !== undefined) {
1315
+ if (parentCatKey !== criteria.categoryKey)
1316
+ continue;
1317
+ if (!state.indexer.hasSubCategoryInCategory(criteria.categoryKey, subKey))
1318
+ continue;
1319
+ }
1320
+ if (criteria.subCategoryKey !== undefined && subKey !== criteria.subCategoryKey) {
1321
+ continue;
1322
+ }
1323
+ const matchedStoreKeys = hasStoreFilter
1324
+ ? this.resolveFilteredStoreKeys(state, {
1325
+ ...criteria,
1326
+ categoryKey: parentCatKey,
1327
+ subCategoryKey: subKey,
1328
+ })
1329
+ : state.indexer.getNodeKeysBySubCategory(subKey);
1330
+ if (hasStoreFilter && matchedStoreKeys.length === 0) {
1331
+ continue;
1332
+ }
1333
+ let matchedHasOffers = false;
1334
+ const itemFloorSet = new Set();
1335
+ for (const key of matchedStoreKeys) {
1336
+ uniqueMemberKeySet.add(key);
1337
+ if (hasStoreFilter && !matchedHasOffers && state.offers.has(key)) {
1338
+ matchedHasOffers = true;
1339
+ }
1340
+ const node = state.indexer.getNodeByKey(key);
1341
+ if (node) {
1342
+ const fl = node.floorIndex ?? 0;
1343
+ floorSet.add(fl);
1344
+ itemFloorSet.add(fl);
1345
+ }
1346
+ }
1347
+ const hasOffers = hasStoreFilter
1348
+ ? matchedHasOffers
1349
+ : state.offers.keys(state.indexer.getOfferNodeKeysBySubCategory(subKey)).length > 0;
1350
+ const summary = {
1351
+ code: sub.code,
1352
+ name: sub.name,
1353
+ categoryCode: sub.categoryCode,
1354
+ image: sub.image && sub.image.trim() !== '' ? sub.image : null,
1355
+ description: sub.description ?? '',
1356
+ storeCount: matchedStoreKeys.length,
1357
+ hasOffers,
1358
+ };
1359
+ const record = {
1360
+ id: subKey,
1361
+ summary,
1362
+ memberKeys: matchedStoreKeys,
1363
+ availableFloors: Array.from(itemFloorSet).sort((a, b) => a - b),
1364
+ };
1365
+ records.push(record);
1366
+ recordsById.set(subKey, record);
1367
+ eligibleIdSet.add(subKey);
1368
+ }
1369
+ }
1370
+ prepared = {
1371
+ records,
1372
+ recordsById,
1373
+ eligibleIdSet,
1374
+ totalRows: records.length,
1375
+ totalMemberCount: uniqueMemberKeySet.size,
1376
+ availableFloors: Array.from(floorSet).sort((a, b) => a - b),
1377
+ };
1378
+ setBoundedCacheEntry(state.subCategoriesQueryCache, cacheKey, prepared);
1379
+ }
1380
+ return prepared;
1381
+ }
1382
+ readSubCategoriesPage(state, criteria, pagination) {
1383
+ const prepared = this.prepareSubCategoriesSummary(state, criteria);
1384
+ const { totalRows, totalMemberCount, availableFloors } = prepared;
1385
+ const { offset, limit } = pagination;
1386
+ const items = limit > 0
1387
+ ? prepared.records
1388
+ .slice(offset, offset + limit)
1389
+ .map((record) => clonePublicSubCategoryData(record.summary))
1390
+ : [];
1391
+ const hasMore = offset + items.length < totalRows;
1392
+ const nextOffset = hasMore ? offset + items.length : null;
1393
+ return {
1394
+ target: 'subcategories',
1395
+ mallId: state.mallId,
1396
+ revision: state.revision,
1397
+ items,
1398
+ totalRows,
1399
+ totalMemberCount,
1400
+ offset,
1401
+ limit,
1402
+ hasMore,
1403
+ nextOffset,
1404
+ availableFloors: [...availableFloors],
1405
+ };
1406
+ }
1407
+ prepareAmenitiesSummary(state, criteria) {
1408
+ const cacheKey = buildCriteriaCacheKey(criteria);
1409
+ let prepared = state.amenitiesQueryCache.get(cacheKey);
1410
+ if (!prepared) {
1411
+ const amenitiesMap = state.amenities;
1412
+ const records = [];
1413
+ const recordsById = new Map();
1414
+ const eligibleIdSet = new Set();
1415
+ const uniqueMemberKeySet = new Set();
1416
+ const floorSet = new Set();
1417
+ // Verify category/subcategory parent compatibility when both are provided
1418
+ const invalidTaxonomyCombo = criteria.categoryKey !== undefined &&
1419
+ criteria.subCategoryKey !== undefined &&
1420
+ state.indexer.getSubCategoryCodesByCategory(criteria.categoryKey).length > 0 &&
1421
+ !state.indexer.hasSubCategoryInCategory(criteria.categoryKey, criteria.subCategoryKey);
1422
+ const hasMemberFilter = criteria.categoryKey !== undefined ||
1423
+ criteria.subCategoryKey !== undefined ||
1424
+ criteria.floorIndex !== undefined ||
1425
+ criteria.offersOnly;
1426
+ if (!invalidTaxonomyCombo && amenitiesMap && typeof amenitiesMap === 'object') {
1427
+ for (const amenity of Object.values(amenitiesMap)) {
1428
+ if (!amenity || typeof amenity !== 'object')
1429
+ continue;
1430
+ if (amenity.status === 0)
1431
+ continue;
1432
+ const amenityKey = normalizeLookupKey(amenity.id);
1433
+ const fieldCodeKey = normalizeLookupKey(amenity.fieldCode);
1434
+ if (amenityKey === undefined)
1435
+ continue;
1436
+ if (criteria.amenityKey !== undefined &&
1437
+ criteria.amenityKey !== amenityKey &&
1438
+ criteria.amenityKey !== fieldCodeKey) {
1439
+ continue;
1440
+ }
1441
+ if (criteria.floorIndex !== undefined &&
1442
+ !state.indexer.hasAmenityOnFloor(amenityKey, criteria.floorIndex)) {
1443
+ continue;
1444
+ }
1445
+ const hasStoreScopedAmenityFilter = criteria.categoryKey !== undefined ||
1446
+ criteria.subCategoryKey !== undefined ||
1447
+ criteria.offersOnly;
1448
+ let matchedMemberKeys;
1449
+ if (hasStoreScopedAmenityFilter) {
1450
+ matchedMemberKeys = this.resolveFilteredStoreKeys(state, {
1451
+ ...criteria,
1452
+ amenityKey,
1453
+ });
1454
+ }
1455
+ else if (criteria.floorIndex !== undefined) {
1456
+ const allMemberKeys = state.indexer.getNodeKeysByAmenity(amenityKey);
1457
+ const floorNodes = state.indexer.getNodesByFloor(criteria.floorIndex);
1458
+ if (floorNodes.length < allMemberKeys.length) {
1459
+ const filteredFloorKeys = [];
1460
+ for (const node of floorNodes) {
1461
+ if (state.indexer.hasNodeInAmenity(amenityKey, node.key)) {
1462
+ filteredFloorKeys.push(node.key);
1463
+ }
1464
+ }
1465
+ matchedMemberKeys = filteredFloorKeys;
1466
+ }
1467
+ else {
1468
+ matchedMemberKeys = this.filterMemberKeysByCriteria(state, allMemberKeys, {
1469
+ ...criteria,
1470
+ amenityKey,
1471
+ });
1472
+ }
1473
+ }
1474
+ else {
1475
+ matchedMemberKeys = state.indexer.getNodeKeysByAmenity(amenityKey);
1476
+ }
1477
+ if (hasMemberFilter && matchedMemberKeys.length === 0) {
1478
+ continue;
1479
+ }
1480
+ const amenityFloors = hasMemberFilter
1481
+ ? this.collectSortedFloorsForKeys(state.indexer, matchedMemberKeys)
1482
+ : state.indexer.getAmenityFloors(amenityKey);
1483
+ for (const key of matchedMemberKeys) {
1484
+ uniqueMemberKeySet.add(key);
1485
+ }
1486
+ for (const fl of amenityFloors) {
1487
+ floorSet.add(fl);
1488
+ }
1489
+ const sortedAmenityFloors = [...amenityFloors];
1490
+ const summary = {
1491
+ id: amenity.id,
1492
+ fieldCode: amenity.fieldCode,
1493
+ name: amenity.name,
1494
+ image: amenity.image && amenity.image.trim() !== '' ? amenity.image : null,
1495
+ status: amenity.status,
1496
+ wayfindingId: amenity.wayfinding_id ?? null,
1497
+ memberCount: matchedMemberKeys.length,
1498
+ availableFloors: sortedAmenityFloors,
1499
+ };
1500
+ const record = {
1501
+ id: amenityKey,
1502
+ summary,
1503
+ memberKeys: matchedMemberKeys,
1504
+ availableFloors: sortedAmenityFloors,
1505
+ };
1506
+ records.push(record);
1507
+ recordsById.set(amenityKey, record);
1508
+ eligibleIdSet.add(amenityKey);
1509
+ }
1510
+ }
1511
+ prepared = {
1512
+ records,
1513
+ recordsById,
1514
+ eligibleIdSet,
1515
+ totalRows: records.length,
1516
+ totalMemberCount: uniqueMemberKeySet.size,
1517
+ availableFloors: Array.from(floorSet).sort((a, b) => a - b),
1518
+ };
1519
+ setBoundedCacheEntry(state.amenitiesQueryCache, cacheKey, prepared);
1520
+ }
1521
+ return prepared;
1522
+ }
1523
+ readAmenitiesPage(state, criteria, pagination) {
1524
+ const prepared = this.prepareAmenitiesSummary(state, criteria);
1525
+ const { totalRows, totalMemberCount, availableFloors } = prepared;
1526
+ const { offset, limit } = pagination;
1527
+ const items = limit > 0
1528
+ ? prepared.records
1529
+ .slice(offset, offset + limit)
1530
+ .map((record) => clonePublicAmenityData(record.summary))
1531
+ : [];
1532
+ const hasMore = offset + items.length < totalRows;
1533
+ const nextOffset = hasMore ? offset + items.length : null;
1534
+ return {
1535
+ target: 'amenities',
1536
+ mallId: state.mallId,
1537
+ revision: state.revision,
1538
+ items,
1539
+ totalRows,
1540
+ totalMemberCount,
1541
+ offset,
1542
+ limit,
1543
+ hasMore,
1544
+ nextOffset,
1545
+ availableFloors: [...availableFloors],
1546
+ };
1547
+ }
1548
+ readOffersPage(state, criteria, pagination) {
1549
+ const effectiveCriteria = {
1550
+ ...criteria,
1551
+ offersOnly: true,
1552
+ };
1553
+ const cacheKey = buildCriteriaCacheKey(effectiveCriteria);
1554
+ let prepared = state.offersQueryCache.get(cacheKey);
1555
+ if (!prepared) {
1556
+ const offerStoreKeys = this.resolveFilteredStoreKeys(state, effectiveCriteria);
1557
+ const offerRefs = [];
1558
+ const floorSet = new Set();
1559
+ let matchedOfferStoreCount = 0;
1560
+ for (const nodeKey of offerStoreKeys) {
1561
+ const node = state.indexer.getNodeByKey(nodeKey);
1562
+ const offerCount = state.offers.offers(nodeKey).length;
1563
+ if (!node || offerCount === 0) {
1564
+ continue;
1565
+ }
1566
+ matchedOfferStoreCount++;
1567
+ floorSet.add(node.floorIndex ?? 0);
1568
+ for (let offerIndex = 0; offerIndex < offerCount; offerIndex++) {
1569
+ offerRefs.push({ nodeKey, offerIndex });
1570
+ }
1571
+ }
1572
+ prepared = {
1573
+ offerRefs,
1574
+ totalRows: offerRefs.length,
1575
+ totalMemberCount: matchedOfferStoreCount,
1576
+ availableFloors: Array.from(floorSet).sort((a, b) => a - b),
1577
+ };
1578
+ setBoundedCacheEntry(state.offersQueryCache, cacheKey, prepared);
1579
+ }
1580
+ const { offerRefs, totalRows, totalMemberCount, availableFloors } = prepared;
1581
+ const { offset, limit } = pagination;
1582
+ const slicedRefs = limit > 0 ? offerRefs.slice(offset, offset + limit) : [];
1583
+ const items = [];
1584
+ for (const ref of slicedRefs) {
1585
+ const publicNode = state.offers.publicNode(ref.nodeKey);
1586
+ const offer = publicNode?.offers?.[ref.offerIndex];
1587
+ if (!publicNode || !offer) {
1588
+ continue;
1589
+ }
1590
+ items.push({
1591
+ offer: clonePublicOffer(offer),
1592
+ nodeKey: publicNode.key,
1593
+ storeName: publicNode.assets.locationName?.text ?? '',
1594
+ floorIndex: publicNode.floorIndex,
1595
+ floorName: publicNode.floorName,
1596
+ ...(publicNode.categoryCode !== undefined ? { categoryCode: publicNode.categoryCode } : {}),
1597
+ ...(publicNode.subCategoryCode !== undefined
1598
+ ? { subCategoryCode: publicNode.subCategoryCode }
1599
+ : {}),
1600
+ });
1601
+ }
1602
+ const hasMore = offset + items.length < totalRows;
1603
+ const nextOffset = hasMore ? offset + items.length : null;
1604
+ return {
1605
+ target: 'offers',
1606
+ mallId: state.mallId,
1607
+ revision: state.revision,
1608
+ items,
1609
+ totalRows,
1610
+ totalMemberCount,
1611
+ offset,
1612
+ limit,
1613
+ hasMore,
1614
+ nextOffset,
1615
+ availableFloors: [...availableFloors],
1616
+ };
1617
+ }
1618
+ resolveEligibleGroupMemberKeys(state, groupId, criteria) {
1619
+ const rawGroupKeys = state.indexer.getGroupNodeKeys(groupId);
1620
+ if (rawGroupKeys.length === 0) {
1621
+ return [];
1622
+ }
1623
+ if (!criteria) {
1624
+ return rawGroupKeys.filter((key) => state.indexer.isIndexedStoreKey(key));
1625
+ }
1626
+ // Verify category/subcategory parent compatibility when both are provided
1627
+ if (criteria.categoryKey !== undefined && criteria.subCategoryKey !== undefined) {
1628
+ const childSubCodes = state.indexer.getSubCategoryCodesByCategory(criteria.categoryKey);
1629
+ if (childSubCodes.length > 0 &&
1630
+ !state.indexer.hasSubCategoryInCategory(criteria.categoryKey, criteria.subCategoryKey)) {
1631
+ return [];
1632
+ }
1633
+ }
1634
+ return this.filterMemberKeysByCriteria(state, rawGroupKeys, criteria, true);
1635
+ }
1636
+ buildPublicNodeGroupData(state, groupId, memberKeys, activeFloorIndex, preferredRepresentativeKey, includeMemberDetails = false, precomputedAvailableFloors) {
1637
+ if (memberKeys.length === 0) {
1638
+ return null;
1639
+ }
1640
+ // Fast compact path when preferredRepresentativeKey and precomputedAvailableFloors are already known
1641
+ if (!includeMemberDetails &&
1642
+ preferredRepresentativeKey !== undefined &&
1643
+ precomputedAvailableFloors !== undefined) {
1644
+ const preferredPub = state.offers.publicNode(preferredRepresentativeKey);
1645
+ if (preferredPub) {
1646
+ const representative = clonePublicNodeData(preferredPub);
1647
+ return {
1648
+ groupId,
1649
+ name: representative.assets.locationName?.text ?? groupId,
1650
+ memberCount: memberKeys.length,
1651
+ availableFloors: [...precomputedAvailableFloors],
1652
+ representative,
1653
+ };
1654
+ }
1655
+ }
1656
+ const normalizedActiveFloor = normalizeFloorFilter(activeFloorIndex);
1657
+ const members = includeMemberDetails
1658
+ ? []
1659
+ : undefined;
1660
+ const floorSet = new Set();
1661
+ let memberCount = 0;
1662
+ let firstPublicNode;
1663
+ let activeFloorPublicNode;
1664
+ let preferredPublicNode;
1665
+ for (const key of memberKeys) {
1666
+ const pub = state.offers.publicNode(key);
1667
+ if (!pub)
1668
+ continue;
1669
+ memberCount++;
1670
+ if (!firstPublicNode) {
1671
+ firstPublicNode = pub;
1672
+ }
1673
+ if (!preferredPublicNode &&
1674
+ preferredRepresentativeKey !== undefined &&
1675
+ pub.key === preferredRepresentativeKey) {
1676
+ preferredPublicNode = pub;
1677
+ }
1678
+ if (!activeFloorPublicNode &&
1679
+ normalizedActiveFloor !== undefined &&
1680
+ pub.floorIndex === normalizedActiveFloor) {
1681
+ activeFloorPublicNode = pub;
1682
+ }
1683
+ floorSet.add(pub.floorIndex);
1684
+ if (members) {
1685
+ members.push({
1686
+ key: pub.key,
1687
+ floorIndex: pub.floorIndex,
1688
+ floorName: pub.floorName,
1689
+ type: pub.type,
1690
+ });
1691
+ }
1692
+ }
1693
+ const chosenRepresentative = preferredPublicNode ?? activeFloorPublicNode ?? firstPublicNode;
1694
+ if (!chosenRepresentative) {
1695
+ return null;
1696
+ }
1697
+ const representative = clonePublicNodeData(chosenRepresentative);
1698
+ const availableFloors = Array.from(floorSet).sort((a, b) => a - b);
1699
+ if (!includeMemberDetails || !members) {
1700
+ return {
1701
+ groupId,
1702
+ name: representative.assets.locationName?.text ?? groupId,
1703
+ memberCount,
1704
+ availableFloors,
1705
+ representative,
1706
+ };
1707
+ }
1708
+ return {
1709
+ groupId,
1710
+ name: representative.assets.locationName?.text ?? groupId,
1711
+ memberKeys: members.map((m) => m.key),
1712
+ memberCount,
1713
+ availableFloors,
1714
+ members,
1715
+ representative,
1716
+ };
1717
+ }
1718
+ filterMemberKeysByCriteria(state, keys, criteria, requireStoreEligibility = false) {
1719
+ if (keys.length === 0)
1720
+ return [];
1721
+ const { indexer } = state;
1722
+ const canonicalAmenityKey = criteria.amenityKey !== undefined
1723
+ ? (this.resolveCanonicalAmenityEntry(state, criteria.amenityKey)?.canonicalKey ??
1724
+ criteria.amenityKey)
1725
+ : undefined;
1726
+ const result = [];
1727
+ for (const key of keys) {
1728
+ if (requireStoreEligibility && !indexer.isIndexedStoreKey(key))
1729
+ continue;
1730
+ if (criteria.categoryKey !== undefined &&
1731
+ !indexer.hasNodeInCategory(criteria.categoryKey, key)) {
1732
+ continue;
1733
+ }
1734
+ if (criteria.subCategoryKey !== undefined &&
1735
+ !indexer.hasNodeInSubCategory(criteria.subCategoryKey, key)) {
1736
+ continue;
1737
+ }
1738
+ if (canonicalAmenityKey !== undefined &&
1739
+ !indexer.hasNodeInAmenity(canonicalAmenityKey, key)) {
1740
+ continue;
1741
+ }
1742
+ if (criteria.offersOnly && !state.offers.has(key))
1743
+ continue;
1744
+ if (criteria.floorIndex !== undefined) {
1745
+ const node = indexer.getNodeByKey(key);
1746
+ if (!node || (node.floorIndex ?? 0) !== criteria.floorIndex)
1747
+ continue;
1748
+ }
1749
+ result.push(key);
1750
+ }
1751
+ return result;
1752
+ }
1753
+ collectSortedFloorsForKeys(indexer, keys) {
1754
+ if (keys.length === 0)
1755
+ return [];
1756
+ const floorSet = new Set();
1757
+ for (const key of keys) {
1758
+ const node = indexer.getNodeByKey(key);
1759
+ if (node) {
1760
+ floorSet.add(node.floorIndex ?? 0);
1761
+ }
1762
+ }
1763
+ return Array.from(floorSet).sort((a, b) => a - b);
1764
+ }
1765
+ resolveCanonicalAmenityEntry(state, amenityId) {
1766
+ const rawKey = normalizeLookupKey(amenityId);
1767
+ if (rawKey === undefined) {
1768
+ return null;
1769
+ }
1770
+ const amenitiesMap = state.amenities;
1771
+ if (amenitiesMap && typeof amenitiesMap === 'object') {
1772
+ const direct = Object.hasOwn(amenitiesMap, rawKey) ? amenitiesMap[rawKey] : undefined;
1773
+ if (direct) {
1774
+ if (direct.status === 0) {
1775
+ return null;
1776
+ }
1777
+ return { canonicalKey: rawKey, publicId: direct.id, amenity: direct };
1778
+ }
1779
+ const alias = state.amenityAliases.get(rawKey);
1780
+ return alias?.amenity?.status === 0 ? null : (alias ?? null);
1781
+ }
1782
+ const memberKeys = state.indexer.getNodeKeysByAmenity(rawKey);
1783
+ if (memberKeys.length === 0) {
1784
+ return null;
1785
+ }
1786
+ return {
1787
+ canonicalKey: rawKey,
1788
+ publicId: amenityId,
1789
+ amenity: null,
1790
+ };
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Factory creating a `CatalogReader` instance implementing `CatalogReadPort`.
1795
+ * `CatalogReadPort` implement karne wala `CatalogReader` instance banane ka factory function.
1796
+ */
1797
+ export function createCatalogReader(options) {
1798
+ return new CatalogReader(options);
1799
+ }