mongolite-ts 0.2.3 → 0.2.4

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
@@ -301,7 +301,54 @@ Drops a specified index from the collection.
301
301
  Drops all indexes from the collection, except for the index on _id.
302
302
 
303
303
  * Returns an object with `acknowledged` (boolean) and `droppedCount` (number) indicating how many indexes were dropped.
304
- ````
304
+ ## Performance Benchmarks
305
+
306
+ *Last updated: 2025-07-25*
307
+
308
+ ### Operation Performance
309
+
310
+ | Operation | Records Tested | Duration (ms) | Ops/Second | Avg Time/Op (ms) |
311
+ |-----------|----------------|---------------|------------|------------------|
312
+ | INSERT | 10,000 | 48572.42 | 206 | 4.857 |
313
+ | QUERY_SIMPLE | 1,000 | 56.67 | 17646 | 0.057 |
314
+ | QUERY_COMPLEX | 500 | 38.30 | 13054 | 0.077 |
315
+ | QUERY_ARRAY | 500 | 3761.94 | 133 | 7.524 |
316
+ | QUERY_FIND_MANY | 100 | 40.74 | 2454 | 0.407 |
317
+ | UPDATE | 1,000 | 5849.96 | 171 | 5.850 |
318
+ | DELETE | 1,000 | 16064.51 | 62 | 16.065 |
319
+
320
+ ### Storage Capacity
321
+
322
+ | Records | Database Size (MB) | Avg Record Size (bytes) |
323
+ |---------|-------------------|------------------------|
324
+ | 1,000 | 0.44 | 459 |
325
+ | 10,000 | 4.27 | 448 |
326
+ | 50,000 | 21.36 | 448 |
327
+ | 100,000 | 42.75 | 448 |
328
+
329
+ ### Notes
330
+
331
+ - **INSERT**: Individual insertOne() operations
332
+ - **QUERY_SIMPLE**: Single field queries with operators
333
+ - **QUERY_COMPLEX**: Multi-field queries with nested objects
334
+ - **QUERY_ARRAY**: Queries searching within arrays
335
+ - **QUERY_FIND_MANY**: Batch queries returning up to 100 records
336
+ - **UPDATE**: Individual updateOne() operations with $set
337
+ - **DELETE**: Individual deleteOne() operations
338
+
339
+ **Storage Characteristics:**
340
+ - SQLite databases scale well with MongoLite
341
+ - Average record size includes JSON overhead and SQLite indexing
342
+ - Practical limits depend on available disk space and memory
343
+ - WAL mode provides better concurrent access for larger datasets
344
+
345
+ **Recommendations:**
346
+ - For high-performance scenarios, consider batching operations
347
+ - Use indexing for frequently queried fields
348
+ - Monitor database file size growth with your specific data patterns
349
+
350
+ ## Development
351
+ ```
305
352
 
306
353
 
307
354
  ## Development
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongolite-ts",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "A MongoDB-like client using SQLite as a persistent store, written in TypeScript.",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -14,7 +14,8 @@
14
14
  "lint:fix": "eslint src/**/*.ts tests/**/*.ts --fix",
15
15
  "verify-build": "node --import tsx scripts/verify-build.js",
16
16
  "test-third-party": "node scripts/test-third-party-usage.js",
17
- "test:all": "npm run lint && npm run test && npm run verify-build && npm run test-third-party"
17
+ "test:all": "npm run lint && npm run test && npm run verify-build && npm run test-third-party",
18
+ "benchmark": "npx tsx scripts/benchmark.ts"
18
19
  },
19
20
  "repository": {
20
21
  "type": "git",
@@ -37,10 +38,10 @@
37
38
  "homepage": "https://github.com/semics-tech/mongolite-ts#readme",
38
39
  "devDependencies": {
39
40
  "@types/better-sqlite3": "^7.6.13",
40
- "@types/node": "^20.17.57",
41
+ "@types/node": "^24.0.7",
41
42
  "@typescript-eslint/eslint-plugin": "^7.9.0",
42
43
  "@typescript-eslint/parser": "^7.9.0",
43
- "c8": "^9.1.0",
44
+ "c8": "^10.1.3",
44
45
  "eslint": "^8.57.0",
45
46
  "eslint-config-prettier": "^9.1.0",
46
47
  "eslint-plugin-prettier": "^5.1.3",
@@ -53,7 +54,7 @@
53
54
  "@types/uuid": "^9.0.8",
54
55
  "better-sqlite3": "^12.1.1",
55
56
  "bson": "^6.10.4",
56
- "uuid": "^9.0.1"
57
+ "uuid": "^11.1.0"
57
58
  },
58
59
  "files": [
59
60
  "dist/**/*",
@@ -1,34 +0,0 @@
1
- /**
2
- * Utility functions for working with document objects
3
- */
4
- /**
5
- * Sets a nested value in an object using dot notation.
6
- * @param obj The object to modify.
7
- * @param path The dot notation path (e.g., 'user.profile.name').
8
- * @param value The value to set.
9
- */
10
- export declare function setNestedValue(obj: any, path: string, value: any): void;
11
- /**
12
- * Removes a nested property from an object using dot notation.
13
- * @param obj The object to modify.
14
- * @param path The dot notation path (e.g., 'user.profile.name').
15
- */
16
- export declare function unsetNestedValue(obj: any, path: string): void;
17
- /**
18
- * Gets a nested value from an object using dot notation.
19
- * @param obj The object to query.
20
- * @param path The dot notation path (e.g., 'user.profile.name').
21
- * @returns The value at the path, or undefined if the path doesn't exist.
22
- */
23
- export declare function getNestedValue(obj: any, path: string): any;
24
- /**
25
- * Generate a retry function with exponential backoff
26
- * @param operation The async operation to retry
27
- * @param operationDescription Description for logging
28
- * @param maxRetries Maximum number of retries
29
- * @param initialDelayMs Initial delay between retries (ms)
30
- * @param maxDelayMs Maximum delay between retries (ms)
31
- * @returns The result of the operation if successful
32
- * @throws The original error if all retries fail
33
- */
34
- export declare function retryWithBackoff<R>(operation: () => Promise<R>, operationDescription: string, maxRetries?: number, initialDelayMs?: number, maxDelayMs?: number): Promise<R>;
@@ -1,101 +0,0 @@
1
- /**
2
- * Utility functions for working with document objects
3
- */
4
- /**
5
- * Sets a nested value in an object using dot notation.
6
- * @param obj The object to modify.
7
- * @param path The dot notation path (e.g., 'user.profile.name').
8
- * @param value The value to set.
9
- */
10
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
- export function setNestedValue(obj, path, value) {
12
- const keys = path.split('.');
13
- let current = obj;
14
- // Navigate to the last parent in the path
15
- for (let i = 0; i < keys.length - 1; i++) {
16
- const key = keys[i];
17
- // Create nested objects if they don't exist
18
- if (current[key] === undefined || current[key] === null) {
19
- current[key] = {};
20
- }
21
- else if (typeof current[key] !== 'object') {
22
- // If the path exists but is not an object, make it an object
23
- current[key] = {};
24
- }
25
- current = current[key];
26
- }
27
- // Set the value at the final key
28
- current[keys[keys.length - 1]] = value;
29
- }
30
- /**
31
- * Removes a nested property from an object using dot notation.
32
- * @param obj The object to modify.
33
- * @param path The dot notation path (e.g., 'user.profile.name').
34
- */
35
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
- export function unsetNestedValue(obj, path) {
37
- const keys = path.split('.');
38
- let current = obj;
39
- // Navigate to the last parent in the path
40
- for (let i = 0; i < keys.length - 1; i++) {
41
- const key = keys[i];
42
- if (current[key] === undefined || current[key] === null) {
43
- // If the path doesn't exist, nothing to unset
44
- return;
45
- }
46
- current = current[key];
47
- }
48
- // Delete the property at the final key
49
- delete current[keys[keys.length - 1]];
50
- }
51
- /**
52
- * Gets a nested value from an object using dot notation.
53
- * @param obj The object to query.
54
- * @param path The dot notation path (e.g., 'user.profile.name').
55
- * @returns The value at the path, or undefined if the path doesn't exist.
56
- */
57
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
58
- export function getNestedValue(obj, path) {
59
- const keys = path.split('.');
60
- let current = obj;
61
- // Navigate through the path
62
- for (let i = 0; i < keys.length; i++) {
63
- const key = keys[i];
64
- if (current === undefined || current === null) {
65
- return undefined;
66
- }
67
- current = current[key];
68
- }
69
- return current;
70
- }
71
- /**
72
- * Generate a retry function with exponential backoff
73
- * @param operation The async operation to retry
74
- * @param operationDescription Description for logging
75
- * @param maxRetries Maximum number of retries
76
- * @param initialDelayMs Initial delay between retries (ms)
77
- * @param maxDelayMs Maximum delay between retries (ms)
78
- * @returns The result of the operation if successful
79
- * @throws The original error if all retries fail
80
- */
81
- export async function retryWithBackoff(operation, operationDescription, maxRetries = 5, initialDelayMs = 100, maxDelayMs = 10000) {
82
- let retries = 0;
83
- let delayMs = initialDelayMs;
84
- while (true) {
85
- try {
86
- return await operation();
87
- }
88
- catch (error) {
89
- if (error.code !== 'SQLITE_BUSY' || retries >= maxRetries) {
90
- throw error;
91
- }
92
- console.warn(`SQLITE_BUSY encountered during ${operationDescription}, retrying (${retries + 1}/${maxRetries})...`);
93
- // Wait for the backoff period
94
- await new Promise((resolve) => setTimeout(resolve, delayMs));
95
- // Increase delay for next retry (exponential backoff)
96
- delayMs = Math.min(delayMs * 2, maxDelayMs);
97
- retries++;
98
- }
99
- }
100
- }
101
- //# sourceMappingURL=document-utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"document-utils.js","sourceRoot":"","sources":["../src/document-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;GAKG;AACH,8DAA8D;AAC9D,MAAM,UAAU,cAAc,CAAC,GAAQ,EAAE,IAAY,EAAE,KAAU;IAC/D,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7B,IAAI,OAAO,GAAG,GAAG,CAAC;IAElB,0CAA0C;IAC1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAEpB,4CAA4C;QAC5C,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC;YACxD,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACpB,CAAC;aAAM,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE,CAAC;YAC5C,6DAA6D;YAC7D,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACpB,CAAC;QAED,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IAED,iCAAiC;IACjC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AACzC,CAAC;AAED;;;;GAIG;AACH,8DAA8D;AAC9D,MAAM,UAAU,gBAAgB,C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pC,SAA2B,EAC3B,oBAA4B,EAC5B,UAAU,GAAG,CAAC,EACd,cAAc,GAAG,GAAG,EACpB,UAAU,GAAG,KAAK;IAElB,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,OAAO,GAAG,cAAc,CAAC;IAE7B,OAAO,IAAI,EAAE,CAAC;QACZ,IAAI,CAAC;YACH,OAAO,MAAM,SAAS,EAAE,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAK,KAA+B,CAAC,IAAI,KAAK,aAAa,IAAI,OAAO,IAAI,UAAU,EAAE,CAAC;gBACrF,MAAM,KAAK,CAAC;YACd,CAAC;YAED,OAAO,CAAC,IAAI,CACV,kCAAkC,oBAAoB,eAAe,OAAO,GAAG,CAAC,IAAI,UAAU,MAAM,CACrG,CAAC;YAEF,8BAA8B;YAC9B,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;YAE7D,sDAAsD;YACtD,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -1,51 +0,0 @@
1
- import { DocumentWithId, Filter, SortCriteria, Projection } from './types.js';
2
- import { SQLiteDB } from './db.js';
3
- /**
4
- * Represents a cursor for find operations, allowing chaining of limit, skip, and sort.
5
- */
6
- export declare class FindCursor<T extends DocumentWithId> {
7
- private db;
8
- private collectionName;
9
- private readonly options;
10
- private queryParts;
11
- private limitCount;
12
- private skipCount;
13
- private sortCriteria;
14
- private projectionFields;
15
- private queryBuilder;
16
- constructor(db: SQLiteDB, collectionName: string, initialFilter: Filter<T>, options?: {
17
- verbose?: boolean;
18
- });
19
- private buildSelectQuery;
20
- /**
21
- * Specifies the maximum number of documents the cursor will return.
22
- * @param count The number of documents to limit to.
23
- * @returns The `FindCursor` instance for chaining.
24
- */
25
- limit(count: number): this;
26
- /**
27
- * Specifies the number of documents to skip.
28
- * @param count The number of documents to skip.
29
- * @returns The `FindCursor` instance for chaining.
30
- */
31
- skip(count: number): this;
32
- /**
33
- * Specifies the sorting order for the documents.
34
- * @param sortCriteria An object defining sort order (e.g., `{ age: -1, name: 1 }`).
35
- * @returns The `FindCursor` instance for chaining.
36
- */
37
- sort(sortCriteria: SortCriteria<T>): this;
38
- /**
39
- * Specifies the fields to return (projection).
40
- * @param projection An object where keys are field names and values are 1 (include) or 0 (exclude).
41
- * `_id` is included by default unless explicitly excluded.
42
- * @returns The `FindCursor` instance for chaining.
43
- */
44
- project(projection: Projection<T>): this;
45
- private applyProjection;
46
- /**
47
- * Executes the query and returns all matching documents as an array.
48
- * @returns A promise that resolves to an array of documents.
49
- */
50
- toArray(): Promise<Partial<T>[]>;
51
- }
@@ -1,204 +0,0 @@
1
- import { QueryBuilder } from './query-builder.js';
2
- /**
3
- * Represents a cursor for find operations, allowing chaining of limit, skip, and sort.
4
- */
5
- export class FindCursor {
6
- constructor(db, collectionName, initialFilter, options = {}) {
7
- this.db = db;
8
- this.collectionName = collectionName;
9
- this.options = options;
10
- this.limitCount = null;
11
- this.skipCount = null;
12
- this.sortCriteria = null;
13
- this.projectionFields = null;
14
- this.queryBuilder = new QueryBuilder(options);
15
- this.queryParts = this.buildSelectQuery(initialFilter);
16
- }
17
- buildSelectQuery(filter) {
18
- const params = [];
19
- const whereClause = this.queryBuilder.buildWhereClause(filter, params);
20
- const sql = `SELECT _id, data FROM "${this.collectionName}" WHERE ${whereClause}`;
21
- if (this.options.verbose) {
22
- console.log(`SQL Query: ${sql}`);
23
- console.log(`Parameters: ${JSON.stringify(params)}`);
24
- }
25
- return { sql, params };
26
- }
27
- /**
28
- * Specifies the maximum number of documents the cursor will return.
29
- * @param count The number of documents to limit to.
30
- * @returns The `FindCursor` instance for chaining.
31
- */
32
- limit(count) {
33
- if (count < 0)
34
- throw new Error('Limit must be a non-negative number.');
35
- this.limitCount = count;
36
- return this;
37
- }
38
- /**
39
- * Specifies the number of documents to skip.
40
- * @param count The number of documents to skip.
41
- * @returns The `FindCursor` instance for chaining.
42
- */
43
- skip(count) {
44
- if (count < 0)
45
- throw new Error('Skip must be a non-negative number.');
46
- this.skipCount = count;
47
- return this;
48
- }
49
- /**
50
- * Specifies the sorting order for the documents.
51
- * @param sortCriteria An object defining sort order (e.g., `{ age: -1, name: 1 }`).
52
- * @returns The `FindCursor` instance for chaining.
53
- */
54
- sort(sortCriteria) {
55
- this.sortCriteria = sortCriteria;
56
- return this;
57
- }
58
- /**
59
- * Specifies the fields to return (projection).
60
- * @param projection An object where keys are field names and values are 1 (include) or 0 (exclude).
61
- * `_id` is included by default unless explicitly excluded.
62
- * @returns The `FindCursor` instance for chaining.
63
- */
64
- project(projection) {
65
- this.projectionFields = projection;
66
- return this;
67
- }
68
- applyProjection(doc) {
69
- if (!this.projectionFields)
70
- return doc;
71
- const projectedDoc = {};
72
- let includeMode = true; // true if any field is 1, false if any field is 0 (excluding _id)
73
- let hasExplicitInclusion = false;
74
- // Determine if it's an inclusion or exclusion projection
75
- for (const key in this.projectionFields) {
76
- if (key === '_id')
77
- continue;
78
- if (this.projectionFields[key] === 1 ||
79
- this.projectionFields[key] === true) {
80
- hasExplicitInclusion = true;
81
- break;
82
- }
83
- if (this.projectionFields[key] === 0 ||
84
- this.projectionFields[key] === false) {
85
- includeMode = false;
86
- // No break here, need to check all for explicit inclusions if _id is also 0
87
- }
88
- }
89
- if ((this.projectionFields._id === 0 || this.projectionFields._id === false) &&
90
- !hasExplicitInclusion) {
91
- // If _id is excluded and no other fields are explicitly included,
92
- // it's an exclusion projection where other fields are implicitly included.
93
- includeMode = false;
94
- }
95
- else if (hasExplicitInclusion) {
96
- includeMode = true;
97
- }
98
- if (includeMode) {
99
- // Inclusion mode
100
- for (const key in this.projectionFields) {
101
- if (this.projectionFields[key] === 1 ||
102
- this.projectionFields[key] === true) {
103
- if (key.includes('.')) {
104
- // Handle nested paths for inclusion (basic implementation)
105
- const path = key.split('.');
106
- let current = doc;
107
- let target = projectedDoc;
108
- // Navigate to the last parent in the path
109
- for (let i = 0; i < path.length - 1; i++) {
110
- const segment = path[i];
111
- if (current[segment] === undefined)
112
- break;
113
- if (target[segment] === undefined) {
114
- target[segment] = {};
115
- }
116
- current = current[segment];
117
- target = target[segment];
118
- }
119
- // Set the final property if we reached it
120
- const lastSegment = path[path.length - 1];
121
- if (current && current[lastSegment] !== undefined) {
122
- target[lastSegment] = current[lastSegment];
123
- }
124
- }
125
- else if (key in doc) {
126
- projectedDoc[key] = doc[key];
127
- }
128
- }
129
- }
130
- // _id is included by default in inclusion mode, unless explicitly excluded
131
- if (this.projectionFields._id !== 0 && this.projectionFields._id !== false && '_id' in doc) {
132
- projectedDoc._id = doc._id;
133
- }
134
- }
135
- else {
136
- // Exclusion mode
137
- Object.assign(projectedDoc, doc);
138
- for (const key in this.projectionFields) {
139
- if (this.projectionFields[key] === 0 ||
140
- this.projectionFields[key] === false) {
141
- if (key.includes('.')) {
142
- // Handle nested paths for exclusion (basic implementation)
143
- const path = key.split('.');
144
- let current = projectedDoc;
145
- // Navigate to the parent of the property to exclude
146
- for (let i = 0; i < path.length - 1; i++) {
147
- const segment = path[i];
148
- if (current[segment] === undefined)
149
- break;
150
- current = current[segment];
151
- }
152
- // Delete the final property if we reached its parent
153
- const lastSegment = path[path.length - 1];
154
- if (current && current[lastSegment] !== undefined) {
155
- delete current[lastSegment];
156
- }
157
- }
158
- else {
159
- delete projectedDoc[key];
160
- }
161
- }
162
- }
163
- }
164
- return projectedDoc;
165
- }
166
- /**
167
- * Executes the query and returns all matching documents as an array.
168
- * @returns A promise that resolves to an array of documents.
169
- */
170
- async toArray() {
171
- let finalSql = this.queryParts.sql;
172
- const finalParams = [...this.queryParts.params];
173
- if (this.sortCriteria) {
174
- const sortClauses = Object.entries(this.sortCriteria).map(([field, order]) => {
175
- if (field === '_id') {
176
- return `_id ${order === 1 ? 'ASC' : 'DESC'}`;
177
- }
178
- return `json_extract(data, ${this.queryBuilder.parseJsonPath(field)}) ${order === 1 ? 'ASC' : 'DESC'}`;
179
- });
180
- if (sortClauses.length > 0) {
181
- finalSql += ` ORDER BY ${sortClauses.join(', ')}`;
182
- }
183
- }
184
- if (this.limitCount !== null) {
185
- finalSql += ` LIMIT ?`;
186
- finalParams.push(this.limitCount);
187
- }
188
- if (this.skipCount !== null) {
189
- if (this.limitCount === null) {
190
- // SQLite requires a LIMIT if OFFSET is used.
191
- // Use a very large number if no limit is specified.
192
- finalSql += ` LIMIT -1`; // Or a large number like 999999999
193
- }
194
- finalSql += ` OFFSET ?`;
195
- finalParams.push(this.skipCount);
196
- }
197
- const rows = await this.db.all(finalSql, finalParams);
198
- return rows.map((row) => {
199
- const doc = { _id: row._id, ...JSON.parse(row.data) };
200
- return this.applyProjection(doc);
201
- });
202
- }
203
- }
204
- //# sourceMappingURL=find-cursor.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"find-cursor.js","sourceRoot":"","sources":["../src/find-cursor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD;;GAEG;AACH,MAAM,OAAO,UAAU;IAWrB,YACU,EAAY,EACZ,cAAsB,EAC9B,aAAwB,EACP,UAAiC,EAAE;QAH5C,OAAE,GAAF,EAAE,CAAU;QACZ,mBAAc,GAAd,cAAc,CAAQ;QAEb,YAAO,GAAP,OAAO,CAA4B;QAV9C,eAAU,GAAkB,IAAI,CAAC;QACjC,cAAS,GAAkB,IAAI,CAAC;QAChC,iBAAY,GAA2B,IAAI,CAAC;QAC5C,qBAAgB,GAAyB,IAAI,CAAC;QASpD,IAAI,CAAC,YAAY,GAAG,IAAI,YAAY,CAAI,OAAO,CAAC,CAAC;QACjD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAEO,gBAAgB,CA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AAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACnC,CAAC;QAOD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,GAAG,CAAY,QAAQ,EAAE,WAAW,CAAC,CAAC;QACjE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;YACtB,MAAM,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAO,CAAC;YAC3D,OAAO,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QACnC,CAAC,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -1,18 +0,0 @@
1
- import { Filter, DocumentWithId } from './types.js';
2
- export declare class QueryBuilder<T extends DocumentWithId> {
3
- private readonly options;
4
- constructor(options?: {
5
- verbose?: boolean;
6
- });
7
- /**
8
- * Converts a field path to a JSON path for SQLite's json_extract function.
9
- */
10
- parseJsonPath(path: string): string;
11
- /**
12
- * Builds a WHERE clause for a filter object.
13
- * @param filter The filter object.
14
- * @param params An array to collect query parameters.
15
- * @returns A SQL WHERE clause.
16
- */
17
- buildWhereClause(filter: Filter<T>, params: unknown[]): string;
18
- }
@@ -1,358 +0,0 @@
1
- export class QueryBuilder {
2
- constructor(options = {}) {
3
- this.options = options;
4
- }
5
- /**
6
- * Converts a field path to a JSON path for SQLite's json_extract function.
7
- */
8
- parseJsonPath(path) {
9
- return `'$.${path.replace(/\./g, '.')}'`;
10
- }
11
- /**
12
- * Builds a WHERE clause for a filter object.
13
- * @param filter The filter object.
14
- * @param params An array to collect query parameters.
15
- * @returns A SQL WHERE clause.
16
- */
17
- buildWhereClause(filter, params) {
18
- const conditions = [];
19
- // Handle $and, $or, $nor logical operators at the top level
20
- for (const key of Object.keys(filter)) {
21
- if (key === '$and' && filter.$and) {
22
- const condition = filter.$and;
23
- const andConditions = condition
24
- .map((subFilter) => `(${this.buildWhereClause(subFilter, params)})`)
25
- .join(' AND ');
26
- conditions.push(`(${andConditions})`);
27
- }
28
- else if (key === '$or' && filter.$or) {
29
- const condition = filter.$or;
30
- const orConditions = condition
31
- .map((subFilter) => `(${this.buildWhereClause(subFilter, params)})`)
32
- .join(' OR ');
33
- conditions.push(`(${orConditions})`);
34
- }
35
- else if (key === '$nor' && filter.$nor) {
36
- const condition = filter.$nor;
37
- const norConditions = condition
38
- .map((subFilter) => `(${this.buildWhereClause(subFilter, params)})`)
39
- .join(' OR ');
40
- conditions.push(`NOT (${norConditions})`);
41
- }
42
- else if (key === '$text' && filter.$text) {
43
- // Handle text search (basic implementation)
44
- const search = filter.$text.$search;
45
- if (typeof search === 'string' && search.trim() !== '') {
46
- conditions.push(`data LIKE ?`);
47
- params.push(`%${search}%`); // Simple LIKE search
48
- }
49
- else {
50
- conditions.push('1=0'); // No valid search term, nothing matches
51
- }
52
- }
53
- else if (key === '$exists' && filter.$exists) {
54
- // Handle existence check
55
- const existsConditions = Object.entries(filter.$exists)
56
- .map(([field, exists]) => {
57
- const jsonPath = this.parseJsonPath(field);
58
- if (exists) {
59
- return `json_extract(data, ${jsonPath}) IS NOT NULL`;
60
- }
61
- else {
62
- return `json_extract(data, ${jsonPath}) IS NULL`;
63
- }
64
- })
65
- .join(' AND ');
66
- conditions.push(`(${existsConditions})`);
67
- }
68
- else if (key === '$not' && filter.$not) {
69
- // Handle negation of conditions
70
- const notConditions = filter.$not;
71
- const notClause = this.buildWhereClause(notConditions, params);
72
- conditions.push(`NOT (${notClause})`);
73
- }
74
- else if (key === '$all' && filter.$all) {
75
- // Handle array all match
76
- const allConditions = Object.entries(filter.$all)
77
- .map(([field, values]) => {
78
- const arrayPath = this.parseJsonPath(field);
79
- if (Array.isArray(values) && values.length > 0) {
80
- const inConditions = values
81
- .map(() => `json_extract(data, ${arrayPath}) = ?`)
82
- .join(' AND ');
83
- params.push(...values);
84
- return `(${inConditions})`;
85
- }
86
- else {
87
- return '1=0'; // Empty $all means nothing matches
88
- }
89
- })
90
- .join(' AND ');
91
- conditions.push(`(${allConditions})`);
92
- }
93
- else if (key === '$elemMatch' && filter.$elemMatch) {
94
- // Handle array element match
95
- const elemMatchConditions = Object.entries(filter.$elemMatch)
96
- .map(([field, subFilter]) => {
97
- const arrayPath = this.parseJsonPath(field);
98
- // First check if the field exists and is an array
99
- const checkArrayCondition = `json_type(json_extract(data, ${arrayPath})) = 'array'`;
100
- // Use a subquery with json_each to find at least one array element matching all conditions
101
- let elemMatchSubquery = `EXISTS (
102
- SELECT 1 FROM json_each(json_extract(data, ${arrayPath})) as elements
103
- WHERE `;
104
- // Process the conditions for the array elements
105
- if (typeof subFilter === 'object' && subFilter !== null) {
106
- const elemConditions = Object.entries(subFilter)
107
- .map(([subField, subValue]) => {
108
- if (typeof subValue === 'object' && subValue !== null) {
109
- // Handle operators in the subfilter
110
- const subConditions = [];
111
- for (const op in subValue) {
112
- const opValue = subValue[op];
113
- switch (op) {
114
- case '$eq':
115
- subConditions.push(`json_extract(elements.value, '$.${subField}') = ?`);
116
- params.push(opValue);
117
- break;
118
- case '$gt':
119
- subConditions.push(`json_extract(elements.value, '$.${subField}') > ?`);
120
- params.push(opValue);
121
- break;
122
- case '$gte':
123
- subConditions.push(`json_extract(elements.value, '$.${subField}') >= ?`);
124
- params.push(opValue);
125
- break;
126
- case '$lt':
127
- subConditions.push(`json_extract(elements.value, '$.${subField}') < ?`);
128
- params.push(opValue);
129
- break;
130
- case '$lte':
131
- subConditions.push(`json_extract(elements.value, '$.${subField}') <= ?`);
132
- params.push(opValue);
133
- break;
134
- // Add other operators as needed
135
- }
136
- }
137
- return subConditions.join(' AND ');
138
- }
139
- else {
140
- // Simple equality for direct value
141
- params.push(subValue);
142
- return `json_extract(elements.value, '$.${subField}') = ?`;
143
- }
144
- })
145
- .join(' AND ');
146
- elemMatchSubquery += elemConditions;
147
- }
148
- else {
149
- // Simple equality check for the entire element
150
- params.push(subFilter);
151
- elemMatchSubquery += `elements.value = ?`;
152
- }
153
- elemMatchSubquery += ')';
154
- return `${checkArrayCondition} AND ${elemMatchSubquery}`;
155
- })
156
- .join(' AND ');
157
- conditions.push(`(${elemMatchConditions})`);
158
- }
159
- else {
160
- // Handle field conditions
161
- if (key.startsWith('$'))
162
- continue; // Skip logical operators already handled
163
- const value = filter[key];
164
- if (key === '_id') {
165
- if (typeof value === 'string') {
166
- conditions.push('_id = ?');
167
- params.push(value);
168
- }
169
- else if (typeof value === 'object' &&
170
- value !== null &&
171
- value.$in) {
172
- const inValues = value.$in;
173
- if (inValues.length > 0) {
174
- conditions.push(`_id IN (${inValues.map(() => '?').join(',')})`);
175
- params.push(...inValues);
176
- }
177
- else {
178
- conditions.push('1=0'); // No values in $in means nothing matches
179
- }
180
- }
181
- else if (typeof value === 'object' &&
182
- value !== null &&
183
- value.$ne) {
184
- conditions.push('_id <> ?');
185
- params.push(value.$ne);
186
- }
187
- // Add other _id specific operators if needed
188
- }
189
- else {
190
- const jsonPath = this.parseJsonPath(key);
191
- if (typeof value === 'object' && value !== null) {
192
- // Handle operators like $gt, $lt, $in, $exists, $not etc.
193
- for (const op in value) {
194
- const opValue = value[op];
195
- switch (op) {
196
- case '$eq':
197
- conditions.push(`json_extract(data, ${jsonPath}) = ?`);
198
- params.push(opValue);
199
- break;
200
- case '$ne':
201
- if (opValue === null) {
202
- conditions.push(`json_extract(data, ${jsonPath}) IS NOT NULL`);
203
- }
204
- else {
205
- conditions.push(`json_extract(data, ${jsonPath}) != ?`);
206
- params.push(opValue);
207
- }
208
- break;
209
- case '$gt':
210
- conditions.push(`json_extract(data, ${jsonPath}) > ?`);
211
- params.push(opValue);
212
- break;
213
- case '$gte':
214
- conditions.push(`json_extract(data, ${jsonPath}) >= ?`);
215
- params.push(opValue);
216
- break;
217
- case '$lt':
218
- conditions.push(`json_extract(data, ${jsonPath}) < ?`);
219
- params.push(opValue);
220
- break;
221
- case '$lte':
222
- conditions.push(`json_extract(data, ${jsonPath}) <= ?`);
223
- params.push(opValue);
224
- break;
225
- case '$in':
226
- if (Array.isArray(opValue) && opValue.length > 0) {
227
- const inConditions = opValue
228
- .map(() => `json_extract(data, ${jsonPath}) = ?`)
229
- .join(' OR ');
230
- conditions.push(`(${inConditions})`);
231
- opValue.forEach((val) => params.push(val));
232
- }
233
- else {
234
- conditions.push('1=0'); // Empty $in array, nothing will match
235
- }
236
- break;
237
- case '$nin':
238
- if (Array.isArray(opValue) && opValue.length > 0) {
239
- const ninConditions = opValue
240
- .map(() => `json_extract(data, ${jsonPath}) != ?`)
241
- .join(' AND ');
242
- conditions.push(`(${ninConditions})`);
243
- opValue.forEach((val) => params.push(val));
244
- }
245
- // Empty $nin array means match everything, so no condition needed
246
- break;
247
- case '$exists':
248
- if (opValue === true) {
249
- conditions.push(`json_extract(data, ${jsonPath}) IS NOT NULL`);
250
- }
251
- else {
252
- conditions.push(`json_extract(data, ${jsonPath}) IS NULL`);
253
- }
254
- break;
255
- case '$not':
256
- // Handle negation of conditions
257
- const notCondition = this.buildWhereClause({ [key]: opValue }, params);
258
- conditions.push(`NOT (${notCondition})`);
259
- break;
260
- case '$all':
261
- if (Array.isArray(opValue) && opValue.length > 0) {
262
- // Check if the field is an array
263
- const arrayTypeCheck = `json_type(json_extract(data, ${jsonPath})) = 'array'`;
264
- // For each value in the $all array, create a subquery to check if it exists in the array
265
- const allConditions = opValue
266
- .map(() => {
267
- return `EXISTS (SELECT 1 FROM json_each(json_extract(data, ${jsonPath})) WHERE json_each.value = ?)`;
268
- })
269
- .join(' AND ');
270
- conditions.push(`(${arrayTypeCheck} AND ${allConditions})`);
271
- opValue.forEach((val) => params.push(val));
272
- }
273
- else {
274
- conditions.push('1=0'); // Empty $all array, nothing will match
275
- }
276
- break;
277
- case '$elemMatch':
278
- // Handle array element match
279
- // For nested.items we need to check for conditions on the same array element
280
- // Build a query that checks if there's at least one array element that satisfies all conditions
281
- const arrayPath = this.parseJsonPath(key);
282
- let elemMatchSubquery = `EXISTS (
283
- SELECT 1
284
- FROM json_each(json_extract(data, ${arrayPath})) as array_elements
285
- WHERE `;
286
- // Process each condition in the $elemMatch
287
- if (typeof opValue === 'object' && opValue !== null) {
288
- const subConditions = Object.entries(opValue)
289
- .map(([sfKey, sfValue]) => {
290
- if (typeof sfValue === 'object' && sfValue !== null) {
291
- // Handle operators in the subfilter
292
- const subOpConditions = [];
293
- for (const op in sfValue) {
294
- const opVal = sfValue[op];
295
- switch (op) {
296
- case '$eq':
297
- subOpConditions.push(`json_extract(array_elements.value, '$.${sfKey}') = ?`);
298
- params.push(opVal);
299
- break;
300
- case '$gt':
301
- subOpConditions.push(`json_extract(array_elements.value, '$.${sfKey}') > ?`);
302
- params.push(opVal);
303
- break;
304
- case '$gte':
305
- subOpConditions.push(`json_extract(array_elements.value, '$.${sfKey}') >= ?`);
306
- params.push(opVal);
307
- break;
308
- case '$lt':
309
- subOpConditions.push(`json_extract(array_elements.value, '$.${sfKey}') < ?`);
310
- params.push(opVal);
311
- break;
312
- case '$lte':
313
- subOpConditions.push(`json_extract(array_elements.value, '$.${sfKey}') <= ?`);
314
- params.push(opVal);
315
- break;
316
- // Add other operators as needed
317
- }
318
- }
319
- return subOpConditions.join(' AND ');
320
- }
321
- else {
322
- // Simple equality for direct value
323
- params.push(sfValue);
324
- return `json_extract(array_elements.value, '$.${sfKey}') = ?`;
325
- }
326
- })
327
- .join(' AND ');
328
- elemMatchSubquery += subConditions;
329
- }
330
- else {
331
- // Simple equality check for the entire element
332
- params.push(opValue);
333
- elemMatchSubquery += `array_elements.value = ?`;
334
- }
335
- elemMatchSubquery += ')';
336
- conditions.push(elemMatchSubquery);
337
- break;
338
- // Add other operators as needed
339
- }
340
- }
341
- }
342
- else {
343
- // Direct equality for non-object values
344
- if (value === null) {
345
- conditions.push(`json_extract(data, ${jsonPath}) IS NULL`);
346
- }
347
- else {
348
- conditions.push(`json_extract(data, ${jsonPath}) = ?`);
349
- params.push(value);
350
- }
351
- }
352
- }
353
- }
354
- }
355
- return conditions.length > 0 ? conditions.join(' AND ') : '1=1';
356
- }
357
- }
358
- //# sourceMappingURL=query-builder.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-builder.js","sourceRoot":"","sources":["../src/query-builder.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,YAAY;IACvB,YAA6B,UAAiC,EAAE;QAAnC,YAAO,GAAP,OAAO,CAA4B;IAAG,CAAC;IAEpE;;OAEG;IACH,aAAa,CAAC,IAAY;QACxB,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC;IAC3C,CAAC;IAED;;;;;OAKG;IACH,gBAAgB,CAAC,MAAiB,EAAE,MAAiB;QACnD,MAAM,UAAU,GAAa,EAAE,CAAC;QAEhC,4DAA4D;QAC5D,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,GAAG,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;gBAClC,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;gBAC9B,MAAM,aAAa,GAAG,SAAS;qBAC5B,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC;qBACnE,IAAI,CAAC,OAAO,CAAC,CAAC;gBACjB,UAAU,CAAC,IAAI,CAAC,IAAI,aAAa,GAAG,CAAC,CAAC;YACxC,CAAC;iBAAM,IAAI,GAAG,KAAK,KAAK,IAAI,MAAM,CAAC,GAAG,EAAE,CAAC;gBACvC,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC;gBAC7B,MAAM,YAAY,GAAG,SAAS;qBAC3B,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC;qBACnE,IAAI,CAAC,MAAM,CAAC,CAAC;gBACh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CAAC;gDACN,mCAAmC;gDACnC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gDACrB,OAAO,yCAAyC,KAAK,QAAQ,CAAC;4CAChE,CAAC;wCACH,CAAC,CAAC;6CACD,IAAI,CAAC,OAAO,CAAC,CAAC;wCAEjB,iBAAiB,IAAI,aAAa,CAAC;oCACrC,CAAC;yCAAM,CAAC;wCACN,+CAA+C;wCAC/C,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;wCACrB,iBAAiB,IAAI,0BAA0B,CAAC;oCAClD,CAAC;oCAED,iBAAiB,IAAI,GAAG,CAAC;oCACzB,UAAU,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;oCACnC,MAAM;gCACR,gCAAgC;4BAClC,CAAC;wBACH,CAAC;oBACH,CAAC;yBAAM,CAAC;wBACN,wCAAwC;wBACxC,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;4BACnB,UAAU,CAAC,IAAI,CAAC,sBAAsB,QAAQ,WAAW,CAAC,CAAC;wBAC7D,CAAC;6BAAM,CAAC;4BACN,UAAU,CAAC,IAAI,CAAC,sBAAsB,QAAQ,OAAO,CAAC,CAAC;4BACvD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;wBACrB,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAClE,CAAC;CACF"}
@@ -1,17 +0,0 @@
1
- import { DocumentWithId, UpdateFilter } from './types.js';
2
- /**
3
- * Class to handle update operations on documents
4
- */
5
- export declare class UpdateOperationHandler<T extends DocumentWithId> {
6
- /**
7
- * Apply update operations to a document
8
- * @param doc The document to modify
9
- * @param update The update operations to apply
10
- * @returns Whether the document was modified
11
- */
12
- applyUpdateOperations(doc: Record<string, any>, update: UpdateFilter<T>): boolean;
13
- /**
14
- * Check if a value matches a filter condition
15
- */
16
- private matchesFilterValue;
17
- }
@@ -1,147 +0,0 @@
1
- import { getNestedValue, setNestedValue, unsetNestedValue } from './document-utils.js';
2
- /**
3
- * Class to handle update operations on documents
4
- */
5
- export class UpdateOperationHandler {
6
- /**
7
- * Apply update operations to a document
8
- * @param doc The document to modify
9
- * @param update The update operations to apply
10
- * @returns Whether the document was modified
11
- */
12
- applyUpdateOperations(doc, update) {
13
- let modified = false;
14
- // Process update operators
15
- for (const operator in update) {
16
- const opArgs = update[operator];
17
- if (!opArgs)
18
- continue;
19
- switch (operator) {
20
- case '$set':
21
- for (const path in opArgs) {
22
- const value = opArgs[path];
23
- setNestedValue(doc, path, value);
24
- modified = true;
25
- }
26
- break;
27
- case '$unset':
28
- for (const path in opArgs) {
29
- unsetNestedValue(doc, path);
30
- modified = true;
31
- }
32
- break;
33
- case '$inc':
34
- for (const path in opArgs) {
35
- const value = opArgs[path];
36
- if (typeof value === 'number') {
37
- const currentValue = getNestedValue(doc, path) || 0;
38
- if (typeof currentValue === 'number') {
39
- setNestedValue(doc, path, currentValue + value);
40
- modified = true;
41
- }
42
- }
43
- }
44
- break;
45
- case '$push':
46
- for (const path in opArgs) {
47
- const value = opArgs[path];
48
- const currentValue = getNestedValue(doc, path);
49
- if (Array.isArray(currentValue)) {
50
- if (typeof value === 'object' && value !== null && '$each' in value) {
51
- if (Array.isArray(value.$each)) {
52
- currentValue.push(...value.$each);
53
- modified = true;
54
- }
55
- }
56
- else {
57
- currentValue.push(value);
58
- modified = true;
59
- }
60
- }
61
- else if (currentValue === undefined) {
62
- // If the field doesn't exist, create it as an array
63
- if (typeof value === 'object' && value !== null && '$each' in value) {
64
- if (Array.isArray(value.$each)) {
65
- setNestedValue(doc, path, [...value.$each]);
66
- modified = true;
67
- }
68
- }
69
- else {
70
- setNestedValue(doc, path, [value]);
71
- modified = true;
72
- }
73
- }
74
- }
75
- break;
76
- case '$pull':
77
- for (const path in opArgs) {
78
- const value = opArgs[path];
79
- const currentValue = getNestedValue(doc, path);
80
- if (Array.isArray(currentValue)) {
81
- // Simple equality pull
82
- const newArray = currentValue.filter((item) => {
83
- if (typeof value === 'object' && value !== null) {
84
- // For objects, we need to check all criteria
85
- for (const key in value) {
86
- if (typeof item === 'object' &&
87
- item !== null &&
88
- !this.matchesFilterValue(item[key], value[key])) {
89
- return true; // Keep the item if it doesn't match the criteria
90
- }
91
- }
92
- return false; // Remove if all criteria match
93
- }
94
- else {
95
- // Simple equality check for primitives
96
- return item !== value;
97
- }
98
- });
99
- if (newArray.length !== currentValue.length) {
100
- setNestedValue(doc, path, newArray);
101
- modified = true;
102
- }
103
- }
104
- }
105
- break;
106
- }
107
- }
108
- return modified;
109
- }
110
- /**
111
- * Check if a value matches a filter condition
112
- */
113
- matchesFilterValue(value, condition) {
114
- if (typeof condition === 'object' && condition !== null) {
115
- // Check for operators
116
- // This is a simplified version, in a real implementation you'd handle many operators
117
- if ('$eq' in condition) {
118
- return value === condition.$eq;
119
- }
120
- else if ('$ne' in condition) {
121
- return value !== condition.$ne;
122
- }
123
- else if ('$gt' in condition) {
124
- return value > condition.$gt;
125
- }
126
- else if ('$gte' in condition) {
127
- return value >= condition.$gte;
128
- }
129
- else if ('$lt' in condition) {
130
- return value < condition.$lt;
131
- }
132
- else if ('$lte' in condition) {
133
- return value <= condition.$lte;
134
- }
135
- else if ('$in' in condition && Array.isArray(condition.$in)) {
136
- return condition.$in.includes(value);
137
- }
138
- else if ('$nin' in condition && Array.isArray(condition.$nin)) {
139
- return !condition.$nin.includes(value);
140
- }
141
- // For a complete implementation, handle more operators
142
- }
143
- // Default to simple equality
144
- return value === condition;
145
- }
146
- }
147
- //# sourceMappingURL=update-operations.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"update-operations.js","sourceRoot":"","sources":["../src/update-operations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,C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