@gravito/dark-matter 1.0.0 → 1.1.1

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/dist/index.d.ts CHANGED
@@ -272,6 +272,17 @@ interface GridFSFile {
272
272
  metadata?: Record<string, unknown>;
273
273
  contentType?: string;
274
274
  }
275
+ /**
276
+ * GridFS 上傳進度資訊
277
+ */
278
+ interface GridFSUploadProgress {
279
+ /** 已寫入的位元組數 */
280
+ bytesWritten: number;
281
+ /** 總位元組數(串流模式下可能為 0) */
282
+ totalBytes: number;
283
+ /** 完成百分比(0-100) */
284
+ percentage: number;
285
+ }
275
286
  /**
276
287
  * MongoDB Collection Contract
277
288
  */
@@ -308,6 +319,38 @@ interface MongoCollectionContract<T = Document$1> {
308
319
  deleteMany(): Promise<DeleteResult>;
309
320
  bulkWrite(operations: BulkWriteOperation<T>[]): Promise<BulkWriteResult>;
310
321
  watch(pipeline?: PipelineStage[], options?: ChangeStreamOptions): AsyncIterable<ChangeEvent<T>>;
322
+ /**
323
+ * 包含已軟刪除的記錄
324
+ */
325
+ withTrashed(): this;
326
+ /**
327
+ * 只查詢已軟刪除的記錄
328
+ */
329
+ onlyTrashed(): this;
330
+ /**
331
+ * 軟刪除單一記錄(設置 deletedAt)
332
+ */
333
+ softDelete(): Promise<UpdateResult>;
334
+ /**
335
+ * 批次軟刪除
336
+ */
337
+ softDeleteMany(): Promise<UpdateResult>;
338
+ /**
339
+ * 恢復軟刪除的記錄
340
+ */
341
+ restore(): Promise<UpdateResult>;
342
+ /**
343
+ * 批次恢復
344
+ */
345
+ restoreMany(): Promise<UpdateResult>;
346
+ /**
347
+ * 強制刪除(真正刪除記錄)
348
+ */
349
+ forceDelete(): Promise<DeleteResult>;
350
+ /**
351
+ * 批次強制刪除
352
+ */
353
+ forceDeleteMany(): Promise<DeleteResult>;
311
354
  aggregate(): MongoAggregateContract<T>;
312
355
  toFilter(): FilterDocument;
313
356
  clone(): MongoCollectionContract<T>;
@@ -370,6 +413,10 @@ interface MongoDatabaseContract {
370
413
  schema?: SchemaValidationOptions;
371
414
  }): Promise<void>;
372
415
  setValidation(collectionName: string, schema: SchemaValidationOptions): Promise<void>;
416
+ createCollectionWithSchema(name: string, schemaBuilder: unknown, options?: {
417
+ validationLevel?: 'off' | 'strict' | 'moderate';
418
+ validationAction?: 'error' | 'warn';
419
+ }): Promise<void>;
373
420
  }
374
421
  /**
375
422
  * Generic document type
@@ -378,6 +425,12 @@ interface Document$1 {
378
425
  _id?: string;
379
426
  [key: string]: unknown;
380
427
  }
428
+ /**
429
+ * 支援軟刪除的文檔類型
430
+ */
431
+ interface SoftDeletableDocument extends Document$1 {
432
+ deletedAt?: Date | null;
433
+ }
381
434
 
382
435
  /**
383
436
  * MongoDB Facade
@@ -711,6 +764,89 @@ declare class MongoGridFS {
711
764
  * ```
712
765
  */
713
766
  list(filter?: FilterDocument): Promise<GridFSFile[]>;
767
+ /**
768
+ * 串流上傳檔案
769
+ *
770
+ * 支援進度回調的串流上傳,適合大檔案上傳
771
+ *
772
+ * @param stream - ReadableStream 來源
773
+ * @param options - 上傳選項
774
+ * @param onProgress - 可選的進度回調函數
775
+ * @returns Promise 解析為檔案 ID
776
+ *
777
+ * @example
778
+ * ```typescript
779
+ * const stream = file.stream()
780
+ * const fileId = await grid.uploadStream(stream, {
781
+ * filename: 'video.mp4'
782
+ * }, (progress) => {
783
+ * console.log(`上傳進度: ${progress.percentage}%`)
784
+ * })
785
+ * ```
786
+ */
787
+ uploadStream(stream: ReadableStream<Uint8Array>, options: GridFSUploadOptions, onProgress?: (progress: GridFSUploadProgress) => void): Promise<string>;
788
+ /**
789
+ * 串流下載檔案
790
+ *
791
+ * 返回 ReadableStream 以支援大檔案的串流下載
792
+ *
793
+ * @param fileId - 檔案 ID
794
+ * @returns ReadableStream 提供檔案內容
795
+ *
796
+ * @example
797
+ * ```typescript
798
+ * const stream = grid.downloadStream(fileId)
799
+ * const reader = stream.getReader()
800
+ *
801
+ * while (true) {
802
+ * const { done, value } = await reader.read()
803
+ * if (done) break
804
+ * // 處理 chunk
805
+ * }
806
+ * ```
807
+ */
808
+ downloadStream(fileId: string): ReadableStream<Uint8Array>;
809
+ /**
810
+ * 分片上傳大檔案
811
+ *
812
+ * 支援進度追蹤的大檔案上傳,自動處理分片
813
+ *
814
+ * @param file - Blob 或 File 物件
815
+ * @param options - 上傳選項
816
+ * @param onProgress - 可選的進度回調函數
817
+ * @returns Promise 解析為檔案 ID
818
+ *
819
+ * @example
820
+ * ```typescript
821
+ * const fileId = await grid.uploadLargeFile(file, {
822
+ * filename: 'large-video.mp4',
823
+ * chunkSizeBytes: 255 * 1024 // 255 KB
824
+ * }, (progress) => {
825
+ * console.log(`進度: ${progress.percentage}%`)
826
+ * console.log(`已上傳: ${progress.bytesWritten} / ${progress.totalBytes}`)
827
+ * })
828
+ * ```
829
+ */
830
+ uploadLargeFile(file: Blob | File, options: GridFSUploadOptions, onProgress?: (progress: GridFSUploadProgress) => void): Promise<string>;
831
+ /**
832
+ * 取得檔案中繼資料
833
+ *
834
+ * 查詢檔案資訊但不下載內容
835
+ *
836
+ * @param fileId - 檔案 ID
837
+ * @returns Promise 解析為檔案中繼資料,找不到時返回 null
838
+ *
839
+ * @example
840
+ * ```typescript
841
+ * const fileInfo = await grid.findById(fileId)
842
+ * if (fileInfo) {
843
+ * console.log(`檔案名稱: ${fileInfo.filename}`)
844
+ * console.log(`檔案大小: ${fileInfo.length} bytes`)
845
+ * console.log(`上傳日期: ${fileInfo.uploadDate}`)
846
+ * }
847
+ * ```
848
+ */
849
+ findById(fileId: string): Promise<GridFSFile | null>;
714
850
  private ensureBucket;
715
851
  }
716
852
 
@@ -898,6 +1034,7 @@ declare class MongoQueryBuilder<T = Document> implements MongoCollectionContract
898
1034
  private sortSpec;
899
1035
  private limitCount;
900
1036
  private skipCount;
1037
+ private softDeleteMode;
901
1038
  constructor(nativeCollection: MongoNativeCollection, collectionName: string, session?: unknown | undefined);
902
1039
  /**
903
1040
  * Adds a basic WHERE clause to the query.
@@ -1320,6 +1457,110 @@ declare class MongoQueryBuilder<T = Document> implements MongoCollectionContract
1320
1457
  * ```
1321
1458
  */
1322
1459
  deleteMany(): Promise<DeleteResult>;
1460
+ /**
1461
+ * 包含已軟刪除的記錄
1462
+ *
1463
+ * 查詢時包含所有記錄,不過濾已刪除的文檔
1464
+ *
1465
+ * @returns 當前查詢建構器實例,支援鏈式調用
1466
+ *
1467
+ * @example
1468
+ * ```typescript
1469
+ * const allUsers = await query.withTrashed().get();
1470
+ * ```
1471
+ */
1472
+ withTrashed(): this;
1473
+ /**
1474
+ * 只查詢已軟刪除的記錄
1475
+ *
1476
+ * 只返回 deletedAt 不為 null 的文檔
1477
+ *
1478
+ * @returns 當前查詢建構器實例,支援鏈式調用
1479
+ *
1480
+ * @example
1481
+ * ```typescript
1482
+ * const trashedUsers = await query.onlyTrashed().get();
1483
+ * ```
1484
+ */
1485
+ onlyTrashed(): this;
1486
+ /**
1487
+ * 軟刪除單一記錄
1488
+ *
1489
+ * 設置 deletedAt 為當前時間,而非真正刪除記錄
1490
+ *
1491
+ * @returns Promise 解析為更新結果
1492
+ *
1493
+ * @example
1494
+ * ```typescript
1495
+ * await query.where('_id', userId).softDelete();
1496
+ * ```
1497
+ */
1498
+ softDelete(): Promise<UpdateResult>;
1499
+ /**
1500
+ * 批次軟刪除
1501
+ *
1502
+ * 設置所有符合條件的文檔的 deletedAt 為當前時間
1503
+ *
1504
+ * @returns Promise 解析為更新結果
1505
+ *
1506
+ * @example
1507
+ * ```typescript
1508
+ * await query.where('status', 'inactive').softDeleteMany();
1509
+ * ```
1510
+ */
1511
+ softDeleteMany(): Promise<UpdateResult>;
1512
+ /**
1513
+ * 恢復軟刪除的記錄
1514
+ *
1515
+ * 將 deletedAt 設置為 null,恢復軟刪除的文檔
1516
+ *
1517
+ * @returns Promise 解析為更新結果
1518
+ *
1519
+ * @example
1520
+ * ```typescript
1521
+ * await query.where('_id', userId).restore();
1522
+ * ```
1523
+ */
1524
+ restore(): Promise<UpdateResult>;
1525
+ /**
1526
+ * 批次恢復軟刪除的記錄
1527
+ *
1528
+ * 將所有符合條件的文檔的 deletedAt 設置為 null
1529
+ *
1530
+ * @returns Promise 解析為更新結果
1531
+ *
1532
+ * @example
1533
+ * ```typescript
1534
+ * await query.onlyTrashed().restoreMany();
1535
+ * ```
1536
+ */
1537
+ restoreMany(): Promise<UpdateResult>;
1538
+ /**
1539
+ * 強制刪除(真正刪除記錄)
1540
+ *
1541
+ * 永久刪除單一文檔,無法恢復
1542
+ *
1543
+ * @returns Promise 解析為刪除結果
1544
+ *
1545
+ * @example
1546
+ * ```typescript
1547
+ * await query.where('_id', userId).forceDelete();
1548
+ * ```
1549
+ */
1550
+ forceDelete(): Promise<DeleteResult>;
1551
+ /**
1552
+ * 批次強制刪除
1553
+ *
1554
+ * 永久刪除所有符合條件的文檔,無法恢復
1555
+ *
1556
+ * @returns Promise 解析為刪除結果
1557
+ *
1558
+ * @example
1559
+ * ```typescript
1560
+ * await query.where('createdAt', '<', oneYearAgo).forceDeleteMany();
1561
+ * ```
1562
+ */
1563
+ forceDeleteMany(): Promise<DeleteResult>;
1323
1564
  /**
1324
1565
  * Executes a bulk write operation.
1325
1566
  *
@@ -1402,6 +1643,15 @@ declare class MongoQueryBuilder<T = Document> implements MongoCollectionContract
1402
1643
  clone(): MongoCollectionContract<T>;
1403
1644
  private mapOperator;
1404
1645
  private normalizeUpdate;
1646
+ /**
1647
+ * 應用軟刪除過濾
1648
+ *
1649
+ * 根據 softDeleteMode 自動過濾已刪除的記錄
1650
+ *
1651
+ * @param filter - 基礎過濾條件
1652
+ * @returns 包含軟刪除過濾的完整過濾條件
1653
+ */
1654
+ private applySoftDeleteFilter;
1405
1655
  private getObjectId;
1406
1656
  }
1407
1657
  /**
@@ -1492,4 +1742,215 @@ interface MongoUpdateResult {
1492
1742
  upsertedId?: MongoObjectId;
1493
1743
  }
1494
1744
 
1495
- export { type BulkWriteOperation, type BulkWriteResult, type DeleteResult, type Document$1 as Document, type FilterDocument, type FilterOperator, type GridFSFile, type GridFSUploadOptions, type InsertManyResult, type InsertResult, type LookupOptions, Mongo, MongoAggregateBuilder, type MongoAggregateContract, MongoClient, type MongoClientContract, type MongoCollectionContract, type MongoConfig, type MongoDatabaseContract, MongoGridFS, MongoManager, type MongoManagerConfig, MongoPoolMonitor, MongoQueryBuilder, type MongoSession, type PipelineStage, type PoolMetrics, type Projection, type RetryConfig, type SortDirection, type SortSpec, type TransactionOptions, type UpdateDocument, type UpdateResult };
1745
+ /**
1746
+ * MongoDB Schema Builder
1747
+ * @description 提供型別安全的 Schema 定義 API
1748
+ */
1749
+
1750
+ /**
1751
+ * MongoDB Schema Builder
1752
+ *
1753
+ * 提供友善的 API 來建構 MongoDB JSON Schema 驗證規則
1754
+ *
1755
+ * @example
1756
+ * ```typescript
1757
+ * const userSchema = schema()
1758
+ * .required('username', 'email')
1759
+ * .string('username', { minLength: 3, maxLength: 50 })
1760
+ * .string('email', { pattern: '^.+@.+$' })
1761
+ * .integer('age', { minimum: 0, maximum: 150 })
1762
+ * .boolean('isActive')
1763
+ * .date('createdAt')
1764
+ * .array('roles', 'string', { minItems: 1 })
1765
+ * .object('profile', (s) =>
1766
+ * s.string('bio', { maxLength: 500 }).string('avatar')
1767
+ * )
1768
+ * ```
1769
+ */
1770
+ declare class MongoSchemaBuilder {
1771
+ private schema;
1772
+ /**
1773
+ * 定義必填欄位
1774
+ *
1775
+ * @param fields - 必填欄位名稱列表
1776
+ * @returns 當前 Schema Builder 實例
1777
+ *
1778
+ * @example
1779
+ * ```typescript
1780
+ * schema().required('name', 'email', 'age')
1781
+ * ```
1782
+ */
1783
+ required(...fields: string[]): this;
1784
+ /**
1785
+ * 定義字串欄位
1786
+ *
1787
+ * @param field - 欄位名稱
1788
+ * @param options - 字串選項(長度、模式、枚舉等)
1789
+ * @returns 當前 Schema Builder 實例
1790
+ *
1791
+ * @example
1792
+ * ```typescript
1793
+ * schema()
1794
+ * .string('username', { minLength: 3, maxLength: 50 })
1795
+ * .string('email', { pattern: '^.+@.+$' })
1796
+ * .string('status', { enum: ['active', 'inactive'] })
1797
+ * ```
1798
+ */
1799
+ string(field: string, options?: {
1800
+ minLength?: number;
1801
+ maxLength?: number;
1802
+ pattern?: string;
1803
+ enum?: string[];
1804
+ }): this;
1805
+ /**
1806
+ * 定義數字欄位
1807
+ *
1808
+ * @param field - 欄位名稱
1809
+ * @param options - 數字選項(最小值、最大值等)
1810
+ * @returns 當前 Schema Builder 實例
1811
+ *
1812
+ * @example
1813
+ * ```typescript
1814
+ * schema()
1815
+ * .number('price', { minimum: 0, maximum: 10000 })
1816
+ * .number('discount', { minimum: 0, maximum: 1, exclusiveMaximum: true })
1817
+ * ```
1818
+ */
1819
+ number(field: string, options?: {
1820
+ minimum?: number;
1821
+ maximum?: number;
1822
+ exclusiveMinimum?: boolean;
1823
+ exclusiveMaximum?: boolean;
1824
+ }): this;
1825
+ /**
1826
+ * 定義整數欄位
1827
+ *
1828
+ * @param field - 欄位名稱
1829
+ * @param options - 整數選項(最小值、最大值)
1830
+ * @returns 當前 Schema Builder 實例
1831
+ *
1832
+ * @example
1833
+ * ```typescript
1834
+ * schema()
1835
+ * .integer('age', { minimum: 0, maximum: 150 })
1836
+ * .integer('count')
1837
+ * ```
1838
+ */
1839
+ integer(field: string, options?: {
1840
+ minimum?: number;
1841
+ maximum?: number;
1842
+ }): this;
1843
+ /**
1844
+ * 定義布林欄位
1845
+ *
1846
+ * @param field - 欄位名稱
1847
+ * @returns 當前 Schema Builder 實例
1848
+ *
1849
+ * @example
1850
+ * ```typescript
1851
+ * schema().boolean('isActive').boolean('verified')
1852
+ * ```
1853
+ */
1854
+ boolean(field: string): this;
1855
+ /**
1856
+ * 定義日期欄位
1857
+ *
1858
+ * @param field - 欄位名稱
1859
+ * @returns 當前 Schema Builder 實例
1860
+ *
1861
+ * @example
1862
+ * ```typescript
1863
+ * schema().date('createdAt').date('updatedAt')
1864
+ * ```
1865
+ */
1866
+ date(field: string): this;
1867
+ /**
1868
+ * 定義陣列欄位
1869
+ *
1870
+ * @param field - 欄位名稱
1871
+ * @param itemType - 陣列元素類型
1872
+ * @param options - 陣列選項(長度、唯一性等)
1873
+ * @returns 當前 Schema Builder 實例
1874
+ *
1875
+ * @example
1876
+ * ```typescript
1877
+ * schema()
1878
+ * .array('tags', 'string')
1879
+ * .array('scores', 'number')
1880
+ * .array('roles', 'string', { minItems: 1, uniqueItems: true })
1881
+ * ```
1882
+ */
1883
+ array(field: string, itemType: 'string' | 'number' | 'object' | 'int' | 'bool' | 'date', options?: {
1884
+ minItems?: number;
1885
+ maxItems?: number;
1886
+ uniqueItems?: boolean;
1887
+ }): this;
1888
+ /**
1889
+ * 定義物件欄位
1890
+ *
1891
+ * @param field - 欄位名稱
1892
+ * @param callback - 巢狀 Schema 建構函數
1893
+ * @returns 當前 Schema Builder 實例
1894
+ *
1895
+ * @example
1896
+ * ```typescript
1897
+ * schema().object('profile', (s) =>
1898
+ * s
1899
+ * .string('bio', { maxLength: 500 })
1900
+ * .string('avatar')
1901
+ * .integer('followers')
1902
+ * )
1903
+ * ```
1904
+ */
1905
+ object(field: string, callback: (builder: MongoSchemaBuilder) => void): this;
1906
+ /**
1907
+ * 建構最終的 JSON Schema
1908
+ *
1909
+ * @returns JSON Schema 物件
1910
+ *
1911
+ * @example
1912
+ * ```typescript
1913
+ * const schema = schema()
1914
+ * .required('name')
1915
+ * .string('name')
1916
+ * .build()
1917
+ * ```
1918
+ */
1919
+ build(): Record<string, unknown>;
1920
+ /**
1921
+ * 轉換為 MongoDB 驗證選項
1922
+ *
1923
+ * @param options - 驗證選項(驗證等級、動作)
1924
+ * @returns MongoDB Schema 驗證選項
1925
+ *
1926
+ * @example
1927
+ * ```typescript
1928
+ * const options = schema()
1929
+ * .required('name')
1930
+ * .string('name')
1931
+ * .toValidationOptions({ validationLevel: 'moderate' })
1932
+ * ```
1933
+ */
1934
+ toValidationOptions(options?: {
1935
+ validationLevel?: 'off' | 'strict' | 'moderate';
1936
+ validationAction?: 'error' | 'warn';
1937
+ }): SchemaValidationOptions;
1938
+ }
1939
+ /**
1940
+ * 建立 Schema Builder 實例
1941
+ *
1942
+ * @returns 新的 MongoSchemaBuilder 實例
1943
+ *
1944
+ * @example
1945
+ * ```typescript
1946
+ * import { schema } from '@gravito/dark-matter'
1947
+ *
1948
+ * const userSchema = schema()
1949
+ * .required('name', 'email')
1950
+ * .string('name')
1951
+ * .string('email')
1952
+ * ```
1953
+ */
1954
+ declare function schema(): MongoSchemaBuilder;
1955
+
1956
+ export { type BulkWriteOperation, type BulkWriteResult, type DeleteResult, type Document$1 as Document, type FilterDocument, type FilterOperator, type GridFSFile, type GridFSUploadOptions, type GridFSUploadProgress, type InsertManyResult, type InsertResult, type LookupOptions, Mongo, MongoAggregateBuilder, type MongoAggregateContract, MongoClient, type MongoClientContract, type MongoCollectionContract, type MongoConfig, type MongoDatabaseContract, MongoGridFS, MongoManager, type MongoManagerConfig, MongoPoolMonitor, MongoQueryBuilder, MongoSchemaBuilder, type MongoSession, type PipelineStage, type PoolMetrics, type Projection, type RetryConfig, type SchemaValidationOptions, type SoftDeletableDocument, type SortDirection, type SortSpec, type TransactionOptions, type UpdateDocument, type UpdateResult, schema };