t1y-sdk-js 5.0.0 → 5.0.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/README.md +106 -1
- package/README.zh-CN.md +106 -1
- package/dist/index.d.mts +84 -2
- package/dist/index.d.ts +84 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/umd/t1y.min.js +2 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
[t1yOS](https://www.t1y.net) Serverless Platform JavaScript/TypeScript SDK — cloud database, metadata, and cloud functions client.
|
|
6
6
|
|
|
7
|
+
## Platform Support
|
|
8
|
+
|
|
9
|
+
| Platform | Supported | Transport API | Notes |
|
|
10
|
+
| ----------------------------------- | --------- | --------------- | -------------------------------- |
|
|
11
|
+
| Web / Vue / React / HTML | ✅ | `fetch` | Modern browsers |
|
|
12
|
+
| Node.js | ✅ | `fetch` (18+) | Via native `fetch` API |
|
|
13
|
+
| WeChat Mini Program(微信小程序) | ✅ | `wx.request` | Auto-detected |
|
|
14
|
+
| QQ Mini Program(QQ 小程序) | ✅ | `qq.request` | Auto-detected as WeChat family |
|
|
15
|
+
| Toutiao Mini Program(头条小程序) | ✅ | `tt.request` | Auto-detected as WeChat family |
|
|
16
|
+
| Douyin Mini Program(抖音小程序) | ✅ | `tt.request` | Auto-detected as WeChat family |
|
|
17
|
+
| Alipay Mini Program(支付宝小程序) | ✅ | `my.request` | Auto-detected |
|
|
18
|
+
| Quick App(快应用) | ✅ | `@system.fetch` | Via build-time module resolution |
|
|
19
|
+
|
|
20
|
+
> **Note:** The SDK automatically detects the runtime environment and uses the appropriate request API. No manual configuration is needed — the same code works across all platforms.
|
|
21
|
+
|
|
7
22
|
## Installation
|
|
8
23
|
|
|
9
24
|
### npm / pnpm / yarn
|
|
@@ -25,6 +40,65 @@ yarn add t1y-sdk-js
|
|
|
25
40
|
</script>
|
|
26
41
|
```
|
|
27
42
|
|
|
43
|
+
### Mini Program(小程序)
|
|
44
|
+
|
|
45
|
+
**WeChat / QQ / Toutiao / Douyin Mini Programs:**
|
|
46
|
+
|
|
47
|
+
1. Install via npm in your mini program project:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install t1y-sdk-js
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
2. Build the npm package in the mini program IDE:
|
|
54
|
+
- WeChat: `Tools → Build npm`
|
|
55
|
+
- QQ / Toutiao / Douyin: Similar option in their respective IDEs
|
|
56
|
+
|
|
57
|
+
3. Import and use:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { T1YOS, timeNow } from 't1y-sdk-js'
|
|
61
|
+
|
|
62
|
+
const client = new T1YOS({
|
|
63
|
+
appId: 1001,
|
|
64
|
+
apiKey: 'your-api-key-32-characters',
|
|
65
|
+
secretKey: 'your-secret-key-32-characters',
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
await client.init()
|
|
69
|
+
// ... use database operations
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
> **Note:** Mini programs require `baseUrl` to be configured in the mini program's **domain allowlist** (服务器域名白名单). Go to the mini program admin panel → Development → Server Domain, and add your t1yOS domain (e.g., `https://myapp.t1y.net`).
|
|
73
|
+
|
|
74
|
+
**Alipay Mini Program:**
|
|
75
|
+
|
|
76
|
+
Same as above — the SDK auto-detects the Alipay environment and uses `my.request` instead of `wx.request`. Configure the domain allowlist in the Alipay Developer Console.
|
|
77
|
+
|
|
78
|
+
### Quick App(快应用)
|
|
79
|
+
|
|
80
|
+
1. Install via npm:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
npm install t1y-sdk-js
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
2. Import and use in your Quick App project:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { T1YOS } from 't1y-sdk-js'
|
|
90
|
+
|
|
91
|
+
const client = new T1YOS({
|
|
92
|
+
appId: 1001,
|
|
93
|
+
apiKey: 'your-api-key-32-characters',
|
|
94
|
+
secretKey: 'your-secret-key-32-characters',
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
await client.init()
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
> **Note:** Quick App's hap-toolkit will automatically resolve the `@system.fetch` module dependency during build. No additional configuration is required.
|
|
101
|
+
|
|
28
102
|
## Quick Start
|
|
29
103
|
|
|
30
104
|
```ts
|
|
@@ -262,6 +336,37 @@ signature = HMAC-SHA256(secretKey, message)
|
|
|
262
336
|
|
|
263
337
|
When safe mode is enabled (via `isSafeMode: true` or auto-detected from init), request bodies are encrypted with AES-256-GCM using your SecretKey, and server responses are decrypted automatically.
|
|
264
338
|
|
|
339
|
+
## Platform Detection
|
|
340
|
+
|
|
341
|
+
The SDK exposes utilities to detect the current runtime environment:
|
|
342
|
+
|
|
343
|
+
```ts
|
|
344
|
+
import { getPlatformType, getMiniProgramSubType } from 't1y-sdk-js'
|
|
345
|
+
|
|
346
|
+
// Returns 'h5' | 'wx' | 'my' | 'hap' | 'nodejs' | 'unknown'
|
|
347
|
+
const platform = getPlatformType()
|
|
348
|
+
|
|
349
|
+
// Within the 'wx' family, returns 'wechat' | 'qq' | 'toutiao' | 'unknown'
|
|
350
|
+
const subType = getMiniProgramSubType()
|
|
351
|
+
|
|
352
|
+
console.log(platform) // e.g., 'wx' in WeChat Mini Program
|
|
353
|
+
console.log(subType) // e.g., 'toutiao' in Toutiao Mini Program
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
### Crypto Availability
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { isAESGCMAvailable, isWebCryptoAvailable } from 't1y-sdk-js'
|
|
360
|
+
|
|
361
|
+
// Always returns true — pure-JS AES-256-GCM fallback is always available
|
|
362
|
+
console.log(isAESGCMAvailable()) // true
|
|
363
|
+
|
|
364
|
+
// Check if the faster native Web Crypto API is available
|
|
365
|
+
console.log(isWebCryptoAvailable()) // true in browsers/Node.js, false in mini programs
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
The SDK uses **Web Crypto API** when available (faster, hardware-accelerated in browsers/Node.js), and automatically falls back to a **pure JavaScript AES-256-GCM** implementation in environments without Web Crypto (mini programs, Quick App). This ensures safe mode encryption works on all platforms.
|
|
369
|
+
|
|
265
370
|
## API Reference
|
|
266
371
|
|
|
267
372
|
### T1YOS
|
|
@@ -310,4 +415,4 @@ T1YOS `db` object also provides:
|
|
|
310
415
|
|
|
311
416
|
MIT
|
|
312
417
|
|
|
313
|
-
Copyright (c)
|
|
418
|
+
Copyright (c) 2026 华易云联(杭州)网络科技有限责任公司
|
package/README.zh-CN.md
CHANGED
|
@@ -4,6 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
[t1yOS](https://www.t1y.net) Serverless 平台 JavaScript/TypeScript SDK — 云数据库、元数据和云函数客户端。
|
|
6
6
|
|
|
7
|
+
## 平台支持
|
|
8
|
+
|
|
9
|
+
| 平台 | 支持 | 传输 API | 说明 |
|
|
10
|
+
| ------------------------ | ---- | --------------- | -------------------------- |
|
|
11
|
+
| Web / Vue / React / HTML | ✅ | `fetch` | 现代浏览器 |
|
|
12
|
+
| Node.js | ✅ | `fetch` (18+) | 使用原生 `fetch` API |
|
|
13
|
+
| 微信小程序 | ✅ | `wx.request` | 自动检测 |
|
|
14
|
+
| QQ 小程序 | ✅ | `qq.request` | 自动检测(微信小程序系列) |
|
|
15
|
+
| 头条小程序 | ✅ | `tt.request` | 自动检测(微信小程序系列) |
|
|
16
|
+
| 抖音小程序 | ✅ | `tt.request` | 自动检测(微信小程序系列) |
|
|
17
|
+
| 支付宝小程序 | ✅ | `my.request` | 自动检测 |
|
|
18
|
+
| 快应用 | ✅ | `@system.fetch` | 构建时模块解析 |
|
|
19
|
+
|
|
20
|
+
> **注意:** SDK 会自动检测运行环境并使用对应的请求 API,无需手动配置——同一套代码在所有平台都能运行。
|
|
21
|
+
|
|
7
22
|
## 安装
|
|
8
23
|
|
|
9
24
|
### npm / pnpm / yarn
|
|
@@ -25,6 +40,65 @@ yarn add t1y-sdk-js
|
|
|
25
40
|
</script>
|
|
26
41
|
```
|
|
27
42
|
|
|
43
|
+
### 小程序
|
|
44
|
+
|
|
45
|
+
**微信 / QQ / 头条 / 抖音小程序:**
|
|
46
|
+
|
|
47
|
+
1. 在小程序项目中通过 npm 安装:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install t1y-sdk-js
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
2. 在开发者工具中构建 npm:
|
|
54
|
+
- 微信:`工具 → 构建 npm`
|
|
55
|
+
- QQ / 头条 / 抖音:在各自开发者工具中类似操作
|
|
56
|
+
|
|
57
|
+
3. 引入并使用:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { T1YOS, timeNow } from 't1y-sdk-js'
|
|
61
|
+
|
|
62
|
+
const client = new T1YOS({
|
|
63
|
+
appId: 1001,
|
|
64
|
+
apiKey: '32位API-Key',
|
|
65
|
+
secretKey: '32位Secret-Key',
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
await client.init()
|
|
69
|
+
// ... 使用数据库操作
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
> **注意:** 小程序需要将 `baseUrl` 配置到**服务器域名白名单**中。前往小程序管理后台 → 开发 → 服务器域名,添加你的 t1yOS 域名(例如 `https://myapp.t1y.net`)。
|
|
73
|
+
|
|
74
|
+
**支付宝小程序:**
|
|
75
|
+
|
|
76
|
+
操作同上——SDK 会自动检测支付宝环境并使用 `my.request` 代替 `wx.request`。在支付宝开发者控制台中配置域名白名单即可。
|
|
77
|
+
|
|
78
|
+
### 快应用
|
|
79
|
+
|
|
80
|
+
1. 通过 npm 安装:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
npm install t1y-sdk-js
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
2. 在快应用项目中引入并使用:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { T1YOS } from 't1y-sdk-js'
|
|
90
|
+
|
|
91
|
+
const client = new T1YOS({
|
|
92
|
+
appId: 1001,
|
|
93
|
+
apiKey: '32位API-Key',
|
|
94
|
+
secretKey: '32位Secret-Key',
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
await client.init()
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
> **注意:** 快应用的 hap-toolkit 会在构建时自动解析 `@system.fetch` 模块依赖,无需额外配置。
|
|
101
|
+
|
|
28
102
|
## 快速开始
|
|
29
103
|
|
|
30
104
|
```ts
|
|
@@ -262,6 +336,37 @@ signature = HMAC-SHA256(secretKey, message)
|
|
|
262
336
|
|
|
263
337
|
当启用安全模式时(通过 `isSafeMode: true` 或初始化时自动检测),请求体将使用 AES-256-GCM 加密,密钥为应用的 SecretKey,服务端响应也会自动解密。
|
|
264
338
|
|
|
339
|
+
## 平台检测
|
|
340
|
+
|
|
341
|
+
SDK 暴露了检测当前运行环境的工具函数:
|
|
342
|
+
|
|
343
|
+
```ts
|
|
344
|
+
import { getPlatformType, getMiniProgramSubType } from 't1y-sdk-js'
|
|
345
|
+
|
|
346
|
+
// 返回 'h5' | 'wx' | 'my' | 'hap' | 'nodejs' | 'unknown'
|
|
347
|
+
const platform = getPlatformType()
|
|
348
|
+
|
|
349
|
+
// 在 'wx' 系列中,返回 'wechat' | 'qq' | 'toutiao' | 'unknown'
|
|
350
|
+
const subType = getMiniProgramSubType()
|
|
351
|
+
|
|
352
|
+
console.log(platform) // 例如在微信小程序中输出 'wx'
|
|
353
|
+
console.log(subType) // 例如在头条小程序中输出 'toutiao'
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
### 加密可用性检测
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { isAESGCMAvailable, isWebCryptoAvailable } from 't1y-sdk-js'
|
|
360
|
+
|
|
361
|
+
// 始终返回 true——纯 JS AES-256-GCM 降级方案始终可用
|
|
362
|
+
console.log(isAESGCMAvailable()) // true
|
|
363
|
+
|
|
364
|
+
// 检测是否有更快的原生 Web Crypto API(硬件加速)
|
|
365
|
+
console.log(isWebCryptoAvailable()) // 浏览器/Node.js 中为 true,小程序中为 false
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
SDK 优先使用 **Web Crypto API**(在浏览器/Node.js 中更快、硬件加速),在没有 Web Crypto 的环境(小程序、快应用)中自动降级为**纯 JavaScript AES-256-GCM** 实现。这确保安全模式加密在所有平台上都能正常工作。
|
|
369
|
+
|
|
265
370
|
## API 参考
|
|
266
371
|
|
|
267
372
|
### T1YOS
|
|
@@ -310,4 +415,4 @@ T1YOS `db` 对象还提供:
|
|
|
310
415
|
|
|
311
416
|
MIT
|
|
312
417
|
|
|
313
|
-
Copyright (c)
|
|
418
|
+
Copyright (c) 2026 华易云联(杭州)网络科技有限责任公司
|
package/dist/index.d.mts
CHANGED
|
@@ -751,8 +751,23 @@ declare function verifyHmacSHA256(secret: string, message: string, signature: st
|
|
|
751
751
|
* Compatible with the t1yOS Go server's AES-256-GCM implementation.
|
|
752
752
|
* Payload format: { "n": "<nonce base64>", "j": "<ciphertext base64>", "t": "<tag base64>" }
|
|
753
753
|
*
|
|
754
|
-
*
|
|
754
|
+
* Uses Web Crypto API when available (Web browsers, Node.js), with automatic
|
|
755
|
+
* fallback to pure-JS implementation for environments without Web Crypto
|
|
756
|
+
* (WeChat/QQ/Alipay Mini Programs, Quick App, etc.).
|
|
755
757
|
*/
|
|
758
|
+
/**
|
|
759
|
+
* Check whether AES-256-GCM encryption/decryption is available in the current environment.
|
|
760
|
+
*
|
|
761
|
+
* Web Crypto API is available in modern browsers and Node.js.
|
|
762
|
+
* In mini programs (WeChat/QQ/Alipay) and Quick App, the pure-JS fallback is used.
|
|
763
|
+
*
|
|
764
|
+
* @returns `true` if AES-256-GCM is available (always true since we have pure-JS fallback)
|
|
765
|
+
*/
|
|
766
|
+
declare function isAESGCMAvailable(): boolean;
|
|
767
|
+
/**
|
|
768
|
+
* Check whether the native Web Crypto API is available (faster than pure-JS fallback).
|
|
769
|
+
*/
|
|
770
|
+
declare function isWebCryptoAvailable(): boolean;
|
|
756
771
|
/**
|
|
757
772
|
* AES-256-GCM encrypted payload structure.
|
|
758
773
|
* Matches the Go server's AESGCMEncryptedPayload struct.
|
|
@@ -768,6 +783,9 @@ interface AESGCMPayload {
|
|
|
768
783
|
/**
|
|
769
784
|
* Encrypt data using AES-256-GCM.
|
|
770
785
|
*
|
|
786
|
+
* Uses Web Crypto API when available (faster), falls back to pure-JS
|
|
787
|
+
* implementation in environments without Web Crypto (mini programs, Quick App).
|
|
788
|
+
*
|
|
771
789
|
* @param data - The plaintext data to encrypt (string)
|
|
772
790
|
* @param keyBytes - 32-byte encryption key (Uint8Array)
|
|
773
791
|
* @returns JSON string of { n, j, t } payload
|
|
@@ -776,6 +794,9 @@ declare function encryptAESGCM(data: string, keyBytes: Uint8Array): Promise<stri
|
|
|
776
794
|
/**
|
|
777
795
|
* Decrypt data using AES-256-GCM.
|
|
778
796
|
*
|
|
797
|
+
* Uses Web Crypto API when available (faster), falls back to pure-JS
|
|
798
|
+
* implementation in environments without Web Crypto (mini programs, Quick App).
|
|
799
|
+
*
|
|
779
800
|
* @param jsonPayload - JSON string of { n, j, t } payload
|
|
780
801
|
* @param keyBytes - 32-byte decryption key (Uint8Array)
|
|
781
802
|
* @returns Decrypted plaintext string
|
|
@@ -917,4 +938,65 @@ declare function isNonEmptyArrayWithNonEmptyObjects(value: unknown): boolean;
|
|
|
917
938
|
*/
|
|
918
939
|
declare function formatTimestampsToLocal(data: unknown, format?: string): unknown;
|
|
919
940
|
|
|
920
|
-
|
|
941
|
+
/**
|
|
942
|
+
* Platform detection module.
|
|
943
|
+
*
|
|
944
|
+
* Detects the current runtime environment and returns a platform type identifier.
|
|
945
|
+
* This enables the SDK to use the correct network request API for each platform:
|
|
946
|
+
*
|
|
947
|
+
* | Platform | Type | Request API | Global Object |
|
|
948
|
+
* |-----------------------|----------|--------------------|---------------|
|
|
949
|
+
* | WeChat Mini Program | `wx` | `wx.request` | `wx` |
|
|
950
|
+
* | QQ Mini Program | `wx` | `qq.request` | `qq` |
|
|
951
|
+
* | Toutiao/Douyin Mini | `wx` | `tt.request` | `tt` |
|
|
952
|
+
* | Alipay Mini Program | `my` | `my.request` | `my` |
|
|
953
|
+
* | Quick App | `hap` | `@system.fetch` | — |
|
|
954
|
+
* | Web / Vue / React | `h5` | `fetch` | `window` |
|
|
955
|
+
* | Node.js | `nodejs` | `fetch` (18+) | `process` |
|
|
956
|
+
*/
|
|
957
|
+
/** Platform type identifiers */
|
|
958
|
+
type PlatformType = 'wx' | 'my' | 'hap' | 'h5' | 'nodejs' | 'unknown';
|
|
959
|
+
/** Mini program sub-type within the `wx` platform family */
|
|
960
|
+
type MiniProgramSubType = 'wechat' | 'qq' | 'toutiao' | 'unknown';
|
|
961
|
+
/**
|
|
962
|
+
* Detect the current platform type.
|
|
963
|
+
*
|
|
964
|
+
* Detection order (from most specific to least):
|
|
965
|
+
* 1. WeChat/QQ/Toutiao/Douyin Mini Programs — global `wx`/`qq`/`tt` object
|
|
966
|
+
* 2. Alipay Mini Program — global `my` object
|
|
967
|
+
* 3. Quick App — no `window`, no `wx`, but has device info via special flag
|
|
968
|
+
* 4. Web / H5 — global `window` and `document`
|
|
969
|
+
* 5. Node.js — global `process` without `window`
|
|
970
|
+
*
|
|
971
|
+
* @returns The detected platform type
|
|
972
|
+
*/
|
|
973
|
+
declare function getPlatformType(): PlatformType;
|
|
974
|
+
/**
|
|
975
|
+
* Detect the mini program sub-type (only meaningful when platform is `wx`).
|
|
976
|
+
*
|
|
977
|
+
* | Sub-type | Global Object | Notes |
|
|
978
|
+
* |------------|---------------|----------------------------------------|
|
|
979
|
+
* | `toutiao` | `tt` | Toutiao/Douyin Mini Program |
|
|
980
|
+
* | `qq` | `qq` | QQ Mini Program |
|
|
981
|
+
* | `wechat` | `wx` | WeChat Mini Program (default for `wx`) |
|
|
982
|
+
*
|
|
983
|
+
* @returns The detected mini program sub-type
|
|
984
|
+
*/
|
|
985
|
+
declare function getMiniProgramSubType(): MiniProgramSubType;
|
|
986
|
+
/**
|
|
987
|
+
* Get the global API object for mini programs.
|
|
988
|
+
*
|
|
989
|
+
* Returns the appropriate global object based on the detected platform:
|
|
990
|
+
* - WeChat: `wx`
|
|
991
|
+
* - QQ: `qq`
|
|
992
|
+
* - Toutiao/Douyin: `tt`
|
|
993
|
+
*
|
|
994
|
+
* @returns The mini program global API object, or `null` if not in a mini program
|
|
995
|
+
*/
|
|
996
|
+
declare function getMiniProgramAPI(): Record<string, unknown> | null;
|
|
997
|
+
/**
|
|
998
|
+
* Reset cached platform detection (useful for testing).
|
|
999
|
+
*/
|
|
1000
|
+
declare function resetPlatformDetection(): void;
|
|
1001
|
+
|
|
1002
|
+
export { type AESGCMPayload, type AggregateResult, type ApiResponse, Array_ as Array, type ArrayMarker, Bigint, type BigintMarker, Boolean_ as Boolean, type BooleanMarker, Date_ as Date, type DateMarker, DateTime, type DateTimeMarker, type DeleteManyResult, type DeleteResult, Double, type DoubleMarker, Empty, type FindResult, Float, type FloatMarker, type HttpMethod, type InitResult, type InsertManyResult, type InsertResult, Integer, type IntegerMarker, Map_ as Map, MapArray, type MapArrayMarker, type MapMarker, type MiniProgramSubType, Nil, None, Null, type NullMarker, ObjectID, type ObjectIDMarker, type Pagination, type PaginationResult, type PlatformType, type SignatureInput, type SpecialTypeMarker, T1Collection, T1YError, T1YOS, type T1YOSConfig, type T1YOSInternalConfig, TimeNow, type TimeNowMarker, TimeNowUnix, type TimeNowUnixMarker, TimeNowUnixNano, type TimeNowUnixNanoMarker, TimeNowWeekday, TimeNowWeekdayChinese, type TimeNowWeekdayChineseMarker, type TimeNowWeekdayMarker, Timestamp, type TimestampMarker, UNDEFINED, Undefined, type UndefinedMarker, type UpdateManyResult, type UpdateResult, ValidationError, assertObjectID, convertDateTypes, createSignature, decryptAESGCM, T1YOS as default, encryptAESGCM, formatTimestampsToLocal, getMiniProgramAPI, getMiniProgramSubType, getPlatformType, getSafeTimestamp, hmacSHA256Hex, hmacSHA256HexAsync, isAESGCMAvailable, isNonEmptyArrayWithNonEmptyObjects, isNonEmptyObject, isPlainObject, isWebCryptoAvailable, resetPlatformDetection, sha256Hex, sha256HexAsync, timeNow, validateApiKey, validateAppId, validateBaseUrl, validateInitConfig, validateSecretKey, verifyHmacSHA256 };
|
package/dist/index.d.ts
CHANGED
|
@@ -751,8 +751,23 @@ declare function verifyHmacSHA256(secret: string, message: string, signature: st
|
|
|
751
751
|
* Compatible with the t1yOS Go server's AES-256-GCM implementation.
|
|
752
752
|
* Payload format: { "n": "<nonce base64>", "j": "<ciphertext base64>", "t": "<tag base64>" }
|
|
753
753
|
*
|
|
754
|
-
*
|
|
754
|
+
* Uses Web Crypto API when available (Web browsers, Node.js), with automatic
|
|
755
|
+
* fallback to pure-JS implementation for environments without Web Crypto
|
|
756
|
+
* (WeChat/QQ/Alipay Mini Programs, Quick App, etc.).
|
|
755
757
|
*/
|
|
758
|
+
/**
|
|
759
|
+
* Check whether AES-256-GCM encryption/decryption is available in the current environment.
|
|
760
|
+
*
|
|
761
|
+
* Web Crypto API is available in modern browsers and Node.js.
|
|
762
|
+
* In mini programs (WeChat/QQ/Alipay) and Quick App, the pure-JS fallback is used.
|
|
763
|
+
*
|
|
764
|
+
* @returns `true` if AES-256-GCM is available (always true since we have pure-JS fallback)
|
|
765
|
+
*/
|
|
766
|
+
declare function isAESGCMAvailable(): boolean;
|
|
767
|
+
/**
|
|
768
|
+
* Check whether the native Web Crypto API is available (faster than pure-JS fallback).
|
|
769
|
+
*/
|
|
770
|
+
declare function isWebCryptoAvailable(): boolean;
|
|
756
771
|
/**
|
|
757
772
|
* AES-256-GCM encrypted payload structure.
|
|
758
773
|
* Matches the Go server's AESGCMEncryptedPayload struct.
|
|
@@ -768,6 +783,9 @@ interface AESGCMPayload {
|
|
|
768
783
|
/**
|
|
769
784
|
* Encrypt data using AES-256-GCM.
|
|
770
785
|
*
|
|
786
|
+
* Uses Web Crypto API when available (faster), falls back to pure-JS
|
|
787
|
+
* implementation in environments without Web Crypto (mini programs, Quick App).
|
|
788
|
+
*
|
|
771
789
|
* @param data - The plaintext data to encrypt (string)
|
|
772
790
|
* @param keyBytes - 32-byte encryption key (Uint8Array)
|
|
773
791
|
* @returns JSON string of { n, j, t } payload
|
|
@@ -776,6 +794,9 @@ declare function encryptAESGCM(data: string, keyBytes: Uint8Array): Promise<stri
|
|
|
776
794
|
/**
|
|
777
795
|
* Decrypt data using AES-256-GCM.
|
|
778
796
|
*
|
|
797
|
+
* Uses Web Crypto API when available (faster), falls back to pure-JS
|
|
798
|
+
* implementation in environments without Web Crypto (mini programs, Quick App).
|
|
799
|
+
*
|
|
779
800
|
* @param jsonPayload - JSON string of { n, j, t } payload
|
|
780
801
|
* @param keyBytes - 32-byte decryption key (Uint8Array)
|
|
781
802
|
* @returns Decrypted plaintext string
|
|
@@ -917,4 +938,65 @@ declare function isNonEmptyArrayWithNonEmptyObjects(value: unknown): boolean;
|
|
|
917
938
|
*/
|
|
918
939
|
declare function formatTimestampsToLocal(data: unknown, format?: string): unknown;
|
|
919
940
|
|
|
920
|
-
|
|
941
|
+
/**
|
|
942
|
+
* Platform detection module.
|
|
943
|
+
*
|
|
944
|
+
* Detects the current runtime environment and returns a platform type identifier.
|
|
945
|
+
* This enables the SDK to use the correct network request API for each platform:
|
|
946
|
+
*
|
|
947
|
+
* | Platform | Type | Request API | Global Object |
|
|
948
|
+
* |-----------------------|----------|--------------------|---------------|
|
|
949
|
+
* | WeChat Mini Program | `wx` | `wx.request` | `wx` |
|
|
950
|
+
* | QQ Mini Program | `wx` | `qq.request` | `qq` |
|
|
951
|
+
* | Toutiao/Douyin Mini | `wx` | `tt.request` | `tt` |
|
|
952
|
+
* | Alipay Mini Program | `my` | `my.request` | `my` |
|
|
953
|
+
* | Quick App | `hap` | `@system.fetch` | — |
|
|
954
|
+
* | Web / Vue / React | `h5` | `fetch` | `window` |
|
|
955
|
+
* | Node.js | `nodejs` | `fetch` (18+) | `process` |
|
|
956
|
+
*/
|
|
957
|
+
/** Platform type identifiers */
|
|
958
|
+
type PlatformType = 'wx' | 'my' | 'hap' | 'h5' | 'nodejs' | 'unknown';
|
|
959
|
+
/** Mini program sub-type within the `wx` platform family */
|
|
960
|
+
type MiniProgramSubType = 'wechat' | 'qq' | 'toutiao' | 'unknown';
|
|
961
|
+
/**
|
|
962
|
+
* Detect the current platform type.
|
|
963
|
+
*
|
|
964
|
+
* Detection order (from most specific to least):
|
|
965
|
+
* 1. WeChat/QQ/Toutiao/Douyin Mini Programs — global `wx`/`qq`/`tt` object
|
|
966
|
+
* 2. Alipay Mini Program — global `my` object
|
|
967
|
+
* 3. Quick App — no `window`, no `wx`, but has device info via special flag
|
|
968
|
+
* 4. Web / H5 — global `window` and `document`
|
|
969
|
+
* 5. Node.js — global `process` without `window`
|
|
970
|
+
*
|
|
971
|
+
* @returns The detected platform type
|
|
972
|
+
*/
|
|
973
|
+
declare function getPlatformType(): PlatformType;
|
|
974
|
+
/**
|
|
975
|
+
* Detect the mini program sub-type (only meaningful when platform is `wx`).
|
|
976
|
+
*
|
|
977
|
+
* | Sub-type | Global Object | Notes |
|
|
978
|
+
* |------------|---------------|----------------------------------------|
|
|
979
|
+
* | `toutiao` | `tt` | Toutiao/Douyin Mini Program |
|
|
980
|
+
* | `qq` | `qq` | QQ Mini Program |
|
|
981
|
+
* | `wechat` | `wx` | WeChat Mini Program (default for `wx`) |
|
|
982
|
+
*
|
|
983
|
+
* @returns The detected mini program sub-type
|
|
984
|
+
*/
|
|
985
|
+
declare function getMiniProgramSubType(): MiniProgramSubType;
|
|
986
|
+
/**
|
|
987
|
+
* Get the global API object for mini programs.
|
|
988
|
+
*
|
|
989
|
+
* Returns the appropriate global object based on the detected platform:
|
|
990
|
+
* - WeChat: `wx`
|
|
991
|
+
* - QQ: `qq`
|
|
992
|
+
* - Toutiao/Douyin: `tt`
|
|
993
|
+
*
|
|
994
|
+
* @returns The mini program global API object, or `null` if not in a mini program
|
|
995
|
+
*/
|
|
996
|
+
declare function getMiniProgramAPI(): Record<string, unknown> | null;
|
|
997
|
+
/**
|
|
998
|
+
* Reset cached platform detection (useful for testing).
|
|
999
|
+
*/
|
|
1000
|
+
declare function resetPlatformDetection(): void;
|
|
1001
|
+
|
|
1002
|
+
export { type AESGCMPayload, type AggregateResult, type ApiResponse, Array_ as Array, type ArrayMarker, Bigint, type BigintMarker, Boolean_ as Boolean, type BooleanMarker, Date_ as Date, type DateMarker, DateTime, type DateTimeMarker, type DeleteManyResult, type DeleteResult, Double, type DoubleMarker, Empty, type FindResult, Float, type FloatMarker, type HttpMethod, type InitResult, type InsertManyResult, type InsertResult, Integer, type IntegerMarker, Map_ as Map, MapArray, type MapArrayMarker, type MapMarker, type MiniProgramSubType, Nil, None, Null, type NullMarker, ObjectID, type ObjectIDMarker, type Pagination, type PaginationResult, type PlatformType, type SignatureInput, type SpecialTypeMarker, T1Collection, T1YError, T1YOS, type T1YOSConfig, type T1YOSInternalConfig, TimeNow, type TimeNowMarker, TimeNowUnix, type TimeNowUnixMarker, TimeNowUnixNano, type TimeNowUnixNanoMarker, TimeNowWeekday, TimeNowWeekdayChinese, type TimeNowWeekdayChineseMarker, type TimeNowWeekdayMarker, Timestamp, type TimestampMarker, UNDEFINED, Undefined, type UndefinedMarker, type UpdateManyResult, type UpdateResult, ValidationError, assertObjectID, convertDateTypes, createSignature, decryptAESGCM, T1YOS as default, encryptAESGCM, formatTimestampsToLocal, getMiniProgramAPI, getMiniProgramSubType, getPlatformType, getSafeTimestamp, hmacSHA256Hex, hmacSHA256HexAsync, isAESGCMAvailable, isNonEmptyArrayWithNonEmptyObjects, isNonEmptyObject, isPlainObject, isWebCryptoAvailable, resetPlatformDetection, sha256Hex, sha256HexAsync, timeNow, validateApiKey, validateAppId, validateBaseUrl, validateInitConfig, validateSecretKey, verifyHmacSHA256 };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var ee=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var ze=Object.prototype.hasOwnProperty;var Ue=e=>{throw TypeError(e)};var et=(e,t)=>{for(var n in t)ee(e,n,{get:t[n],enumerable:!0})},tt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xe(t))!ze.call(e,o)&&o!==n&&ee(e,o,{get:()=>t[o],enumerable:!(r=Qe(t,o))||r.enumerable});return e};var nt=e=>tt(ee({},"__esModule",{value:!0}),e);var rt=(e,t,n)=>t.has(e)||Ue("Cannot "+n);var Ie=(e,t,n)=>t.has(e)?Ue("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var k=(e,t,n)=>(rt(e,t,"access private method"),n);var lt={};et(lt,{Array:()=>de,Bigint:()=>ye,Boolean:()=>ue,Date:()=>ae,DateTime:()=>ce,Double:()=>le,Empty:()=>Ae,Float:()=>me,Integer:()=>fe,Map:()=>ge,MapArray:()=>he,Nil:()=>be,None:()=>we,Null:()=>xe,ObjectID:()=>ie,T1Collection:()=>N,T1YError:()=>h,T1YOS:()=>v,TimeNow:()=>J,TimeNowUnix:()=>Z,TimeNowUnixNano:()=>V,TimeNowWeekday:()=>Q,TimeNowWeekdayChinese:()=>X,Timestamp:()=>pe,UNDEFINED:()=>Te,Undefined:()=>Ee,ValidationError:()=>y,assertObjectID:()=>b,convertDateTypes:()=>S,createSignature:()=>H,decryptAESGCM:()=>B,default:()=>We,encryptAESGCM:()=>_,formatTimestampsToLocal:()=>M,getSafeTimestamp:()=>$,hmacSHA256Hex:()=>E,hmacSHA256HexAsync:()=>ne,isNonEmptyArrayWithNonEmptyObjects:()=>U,isNonEmptyObject:()=>l,isPlainObject:()=>x,sha256Hex:()=>D,sha256HexAsync:()=>te,timeNow:()=>Re,validateApiKey:()=>G,validateAppId:()=>K,validateBaseUrl:()=>W,validateInitConfig:()=>C,validateSecretKey:()=>Y,verifyHmacSHA256:()=>j});module.exports=nt(lt);var Oe="https://myapp.t1y.net";var F="YYYY-MM-DD HH:mm:ss";var q=/^[0-9a-fA-F]{24}$/;var h=class extends Error{constructor(t,n,r){super(n),this.name="T1YError",this.code=t,this.data=r}toJSON(){return{name:this.name,code:this.code,message:this.message,data:this.data}}},y=class extends Error{constructor(t){super(t),this.name="ValidationError"}};function K(e){if(!Number.isInteger(e))throw new y("appId must be an integer");if(e<1001)throw new y(`appId must be >= ${1001}`)}function G(e){if(typeof e!="string")throw new y("apiKey must be a string");if(e.length!==32)throw new y(`apiKey must be exactly ${32} characters (got ${e.length})`)}function Y(e){if(typeof e!="string")throw new y("secretKey must be a string");if(e.length!==32)throw new y(`secretKey must be exactly ${32} characters (got ${e.length})`)}function W(e){if(!/^https?:\/\//.test(e))throw new y('baseUrl must start with "http://" or "https://"')}function C(e){if(e.baseUrl!==void 0&&W(e.baseUrl),K(e.appId),G(e.apiKey),Y(e.secretKey),e.version!==void 0&&(!Number.isInteger(e.version)||e.version<0))throw new y("version must be a non-negative integer")}function b(e,t="ObjectID"){if(typeof e!="string")throw new y(`${t} must be a string`);if(!q.test(e))throw new y(`Invalid ${t} string: "${e}"`);return!0}function S(e){if(e instanceof Date)return`Date('${e.toISOString()}')`;if(typeof e=="number"){let t=String(e);return/^\d{10,}$/.test(t)?`Timestamp('${t}')`:e}if(Array.isArray(e))return e.map(t=>S(t));if(e&&typeof e=="object"){let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=S(e[n]));return t}return e}function l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function U(e){return!Array.isArray(e)||e.length===0?!1:e.every(t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0)}function Ce(){try{if(typeof require<"u")return require}catch{}return null}function D(e){let t=Ce();if(t)try{return t("node:crypto").createHash("sha256").update(e).digest("hex")}catch{}let n=ot(e);return P(n)}function P(e){return st(e)}async function te(e){let t=Ce();if(t)try{return t("node:crypto").createHash("sha256").update(e).digest("hex")}catch{}let n=new TextEncoder,r=await crypto.subtle.digest("SHA-256",n.encode(e));return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}function ot(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)t.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let o=e.charCodeAt(n),i=65536+((r&1023)<<10)+(o&1023);t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63)}}return new Uint8Array(t)}function st(e){let t=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=e.length,r=n*8,o=(64-(n+9)%64)%64,i=n+1+o+8,c=new Uint8Array(i);c.set(e),c[n]=128;for(let a=0;a<8;a++)c[i-8+a]=Number(BigInt(r)>>BigInt((7-a)*8)&BigInt(255));let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let a=0;a<i;a+=64){let u=new Array(64);for(let p=0;p<16;p++)u[p]=c[a+p*4]<<24|c[a+p*4+1]<<16|c[a+p*4+2]<<8|c[a+p*4+3];for(let p=16;p<64;p++){let g=(A(u[p-15],7)^A(u[p-15],18)^u[p-15]>>>3)>>>0,z=(A(u[p-2],17)^A(u[p-2],19)^u[p-2]>>>10)>>>0;u[p]=u[p-16]+g+u[p-7]+z>>>0}let[f,d,m,I,w,O,R,L]=s;for(let p=0;p<64;p++){let g=(A(w,6)^A(w,11)^A(w,25))>>>0,z=(w&O^~w&R)>>>0,Se=L+g+z+t[p]+u[p]>>>0,Je=(A(f,2)^A(f,13)^A(f,22))>>>0,Ze=(f&d^f&m^d&m)>>>0,Ve=Je+Ze>>>0;L=R,R=O,O=w,w=I+Se>>>0,I=m,m=d,d=f,f=Se+Ve>>>0}s[0]=s[0]+f>>>0,s[1]=s[1]+d>>>0,s[2]=s[2]+m>>>0,s[3]=s[3]+I>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+O>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+L>>>0}return s.map(a=>a.toString(16).padStart(8,"0")).join("")}function A(e,t){return e>>>t|e<<32-t}function _e(){try{if(typeof require<"u")return require}catch{}return null}function E(e,t){let n=_e();if(n)try{return n("node:crypto").createHmac("sha256",e).update(t).digest("hex")}catch{}return at(e,t)}async function ne(e,t){let n=_e();if(n)try{return n("node:crypto").createHmac("sha256",e).update(t).digest("hex")}catch{}let r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,r.encode(t));return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}function j(e,t,n){if(typeof n!="string")return!1;let r=E(e,t);return it(r,n.toLowerCase())}function it(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function at(e,t){let r=Pe(e),o=Pe(t);r.length>64&&(r=je(P(r)));let i=new Uint8Array(64);i.set(r.subarray(0,Math.min(r.length,64)));let c=new Uint8Array(64);c.fill(54);let s=De(i,c),a=new Uint8Array(64+o.length);a.set(s),a.set(o,64);let u=je(P(a)),f=new Uint8Array(64);f.fill(92);let d=De(i,f),m=new Uint8Array(64+u.length);return m.set(d),m.set(u,64),P(m)}function De(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function Pe(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)t.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let o=e.charCodeAt(n),i=65536+((r&1023)<<10)+(o&1023);t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63)}}return new Uint8Array(t)}function je(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}function He(){if(typeof globalThis<"u"){if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle)return globalThis.crypto;try{let e=globalThis.require?globalThis.require("node:crypto"):null;if(e?.webcrypto)return e.webcrypto}catch{}}throw new Error("Web Crypto API is not available in this environment")}var Be=16,ct=12;function re(e){let t="",n=e.byteLength;for(let r=0;r<n;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function oe(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let o=0;o<n;o++)r[o]=t.charCodeAt(o);return r}async function _(e,t){if(!(t instanceof Uint8Array))throw new Error("key must be Uint8Array");if(t.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");let n=He(),r=await n.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt"]),o=new Uint8Array(ct);n.getRandomValues(o);let i=new TextEncoder().encode(e),c=new Uint8Array(await n.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},r,i)),s=c.slice(0,c.length-Be),a=c.slice(c.length-Be),u={n:re(o),j:re(s),t:re(a)};return JSON.stringify(u)}async function B(e,t){if(!(t instanceof Uint8Array))throw new Error("key must be Uint8Array");if(t.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");let n=He(),{n:r,j:o,t:i}=JSON.parse(e),c=oe(r),s=oe(o),a=oe(i),u=new Uint8Array(s.length+a.length);u.set(s),u.set(a,s.length);let f=await n.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]),d=await n.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},f,u);return new TextDecoder().decode(d)}function H(e){let{method:t,pathAndQuery:n,body:r,appId:o,timestamp:i,secretKey:c}=e,s=D(r),a=[t.toUpperCase(),n,s,String(o),String(i)].join(`
|
|
2
|
-
`);return E(c,a)}function $(e){return String(Math.floor(Date.now()/1e3)+e)}function $e(e){return e.replace(/\/+$/,"")}function ve(e,t){for(let n of Object.keys(t)){let r=t[n];r!=null&&e.searchParams.set(n,typeof r=="string"?r:JSON.stringify(r))}}function pt(e,t){let n=new Date(e);if(isNaN(n.getTime()))return e;let r=o=>String(o).padStart(2,"0");return t.replace("YYYY",String(n.getFullYear())).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))}function M(e,t=F){function n(r){if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let o={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(i==="createdAt"||i==="updatedAt"?o[i]=pt(r[i],t):o[i]=n(r[i]));return o}return r}return n(e)}async function Le(e,t,n,r){let o,i=e.headers.get("content-type")||"",c=await e.text();if(i.includes("application/json"))try{o=JSON.parse(c)}catch{o=c}else o=c;if(t&&o&&typeof o=="object"&&"j"in o)try{let s=await B(JSON.stringify(o),new TextEncoder().encode(n));try{o=JSON.parse(s)}catch{o=s}}catch(s){throw new h(400,"AES-256-GCM decryption failed",s instanceof Error?s.message:null)}if(o&&typeof o=="object"&&"data"in o){let s=o;if(s.data=M(s.data,r),!e.ok)throw new h(s.code||e.status,s.message||e.statusText,s.data);return s}if(!e.ok)throw new h(e.status,e.statusText,o);return{code:0,message:"ok",data:M(o,r)}}function Fe(e){if(e&&typeof e=="object"&&"response"in e){let t=e;throw e}throw e instanceof h?e:e instanceof Error?e.name==="AbortError"?new h(408,"Request timeout",null):new h(0,e.message,null):new h(0,"Unknown error",e)}async function se(e,t){let{method:n,path:r,params:o,encryption:i,timeout:c}=t,s=$e(e.baseUrl),a=i??e.isSafeMode,u=new URL(s+r),f=S(o),d,m="";if(n!=="GET")if(a&&f!==void 0){let g=await _(JSON.stringify(f),new TextEncoder().encode(e.secretKey));d=g,m=g}else if(f!==void 0){let g=JSON.stringify(f);d=g,m=g}else m="";else f&&typeof f=="object"&&Object.keys(f).length>0&&ve(u,f);let I=Number($(e.offset)),w=u.pathname+u.search,O=H({method:n,pathAndQuery:w,body:m,appId:e.appId,timestamp:I,secretKey:e.secretKey}),R=new AbortController,p=setTimeout(()=>R.abort(),c??3e5);try{let g=await fetch(u.toString(),{method:n,headers:{"X-T1Y-Application-ID":String(e.appId),"X-T1Y-API-Key":e.apiKey,"X-T1Y-Safe-Timestamp":String(I),"X-T1Y-Safe-Sign":O,"Content-Type":"application/json"},body:n!=="GET"?d:void 0,signal:R.signal});return clearTimeout(p),await Le(g,a,e.secretKey,e.timeFormat)}catch(g){return clearTimeout(p),Fe(g)}}var N=class{constructor(t,n){this.client=t,this.name=n}async insertOne(t){if(!l(t))throw new TypeError("insertOne data must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}`,t)}async deleteById(t){return b(t),await this.client.request("DELETE",`/v5/classes/${this.name}/${t}`)}async updateById(t,n){if(b(t),!l(n))throw new TypeError("update data must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/${t}`,n)}async findById(t){return b(t),await this.client.request("GET",`/v5/classes/${this.name}/${t}`)}async deleteOne(t){if(!l(t))throw new TypeError("deleteOne filter must be a non-empty plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/one`,t)}async updateOne(t,n){if(!l(t))throw new TypeError("updateOne filter must be a non-empty plain object");if(!l(n))throw new TypeError("updateOne body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/one`,{filter:t,body:n})}async findOne(t){if(!l(t))throw new TypeError("findOne filter must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}/one`,t)}async insertMany(t){if(!U(t))throw new TypeError("insertMany dataList must be a non-empty array of non-empty plain objects");return await this.client.request("POST",`/v5/classes/${this.name}/many`,t)}async deleteMany(t){if(!x(t))throw new TypeError("deleteMany filter must be a plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/many`,t)}async updateMany(t,n){if(!x(t))throw new TypeError("updateMany filter must be a plain object");if(!l(n))throw new TypeError("updateMany body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/many`,{filter:t,body:n})}async find(t=1,n=10,r={createdAt:-1},o={}){if(!Number.isInteger(t)||t<1)throw new TypeError("find page must be a positive integer");if(!Number.isInteger(n)||n<1)throw new TypeError("find size must be a positive integer");if(n>100&&(n=100),!l(r))throw new TypeError("find sort must be a non-empty plain object");if(!x(o))throw new TypeError("find filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/find`,{page:t,size:n,sort:r,filter:o})}async aggregate(t){if(!Array.isArray(t))throw new TypeError("aggregate pipeline must be an array");return await this.client.request("POST",`/v5/classes/${this.name}/aggregate`,t)}async count(t={}){if(!x(t))throw new TypeError("count filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/count`,t)}async distinct(t,n={}){if(typeof t!="string"||t.length===0)throw new TypeError("distinct fieldName must be a non-empty string");if(!x(n))throw new TypeError("distinct filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/distinct/${encodeURIComponent(t)}`,n)}async create(){return await this.client.request("POST",`/v5/schemas/${encodeURIComponent(this.name)}`)}async clear(){return await this.client.request("PUT",`/v5/schemas/${encodeURIComponent(this.name)}`)}async drop(){return await this.client.request("DELETE",`/v5/schemas/${encodeURIComponent(this.name)}`)}};var T,qe,Ke,Ge,Ye,v=class{constructor(t){Ie(this,T);C(t),this.config={baseUrl:t.baseUrl??Oe,appId:t.appId,apiKey:t.apiKey,secretKey:t.secretKey,version:t.version??0,isSafeMode:t.isSafeMode??!1,timeFormat:t.timeFormat??F,offset:t.offset??0},this.db={collection:n=>k(this,T,qe).call(this,n),toObjectID:n=>k(this,T,Ge).call(this,n),getCollections:()=>k(this,T,Ke).call(this)}}async init(){try{let n=(await this.request("GET",`/init/${this.config.appId}`,void 0,!1)).data;this.config.isSafeMode=n.is_safe_mode,this.config.offset=n.unix-Math.floor(Date.now()/1e3)}catch(t){console.warn("Failed to get time offset from server, defaulting to 0. Error:",t),this.config.isSafeMode=!1,this.config.offset=0}}async getMeta(t){if(t!==void 0&&t!==""&&typeof t!="string")throw new TypeError("Meta field must be a string");let n=t?`?field=${encodeURIComponent(t)}`:"";return await this.request("GET",`/v5/meta${n}`)}async checkUpdate(){try{return(await this.request("GET","/v5/meta?field=version")).data.result>this.config.version}catch{return!1}}async callFunc(t,n=null,r){if(typeof t!="string")throw new TypeError("Function name must be a string");return await this.request("POST",`/${this.config.appId}/${k(this,T,Ye).call(this,t)}`,n,r)}async request(t,n,r,o){if(typeof n!="string")throw new TypeError("request path must be a string");return await se(this.config,{method:t,path:n,params:r,encryption:o??this.config.isSafeMode})}assertObjectID(t,n="ObjectID"){return b(t,n)}isNonEmptyObject(t){return l(t)}isPlainObject(t){return x(t)}isNonEmptyArrayWithNonEmptyObjects(t){return U(t)}hmacSHA256(t,n){return E(t,n)}verifyHmacSHA256(t,n,r){return j(t,n,r)}};T=new WeakSet,qe=function(t){if(typeof t!="string")throw new TypeError("Collection name must be a string");return new N(this,t)},Ke=async function(){return await this.request("GET","/v5/schemas")},Ge=function(t){return b(t),`ObjectID('${t}')`},Ye=function(t){let n=t.startsWith("/")?t.slice(1):t,r=n.indexOf("#"),o=r!==-1?n.slice(r):"",i=r!==-1?n.slice(0,r):n,c=i.indexOf("?"),s=c!==-1?i.slice(c):"",a=c!==-1?i.slice(0,c):i;return a.endsWith("/")?a=a+"index.jsc":a.endsWith(".jsc")||(a.endsWith(".js")?a=a.replace(/\.js$/,".jsc"):a=a+".jsc"),a+s+o};var We=v;function ie(e){if(!q.test(e))throw new Error(`Invalid ObjectID: "${e}" (must be 24 hex characters)`);return`ObjectID('${e}')`}function ae(e){return`Date('${e}')`}function ce(e){return`DateTime('${e}')`}function pe(e){return`Timestamp('${String(e)}')`}function ue(e){return`Boolean(${e})`}function fe(e){return`Integer(${e})`}function ye(e){return`Bigint(${Number(e)})`}function me(e){return`Float(${e})`}function le(e){return`Double(${e})`}function de(e){return`Array(${JSON.stringify(e)})`}function ge(e){return`Map(${JSON.stringify(e)})`}function he(e){return`Map[](${JSON.stringify(e)})`}var xe="Null",we="None",be="Nil",Ae="",Te="UNDEFINED",Ee="Undefined";var J="time.Now()",Z="time.Now().Unix()",V="time.Now().UnixNano()",Q="time.Now().Weekday()",X="time.Now().Weekday().Chinese()",Re={Now:()=>J,NowUnix:()=>Z,NowUnixNano:()=>V,NowWeekday:()=>Q,NowWeekdayChinese:()=>X};0&&(module.exports={Array,Bigint,Boolean,Date,DateTime,Double,Empty,Float,Integer,Map,MapArray,Nil,None,Null,ObjectID,T1Collection,T1YError,T1YOS,TimeNow,TimeNowUnix,TimeNowUnixNano,TimeNowWeekday,TimeNowWeekdayChinese,Timestamp,UNDEFINED,Undefined,ValidationError,assertObjectID,convertDateTypes,createSignature,decryptAESGCM,encryptAESGCM,formatTimestampsToLocal,getSafeTimestamp,hmacSHA256Hex,hmacSHA256HexAsync,isNonEmptyArrayWithNonEmptyObjects,isNonEmptyObject,isPlainObject,sha256Hex,sha256HexAsync,timeNow,validateApiKey,validateAppId,validateBaseUrl,validateInitConfig,validateSecretKey,verifyHmacSHA256});
|
|
1
|
+
"use strict";var le=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Ke=t=>{throw TypeError(t)};var Ct=(t,e)=>{for(var n in e)le(t,n,{get:e[n],enumerable:!0})},It=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Mt(e))!Ot.call(t,a)&&a!==n&&le(t,a,{get:()=>e[a],enumerable:!(r=Pt(e,a))||r.enumerable});return t};var qt=t=>It(le({},"__esModule",{value:!0}),t);var Nt=(t,e,n)=>e.has(t)||Ke("Cannot "+n);var We=(t,e,n)=>e.has(t)?Ke("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);var _=(t,e,n)=>(Nt(t,e,"access private method"),n);var Xt={};Ct(Xt,{Array:()=>Ne,Bigint:()=>Ce,Boolean:()=>Me,Date:()=>Ue,DateTime:()=>ke,Double:()=>qe,Empty:()=>He,Float:()=>Ie,Integer:()=>Oe,Map:()=>De,MapArray:()=>je,Nil:()=>_e,None:()=>Be,Null:()=>ve,ObjectID:()=>Se,T1Collection:()=>B,T1YError:()=>A,T1YOS:()=>V,TimeNow:()=>se,TimeNowUnix:()=>ie,TimeNowUnixNano:()=>ae,TimeNowWeekday:()=>ce,TimeNowWeekdayChinese:()=>ue,Timestamp:()=>Pe,UNDEFINED:()=>Fe,Undefined:()=>$e,ValidationError:()=>g,assertObjectID:()=>S,convertDateTypes:()=>C,createSignature:()=>Y,decryptAESGCM:()=>W,default:()=>Rt,encryptAESGCM:()=>K,formatTimestampsToLocal:()=>v,getMiniProgramAPI:()=>Q,getMiniProgramSubType:()=>z,getPlatformType:()=>q,getSafeTimestamp:()=>J,hmacSHA256Hex:()=>P,hmacSHA256HexAsync:()=>de,isAESGCMAvailable:()=>we,isNonEmptyArrayWithNonEmptyObjects:()=>I,isNonEmptyObject:()=>h,isPlainObject:()=>T,isWebCryptoAvailable:()=>Ae,resetPlatformDetection:()=>Te,sha256Hex:()=>F,sha256HexAsync:()=>ye,timeNow:()=>Ge,validateApiKey:()=>te,validateAppId:()=>ee,validateBaseUrl:()=>re,validateInitConfig:()=>H,validateSecretKey:()=>ne,verifyHmacSHA256:()=>G});module.exports=qt(Xt);var Ye="https://myapp.t1y.net";var Z="YYYY-MM-DD HH:mm:ss";var X=/^[0-9a-fA-F]{24}$/;var A=class extends Error{constructor(e,n,r){super(n),this.name="T1YError",this.code=e,this.data=r}toJSON(){return{name:this.name,code:this.code,message:this.message,data:this.data}}},g=class extends Error{constructor(e){super(e),this.name="ValidationError"}};function ee(t){if(!Number.isInteger(t))throw new g("appId must be an integer");if(t<1001)throw new g(`appId must be >= ${1001}`)}function te(t){if(typeof t!="string")throw new g("apiKey must be a string");if(t.length!==32)throw new g(`apiKey must be exactly ${32} characters (got ${t.length})`)}function ne(t){if(typeof t!="string")throw new g("secretKey must be a string");if(t.length!==32)throw new g(`secretKey must be exactly ${32} characters (got ${t.length})`)}function re(t){if(!/^https?:\/\//.test(t))throw new g('baseUrl must start with "http://" or "https://"')}function H(t){if(t.baseUrl!==void 0&&re(t.baseUrl),ee(t.appId),te(t.apiKey),ne(t.secretKey),t.version!==void 0&&(!Number.isInteger(t.version)||t.version<0))throw new g("version must be a non-negative integer")}function S(t,e="ObjectID"){if(typeof t!="string")throw new g(`${e} must be a string`);if(!X.test(t))throw new g(`Invalid ${e} string: "${t}"`);return!0}function C(t){if(t instanceof Date)return`Date('${t.toISOString()}')`;if(typeof t=="number"){let e=String(t);return/^\d{10,}$/.test(e)?`Timestamp('${e}')`:t}if(Array.isArray(t))return t.map(e=>C(e));if(t&&typeof t=="object"){let e={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=C(t[n]));return e}return t}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0}function T(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function I(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0)}function Ve(){try{if(typeof require<"u")return require}catch{}return null}function F(t){let e=Ve();if(e)try{return e("node:crypto").createHash("sha256").update(t).digest("hex")}catch{}let n=Dt(t);return $(n)}function $(t){return jt(t)}async function ye(t){let e=Ve();if(e)try{return e("node:crypto").createHash("sha256").update(t).digest("hex")}catch{}let n=new TextEncoder,r=await crypto.subtle.digest("SHA-256",n.encode(t));return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Dt(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)e.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let a=t.charCodeAt(n),o=65536+((r&1023)<<10)+(a&1023);e.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}}return new Uint8Array(e)}function jt(t){let e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=t.length,r=n*8,a=(64-(n+9)%64)%64,o=n+1+a+8,c=new Uint8Array(o);c.set(t),c[n]=128;for(let s=0;s<8;s++)c[o-8+s]=Number(BigInt(r)>>BigInt((7-s)*8)&BigInt(255));let i=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let s=0;s<o;s+=64){let f=new Array(64);for(let d=0;d<16;d++)f[d]=c[s+d*4]<<24|c[s+d*4+1]<<16|c[s+d*4+2]<<8|c[s+d*4+3];for(let d=16;d<64;d++){let fe=(U(f[d-15],7)^U(f[d-15],18)^f[d-15]>>>3)>>>0,pe=(U(f[d-2],17)^U(f[d-2],19)^f[d-2]>>>10)>>>0;f[d]=f[d-16]+fe+f[d-7]+pe>>>0}let[p,u,l,m,y,w,R,x]=i;for(let d=0;d<64;d++){let fe=(U(y,6)^U(y,11)^U(y,25))>>>0,pe=(y&w^~y&R)>>>0,Le=x+fe+pe+e[d]+f[d]>>>0,St=(U(p,2)^U(p,13)^U(p,22))>>>0,Ut=(p&u^p&l^u&l)>>>0,kt=St+Ut>>>0;x=R,R=w,w=y,y=m+Le>>>0,m=l,l=u,u=p,p=Le+kt>>>0}i[0]=i[0]+p>>>0,i[1]=i[1]+u>>>0,i[2]=i[2]+l>>>0,i[3]=i[3]+m>>>0,i[4]=i[4]+y>>>0,i[5]=i[5]+w>>>0,i[6]=i[6]+R>>>0,i[7]=i[7]+x>>>0}return i.map(s=>s.toString(16).padStart(8,"0")).join("")}function U(t,e){return t>>>e|t<<32-e}function nt(){try{if(typeof require<"u")return require}catch{}return null}function P(t,e){let n=nt();if(n)try{return n("node:crypto").createHmac("sha256",t).update(e).digest("hex")}catch{}return Bt(t,e)}async function de(t,e){let n=nt();if(n)try{return n("node:crypto").createHmac("sha256",t).update(e).digest("hex")}catch{}let r=new TextEncoder,a=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,r.encode(e));return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}function G(t,e,n){if(typeof n!="string")return!1;let r=P(t,e);return vt(r,n.toLowerCase())}function vt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}function Bt(t,e){let r=Xe(t),a=Xe(e);r.length>64&&(r=et($(r)));let o=new Uint8Array(64);o.set(r.subarray(0,Math.min(r.length,64)));let c=new Uint8Array(64);c.fill(54);let i=Ze(o,c),s=new Uint8Array(64+a.length);s.set(i),s.set(a,64);let f=et($(s)),p=new Uint8Array(64);p.fill(92);let u=Ze(o,p),l=new Uint8Array(64+f.length);return l.set(u),l.set(f,64),$(l)}function Ze(t,e){let n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function Xe(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)e.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let a=t.charCodeAt(n),o=65536+((r&1023)<<10)+(a&1023);e.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}}return new Uint8Array(e)}function et(t){let e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}var L=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],_t=[1,2,4,8,16,32,64,128,27,54];function ge(t){if(t.length!==32)throw new Error("AES-256 requires a 32-byte key");let e=8,n=14,a=4*(n+1),o=new Array(a);for(let i=0;i<e;i++)o[i]=t[4*i]<<24|t[4*i+1]<<16|t[4*i+2]<<8|t[4*i+3];for(let i=e;i<a;i++){let s=o[i-1];i%e===0?s=rt(Ht(s))^_t[Math.floor(i/e)-1]<<24:e>6&&i%e===4&&(s=rt(s)),o[i]=o[i-e]^s}let c=[];for(let i=0;i<=n;i++){let s=new Uint8Array(16);for(let f=0;f<4;f++){let p=o[i*4+f];s[4*f]=p>>>24&255,s[4*f+1]=p>>>16&255,s[4*f+2]=p>>>8&255,s[4*f+3]=p&255}c.push(s)}return c}function Ht(t){return(t<<8|t>>>24)>>>0}function rt(t){return(L[t>>>24&255]<<24|L[t>>>16&255]<<16|L[t>>>8&255]<<8|L[t&255]<<0)>>>0}function be(t,e){if(t.length!==16)throw new Error("AES block must be exactly 16 bytes");let n=[[],[],[],[]];for(let o=0;o<4;o++)for(let c=0;c<4;c++)n[c][o]=t[o*4+c];let r=14;me(n,e[0]);for(let o=1;o<r;o++)ot(n),st(n),Ft(n),me(n,e[o]);ot(n),st(n),me(n,e[r]);let a=new Uint8Array(16);for(let o=0;o<4;o++)for(let c=0;c<4;c++)a[o*4+c]=n[c][o];return a}function ot(t){for(let e=0;e<4;e++)for(let n=0;n<4;n++)t[e][n]=L[t[e][n]]}function st(t){for(let e=1;e<4;e++){let n=t[e];t[e]=[n[e%4],n[(e+1)%4],n[(e+2)%4],n[(e+3)%4]]}}function Ft(t){for(let e=0;e<4;e++){let n=[];for(let r=0;r<4;r++)n[r]=t[r][e];t[0][e]=M(2,n[0])^M(3,n[1])^n[2]^n[3],t[1][e]=n[0]^M(2,n[1])^M(3,n[2])^n[3],t[2][e]=n[0]^n[1]^M(2,n[2])^M(3,n[3]),t[3][e]=M(3,n[0])^n[1]^n[2]^M(2,n[3])}}function me(t,e){for(let n=0;n<4;n++)for(let r=0;r<4;r++)t[r][n]=t[r][n]^e[n*4+r]}function M(t,e){let n=0,r=t,a=e;for(let o=0;o<8;o++){a&1&&(n^=r);let c=r&128;r=r<<1&255,c&&(r^=27),a>>=1}return n}function oe(t,e,n){let r=ge(t),a=Math.ceil(n.length/16),o=new Uint8Array(n.length),c=new Uint8Array(e);for(let i=0;i<a;i++){let s=be(c,r),f=Math.min(16,n.length-i*16);for(let p=0;p<f;p++)o[i*16+p]=n[i*16+p]^s[p];he(c)}return o}function he(t){for(let e=15;e>=12;e--){let n=t[e]+1;if(t[e]=n&255,n<=255)break}}function it(t,e,n){let r=Math.floor(n/4294967296),a=n%4294967296;t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255,t[e+4]=a>>>24&255,t[e+5]=a>>>16&255,t[e+6]=a>>>8&255,t[e+7]=a&255}function at(t,e,n){let a=Math.ceil(e.length/16),o=Math.ceil(n.length/16),c=a+o+1,i=new Uint8Array(16);for(let l=0;l<a;l++){let m=new Uint8Array(16),y=l*16,w=Math.min(16,e.length-y);for(let x=0;x<w;x++)m[x]=e[y+x];for(let x=0;x<16;x++)m[x]^=i[x];let R=xe(m,t);i.set(R)}for(let l=0;l<o;l++){let m=new Uint8Array(16),y=l*16,w=Math.min(16,n.length-y);for(let x=0;x<w;x++)m[x]=n[y+x];for(let x=0;x<16;x++)m[x]^=i[x];let R=xe(m,t);i.set(R)}let s=new Uint8Array(16),f=e.length*8,p=n.length*8;it(s,0,f),it(s,8,p);for(let l=0;l<16;l++)s[l]^=i[l];return xe(s,t)}function xe(t,e){let n=new Uint8Array(16),r=new Uint8Array(e);for(let a=0;a<16;a++)for(let o=0;o<8;o++){if(t[15-a]>>7-o&1)for(let i=0;i<16;i++)n[i]^=r[i];let c=r[15]&1;for(let i=15;i>0;i--)r[i]=r[i]>>1|(r[i-1]&1)<<7;r[0]=r[0]>>1,c&&(r[0]^=225)}return n}function ct(t,e,n,r=new Uint8Array(0)){if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");if(n.length!==12)throw new Error("nonce length must be 12 bytes for AES-256-GCM");let a=new Uint8Array(16);a.set(n),a[15]=1;let o=ge(e),c=new Uint8Array(16),i=be(c,o),s=new Uint8Array(16);s.set(n),s[15]=1;let f=new Uint8Array(s);he(f);let p=oe(e,f,t),u=at(i,r,p),l=oe(e,s,u),m=new Uint8Array(16);for(let y=0;y<16;y++)m[y]=u[y]^l[y];return{ciphertext:p,tag:m}}function ut(t,e,n,r,a=new Uint8Array(0)){if(n.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");if(r.length!==12)throw new Error("nonce length must be 12 bytes for AES-256-GCM");if(e.length!==16)throw new Error("tag length must be 16 bytes for AES-256-GCM");let o=ge(n),c=new Uint8Array(16),i=be(c,o),s=new Uint8Array(16);s.set(r),s[15]=1;let f=at(i,a,t),p=oe(n,s,f),u=new Uint8Array(16);for(let y=0;y<16;y++)u[y]=f[y]^p[y];let l=0;for(let y=0;y<16;y++)l|=e[y]^u[y];if(l!==0)throw new Error("AES-256-GCM authentication failed: tag mismatch");let m=new Uint8Array(s);return he(m),oe(n,m,t)}function j(){try{if(typeof globalThis<"u"){if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle)return globalThis.crypto;try{let t=typeof require<"u"?require:null;if(t){let e=t("node:crypto");if(e?.webcrypto)return e.webcrypto}}catch{}}}catch{}return null}function we(){return!0}function Ae(){return j()!==null}var ft=16,pt=12;function $t(t){let e=j();if(e){let r=new Uint8Array(t);return e.getRandomValues(r),r}try{if(typeof wx<"u"&&typeof wx.getRandomValues=="function"){let r=new Uint8Array(t);return wx.getRandomValues(r),r}}catch{}let n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=Math.floor(Math.random()*256);return n}function N(t){let e="",n=t.byteLength;for(let r=0;r<n;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function D(t){let e=atob(t),n=e.length,r=new Uint8Array(n);for(let a=0;a<n;a++)r[a]=e.charCodeAt(a);return r}async function Gt(t,e){let n=j();if(!n)throw new Error("Web Crypto API is not available");let r=await n.subtle.importKey("raw",e,"AES-GCM",!1,["encrypt"]),a=new Uint8Array(pt);n.getRandomValues(a);let o=new TextEncoder().encode(t),c=new Uint8Array(await n.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)),i=c.slice(0,c.length-ft),s=c.slice(c.length-ft),f={n:N(a),j:N(i),t:N(s)};return JSON.stringify(f)}async function Lt(t,e){let n=j();if(!n)throw new Error("Web Crypto API is not available");let{n:r,j:a,t:o}=JSON.parse(t),c=D(r),i=D(a),s=D(o),f=new Uint8Array(i.length+s.length);f.set(i),f.set(s,i.length);let p=await n.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]),u=await n.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},p,f);return new TextDecoder().decode(u)}function Kt(t,e){let n=$t(pt),r=new TextEncoder().encode(t),{ciphertext:a,tag:o}=ct(r,e,n),c={n:N(n),j:N(a),t:N(o)};return JSON.stringify(c)}function Wt(t,e){let{n,j:r,t:a}=JSON.parse(t),o=D(n),c=D(r),i=D(a),s=ut(c,i,e,o);return new TextDecoder().decode(s)}async function K(t,e){if(!(e instanceof Uint8Array))throw new Error("key must be Uint8Array");if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");return j()?await Gt(t,e):Kt(t,e)}async function W(t,e){if(!(e instanceof Uint8Array))throw new Error("key must be Uint8Array");if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");return j()?await Lt(t,e):Wt(t,e)}function Y(t){let{method:e,pathAndQuery:n,body:r,appId:a,timestamp:o,secretKey:c}=t,i=F(r),s=[e.toUpperCase(),n,i,String(a),String(o)].join(`
|
|
2
|
+
`);return P(c,s)}function J(t){return String(Math.floor(Date.now()/1e3)+t)}function lt(t){return t.replace(/\/+$/,"")}function yt(t,e){for(let n of Object.keys(e)){let r=e[n];r!=null&&t.searchParams.set(n,typeof r=="string"?r:JSON.stringify(r))}}function Yt(t,e){let n=new Date(t);if(isNaN(n.getTime()))return t;let r=a=>String(a).padStart(2,"0");return e.replace("YYYY",String(n.getFullYear())).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))}function v(t,e=Z){function n(r){if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let a={};for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&(o==="createdAt"||o==="updatedAt"?a[o]=Yt(r[o],e):a[o]=n(r[o]));return a}return r}return n(t)}async function dt(t,e,n,r){let a=t.headers["content-type"]||"",o,c=t.body;if(a.includes("application/json"))try{o=JSON.parse(c)}catch{o=c}else o=c;if(e&&o&&typeof o=="object"&&"j"in o)try{let s=await W(JSON.stringify(o),new TextEncoder().encode(n));try{o=JSON.parse(s)}catch{o=s}}catch(s){throw new A(400,"AES-256-GCM decryption failed",s instanceof Error?s.message:null)}let i=t.status>=200&&t.status<300;if(o&&typeof o=="object"&&"data"in o){let s=o;if(s.data=v(s.data,r),!i)throw new A(s.code||t.status,s.message||t.statusText,s.data);return s}if(!i)throw new A(t.status,t.statusText,o);return{code:0,message:"ok",data:v(o,r)}}function mt(t){if(t instanceof A)throw t;if(t instanceof Error){let e=t.message||"Unknown error";throw e.includes("timeout")||e.includes("\u8D85\u65F6")||t.name==="AbortError"||e.includes("abort")?new A(408,"Request timeout",null):new A(0,e,null)}throw new A(0,"Unknown error",t)}var b=null,E=null;function q(){if(b!==null)return b;if(typeof wx<"u"&&typeof wx.request=="function")return b="wx",b;if(typeof my<"u"&&typeof my.request=="function")return b="my",b;if(typeof window>"u"&&typeof document>"u"&&typeof global<"u"&&typeof global.require=="function")try{if(typeof require<"u"&&typeof require("@system.fetch")<"u")return b="hap",b}catch{}return typeof window<"u"&&typeof document<"u"?(b="h5",b):typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions?.node<"u"?(b="nodejs",b):(b="unknown",b)}function z(){return E!==null?E:q()!=="wx"?(E="unknown",E):typeof tt<"u"&&typeof tt.request=="function"?(E="toutiao",E):typeof qq<"u"&&typeof qq.request=="function"?(E="qq",E):(E="wechat",E)}function Q(){let t=q();if(t==="my")return my;if(t!=="wx")return null;switch(z()){case"toutiao":return tt;case"qq":return qq;default:return wx}}function Te(){b=null,E=null}var Ee=async t=>{let{url:e,method:n,headers:r,body:a,signal:o}=t,c={method:n,headers:r,signal:o};a!==void 0&&n!=="GET"&&(c.body=a);let i=await fetch(e,c),s={};i.headers.forEach((p,u)=>{s[u.toLowerCase()]=p});let f=await i.text();return{status:i.status,statusText:i.statusText,headers:s,body:f}};var xt=async t=>{let e=Q();if(!e||typeof e.request!="function")throw new Error("Mini program request API is not available");let n=e.request,{url:r,method:a,headers:o,body:c,timeout:i}=t;return new Promise((s,f)=>{let p=n({url:r,method:a,header:o,data:c,timeout:i??3e5,dataType:"text",responseType:"text",success:u=>{let l={};if(u.header)for(let y of Object.keys(u.header))l[y.toLowerCase()]=u.header[y];let m;typeof u.data=="string"?m=u.data:u.data!==void 0&&u.data!==null?m=JSON.stringify(u.data):m="",s({status:u.statusCode,statusText:u.errMsg??"",headers:l,body:m})},fail:u=>{let l=u.errMsg??"Mini program request failed";l.includes("timeout")||l.includes("\u8D85\u65F6")?f(new Error("Request timeout")):f(new Error(l))}});if(t.signal){let u=()=>{typeof p.abort=="function"&&p.abort()};t.signal.addEventListener("abort",u,{once:!0})}})};var gt=async t=>{let e=my;if(!e||typeof e.request!="function")throw new Error("Alipay mini program request API (my.request) is not available");let n=e.request,{url:r,method:a,headers:o,body:c,timeout:i}=t;return new Promise((s,f)=>{let p=n({url:r,method:a.toUpperCase(),headers:o,data:c!==void 0?c:void 0,timeout:i??3e5,dataType:"text",success:u=>{let l=u.status??u.statusCode??200,m={};if(u.headers)for(let w of Object.keys(u.headers))m[w.toLowerCase()]=u.headers[w];let y;typeof u.data=="string"?y=u.data:u.data!==void 0&&u.data!==null?y=JSON.stringify(u.data):y="",s({status:l,statusText:"",headers:m,body:y})},fail:u=>{let l=u.errorMessage??u.errMsg??`Alipay request failed (error: ${u.error})`;f(new Error(l))},complete:()=>{}});if(t.signal){let u=()=>{p&&typeof p.abort=="function"&&p.abort()};t.signal.addEventListener("abort",u,{once:!0})}})};function Jt(){try{return require("@system.fetch")}catch{return null}}var bt=async t=>{let e=Jt();if(!e)throw new Error("Quick App fetch module (@system.fetch) is not available. Ensure you are running inside a Quick App environment.");let{url:n,method:r,headers:a,body:o}=t;return new Promise((c,i)=>{e.fetch({url:n,method:r.toUpperCase(),header:a,data:o,responseType:"text",success:s=>{let f={};if(s.headers)for(let p of Object.keys(s.headers))f[p.toLowerCase()]=s.headers[p];c({status:s.code,statusText:"",headers:f,body:typeof s.data=="string"?s.data:JSON.stringify(s.data)})},fail:s=>{i(new Error(`Quick App request failed (code: ${s.code}, data: ${s.data})`))},complete:()=>{}})})};var O=null;function ht(){if(O!==null)return O;switch(q()){case"h5":case"nodejs":O=Ee;break;case"wx":O=xt;break;case"my":O=gt;break;case"hap":O=bt;break;default:if(typeof fetch=="function")O=Ee;else throw new Error("Unable to determine platform request adapter. The current environment does not have `fetch`, `wx.request`, `my.request`, or `@system.fetch` available. Please ensure you are running in a supported environment: Web browser, Node.js 18+, WeChat/QQ/Alipay/Toutiao/Douyin Mini Program, or Quick App.");break}return O}async function Re(t,e){let{method:n,path:r,params:a,encryption:o,timeout:c}=e,i=lt(t.baseUrl),s=o??t.isSafeMode,f=new URL(i+r),p=C(a),u,l="";if(n!=="GET")if(s&&p!==void 0){let d=await K(JSON.stringify(p),new TextEncoder().encode(t.secretKey));u=d,l=d}else if(p!==void 0){let d=JSON.stringify(p);u=d,l=d}else l="";else p&&typeof p=="object"&&Object.keys(p).length>0&&yt(f,p);let m=Number(J(t.offset)),y=f.pathname+f.search,w=Y({method:n,pathAndQuery:y,body:l,appId:t.appId,timestamp:m,secretKey:t.secretKey}),R=ht(),x=c??3e5;try{let d=await R({url:f.toString(),method:n,headers:{"X-T1Y-Application-ID":String(t.appId),"X-T1Y-API-Key":t.apiKey,"X-T1Y-Safe-Timestamp":String(m),"X-T1Y-Safe-Sign":w,"Content-Type":"application/json"},body:n!=="GET"?u:void 0,timeout:x});return await dt(d,s,t.secretKey,t.timeFormat)}catch(d){return mt(d)}}var B=class{constructor(e,n){this.client=e,this.name=n}async insertOne(e){if(!h(e))throw new TypeError("insertOne data must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}`,e)}async deleteById(e){return S(e),await this.client.request("DELETE",`/v5/classes/${this.name}/${e}`)}async updateById(e,n){if(S(e),!h(n))throw new TypeError("update data must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/${e}`,n)}async findById(e){return S(e),await this.client.request("GET",`/v5/classes/${this.name}/${e}`)}async deleteOne(e){if(!h(e))throw new TypeError("deleteOne filter must be a non-empty plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/one`,e)}async updateOne(e,n){if(!h(e))throw new TypeError("updateOne filter must be a non-empty plain object");if(!h(n))throw new TypeError("updateOne body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/one`,{filter:e,body:n})}async findOne(e){if(!h(e))throw new TypeError("findOne filter must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}/one`,e)}async insertMany(e){if(!I(e))throw new TypeError("insertMany dataList must be a non-empty array of non-empty plain objects");return await this.client.request("POST",`/v5/classes/${this.name}/many`,e)}async deleteMany(e){if(!T(e))throw new TypeError("deleteMany filter must be a plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/many`,e)}async updateMany(e,n){if(!T(e))throw new TypeError("updateMany filter must be a plain object");if(!h(n))throw new TypeError("updateMany body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/many`,{filter:e,body:n})}async find(e=1,n=10,r={createdAt:-1},a={}){if(!Number.isInteger(e)||e<1)throw new TypeError("find page must be a positive integer");if(!Number.isInteger(n)||n<1)throw new TypeError("find size must be a positive integer");if(n>100&&(n=100),!h(r))throw new TypeError("find sort must be a non-empty plain object");if(!T(a))throw new TypeError("find filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/find`,{page:e,size:n,sort:r,filter:a})}async aggregate(e){if(!Array.isArray(e))throw new TypeError("aggregate pipeline must be an array");return await this.client.request("POST",`/v5/classes/${this.name}/aggregate`,e)}async count(e={}){if(!T(e))throw new TypeError("count filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/count`,e)}async distinct(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("distinct fieldName must be a non-empty string");if(!T(n))throw new TypeError("distinct filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/distinct/${encodeURIComponent(e)}`,n)}async create(){return await this.client.request("POST",`/v5/schemas/${encodeURIComponent(this.name)}`)}async clear(){return await this.client.request("PUT",`/v5/schemas/${encodeURIComponent(this.name)}`)}async drop(){return await this.client.request("DELETE",`/v5/schemas/${encodeURIComponent(this.name)}`)}};var k,wt,At,Tt,Et,V=class{constructor(e){We(this,k);H(e),this.config={baseUrl:e.baseUrl??Ye,appId:e.appId,apiKey:e.apiKey,secretKey:e.secretKey,version:e.version??0,isSafeMode:e.isSafeMode??!1,timeFormat:e.timeFormat??Z,offset:e.offset??0},this.db={collection:n=>_(this,k,wt).call(this,n),toObjectID:n=>_(this,k,Tt).call(this,n),getCollections:()=>_(this,k,At).call(this)}}async init(){try{let n=(await this.request("GET",`/init/${this.config.appId}`,void 0,!1)).data;this.config.isSafeMode=n.is_safe_mode,this.config.offset=n.unix-Math.floor(Date.now()/1e3)}catch(e){console.warn("Failed to get time offset from server, defaulting to 0. Error:",e),this.config.isSafeMode=!1,this.config.offset=0}}async getMeta(e){if(e!==void 0&&e!==""&&typeof e!="string")throw new TypeError("Meta field must be a string");let n=e?`?field=${encodeURIComponent(e)}`:"";return await this.request("GET",`/v5/meta${n}`)}async checkUpdate(){try{return(await this.request("GET","/v5/meta?field=version")).data.result>this.config.version}catch{return!1}}async callFunc(e,n=null,r){if(typeof e!="string")throw new TypeError("Function name must be a string");return await this.request("POST",`/${this.config.appId}/${_(this,k,Et).call(this,e)}`,n,r)}async request(e,n,r,a){if(typeof n!="string")throw new TypeError("request path must be a string");return await Re(this.config,{method:e,path:n,params:r,encryption:a??this.config.isSafeMode})}assertObjectID(e,n="ObjectID"){return S(e,n)}isNonEmptyObject(e){return h(e)}isPlainObject(e){return T(e)}isNonEmptyArrayWithNonEmptyObjects(e){return I(e)}hmacSHA256(e,n){return P(e,n)}verifyHmacSHA256(e,n,r){return G(e,n,r)}};k=new WeakSet,wt=function(e){if(typeof e!="string")throw new TypeError("Collection name must be a string");return new B(this,e)},At=async function(){return await this.request("GET","/v5/schemas")},Tt=function(e){return S(e),`ObjectID('${e}')`},Et=function(e){let n=e.startsWith("/")?e.slice(1):e,r=n.indexOf("#"),a=r!==-1?n.slice(r):"",o=r!==-1?n.slice(0,r):n,c=o.indexOf("?"),i=c!==-1?o.slice(c):"",s=c!==-1?o.slice(0,c):o;return s.endsWith("/")?s=s+"index.jsc":s.endsWith(".jsc")||(s.endsWith(".js")?s=s.replace(/\.js$/,".jsc"):s=s+".jsc"),s+i+a};var Rt=V;function Se(t){if(!X.test(t))throw new Error(`Invalid ObjectID: "${t}" (must be 24 hex characters)`);return`ObjectID('${t}')`}function Ue(t){return`Date('${t}')`}function ke(t){return`DateTime('${t}')`}function Pe(t){return`Timestamp('${String(t)}')`}function Me(t){return`Boolean(${t})`}function Oe(t){return`Integer(${t})`}function Ce(t){return`Bigint(${Number(t)})`}function Ie(t){return`Float(${t})`}function qe(t){return`Double(${t})`}function Ne(t){return`Array(${JSON.stringify(t)})`}function De(t){return`Map(${JSON.stringify(t)})`}function je(t){return`Map[](${JSON.stringify(t)})`}var ve="Null",Be="None",_e="Nil",He="",Fe="UNDEFINED",$e="Undefined";var se="time.Now()",ie="time.Now().Unix()",ae="time.Now().UnixNano()",ce="time.Now().Weekday()",ue="time.Now().Weekday().Chinese()",Ge={Now:()=>se,NowUnix:()=>ie,NowUnixNano:()=>ae,NowWeekday:()=>ce,NowWeekdayChinese:()=>ue};0&&(module.exports={Array,Bigint,Boolean,Date,DateTime,Double,Empty,Float,Integer,Map,MapArray,Nil,None,Null,ObjectID,T1Collection,T1YError,T1YOS,TimeNow,TimeNowUnix,TimeNowUnixNano,TimeNowWeekday,TimeNowWeekdayChinese,Timestamp,UNDEFINED,Undefined,ValidationError,assertObjectID,convertDateTypes,createSignature,decryptAESGCM,encryptAESGCM,formatTimestampsToLocal,getMiniProgramAPI,getMiniProgramSubType,getPlatformType,getSafeTimestamp,hmacSHA256Hex,hmacSHA256HexAsync,isAESGCMAvailable,isNonEmptyArrayWithNonEmptyObjects,isNonEmptyObject,isPlainObject,isWebCryptoAvailable,resetPlatformDetection,sha256Hex,sha256HexAsync,timeNow,validateApiKey,validateAppId,validateBaseUrl,validateInitConfig,validateSecretKey,verifyHmacSHA256});
|
|
3
3
|
//# sourceMappingURL=index.js.map
|