@fast-china/utils 2.0.0 → 2.0.3

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 (80) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/Fast.png +0 -0
  3. package/README.md +27 -29
  4. package/README.zh.md +27 -29
  5. package/dist/base64/index.mjs.map +1 -1
  6. package/dist/crypto/index.d.mts +266 -97
  7. package/dist/crypto/index.mjs +565 -263
  8. package/dist/crypto/index.mjs.map +1 -1
  9. package/dist/identity/index.d.mts +5 -5
  10. package/dist/identity/index.mjs +2 -2
  11. package/dist/identity/index.mjs.map +1 -1
  12. package/dist/index.d.mts +3 -3
  13. package/dist/index.global.min.js +3 -0
  14. package/dist/index.global.min.js.map +1 -0
  15. package/dist/index.mjs +2 -2
  16. package/dist/storage/index.d.mts +11 -8
  17. package/dist/storage/index.mjs +21 -18
  18. package/dist/storage/index.mjs.map +1 -1
  19. package/dist/vue/emits.mjs.map +1 -1
  20. package/dist/vue/index.d.mts +2 -2
  21. package/dist/vue/install.d.mts +11 -29
  22. package/dist/vue/install.mjs +25 -25
  23. package/dist/vue/install.mjs.map +1 -1
  24. package/dist/vue/props.mjs.map +1 -1
  25. package/dist/vue/render.d.mts +2 -3
  26. package/dist/vue/render.mjs +3 -9
  27. package/dist/vue/render.mjs.map +1 -1
  28. package/docs/API.md +30 -14
  29. package/docs/API.zh-CN.md +30 -14
  30. package/docs/DEVELOPMENT_RELEASE.zh-CN.md +4 -4
  31. package/docs/RUNTIME_CONTRACT.md +10 -10
  32. package/package.json +9 -11
  33. package/dist/array/index.d.mts.map +0 -1
  34. package/dist/async/index.d.mts.map +0 -1
  35. package/dist/base64/index.d.mts.map +0 -1
  36. package/dist/color/index.d.mts.map +0 -1
  37. package/dist/crypto/index.d.mts.map +0 -1
  38. package/dist/date/index.d.mts.map +0 -1
  39. package/dist/dom/style.d.mts.map +0 -1
  40. package/dist/env/index.d.mts.map +0 -1
  41. package/dist/identity/index.d.mts.map +0 -1
  42. package/dist/logger/index.d.mts.map +0 -1
  43. package/dist/number/index.d.mts.map +0 -1
  44. package/dist/object/index.d.mts.map +0 -1
  45. package/dist/storage/index.d.mts.map +0 -1
  46. package/dist/string/index.d.mts.map +0 -1
  47. package/dist/vue/emits.d.mts.map +0 -1
  48. package/dist/vue/expose.d.mts.map +0 -1
  49. package/dist/vue/func.d.mts.map +0 -1
  50. package/dist/vue/install.d.mts.map +0 -1
  51. package/dist/vue/props.d.mts.map +0 -1
  52. package/dist/vue/render.d.mts.map +0 -1
  53. package/dist/vue/slots.d.mts.map +0 -1
  54. package/dist/vue/with.d.mts.map +0 -1
  55. package/src/array/index.ts +0 -173
  56. package/src/async/index.ts +0 -475
  57. package/src/base64/index.ts +0 -374
  58. package/src/color/index.ts +0 -208
  59. package/src/crypto/index.ts +0 -670
  60. package/src/date/index.ts +0 -451
  61. package/src/dom/index.ts +0 -6
  62. package/src/dom/style.ts +0 -92
  63. package/src/env/index.ts +0 -169
  64. package/src/identity/index.ts +0 -144
  65. package/src/index.ts +0 -20
  66. package/src/internal/text.ts +0 -46
  67. package/src/logger/index.ts +0 -219
  68. package/src/number/index.ts +0 -235
  69. package/src/object/index.ts +0 -160
  70. package/src/storage/index.ts +0 -524
  71. package/src/string/index.ts +0 -328
  72. package/src/vue/emits.ts +0 -71
  73. package/src/vue/expose.ts +0 -11
  74. package/src/vue/func.ts +0 -17
  75. package/src/vue/index.ts +0 -13
  76. package/src/vue/install.ts +0 -185
  77. package/src/vue/props.ts +0 -39
  78. package/src/vue/render.ts +0 -41
  79. package/src/vue/slots.ts +0 -23
  80. package/src/vue/with.ts +0 -10
@@ -1,524 +0,0 @@
1
- import { decodeBase64, encodeBase64 } from "../base64/index.js";
2
-
3
- /** uni-app 同步存储信息中本库实际读取的字段。 */
4
- interface UniStorageInfo {
5
- /** 当前平台可见的物理键快照。 */
6
- keys: readonly string[];
7
- }
8
-
9
- /** 全局 `uni` 必须提供的同步存储 API 最小结构。 */
10
- interface UniStorageLike {
11
- /**
12
- * 同步读取一个物理键的原始值。
13
- * @param key - 已包含全局命名空间前缀的物理键。
14
- * @returns 平台保存的值;键缺失时应返回 `undefined`、`null` 或空字符串。
15
- */
16
- getStorageSync: (key: string) => unknown;
17
- /**
18
- * 同步读取平台当前可见的全部物理键。
19
- * @returns 至少包含只读 `keys` 数组的快照对象。
20
- */
21
- getStorageInfoSync: () => UniStorageInfo;
22
- /**
23
- * 同步删除一个物理键;键不存在时应保持幂等。
24
- * @param key - 已包含全局命名空间前缀的物理键。
25
- */
26
- removeStorageSync: (key: string) => void;
27
- /**
28
- * 同步写入已经序列化的包络文本。
29
- * @param key - 已包含全局命名空间前缀的物理键。
30
- * @param value - JSON 包络字符串,不是未经编码的业务值。
31
- */
32
- setStorageSync: (key: string, value: string) => void;
33
- }
34
-
35
- /** Storage 业务值编码器。 */
36
- export interface StorageCodec {
37
- /**
38
- * 把已编码文本恢复为业务值。
39
- * @param value - 由同一 Codec 的 `encode` 生成并持久化的文本。
40
- * @returns 解码后的业务值。
41
- * @throws 当文本损坏、格式不受支持或无法反序列化时应抛出错误。
42
- */
43
- decode: (value: string) => unknown;
44
- /**
45
- * 把业务值编码为可持久化字符串。
46
- * @param value - 调用方传入的业务值。
47
- * @returns 可由同一 Codec 的 `decode` 无损恢复的文本。
48
- * @throws 当值不受支持或无法序列化时应抛出错误。
49
- */
50
- encode: (value: unknown) => string;
51
- }
52
-
53
- /** 程序入口调用 {@link configureStorage} 时使用的全局配置。 */
54
- export interface StorageConfiguration {
55
- /** 自定义值编码器;默认使用严格 JSON Codec,同一应用生命周期内必须保持同一引用。 */
56
- codec?: StorageCodec;
57
- /** 返回 Unix 毫秒时间戳的时钟;默认使用 `Date.now`,主要用于 TTL 测试与受控时间源。 */
58
- now?: () => number;
59
- /** 所有物理键使用的非空命名空间前缀;`clear` 与 `keys` 不会越过该范围。 */
60
- prefix: string;
61
- }
62
-
63
- /** 单次 Storage 写入配置。 */
64
- export interface StorageWriteOptions {
65
- /** 从写入时刻开始的有效毫秒数;必须是大于 0 的有限数,省略时永久有效。 */
66
- ttlMs?: number;
67
- }
68
-
69
- /** `Local` 与 `Session` 的统一操作接口。 */
70
- export interface StorageArea {
71
- /** 当前全局 Storage 配置的物理键前缀;读取它会要求 Storage 已经完成配置。 */
72
- readonly prefix: string;
73
- /**
74
- * 删除当前命名空间内的全部键,不影响同一后端中的其他应用键。
75
- * @throws `Error` 当 Storage 尚未配置或后端不可用。
76
- */
77
- clear: () => void;
78
- /**
79
- * 获取并解码业务值;已过期记录会在读取时删除。
80
- * @param key - 不含全局前缀的非空业务键。
81
- * @returns 解码后的值;键缺失或过期时返回 `undefined`。
82
- * @throws 当键非法、包络损坏、Codec 解码失败或后端不可用时抛出错误。
83
- */
84
- get: <Value = unknown>(key: string) => Value | undefined;
85
- /**
86
- * 判断一个可成功读取且未过期的业务键是否存在。
87
- * @param key - 不含全局前缀的非空业务键。
88
- * @returns 键存在且包络有效时返回 `true`。
89
- */
90
- has: (key: string) => boolean;
91
- /**
92
- * 返回当前命名空间内的业务键快照。
93
- * @returns 已移除全局前缀并按字典序排列的新数组;不会自动清理过期项。
94
- */
95
- keys: () => string[];
96
- /**
97
- * 扫描当前命名空间并删除全部过期记录。
98
- * @returns 本次实际删除的记录数量。
99
- * @throws 当发现损坏包络或后端不可用时抛出错误。
100
- */
101
- pruneExpired: () => number;
102
- /**
103
- * 删除单个业务键;键不存在时保持幂等。
104
- * @param key - 不含全局前缀的非空业务键。
105
- */
106
- remove: (key: string) => void;
107
- /**
108
- * 删除业务键以指定文本开头的全部条目,范围仍受全局命名空间限制。
109
- * @param keyPrefix - 不含全局前缀的非空业务键前缀。
110
- */
111
- removeByPrefix: (keyPrefix: string) => void;
112
- /**
113
- * 编码并写入业务值,可附加惰性清理的 TTL。
114
- * @param key - 不含全局前缀的非空业务键。
115
- * @param value - 必须受当前 Codec 支持的业务值。
116
- * @param options - 可选的单次写入 TTL。
117
- * @throws 当键、TTL、业务值或后端写入无效时抛出错误。
118
- */
119
- set: <Value>(key: string, value: Value, options?: StorageWriteOptions) => void;
120
- }
121
-
122
- /** 浏览器 Storage 与 uni-app Storage 适配后的最小内部协议。 */
123
- interface StorageBackend {
124
- /** 读取物理键原始值;缺失约定由上层统一规范为 `undefined`。 */
125
- getItem: (key: string) => unknown;
126
- /** 枚举后端可见的全部物理键;返回值必须是不会随枚举过程变化的快照。 */
127
- keys: () => readonly string[];
128
- /** 删除单个物理键;实现必须允许重复删除。 */
129
- removeItem: (key: string) => void;
130
- /** 写入已经序列化的包络文本;配额和平台错误保持原样传播。 */
131
- setItem: (key: string, value: string) => void;
132
- }
133
-
134
- /** 物理存储中的版本化包络;业务值始终先经 Codec 转为文本。 */
135
- interface StoredEnvelope {
136
- /** Codec 编码后的业务文本;只有在包络结构校验通过后才能交给 Codec。 */
137
- data: string;
138
- /** Unix 毫秒绝对过期时间戳;`null` 表示永久有效。 */
139
- expiresAt: number | null;
140
- /** 当前持久化协议版本;读取其他版本必须明确失败,不能猜测迁移。 */
141
- version: 3;
142
- }
143
-
144
- /** 首次配置后冻结使用的解析结果和两个稳定门面。 */
145
- interface ActiveStorageConfiguration {
146
- /** 首次配置后锁定的业务值 Codec 引用。 */
147
- codec: StorageCodec;
148
- /** 已绑定 Local 后端、命名空间、Codec 与时钟的实际 Area。 */
149
- local: StorageArea;
150
- /** 首次配置后锁定的 TTL 时钟引用。 */
151
- now: () => number;
152
- /** 所有 Area 共享的物理键命名空间前缀。 */
153
- prefix: string;
154
- /** 仅浏览器模式存在的 Session Area;uni-app 模式必须保持缺失。 */
155
- session?: StorageArea;
156
- }
157
-
158
- /** 浏览器 Storage 在调用阶段延迟读取的平台全局对象最小视图。 */
159
- interface RuntimeStorageGlobals {
160
- /** 可选 localStorage;缺失时 `Local` 操作明确失败。 */
161
- localStorage?: Storage;
162
- /** 可选 sessionStorage;缺失时 `Session` 操作明确失败。 */
163
- sessionStorage?: Storage;
164
- /** uni-app 运行时暴露的全局对象;只在调用 `configureStorage` 时读取和校验。 */
165
- uni?: unknown;
166
- }
167
-
168
- const runtimeStorageGlobals = globalThis as unknown as RuntimeStorageGlobals;
169
-
170
- /**
171
- * 读取并校验当前运行时的全局 uni-app 同步 Storage。
172
- *
173
- * @returns 检测到 uni-app 时返回同步 Storage;普通浏览器环境返回 `undefined`。
174
- * @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。
175
- */
176
- const getGlobalUniStorage = (): UniStorageLike | undefined => {
177
- const value = runtimeStorageGlobals.uni;
178
- if (value === undefined) return undefined;
179
- if ((typeof value !== "object" && typeof value !== "function") || value === null) {
180
- throw new TypeError("The global uni object does not provide synchronous Storage APIs.");
181
- }
182
- const storage = value as Partial<UniStorageLike>;
183
- if (
184
- typeof storage.getStorageSync !== "function" ||
185
- typeof storage.getStorageInfoSync !== "function" ||
186
- typeof storage.removeStorageSync !== "function" ||
187
- typeof storage.setStorageSync !== "function"
188
- ) {
189
- throw new TypeError("The global uni object does not provide synchronous Storage APIs.");
190
- }
191
- return storage as UniStorageLike;
192
- };
193
-
194
- /** 默认 JSON Codec;显式拒绝会被 JSON.stringify 静默丢弃的顶层值。 */
195
- const jsonCodec: StorageCodec = {
196
- decode: (value): unknown => JSON.parse(value) as unknown,
197
- encode: (value): string => {
198
- const encoded: unknown = JSON.stringify(value);
199
- if (typeof encoded !== "string") throw new TypeError("The storage value is not JSON-serializable.");
200
- return encoded;
201
- },
202
- };
203
-
204
- /** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */
205
- export const base64StorageCodec: StorageCodec = {
206
- decode: (value): unknown => JSON.parse(decodeBase64(value)) as unknown,
207
- encode: (value): string => {
208
- const encoded: unknown = JSON.stringify(value);
209
- if (typeof encoded !== "string") throw new TypeError("The storage value is not JSON-serializable.");
210
- return encodeBase64(encoded);
211
- },
212
- };
213
-
214
- /** 页面级唯一配置;只允许幂等重复配置,避免模块加载顺序改变行为。 */
215
- let activeConfiguration: ActiveStorageConfiguration | undefined;
216
-
217
- /**
218
- * 判断未知值是否为非数组对象记录。
219
- *
220
- * @param value - JSON.parse 返回的未知值。
221
- * @returns 值为非空、非数组对象时返回 `true`。
222
- */
223
- const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
224
-
225
- /**
226
- * 校验 Storage 业务键。
227
- *
228
- * @param key - 不含全局 Prefix 的业务键或业务键前缀。
229
- * @throws `TypeError` 当值不是非空字符串。
230
- */
231
- const assertKey = (key: string): void => {
232
- if (typeof key !== "string" || key.length === 0) throw new TypeError("Storage keys must be non-empty strings.");
233
- };
234
-
235
- /**
236
- * 创建浏览器 Storage 后端。
237
- *
238
- * @remarks 平台对象在调用阶段读取,因此导入模块不会访问浏览器全局对象。
239
- * @param kind - 选择 `localStorage` 或 `sessionStorage`。
240
- * @returns 统一的内部同步后端。
241
- * @throws `Error` 当所选 Storage 在当前环境不可用。
242
- */
243
- const createWebStorageBackend = (kind: "local" | "session"): StorageBackend => {
244
- const storage = kind === "local" ? runtimeStorageGlobals.localStorage : runtimeStorageGlobals.sessionStorage;
245
- if (storage === undefined) throw new Error(`${kind}Storage is unavailable in the current runtime.`);
246
- return {
247
- getItem: (key): string | null => storage.getItem(key),
248
- keys: (): string[] => {
249
- const keys: string[] = [];
250
- for (let index = 0; index < storage.length; index += 1) {
251
- const key = storage.key(index);
252
- if (key !== null) keys.push(key);
253
- }
254
- return keys;
255
- },
256
- removeItem: (key): void => {
257
- storage.removeItem(key);
258
- },
259
- setItem: (key, value): void => {
260
- storage.setItem(key, value);
261
- },
262
- };
263
- };
264
-
265
- /**
266
- * 把 uni-app 同步 Storage 适配为内部后端。
267
- *
268
- * @remarks uni-app 以空字符串同时表示“键缺失”和“真实空值”,因此空字符串需要结合键清单消除歧义。
269
- * @param storage - 已从全局 `uni` 读取并校验的同步 API。
270
- * @returns 统一的内部同步后端。
271
- */
272
- const createUniStorageBackend = (storage: UniStorageLike): StorageBackend => ({
273
- getItem: (key): unknown => {
274
- const value = storage.getStorageSync(key);
275
- if (value !== "") return value;
276
- return storage.getStorageInfoSync().keys.includes(key) ? value : undefined;
277
- },
278
- keys: (): readonly string[] => [...storage.getStorageInfoSync().keys],
279
- removeItem: (key): void => {
280
- storage.removeStorageSync(key);
281
- },
282
- setItem: (key, value): void => {
283
- storage.setStorageSync(key, value);
284
- },
285
- });
286
-
287
- /**
288
- * 解析并校验版本化 Storage 包络。
289
- *
290
- * @param rawValue - 后端返回的原始值。
291
- * @param key - 用于错误定位的完整物理键。
292
- * @returns 当前 v3 包络。
293
- * @throws `TypeError` 当原始值不是字符串、JSON 损坏、版本不支持或字段类型非法。
294
- */
295
- const parseStoredEnvelope = (rawValue: unknown, key: string): StoredEnvelope => {
296
- if (typeof rawValue !== "string") throw new TypeError(`Storage entry "${key}" is not a string.`);
297
- try {
298
- const parsed = JSON.parse(rawValue) as unknown;
299
- if (
300
- !isRecord(parsed) ||
301
- parsed["version"] !== 3 ||
302
- typeof parsed["data"] !== "string" ||
303
- !(parsed["expiresAt"] === null || (typeof parsed["expiresAt"] === "number" && Number.isFinite(parsed["expiresAt"])))
304
- ) {
305
- throw new TypeError("Unsupported storage envelope.");
306
- }
307
- return { data: parsed["data"], expiresAt: parsed["expiresAt"], version: 3 };
308
- } catch (cause) {
309
- throw new TypeError(`Storage entry "${key}" is corrupted or unsupported.`, { cause });
310
- }
311
- };
312
-
313
- /**
314
- * 创建绑定命名空间、Codec 与时钟的 Storage Area。
315
- *
316
- * @param backendFactory - 每次操作时解析平台后端的工厂,保证导入安全并反映平台可用性。
317
- * @param prefix - 已校验的全局物理键前缀。
318
- * @param codec - 业务值与包络文本之间的 Codec。
319
- * @param now - TTL 计算使用的可注入时钟。
320
- * @returns 完整的命名空间 Storage 操作集合。
321
- */
322
- const createStorageArea = (backendFactory: () => StorageBackend, prefix: string, codec: StorageCodec, now: () => number): StorageArea => {
323
- /**
324
- * 拼接物理键。
325
- *
326
- * @param key - 已校验业务键。
327
- * @returns 带当前命名空间前缀的物理键。
328
- */
329
- const toStorageKey = (key: string): string => `${prefix}${key}`;
330
- /**
331
- * 枚举当前命名空间中的业务键。
332
- *
333
- * @param backend - 本次操作使用的后端。
334
- * @returns 已移除物理前缀、去重并排序的业务键。
335
- * @throws `TypeError` 当后端返回非字符串键。
336
- */
337
- const listBusinessKeys = (backend: StorageBackend): string[] => {
338
- const keys = backend.keys();
339
- if (!Array.isArray(keys) || !keys.every((key) => typeof key === "string")) {
340
- throw new TypeError("Storage backend keys must be strings.");
341
- }
342
- return [...new Set(keys.filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length)))].sort();
343
- };
344
- /**
345
- * 读取并处理单个包络。
346
- *
347
- * @param backend - 本次操作使用的后端。
348
- * @param key - 业务键。
349
- * @returns 未过期包络;键缺失或已经过期时返回 `undefined`。
350
- * @throws `TypeError` 当键或包络非法。
351
- * @throws `RangeError` 当注入时钟返回非有限时间戳。
352
- */
353
- const readStoredEnvelope = (backend: StorageBackend, key: string): StoredEnvelope | undefined => {
354
- assertKey(key);
355
- const storageKey = toStorageKey(key);
356
- const rawValue = backend.getItem(storageKey);
357
- if (rawValue === null || rawValue === undefined) return undefined;
358
- const envelope = parseStoredEnvelope(rawValue, storageKey);
359
- if (envelope.expiresAt === null) return envelope;
360
- const timestamp = now();
361
- if (!Number.isFinite(timestamp)) throw new RangeError("Storage clock must return a finite timestamp.");
362
- if (timestamp < envelope.expiresAt) return envelope;
363
- // 过期项在读取时立即删除,后续 has/keys/pruneExpired 观察到一致状态。
364
- backend.removeItem(storageKey);
365
- return undefined;
366
- };
367
-
368
- return {
369
- prefix,
370
- clear(): void {
371
- const backend = backendFactory();
372
- for (const key of listBusinessKeys(backend)) backend.removeItem(toStorageKey(key));
373
- },
374
- get<Value>(key: string): Value | undefined {
375
- const envelope = readStoredEnvelope(backendFactory(), key);
376
- if (envelope === undefined) return undefined;
377
- try {
378
- return codec.decode(envelope.data) as Value;
379
- } catch (cause) {
380
- throw new TypeError(`Storage entry "${toStorageKey(key)}" could not be decoded.`, { cause });
381
- }
382
- },
383
- has: (key): boolean => readStoredEnvelope(backendFactory(), key) !== undefined,
384
- keys: (): string[] => listBusinessKeys(backendFactory()),
385
- pruneExpired(): number {
386
- const backend = backendFactory();
387
- let removed = 0;
388
- for (const key of listBusinessKeys(backend)) {
389
- // read 同时处理删除;先读取一次用于区分“原本缺失”和“本轮因过期删除”。
390
- const before = backend.getItem(toStorageKey(key));
391
- if (before !== null && before !== undefined && readStoredEnvelope(backend, key) === undefined) removed += 1;
392
- }
393
- return removed;
394
- },
395
- remove(key: string): void {
396
- assertKey(key);
397
- backendFactory().removeItem(toStorageKey(key));
398
- },
399
- removeByPrefix(keyPrefix: string): void {
400
- assertKey(keyPrefix);
401
- const backend = backendFactory();
402
- for (const key of listBusinessKeys(backend)) if (key.startsWith(keyPrefix)) backend.removeItem(toStorageKey(key));
403
- },
404
- set<Value>(key: string, value: Value, options: StorageWriteOptions = {}): void {
405
- assertKey(key);
406
- if (value === undefined) throw new TypeError("Top-level undefined cannot be stored; remove the key instead.");
407
- let expiresAt: number | null = null;
408
- if (options.ttlMs !== undefined) {
409
- if (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) throw new RangeError("ttlMs must be a positive finite number.");
410
- const timestamp = now();
411
- if (!Number.isFinite(timestamp) || !Number.isFinite(timestamp + options.ttlMs)) {
412
- throw new RangeError("Storage expiry exceeds the supported timestamp range.");
413
- }
414
- expiresAt = timestamp + options.ttlMs;
415
- }
416
- let data: string;
417
- try {
418
- data = codec.encode(value);
419
- if (typeof data !== "string") throw new TypeError("Storage codecs must return strings.");
420
- } catch (cause) {
421
- throw new TypeError("The storage value could not be encoded.", { cause });
422
- }
423
- backendFactory().setItem(toStorageKey(key), JSON.stringify({ data, expiresAt, version: 3 } satisfies StoredEnvelope));
424
- },
425
- };
426
- };
427
-
428
- /**
429
- * 获取已激活的全局 Storage 配置。
430
- *
431
- * @returns 首次 `configureStorage` 创建的内部配置。
432
- * @throws `Error` 当应用入口尚未配置 Storage。
433
- */
434
- const requireStorageConfiguration = (): ActiveStorageConfiguration => {
435
- if (activeConfiguration === undefined) {
436
- throw new Error("Storage is not configured. Call configureStorage() once from the application entry.");
437
- }
438
- return activeConfiguration;
439
- };
440
-
441
- /**
442
- * 创建稳定的公开 Storage 门面。
443
- *
444
- * @param select - 从激活配置选择 Local 或 Session 的函数。
445
- * @param name - 用于不可用错误的公开门面名称。
446
- * @returns 可在配置前导入、但只在调用时解析实际 Area 的稳定对象。
447
- */
448
- const createStorageAreaProxy = (select: (configuration: ActiveStorageConfiguration) => StorageArea | undefined, name: string): StorageArea => {
449
- /**
450
- * 解析当前实际 Area。
451
- *
452
- * @returns 配置中的 Local 或 Session Area。
453
- * @throws `Error` 当尚未配置,或 uni-app 模式请求 Session。
454
- */
455
- const getArea = (): StorageArea => {
456
- const area = select(requireStorageConfiguration());
457
- if (area === undefined) throw new Error(`${name} is unavailable in uni-app.`);
458
- return area;
459
- };
460
- return {
461
- get prefix(): string {
462
- return getArea().prefix;
463
- },
464
- clear: (): void => {
465
- getArea().clear();
466
- },
467
- get: <Value>(key: string): Value | undefined => getArea().get<Value>(key),
468
- has: (key): boolean => getArea().has(key),
469
- keys: (): string[] => getArea().keys(),
470
- pruneExpired: (): number => getArea().pruneExpired(),
471
- remove: (key): void => {
472
- getArea().remove(key);
473
- },
474
- removeByPrefix: (keyPrefix): void => {
475
- getArea().removeByPrefix(keyPrefix);
476
- },
477
- set: <Value>(key: string, value: Value, options?: StorageWriteOptions): void => {
478
- getArea().set(key, value, options);
479
- },
480
- };
481
- };
482
-
483
- /** 浏览器 localStorage 或自动检测的 uni-app Storage 全局业务入口。 */
484
- export const Local: StorageArea = createStorageAreaProxy((configuration) => configuration.local, "Local");
485
-
486
- /** 浏览器 sessionStorage 的全局业务入口;uni-app 不提供会话存储。 */
487
- export const Session: StorageArea = createStorageAreaProxy((configuration) => configuration.session, "Session");
488
-
489
- /**
490
- * 在应用入口一次性配置 `Local` 与 `Session`。
491
- *
492
- * @remarks 首次配置后只允许以完全相同的值和引用重复调用。模块导入不会访问平台对象;调用本函数时若检测到
493
- * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。
494
- * @param options - 全局键前缀、Codec 与时钟。
495
- * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。
496
- */
497
- export function configureStorage(options: StorageConfiguration): void {
498
- if (typeof options.prefix !== "string" || options.prefix.length === 0) {
499
- throw new TypeError("Storage prefix must be a non-empty string.");
500
- }
501
- const codec = options.codec ?? jsonCodec;
502
- const now = options.now ?? Date.now;
503
- if (activeConfiguration !== undefined) {
504
- // 相同配置允许多个入口模块幂等调用;任何引用或值变化都视为冲突。
505
- if (activeConfiguration.prefix === options.prefix && activeConfiguration.codec === codec && activeConfiguration.now === now) {
506
- return;
507
- }
508
- throw new Error("Storage has already been configured with different options.");
509
- }
510
- const uni = getGlobalUniStorage();
511
- const localBackend =
512
- uni === undefined ? (): StorageBackend => createWebStorageBackend("local") : (): StorageBackend => createUniStorageBackend(uni);
513
- const local = createStorageArea(localBackend, options.prefix, codec, now);
514
- const configuration: ActiveStorageConfiguration = { codec, local, now, prefix: options.prefix };
515
- if (uni === undefined) {
516
- configuration.session = createStorageArea(() => createWebStorageBackend("session"), options.prefix, codec, now);
517
- }
518
- activeConfiguration = configuration;
519
- }
520
-
521
- /** 返回全局 Storage 是否已经由应用入口配置。 */
522
- export function isStorageConfigured(): boolean {
523
- return activeConfiguration !== undefined;
524
- }