import type { App, InjectionKey } from "vue"; import { inject } from "vue"; import dataStorePlugin from "./devtools"; import type { HttpClient } from "./http"; import ModelStoreRegistry from "./model-store-registry"; import { AsyncModel, Model } from "./models"; import { AsyncStore, Store } from "./stores"; /** * Symbol-based injection key for the ApplicationStore. Used by kita's own * `useStore` helper. Exported so advanced consumers can write their own * inject() calls without colliding on a string key like `"store"`. */ export const KITA_STORE_KEY: InjectionKey = Symbol( "@ofrusch/kita/application-store", ); export class ApplicationStore { declare client: TClient; // accept any store definitions [key: string]: any; constructor(client: TClient) { this.client = client; } registerStore | typeof AsyncStore>(StoreClass: T) { const storeInstance = new StoreClass(this.client, {}); this[StoreClass.id] = storeInstance; ModelStoreRegistry.registerStore(StoreClass.id, storeInstance); return this; } getStore | AsyncStore>(recordType: string): T { return this[recordType] as T; } install(app: App) { app.provide(KITA_STORE_KEY, this); // Keep globalProperties.store for Vue DevTools and template access compatibility. app.config.globalProperties.store = this; // Register the DevTools plugin. app.use(dataStorePlugin); } } export function createStore ApplicationStore>( appStoreClass: T, client: ConstructorParameters[0], ): { appStore: InstanceType; useStore: () => InstanceType } { const useStore = () => { return inject(KITA_STORE_KEY) as InstanceType; }; const appStore = new appStoreClass(client as never) as InstanceType; return { appStore, useStore }; } export function createAndRegisterStore< T extends new (client: never) => ApplicationStore, >( appStoreClass: T, modelStores: Array | typeof AsyncStore>, client: ConstructorParameters[0], ): { appStore: InstanceType; useStore: () => InstanceType; } { const { appStore, useStore } = createStore(appStoreClass, client); modelStores.forEach((store) => appStore.registerStore(store)); return { appStore, useStore }; }