@superbright/indexeddb-orm 1.0.30 → 1.0.31
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 +3 -21
- package/dist/stores/store.mjs +72 -120
- 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 d=require("../storage.cjs"),c=require("../schema.cjs"),S=require("../validation.cjs"),P=require("../features/filters/transformers.cjs"),f={date_availability:void 0,qty_bedrooms:void 0,base_price:void 0,highlights:void 0},h={properties:{},currentPropertyId:null,currentPropertySlug:null,hasPreviouslySearched:[],unitResults:[],filters:f,tempFilters:f,apiFilters:{limit:10,page:1,sortBy:"relevance"},resultsMode:"all",resolvedQuestionnaireValues:{},sortBy:"relevance"};class w{async getState(){const t=await d.kvGet("app");if(!t)return h;const e={...h,...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=c.UnifiedStoreDataSchema.safeParse(e);if(r.success)return r.data;const s=Object.entries(e.properties??{}).reduce((u,[p,l])=>{const y=c.UserPropertyStateSchema.safeParse(l);return y.success&&(u[p]=y.data),u},{}),i=(Array.isArray(e.unitResults)?e.unitResults:e.unitResults&&typeof e.unitResults=="object"?Object.values(e.unitResults):[]).reduce((u,p)=>{const l=c.UnitSchema.safeParse(p);return l.success&&u.push(l.data),u},[]),a={...e,properties:s,unitResults:i},n=c.UnifiedStoreDataSchema.safeParse(a);return n.success?n.data:h}async setState(t){const e=await this.getState(),r=t(e),s=c.UnifiedStoreDataSchema.parse(r);await d.kvSet("app",s)}async waitForCurrentProperty(t=1e3){const e=Date.now()+t;for(;Date.now()<e;){const o=await this.getState(),i=o.currentPropertyId;if(i&&o.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??c.UnitSchema,s=[];(Array.isArray(t)?t:t&&typeof t=="object"?Object.values(t):[]).forEach((i,a)=>{const n=S.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 setPropertyData(t,e,r){const s=String(t),o=r??c.PropertySchema;await this.setState(i=>{const a=i.properties[s];if(!a)return i;const n=S.validate(o,e,`properties.${s}.data`);return n?{...i,properties:{...i.properties,[s]:{...a,data:n}}}:i})}async mergePropertyData(t,e,r){const s=String(t),o=r??c.PropertySchema;await this.setState(i=>{const a=i.properties[s];if(!a)return i;const n=a.data;if(!n){const y=S.validate(o,e,`properties.${s}.data`);return y?{...i,properties:{...i.properties,[s]:{...a,data:y}}}:i}const u=o.partial(),p=S.validate(u,e,`properties.${s}.data.partial`);if(!p)return i;const l=S.validate(o,{...n,...p},`properties.${s}.data`);return l?{...i,properties:{...i.properties,[s]:{...a,data:l}}}:i})}async upsertPropertyFromApi(t,e){const s=(e??c.PropertySchema).parse(t),o=s.id??s.propertyId;if(o==null)throw new Error("upsertPropertyFromApi: property id is required");const i=String(o),a=s.slug??void 0;await this.setState(n=>{const u=n.properties[i],p=u?{...u,...a?{slug:a}:{},data:s}:{id:i,slug:a??"",favoritedUnits:[],tourContactedOn:null,viewedUnits:[],questionnaireResults:null,tourContactData:null,data:s};return{...n,properties:{...n.properties,[i]:p}}})}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,o=`${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 u=[...n.viewedUnits.filter(p=>p.unitId!==t),{unitId:t,viewedDate:o}];return{...i,properties:{...i.properties,[a]:{...n,viewedUnits:u}}}})}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:f}))}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 d.kvGet("user");return(t==null?void 0:t.visitor_uuid)??null}async setVisitorUUID(t){const e=await d.kvGet("user"),r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};await d.kvSet("user",{...r,visitor_uuid:t})}async clearVisitorUUID(){const t=await d.kvGet("user");if(t===null||typeof t!="object"||Array.isArray(t))return;const{visitor_uuid:e,...r}=t;await d.kvSet("user",r)}async getResultsUrl(){const t=await this.getState();return t.currentPropertySlug?`/${t.currentPropertySlug}/results`:null}async getCurrentProperty(){const t=await this.getState();return t.currentPropertyId?t.properties[t.currentPropertyId]??null:null}async getPropertyData(t){const e=await this.getState(),r=t==null?e.currentPropertyId:String(t);return r?e.properties[r]??null:null}async getFullState(){return this.getState()}async initialize(){await this.setState(t=>({...h,...t}))}}const g=new w;exports.Store=w;exports.UnifiedStore=w;exports.store=g;
|
|
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,kBAAmB,OACnB,aAAc,OACd,WAAY,OACZ,WAAY,MACd,EAEMC,EAA4C,CAEhD,WAAY,CAAA,EACZ,kBAAmB,KACnB,oBAAqB,KACrB,sBAAuB,CAAA,EAGvB,YAAa,CAAA,EACb,QAASD,EACT,YAAaA,EACb,WAAY,CACV,MAAO,GACP,KAAM,EACN,OAAQ,WAAA,EAEV,YAAa,MACb,4BAA6B,CAAA,EAC7B,OAAQ,WACV,EA8CO,MAAME,CAAa,CAK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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 { 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 * 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 // === UTILITY METHODS ===\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","unitId","url","today","formattedDate","updatedViewedUnits","u","_a","results","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","safe","_","rest","store"],"mappings":"8NAsBMA,EAA0B,CAC9B,kBAAmB,OACnB,aAAc,OACd,WAAY,OACZ,WAAY,MACd,EAEMC,EAA4C,CAEhD,WAAY,CAAA,EACZ,kBAAmB,KACnB,oBAAqB,KACrB,sBAAuB,CAAA,EAGvB,YAAa,CAAA,EACb,QAASD,EACT,YAAaA,EACb,WAAY,CACV,MAAO,GACP,KAAM,EACN,OAAQ,WAAA,EAEV,YAA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AAU,MAAMtC,EAAAA,MAA+B,MAAM,EACrD8D,EAAOxB,IAAY,MAAQ,OAAOA,GAAY,UAAY,CAAC,MAAM,QAAQA,CAAO,EAAIA,EAAU,CAAA,EACpG,MAAMpB,EAAAA,MAAM,OAAQ,CAAE,GAAG4C,EAAM,aAAcD,EAAK,CACpD,CAMA,MAAM,kBAAkC,CACtC,MAAMvB,EAAU,MAAMtC,EAAAA,MAA+B,MAAM,EAC3D,GAAIsC,IAAY,MAAQ,OAAOA,GAAY,UAAY,MAAM,QAAQA,CAAO,EAAG,OAC/E,KAAM,CAAE,aAAcyB,EAAG,GAAGC,GAAS1B,EACrC,MAAMpB,EAAAA,MAAM,OAAQ8C,CAAI,CAC1B,CASA,MAAM,eAAwC,CAC5C,MAAMjE,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"}
|
package/dist/stores/store.d.ts
CHANGED
|
@@ -80,19 +80,6 @@ export declare class UnifiedStore {
|
|
|
80
80
|
* @param slug - Slug to record.
|
|
81
81
|
*/
|
|
82
82
|
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
83
|
/**
|
|
97
84
|
* Records the most recent view date for a unit and opens the unit URL in the browser when available.
|
|
98
85
|
*
|
|
@@ -188,15 +175,10 @@ export declare class UnifiedStore {
|
|
|
188
175
|
*/
|
|
189
176
|
setVisitorUUID(vid: string): Promise<void>;
|
|
190
177
|
/**
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* @param unitId - Identifier of the unit to inspect.
|
|
194
|
-
* @returns Favorite flag and last viewed date.
|
|
178
|
+
* Removes the visitor UUID from the KV store.
|
|
179
|
+
* Use when the stored UUID is stale (e.g. bootstrap returns 404).
|
|
195
180
|
*/
|
|
196
|
-
|
|
197
|
-
isFavorite: boolean;
|
|
198
|
-
viewedDate: string;
|
|
199
|
-
}>;
|
|
181
|
+
clearVisitorUUID(): Promise<void>;
|
|
200
182
|
/**
|
|
201
183
|
* Builds a canonical results URL based on the current property slug.
|
|
202
184
|
*
|
package/dist/stores/store.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { kvGet as
|
|
2
|
-
import { UnifiedStoreDataSchema as
|
|
1
|
+
import { kvGet as y, kvSet as h } from "../storage.mjs";
|
|
2
|
+
import { UnifiedStoreDataSchema as w, UserPropertyStateSchema as m, UnitSchema as g, PropertySchema as f } from "../schema.mjs";
|
|
3
3
|
import { validate as d } from "../validation.mjs";
|
|
4
|
-
import { transformFiltersToUnitsSearchParams as
|
|
5
|
-
const
|
|
4
|
+
import { transformFiltersToUnitsSearchParams as v } from "../features/filters/transformers.mjs";
|
|
5
|
+
const P = {
|
|
6
6
|
date_availability: void 0,
|
|
7
7
|
qty_bedrooms: void 0,
|
|
8
8
|
base_price: void 0,
|
|
9
9
|
highlights: void 0
|
|
10
|
-
},
|
|
10
|
+
}, S = {
|
|
11
11
|
// Property data
|
|
12
12
|
properties: {},
|
|
13
13
|
currentPropertyId: null,
|
|
@@ -15,8 +15,8 @@ const w = {
|
|
|
15
15
|
hasPreviouslySearched: [],
|
|
16
16
|
// App data
|
|
17
17
|
unitResults: [],
|
|
18
|
-
filters:
|
|
19
|
-
tempFilters:
|
|
18
|
+
filters: P,
|
|
19
|
+
tempFilters: P,
|
|
20
20
|
apiFilters: {
|
|
21
21
|
limit: 10,
|
|
22
22
|
page: 1,
|
|
@@ -32,31 +32,31 @@ class U {
|
|
|
32
32
|
* and sanitizing invalid entries where possible.
|
|
33
33
|
*/
|
|
34
34
|
async getState() {
|
|
35
|
-
const t = await
|
|
35
|
+
const t = await y("app");
|
|
36
36
|
if (!t)
|
|
37
|
-
return
|
|
37
|
+
return S;
|
|
38
38
|
const e = {
|
|
39
|
-
...
|
|
39
|
+
...S,
|
|
40
40
|
...t,
|
|
41
41
|
properties: t.properties ?? {},
|
|
42
42
|
unitResults: t.unitResults ?? [],
|
|
43
43
|
currentPropertyId: t.currentPropertyId == null ? null : String(t.currentPropertyId),
|
|
44
44
|
currentPropertySlug: t.currentPropertySlug ?? null,
|
|
45
45
|
hasPreviouslySearched: Array.isArray(t.hasPreviouslySearched) ? t.hasPreviouslySearched.map(String) : []
|
|
46
|
-
}, r =
|
|
46
|
+
}, r = w.safeParse(e);
|
|
47
47
|
if (r.success) return r.data;
|
|
48
48
|
const s = Object.entries(e.properties ?? {}).reduce((p, [u, c]) => {
|
|
49
|
-
const l =
|
|
49
|
+
const l = m.safeParse(c);
|
|
50
50
|
return l.success && (p[u] = l.data), p;
|
|
51
51
|
}, {}), i = (Array.isArray(e.unitResults) ? e.unitResults : e.unitResults && typeof e.unitResults == "object" ? Object.values(e.unitResults) : []).reduce((p, u) => {
|
|
52
52
|
const c = g.safeParse(u);
|
|
53
53
|
return c.success && p.push(c.data), p;
|
|
54
|
-
}, []),
|
|
54
|
+
}, []), a = {
|
|
55
55
|
...e,
|
|
56
56
|
properties: s,
|
|
57
57
|
unitResults: i
|
|
58
|
-
},
|
|
59
|
-
return
|
|
58
|
+
}, n = w.safeParse(a);
|
|
59
|
+
return n.success ? n.data : S;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
62
|
* Applies an updater function to the current store state, validates the result, and persists it.
|
|
@@ -64,8 +64,8 @@ class U {
|
|
|
64
64
|
* @param updater - Pure function that maps the current state to the next state.
|
|
65
65
|
*/
|
|
66
66
|
async setState(t) {
|
|
67
|
-
const e = await this.getState(), r = t(e), s =
|
|
68
|
-
await
|
|
67
|
+
const e = await this.getState(), r = t(e), s = w.parse(r);
|
|
68
|
+
await h("app", s);
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
71
|
* Polls the persisted state until a current property pointer is available or the timeout elapses.
|
|
@@ -77,9 +77,9 @@ class U {
|
|
|
77
77
|
async waitForCurrentProperty(t = 1e3) {
|
|
78
78
|
const e = Date.now() + t;
|
|
79
79
|
for (; Date.now() < e; ) {
|
|
80
|
-
const
|
|
81
|
-
if (i &&
|
|
82
|
-
await new Promise((
|
|
80
|
+
const o = await this.getState(), i = o.currentPropertyId;
|
|
81
|
+
if (i && o.properties[i]) return i;
|
|
82
|
+
await new Promise((a) => setTimeout(a, 16));
|
|
83
83
|
}
|
|
84
84
|
const r = await this.getState(), s = r.currentPropertyId;
|
|
85
85
|
if (s && r.properties[s]) return s;
|
|
@@ -125,9 +125,9 @@ class U {
|
|
|
125
125
|
*/
|
|
126
126
|
async setUnitResults(t, e) {
|
|
127
127
|
const r = e ?? g, s = [];
|
|
128
|
-
(Array.isArray(t) ? t : t && typeof t == "object" ? Object.values(t) : []).forEach((i,
|
|
129
|
-
const
|
|
130
|
-
|
|
128
|
+
(Array.isArray(t) ? t : t && typeof t == "object" ? Object.values(t) : []).forEach((i, a) => {
|
|
129
|
+
const n = d(r, i, `unitResults[${a}]`);
|
|
130
|
+
n && s.push(n);
|
|
131
131
|
}), await this.setState((i) => ({
|
|
132
132
|
...i,
|
|
133
133
|
unitResults: s
|
|
@@ -151,18 +151,18 @@ class U {
|
|
|
151
151
|
* @param schema - Optional schema override used for validation.
|
|
152
152
|
*/
|
|
153
153
|
async setPropertyData(t, e, r) {
|
|
154
|
-
const s = String(t),
|
|
154
|
+
const s = String(t), o = r ?? f;
|
|
155
155
|
await this.setState((i) => {
|
|
156
|
-
const
|
|
157
|
-
if (!
|
|
158
|
-
const
|
|
159
|
-
return
|
|
156
|
+
const a = i.properties[s];
|
|
157
|
+
if (!a) return i;
|
|
158
|
+
const n = d(o, e, `properties.${s}.data`);
|
|
159
|
+
return n ? {
|
|
160
160
|
...i,
|
|
161
161
|
properties: {
|
|
162
162
|
...i.properties,
|
|
163
163
|
[s]: {
|
|
164
|
-
...
|
|
165
|
-
data:
|
|
164
|
+
...a,
|
|
165
|
+
data: n
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
} : i;
|
|
@@ -176,33 +176,33 @@ class U {
|
|
|
176
176
|
* @param schema - Optional schema override for validation.
|
|
177
177
|
*/
|
|
178
178
|
async mergePropertyData(t, e, r) {
|
|
179
|
-
const s = String(t),
|
|
179
|
+
const s = String(t), o = r ?? f;
|
|
180
180
|
await this.setState((i) => {
|
|
181
|
-
const
|
|
182
|
-
if (!
|
|
183
|
-
const
|
|
184
|
-
if (!
|
|
185
|
-
const l = d(
|
|
181
|
+
const a = i.properties[s];
|
|
182
|
+
if (!a) return i;
|
|
183
|
+
const n = a.data;
|
|
184
|
+
if (!n) {
|
|
185
|
+
const l = d(o, e, `properties.${s}.data`);
|
|
186
186
|
return l ? {
|
|
187
187
|
...i,
|
|
188
188
|
properties: {
|
|
189
189
|
...i.properties,
|
|
190
190
|
[s]: {
|
|
191
|
-
...
|
|
191
|
+
...a,
|
|
192
192
|
data: l
|
|
193
193
|
}
|
|
194
194
|
}
|
|
195
195
|
} : i;
|
|
196
196
|
}
|
|
197
|
-
const p =
|
|
197
|
+
const p = o.partial(), u = d(
|
|
198
198
|
p,
|
|
199
199
|
e,
|
|
200
200
|
`properties.${s}.data.partial`
|
|
201
201
|
);
|
|
202
202
|
if (!u) return i;
|
|
203
203
|
const c = d(
|
|
204
|
-
|
|
205
|
-
{ ...
|
|
204
|
+
o,
|
|
205
|
+
{ ...n, ...u },
|
|
206
206
|
`properties.${s}.data`
|
|
207
207
|
);
|
|
208
208
|
return c ? {
|
|
@@ -210,7 +210,7 @@ class U {
|
|
|
210
210
|
properties: {
|
|
211
211
|
...i.properties,
|
|
212
212
|
[s]: {
|
|
213
|
-
...
|
|
213
|
+
...a,
|
|
214
214
|
data: c
|
|
215
215
|
}
|
|
216
216
|
}
|
|
@@ -226,18 +226,18 @@ class U {
|
|
|
226
226
|
* @param schema - Optional schema override.
|
|
227
227
|
*/
|
|
228
228
|
async upsertPropertyFromApi(t, e) {
|
|
229
|
-
const s = (e ??
|
|
230
|
-
if (
|
|
229
|
+
const s = (e ?? f).parse(t), o = s.id ?? s.propertyId;
|
|
230
|
+
if (o == null)
|
|
231
231
|
throw new Error("upsertPropertyFromApi: property id is required");
|
|
232
|
-
const i = String(
|
|
233
|
-
await this.setState((
|
|
234
|
-
const p =
|
|
232
|
+
const i = String(o), a = s.slug ?? void 0;
|
|
233
|
+
await this.setState((n) => {
|
|
234
|
+
const p = n.properties[i], u = p ? {
|
|
235
235
|
...p,
|
|
236
|
-
...
|
|
236
|
+
...a ? { slug: a } : {},
|
|
237
237
|
data: s
|
|
238
238
|
} : {
|
|
239
239
|
id: i,
|
|
240
|
-
slug:
|
|
240
|
+
slug: a ?? "",
|
|
241
241
|
favoritedUnits: [],
|
|
242
242
|
tourContactedOn: null,
|
|
243
243
|
viewedUnits: [],
|
|
@@ -246,9 +246,9 @@ class U {
|
|
|
246
246
|
data: s
|
|
247
247
|
};
|
|
248
248
|
return {
|
|
249
|
-
...
|
|
249
|
+
...n,
|
|
250
250
|
properties: {
|
|
251
|
-
...
|
|
251
|
+
...n.properties,
|
|
252
252
|
[i]: u
|
|
253
253
|
}
|
|
254
254
|
};
|
|
@@ -292,50 +292,6 @@ class U {
|
|
|
292
292
|
)
|
|
293
293
|
}));
|
|
294
294
|
}
|
|
295
|
-
/**
|
|
296
|
-
* Replaces the favoritedUnits list for the current property with the provided array.
|
|
297
|
-
* Intended for seeding IndexedDB from an API response (e.g. bootstrap endpoint).
|
|
298
|
-
*
|
|
299
|
-
* @param unitIds - Canonical list of favorited unit IDs from the API.
|
|
300
|
-
*/
|
|
301
|
-
async setFavoriteUnitIds(t) {
|
|
302
|
-
await this.setState((e) => {
|
|
303
|
-
const r = e.currentPropertyId;
|
|
304
|
-
if (!r) return e;
|
|
305
|
-
const s = e.properties[r];
|
|
306
|
-
return s ? {
|
|
307
|
-
...e,
|
|
308
|
-
properties: {
|
|
309
|
-
...e.properties,
|
|
310
|
-
[r]: { ...s, favoritedUnits: t }
|
|
311
|
-
}
|
|
312
|
-
} : e;
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Toggles a unit's favorite state for the currently active property.
|
|
317
|
-
*
|
|
318
|
-
* @param unitId - Unit identifier to toggle.
|
|
319
|
-
*/
|
|
320
|
-
async toggleFavorite(t) {
|
|
321
|
-
await this.setState((e) => {
|
|
322
|
-
const r = e.currentPropertyId;
|
|
323
|
-
if (!r) return e;
|
|
324
|
-
const s = e.properties[r];
|
|
325
|
-
if (!s) return e;
|
|
326
|
-
const i = s.favoritedUnits.includes(t) ? s.favoritedUnits.filter((n) => n !== t) : [...s.favoritedUnits, t];
|
|
327
|
-
return {
|
|
328
|
-
...e,
|
|
329
|
-
properties: {
|
|
330
|
-
...e.properties,
|
|
331
|
-
[r]: {
|
|
332
|
-
...s,
|
|
333
|
-
favoritedUnits: i
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
};
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
295
|
/**
|
|
340
296
|
* Records the most recent view date for a unit and opens the unit URL in the browser when available.
|
|
341
297
|
*
|
|
@@ -345,25 +301,25 @@ class U {
|
|
|
345
301
|
async markUnitAsViewed(t, e) {
|
|
346
302
|
const r = `https://${e}`;
|
|
347
303
|
window.open(r, "_blank", "noopener,noreferrer");
|
|
348
|
-
const s = /* @__PURE__ */ new Date(),
|
|
304
|
+
const s = /* @__PURE__ */ new Date(), o = `${String(s.getMonth() + 1).padStart(
|
|
349
305
|
2,
|
|
350
306
|
"0"
|
|
351
307
|
)}/${String(s.getDate()).padStart(2, "0")}`;
|
|
352
308
|
await this.setState((i) => {
|
|
353
|
-
const
|
|
309
|
+
const a = i.currentPropertyId;
|
|
310
|
+
if (!a) return i;
|
|
311
|
+
const n = i.properties[a];
|
|
354
312
|
if (!n) return i;
|
|
355
|
-
const o = i.properties[n];
|
|
356
|
-
if (!o) return i;
|
|
357
313
|
const p = [
|
|
358
|
-
...
|
|
359
|
-
{ unitId: t, viewedDate:
|
|
314
|
+
...n.viewedUnits.filter((u) => u.unitId !== t),
|
|
315
|
+
{ unitId: t, viewedDate: o }
|
|
360
316
|
];
|
|
361
317
|
return {
|
|
362
318
|
...i,
|
|
363
319
|
properties: {
|
|
364
320
|
...i.properties,
|
|
365
|
-
[
|
|
366
|
-
...
|
|
321
|
+
[a]: {
|
|
322
|
+
...n,
|
|
367
323
|
viewedUnits: p
|
|
368
324
|
}
|
|
369
325
|
}
|
|
@@ -471,7 +427,7 @@ class U {
|
|
|
471
427
|
* Resets the committed filters to their default values.
|
|
472
428
|
*/
|
|
473
429
|
async setFiltersToDefault() {
|
|
474
|
-
await this.setState((t) => ({ ...t, filters:
|
|
430
|
+
await this.setState((t) => ({ ...t, filters: P }));
|
|
475
431
|
}
|
|
476
432
|
/**
|
|
477
433
|
* Merges partial values into the API filters payload used for network requests.
|
|
@@ -501,7 +457,7 @@ class U {
|
|
|
501
457
|
*/
|
|
502
458
|
async submitFilterUpdate() {
|
|
503
459
|
await this.setState((t) => {
|
|
504
|
-
const e =
|
|
460
|
+
const e = v(
|
|
505
461
|
{
|
|
506
462
|
...t.filters,
|
|
507
463
|
limit: t.apiFilters.limit,
|
|
@@ -560,7 +516,7 @@ class U {
|
|
|
560
516
|
* @returns The visitor UUID string or null when not yet set.
|
|
561
517
|
*/
|
|
562
518
|
async getVisitorUUID() {
|
|
563
|
-
const t = await
|
|
519
|
+
const t = await y("user");
|
|
564
520
|
return (t == null ? void 0 : t.visitor_uuid) ?? null;
|
|
565
521
|
}
|
|
566
522
|
/**
|
|
@@ -569,24 +525,20 @@ class U {
|
|
|
569
525
|
* @param vid - Visitor UUID string returned by the session API.
|
|
570
526
|
*/
|
|
571
527
|
async setVisitorUUID(t) {
|
|
572
|
-
const e = await
|
|
573
|
-
await
|
|
528
|
+
const e = await y("user"), r = e !== null && typeof e == "object" && !Array.isArray(e) ? e : {};
|
|
529
|
+
await h("user", { ...r, visitor_uuid: t });
|
|
574
530
|
}
|
|
575
|
-
// === UTILITY METHODS ===
|
|
576
531
|
/**
|
|
577
|
-
*
|
|
578
|
-
*
|
|
579
|
-
* @param unitId - Identifier of the unit to inspect.
|
|
580
|
-
* @returns Favorite flag and last viewed date.
|
|
532
|
+
* Removes the visitor UUID from the KV store.
|
|
533
|
+
* Use when the stored UUID is stale (e.g. bootstrap returns 404).
|
|
581
534
|
*/
|
|
582
|
-
async
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
viewedDate: ((s = r == null ? void 0 : r.viewedUnits.find((a) => a.unitId === t)) == null ? void 0 : s.viewedDate) ?? ""
|
|
588
|
-
};
|
|
535
|
+
async clearVisitorUUID() {
|
|
536
|
+
const t = await y("user");
|
|
537
|
+
if (t === null || typeof t != "object" || Array.isArray(t)) return;
|
|
538
|
+
const { visitor_uuid: e, ...r } = t;
|
|
539
|
+
await h("user", r);
|
|
589
540
|
}
|
|
541
|
+
// === UTILITY METHODS ===
|
|
590
542
|
/**
|
|
591
543
|
* Builds a canonical results URL based on the current property slug.
|
|
592
544
|
*
|
|
@@ -625,7 +577,7 @@ class U {
|
|
|
625
577
|
* Hydrates the store with the default scaffold when no data has been persisted yet.
|
|
626
578
|
*/
|
|
627
579
|
async initialize() {
|
|
628
|
-
await this.setState((t) => ({ ...
|
|
580
|
+
await this.setState((t) => ({ ...S, ...t }));
|
|
629
581
|
}
|
|
630
582
|
}
|
|
631
583
|
const C = new U();
|