@superbright/indexeddb-orm 1.0.30 → 1.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/zustand-store.cjs +1 -1
- package/dist/adapters/zustand-store.cjs.map +1 -1
- package/dist/adapters/zustand-store.d.ts +2 -6
- package/dist/adapters/zustand-store.mjs +212 -167
- package/dist/adapters/zustand-store.mjs.map +1 -1
- package/dist/base/enums.cjs +1 -1
- package/dist/base/enums.cjs.map +1 -1
- package/dist/base/enums.d.ts +4 -0
- package/dist/base/enums.mjs +2 -1
- package/dist/base/enums.mjs.map +1 -1
- package/dist/base/userinquiry.d.ts +23 -0
- package/dist/base/visitor.d.ts +17 -0
- package/dist/base/visitorfilter.d.ts +25 -0
- package/dist/base/visitorquestionnaire.d.ts +25 -0
- package/dist/base/visitorunitengagement.d.ts +24 -0
- package/dist/features/units/transformers.cjs.map +1 -1
- package/dist/features/units/transformers.d.ts +2 -0
- package/dist/features/units/transformers.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -5
- package/dist/index.mjs +111 -127
- package/dist/index.mjs.map +1 -1
- package/dist/schema.cjs +1 -1
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.ts +13 -41
- package/dist/schema.mjs +63 -74
- package/dist/schema.mjs.map +1 -1
- package/dist/stores/store.cjs +1 -1
- package/dist/stores/store.cjs.map +1 -1
- package/dist/stores/store.d.ts +5 -73
- package/dist/stores/store.mjs +53 -254
- package/dist/stores/store.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/api/favorites.cjs +0 -2
- package/dist/api/favorites.cjs.map +0 -1
- package/dist/api/favorites.d.ts +0 -4
- package/dist/api/favorites.mjs +0 -34
- package/dist/api/favorites.mjs.map +0 -1
- package/dist/api/properties.cjs +0 -2
- package/dist/api/properties.cjs.map +0 -1
- package/dist/api/properties.d.ts +0 -22
- package/dist/api/properties.mjs +0 -197
- package/dist/api/properties.mjs.map +0 -1
- package/dist/api/users.cjs +0 -2
- package/dist/api/users.cjs.map +0 -1
- package/dist/api/users.d.ts +0 -5
- package/dist/api/users.mjs +0 -54
- package/dist/api/users.mjs.map +0 -1
- package/dist/units/favorites.cjs +0 -2
- package/dist/units/favorites.cjs.map +0 -1
- package/dist/units/favorites.d.ts +0 -7
- package/dist/units/favorites.mjs +0 -19
- package/dist/units/favorites.mjs.map +0 -1
package/dist/stores/store.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../storage.cjs"),p=require("../schema.cjs"),w=require("../validation.cjs"),P=require("../features/filters/transformers.cjs"),S={date_availability:void 0,qty_bedrooms:void 0,base_price:void 0,highlights:void 0},y={properties:{},currentPropertyId:null,currentPropertySlug:null,hasPreviouslySearched:[],unitResults:[],filters:S,tempFilters:S,apiFilters:{limit:10,page:1,sortBy:"relevance"},resultsMode:"all",resolvedQuestionnaireValues:{},sortBy:"relevance"};class h{async getState(){const t=await u.kvGet("app");if(!t)return y;const e={...y,...t,properties:t.properties??{},unitResults:t.unitResults??[],currentPropertyId:t.currentPropertyId==null?null:String(t.currentPropertyId),currentPropertySlug:t.currentPropertySlug??null,hasPreviouslySearched:Array.isArray(t.hasPreviouslySearched)?t.hasPreviouslySearched.map(String):[]},r=p.UnifiedStoreDataSchema.safeParse(e);if(r.success)return r.data;const s=Object.entries(e.properties??{}).reduce((o,[l,d])=>{const f=p.UserPropertyStateSchema.safeParse(d);return f.success&&(o[l]=f.data),o},{}),i=(Array.isArray(e.unitResults)?e.unitResults:e.unitResults&&typeof e.unitResults=="object"?Object.values(e.unitResults):[]).reduce((o,l)=>{const d=p.UnitSchema.safeParse(l);return d.success&&o.push(d.data),o},[]),a={...e,properties:s,unitResults:i},n=p.UnifiedStoreDataSchema.safeParse(a);return n.success?n.data:y}async setState(t){const e=await this.getState(),r=t(e),s=p.UnifiedStoreDataSchema.parse(r);await u.kvSet("app",s)}async waitForCurrentProperty(t=1e3){const e=Date.now()+t;for(;Date.now()<e;){const c=await this.getState(),i=c.currentPropertyId;if(i&&c.properties[i])return i;await new Promise(a=>setTimeout(a,16))}const r=await this.getState(),s=r.currentPropertyId;if(s&&r.properties[s])return s;throw new Error("UnifiedStore: current property was not initialized in time")}async initializeProperty(t,e){const r=String(t);await this.setState(s=>s.properties&&s.properties[r]?{...s,currentPropertyId:r,currentPropertySlug:e}:{...s,currentPropertyId:r,currentPropertySlug:e,properties:{...s.properties,[r]:{id:r,slug:e,favoritedUnits:[],tourContactedOn:null,viewedUnits:[],questionnaireResults:null,tourContactData:null}}})}async setUnitResults(t,e){const r=e??p.UnitSchema,s=[];(Array.isArray(t)?t:t&&typeof t=="object"?Object.values(t):[]).forEach((i,a)=>{const n=w.validate(r,i,`unitResults[${a}]`);n&&s.push(n)}),await this.setState(i=>({...i,unitResults:s}))}async clearUnitResults(){await this.setState(t=>({...t,unitResults:[]}))}async setCurrentProperty(t,e){const r=String(t);await this.setState(s=>({...s,currentPropertyId:r,currentPropertySlug:e||s.currentPropertySlug}))}async setCurrentPropertySlug(t){await this.setState(e=>({...e,currentPropertySlug:t}))}async setHasPreviouslySearched(t){await this.setState(e=>({...e,hasPreviouslySearched:Array.from(new Set([...e.hasPreviouslySearched,t]))}))}async markUnitAsViewed(t,e){const r=`https://${e}`;window.open(r,"_blank","noopener,noreferrer");const s=new Date,c=`${String(s.getMonth()+1).padStart(2,"0")}/${String(s.getDate()).padStart(2,"0")}`;await this.setState(i=>{const a=i.currentPropertyId;if(!a)return i;const n=i.properties[a];if(!n)return i;const o=[...n.viewedUnits.filter(l=>l.unitId!==t),{unitId:t,viewedDate:c}];return{...i,properties:{...i.properties,[a]:{...n,viewedUnits:o}}}})}async setTourContactedOn(){await this.setState(t=>{const e=t.currentPropertyId;if(!e)return t;const r=t.properties[e];return r?{...t,properties:{...t.properties,[e]:{...r,tourContactedOn:new Date().toISOString()}}}:t})}async getTourContactedOn(){var r;const t=await this.getState(),e=t.currentPropertyId;return e?((r=t.properties[e])==null?void 0:r.tourContactedOn)??null:null}async setQuestionnaireResults(t){await this.setState(e=>{const r=e.currentPropertyId;if(!r)return e;const s=e.properties[r];return s?{...e,properties:{...e.properties,[r]:{...s,questionnaireResults:t}}}:e})}async setTourContactData(t){const e=await this.waitForCurrentProperty();await this.setState(r=>{const s=r.properties[e];return s?{...r,properties:{...r.properties,[e]:{...s,tourContactData:t}}}:r})}async setFilters(t){await this.setState(e=>({...e,filters:{...e.filters,...t}}))}async setTempFilters(t){await this.setState(e=>({...e,tempFilters:{...e.tempFilters,...t}}))}async setFiltersToDefault(){await this.setState(t=>({...t,filters:S}))}async setApiFilters(t){await this.setState(e=>({...e,apiFilters:{...e.apiFilters,...t}}))}async handleTempFilterChange(t,e){await this.setState(r=>({...r,tempFilters:{...r.tempFilters,[t]:e}}))}async submitFilterUpdate(){await this.setState(t=>{const e=P.transformFiltersToUnitsSearchParams({...t.filters,limit:t.apiFilters.limit,page:t.apiFilters.page,sortBy:t.sortBy},{defaultLimit:t.apiFilters.limit,defaultPage:t.apiFilters.page,defaultSort:t.sortBy});return{...t,apiFilters:e}})}async setResultsMode(t){await this.setState(e=>({...e,resultsMode:t}))}async setSortBy(t){await this.setState(e=>({...e,sortBy:t}))}async setResolvedQuestionnaireValues(t,e){await this.setState(r=>({...r,resolvedQuestionnaireValues:{...r.resolvedQuestionnaireValues,[t]:e}}))}async getVisitorUUID(){const t=await u.kvGet("user");return(t==null?void 0:t.visitor_uuid)??null}async setVisitorUUID(t){const e=await u.kvGet("user"),r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};await u.kvSet("user",{...r,visitor_uuid:t})}async clearVisitorUUID(){const t=await u.kvGet("user");if(t===null||typeof t!="object"||Array.isArray(t))return;const{visitor_uuid:e,...r}=t;await u.kvSet("user",r)}}const v=new h;exports.Store=h;exports.UnifiedStore=h;exports.store=v;
|
|
2
2
|
//# sourceMappingURL=store.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.cjs","sources":["../../src/stores/store.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport type { ZodObject, ZodType, ZodTypeAny } from \"zod\";\nimport {\n UnifiedStoreDataSchema,\n UserPropertyStateSchema,\n type UnifiedStoreData,\n type UserPropertyState,\n type Property,\n type Filters,\n type QueryParams,\n type ResultsMode,\n type SortBy,\n type TourContactData,\n type Unit,\n PropertySchema,\n TourContactDataSchema,\n UnitSchema,\n} from \"../schema\";\nimport { validate } from \"../validation\";\nimport { transformFiltersToUnitsSearchParams } from \"../features/filters/transformers\";\n\n// Default values\nconst defaultFilters: Filters = {\n date_availability: undefined,\n qty_bedrooms: undefined,\n base_price: undefined,\n highlights: undefined,\n};\n\nconst defaultUnifiedStoreData: UnifiedStoreData = {\n // Property data\n properties: {},\n currentPropertyId: null,\n currentPropertySlug: null,\n hasPreviouslySearched: [],\n\n // App data\n unitResults: [],\n filters: defaultFilters,\n tempFilters: defaultFilters,\n apiFilters: {\n limit: 10,\n page: 1,\n sortBy: \"relevance\",\n },\n resultsMode: \"all\",\n resolvedQuestionnaireValues: {},\n sortBy: \"relevance\",\n};\n\nconst toArray = (input: unknown): unknown[] => {\n if (input == null) return [];\n return Array.isArray(input) ? input : [input];\n};\n\nconst extractFilterValues = (value: unknown): unknown[] => {\n return toArray(value).flatMap(item => {\n if (item == null) return [];\n if (Array.isArray(item)) return item;\n if (typeof item === \"object\" && \"value\" in (item as any)) {\n const v = (item as any).value;\n return Array.isArray(v) ? v : v != null ? [v] : [];\n }\n return [item];\n });\n};\n\nconst toStringArray = (value: unknown): string[] =>\n extractFilterValues(value)\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .map(v => String(v))\n .map(v => v.trim())\n .filter(v => v.length > 0);\n\nconst toNumberArray = (value: unknown): number[] =>\n extractFilterValues(value)\n .map(v => {\n if (typeof v === \"number\" && Number.isFinite(v)) return v;\n const num = Number(v);\n return Number.isFinite(num) ? num : null;\n })\n .filter((v): v is number => v !== null);\n\nconst toNumberValue = (value: unknown): number | null => {\n if (value == null) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"object\" && \"value\" in (value as any)) {\n return toNumberValue((value as any).value);\n }\n const num = Number(value);\n return Number.isFinite(num) ? num : null;\n};\n\n// Unified store class\nexport class UnifiedStore {\n /**\n * Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema\n * and sanitizing invalid entries where possible.\n */\n private async getState(): Promise<UnifiedStoreData> {\n const state = await kvGet<UnifiedStoreData>(\"app\");\n if (!state) {\n return defaultUnifiedStoreData;\n }\n\n const merged = {\n ...defaultUnifiedStoreData,\n ...state,\n properties: state.properties ?? {},\n unitResults: state.unitResults ?? [],\n currentPropertyId:\n state.currentPropertyId == null ? null : String(state.currentPropertyId),\n currentPropertySlug: state.currentPropertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = UnifiedStoreDataSchema.safeParse(merged);\n if (parsed.success) return parsed.data;\n\n // Sanitize by dropping invalid property entries and unit results\n const sanitizedProperties = Object.entries(merged.properties ?? {}).reduce<\n Record<string, UserPropertyState>\n >((acc, [key, value]) => {\n const entry = UserPropertyStateSchema.safeParse(value);\n if (entry.success) acc[key] = entry.data;\n return acc;\n }, {});\n\n const rawUnitResults = Array.isArray(merged.unitResults)\n ? merged.unitResults\n : merged.unitResults && typeof merged.unitResults === \"object\"\n ? Object.values(merged.unitResults as Record<string, unknown>)\n : [];\n\n const sanitizedUnitResults = rawUnitResults.reduce<Unit[]>((acc, value) => {\n const entry = UnitSchema.safeParse(value);\n if (entry.success) acc.push(entry.data);\n return acc;\n }, []);\n\n const fallback = {\n ...merged,\n properties: sanitizedProperties,\n unitResults: sanitizedUnitResults,\n };\n\n const fallbackParsed = UnifiedStoreDataSchema.safeParse(fallback);\n return fallbackParsed.success ? fallbackParsed.data : defaultUnifiedStoreData;\n }\n\n /**\n * Applies an updater function to the current store state, validates the result, and persists it.\n *\n * @param updater - Pure function that maps the current state to the next state.\n */\n private async setState(updater: (state: UnifiedStoreData) => UnifiedStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = UnifiedStoreDataSchema.parse(newState);\n await kvSet(\"app\", validatedState);\n }\n\n /**\n * Polls the persisted state until a current property pointer is available or the timeout elapses.\n *\n * @param timeoutMs - Maximum time in milliseconds to wait before failing.\n * @returns The active property ID once it becomes available.\n * @throws Error if the property pointer is not set before the timeout expires.\n */\n private async waitForCurrentProperty(timeoutMs = 1000): Promise<string> {\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (propertyId && state.properties[propertyId]) return propertyId;\n\n await new Promise(resolve => setTimeout(resolve, 16));\n }\n\n const finalState = await this.getState();\n const propertyId = finalState.currentPropertyId;\n if (propertyId && finalState.properties[propertyId]) return propertyId;\n\n throw new Error(\"UnifiedStore: current property was not initialized in time\");\n }\n\n // === PROPERTY OPERATIONS ===\n\n /**\n * Ensures a property entry exists and registers it as the current property.\n *\n * @param propertyId - Identifier used to track the property.\n * @param slug - Canonical slug associated with the property.\n */\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.properties && state.properties[id]) {\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug\n };\n }\n\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug,\n properties: {\n ...state.properties,\n [id]: {\n id,\n slug,\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n },\n },\n };\n });\n }\n\n // === UNIT RESULTS CACHE ===\n /**\n * Persists a collection of units after validating each entry against the provided schema.\n *\n * @param units - Raw units collection returned by an API call.\n * @param schema - Optional override schema when the default `UnitSchema` is not sufficient.\n */\n async setUnitResults(\n units: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const baseSchema = (schema ?? UnitSchema) as ZodType<Unit>;\n const validatedUnits: Unit[] = [];\n const collection = Array.isArray(units)\n ? units\n : units && typeof units === \"object\"\n ? Object.values(units as Record<string, unknown>)\n : [];\n\n collection.forEach((unit, index) => {\n const parsed = validate(baseSchema, unit, `unitResults[${index}]`);\n if (parsed) validatedUnits.push(parsed);\n });\n await this.setState(state => ({\n ...state,\n unitResults: validatedUnits,\n }));\n }\n\n /**\n * Clears the cached unit results array.\n */\n async clearUnitResults(): Promise<void> {\n await this.setState(state => ({\n ...state,\n unitResults: [],\n }));\n }\n\n // === PROPERTY DATA BAG (full property payloads & custom data) ===\n /**\n * Replaces the persisted property payload with validated data.\n *\n * @param propertyId - ID of the property to mutate.\n * @param data - New property payload.\n * @param schema - Optional schema override used for validation.\n */\n async setPropertyData(\n propertyId: string | number,\n data: unknown,\n schema?: ZodObject<any, any, any, any, any>,\n ): Promise<void> {\n const id = String(propertyId);\n const baseSchema = (schema ?? PropertySchema) as ZodObject<any, any, any, any, any>;\n await this.setState(state => {\n const property = state.properties[id];\n if (!property) return state;\n const validated = validate(baseSchema, data, `properties.${id}.data`) as Property | null;\n if (!validated) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: validated,\n },\n },\n };\n });\n }\n\n /**\n * Merges partial property data into the persisted payload with validation safeguards.\n *\n * @param propertyId - ID of the property to update.\n * @param partial - Partial payload to merge.\n * @param schema - Optional schema override for validation.\n */\n async mergePropertyData(\n propertyId: string | number,\n partial: unknown,\n schema?: ZodObject<any, any, any, any, any>,\n ): Promise<void> {\n const id = String(propertyId);\n const baseSchema = (schema ?? PropertySchema) as ZodObject<any, any, any, any, any>;\n await this.setState(state => {\n const property = state.properties[id];\n if (!property) return state;\n const current = property.data;\n if (!current) {\n const full = validate(baseSchema, partial, `properties.${id}.data`) as Property | null;\n if (!full) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: full,\n },\n },\n };\n }\n\n const partialSchema = baseSchema.partial();\n const validatedPartial = validate(\n partialSchema,\n partial,\n `properties.${id}.data.partial`,\n ) as Partial<Property> | null;\n if (!validatedPartial) return state;\n const merged = validate(\n baseSchema,\n { ...current, ...validatedPartial },\n `properties.${id}.data`,\n ) as Property | null;\n if (!merged) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: merged,\n },\n },\n };\n });\n }\n\n // Accepts a full API property object, validates, and stores it into the\n // per-property `data` bag. Ensures the property entry exists/updated.\n /**\n * Inserts or updates a property entry from an API payload, enforcing schema validation.\n *\n * @param apiProperty - Raw property object returned by an API.\n * @param schema - Optional schema override.\n */\n async upsertPropertyFromApi(\n apiProperty: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const s = schema ?? PropertySchema;\n const parsed: any = s.parse(apiProperty);\n const id = parsed.id ?? parsed.propertyId;\n if (id === undefined || id === null) {\n throw new Error(\"upsertPropertyFromApi: property id is required\");\n }\n const propertyId = String(id);\n const slug: string | undefined = parsed.slug ?? undefined;\n\n await this.setState(state => {\n const existing = state.properties[propertyId];\n const next: UserPropertyState = existing\n ? {\n ...existing,\n ...(slug ? { slug } : {}),\n data: parsed,\n }\n : {\n id: propertyId,\n slug: slug ?? \"\",\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n data: parsed,\n };\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: next,\n },\n };\n });\n }\n\n /**\n * Marks the provided property as current and optionally updates the slug.\n *\n * @param propertyId - Property identifier to focus.\n * @param slug - Optional slug override.\n */\n async setCurrentProperty(propertyId: string | number, slug?: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => ({\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug || state.currentPropertySlug,\n }));\n }\n\n /**\n * Updates the slug for the current property selection.\n *\n * @param slug - New slug to persist.\n */\n async setCurrentPropertySlug(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n currentPropertySlug: slug\n }));\n }\n\n /**\n * Adds a slug to the `hasPreviouslySearched` list without duplicating existing entries.\n *\n * @param slug - Slug to record.\n */\n async setHasPreviouslySearched(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n hasPreviouslySearched: Array.from(\n new Set([...state.hasPreviouslySearched, slug])\n ),\n }));\n }\n\n /**\n * Replaces the favoritedUnits list for the current property with the provided array.\n * Intended for seeding IndexedDB from an API response (e.g. bootstrap endpoint).\n *\n * @param unitIds - Canonical list of favorited unit IDs from the API.\n */\n async setFavoriteUnitIds(unitIds: string[]): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: { ...property, favoritedUnits: unitIds },\n },\n };\n });\n }\n\n /**\n * Toggles a unit's favorite state for the currently active property.\n *\n * @param unitId - Unit identifier to toggle.\n */\n async toggleFavorite(unitId: string): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const isFavorited = property.favoritedUnits.includes(unitId);\n const updatedFavoritedUnits = isFavorited\n ? property.favoritedUnits.filter((id) => id !== unitId)\n : [...property.favoritedUnits, unitId];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n favoritedUnits: updatedFavoritedUnits,\n },\n },\n };\n });\n }\n\n /**\n * Records the most recent view date for a unit and opens the unit URL in the browser when available.\n *\n * @param unitId - Identifier of the viewed unit.\n * @param slug - Property slug used to construct the URL.\n */\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\n\n const url = `https://${slug}`;\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n\n const today = new Date();\n const formattedDate = `${String(today.getMonth() + 1).padStart(\n 2,\n \"0\"\n )}/${String(today.getDate()).padStart(2, \"0\")}`;\n\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n { unitId, viewedDate: formattedDate },\n ];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n\n }\n\n /**\n * Stamps the current property with the moment the tour outreach occurred.\n */\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n /**\n * Reads the stored tour contact timestamp for the current property.\n *\n * @returns ISO string or null when no timestamp exists.\n */\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (!propertyId) return null;\n\n return state.properties[propertyId]?.tourContactedOn ?? null;\n }\n\n /**\n * Persists questionnaire results captured for the current property.\n *\n * @param results - Arbitrary questionnaire data.\n */\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n /**\n * Persists structured tour contact preferences for the active property. The method waits until\n * a current property is available, allowing callers to invoke it before initialization completes.\n *\n * @param data - Contact preferences captured from the UI.\n */\n async setTourContactData(data: TourContactData): Promise<void> {\n const propertyId = await this.waitForCurrentProperty();\n\n await this.setState(state => {\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n\n\n\n\n\n\n // === FILTER OPERATIONS ===\n\n /**\n * Merges the provided filter values into the committed filter state.\n *\n * @param filters - Partial filter payload to apply.\n */\n async setFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n filters: { ...state.filters, ...filters }\n }));\n }\n\n /**\n * Updates the transient filters used for in-progress UI interactions.\n *\n * @param filters - Partial staging filter payload.\n */\n async setTempFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, ...filters }\n }));\n }\n\n /**\n * Resets the committed filters to their default values.\n */\n async setFiltersToDefault(): Promise<void> {\n await this.setState(state => ({ ...state, filters: defaultFilters }));\n }\n\n /**\n * Merges partial values into the API filters payload used for network requests.\n *\n * @param filters - Partial query parameters to persist.\n */\n async setApiFilters(filters: Partial<QueryParams>): Promise<void> {\n await this.setState(state => ({\n ...state,\n apiFilters: { ...state.apiFilters, ...filters }\n }));\n }\n\n /**\n * Updates a single temporary filter field without touching the rest of the staged filters.\n *\n * @param key - Filter key to mutate.\n * @param value - New value to assign.\n */\n async handleTempFilterChange<K extends keyof Filters>(\n key: K,\n value: Filters[K]\n ): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, [key]: value }\n }));\n }\n\n /**\n * Normalizes the committed filters into API-ready structures and persists the result.\n */\n async submitFilterUpdate(): Promise<void> {\n await this.setState(state => {\n const apiParams: QueryParams = transformFiltersToUnitsSearchParams(\n {\n ...state.filters,\n limit: state.apiFilters.limit,\n page: state.apiFilters.page,\n sortBy: state.sortBy,\n },\n {\n defaultLimit: state.apiFilters.limit,\n defaultPage: state.apiFilters.page,\n defaultSort: state.sortBy,\n },\n );\n\n return {\n ...state,\n apiFilters: apiParams,\n };\n });\n }\n\n // === RESULTS AND SORTING ===\n\n /**\n * Persists the selected results mode (e.g. \"all\" or \"favorites\").\n *\n * @param mode - Mode identifier to store.\n */\n async setResultsMode(mode: ResultsMode): Promise<void> {\n await this.setState(state => ({ ...state, resultsMode: mode }));\n }\n\n /**\n * Persists the currently selected sort option.\n *\n * @param sortBy - Sort identifier.\n */\n async setSortBy(sortBy: SortBy): Promise<void> {\n await this.setState(state => ({ ...state, sortBy }));\n }\n\n // === QUESTIONNAIRE ===\n\n /**\n * Stores resolved questionnaire answers keyed by questionnaire name.\n *\n * @param name - Questionnaire identifier.\n * @param values - Selected option values.\n */\n async setResolvedQuestionnaireValues(name: string, values: string[]): Promise<void> {\n await this.setState(state => ({\n ...state,\n resolvedQuestionnaireValues: {\n ...state.resolvedQuestionnaireValues,\n [name]: values\n }\n }));\n }\n\n // === VISITOR UUID ===\n\n /**\n * Reads the persisted visitor UUID from the KV store.\n *\n * @returns The visitor UUID string or null when not yet set.\n */\n async getVisitorUUID(): Promise<string | null> {\n const user = await kvGet<{ visitor_uuid?: string }>(\"user\");\n return user?.visitor_uuid ?? null;\n }\n\n /**\n * Persists a visitor UUID to the KV store.\n *\n * @param vid - Visitor UUID string returned by the session API.\n */\n async setVisitorUUID(vid: string): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n const safe = current !== null && typeof current === \"object\" && !Array.isArray(current) ? current : {};\n await kvSet(\"user\", { ...safe, visitor_uuid: vid });\n }\n\n // === UTILITY METHODS ===\n\n /**\n * Returns convenience state for a unit within the current property.\n *\n * @param unitId - Identifier of the unit to inspect.\n * @returns Favorite flag and last viewed date.\n */\n async getUnitState(unitId: string): Promise<{\n isFavorite: boolean;\n viewedDate: string;\n }> {\n const state = await this.getState();\n const property = state.currentPropertyId ? state.properties[state.currentPropertyId] : null;\n\n return {\n isFavorite: property?.favoritedUnits.includes(unitId) ?? false,\n viewedDate:\n property?.viewedUnits.find((u) => u.unitId === unitId)?.viewedDate ?? \"\",\n };\n }\n\n /**\n * Builds a canonical results URL based on the current property slug.\n *\n * @returns Relative results URL or null when no property is selected.\n */\n async getResultsUrl(): Promise<string | null> {\n const state = await this.getState();\n return state.currentPropertySlug ? `/${state.currentPropertySlug}/results` : null;\n }\n\n /**\n * Retrieves the currently selected property entry.\n *\n * @returns Property state or null when unset.\n */\n async getCurrentProperty(): Promise<UserPropertyState | null> {\n const state = await this.getState();\n return state.currentPropertyId ? state.properties[state.currentPropertyId] ?? null : null;\n }\n\n /**\n * Retrieves property data for a specific property or defaults to the current property.\n *\n * @param propertyId - Optional property identifier to fetch.\n * @returns Property state or null when unavailable.\n */\n async getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null> {\n const state = await this.getState();\n const id = propertyId == null ? state.currentPropertyId : String(propertyId);\n return id ? state.properties[id] ?? null : null;\n }\n\n /**\n * Reads and returns the full validated unified store state.\n */\n async getFullState(): Promise<UnifiedStoreData> {\n return this.getState();\n }\n\n /**\n * Hydrates the store with the default scaffold when no data has been persisted yet.\n */\n async initialize(): Promise<void> {\n // Ensure default shape is present; no-op if already initialized\n await this.setState(state => ({ ...defaultUnifiedStoreData, ...state }));\n }\n\n}\n\n// Export singleton instance\nexport const store = new UnifiedStore();\n// Alias to prefer neutral naming going forward\nexport { UnifiedStore as Store };\n// Re-export types for convenience (tests import from this module)\nexport type { UserPropertyState, Filters } from \"../schema\";\n"],"names":["defaultFilters","defaultUnifiedStoreData","UnifiedStore","state","kvGet","merged","parsed","UnifiedStoreDataSchema","sanitizedProperties","acc","key","value","entry","UserPropertyStateSchema","sanitizedUnitResults","UnitSchema","fallback","fallbackParsed","updater","currentState","newState","validatedState","kvSet","timeoutMs","deadline","propertyId","resolve","finalState","slug","id","units","schema","baseSchema","validatedUnits","unit","index","validate","data","PropertySchema","property","validated","partial","current","full","partialSchema","validatedPartial","apiProperty","existing","next","unitIds","unitId","updatedFavoritedUnits","url","today","formattedDate","updatedViewedUnits","_a","results","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","safe","u","store"],"mappings":"8NAsBMA,EAA0B,CAC9B,kBAA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,CACpD,CAUA,MAAM,aAAahB,EAGhB,OACD,MAAM/C,EAAQ,MAAM,KAAK,SAAA,EACnBoC,EAAWpC,EAAM,kBAAoBA,EAAM,WAAWA,EAAM,iBAAiB,EAAI,KAEvF,MAAO,CACL,YAAYoC,GAAA,YAAAA,EAAU,eAAe,SAASW,KAAW,GACzD,aACEM,EAAAjB,GAAA,YAAAA,EAAU,YAAY,KAAM6B,GAAMA,EAAE,SAAWlB,KAA/C,YAAAM,EAAwD,aAAc,EAAA,CAE5E,CAOA,MAAM,eAAwC,CAC5C,MAAMrD,EAAQ,MAAM,KAAK,SAAA,EACzB,OAAOA,EAAM,oBAAsB,IAAIA,EAAM,mBAAmB,WAAa,IAC/E,CAOA,MAAM,oBAAwD,CAC5D,MAAMA,EAAQ,MAAM,KAAK,SAAA,EACzB,OAAOA,EAAM,kBAAoBA,EAAM,WAAWA,EAAM,iBAAiB,GAAK,KAAO,IACvF,CAQA,MAAM,gBAAgBsB,EAAiE,CACrF,MAAMtB,EAAQ,MAAM,KAAK,SAAA,EACnB0B,EAAKJ,GAAc,KAAOtB,EAAM,kBAAoB,OAAOsB,CAAU,EAC3E,OAAOI,EAAK1B,EAAM,WAAW0B,CAAE,GAAK,KAAO,IAC7C,CAKA,MAAM,cAA0C,CAC9C,OAAO,KAAK,SAAA,CACd,CAKA,MAAM,YAA4B,CAEhC,MAAM,KAAK,SAAS1B,IAAU,CAAE,GAAGF,EAAyB,GAAGE,GAAQ,CACzE,CAEF,CAGO,MAAMkE,EAAQ,IAAInE"}
|
|
1
|
+
{"version":3,"file":"store.cjs","sources":["../../src/stores/store.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport type { ZodType, ZodTypeAny } from \"zod\";\nimport {\n UnifiedStoreDataSchema,\n UserPropertyStateSchema,\n type UnifiedStoreData,\n type UserPropertyState,\n type Filters,\n type QueryParams,\n type ResultsMode,\n type SortBy,\n type TourContactData,\n type Unit,\n UnitSchema,\n} from \"../schema\";\nimport { validate } from \"../validation\";\nimport { transformFiltersToUnitsSearchParams } from \"../features/filters/transformers\";\n\n// Default values\nconst defaultFilters: Filters = {\n date_availability: undefined,\n qty_bedrooms: undefined,\n base_price: undefined,\n highlights: undefined,\n};\n\nconst defaultUnifiedStoreData: UnifiedStoreData = {\n // Property data\n properties: {},\n currentPropertyId: null,\n currentPropertySlug: null,\n hasPreviouslySearched: [],\n\n // App data\n unitResults: [],\n filters: defaultFilters,\n tempFilters: defaultFilters,\n apiFilters: {\n limit: 10,\n page: 1,\n sortBy: \"relevance\",\n },\n resultsMode: \"all\",\n resolvedQuestionnaireValues: {},\n sortBy: \"relevance\",\n};\n\nconst toArray = (input: unknown): unknown[] => {\n if (input == null) return [];\n return Array.isArray(input) ? input : [input];\n};\n\nconst extractFilterValues = (value: unknown): unknown[] => {\n return toArray(value).flatMap(item => {\n if (item == null) return [];\n if (Array.isArray(item)) return item;\n if (typeof item === \"object\" && \"value\" in (item as any)) {\n const v = (item as any).value;\n return Array.isArray(v) ? v : v != null ? [v] : [];\n }\n return [item];\n });\n};\n\nconst toStringArray = (value: unknown): string[] =>\n extractFilterValues(value)\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .map(v => String(v))\n .map(v => v.trim())\n .filter(v => v.length > 0);\n\nconst toNumberArray = (value: unknown): number[] =>\n extractFilterValues(value)\n .map(v => {\n if (typeof v === \"number\" && Number.isFinite(v)) return v;\n const num = Number(v);\n return Number.isFinite(num) ? num : null;\n })\n .filter((v): v is number => v !== null);\n\nconst toNumberValue = (value: unknown): number | null => {\n if (value == null) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"object\" && \"value\" in (value as any)) {\n return toNumberValue((value as any).value);\n }\n const num = Number(value);\n return Number.isFinite(num) ? num : null;\n};\n\n// Unified store class\nexport class UnifiedStore {\n /**\n * Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema\n * and sanitizing invalid entries where possible.\n */\n private async getState(): Promise<UnifiedStoreData> {\n const state = await kvGet<UnifiedStoreData>(\"app\");\n if (!state) {\n return defaultUnifiedStoreData;\n }\n\n const merged = {\n ...defaultUnifiedStoreData,\n ...state,\n properties: state.properties ?? {},\n unitResults: state.unitResults ?? [],\n currentPropertyId:\n state.currentPropertyId == null ? null : String(state.currentPropertyId),\n currentPropertySlug: state.currentPropertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = UnifiedStoreDataSchema.safeParse(merged);\n if (parsed.success) return parsed.data;\n\n // Sanitize by dropping invalid property entries and unit results\n const sanitizedProperties = Object.entries(merged.properties ?? {}).reduce<\n Record<string, UserPropertyState>\n >((acc, [key, value]) => {\n const entry = UserPropertyStateSchema.safeParse(value);\n if (entry.success) acc[key] = entry.data;\n return acc;\n }, {});\n\n const rawUnitResults = Array.isArray(merged.unitResults)\n ? merged.unitResults\n : merged.unitResults && typeof merged.unitResults === \"object\"\n ? Object.values(merged.unitResults as Record<string, unknown>)\n : [];\n\n const sanitizedUnitResults = rawUnitResults.reduce<Unit[]>((acc, value) => {\n const entry = UnitSchema.safeParse(value);\n if (entry.success) acc.push(entry.data);\n return acc;\n }, []);\n\n const fallback = {\n ...merged,\n properties: sanitizedProperties,\n unitResults: sanitizedUnitResults,\n };\n\n const fallbackParsed = UnifiedStoreDataSchema.safeParse(fallback);\n return fallbackParsed.success ? fallbackParsed.data : defaultUnifiedStoreData;\n }\n\n /**\n * Applies an updater function to the current store state, validates the result, and persists it.\n *\n * @param updater - Pure function that maps the current state to the next state.\n */\n private async setState(updater: (state: UnifiedStoreData) => UnifiedStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = UnifiedStoreDataSchema.parse(newState);\n await kvSet(\"app\", validatedState);\n }\n\n /**\n * Polls the persisted state until a current property pointer is available or the timeout elapses.\n *\n * @param timeoutMs - Maximum time in milliseconds to wait before failing.\n * @returns The active property ID once it becomes available.\n * @throws Error if the property pointer is not set before the timeout expires.\n */\n private async waitForCurrentProperty(timeoutMs = 1000): Promise<string> {\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (propertyId && state.properties[propertyId]) return propertyId;\n\n await new Promise(resolve => setTimeout(resolve, 16));\n }\n\n const finalState = await this.getState();\n const propertyId = finalState.currentPropertyId;\n if (propertyId && finalState.properties[propertyId]) return propertyId;\n\n throw new Error(\"UnifiedStore: current property was not initialized in time\");\n }\n\n // === PROPERTY OPERATIONS ===\n\n /**\n * Ensures a property entry exists and registers it as the current property.\n *\n * @param propertyId - Identifier used to track the property.\n * @param slug - Canonical slug associated with the property.\n */\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.properties && state.properties[id]) {\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug\n };\n }\n\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug,\n properties: {\n ...state.properties,\n [id]: {\n id,\n slug,\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n },\n },\n };\n });\n }\n\n // === UNIT RESULTS CACHE ===\n /**\n * Persists a collection of units after validating each entry against the provided schema.\n *\n * @param units - Raw units collection returned by an API call.\n * @param schema - Optional override schema when the default `UnitSchema` is not sufficient.\n */\n async setUnitResults(\n units: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const baseSchema = (schema ?? UnitSchema) as ZodType<Unit>;\n const validatedUnits: Unit[] = [];\n const collection = Array.isArray(units)\n ? units\n : units && typeof units === \"object\"\n ? Object.values(units as Record<string, unknown>)\n : [];\n\n collection.forEach((unit, index) => {\n const parsed = validate(baseSchema, unit, `unitResults[${index}]`);\n if (parsed) validatedUnits.push(parsed);\n });\n await this.setState(state => ({\n ...state,\n unitResults: validatedUnits,\n }));\n }\n\n /**\n * Clears the cached unit results array.\n */\n async clearUnitResults(): Promise<void> {\n await this.setState(state => ({\n ...state,\n unitResults: [],\n }));\n }\n\n /**\n * Marks the provided property as current and optionally updates the slug.\n *\n * @param propertyId - Property identifier to focus.\n * @param slug - Optional slug override.\n */\n async setCurrentProperty(propertyId: string | number, slug?: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => ({\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug || state.currentPropertySlug,\n }));\n }\n\n /**\n * Updates the slug for the current property selection.\n *\n * @param slug - New slug to persist.\n */\n async setCurrentPropertySlug(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n currentPropertySlug: slug\n }));\n }\n\n /**\n * Adds a slug to the `hasPreviouslySearched` list without duplicating existing entries.\n *\n * @param slug - Slug to record.\n */\n async setHasPreviouslySearched(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n hasPreviouslySearched: Array.from(\n new Set([...state.hasPreviouslySearched, slug])\n ),\n }));\n }\n\n /**\n * Records the most recent view date for a unit and opens the unit URL in the browser when available.\n *\n * @param unitId - Identifier of the viewed unit.\n * @param slug - Property slug used to construct the URL.\n */\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\n\n const url = `https://${slug}`;\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n\n const today = new Date();\n const formattedDate = `${String(today.getMonth() + 1).padStart(\n 2,\n \"0\"\n )}/${String(today.getDate()).padStart(2, \"0\")}`;\n\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n { unitId, viewedDate: formattedDate },\n ];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n\n }\n\n /**\n * Stamps the current property with the moment the tour outreach occurred.\n */\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n /**\n * Reads the stored tour contact timestamp for the current property.\n *\n * @returns ISO string or null when no timestamp exists.\n */\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (!propertyId) return null;\n\n return state.properties[propertyId]?.tourContactedOn ?? null;\n }\n\n /**\n * Persists questionnaire results captured for the current property.\n *\n * @param results - Arbitrary questionnaire data.\n */\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n /**\n * Persists structured tour contact preferences for the active property. The method waits until\n * a current property is available, allowing callers to invoke it before initialization completes.\n *\n * @param data - Contact preferences captured from the UI.\n */\n async setTourContactData(data: TourContactData): Promise<void> {\n const propertyId = await this.waitForCurrentProperty();\n\n await this.setState(state => {\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n\n\n\n\n\n\n // === FILTER OPERATIONS ===\n\n /**\n * Merges the provided filter values into the committed filter state.\n *\n * @param filters - Partial filter payload to apply.\n */\n async setFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n filters: { ...state.filters, ...filters }\n }));\n }\n\n /**\n * Updates the transient filters used for in-progress UI interactions.\n *\n * @param filters - Partial staging filter payload.\n */\n async setTempFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, ...filters }\n }));\n }\n\n /**\n * Resets the committed filters to their default values.\n */\n async setFiltersToDefault(): Promise<void> {\n await this.setState(state => ({ ...state, filters: defaultFilters }));\n }\n\n /**\n * Merges partial values into the API filters payload used for network requests.\n *\n * @param filters - Partial query parameters to persist.\n */\n async setApiFilters(filters: Partial<QueryParams>): Promise<void> {\n await this.setState(state => ({\n ...state,\n apiFilters: { ...state.apiFilters, ...filters }\n }));\n }\n\n /**\n * Updates a single temporary filter field without touching the rest of the staged filters.\n *\n * @param key - Filter key to mutate.\n * @param value - New value to assign.\n */\n async handleTempFilterChange<K extends keyof Filters>(\n key: K,\n value: Filters[K]\n ): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, [key]: value }\n }));\n }\n\n /**\n * Normalizes the committed filters into API-ready structures and persists the result.\n */\n async submitFilterUpdate(): Promise<void> {\n await this.setState(state => {\n const apiParams: QueryParams = transformFiltersToUnitsSearchParams(\n {\n ...state.filters,\n limit: state.apiFilters.limit,\n page: state.apiFilters.page,\n sortBy: state.sortBy,\n },\n {\n defaultLimit: state.apiFilters.limit,\n defaultPage: state.apiFilters.page,\n defaultSort: state.sortBy,\n },\n );\n\n return {\n ...state,\n apiFilters: apiParams,\n };\n });\n }\n\n // === RESULTS AND SORTING ===\n\n /**\n * Persists the selected results mode (e.g. \"all\" or \"favorites\").\n *\n * @param mode - Mode identifier to store.\n */\n async setResultsMode(mode: ResultsMode): Promise<void> {\n await this.setState(state => ({ ...state, resultsMode: mode }));\n }\n\n /**\n * Persists the currently selected sort option.\n *\n * @param sortBy - Sort identifier.\n */\n async setSortBy(sortBy: SortBy): Promise<void> {\n await this.setState(state => ({ ...state, sortBy }));\n }\n\n // === QUESTIONNAIRE ===\n\n /**\n * Stores resolved questionnaire answers keyed by questionnaire name.\n *\n * @param name - Questionnaire identifier.\n * @param values - Selected option values.\n */\n async setResolvedQuestionnaireValues(name: string, values: string[]): Promise<void> {\n await this.setState(state => ({\n ...state,\n resolvedQuestionnaireValues: {\n ...state.resolvedQuestionnaireValues,\n [name]: values\n }\n }));\n }\n\n // === VISITOR UUID ===\n\n /**\n * Reads the persisted visitor UUID from the KV store.\n *\n * @returns The visitor UUID string or null when not yet set.\n */\n async getVisitorUUID(): Promise<string | null> {\n const user = await kvGet<{ visitor_uuid?: string }>(\"user\");\n return user?.visitor_uuid ?? null;\n }\n\n /**\n * Persists a visitor UUID to the KV store.\n *\n * @param vid - Visitor UUID string returned by the session API.\n */\n async setVisitorUUID(vid: string): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n const safe = current !== null && typeof current === \"object\" && !Array.isArray(current) ? current : {};\n await kvSet(\"user\", { ...safe, visitor_uuid: vid });\n }\n\n /**\n * Removes the visitor UUID from the KV store.\n * Use when the stored UUID is stale (e.g. bootstrap returns 404).\n */\n async clearVisitorUUID(): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) return;\n const { visitor_uuid: _, ...rest } = current;\n await kvSet(\"user\", rest);\n }\n\n}\n\n// Export singleton instance\nexport const store = new UnifiedStore();\n// Alias to prefer neutral naming going forward\nexport { UnifiedStore as Store };\n// Re-export types for convenience (tests import from this module)\nexport type { UserPropertyState, Filters } from \"../schema\";\n"],"names":["defaultFilters","defaultUnifiedStoreData","UnifiedStore","state","kvGet","merged","parsed","UnifiedStoreDataSchema","sanitizedProperties","acc","key","value","entry","UserPropertyStateSchema","sanitizedUnitResults","UnitSchema","fallback","fallbackParsed","updater","currentState","newState","validatedState","kvSet","timeoutMs","deadline","propertyId","resolve","finalState","slug","id","units","schema","baseSchema","validatedUnits","unit","index","validate","unitId","url","today","formattedDate","property","updatedViewedUnits","u","_a","results","data","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","current","safe","_","rest","store"],"mappings":"8NAmBMA,EAA0B,CAC9B,kBAAmB,OACnB,aAAc,OACd,WAAY,OACZ,WAAY,MACd,EAEMC,EAA4C,CAEhD,WAAY,CAAA,EACZ,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ZodTypeAny } from "zod";
|
|
2
|
+
import { type Filters, type QueryParams, type ResultsMode, type SortBy, type TourContactData } from "../schema";
|
|
3
3
|
export declare class UnifiedStore {
|
|
4
4
|
/**
|
|
5
5
|
* Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema
|
|
@@ -38,29 +38,6 @@ export declare class UnifiedStore {
|
|
|
38
38
|
* Clears the cached unit results array.
|
|
39
39
|
*/
|
|
40
40
|
clearUnitResults(): Promise<void>;
|
|
41
|
-
/**
|
|
42
|
-
* Replaces the persisted property payload with validated data.
|
|
43
|
-
*
|
|
44
|
-
* @param propertyId - ID of the property to mutate.
|
|
45
|
-
* @param data - New property payload.
|
|
46
|
-
* @param schema - Optional schema override used for validation.
|
|
47
|
-
*/
|
|
48
|
-
setPropertyData(propertyId: string | number, data: unknown, schema?: ZodObject<any, any, any, any, any>): Promise<void>;
|
|
49
|
-
/**
|
|
50
|
-
* Merges partial property data into the persisted payload with validation safeguards.
|
|
51
|
-
*
|
|
52
|
-
* @param propertyId - ID of the property to update.
|
|
53
|
-
* @param partial - Partial payload to merge.
|
|
54
|
-
* @param schema - Optional schema override for validation.
|
|
55
|
-
*/
|
|
56
|
-
mergePropertyData(propertyId: string | number, partial: unknown, schema?: ZodObject<any, any, any, any, any>): Promise<void>;
|
|
57
|
-
/**
|
|
58
|
-
* Inserts or updates a property entry from an API payload, enforcing schema validation.
|
|
59
|
-
*
|
|
60
|
-
* @param apiProperty - Raw property object returned by an API.
|
|
61
|
-
* @param schema - Optional schema override.
|
|
62
|
-
*/
|
|
63
|
-
upsertPropertyFromApi(apiProperty: unknown, schema?: ZodTypeAny): Promise<void>;
|
|
64
41
|
/**
|
|
65
42
|
* Marks the provided property as current and optionally updates the slug.
|
|
66
43
|
*
|
|
@@ -80,19 +57,6 @@ export declare class UnifiedStore {
|
|
|
80
57
|
* @param slug - Slug to record.
|
|
81
58
|
*/
|
|
82
59
|
setHasPreviouslySearched(slug: string): Promise<void>;
|
|
83
|
-
/**
|
|
84
|
-
* Replaces the favoritedUnits list for the current property with the provided array.
|
|
85
|
-
* Intended for seeding IndexedDB from an API response (e.g. bootstrap endpoint).
|
|
86
|
-
*
|
|
87
|
-
* @param unitIds - Canonical list of favorited unit IDs from the API.
|
|
88
|
-
*/
|
|
89
|
-
setFavoriteUnitIds(unitIds: string[]): Promise<void>;
|
|
90
|
-
/**
|
|
91
|
-
* Toggles a unit's favorite state for the currently active property.
|
|
92
|
-
*
|
|
93
|
-
* @param unitId - Unit identifier to toggle.
|
|
94
|
-
*/
|
|
95
|
-
toggleFavorite(unitId: string): Promise<void>;
|
|
96
60
|
/**
|
|
97
61
|
* Records the most recent view date for a unit and opens the unit URL in the browser when available.
|
|
98
62
|
*
|
|
@@ -188,42 +152,10 @@ export declare class UnifiedStore {
|
|
|
188
152
|
*/
|
|
189
153
|
setVisitorUUID(vid: string): Promise<void>;
|
|
190
154
|
/**
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* @param unitId - Identifier of the unit to inspect.
|
|
194
|
-
* @returns Favorite flag and last viewed date.
|
|
195
|
-
*/
|
|
196
|
-
getUnitState(unitId: string): Promise<{
|
|
197
|
-
isFavorite: boolean;
|
|
198
|
-
viewedDate: string;
|
|
199
|
-
}>;
|
|
200
|
-
/**
|
|
201
|
-
* Builds a canonical results URL based on the current property slug.
|
|
202
|
-
*
|
|
203
|
-
* @returns Relative results URL or null when no property is selected.
|
|
204
|
-
*/
|
|
205
|
-
getResultsUrl(): Promise<string | null>;
|
|
206
|
-
/**
|
|
207
|
-
* Retrieves the currently selected property entry.
|
|
208
|
-
*
|
|
209
|
-
* @returns Property state or null when unset.
|
|
210
|
-
*/
|
|
211
|
-
getCurrentProperty(): Promise<UserPropertyState | null>;
|
|
212
|
-
/**
|
|
213
|
-
* Retrieves property data for a specific property or defaults to the current property.
|
|
214
|
-
*
|
|
215
|
-
* @param propertyId - Optional property identifier to fetch.
|
|
216
|
-
* @returns Property state or null when unavailable.
|
|
217
|
-
*/
|
|
218
|
-
getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null>;
|
|
219
|
-
/**
|
|
220
|
-
* Reads and returns the full validated unified store state.
|
|
221
|
-
*/
|
|
222
|
-
getFullState(): Promise<UnifiedStoreData>;
|
|
223
|
-
/**
|
|
224
|
-
* Hydrates the store with the default scaffold when no data has been persisted yet.
|
|
155
|
+
* Removes the visitor UUID from the KV store.
|
|
156
|
+
* Use when the stored UUID is stale (e.g. bootstrap returns 404).
|
|
225
157
|
*/
|
|
226
|
-
|
|
158
|
+
clearVisitorUUID(): Promise<void>;
|
|
227
159
|
}
|
|
228
160
|
export declare const store: UnifiedStore;
|
|
229
161
|
export { UnifiedStore as Store };
|