@cuteminded/simplestorage 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lizzy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ > ## Pre-Production Notice
2
+ > This package is currently not ready for production use.
3
+ > It may contain bugs, incomplete features, breaking changes, and other issues that can result in unexpected behavior. APIs and functionality may change without notice until a stable release is released.
4
+
5
+ # simplestorage
6
+
7
+ A TypeScript package that provides a Laravel Query Builder-like API on top of IndexedDB.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @cuteminded/simplestorage
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```js
18
+ import { openDatabase } from "@cuteminded/simplestorage";
19
+
20
+ const db = await openDatabase({
21
+ name: "app-db",
22
+ version: 1,
23
+ stores: {
24
+ users: {
25
+ keyPath: "id",
26
+ autoIncrement: true,
27
+ indexes: [{ name: "email", keyPath: "email", options: { unique: true } }],
28
+ },
29
+ },
30
+ });
31
+
32
+ await db.table("users").insert([
33
+ { name: "lizzy", email: "lizzy@example.com", age: 25 },
34
+ { name: "Alex", email: "alex@example.com", age: 26 },
35
+ ]);
36
+
37
+ const users = await db.table("users").select("id", "name", "age").where("age", ">=", 25).orderBy("name", "asc").get();
38
+
39
+ console.log(users);
40
+ ```
41
+
42
+ ## API
43
+
44
+ ### `openDatabase(options)`
45
+
46
+ - `name` (string, required)
47
+ - `version` (number, default: `1`)
48
+ - `stores` (object)
49
+
50
+ Store config example:
51
+
52
+ ```js
53
+ {
54
+ users: {
55
+ keyPath: "id",
56
+ autoIncrement: true,
57
+ indexes: [
58
+ { name: "email", keyPath: "email", options: { unique: true } }
59
+ ]
60
+ }
61
+ }
62
+ ```
63
+
64
+ ### Query builder methods
65
+
66
+ - `table(name)`
67
+ - `select(...columns)`
68
+ - `where(column, value)`
69
+ - `where(column, operator, value)`
70
+ - `orWhere(column, value)`
71
+ - `orWhere(column, operator, value)`
72
+ - `whereIn(column, values)`
73
+ - `whereNull(column)`
74
+ - `whereNotNull(column)`
75
+ - `orderBy(column, direction)`
76
+ - `limit(number)`
77
+ - `offset(number)`
78
+ - `get()`
79
+ - `first()`
80
+ - `find(id)`
81
+ - `insert(data | data[])`
82
+ - `update(values)`
83
+ - `delete()`
84
+ - `truncate()`
@@ -0,0 +1,92 @@
1
+ type Row = Record<string, unknown>;
2
+ type Direction = "asc" | "desc";
3
+ type Operator = "=" | "==" | "!=" | "<>" | ">" | ">=" | "<" | "<=" | "like";
4
+ interface StoreIndexConfig {
5
+ name: string;
6
+ keyPath: string | string[];
7
+ options?: IDBIndexParameters;
8
+ }
9
+ interface StoreConfig {
10
+ keyPath?: string | string[];
11
+ autoIncrement?: boolean;
12
+ indexes?: StoreIndexConfig[];
13
+ }
14
+ interface OpenDatabaseOptions {
15
+ name: string;
16
+ version?: number;
17
+ stores?: Record<string, StoreConfig>;
18
+ }
19
+ interface StoreClient {
20
+ store(tableName: string, mode?: IDBTransactionMode): Promise<IDBObjectStore>;
21
+ }
22
+ type BasicWhere = {
23
+ type: "basic";
24
+ boolean: "and" | "or";
25
+ column: string;
26
+ operator: Operator;
27
+ value: unknown;
28
+ };
29
+ type InWhere = {
30
+ type: "in";
31
+ boolean: "and" | "or";
32
+ column: string;
33
+ values: unknown[];
34
+ };
35
+ type NullWhere = {
36
+ type: "null";
37
+ boolean: "and" | "or";
38
+ column: string;
39
+ isNull: boolean;
40
+ };
41
+ type WhereClause = BasicWhere | InWhere | NullWhere;
42
+
43
+ declare class IndexedQueryBuilder<T extends Row = Row> {
44
+ private readonly client;
45
+ private readonly tableName;
46
+ private _wheres;
47
+ private _orderBy;
48
+ private _limit;
49
+ private _offset;
50
+ private _selectedColumns;
51
+ constructor(client: StoreClient, tableName: string);
52
+ clone(): IndexedQueryBuilder<T>;
53
+ select<K extends keyof T>(...columns: K[]): IndexedQueryBuilder<Pick<T, K>>;
54
+ where(column: keyof T | string, value: unknown): this;
55
+ where(column: keyof T | string, operator: Operator, value: unknown): this;
56
+ orWhere(column: keyof T | string, value: unknown): this;
57
+ orWhere(column: keyof T | string, operator: Operator, value: unknown): this;
58
+ whereIn(column: keyof T | string, values: unknown[]): this;
59
+ whereNull(column: keyof T | string): this;
60
+ whereNotNull(column: keyof T | string): this;
61
+ orderBy(column: keyof T | string, direction?: Direction): this;
62
+ limit(limit: number): this;
63
+ offset(offset: number): this;
64
+ find(id: IDBValidKey): Promise<T | null>;
65
+ get(): Promise<T[]>;
66
+ first(): Promise<T | null>;
67
+ insert(payload: T): Promise<IDBValidKey>;
68
+ insert(payload: T[]): Promise<IDBValidKey[]>;
69
+ update(values: Partial<T>): Promise<number>;
70
+ delete(): Promise<number>;
71
+ truncate(): Promise<void>;
72
+ private _matchesWhere;
73
+ private _rowMatchesAllWheres;
74
+ private _applyPostFilters;
75
+ private _readFilteredRows;
76
+ }
77
+
78
+ declare class IndexedClient {
79
+ private readonly db;
80
+ constructor(db: IDBDatabase);
81
+ table<T extends Row = Row>(tableName: string): IndexedQueryBuilder<T>;
82
+ store(tableName: string, mode?: IDBTransactionMode): Promise<IDBObjectStore>;
83
+ close(): void;
84
+ }
85
+
86
+ declare function openDatabase({ name, version, stores }: OpenDatabaseOptions): Promise<IndexedClient>;
87
+
88
+ declare const _default: {
89
+ openDatabase: typeof openDatabase;
90
+ };
91
+
92
+ export { type BasicWhere, type Direction, type InWhere, IndexedClient, IndexedQueryBuilder, type NullWhere, type OpenDatabaseOptions, type Operator, type Row, type StoreClient, type StoreConfig, type StoreIndexConfig, type WhereClause, _default as default, openDatabase };
@@ -0,0 +1,92 @@
1
+ type Row = Record<string, unknown>;
2
+ type Direction = "asc" | "desc";
3
+ type Operator = "=" | "==" | "!=" | "<>" | ">" | ">=" | "<" | "<=" | "like";
4
+ interface StoreIndexConfig {
5
+ name: string;
6
+ keyPath: string | string[];
7
+ options?: IDBIndexParameters;
8
+ }
9
+ interface StoreConfig {
10
+ keyPath?: string | string[];
11
+ autoIncrement?: boolean;
12
+ indexes?: StoreIndexConfig[];
13
+ }
14
+ interface OpenDatabaseOptions {
15
+ name: string;
16
+ version?: number;
17
+ stores?: Record<string, StoreConfig>;
18
+ }
19
+ interface StoreClient {
20
+ store(tableName: string, mode?: IDBTransactionMode): Promise<IDBObjectStore>;
21
+ }
22
+ type BasicWhere = {
23
+ type: "basic";
24
+ boolean: "and" | "or";
25
+ column: string;
26
+ operator: Operator;
27
+ value: unknown;
28
+ };
29
+ type InWhere = {
30
+ type: "in";
31
+ boolean: "and" | "or";
32
+ column: string;
33
+ values: unknown[];
34
+ };
35
+ type NullWhere = {
36
+ type: "null";
37
+ boolean: "and" | "or";
38
+ column: string;
39
+ isNull: boolean;
40
+ };
41
+ type WhereClause = BasicWhere | InWhere | NullWhere;
42
+
43
+ declare class IndexedQueryBuilder<T extends Row = Row> {
44
+ private readonly client;
45
+ private readonly tableName;
46
+ private _wheres;
47
+ private _orderBy;
48
+ private _limit;
49
+ private _offset;
50
+ private _selectedColumns;
51
+ constructor(client: StoreClient, tableName: string);
52
+ clone(): IndexedQueryBuilder<T>;
53
+ select<K extends keyof T>(...columns: K[]): IndexedQueryBuilder<Pick<T, K>>;
54
+ where(column: keyof T | string, value: unknown): this;
55
+ where(column: keyof T | string, operator: Operator, value: unknown): this;
56
+ orWhere(column: keyof T | string, value: unknown): this;
57
+ orWhere(column: keyof T | string, operator: Operator, value: unknown): this;
58
+ whereIn(column: keyof T | string, values: unknown[]): this;
59
+ whereNull(column: keyof T | string): this;
60
+ whereNotNull(column: keyof T | string): this;
61
+ orderBy(column: keyof T | string, direction?: Direction): this;
62
+ limit(limit: number): this;
63
+ offset(offset: number): this;
64
+ find(id: IDBValidKey): Promise<T | null>;
65
+ get(): Promise<T[]>;
66
+ first(): Promise<T | null>;
67
+ insert(payload: T): Promise<IDBValidKey>;
68
+ insert(payload: T[]): Promise<IDBValidKey[]>;
69
+ update(values: Partial<T>): Promise<number>;
70
+ delete(): Promise<number>;
71
+ truncate(): Promise<void>;
72
+ private _matchesWhere;
73
+ private _rowMatchesAllWheres;
74
+ private _applyPostFilters;
75
+ private _readFilteredRows;
76
+ }
77
+
78
+ declare class IndexedClient {
79
+ private readonly db;
80
+ constructor(db: IDBDatabase);
81
+ table<T extends Row = Row>(tableName: string): IndexedQueryBuilder<T>;
82
+ store(tableName: string, mode?: IDBTransactionMode): Promise<IDBObjectStore>;
83
+ close(): void;
84
+ }
85
+
86
+ declare function openDatabase({ name, version, stores }: OpenDatabaseOptions): Promise<IndexedClient>;
87
+
88
+ declare const _default: {
89
+ openDatabase: typeof openDatabase;
90
+ };
91
+
92
+ export { type BasicWhere, type Direction, type InWhere, IndexedClient, IndexedQueryBuilder, type NullWhere, type OpenDatabaseOptions, type Operator, type Row, type StoreClient, type StoreConfig, type StoreIndexConfig, type WhereClause, _default as default, openDatabase };
@@ -0,0 +1 @@
1
+ "use strict";var simpleStorage=(()=>{var f=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var k=(s,e)=>{for(var r in e)f(s,r,{get:e[r],enumerable:!0})},P=(s,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of T(e))!_.call(s,n)&&n!==r&&f(s,n,{get:()=>e[n],enumerable:!(t=g(e,n))||t.enumerable});return s};var B=s=>P(f({},"__esModule",{value:!0}),s);var v={};k(v,{IndexedClient:()=>d,IndexedQueryBuilder:()=>h,default:()=>D,openDatabase:()=>w});function y(s,e,r){return r===void 0?{column:s,operator:"=",value:e}:{column:s,operator:e,value:r}}function p(s,e,r){switch(e){case"=":case"==":return s===r;case"!=":case"<>":return s!==r;case">":return s>r;case">=":return s>=r;case"<":return s<r;case"<=":return s<=r;case"like":return typeof s!="string"?!1:new RegExp(`^${String(r).replace(/[.*+?^${}()|[\\]\\]/g,"\\$&").replace(/%/g,".*")}$`,"i").test(s);default:throw new Error(`Unsupported operator: ${e}`)}}function b(s,e){if(!e)return s;let r={};for(let t of e)r[t]=s[t];return r}var h=class s{client;tableName;_wheres;_orderBy;_limit;_offset;_selectedColumns;constructor(e,r){this.client=e,this.tableName=r,this._wheres=[],this._orderBy=null,this._limit=null,this._offset=0,this._selectedColumns=null}clone(){let e=new s(this.client,this.tableName);return e._wheres=[...this._wheres],e._orderBy=this._orderBy?{...this._orderBy}:null,e._limit=this._limit,e._offset=this._offset,e._selectedColumns=this._selectedColumns?[...this._selectedColumns]:null,e}select(...e){return this._selectedColumns=e.map(r=>String(r)),this}where(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"and",...n}),this}orWhere(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"or",...n}),this}whereIn(e,r){return this._wheres.push({type:"in",boolean:"and",column:String(e),values:[...r]}),this}whereNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!0}),this}whereNotNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!1}),this}orderBy(e,r="asc"){let t=String(r).toLowerCase();if(t!=="asc"&&t!=="desc")throw new Error("orderBy direction must be asc or desc");return this._orderBy={column:String(e),direction:t},this}limit(e){return this._limit=e,this}offset(e){return this._offset=e,this}async find(e){let r=await this.client.store(this.tableName,"readonly");return new Promise((t,n)=>{let o=r.get(e);o.onsuccess=()=>t(o.result??null),o.onerror=()=>n(o.error)})}async get(){return(await this._readFilteredRows()).map(r=>b(r,this._selectedColumns))}async first(){return(await this.limit(1).get())[0]??null}async insert(e){let r=Array.isArray(e)?e:[e],t=await this.client.store(this.tableName,"readwrite"),n=[];for(let o of r){let i=await new Promise((a,u)=>{let l=t.add({...o});l.onsuccess=()=>a(l.result),l.onerror=()=>u(l.error)});n.push(i)}return Array.isArray(e)?n:n[0]}async update(e){let r=await this._readFilteredRows(),t=0;for(let n of r){let o=await this.client.store(this.tableName,"readwrite");await new Promise((i,a)=>{let u={...n,...e},l=o.put(u);l.onsuccess=()=>i(),l.onerror=()=>a(l.error)}),t+=1}return t}async delete(){let e=await this._readFilteredRows(),t=(await this.client.store(this.tableName,"readonly")).keyPath,n=e.map(i=>{if(typeof t=="string")return i[t]}),o=0;for(let i of n){if(i==null)continue;let a=await this.client.store(this.tableName,"readwrite");await new Promise((u,l)=>{let c=a.delete(i);c.onsuccess=()=>u(),c.onerror=()=>l(c.error)}),o+=1}return o}async truncate(){let e=await this.client.store(this.tableName,"readwrite");return new Promise((r,t)=>{let n=e.clear();n.onsuccess=()=>r(),n.onerror=()=>t(n.error)})}_matchesWhere(e,r){if(r.type==="basic")return p(e[r.column],r.operator,r.value);if(r.type==="in")return r.values.includes(e[r.column]);let t=e[r.column]===null||e[r.column]===void 0;return r.isNull?t:!t}_rowMatchesAllWheres(e){if(this._wheres.length===0)return!0;let r=null;for(let t of this._wheres){let n=this._matchesWhere(e,t);r===null?r=n:t.boolean==="or"?r=r||n:r=r&&n}return!!r}_applyPostFilters(e){let r=e.filter(t=>this._rowMatchesAllWheres(t));if(this._orderBy){let{column:t,direction:n}=this._orderBy,o=n==="asc"?1:-1;r=[...r].sort((i,a)=>{let u=i[t],l=a[t];return u===l?0:u!==void 0&&l!==void 0&&u>l?o:-o})}return this._offset&&(r=r.slice(this._offset)),this._limit!==null&&(r=r.slice(0,this._limit)),r}async _readFilteredRows(){let e=await this.client.store(this.tableName,"readonly"),r=[];return new Promise((t,n)=>{let o=e.openCursor();o.onsuccess=i=>{let a=i.target.result;if(!a){t(this._applyPostFilters(r));return}r.push(a.value),a.continue()},o.onerror=()=>n(o.error)})}};var d=class{db;constructor(e){this.db=e}table(e){if(!this.db.objectStoreNames.contains(e))throw new Error(`Object store "${e}" does not exist in this database`);return new h(this,e)}store(e,r="readonly"){let t=this.db.transaction(e,r);return Promise.resolve(t.objectStore(e))}close(){this.db.close()}};function w({name:s,version:e=1,stores:r={}}){if(!s)throw new Error("Database name is required");return new Promise((t,n)=>{let o=indexedDB.open(s,e);o.onupgradeneeded=()=>{let i=o.result;for(let[a,u]of Object.entries(r)){i.objectStoreNames.contains(a)&&i.deleteObjectStore(a);let c=i.createObjectStore(a,{keyPath:u.keyPath,autoIncrement:u.autoIncrement});for(let m of u.indexes||[])c.createIndex(m.name,m.keyPath,m.options||{})}},o.onsuccess=()=>{t(new d(o.result))},o.onerror=()=>{n(o.error)}})}var D={openDatabase:w};return B(v);})();
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var f=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var x=(o,e)=>{for(var r in e)f(o,r,{get:e[r],enumerable:!0})},P=(o,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of k(e))!_.call(o,n)&&n!==r&&f(o,n,{get:()=>e[n],enumerable:!(t=T(e,n))||t.enumerable});return o};var B=o=>P(f({},"__esModule",{value:!0}),o);var I={};x(I,{IndexedClient:()=>m,IndexedQueryBuilder:()=>d,default:()=>D,openDatabase:()=>w});module.exports=B(I);function y(o,e,r){return r===void 0?{column:o,operator:"=",value:e}:{column:o,operator:e,value:r}}function b(o,e,r){switch(e){case"=":case"==":return o===r;case"!=":case"<>":return o!==r;case">":return o>r;case">=":return o>=r;case"<":return o<r;case"<=":return o<=r;case"like":return typeof o!="string"?!1:new RegExp(`^${String(r).replace(/[.*+?^${}()|[\\]\\]/g,"\\$&").replace(/%/g,".*")}$`,"i").test(o);default:throw new Error(`Unsupported operator: ${e}`)}}function g(o,e){if(!e)return o;let r={};for(let t of e)r[t]=o[t];return r}var d=class o{client;tableName;_wheres;_orderBy;_limit;_offset;_selectedColumns;constructor(e,r){this.client=e,this.tableName=r,this._wheres=[],this._orderBy=null,this._limit=null,this._offset=0,this._selectedColumns=null}clone(){let e=new o(this.client,this.tableName);return e._wheres=[...this._wheres],e._orderBy=this._orderBy?{...this._orderBy}:null,e._limit=this._limit,e._offset=this._offset,e._selectedColumns=this._selectedColumns?[...this._selectedColumns]:null,e}select(...e){return this._selectedColumns=e.map(r=>String(r)),this}where(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"and",...n}),this}orWhere(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"or",...n}),this}whereIn(e,r){return this._wheres.push({type:"in",boolean:"and",column:String(e),values:[...r]}),this}whereNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!0}),this}whereNotNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!1}),this}orderBy(e,r="asc"){let t=String(r).toLowerCase();if(t!=="asc"&&t!=="desc")throw new Error("orderBy direction must be asc or desc");return this._orderBy={column:String(e),direction:t},this}limit(e){return this._limit=e,this}offset(e){return this._offset=e,this}async find(e){let r=await this.client.store(this.tableName,"readonly");return new Promise((t,n)=>{let s=r.get(e);s.onsuccess=()=>t(s.result??null),s.onerror=()=>n(s.error)})}async get(){return(await this._readFilteredRows()).map(r=>g(r,this._selectedColumns))}async first(){return(await this.limit(1).get())[0]??null}async insert(e){let r=Array.isArray(e)?e:[e],t=await this.client.store(this.tableName,"readwrite"),n=[];for(let s of r){let i=await new Promise((a,u)=>{let l=t.add({...s});l.onsuccess=()=>a(l.result),l.onerror=()=>u(l.error)});n.push(i)}return Array.isArray(e)?n:n[0]}async update(e){let r=await this._readFilteredRows(),t=0;for(let n of r){let s=await this.client.store(this.tableName,"readwrite");await new Promise((i,a)=>{let u={...n,...e},l=s.put(u);l.onsuccess=()=>i(),l.onerror=()=>a(l.error)}),t+=1}return t}async delete(){let e=await this._readFilteredRows(),t=(await this.client.store(this.tableName,"readonly")).keyPath,n=e.map(i=>{if(typeof t=="string")return i[t]}),s=0;for(let i of n){if(i==null)continue;let a=await this.client.store(this.tableName,"readwrite");await new Promise((u,l)=>{let c=a.delete(i);c.onsuccess=()=>u(),c.onerror=()=>l(c.error)}),s+=1}return s}async truncate(){let e=await this.client.store(this.tableName,"readwrite");return new Promise((r,t)=>{let n=e.clear();n.onsuccess=()=>r(),n.onerror=()=>t(n.error)})}_matchesWhere(e,r){if(r.type==="basic")return b(e[r.column],r.operator,r.value);if(r.type==="in")return r.values.includes(e[r.column]);let t=e[r.column]===null||e[r.column]===void 0;return r.isNull?t:!t}_rowMatchesAllWheres(e){if(this._wheres.length===0)return!0;let r=null;for(let t of this._wheres){let n=this._matchesWhere(e,t);r===null?r=n:t.boolean==="or"?r=r||n:r=r&&n}return!!r}_applyPostFilters(e){let r=e.filter(t=>this._rowMatchesAllWheres(t));if(this._orderBy){let{column:t,direction:n}=this._orderBy,s=n==="asc"?1:-1;r=[...r].sort((i,a)=>{let u=i[t],l=a[t];return u===l?0:u!==void 0&&l!==void 0&&u>l?s:-s})}return this._offset&&(r=r.slice(this._offset)),this._limit!==null&&(r=r.slice(0,this._limit)),r}async _readFilteredRows(){let e=await this.client.store(this.tableName,"readonly"),r=[];return new Promise((t,n)=>{let s=e.openCursor();s.onsuccess=i=>{let a=i.target.result;if(!a){t(this._applyPostFilters(r));return}r.push(a.value),a.continue()},s.onerror=()=>n(s.error)})}};var m=class{db;constructor(e){this.db=e}table(e){if(!this.db.objectStoreNames.contains(e))throw new Error(`Object store "${e}" does not exist in this database`);return new d(this,e)}store(e,r="readonly"){let t=this.db.transaction(e,r);return Promise.resolve(t.objectStore(e))}close(){this.db.close()}};function w({name:o,version:e=1,stores:r={}}){if(!o)throw new Error("Database name is required");return new Promise((t,n)=>{let s=indexedDB.open(o,e);s.onupgradeneeded=()=>{let i=s.result;for(let[a,u]of Object.entries(r)){i.objectStoreNames.contains(a)&&i.deleteObjectStore(a);let c=i.createObjectStore(a,{keyPath:u.keyPath,autoIncrement:u.autoIncrement});for(let p of u.indexes||[])c.createIndex(p.name,p.keyPath,p.options||{})}},s.onsuccess=()=>{t(new m(s.result))},s.onerror=()=>{n(s.error)}})}var D={openDatabase:w};0&&(module.exports={IndexedClient,IndexedQueryBuilder,openDatabase});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ function y(s,e,r){return r===void 0?{column:s,operator:"=",value:e}:{column:s,operator:e,value:r}}function w(s,e,r){switch(e){case"=":case"==":return s===r;case"!=":case"<>":return s!==r;case">":return s>r;case">=":return s>=r;case"<":return s<r;case"<=":return s<=r;case"like":return typeof s!="string"?!1:new RegExp(`^${String(r).replace(/[.*+?^${}()|[\\]\\]/g,"\\$&").replace(/%/g,".*")}$`,"i").test(s);default:throw new Error(`Unsupported operator: ${e}`)}}function b(s,e){if(!e)return s;let r={};for(let t of e)r[t]=s[t];return r}var m=class s{client;tableName;_wheres;_orderBy;_limit;_offset;_selectedColumns;constructor(e,r){this.client=e,this.tableName=r,this._wheres=[],this._orderBy=null,this._limit=null,this._offset=0,this._selectedColumns=null}clone(){let e=new s(this.client,this.tableName);return e._wheres=[...this._wheres],e._orderBy=this._orderBy?{...this._orderBy}:null,e._limit=this._limit,e._offset=this._offset,e._selectedColumns=this._selectedColumns?[...this._selectedColumns]:null,e}select(...e){return this._selectedColumns=e.map(r=>String(r)),this}where(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"and",...n}),this}orWhere(e,r,t){let n=y(String(e),r,t);return this._wheres.push({type:"basic",boolean:"or",...n}),this}whereIn(e,r){return this._wheres.push({type:"in",boolean:"and",column:String(e),values:[...r]}),this}whereNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!0}),this}whereNotNull(e){return this._wheres.push({type:"null",boolean:"and",column:String(e),isNull:!1}),this}orderBy(e,r="asc"){let t=String(r).toLowerCase();if(t!=="asc"&&t!=="desc")throw new Error("orderBy direction must be asc or desc");return this._orderBy={column:String(e),direction:t},this}limit(e){return this._limit=e,this}offset(e){return this._offset=e,this}async find(e){let r=await this.client.store(this.tableName,"readonly");return new Promise((t,n)=>{let o=r.get(e);o.onsuccess=()=>t(o.result??null),o.onerror=()=>n(o.error)})}async get(){return(await this._readFilteredRows()).map(r=>b(r,this._selectedColumns))}async first(){return(await this.limit(1).get())[0]??null}async insert(e){let r=Array.isArray(e)?e:[e],t=await this.client.store(this.tableName,"readwrite"),n=[];for(let o of r){let i=await new Promise((a,u)=>{let l=t.add({...o});l.onsuccess=()=>a(l.result),l.onerror=()=>u(l.error)});n.push(i)}return Array.isArray(e)?n:n[0]}async update(e){let r=await this._readFilteredRows(),t=0;for(let n of r){let o=await this.client.store(this.tableName,"readwrite");await new Promise((i,a)=>{let u={...n,...e},l=o.put(u);l.onsuccess=()=>i(),l.onerror=()=>a(l.error)}),t+=1}return t}async delete(){let e=await this._readFilteredRows(),t=(await this.client.store(this.tableName,"readonly")).keyPath,n=e.map(i=>{if(typeof t=="string")return i[t]}),o=0;for(let i of n){if(i==null)continue;let a=await this.client.store(this.tableName,"readwrite");await new Promise((u,l)=>{let c=a.delete(i);c.onsuccess=()=>u(),c.onerror=()=>l(c.error)}),o+=1}return o}async truncate(){let e=await this.client.store(this.tableName,"readwrite");return new Promise((r,t)=>{let n=e.clear();n.onsuccess=()=>r(),n.onerror=()=>t(n.error)})}_matchesWhere(e,r){if(r.type==="basic")return w(e[r.column],r.operator,r.value);if(r.type==="in")return r.values.includes(e[r.column]);let t=e[r.column]===null||e[r.column]===void 0;return r.isNull?t:!t}_rowMatchesAllWheres(e){if(this._wheres.length===0)return!0;let r=null;for(let t of this._wheres){let n=this._matchesWhere(e,t);r===null?r=n:t.boolean==="or"?r=r||n:r=r&&n}return!!r}_applyPostFilters(e){let r=e.filter(t=>this._rowMatchesAllWheres(t));if(this._orderBy){let{column:t,direction:n}=this._orderBy,o=n==="asc"?1:-1;r=[...r].sort((i,a)=>{let u=i[t],l=a[t];return u===l?0:u!==void 0&&l!==void 0&&u>l?o:-o})}return this._offset&&(r=r.slice(this._offset)),this._limit!==null&&(r=r.slice(0,this._limit)),r}async _readFilteredRows(){let e=await this.client.store(this.tableName,"readonly"),r=[];return new Promise((t,n)=>{let o=e.openCursor();o.onsuccess=i=>{let a=i.target.result;if(!a){t(this._applyPostFilters(r));return}r.push(a.value),a.continue()},o.onerror=()=>n(o.error)})}};var p=class{db;constructor(e){this.db=e}table(e){if(!this.db.objectStoreNames.contains(e))throw new Error(`Object store "${e}" does not exist in this database`);return new m(this,e)}store(e,r="readonly"){let t=this.db.transaction(e,r);return Promise.resolve(t.objectStore(e))}close(){this.db.close()}};function g({name:s,version:e=1,stores:r={}}){if(!s)throw new Error("Database name is required");return new Promise((t,n)=>{let o=indexedDB.open(s,e);o.onupgradeneeded=()=>{let i=o.result;for(let[a,u]of Object.entries(r)){i.objectStoreNames.contains(a)&&i.deleteObjectStore(a);let c=i.createObjectStore(a,{keyPath:u.keyPath,autoIncrement:u.autoIncrement});for(let f of u.indexes||[])c.createIndex(f.name,f.keyPath,f.options||{})}},o.onsuccess=()=>{t(new p(o.result))},o.onerror=()=>{n(o.error)}})}var N={openDatabase:g};export{p as IndexedClient,m as IndexedQueryBuilder,N as default,g as openDatabase};
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@cuteminded/simplestorage",
3
+ "description": "ESM JavaScript query-builder style wrapper for IndexedDB",
4
+ "version": "0.1.0",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "homepage": "https://lizzy.nu/",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Cuteminded/simplestorage.git"
12
+ },
13
+ "scripts": {
14
+ "build": "tsup",
15
+ "pub": "npm publish --access public",
16
+ "test": "npm run build && node --test test/*.test.js"
17
+ },
18
+ "keywords": [
19
+ "indexeddb",
20
+ "query-builder"
21
+ ],
22
+ "author": "Lizzy / CuteMinded",
23
+ "license": "MIT",
24
+ "type": "commonjs",
25
+ "devDependencies": {
26
+ "fake-indexeddb": "^6.2.5",
27
+ "tsup": "^8.5.1",
28
+ "typescript": "^6.0.2"
29
+ }
30
+ }