@fast-china/utils 2.1.5 → 2.1.7

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +14 -4
  3. package/README.zh.md +14 -4
  4. package/THIRD_PARTY_LICENSES.md +26 -0
  5. package/dist/crypto/index.mjs +2240 -33
  6. package/dist/crypto/index.mjs.map +1 -1
  7. package/dist/dom/index.mjs +2 -0
  8. package/dist/index.d.mts +1918 -26
  9. package/dist/index.global.min.js +1 -1
  10. package/dist/index.global.min.js.map +1 -1
  11. package/dist/index.mjs +9 -1
  12. package/dist/internal/runtime.mjs.map +1 -1
  13. package/dist/vue/breakpoints.mjs +46 -0
  14. package/dist/vue/breakpoints.mjs.map +1 -0
  15. package/dist/vue/element-size.mjs +33 -0
  16. package/dist/vue/element-size.mjs.map +1 -0
  17. package/dist/vue/event-listener.mjs +30 -0
  18. package/dist/vue/event-listener.mjs.map +1 -0
  19. package/dist/vue/index.mjs +15 -0
  20. package/dist/vue/now.mjs +29 -0
  21. package/dist/vue/now.mjs.map +1 -0
  22. package/dist/vue/resize-observer.mjs +31 -0
  23. package/dist/vue/resize-observer.mjs.map +1 -0
  24. package/dist/vue/window-size.mjs +32 -0
  25. package/dist/vue/window-size.mjs.map +1 -0
  26. package/package.json +4 -6
  27. package/dist/array/index.d.mts +0 -94
  28. package/dist/async/index.d.mts +0 -145
  29. package/dist/base64/index.d.mts +0 -106
  30. package/dist/color/index.d.mts +0 -89
  31. package/dist/crypto/index.d.mts +0 -327
  32. package/dist/date/index.d.mts +0 -190
  33. package/dist/dom/style.d.mts +0 -29
  34. package/dist/env/index.d.mts +0 -62
  35. package/dist/function/index.d.mts +0 -13
  36. package/dist/identity/index.d.mts +0 -77
  37. package/dist/internal/text.d.mts +0 -15
  38. package/dist/logger/index.d.mts +0 -90
  39. package/dist/number/index.d.mts +0 -89
  40. package/dist/object/index.d.mts +0 -114
  41. package/dist/storage/index.d.mts +0 -115
  42. package/dist/string/index.d.mts +0 -141
  43. package/dist/vue/emits.d.mts +0 -23
  44. package/dist/vue/expose.d.mts +0 -11
  45. package/dist/vue/func.d.mts +0 -13
  46. package/dist/vue/index.d.mts +0 -9
  47. package/dist/vue/install.d.mts +0 -50
  48. package/dist/vue/props.d.mts +0 -22
  49. package/dist/vue/render.d.mts +0 -11
  50. package/dist/vue/slots.d.mts +0 -18
  51. package/dist/vue/with.d.mts +0 -11
  52. package/docs/API.md +0 -155
  53. package/docs/API.zh-CN.md +0 -154
  54. package/docs/DEVELOPMENT_RELEASE.zh-CN.md +0 -65
  55. package/docs/RUNTIME_CONTRACT.md +0 -42
package/docs/API.md DELETED
@@ -1,155 +0,0 @@
1
- # Fast.Utils API
2
-
3
- Fast.Utils is a browser-first utility package targeting ES2022. Package managers use its ESM entry, while CDNs use the separately minified IIFE entry. Its application environments are modern browsers, WebViews, Vue 3, and uni-app.
4
-
5
- ## Imports
6
-
7
- The package has one public root entry. Every utility, including the Vue helpers, is exposed as a named export.
8
-
9
- ```ts
10
- import { chunk, configureStorage, installationIdentity, Local } from "@fast-china/utils";
11
- ```
12
-
13
- Internal helpers are not public subpaths. Aggregate utility objects are not exported; import named functions so bundlers can remove unused code.
14
-
15
- ## Storage
16
-
17
- `Local` and `Session` initialize lazily with the legacy-compatible `fast__` prefix, JSON codec, and `Date.now`. Calling `configureStorage` is optional unless the defaults must be overridden.
18
-
19
- ```ts
20
- import { Local, Session } from "@fast-china/utils";
21
-
22
- Local.set("profile", { name: "Ada" }, { ttlMs: 3_600_000 });
23
- Session.set("draft", { step: 2 });
24
-
25
- Local.set("private-profile", { name: "Ada" }, { crypto: true });
26
- Local.get<{ name: string }>("private-profile", { crypto: true });
27
- ```
28
-
29
- `Local` and `Session` provide `get`, `set`, `has`, `remove`, `removeByPrefix`, `keys`, `pruneExpired`, and namespace-scoped `clear`. Missing and expired values return `undefined`. Invalid TTL values, empty prefixes, malformed stored envelopes, unavailable platform storage, and conflicting repeated configuration throw errors. Native storage quota and privacy errors are propagated. Custom options must be configured before the first Storage operation.
30
-
31
- `get<Value = string>()` has the static return type `string | undefined` when its generic is omitted, so string entries can be read directly. The codec still restores the original JSON value at runtime and does not convert objects, arrays, or other non-string values to strings; pass an explicit generic when accurate type information is required.
32
-
33
- For uni-app, the first Storage operation or an explicit `configureStorage` call detects the global `uni` object and uses its synchronous Storage API. uni-app has no separate session backend, so `Session` throws when called in this mode.
34
-
35
- ```ts
36
- import { Local } from "@fast-china/utils";
37
-
38
- Local.set("token", "value");
39
- ```
40
-
41
- `configureStorage({ prefix: "admin:", crypto: true })` restores the old global prefix and Base64-obfuscation options. `Local` and `Session` `set/get` also accept a per-operation `{ crypto: boolean }`: `true` selects the Base64 codec, `false` selects the JSON codec, and omission uses the global codec. An operation override does not mutate global configuration. The current v3 envelope does not record its codec, so writes and reads of the same entry must use matching options; a mismatch throws a decoding error.
42
-
43
- `crypto: true` and `base64StorageCodec` are reversible encoding rather than encryption and must not protect secrets. A custom `codec` may be supplied instead of global `crypto`.
44
-
45
- `decodeBase64`, `decodeBase64Url`, `decodeLatin1Base64`, and `decodeSecureBase64` return the primitive-string `DecodedText` type. It is directly assignable to `string` and supports strict equality; an explicit `.parseJson<T = any>()` call attempts JSON parsing and returns the unchanged source string when its syntax is invalid. The first text decode lazily installs a non-enumerable `String.prototype.parseJson`; a foreign property with the same name causes a `TypeError` instead of being overwritten. The generic type describes the expected shape but neither validates it nor guarantees an object result at runtime. Storage codecs do not use this fallback and continue to reject invalid JSON strictly.
46
-
47
- `encodeSecureBase64` and `decodeSecureBase64` preserve the legacy dictionary payload. The random prefix prefers Web Crypto and falls back to `Math.random()` when unavailable; it does not provide a security property. Given the same default six-character prefix, valid legacy payloads remain byte-for-byte compatible. The old dictionary references an unavailable character for Base64 lengths 101–124, so the current implementation inserts a one-character fallback that the legacy removal flow can decode. The old custom-length argument always generated six random characters; the current API correctly generates `prefixLength` characters. Custom lengths must match during encoding and decoding; `0` disables both the prefix and dictionary insertion. The format remains reversible encoding rather than encryption.
48
-
49
- ## Identity
50
-
51
- `installationIdentity` is the global installation identifier facade. Call `configureInstallationIdentity` in the application entry before first use to override its `identity:installation-id` cache key. `getOrCreateInstallationId(installationId?)` loads, creates, or replaces its UUID v4 value in `Local` storage. Storage uses its defaults when no explicit configuration was supplied. UUID generation prefers Web Crypto and falls back to `Math.random()` when unavailable.
52
-
53
- ```ts
54
- import { configureInstallationIdentity, configureStorage, getOrCreateInstallationId, installationIdentity } from "@fast-china/utils";
55
-
56
- configureStorage({ prefix: "app:" });
57
- configureInstallationIdentity({ cacheKey: "account:installation-id" });
58
- getOrCreateInstallationId();
59
- installationIdentity.read();
60
- installationIdentity.clear();
61
- ```
62
-
63
- The identifier is an installation-scoped value, not a hardware identifier, authentication credential, secret, or anti-fraud signal.
64
-
65
- ## Logger
66
-
67
- Logger scope belongs to each entry rather than a logger or child instance. The default `logger` works without construction and has a minimum level of `debug`. Configure it once
68
- at application startup when uni-app App-Plus needs split object output:
69
-
70
- ```ts
71
- import { configureLogger, logger } from "@fast-china/utils";
72
-
73
- configureLogger({ uniAppPlusSplit: true });
74
- logger.log("Launch", { code: 200, data: { id: 1 } });
75
- logger.log("storage", "profile loaded", { userId: 1 });
76
- logger.error("network", "request failed", error);
77
- ```
78
-
79
- Log content is optional and may directly contain objects, arrays, `Error` instances, or other values. Non-string values are passed unchanged to
80
- the Sink in normal runtimes. With App-Plus splitting enabled, the heading is emitted separately and each additional value is converted to readable
81
- text because HBuilderX does not reliably display objects.
82
-
83
- `configureLogger` replaces the complete configuration of the default `logger`; previously retained `logger` references immediately observe the new
84
- configuration. Calling it without options restores all defaults. `createLogger` creates an isolated instance unaffected by global configuration.
85
- Logger's `debug`, `log`, `warn`, and `error` methods call the matching Sink methods; the default Sink maps them to `console.debug`, `console.log`, `console.warn`, and `console.error`. Both support a minimum level, brand prefix, Sink, and optional App-Plus split output. Scope must be a non-empty string without surrounding whitespace.
86
-
87
- ## Clipboard
88
-
89
- `copy(value)` restores the V1 text-copy capability and returns `Promise<void>`. uni-app uses `setClipboardData`; browsers prefer the Clipboard API and fall back to `document.execCommand("copy")` when it is unavailable. Missing capabilities, denied permission, and copy failures throw errors.
90
-
91
- ```ts
92
- import { copy } from "@fast-china/utils";
93
-
94
- await copy("Fast utilities");
95
- ```
96
-
97
- ## Crypto
98
-
99
- The TypeScript Crypto public API mirrors the public methods and algorithm casing of .NET `CryptoUtil`:
100
-
101
- | Capability | Shared method names |
102
- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
103
- | Random bytes and byte comparison | `GenerateRandomBytes`, `FixedTimeEquals` |
104
- | MD5, SHA-1, and SHA-2 digests | `MD5Encrypt`, `SHA1Encrypt`, `SHA256Encrypt`, `SHA256Bytes`, `SHA384Encrypt`, `SHA384Bytes`, `SHA512Encrypt`, `SHA512Bytes` |
105
- | HMAC | `HMACSHA256Encrypt`, `HMACSHA384Encrypt`, `HMACSHA512Encrypt` |
106
- | Password derivation and hashing | `PBKDF2SHA256`, `HashPasswordPBKDF2SHA256`, `VerifyPasswordPBKDF2SHA256` |
107
- | HKDF | `HKDFSHA256` |
108
- | AES | `AESEncrypt`, `AESDecrypt`, `AESEncryptAuthenticated`, `AESDecryptAuthenticated`, `AESEncryptWithPassword`, `AESDecryptWithPassword` |
109
- | RSA | `GenerateRSAKeyPair`, `RSAEncryptOAEP`, `RSADecryptOAEP`, `RSASignPSS`, `RSAVerifyPSS` |
110
- | Elliptic curves | `GenerateECDSAKeyPair`, `ECDSASign`, `ECDSAVerify`, `GenerateECDHKeyPair`, `DeriveECDHSecret`, `DeriveECDHKeySHA256` |
111
-
112
- The Base64 v1 payload produced by `AESEncryptAuthenticated`, the `FAST-AES-256-GCM-V1` password payload, PBKDF2 password hashes, and PKCS#8/SPKI PEM keys interoperate with .NET in both directions. MD5 and HMAC output lowercase hexadecimal; SHA-1/256/384/512 output uppercase hexadecimal, matching .NET.
113
-
114
- `AESDecrypt`, `AESDecryptAuthenticated`, `AESDecryptWithPassword`, and `RSADecryptOAEP` return the primitive-string `DecodedText` type (wrapped in a Promise for asynchronous APIs). Use the result directly as plaintext or call `.parseJson<T = any>()` explicitly:
115
-
116
- ```ts
117
- const plaintext = await AESDecryptWithPassword(payload, password);
118
- const raw: string = plaintext;
119
- const result = plaintext.parseJson<{ id: number }>();
120
- ```
121
-
122
- Store passwords with `HashPasswordPBKDF2SHA256` and `VerifyPasswordPBKDF2SHA256`; the result is not decryptable. AES-GCM provides confidentiality and integrity, HMAC authenticates with a shared key, SHA-2 computes digests, and HKDF/PBKDF2 derive keys. MD5, SHA-1, AES-CBC, and AES-ECB do not provide modern password-storage or authenticated-encryption guarantees.
123
-
124
- ## Modules
125
-
126
- - `array`: `chunk`, `removeNullishValues`, `unique`, `uniqueBy`, `groupBy`, `partition`, `difference`, `intersection`, `symmetricDifference`, `hasDuplicatesBy`, and `allEqualBy`.
127
- - `async`: abort-aware `sleep`, timeout, retry, bounded concurrent mapping, debounce, and throttle primitives.
128
- - `base64`: strict UTF-8 Base64/Base64URL byte functions and chainable text results plus the historical Latin-1 and dictionary-obfuscation functions.
129
- - `color`: Hex parsing/formatting/mixing, explicit black/white mixing, luminance, and contrast helpers.
130
- - `crypto`: random bytes, digests, HMAC, PBKDF2, HKDF, AES, RSA-OAEP/PSS, ECDSA, and ECDH.
131
- - `date`: date validation and arithmetic, day ranges, relative formatting, and the seven historical date helpers as named functions.
132
- - `dom`: CSS unit and style serialization helpers.
133
- - `env`: capability and user-agent detection. Detection does not expand the supported runtime contract.
134
- - `function`: `once` execution with cached return, Promise identity, and synchronous-error behavior.
135
- - `logger`: isolated configurable loggers and the default `logger`.
136
- - `number`: ranges, rounding, aggregation, interpolation, byte formatting, and Web Crypto-preferred `randomInt`.
137
- - `object`: deep cloning and equality, prototype-safe key and predicate selection, mapping, and query serialization. Style serialization is provided by the `dom` module.
138
- - `string`: query parsing, casing, grapheme-aware truncation, clipboard copying, UUID, Web Crypto-preferred `randomString`, escaping, and whitespace normalization.
139
- - `vue`: Composition API, type, render, and `app.use()` registration helpers for Vue 3.
140
-
141
- ## Security and limits
142
-
143
- AES-GCM provides confidentiality and integrity; AES-CBC/ECB do not authenticate ciphertexts. MD5, SHA-1, and the historical Base64 dictionary must not protect passwords, signatures, or sensitive data. Cryptographic helpers enforce algorithm-specific parameter and payload limits and require Web Crypto where applicable.
144
-
145
- Query and object helpers reject prototype-polluting keys. URL decoders are bounded. Storage cleanup is always restricted to the configured namespace. Browser globals are resolved only when an API is called, never during module import.
146
-
147
- ## Errors and compatibility
148
-
149
- Programming errors, invalid inputs, unsupported platform capabilities, and malformed protected data throw native errors unless a function explicitly documents a nullable result.
150
-
151
- Since Fast.Utils 2.1.1, built-in validation and runtime failure messages are Chinese. Consumers must branch on native error types instead of matching message text.
152
-
153
- `randomInt`, `randomString`, `generateUuidV4`, and `GenerateRandomBytes` all prefer Web Crypto and fall back to `Math.random()` when unavailable.
154
-
155
- Fast.Utils 2.1.0 removes `secureRandomInt` and `secureRandomString`. This is a breaking change; consumers must migrate to `randomInt` and `randomString`, respectively.
package/docs/API.zh-CN.md DELETED
@@ -1,154 +0,0 @@
1
- # Fast.Utils API
2
-
3
- Fast.Utils 是面向浏览器的 ES2022 工具包;包管理器使用 ESM 入口,CDN 使用单独压缩的 IIFE 入口。应用环境包括现代浏览器、WebView、Vue 3 和 uni-app。
4
-
5
- ## 导入
6
-
7
- 包只提供一个公开根入口,包含普通工具和 Vue Helper 在内的全部 API 均使用具名导出。
8
-
9
- ```ts
10
- import { chunk, configureStorage, installationIdentity, Local } from "@fast-china/utils";
11
- ```
12
-
13
- 内部 Helper 不提供公共子路径。库不再导出工具聚合对象,调用方应直接导入具名函数,以便 Tree Shaking。
14
-
15
- ## Storage
16
-
17
- `Local` 和 `Session` 会以旧版兼容的 `fast__` 前缀、JSON Codec 与 `Date.now` 延迟初始化。除非需要覆盖默认值,否则无需调用 `configureStorage`。
18
-
19
- ```ts
20
- import { Local, Session } from "@fast-china/utils";
21
-
22
- Local.set("profile", { name: "Ada" }, { ttlMs: 3_600_000 });
23
- Session.set("draft", { step: 2 });
24
-
25
- Local.set("private-profile", { name: "Ada" }, { crypto: true });
26
- Local.get<{ name: string }>("private-profile", { crypto: true });
27
- ```
28
-
29
- `Local` 和 `Session` 提供 `get`、`set`、`has`、`remove`、`removeByPrefix`、`keys`、`pruneExpired` 和仅清理当前命名空间的 `clear`。键缺失或过期时返回 `undefined`。TTL 非法、Prefix 为空、存储包络损坏、平台 Storage 不可用或重复配置发生冲突时抛出错误;浏览器配额与隐私策略错误直接向上传播。自定义选项必须在首次 Storage 操作前配置。
30
-
31
- `get<Value = string>()` 在未传泛型时的静态返回类型为 `string | undefined`,可以直接读取字符串条目。Codec 在运行时仍通过 JSON 反序列化恢复原值,因此对象、数组或其他非字符串值不会被转换成字符串;需要准确类型提示时显式传入对应泛型。
32
-
33
- uni-app 中,首次 Storage 操作或显式调用 `configureStorage` 会自动检测全局 `uni` 并使用其同步 Storage API。uni-app 没有独立 Session 后端,因此该模式调用 `Session` 会明确抛错。
34
-
35
- ```ts
36
- import { Local } from "@fast-china/utils";
37
-
38
- Local.set("token", "value");
39
- ```
40
-
41
- `configureStorage({ prefix: "admin:", crypto: true })` 恢复了旧版全局前缀与 Base64 混淆选项。`Local` 与 `Session` 的 `set/get` 也接受单次 `{ crypto: boolean }`:`true` 使用 Base64 Codec,`false` 使用 JSON Codec,省略时沿用全局 Codec。单次设置不会修改全局配置;当前 v3 包络不记录 Codec,读写同一条目时必须传入一致选项,错误配置会明确抛出解码错误。
42
-
43
- `crypto: true` 和 `base64StorageCodec` 都只是可逆编码,不是加密,不能保护敏感数据。可以使用自定义 `codec` 替代全局 `crypto`。
44
-
45
- `decodeBase64`、`decodeBase64Url`、`decodeLatin1Base64` 与 `decodeSecureBase64` 返回原始字符串类型 `DecodedText`,可以直接赋值给 `string` 或参与严格比较;显式调用 `.parseJson<T = any>()` 才尝试解析 JSON,语法无效时返回未经修改的原始字符串。首次文本解码会按需安装不可枚举的 `String.prototype.parseJson`;若同名属性已被其他实现占用则抛出 `TypeError`,不会覆盖。泛型只描述期望类型,不执行运行时结构校验,也不保证结果一定是对象。Storage Codec 不使用该容错行为,仍会严格拒绝非法 JSON。
46
-
47
- `encodeSecureBase64` 与 `decodeSecureBase64` 保留旧字典兼容载荷。随机前缀优先使用 Web Crypto,能力缺失时回退到 `Math.random()`;它不承担安全用途。给定相同的默认 6 字符前缀时,有效旧载荷保持逐字符兼容;旧字典在 Base64 长度 101–124 时会引用越界,当前实现使用单字符回退,旧删除字典流程仍可解码。旧自定义长度参数始终生成 6 个随机字符,当前 API 已按 `prefixLength` 正确生成。自定义 `prefixLength` 必须在编码和解码时保持一致;传入 `0` 会同时关闭随机前缀与字典插入。该格式仍是可逆编码,不等同于加密。
48
-
49
- ## Identity
50
-
51
- `installationIdentity` 是全局安装标识门面。可在程序入口、首次使用前调用 `configureInstallationIdentity` 覆盖默认缓存键 `identity:installation-id`。`getOrCreateInstallationId(installationId?)` 会通过 `Local` 读取、生成或替换 UUID v4;未显式配置 Storage 时使用其默认值。UUID 优先使用 Web Crypto 生成,能力缺失时回退到 `Math.random()`。
52
-
53
- ```ts
54
- import { configureInstallationIdentity, configureStorage, getOrCreateInstallationId, installationIdentity } from "@fast-china/utils";
55
-
56
- configureStorage({ prefix: "app:" });
57
- configureInstallationIdentity({ cacheKey: "account:installation-id" });
58
- getOrCreateInstallationId();
59
- installationIdentity.read();
60
- installationIdentity.clear();
61
- ```
62
-
63
- 这个 ID 只标识当前存储空间中的安装实例,不是硬件标识、认证凭证、秘密或反欺诈信号。
64
-
65
- ## Logger
66
-
67
- Logger 作用域属于每条日志,不保存在 Logger 或 Child 实例中。默认 `logger` 无需创建即可使用,最低输出级别为 `debug`;uni-app App-Plus
68
- 需要拆分对象输出时,在应用入口配置一次:
69
-
70
- ```ts
71
- import { configureLogger, logger } from "@fast-china/utils";
72
-
73
- configureLogger({ uniAppPlusSplit: true });
74
- logger.log("Launch", { code: 200, data: { id: 1 } });
75
- logger.log("storage", "profile loaded", { userId: 1 });
76
- logger.error("network", "request failed", error);
77
- ```
78
-
79
- 日志内容可省略,也可以直接传入对象、数组、`Error` 等任意值。普通环境会把非字符串值原样传给 Sink;启用 App-Plus
80
- 拆分输出后,为解决 HBuilderX 无法正确显示对象的问题,标题单独输出,附加值逐条转换为可读文本。
81
-
82
- `configureLogger` 会替换默认 `logger` 的完整配置,已经保存的 `logger` 引用也会立即使用新配置;无参数调用会恢复默认值。
83
- `createLogger` 用于创建不受全局配置影响的独立实例。Logger 的 `debug`、`log`、`warn`、`error` 分别调用 Sink 的同名方法,默认 Sink 对应 `console.debug`、`console.log`、`console.warn`、`console.error`。两者均支持最低级别、品牌前缀、Sink 和可选的 App-Plus 拆分输出。
84
- 作用域必须是无外围空白的非空字符串。
85
-
86
- ## 剪贴板
87
-
88
- `copy(value)` 恢复 V1 的文本复制能力,并返回 `Promise<void>`。uni-app 使用 `setClipboardData`;浏览器优先使用 Clipboard API,不可用时回退到 `document.execCommand("copy")`。平台能力缺失、权限被拒绝或复制失败时会抛出错误。
89
-
90
- ```ts
91
- import { copy } from "@fast-china/utils";
92
-
93
- await copy("Fast 工具库");
94
- ```
95
-
96
- ## Crypto
97
-
98
- TypeScript Crypto 公共 API 与 .NET `CryptoUtil` 的公开方法及算法名称大小写保持一致:
99
-
100
- | 能力 | 两端统一的方法名 |
101
- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
102
- | 随机字节与字节比较 | `GenerateRandomBytes`、`FixedTimeEquals` |
103
- | MD5、SHA-1 与 SHA-2 摘要 | `MD5Encrypt`、`SHA1Encrypt`、`SHA256Encrypt`、`SHA256Bytes`、`SHA384Encrypt`、`SHA384Bytes`、`SHA512Encrypt`、`SHA512Bytes` |
104
- | HMAC | `HMACSHA256Encrypt`、`HMACSHA384Encrypt`、`HMACSHA512Encrypt` |
105
- | 密码派生与密码哈希 | `PBKDF2SHA256`、`HashPasswordPBKDF2SHA256`、`VerifyPasswordPBKDF2SHA256` |
106
- | HKDF | `HKDFSHA256` |
107
- | AES | `AESEncrypt`、`AESDecrypt`、`AESEncryptAuthenticated`、`AESDecryptAuthenticated`、`AESEncryptWithPassword`、`AESDecryptWithPassword` |
108
- | RSA | `GenerateRSAKeyPair`、`RSAEncryptOAEP`、`RSADecryptOAEP`、`RSASignPSS`、`RSAVerifyPSS` |
109
- | 椭圆曲线 | `GenerateECDSAKeyPair`、`ECDSASign`、`ECDSAVerify`、`GenerateECDHKeyPair`、`DeriveECDHSecret`、`DeriveECDHKeySHA256` |
110
-
111
- `AESEncryptAuthenticated` 的 Base64 v1 载荷、`AESEncryptWithPassword` 的 `FAST-AES-256-GCM-V1` 载荷、PBKDF2 密码哈希以及 PKCS#8/SPKI PEM 密钥均可与 .NET 双向使用。MD5 与 HMAC 输出小写十六进制;SHA-1/256/384/512 输出大写十六进制,与 .NET 保持一致。
112
-
113
- `AESDecrypt`、`AESDecryptAuthenticated`、`AESDecryptWithPassword` 与 `RSADecryptOAEP` 返回原始字符串类型 `DecodedText`(异步入口返回其 Promise)。返回值可直接作为明文字符串使用,也可通过 `.parseJson<T = any>()` 显式解析 JSON:
114
-
115
- ```ts
116
- const plaintext = await AESDecryptWithPassword(payload, password);
117
- const raw: string = plaintext;
118
- const result = plaintext.parseJson<{ id: number }>();
119
- ```
120
-
121
- 密码存储使用 `HashPasswordPBKDF2SHA256` 和 `VerifyPasswordPBKDF2SHA256`;该哈希不可解密。需要同时保证机密性和完整性的文本使用 AES-GCM 入口。HMAC 用于共享密钥认证,SHA-2 用于摘要,HKDF/PBKDF2 用于密钥派生。MD5、SHA-1、AES-CBC 和 AES-ECB 不提供现代密码存储或认证加密保证。
122
-
123
- ## 模块
124
-
125
- - `array`:分块、压缩、去重、分组、分区、差集、交集、对称差集和一致性判断。
126
- - `async`:支持取消的 Sleep、超时、重试、受限并发映射、防抖和节流。
127
- - `base64`:严格 UTF-8 Base64/Base64URL 字节与链式文本结果,以及 Latin-1 和 SecureBase64 兼容函数。
128
- - `color`:颜色解析、格式化、混合、明暗、亮度和对比度。
129
- - `crypto`:随机字节、摘要、HMAC、PBKDF2、HKDF、AES、RSA-OAEP/PSS、ECDSA 和 ECDH。
130
- - `date`:日期校验、加减、日范围、相对时间,以及七个历史日期功能的具名函数。
131
- - `dom`:CSS 单位和 Style 序列化。
132
- - `env`:能力与 User-Agent 检测;检测函数不扩大运行时支持范围。
133
- - `function`:最多执行一次并缓存返回值、Promise 引用或同步错误的 `once`。
134
- - `logger`:隔离的可配置 Logger 和默认 `logger`。
135
- - `number`:范围、舍入、聚合、插值、字节格式化,以及优先使用 Web Crypto 的 `randomInt`。
136
- - `object`:深复制、深度比较、防原型污染的键和条件筛选、映射及 Query 序列化;Style 序列化由 `dom` 模块提供。
137
- - `string`:Query 解析、大小写、字素截断、剪贴板复制、UUID、优先使用 Web Crypto 的 `randomString`、转义和空白规范化。
138
- - `vue`:Vue 3 的 Composition API、类型、Render 和 `app.use()` 注册 Helper。
139
-
140
- ## 安全与限制
141
-
142
- AES-GCM 提供机密性和完整性;AES-CBC/ECB 不提供认证。MD5、SHA-1 和历史 Base64 字典不能用于密码存储、签名或受保护数据。Crypto API 按算法限制参数和载荷大小,并在需要时强制要求 Web Crypto。
143
-
144
- Query 与 Object API 拒绝原型污染键,URL 解码有最大深度,Storage 清理只作用于配置的命名空间。浏览器全局对象只在调用 API 时解析,模块导入阶段不会访问。
145
-
146
- ## 错误与兼容性
147
-
148
- 除明确说明返回空值的函数外,编程错误、非法输入、平台能力缺失和受保护数据损坏均抛出原生错误。
149
-
150
- 自 Fast.Utils 2.1.1 起,内置校验与运行时失败消息统一使用中文;调用方应依据原生错误类型分支,不应匹配消息文本。
151
-
152
- `randomInt`、`randomString`、`generateUuidV4` 与 `GenerateRandomBytes` 默认都优先使用 Web Crypto,能力缺失时回退到 `Math.random()`。
153
-
154
- Fast.Utils 2.1.0 已删除 `secureRandomInt` 与 `secureRandomString`,这是破坏性修改;调用方应分别改用 `randomInt` 与 `randomString`。
@@ -1,65 +0,0 @@
1
- # Fast.Utils 开发与发布
2
-
3
- ## 基线
4
-
5
- - Node.js:`^22.18.0 || ^24.18.0`。
6
- - pnpm:`^11.0.0`,不固定补丁版本。
7
- - TypeScript 6、tsdown、ESLint 10 Flat Config、Prettier 3。
8
- - 发布格式:包管理器使用 ESM、`.mjs` 与 `.d.mts`,CDN 使用压缩 IIFE;两类 JavaScript 产物均提供 Source Map。
9
- - 根目录是唯一 npm 发布单元,根 `dist/` 是唯一产物目录。
10
-
11
- 应用环境包括现代浏览器、WebView、Vue 3 和 uni-app。
12
-
13
- ## 安装与命令
14
-
15
- ```bash
16
- corepack enable
17
- pnpm install --frozen-lockfile
18
- ```
19
-
20
- | 命令 | 用途 |
21
- | ------------------- | ---------------------------------------------------------------------- |
22
- | `pnpm dev` | 使用 tsdown 监听源码并增量构建 |
23
- | `pnpm build` | 使用 tsdown 构建 ESM 模块与压缩 IIFE |
24
- | `pnpm typecheck` | 检查源码与构建配置类型 |
25
- | `pnpm lint` | 运行零警告 ESLint |
26
- | `pnpm format:check` | 检查 Prettier |
27
- | `pnpm test:types` | 验证公开消费者类型 |
28
- | `pnpm test:runtime` | 运行单元、平台与 Vue Runtime 测试 |
29
- | `pnpm test:package` | 验证 Tarball、公开入口、声明、Source Map、Tree Shaking、体积与 Publint |
30
- | `pnpm check` | 运行统一质量门禁 |
31
-
32
- ## 修改公共模块
33
-
34
- 新增公共模块时必须同步:
35
-
36
- 1. 在 `src/<module>/index.ts` 定义具名 API 和 TSDoc。
37
- 2. 在 `src/index.ts` 统一重新导出公共 API。
38
- 3. 不为模块增加 `package.json#exports` 子路径或独立构建入口。
39
- 4. 增加源码类型、消费者类型、单元和真实包测试。
40
- 5. 更新双语 README、API 和 Changelog。
41
-
42
- 禁止在导入阶段访问浏览器或 uni-app 全局对象。平台能力应在调用阶段解析;`configureStorage` 在调用时自动检测全局 `uni`。
43
-
44
- ## 依赖与锁文件
45
-
46
- - Runtime Dependency 必须证明无法由平台能力或小型实现替代。
47
- - Vue 3.3+ 是必须安装的 Peer Dependency;ESM 与 IIFE 均保持外部引用,不打包进发布产物。
48
- - 依赖升级后使用当前 pnpm 11 更新 Lockfile,并通过 Frozen Lockfile 安装验证。
49
- - 不混用 npm、Yarn 或不同 pnpm 主版本改写 Lockfile。
50
-
51
- ## CI
52
-
53
- CI 在 Node 22 与 24 上运行,使用 Frozen Lockfile,并执行 `pnpm check` 与 Pack Dry Run。不得通过关闭类型、Lint、测试或包验证来修复门禁。
54
-
55
- ## 发布
56
-
57
- 仓库只采用人工发布流程,不声明或配置 OIDC Trusted Publishing:
58
-
59
- 1. 更新 SemVer 与 `CHANGELOG.md` 日期。
60
- 2. 执行 `pnpm install --frozen-lockfile`。
61
- 3. 执行 `pnpm check`。
62
- 4. 人工检查 `pnpm --config.ignore-scripts=true pack --dry-run` 清单。
63
- 5. 由维护者在可信环境执行 npm Publish,并创建对应 `v<version>` Tag。
64
-
65
- 未经明确授权,不执行 Publish、Push、Tag 或 Release。npm 已发布版本不可覆盖;发布后缺陷必须通过新 Patch 或 Pre-release 修复。
@@ -1,42 +0,0 @@
1
- # Fast.Utils runtime contract / 运行时契约
2
-
3
- ## Runtime and package contract
4
-
5
- - Runtime platforms: ES2022 modern browsers, WebViews, Vue 3 applications, and uni-app.
6
- - Package format: one public named-export ESM entry for package managers and one separately minified IIFE entry for CDN use; CommonJS and UMD are not shipped.
7
- - Framework boundary: Vue remains external to the package-manager build and is a required peer in `^3.3.0`.
8
- - uni-app boundary: the first Storage operation, or an earlier `configureStorage({ prefix })` call, detects global `uni` and uses its synchronous Storage API.
9
- - Browser storage: applications import `Local` and `Session` directly; `configureStorage()` is needed only to override defaults before the first operation.
10
- - Storage operation overrides: `set/get({ crypto })` select JSON or Base64 for one operation without mutating global configuration. The v3 envelope does not identify its codec, so callers must use matching options for the same entry.
11
- - Storage read typing: `get<Value = string>()` defaults to `string | undefined` when no generic is supplied; codecs still restore the original runtime JSON value.
12
- - Stateful browser defaults: Storage, Identity, and default Logger configuration are page-global by design. Storage and Identity reject conflicting reconfiguration; `configureLogger` replaces the default Logger configuration while preserving the exported facade reference.
13
- - Randomness: every random generation entry prefers Web Crypto and falls back to `Math.random()` when unavailable.
14
- - Publishing: the repository root is the only package, `dist/` is the only build output, and `package.json#exports` is the complete public path whitelist.
15
-
16
- Importing a module does not itself read `window`, browser Storage, or `uni`, so unsupported platform capabilities fail only when the corresponding API is called.
17
-
18
- ## Public API policy
19
-
20
- - Stateless Array, Date, String, Number, Object, Base64, Color, DOM, Env, Async, and Crypto capabilities use named exports.
21
- - The public API uses named functions instead of mutable aggregate utility objects.
22
- - Base64 and Crypto text decoders return primitive strings typed as `DecodedText`. They can be used directly as strings; an explicit `.parseJson<T = any>()` call attempts JSON parsing and falls back to the original string for invalid JSON. The first text decode lazily installs a non-enumerable `String.prototype.parseJson` and rejects a foreign same-name property instead of overwriting it. Storage codecs continue to parse JSON automatically and strictly.
23
- - Stateful browser capabilities use cohesive package-owned objects: `Local`, `Session`, `installationIdentity`, and Logger instances. Logger exposes the matching `debug`, `log`, `warn`, and `error` levels, defaults to the `debug` minimum, and receives scope on each method rather than storing it in child instances. `createLogger` returns isolated instances, while `configureLogger` only changes the default `logger` facade.
24
- - Internal adapters and client factories are implementation details and are not public export paths.
25
- - Removing a named function, changing Storage/ciphertext formats, raising the browser syntax target, or changing the Vue peer range requires an explicit major-version Breaking Change.
26
-
27
- ## 运行时与包契约
28
-
29
- - 运行平台:ES2022 现代浏览器、WebView、Vue 3 应用和 uni-app。
30
- - 包格式:包管理器使用单一公开具名导出 ESM 入口,CDN 使用单独压缩的 IIFE;不发布 CommonJS 或 UMD。
31
- - Vue 边界:Vue 不会打进包管理器使用的构建产物,是 `^3.3.0` 的必需 Peer。
32
- - uni-app:首次 Storage 操作或更早的 `configureStorage({ prefix })` 调用会检测全局 `uni`,并使用其同步 Storage API。
33
- - Storage:直接从包导入 `Local` 和 `Session` 即可;只有覆盖默认值时才需在首次操作前调用 `configureStorage()`。
34
- - Storage 单次覆盖:`set/get({ crypto })` 只为当前操作选择 JSON 或 Base64,不修改全局配置。v3 包络不记录 Codec,调用方必须对同一条目使用匹配的读写选项。
35
- - Storage 读取类型:`get<Value = string>()` 未传泛型时默认推断为 `string | undefined`,Codec 在运行时仍恢复原始 JSON 值。
36
- - 状态:Storage、Identity 与默认 Logger 配置按浏览器页面全局共享。Storage 和 Identity 的冲突配置明确抛错;`configureLogger` 替换默认 Logger 的配置,同时保持导出的门面引用稳定。
37
- - 随机数:所有随机生成入口都优先使用 Web Crypto,缺失时回退到 `Math.random()`。
38
- - 发布:根目录是唯一 npm 包,`dist/` 是唯一构建输出,`exports` 是完整公共路径白名单。
39
-
40
- 模块导入本身不读取 `window`、浏览器 Storage 或 `uni`,不具备对应平台能力时只在调用相关 API 时明确失败。
41
-
42
- 无状态能力统一使用具名导出。Base64 与 Crypto 文本解码入口返回原始字符串类型 `DecodedText`,可以直接作为字符串使用;`.parseJson<T = any>()` 只在显式调用时尝试解析 JSON,非法 JSON 回退为原始字符串。首次文本解码会按需安装不可枚举的 `String.prototype.parseJson`,若同名属性已被其他实现占用则拒绝覆盖并抛错。Storage Codec 继续严格自动解析 JSON。有状态浏览器能力使用 `Local`、`Session`、`installationIdentity` 和 Logger 实例;Logger 提供与 Sink 同名的 `debug`、`log`、`warn`、`error` 级别,默认最低级别为 `debug`,作用域随每次调用传入,不创建 Child Logger。`createLogger` 返回隔离实例,`configureLogger` 只修改默认 `logger` 门面。