@flumens/models 0.32.1 → 0.33.0

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/README.md CHANGED
@@ -1 +1,124 @@
1
1
  # @flumens/models
2
+
3
+ Indicia-specific stores live in `src/Stores/Indicia/`: `Taxa.ts`,
4
+ `TaxonLists.ts`, `Groups.ts`, and `Locations.ts`. Their public exports remain
5
+ `TaxaStore`, `TaxonListsStore`, `GroupsStore`, and `LocationsStore`.
6
+
7
+ ## Offline species search
8
+
9
+ Create stores against the app's existing SQLite database. No app singleton,
10
+ report URL, token, country, or species-group settings are required.
11
+
12
+ ```ts
13
+ import { eq } from 'drizzle-orm';
14
+ import {
15
+ SQLiteDatabase,
16
+ TaxonListsStore,
17
+ TaxaStore,
18
+ GroupsStore,
19
+ } from '@flumens/models';
20
+
21
+ const db = new SQLiteDatabase({ name: 'my-app', web: true });
22
+ const taxonListsStore = new TaxonListsStore({ db });
23
+ const taxaStore = new TaxaStore({ db, taxonListsStore });
24
+ await db.init();
25
+
26
+ // Save the list model/metadata before importing its species (foreign key).
27
+ // Fetch and validate your own report, then map its rows to the taxa schema.
28
+ await taxaStore.replaceSpecies(listCid, species);
29
+
30
+ const results = await taxaStore.search({
31
+ searchPhrase: 'red admiral',
32
+ language: 'eng',
33
+ maxResults: 20,
34
+ where: table => eq(table.list_cid, listCid),
35
+ });
36
+ const listSpecies = await taxaStore.fetchSpecies(listCid, 'eng');
37
+ const commonName = await taxaStore.getCommonNameById(preferredId, 'eng');
38
+ ```
39
+
40
+ Taxa use warehouse IDs, a list CID, taxon-group ID, language code (`lat` for
41
+ scientific names), taxon name, optional preferred/parent IDs and external key,
42
+ and a JSON `data` object for app-specific attributes. `replaceSpecies` rows use
43
+ camelCase keys: `id`, `taxonGroupId`, `preferredTaxaTaxonListId`, `parentId`,
44
+ `externalKey`, `languageIso`, `taxon`, and `data`. The list CID is supplied
45
+ separately. Database columns remain snake_case, and keys inside `data` are
46
+ preserved unchanged. The composite primary key
47
+ is `(id, list_cid)`. `replaceSpecies` replaces only the selected list, in
48
+ batches inside a transaction; failed inserts roll back the replacement.
49
+ Concurrent replacements sharing a database are serialized, including after a
50
+ failed import. Call it outside any other transaction on the same database
51
+ connection.
52
+
53
+ Search includes common and scientific names, five-character genus/species
54
+ shortcuts, optional SQL filters, and a configurable result limit (default 20).
55
+ Common names fill the limit first. Results are sorted by match position.
56
+ `fetchSpecies` preserves the common-name-only list behaviour: taxa without a
57
+ name in the requested language are omitted.
58
+
59
+ ### Optional group relationships
60
+
61
+ ```ts
62
+ const groups = new GroupsStore({ db }); // no relationship tables
63
+
64
+ const linkedGroups = new GroupsStore({
65
+ db,
66
+ locationsStore, // optional, independently of taxon lists
67
+ taxonListsStore, // optional, independently of locations
68
+ });
69
+ ```
70
+
71
+ Only configured join tables are created. `findAll` always returns
72
+ `locationCids` and `taxonListCids` arrays, empty for disabled relationships.
73
+ `groupsLocations` and `groupsLists` are undefined when disabled; check them
74
+ before writing links. Supplied stores must use the same database.
75
+
76
+ Default table names preserve existing eBMS databases: `taxon_lists`, `taxa`,
77
+ `groups`, `groups_locations`, and `groups_taxon_lists`. Store names can be
78
+ overridden; group join-table names follow the group store name. Applications
79
+ remain responsible for model hydration, link writes, remote reports, and UI.
80
+
81
+ ### Locations with optional taxon lists
82
+
83
+ ```ts
84
+ import { LocationsStore } from '@flumens/models';
85
+
86
+ const locations = new LocationsStore({ db }); // plain locations
87
+ const linkedLocations = new LocationsStore({ db, taxonListsStore });
88
+ ```
89
+
90
+ Without `taxonListsStore`, no relationship table is created or queried.
91
+ `findAll` returns `taxonListCids: []`, and `locationLists` is undefined.
92
+ With linking enabled, `locationLists` exposes the join store for link writes.
93
+ Both stores must use the same database.
94
+
95
+ Defaults preserve the existing `locations` and `locations_lists` tables,
96
+ including their columns, composite relationship key, and cascading foreign
97
+ keys. Using this store requires no migration when the app already uses that
98
+ schema. A different existing storage format still needs its own migration.
99
+ A custom `name` changes the location table name and uses `<name>_lists` for links.
100
+ App-specific location models, remote fetching, and GPS remain in the app.
101
+
102
+ ### Taxon-list models
103
+
104
+ `IndiciaTaxonList` provides metadata persistence, optional group/location links,
105
+ list size, and local species queries. Inject `store: taxonListsStore` and
106
+ `taxaStore` alongside the model's `cid` and `data`.
107
+
108
+ Extend `IndiciaTaxonList<MyListData>` for app-specific metadata. Its
109
+ `groupCids` and `locationCids` default to empty arrays. Optional link methods
110
+ accept models exposing `cid`, `taxonListCids`, and `linkTaxonList`; the linked
111
+ model is responsible for persisting the relationship.
112
+
113
+ Use `skipStore: true` for an ephemeral list and `save(true)` to install it
114
+ into the injected metadata store. Apps own DTO mapping and stable list CIDs.
115
+ The shared class does not implement `fetchRemoteSpecies` or configure remote
116
+ reports or authentication; eBMS keeps those in its subclass.
117
+
118
+ ### Local development
119
+
120
+ For local development, eBMS can link this package using
121
+ `file:../@flumens/apps/packages/models` instead of its published version.
122
+ After changing library source, run `npm run build` here to refresh the linked
123
+ package's exports and declarations. Use the consuming app's Drizzle instance
124
+ in bundler aliases when linking to avoid duplicate Drizzle module instances.
@@ -7,9 +7,9 @@ export declare const dtoSchema: z.ZodObject<{
7
7
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
8
  groupType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
9
  joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
10
+ I: "I";
10
11
  R: "R";
11
12
  P: "P";
12
- I: "I";
13
13
  A: "A";
14
14
  }>>>;
15
15
  websiteId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -0,0 +1,35 @@
1
+ import { SQL } from 'drizzle-orm';
2
+ import Model, { type Data as ModelData, type Options as ModelOptions } from '../Model';
3
+ import type TaxaStore from '../Stores/Indicia/Taxa';
4
+ import type { SearchResult } from '../Stores/Indicia/Taxa';
5
+ export type Data = ModelData & {
6
+ title: string;
7
+ description?: string;
8
+ size?: number;
9
+ };
10
+ export type Options<T extends Data = Data> = ModelOptions<T> & {
11
+ taxaStore: Pick<TaxaStore, 'fetchSpecies'>;
12
+ skipStore?: boolean;
13
+ groupCids?: string[];
14
+ locationCids?: string[];
15
+ };
16
+ type LinkedModel<T extends Data> = {
17
+ cid: string;
18
+ taxonListCids: readonly string[];
19
+ linkTaxonList(list: TaxonList<T>): Promise<void>;
20
+ };
21
+ export default class TaxonList<T extends Data = Data> extends Model<T> {
22
+ private readonly defaultStore?;
23
+ private readonly taxaStore;
24
+ private _groupCids;
25
+ private _locationCids;
26
+ constructor({ store, taxaStore, skipStore, groupCids, locationCids, ...options }: Options<T>);
27
+ get groupCids(): string[];
28
+ get locationCids(): string[];
29
+ linkGroup(group: LinkedModel<T>): Promise<void>;
30
+ linkLocation(location: LinkedModel<T>): Promise<void>;
31
+ getSize(): number;
32
+ save(force?: boolean): Promise<void>;
33
+ fetchSpecies(language: string, customWhere?: (table: TaxaStore['table']) => SQL): Promise<SearchResult[]>;
34
+ }
35
+ export {};
@@ -0,0 +1 @@
1
+ import{__rest as i,__awaiter as t}from"tslib";import s from"../Model.mjs";class o extends s{constructor(t){var{store:s,taxaStore:o,skipStore:e,groupCids:r,locationCids:d}=t,n=i(t,["store","taxaStore","skipStore","groupCids","locationCids"]);super(Object.assign(Object.assign({},n),{store:e?void 0:s})),this.defaultStore=s,this.taxaStore=o,this._groupCids=r||[],this._locationCids=d||[]}get groupCids(){return this._groupCids}get locationCids(){return this._locationCids}linkGroup(i){return t(this,void 0,void 0,(function*(){this._groupCids.includes(i.cid)||this._groupCids.push(i.cid),i.taxonListCids.includes(this.cid)||(yield i.linkTaxonList(this))}))}linkLocation(i){return t(this,void 0,void 0,(function*(){this._locationCids.includes(i.cid)||this._locationCids.push(i.cid),i.taxonListCids.includes(this.cid)||(yield i.linkTaxonList(this))}))}getSize(){return this.data.size||0}save(){const i=Object.create(null,{save:{get:()=>super.save}});return t(this,arguments,void 0,(function*(t=!1){t&&!this.store&&(this.store=this.defaultStore),yield i.save.call(this)}))}fetchSpecies(i,t){return this.taxaStore.fetchSpecies(this.cid,i,t)}}export{o as default};
@@ -0,0 +1,30 @@
1
+ import Store, { type SelectQueryFn, type SQLiteStoreOptions, type ColumnMap, defaultCols } from '../SQLiteStore';
2
+ declare const groupLocationsColumns: (groups: Store, locations: Store) => {
3
+ groupCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"group_cid", [string, ...string[]], number | undefined>>;
4
+ locationCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"location_cid", [string, ...string[]], number | undefined>>;
5
+ };
6
+ declare const groupTaxonListsColumns: (groups: Store, taxonLists: Store) => {
7
+ groupCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"group_cid", [string, ...string[]], number | undefined>>;
8
+ taxonListCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"taxon_list_cid", [string, ...string[]], number | undefined>>;
9
+ };
10
+ type DefaultColumns = ReturnType<typeof defaultCols>;
11
+ export default class GroupsStore extends Store<DefaultColumns, ColumnMap<DefaultColumns>, string> {
12
+ groupsLocations?: Store<ReturnType<typeof groupLocationsColumns>>;
13
+ groupsLists?: Store<ReturnType<typeof groupTaxonListsColumns>>;
14
+ constructor({ locationsStore, taxonListsStore, name, ...options }: Omit<SQLiteStoreOptions<DefaultColumns>, 'name'> & {
15
+ name?: string;
16
+ locationsStore?: Store;
17
+ taxonListsStore?: Store;
18
+ });
19
+ findAll(filter?: SelectQueryFn): Promise<{
20
+ data: any;
21
+ locationCids: string[];
22
+ taxonListCids: string[];
23
+ id: string | null;
24
+ cid: string;
25
+ createdAt: number;
26
+ updatedAt: number;
27
+ syncedAt: number | null;
28
+ }[]>;
29
+ }
30
+ export {};
@@ -0,0 +1 @@
1
+ import{__rest as t,__awaiter as i}from"tslib";import{getTableColumns as o,sql as s}from"drizzle-orm";import{primaryKey as e,QueryBuilder as a,text as n}from"drizzle-orm/sqlite-core";import{getCamelCaseObj as r}from"@flumens/utils";import l from"../SQLiteStore.mjs";const d=(t,i)=>({groupCid:n("group_cid").notNull().references((()=>t.table.cid),{onDelete:"cascade"}),taxonListCid:n("taxon_list_cid").notNull().references((()=>i.table.cid),{onDelete:"cascade"})});class c extends l{constructor(i){var o,s,{locationsStore:a,taxonListsStore:r,name:c="groups"}=i,u=t(i,["locationsStore","taxonListsStore","name"]);super(Object.assign(Object.assign({},u),{name:c})),a&&(this.groupsLocations=new l({name:`${c}_locations`,db:this.db,columns:(o=this,s=a,{groupCid:n("group_cid").notNull().references((()=>o.table.cid),{onDelete:"cascade"}),locationCid:n("location_cid").notNull().references((()=>s.table.cid),{onDelete:"cascade"})}),extraConf:t=>({primaryKey:e({columns:[t.locationCid,t.groupCid]})})})),r&&(this.groupsLists=new l({name:`${c}_taxon_lists`,db:this.db,columns:d(this,r),extraConf:t=>({primaryKey:e({columns:[t.groupCid,t.taxonListCid]})})}))}findAll(e){return i(this,void 0,void 0,(function*(){var i,n,l,d;yield Promise.all([this.ready,null===(i=this.groupsLocations)||void 0===i?void 0:i.ready,null===(n=this.groupsLists)||void 0===n?void 0:n.ready]);const c=null===(l=this.groupsLocations)||void 0===l?void 0:l.table,u=null===(d=this.groupsLists)||void 0===d?void 0:d.table,p=(new a).select(Object.assign(Object.assign({},o(this.table)),{locationCids:c?s`(SELECT json_group_array(${c.locationCid}) FROM ${c} WHERE ${c.groupCid} = ${this.table.cid})`.as("locationCids"):s`'[]'`.as("locationCids"),taxonListCids:u?s`(SELECT json_group_array(${u.taxonListCid}) FROM ${u} WHERE ${u.groupCid} = ${this.table.cid})`.as("taxonListCids"):s`'[]'`.as("taxonListCids")})).from(this.table),m=e?e(p):p,C=yield this.db.query(m.toSQL()),g=t=>JSON.parse(t).filter((t=>null!==t));return C.map((i=>{var{data:o,locationCids:s,taxonListCids:e}=i,a=t(i,["data","locationCids","taxonListCids"]);return Object.assign(Object.assign({},r(a)),{data:JSON.parse(String(o)),locationCids:g(s),taxonListCids:g(e)})}))}))}}export{c as default};
@@ -0,0 +1,23 @@
1
+ import Store, { type SelectQueryFn, type SQLiteStoreOptions, type ColumnMap, defaultCols } from '../SQLiteStore';
2
+ declare const locationListColumns: (locations: Store, taxonLists: Store) => {
3
+ locationCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"location_cid", [string, ...string[]], number | undefined>>;
4
+ taxonListCid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"taxon_list_cid", [string, ...string[]], number | undefined>>;
5
+ };
6
+ type DefaultColumns = ReturnType<typeof defaultCols>;
7
+ export default class LocationsStore extends Store<DefaultColumns, ColumnMap<DefaultColumns>, string> {
8
+ locationLists?: Store<ReturnType<typeof locationListColumns>>;
9
+ constructor({ taxonListsStore, name, ...options }: Omit<SQLiteStoreOptions<DefaultColumns>, 'name'> & {
10
+ name?: string;
11
+ taxonListsStore?: Store;
12
+ });
13
+ findAll(filter?: SelectQueryFn): Promise<{
14
+ data: any;
15
+ taxonListCids: string[];
16
+ id: string | null;
17
+ cid: string;
18
+ createdAt: number;
19
+ updatedAt: number;
20
+ syncedAt: number | null;
21
+ }[]>;
22
+ }
23
+ export {};
@@ -0,0 +1 @@
1
+ import{__rest as t,__awaiter as i}from"tslib";import{getTableColumns as s,sql as o}from"drizzle-orm";import{primaryKey as a,QueryBuilder as e,text as n}from"drizzle-orm/sqlite-core";import{getCamelCaseObj as r}from"@flumens/utils";import l from"../SQLiteStore.mjs";class d extends l{constructor(i){var s,o,{taxonListsStore:e,name:r="locations"}=i,d=t(i,["taxonListsStore","name"]);if(super(Object.assign(Object.assign({},d),{name:r})),e){const t=(s=this,o=e,{locationCid:n("location_cid").notNull().references((()=>s.table.cid),{onDelete:"cascade"}),taxonListCid:n("taxon_list_cid").notNull().references((()=>o.table.cid),{onDelete:"cascade"})});this.locationLists=new l({name:`${r}_lists`,db:this.db,columns:t,extraConf:t=>({primaryKey:a({columns:[t.locationCid,t.taxonListCid]})})})}}findAll(a){return i(this,void 0,void 0,(function*(){var i,n;yield Promise.all([this.ready,null===(i=this.locationLists)||void 0===i?void 0:i.ready]);const l=null===(n=this.locationLists)||void 0===n?void 0:n.table,d=(new e).select(Object.assign(Object.assign({},s(this.table)),{taxonListCids:l?o`(SELECT json_group_array(${l.taxonListCid}) FROM ${l} WHERE ${l.locationCid} = ${this.table.cid})`.as("taxonListCids"):o`'[]'`.as("taxonListCids")})).from(this.table),c=a?a(d):d,m=yield this.db.query(c.toSQL()),u=t=>JSON.parse(t).filter((t=>null!==t));return m.map((i=>{var{data:s,taxonListCids:o}=i,a=t(i,["data","taxonListCids"]);return Object.assign(Object.assign({},r(a)),{data:JSON.parse(String(s)),taxonListCids:u(o)})}))}))}}export{d as default};
@@ -0,0 +1,83 @@
1
+ import { SQL } from 'drizzle-orm';
2
+ import type { CamelizeKeys } from '@flumens/utils';
3
+ import SQLiteStore, { type SQLiteStoreOptions } from '../SQLiteStore';
4
+ export declare const taxonColumns: (taxonListsStore: SQLiteStore) => {
5
+ /**
6
+ * Warehouse taxa_taxon_list_id of the taxon. Not a unique ID on its own as multiple lists can contain the same taxon.
7
+ */
8
+ readonly id: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"">>;
9
+ /**
10
+ * Identifies the taxon list which this searchable name is from.
11
+ */
12
+ readonly list_cid: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>>;
13
+ /**
14
+ * Informal taxon group ID.
15
+ */
16
+ readonly taxon_group_id: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"">>;
17
+ /**
18
+ * ID of the preferred version of this term.
19
+ */
20
+ readonly preferred_taxa_taxon_list_id: import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"">;
21
+ /**
22
+ * Identifies the parent of the taxon in the hierarchy, if one exists.
23
+ */
24
+ readonly parent_id: import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"">;
25
+ /**
26
+ * Searchable identifier for the taxon. Includes taxon formal and vernacular names, simplified versions of these for searching and codes, abbreviations or other shortcuts used to lookup taxa.
27
+ */
28
+ readonly external_key: import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>;
29
+ /**
30
+ * The language associated with the search term, or null if not language specific.
31
+ */
32
+ readonly language_iso: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>>;
33
+ /**
34
+ * Provides the preferred taxon name for a taxon that has been looked up.
35
+ */
36
+ readonly taxon: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>>;
37
+ /**
38
+ * For storing additional taxon attributes, like country presence.
39
+ */
40
+ readonly data: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
41
+ name: string;
42
+ dataType: "custom";
43
+ columnType: "SQLiteCustomColumn";
44
+ data: Record<string, unknown>;
45
+ driverParam: string;
46
+ enumValues: undefined;
47
+ }>>>;
48
+ };
49
+ export type SpeciesColumns = TaxaStore['table']['$inferSelect'];
50
+ export type SearchResult = {
51
+ foundInName: 'scientificName' | 'commonName';
52
+ warehouseId: number;
53
+ scientificName: string;
54
+ taxonGroupId: number;
55
+ commonName?: string;
56
+ preferredId?: number;
57
+ };
58
+ export type SearchOptions = {
59
+ searchPhrase: string;
60
+ language: string;
61
+ maxResults?: number;
62
+ where?: (table: TaxaStore['table']) => SQL;
63
+ };
64
+ type TaxonColumns = ReturnType<typeof taxonColumns>;
65
+ export default class TaxaStore extends SQLiteStore<TaxonColumns> {
66
+ private static replacements;
67
+ constructor({ taxonListsStore, name, ...options }: Omit<SQLiteStoreOptions<TaxonColumns>, 'columns' | 'extraConf' | 'name'> & {
68
+ name?: string;
69
+ taxonListsStore: SQLiteStore;
70
+ });
71
+ search({ searchPhrase, language, where, maxResults, }: SearchOptions): Promise<SearchResult[]>;
72
+ private searchCommonNames;
73
+ private searchSciNames;
74
+ private normaliseSearchPhrase;
75
+ getCommonNameById(taxaTaxonListId: string | number, language?: string): Promise<string | null>;
76
+ replaceSpecies(listCid: string, species: CamelizeKeys<Omit<typeof this.table.$inferInsert, 'list_cid'>>[]): Promise<void>;
77
+ /**
78
+ * Fetches all species belonging to this list from the local species store.
79
+ * Optionally accepts an additional where clause to further filter results.
80
+ */
81
+ fetchSpecies(listCid: string, language: string, customWhere?: (table: TaxaStore['table']) => SQL): Promise<SearchResult[]>;
82
+ }
83
+ export {};
@@ -0,0 +1 @@
1
+ import{__rest as e,__awaiter as t}from"tslib";import{sql as a,getTableColumns as i,and as o,eq as n,or as r}from"drizzle-orm";import{index as s,primaryKey as d,alias as l,QueryBuilder as c,SQLiteSyncDialect as m,SQLiteInsertBuilder as u,text as _,integer as h}from"drizzle-orm/sqlite-core";import x,{conflictUpdateAllExcept as p,jsonb as f}from"../SQLiteStore.mjs";const g=e=>({id:h().notNull(),list_cid:_().references((()=>e.table.cid),{onDelete:"cascade"}).notNull(),taxon_group_id:h().notNull(),preferred_taxa_taxon_list_id:h(),parent_id:h(),external_key:_(),language_iso:_().notNull(),taxon:_().notNull(),data:f("data").notNull().default({})});class y extends x{constructor(t){var{taxonListsStore:a,name:i="taxa"}=t,o=e(t,["taxonListsStore","name"]);super(Object.assign(Object.assign({},o),{name:i,columns:g(a),extraConf:e=>({primaryKey:d({columns:[e.id,e.list_cid]}),taxonIndex:s("taxa"===i?"taxon_idx":`${i}_taxon_idx`).on(e.taxon),languageTaxonGroupIndex:s("taxa"===i?"language_iso_taxon_group_id_idx":`${i}_language_iso_taxon_group_id_idx`).on(e.language_iso,e.taxon_group_id)})}))}search(e){return t(this,arguments,void 0,(function*({searchPhrase:e,language:t,where:a,maxResults:i=20}){yield this.ready;const o=[];if(!e||i<=0)return o;if(!t)return[];const n=e.toLowerCase(),r=yield this.searchCommonNames(n,t,a,i);if(o.push(...r),o.length<i){const e=yield this.searchSciNames(n,t,a,i-o.length);o.push(...e)}return o.sort(((e,t)=>{var a,i;const o=null===(a=e[e.foundInName])||void 0===a?void 0:a.toLowerCase().indexOf(n),r=null===(i=t[t.foundInName])||void 0===i?void 0:i.toLowerCase().indexOf(n);return-1===o&&-1===r?0:-1===o?1:-1===r?-1:o-r})),o}))}searchCommonNames(e,r,s){return t(this,arguments,void 0,(function*(e,t,r,s=20){const{table:d}=this,m=l(d,"preferred"),u=r?r(d):a`1`,_=this.normaliseSearchPhrase(e),h=(new c).select(Object.assign(Object.assign({},i(d)),{scientificName:a`${m.taxon} as scientificName`})).from(d).leftJoin(m,o(n(m.id,d.preferred_taxa_taxon_list_id),n(m.list_cid,d.list_cid))).where(o(n(d.language_iso,t),a`${d.taxon} LIKE ${`%${_}%`} ESCAPE '!'`,u)).groupBy(d.id).limit(s);return(yield this.db.query(h.toSQL())).map((e=>({foundInName:"commonName",warehouseId:e.id,commonName:e.taxon,scientificName:e.scientificName,taxonGroupId:e.taxon_group_id,preferredId:e.preferred_taxa_taxon_list_id})))}))}searchSciNames(e,s,d){return t(this,arguments,void 0,(function*(e,t,s,d=20){const{table:m}=this,u=l(m,"synonym"),_=s?s(m):a`1`,h=this.normaliseSearchPhrase(e),x=[`%${h}%`];if(5===e.length){const e=h.substr(0,2),t=h.substr(2,4);x.push(`${e}% ${t}%`)}const p=(new c).select(Object.assign(Object.assign({},i(m)),{commonName:a`${u.taxon} as commonName`})).from(m).leftJoin(u,o(n(u.preferred_taxa_taxon_list_id,m.id),n(u.list_cid,m.list_cid),n(u.language_iso,t))).where(o(n(m.language_iso,"lat"),r(...x.map((e=>a`${m.taxon} LIKE ${e} ESCAPE '!'`))),_)).groupBy(m.id).limit(d);return(yield this.db.query(p.toSQL())).map((e=>({foundInName:"scientificName",warehouseId:e.id,scientificName:e.taxon,commonName:e.commonName,taxonGroupId:e.taxon_group_id,preferredId:e.preferred_taxa_taxon_list_id})))}))}normaliseSearchPhrase(e){return e.replace(/[!%_]/g,"!$&").replace(/[-.*+?^${}()|[\]\\]/g,"_").replace(/\s+/g,"%")}getCommonNameById(e){return t(this,arguments,void 0,(function*(e,t="eng"){yield this.ready;const a=(new c).select({taxon:this.table.taxon}).from(this.table).where(o(n(this.table.preferred_taxa_taxon_list_id,parseInt(`${e}`,10)),n(this.table.language_iso,t))).limit(1),[i]=yield this.db.query(a.toSQL());return(null==i?void 0:i.taxon)||null}))}replaceSpecies(e,i){return t(this,void 0,void 0,(function*(){const o=(y.replacements.get(this.db)||Promise.resolve()).catch((()=>{})).then((()=>t(this,void 0,void 0,(function*(){yield this.ready;const t=new m;yield this.db.query({sql:"BEGIN TRANSACTION"});try{yield this.db.query(t.sqlToQuery(a`DELETE FROM ${this.table} WHERE ${this.table.list_cid} = ${e}`));for(let a=0;a<i.length;a+=500){const o=i.slice(a,a+500),n=new u(this.table,{},t).values(o.map((t=>({id:t.id,list_cid:e,taxon_group_id:t.taxonGroupId,preferred_taxa_taxon_list_id:t.preferredTaxaTaxonListId,parent_id:t.parentId,external_key:t.externalKey,language_iso:t.languageIso,taxon:t.taxon,data:t.data})))).onConflictDoUpdate({target:[this.table.id,this.table.list_cid],set:p(this.table,[])});yield this.db.query(n.toSQL())}yield this.db.query({sql:"COMMIT"})}catch(e){throw yield this.db.query({sql:"ROLLBACK"}),e}}))));return y.replacements.set(this.db,o),o}))}fetchSpecies(e,r,s){return t(this,void 0,void 0,(function*(){yield this.ready;const{table:t}=this,d=s?s(t):a`1`,m=n(t.list_cid,e),u=l(t,"preferred"),_=(new c).select(Object.assign(Object.assign({},i(t)),{commonName:a`${u.taxon} as commonName`})).from(t).leftJoin(u,o(n(u.preferred_taxa_taxon_list_id,t.id),n(u.list_cid,t.list_cid),n(u.language_iso,r))).where(o(n(t.language_iso,"lat"),m,d)).groupBy(t.id).orderBy(t.taxon);return(yield this.db.query(_.toSQL())).map((e=>({foundInName:"commonName",warehouseId:e.id,scientificName:e.taxon,commonName:e.commonName,taxonGroupId:e.taxon_group_id,preferredId:e.preferred_taxa_taxon_list_id}))).filter((e=>!!e.commonName))}))}}y.replacements=new WeakMap;export{y as default,g as taxonColumns};
@@ -0,0 +1,6 @@
1
+ import SQLiteStore, { type SQLiteStoreOptions } from '../SQLiteStore';
2
+ export default class TaxonListsStore extends SQLiteStore {
3
+ constructor({ name, ...options }: Omit<SQLiteStoreOptions, 'name'> & {
4
+ name?: string;
5
+ });
6
+ }
@@ -0,0 +1 @@
1
+ import{__rest as s}from"tslib";import t from"../SQLiteStore.mjs";class e extends t{constructor(t){var{name:e="taxon_lists"}=t,a=s(t,["name"]);super(Object.assign(Object.assign({},a),{name:e}))}}export{e as default};
@@ -2,3 +2,7 @@ export { default as SQLiteDatabase } from './SQLiteDatabase';
2
2
  export { default as LocalForageStore } from './LocalForageStore';
3
3
  export { default as SQLiteStore } from './SQLiteStore';
4
4
  export { default as IStore } from './Store';
5
+ export { default as TaxaStore } from './Indicia/Taxa';
6
+ export { default as TaxonListsStore } from './Indicia/TaxonLists';
7
+ export { default as GroupsStore } from './Indicia/Groups';
8
+ export { default as LocationsStore } from './Indicia/Locations';
package/dist/Stores.mjs CHANGED
@@ -1 +1 @@
1
- export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";
1
+ export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";export{default as TaxaStore}from"./Stores/Indicia/Taxa.mjs";export{default as TaxonListsStore}from"./Stores/Indicia/TaxonLists.mjs";export{default as GroupsStore}from"./Stores/Indicia/Groups.mjs";export{default as LocationsStore}from"./Stores/Indicia/Locations.mjs";
package/dist/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  export { default as DrupalUserModel, DrupalUserError, DrupalUserErrorCode, } from './Drupal/User';
2
2
  export * from './Stores';
3
+ export type { SearchOptions, SearchResult, SpeciesColumns, } from './Stores/Indicia/Taxa';
3
4
  export { default as Model } from './Model';
4
5
  export { default as Collection } from './Collection';
5
6
  export { default as IndiciaMedia } from './Indicia/Media';
7
+ export { default as IndiciaTaxonList } from './Indicia/TaxonList';
8
+ export type { Data as TaxonListData, Options as TaxonListOptions, } from './Indicia/TaxonList';
6
9
  export { default as ElasticIndiciaOccurrence } from './Indicia/ElasticOccurrence';
7
10
  export { default as ElasticIndiciaSample } from './Indicia/ElasticSample';
8
11
  export { default as IndiciaOccurrence } from './Indicia/Occurrence';
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{DrupalUserError,DrupalUserErrorCode,default as DrupalUserModel}from"./Drupal/User.mjs";export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";export{default as Model}from"./Model.mjs";export{default as Collection}from"./Collection.mjs";export{default as IndiciaMedia}from"./Indicia/Media.mjs";export{default as IndiciaOccurrence}from"./Indicia/Occurrence.mjs";export{default as IndiciaSample}from"./Indicia/Sample.mjs";export{default as IndiciaGroup,dtoSchema as groupDtoSchema}from"./Indicia/Group.mjs";export{default as IndiciaLocation,LocationType,dtoSchema as locationDtoSchema}from"./Indicia/Location.mjs";export{default as IndiciaSampleCollection}from"./Indicia/SampleCollection.mjs";export{default as IndiciaGroupCollection,byGroupMembershipStatus}from"./Indicia/GroupCollection.mjs";export{default as IndiciaLocationCollection,byLocationType}from"./Indicia/LocationCollection.mjs";
1
+ export{DrupalUserError,DrupalUserErrorCode,default as DrupalUserModel}from"./Drupal/User.mjs";export{default as SQLiteDatabase}from"./Stores/SQLiteDatabase.mjs";export{default as LocalForageStore}from"./Stores/LocalForageStore.mjs";export{default as SQLiteStore}from"./Stores/SQLiteStore.mjs";export{default as IStore}from"./Stores/Store.mjs";export{default as TaxaStore}from"./Stores/Indicia/Taxa.mjs";export{default as TaxonListsStore}from"./Stores/Indicia/TaxonLists.mjs";export{default as GroupsStore}from"./Stores/Indicia/Groups.mjs";export{default as LocationsStore}from"./Stores/Indicia/Locations.mjs";export{default as Model}from"./Model.mjs";export{default as Collection}from"./Collection.mjs";export{default as IndiciaMedia}from"./Indicia/Media.mjs";export{default as IndiciaTaxonList}from"./Indicia/TaxonList.mjs";export{default as IndiciaOccurrence}from"./Indicia/Occurrence.mjs";export{default as IndiciaSample}from"./Indicia/Sample.mjs";export{default as IndiciaGroup,dtoSchema as groupDtoSchema}from"./Indicia/Group.mjs";export{default as IndiciaLocation,LocationType,dtoSchema as locationDtoSchema}from"./Indicia/Location.mjs";export{default as IndiciaSampleCollection}from"./Indicia/SampleCollection.mjs";export{default as IndiciaGroupCollection,byGroupMembershipStatus}from"./Indicia/GroupCollection.mjs";export{default as IndiciaLocationCollection,byLocationType}from"./Indicia/LocationCollection.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.32.1",
3
+ "version": "0.33.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",