type DescriptorHolder = { $MODEL_TYPE: 'descriptor'; descriptor: PropertyDescriptor; __type__: T; }; declare class IdentifiersMap { private readonly valuesByTypes; constructor(); get(type: Type, id: Id): NonNullable | null; set(type: Type, id: Id, value: T): void; delete(type: Type, id: Id): void; clear(type: Type): void; } type Dictionary = { [K: string]: T; }; type Constructor = new (...args: any[]) => T; type Awaitable = T | Promise; type ArrayableVariadic = T[] | [T[]]; type Optional = T | null | undefined; type HookCallback = (event: E) => Awaitable; type HooksDefinition = Dictionary>; type HooksRegistrar = { [K in keyof D]?: D[K][]; }; type Hookable = { $hooks: HooksRegistrar | null; }; type Normalizer = (value: T) => U; type FunctionTransform = (value: S) => Awaitable; type ObjectTransform = { serialize(value: T): Awaitable; deserialize(value: S): Awaitable; }; type Transform = FunctionTransform | ObjectTransform; /** * Configuration of a model class. */ type ModelConfig = { /** * Path which is used to query the model. * Defaults to the model's type. */ path?: Optional; /** * Normalize a model/relation path when injecting it inside an action context. */ normalizePath?: Optional>; /** * Normalize a model path when injecting it inside an action context. * Prioritized over `normalizePath`. */ normalizeModelPath?: Optional>; /** * Normalize a relation path when injecting it inside an action context. * Prioritized over `normalizePath`. */ normalizeRelationPath?: Optional>; /** * Normalize an attribute/relation key when (de)serializing for data source. */ normalizeKey?: Optional>; /** * Normalize an attribute key when (de)serializing for data source. * Prioritized over `normalizeKey`. */ normalizeAttributeKey?: Optional>; /** * Normalize a relation key when (de)serializing for data source. * Prioritized over `normalizeKey`. */ normalizeRelationKey?: Optional>; /** * Guess the type for a given relation. */ guessRelationType?: Optional; /** * Compare two values when checking model instance changed values. * * @param nextValue * @param prevValue * * @see {@link changed} */ compareValue?: Optional<((nextValue: unknown, prevValue: unknown) => boolean)>; /** * Clone two values when sync model instances values state. * * @param value * * @see {@link restore} * @see {@link markSynced} */ cloneValue?: Optional<((value: T) => T)>; /** * Dedicated base URL. Will overwrite the default base URL. */ baseURL?: Optional; }; /** * Guess a model's relation related type. */ type ModelRelationTypeGuesser = (model: ModelClass, def: ModelRelation) => Optional; /** * Unique identifier for a model instance. */ type ModelId = string | number; /** * Sync precise configuration for a property (will only do defined action). */ type ModelPropSync = 'retrieve' | 'write'; /** * Normalized part of a property's definition (attribute or relation). */ type ModelPropNormalized = { key: K; }; /** * Raw definition for a model's property (attribute or relation). */ type ModelPropRaw = { /** * Default value for the property. */ default?: T | (() => T) | undefined; /** * Alias of the property (might be used when (de)serializing). */ alias?: string | undefined; /** * Makes the property read-only. */ readOnly?: boolean; /** * Tells if the property should be synced with the data store. */ sync?: boolean | ModelPropSync; }; /** * Raw definition for a model's attribute. */ type ModelAttributeRaw = ModelPropRaw & { /** * Internal type identifier for Foscia's type guards. */ $MODEL_TYPE: 'attribute'; transformer?: Transform | undefined; }; /** * Definition for a model's attribute. */ type ModelAttribute = ModelPropNormalized & ModelAttributeRaw; /** * Available model relation types. */ type ModelRelationType = 'hasOne' | 'hasMany'; /** * Raw definition for a model's relation. */ type ModelRelationRaw = ModelPropRaw & { /** * Internal type identifier for Foscia's type guards. */ $MODEL_TYPE: 'relation'; $RELATION_TYPE: ModelRelationType; type?: string; path?: string; }; /** * Definition for a model's attribute. */ type ModelRelation = ModelPropNormalized & ModelRelationRaw; /** * Extract model's attributes and relations from the whole definition. */ type ModelSchema = { [K in keyof D]: D[K] extends ModelAttribute ? D[K] : D[K] extends ModelRelation ? D[K] : never; }; /** * Model hook callback function. */ type ModelHookCallback = HookCallback; /** * Model's hooks definition. */ type ModelHooksDefinition = { retrieved: ModelHookCallback; creating: ModelHookCallback; created: ModelHookCallback; updating: ModelHookCallback; updated: ModelHookCallback; saving: ModelHookCallback; saved: ModelHookCallback; destroying: ModelHookCallback; destroyed: ModelHookCallback; }; /** * Extendable model class holding the configuration and schema. */ type ModelClass = Hookable & { /** * Internal type identifier for Foscia's type guards. */ readonly $MODEL_TYPE: 'model'; readonly $type: string; readonly $config: ModelConfig; readonly $schema: ModelSchema; configure(rawConfig?: ModelConfig, override?: boolean): void; extends(rawDefinition?: ND & ThisType>): Model>; }; /** * Model class of a dedicated instance. * This type is used to keep instance generic typing across actions enhancements. */ type Model = any> = ModelClass & Constructor; /** * Model instance for a dedicated model class. * This type is used to keep instance generic typing across actions enhancements. */ type ModelClassInstance = { readonly $model: ModelClass; }; /** * Model instance holding state and values. */ type ModelInstance = { /** * Internal type identifier for Foscia's type guards. */ readonly $MODEL_TYPE: 'instance'; readonly $model: ModelClass; id: ModelId; lid: Optional; exists: boolean; $loaded: Dictionary; $values: Partial>>; $raw: any; $original: ModelSnapshot>; } & { [K in keyof D]: D[K] extends ModelAttribute ? T : D[K] extends ModelRelation ? T : D[K] extends DescriptorHolder ? T : D[K]; }; /** * Model class or instance snapshot. */ type ModelSnapshot = { id: Optional; lid: Optional; exists: boolean; $raw: any; $loaded: Dictionary; $values: Partial>; }; type ModelClassOrInstance = ModelClass | ModelClassInstance; /** * Infer the definition from a model class or model instance. */ type ModelInferDefinition = M extends ModelClassOrInstance ? D : M extends {} ? M : never; /** * Infer the schema from a model class or model instance. */ type ModelInferSchema = ModelSchema>; /** * Model class or instance values map (only attributes/relations). */ type ModelValues = { [K in keyof ModelInferSchema]: ModelInferSchema[K] extends ModelAttribute ? T : ModelInferSchema[K] extends ModelRelation ? T : never; }; /** * Model class or instance attributes/relations key. */ type ModelKey = keyof ModelInferSchema; type SerializerI = { serialize(instance: ModelInstance, context: {}): Awaitable; }; type DeserializedData = { instances: I[]; }; type DeserializerI = { deserialize(data: AdapterData, context: {}): Awaitable; }; type ActionHooksDefinition = { preparing: HookCallback; running: HookCallback<{ context: C; runner: Function; }>; success: HookCallback<{ context: C; result: unknown; }>; error: HookCallback<{ context: C; error: unknown; }>; finally: HookCallback<{ context: C; }>; }; type Action = { useContext(): Promise; updateContext(newContext: NewContext): Action; use(enhancer: ContextEnhancer): Action; run(runner: ContextRunner): Promise>; } & Hookable> & ExtendedAction; type ActionParsedExtension = { [K in keyof E]: E[K] extends DescriptorHolder ? E[K] : DescriptorHolder; }; type ExtendedAction = { [K in keyof E]: E[K] extends DescriptorHolder ? T : E[K]; }; type ContextEnhancer = (action: Action) => Awaitable | void>; type ContextRunner = (action: Action) => R; type ConsumeModel = { model: M; }; type AllData = { data: AD; deserialized: DD; instances: I[]; }; type ObjectOptionalIdentifier = { type?: string; id?: ModelId; lid?: ModelId; }; type ObjectNormalizedIdentifier = { type: string; id?: ModelId; lid?: ModelId; }; type ObjectExtractedData = { resources: Optional; }; type ObjectDeserializerConfig = {}; type ObjectSerializerConfig = {}; declare abstract class ObjectDeserializer = ObjectExtractedData, Data extends DeserializedData = DeserializedData> implements DeserializerI { protected static NON_IDENTIFIED_LOCAL_ID: string; constructor(config?: ObjectDeserializerConfig); configure(config?: ObjectDeserializerConfig, override?: boolean): void; deserialize(data: AdapterData, context: {}): Promise; protected abstract makeDeserializedData(instances: ModelInstance[], extractedData: Extract): Promise; protected abstract extractData(data: AdapterData, context: {}): Promise; protected abstract extractOptionalIdentifier(resource: Resource, context: {}, parent?: ModelInstance, relation?: ModelRelation): Promise; protected initInstancesMap(): Promise>>>; protected prepareInstancesMap(extractedData: Extract, instancesMap: IdentifiersMap>, context: {}): Promise; protected deserializeResource(extractedData: Extract, instancesMap: IdentifiersMap>, resource: Resource, context: {}, parent?: ModelInstance, relation?: ModelRelation): Promise>; protected deserializeResourceOnInstance(extractedData: Extract, instancesMap: IdentifiersMap>, resource: Resource, identifier: ObjectNormalizedIdentifier, instance: ModelInstance, context: {}): Promise>; protected extractIdentifier(resource: Resource, context: {}, parent?: ModelInstance, relation?: ModelRelation): Promise; protected extractLocalId(_resource: Resource, identifier: ObjectNormalizedIdentifier, _context: {}): Promise; protected findOrMakeInstance(resource: Resource, identifier: ObjectNormalizedIdentifier, context: {}): Promise>; protected findInstance(_resource: Resource, identifier: ObjectNormalizedIdentifier, context: {}): Promise; protected makeInstance(_resource: Resource, identifier: ObjectNormalizedIdentifier, context: {}): Promise; protected releaseInstance(resource: Resource, instance: ModelInstance, context: {}): Promise; protected extractPropValue(_resource: Resource, _serializedKey: string, _context: {}): Promise; protected extractAttributeValue(_extractedData: Extract, resource: Resource, serializedKey: string, context: {}): Promise; protected extractRelationValue(_extractedData: Extract, resource: Resource, serializedKey: string, context: {}): Promise>; protected hydratePropInInstance(instance: ModelInstance, def: ModelAttribute | ModelRelation, value: unknown): void; protected hydrateAttributeInInstance(instance: ModelInstance, def: ModelAttribute, value: unknown): Promise; protected hydrateRelationInInstance(instance: ModelInstance, def: ModelRelation, value: unknown): Promise; protected serializeAttributeKey(instance: ModelInstance, def: ModelAttribute, _context: {}): Promise; protected serializeRelationKey(instance: ModelInstance, def: ModelRelation, _context: {}): Promise; protected shouldDeserializeAttribute(instance: ModelInstance, def: ModelAttribute, rawValue: unknown, context: {}): Promise; protected shouldDeserializeRelation(instance: ModelInstance, def: ModelRelation, rawValue: unknown, context: {}): Promise; protected shouldDeserializeProp(_instance: ModelInstance, def: ModelAttribute | ModelRelation, rawValue: unknown, _context: {}): Promise; protected deserializeAttributeValue(_instance: ModelInstance, def: ModelAttribute, rawValue: unknown, _context: {}): Promise; protected deserializeRelationValue(extractedData: Extract, instancesMap: IdentifiersMap>, instance: ModelInstance, def: ModelRelation, rawValue: Optional, context: {}): Promise | Resource | ({ readonly $MODEL_TYPE: "instance"; readonly $model: ModelClass; id: ModelId; lid: Optional; exists: boolean; $loaded: Dictionary; $values: Partial>>; $raw: any; $original: ModelSnapshot>; } & { [x: string]: any; })[] | null | undefined>; } declare abstract class ObjectSerializer implements SerializerI { constructor(config?: ObjectSerializerConfig); configure(config?: ObjectSerializerConfig, override?: boolean): void; serialize(instance: ModelInstance, context: {}): Promise; protected abstract makeResource(instance: ModelInstance, context: {}): Promise; protected abstract serializeRelatedInstance(instance: ModelInstance, def: ModelRelation, related: ModelInstance, context: {}): Promise; protected hydratePropInResource(_resource: Data, _serializedKey: string, _serializedValue: unknown): Promise; protected hydrateAttributeInResource(resource: Data, serializedKey: string, serializedValue: unknown): Promise; protected hydrateRelationInResource(resource: Data, serializedKey: string, serializedValue: unknown): Promise; protected serializeAttributeKey(instance: ModelInstance, def: ModelAttribute, _context: {}): Promise; protected serializeRelationKey(instance: ModelInstance, def: ModelRelation, _context: {}): Promise; protected shouldSerializeAttribute(instance: ModelInstance, def: ModelAttribute, rawValue: unknown, context: {}): Promise; protected shouldSerializeRelation(instance: ModelInstance, def: ModelRelation, rawValue: unknown, context: {}): Promise; protected shouldSerializeProp(instance: ModelInstance, def: ModelAttribute | ModelRelation, rawValue: unknown, _context: {}): Promise; protected serializeAttributeValue(_instance: ModelInstance, def: ModelAttribute, rawValue: unknown, _context: {}): Promise; protected serializeRelationValue(instance: ModelInstance, def: ModelRelation, rawValue: unknown, context: {}): Promise; } type OneData = AllData & { instance: I; }; /** * [Select the given JSON:API fieldsets](https://jsonapi.org/format/#fetching-sparse-fieldsets) * for the current context's model. * The new fieldsets will be merged with the previous ones. * * @param fieldset * * @category Enhancers */ declare function fields(...fieldset: ArrayableVariadic>): (action: Action>) => Promise> & { params: { [x: string]: any; }; }, {}>>; declare namespace fields { var extension: ActionParsedExtension<{ fields>(this: Action, ...fieldset: ArrayableVariadic>): Action; }>; } /** * [Select the given JSON:API fieldsets](https://jsonapi.org/format/#fetching-sparse-fieldsets) * for the given model. The new fieldsets will be merged with the previous ones. * * @param model * @param fieldset * * @category Enhancers */ declare function fieldsFor(model: M, ...fieldset: ArrayableVariadic>): (action: Action) => Promise & { params: { [x: string]: any; }; }, {}>>; declare namespace fieldsFor { var extension: ActionParsedExtension<{ fieldsFor>(this: Action, model: M, ...fieldset: ArrayableVariadic>): Action; }>; } /** * [Filter the JSON:API resource](https://jsonapi.org/format/#fetching-filtering) * by the given key and value. * When key is an object, it will spread the object as a filter values map. * The new filter will be merged with the previous ones. * * @param key * @param value * * @category Enhancers */ declare function filterBy(key: string | Dictionary, value?: unknown): (action: Action) => Promise & { params: { [x: string]: any; }; }, {}>>; declare namespace filterBy { var extension: ActionParsedExtension<{ filterBy(this: Action, key: string | Dictionary, value?: unknown): Action; }>; } /** * [Paginate the JSON:API resource](https://jsonapi.org/format/#fetching-pagination) * by the given params. * JSON:API specification on pagination is agnostic, so page params may be * anything used by your implementation. * * @param page * * @category Enhancers */ declare function paginate(page: unknown): (action: Action) => Promise & { params: { [x: string]: any; }; }, {}>>; declare namespace paginate { var extension: ActionParsedExtension<{ paginate(this: Action, page: unknown): Action; }>; } /** * [Sort the JSON:API resource](https://jsonapi.org/format/#fetching-sorting) * by the given key and direction. * The new sort will be merged with the previous ones. * Sorts priority are kept. * * @param key * @param direction * * @category Enhancers */ declare function sortBy(key: string | string[], direction?: 'asc' | 'desc'): (action: Action) => Promise & { params: { [x: string]: any; }; }, {}>>; declare namespace sortBy { var extension: ActionParsedExtension<{ sortBy(this: Action, key: string | string[], direction?: "asc" | "desc" | undefined): Action; }>; } /** * Shortcut for the {@link sortBy} function with a desc direction. * * @param key * * @category Enhancers */ declare function sortByDesc(key: string | string[]): (action: Action) => Promise & { params: { [x: string]: any; }; }, {}>>; declare namespace sortByDesc { var extension: ActionParsedExtension<{ sortByDesc(this: Action, key: string | string[]): Action; }>; } /** * @see [JSON:API specification](https://jsonapi.org/format/#document-links) */ type JsonApiLink = { href: string; meta?: JsonApiMeta; } | string; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-links) */ type JsonApiLinks = Dictionary; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-meta) */ type JsonApiMeta = Dictionary; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-identifier-objects) */ type JsonApiResourceIdentifier = { type: string; id: string; lid?: string; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-object-attributes) */ type JsonApiAttributes = Dictionary; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-object-relationships) */ type JsonApiRelationship = { data?: JsonApiResourceIdentifier[] | JsonApiResourceIdentifier | null; links?: JsonApiLinks; meta?: JsonApiMeta; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-object-relationships) */ type JsonApiRelationships = Dictionary; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-objects) */ type JsonApiAbstractResource = { type: string; lid?: string; attributes?: JsonApiAttributes; relationships?: JsonApiRelationships; links?: JsonApiLinks; meta?: JsonApiMeta; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-objects) */ type JsonApiResource = JsonApiAbstractResource & { id: string; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-resource-objects) */ type JsonApiNewResource = JsonApiAbstractResource & { id?: string; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#error-objects) */ type JsonApiError = { status?: string; code?: string; title?: string; detail?: string; source?: { pointer?: string; parameter?: string; header?: string; }; meta?: JsonApiMeta; }; /** * @see [JSON:API specification](https://jsonapi.org/format/#document-top-level) */ type JsonApiDocument = { data?: JsonApiResource[] | JsonApiResource | JsonApiNewResource | null; included?: JsonApiResource[]; links?: JsonApiLinks; meta?: JsonApiMeta; errors?: JsonApiError[]; jsonapi?: { version?: string; meta?: JsonApiMeta; }; }; /** * Extracted data from a JSON:API backend Response object. */ type JsonApiExtractedData = ObjectExtractedData & { included: IdentifiersMap; document: JsonApiDocument; response: Response; }; /** * Deserialized data from a JSON:API backend Response object. */ type JsonApiDeserializedData = DeserializedData & { document: JsonApiDocument; response: Response; }; /** * Deserializer implementation for JSON:API. */ declare class JsonApiDeserializer extends ObjectDeserializer { /** * @inheritDoc */ protected makeDeserializedData(instances: ModelInstance[], extractedData: JsonApiExtractedData): Promise<{ instances: ModelInstance[]; document: JsonApiDocument; response: Response; }>; /** * @inheritDoc */ protected extractData(response: Response): Promise<{ resources: JsonApiResource | JsonApiNewResource | JsonApiResource[] | null | undefined; included: IdentifiersMap; document: JsonApiDocument; response: Response; }>; /** * @inheritDoc */ protected extractOptionalIdentifier(resource: JsonApiNewResource): Promise; /** * @inheritDoc */ protected extractAttributeValue(_extractedData: JsonApiExtractedData, resource: JsonApiNewResource, serializedKey: string): Promise; /** * @inheritDoc */ protected extractRelationValue(extractedData: JsonApiExtractedData, resource: JsonApiNewResource, serializedKey: string): Promise; /** * Extract an included JSON:API resource from extracted data. * * @param extractedData * @param identifier */ protected extractIncluded(extractedData: JsonApiExtractedData, identifier: JsonApiResourceIdentifier): JsonApiNewResource; } /** * Append the JSON:API document object to data object. * Use it as the parameter of `allUsing` and `oneUsing` runners. * * @param data */ declare function usingDocument, D extends OneData | AllData>(data: D): D & { document: JsonApiDocument; }; /** * Serializer implementation for JSON:API. */ declare class JsonApiSerializer extends ObjectSerializer { /** * @inheritDoc */ protected makeResource(instance: ModelInstance): Promise<{ data: { attributes: {}; relationships: {}; type: string; id: string | undefined; lid: string | undefined; }; }>; /** * @inheritDoc */ protected hydrateAttributeInResource(resource: JsonApiDocument, serializedKey: string, serializedValue: unknown): Promise; /** * @inheritDoc */ protected hydrateRelationInResource(resource: JsonApiDocument, serializedKey: string, serializedValue: unknown): Promise; /** * @inheritDoc */ protected serializeRelatedInstance(_instance: ModelInstance, _def: ModelRelation, related: ModelInstance): Promise<{ type: string; id: string | undefined; lid: string | undefined; }>; /** * Serialize an instance unique identifier object. * * @param instance */ protected serializeInstanceIdentifier(instance: ModelInstance): { type: string; id: string | undefined; lid: string | undefined; }; /** * Serialize an instance's ID. * * @param id */ protected serializeId(id?: Optional): string | undefined; } export { JsonApiAbstractResource, JsonApiAttributes, JsonApiDeserializer, JsonApiDocument, JsonApiError, JsonApiLink, JsonApiLinks, JsonApiMeta, JsonApiNewResource, JsonApiRelationship, JsonApiRelationships, JsonApiResource, JsonApiResourceIdentifier, JsonApiSerializer, fields, fieldsFor, filterBy, paginate, sortBy, sortByDesc, usingDocument };