@kevisual/api 0.0.47 → 0.0.49

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.
@@ -0,0 +1,444 @@
1
+ // store/store-mark/index.ts
2
+ import { create } from "zustand";
3
+
4
+ // dist/query-mark.js
5
+ var isTextForContentType = (contentType) => {
6
+ if (!contentType)
7
+ return false;
8
+ const textTypes = ["text/", "xml", "html", "javascript", "css", "csv", "plain", "x-www-form-urlencoded", "md"];
9
+ return textTypes.some((type) => contentType.includes(type));
10
+ };
11
+ var adapter = async (opts = {}, overloadOpts) => {
12
+ const controller = new AbortController;
13
+ const signal = controller.signal;
14
+ const isPostFile = opts.isPostFile || false;
15
+ let responseType = opts.responseType || "json";
16
+ if (opts.isBlob) {
17
+ responseType = "blob";
18
+ } else if (opts.isText) {
19
+ responseType = "text";
20
+ }
21
+ const timeout = opts.timeout || 60000 * 3;
22
+ const timer = setTimeout(() => {
23
+ controller.abort();
24
+ }, timeout);
25
+ let method = overloadOpts?.method || opts?.method || "POST";
26
+ let headers = { ...opts?.headers, ...overloadOpts?.headers };
27
+ let origin = "";
28
+ let url;
29
+ if (opts?.url?.startsWith("http")) {
30
+ url = new URL(opts.url);
31
+ } else {
32
+ origin = window?.location?.origin || "http://localhost:51515";
33
+ url = new URL(opts?.url || "", origin);
34
+ }
35
+ const isGet = method === "GET";
36
+ const oldSearchParams = url.searchParams;
37
+ if (isGet) {
38
+ let searchParams = new URLSearchParams({ ...Object.fromEntries(oldSearchParams), ...opts?.params, ...opts?.body });
39
+ url.search = searchParams.toString();
40
+ } else {
41
+ const params = {
42
+ ...Object.fromEntries(oldSearchParams),
43
+ ...opts.params
44
+ };
45
+ const searchParams = new URLSearchParams(params);
46
+ if (typeof opts.body === "object" && opts.body !== null) {
47
+ let body2 = opts.body || {};
48
+ if (!params.path && body2?.path) {
49
+ searchParams.set("path", body2.path);
50
+ if (body2?.key) {
51
+ searchParams.set("key", body2.key);
52
+ }
53
+ }
54
+ }
55
+ url.search = searchParams.toString();
56
+ }
57
+ let body = undefined;
58
+ if (isGet) {
59
+ body = undefined;
60
+ } else if (isPostFile) {
61
+ body = opts.body;
62
+ } else {
63
+ if (opts.body && typeof opts.body === "object" && !(opts.body instanceof FormData)) {
64
+ headers = {
65
+ "Content-Type": "application/json",
66
+ ...headers
67
+ };
68
+ body = JSON.stringify(opts.body);
69
+ }
70
+ }
71
+ return fetch(url, {
72
+ method: method.toUpperCase(),
73
+ signal,
74
+ body,
75
+ ...overloadOpts,
76
+ headers
77
+ }).then(async (response) => {
78
+ const contentType = response.headers.get("Content-Type");
79
+ if (responseType === "blob") {
80
+ return await response.blob();
81
+ }
82
+ const isText = responseType === "text";
83
+ const isJson = contentType && contentType.includes("application/json");
84
+ if (isJson && !isText) {
85
+ return await response.json();
86
+ } else if (isTextForContentType(contentType)) {
87
+ return {
88
+ code: response.status,
89
+ status: response.status,
90
+ data: await response.text()
91
+ };
92
+ } else {
93
+ return response;
94
+ }
95
+ }).catch((err) => {
96
+ if (err.name === "AbortError") {
97
+ return {
98
+ code: 408,
99
+ message: "请求超时"
100
+ };
101
+ }
102
+ return {
103
+ code: 500,
104
+ message: err.message || "网络错误"
105
+ };
106
+ }).finally(() => {
107
+ clearTimeout(timer);
108
+ });
109
+ };
110
+ var wrapperError = ({ code, message }) => {
111
+ const result = {
112
+ code: code || 500,
113
+ success: false,
114
+ message: message || "api request error",
115
+ showError: (fn) => {},
116
+ noMsg: true
117
+ };
118
+ return result;
119
+ };
120
+
121
+ class Query {
122
+ adapter;
123
+ url;
124
+ beforeRequest;
125
+ afterResponse;
126
+ headers;
127
+ timeout;
128
+ stop;
129
+ qws;
130
+ isClient = false;
131
+ constructor(opts) {
132
+ this.adapter = opts?.adapter || adapter;
133
+ const defaultURL = opts?.isClient ? "/client/router" : "/api/router";
134
+ this.url = opts?.url || defaultURL;
135
+ this.headers = opts?.headers || {
136
+ "Content-Type": "application/json"
137
+ };
138
+ this.timeout = opts?.timeout || 60000 * 3;
139
+ if (opts?.beforeRequest) {
140
+ this.beforeRequest = opts.beforeRequest;
141
+ } else {
142
+ this.beforeRequest = async (opts2) => {
143
+ const token = globalThis?.localStorage?.getItem("token");
144
+ if (token) {
145
+ opts2.headers = {
146
+ ...opts2.headers,
147
+ Authorization: `Bearer ${token}`
148
+ };
149
+ }
150
+ return opts2;
151
+ };
152
+ }
153
+ }
154
+ setQueryWs(qws) {
155
+ this.qws = qws;
156
+ }
157
+ setStop(stop) {
158
+ this.stop = stop;
159
+ }
160
+ async get(params, options) {
161
+ return this.post(params, options);
162
+ }
163
+ async post(body, options) {
164
+ const url = options?.url || this.url;
165
+ const { headers, adapter: adapter2, beforeRequest, afterResponse, timeout, ...rest } = options || {};
166
+ const _headers = { ...this.headers, ...headers };
167
+ const _adapter = adapter2 || this.adapter;
168
+ const _beforeRequest = beforeRequest || this.beforeRequest;
169
+ const _afterResponse = afterResponse || this.afterResponse;
170
+ const _timeout = timeout || this.timeout;
171
+ const req = {
172
+ url,
173
+ headers: _headers,
174
+ body,
175
+ timeout: _timeout,
176
+ ...rest
177
+ };
178
+ try {
179
+ if (_beforeRequest) {
180
+ const res = await _beforeRequest(req);
181
+ if (res === false) {
182
+ return wrapperError({
183
+ code: 500,
184
+ message: "request is cancel",
185
+ req
186
+ });
187
+ }
188
+ }
189
+ } catch (e) {
190
+ console.error("request beforeFn error", e, req);
191
+ return wrapperError({
192
+ code: 500,
193
+ message: "api request beforeFn error"
194
+ });
195
+ }
196
+ if (this.stop && !options?.noStop) {
197
+ const that = this;
198
+ await new Promise((resolve) => {
199
+ let timer = 0;
200
+ const detect = setInterval(() => {
201
+ if (!that.stop) {
202
+ clearInterval(detect);
203
+ resolve(true);
204
+ }
205
+ timer++;
206
+ if (timer > 30) {
207
+ console.error("request stop: timeout", req.url, timer);
208
+ }
209
+ }, 1000);
210
+ });
211
+ }
212
+ return _adapter(req).then(async (res) => {
213
+ try {
214
+ if (_afterResponse) {
215
+ return await _afterResponse(res, {
216
+ req,
217
+ res,
218
+ fetch: adapter2
219
+ });
220
+ }
221
+ return res;
222
+ } catch (e) {
223
+ console.error("request afterFn error", e, req);
224
+ return wrapperError({
225
+ code: 500,
226
+ message: "api request afterFn error"
227
+ });
228
+ }
229
+ });
230
+ }
231
+ before(fn) {
232
+ this.beforeRequest = fn;
233
+ }
234
+ after(fn) {
235
+ this.afterResponse = fn;
236
+ }
237
+ async fetchText(urlOrOptions, options) {
238
+ let _options = { ...options };
239
+ if (typeof urlOrOptions === "string" && !_options.url) {
240
+ _options.url = urlOrOptions;
241
+ }
242
+ if (typeof urlOrOptions === "object") {
243
+ _options = { ...urlOrOptions, ..._options };
244
+ }
245
+ const res = await adapter({
246
+ method: "GET",
247
+ ..._options,
248
+ headers: {
249
+ ...this.headers,
250
+ ..._options?.headers || {}
251
+ }
252
+ });
253
+ if (res && !res.code) {
254
+ return {
255
+ code: 200,
256
+ data: res
257
+ };
258
+ }
259
+ return res;
260
+ }
261
+ }
262
+ class QueryMarkBase {
263
+ query;
264
+ isBrowser;
265
+ load;
266
+ storage;
267
+ onLoad;
268
+ constructor(opts) {
269
+ this.query = opts?.query || new Query;
270
+ this.isBrowser = opts?.isBrowser ?? true;
271
+ this.init();
272
+ this.onLoad = opts?.onLoad;
273
+ }
274
+ setQuery(query) {
275
+ this.query = query;
276
+ }
277
+ async init() {
278
+ this.load = true;
279
+ this.onLoad?.();
280
+ }
281
+ async post(data, opts) {
282
+ try {
283
+ return this.query.post({ path: "mark", ...data }, opts);
284
+ } catch (error) {
285
+ console.log("error", error);
286
+ return {
287
+ code: 400
288
+ };
289
+ }
290
+ }
291
+ async getMarkList(search, opts) {
292
+ return this.post({ key: "list", ...search }, opts);
293
+ }
294
+ async getMark(id, opts) {
295
+ return this.post({ key: "get", id }, opts);
296
+ }
297
+ async getVersion(id, opts) {
298
+ return this.post({ key: "getVersion", id }, opts);
299
+ }
300
+ async checkVersion(id, version, opts) {
301
+ if (!version) {
302
+ return true;
303
+ }
304
+ const res = await this.getVersion(id, opts);
305
+ if (res.code === 200) {
306
+ if (res.data.version > version) {
307
+ return true;
308
+ }
309
+ return false;
310
+ }
311
+ return true;
312
+ }
313
+ async updateMark(data, opts) {
314
+ return this.post({ key: "update", data }, opts);
315
+ }
316
+ async deleteMark(id, opts) {
317
+ return this.post({ key: "delete", id }, opts);
318
+ }
319
+ }
320
+
321
+ class QueryMark extends QueryMarkBase {
322
+ markType;
323
+ constructor(opts) {
324
+ super(opts);
325
+ this.markType = opts?.markType || "simple";
326
+ }
327
+ async getMarkList(search, opts) {
328
+ return this.post({ key: "list", ...search, markType: this.markType }, opts);
329
+ }
330
+ async updateMark(data, opts) {
331
+ if (!data.id) {
332
+ data.markType = this.markType || "simple";
333
+ }
334
+ return super.updateMark(data, opts);
335
+ }
336
+ }
337
+
338
+ // node_modules/.pnpm/es-toolkit@1.44.0/node_modules/es-toolkit/dist/array/uniqBy.mjs
339
+ function uniqBy(arr, mapper) {
340
+ const map = new Map;
341
+ for (let i = 0;i < arr.length; i++) {
342
+ const item = arr[i];
343
+ const key = mapper(item, i, arr);
344
+ if (!map.has(key)) {
345
+ map.set(key, item);
346
+ }
347
+ }
348
+ return Array.from(map.values());
349
+ }
350
+ // store/store-mark/index.ts
351
+ import { useContextKey } from "@kevisual/context";
352
+ var queryClient = useContextKey("queryLogin");
353
+ var useMarkStore = create((set, get) => {
354
+ return {
355
+ currentMarkId: "",
356
+ setCurrentMarkId: (markId) => set(() => ({ currentMarkId: markId })),
357
+ open: false,
358
+ setOpen: (open) => set(() => ({ open })),
359
+ getList: async () => {
360
+ const queryMark = get().queryMark;
361
+ const { search, pagination } = get();
362
+ const res = await queryMark.getMarkList({ page: pagination.current, pageSize: pagination.pageSize, search });
363
+ const oldList = get().list;
364
+ if (res.code === 200) {
365
+ const { pagination: pagination2, list } = res.data || {};
366
+ const newList = [...oldList, ...list];
367
+ const uniqueList = uniqBy(newList, (item) => item.id);
368
+ set(() => ({ list: uniqueList }));
369
+ set(() => ({ pagination: { current: pagination2.current, pageSize: pagination2.pageSize, total: pagination2.total } }));
370
+ }
371
+ },
372
+ getMarkFromList: (markId) => {
373
+ return get().list.find((item) => item.id === markId);
374
+ },
375
+ updateMark: async (mark) => {
376
+ const queryMark = get().queryMark;
377
+ const res = await queryMark.updateMark(mark);
378
+ if (res.code === 200) {
379
+ set((state) => {
380
+ const oldList = state.list;
381
+ const resMark = res.data;
382
+ const newList = oldList.map((item) => item.id === mark.id ? mark : item);
383
+ if (!mark.id) {
384
+ newList.unshift(resMark);
385
+ }
386
+ return {
387
+ list: newList
388
+ };
389
+ });
390
+ }
391
+ return res;
392
+ },
393
+ getMark: async (markId) => {
394
+ const queryMark = get().queryMark;
395
+ const res = await queryMark.getMark(markId);
396
+ return res;
397
+ },
398
+ list: [],
399
+ setList: (list) => set(() => ({ list })),
400
+ init: async (markType = "wallnote") => {
401
+ console.log("init", set, get);
402
+ const queryMark = new QueryMark({
403
+ query: queryClient,
404
+ markType
405
+ });
406
+ const url = new URL(window.location.href);
407
+ const pageSize = url.searchParams.get("pageSize") || "10";
408
+ set({ queryMark, markType, list: [], pagination: { current: 1, pageSize: parseInt(pageSize), total: 0 }, currentMarkId: "", markData: undefined });
409
+ setTimeout(async () => {
410
+ console.log("get", get);
411
+ get().getList();
412
+ }, 1000);
413
+ },
414
+ deleteMark: async (markId) => {
415
+ const queryMark = get().queryMark;
416
+ const res = await queryMark.deleteMark(markId);
417
+ const currentMarkId = get().currentMarkId;
418
+ if (res.code === 200) {
419
+ set((state) => ({
420
+ list: state.list.filter((item) => item.id !== markId)
421
+ }));
422
+ if (currentMarkId === markId) {
423
+ set(() => ({ currentMarkId: "", markData: undefined }));
424
+ }
425
+ }
426
+ return res;
427
+ },
428
+ queryMark: undefined,
429
+ markType: "simple",
430
+ markData: undefined,
431
+ setMarkData: (mark) => set(() => ({ markData: mark })),
432
+ pagination: {
433
+ current: 1,
434
+ pageSize: 10,
435
+ total: 0
436
+ },
437
+ setPagination: (pagination) => set(() => ({ pagination })),
438
+ search: "",
439
+ setSearch: (search) => set(() => ({ search, list: [], pagination: { current: 1, pageSize: 10, total: 0 } }))
440
+ };
441
+ });
442
+ export {
443
+ useMarkStore
444
+ };
package/dist/utils.d.ts CHANGED
@@ -4,15 +4,15 @@ declare const alphanumericWithDash = "abcdefghijklmnopqrstuvwxyz0123456789-";
4
4
  /**
5
5
  * 创建一个随机的字母字符串
6
6
  */
7
- declare const uuid: any;
7
+ declare const uuid: (size?: number) => string;
8
8
  /**
9
9
  * 创建一个随机的 id,包含字母和数字
10
10
  */
11
- declare const nanoid: any;
11
+ declare const nanoid: (size?: number) => string;
12
12
  /**
13
13
  * 创建一个随机的 id,包含字母、数字和短横线
14
14
  */
15
- declare const nanoidWithDash: any;
15
+ declare const nanoidWithDash: (size?: number) => string;
16
16
  /**
17
17
  * 创建一个随机的 id,以字母开头的字符串
18
18
  * @param number
package/dist/utils.js CHANGED
@@ -1,44 +1,22 @@
1
- // node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/index.js
2
- import { webcrypto as crypto } from "node:crypto";
3
- var POOL_SIZE_MULTIPLIER = 128;
4
- var pool;
5
- var poolOffset;
6
- function fillPool(bytes) {
7
- if (!pool || pool.length < bytes) {
8
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
9
- crypto.getRandomValues(pool);
10
- poolOffset = 0;
11
- } else if (poolOffset + bytes > pool.length) {
12
- crypto.getRandomValues(pool);
13
- poolOffset = 0;
14
- }
15
- poolOffset += bytes;
16
- }
17
- function random(bytes) {
18
- fillPool(bytes |= 0);
19
- return pool.subarray(poolOffset - bytes, poolOffset);
20
- }
21
- function customRandom(alphabet, defaultSize, getRandom) {
22
- let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
23
- let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
1
+ // node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/index.browser.js
2
+ var random = (bytes) => crypto.getRandomValues(new Uint8Array(bytes));
3
+ var customRandom = (alphabet, defaultSize, getRandom) => {
4
+ let mask = (2 << Math.log2(alphabet.length - 1)) - 1;
5
+ let step = -~(1.6 * mask * defaultSize / alphabet.length);
24
6
  return (size = defaultSize) => {
25
- if (!size)
26
- return "";
27
7
  let id = "";
28
8
  while (true) {
29
9
  let bytes = getRandom(step);
30
- let i = step;
31
- while (i--) {
32
- id += alphabet[bytes[i] & mask] || "";
10
+ let j = step | 0;
11
+ while (j--) {
12
+ id += alphabet[bytes[j] & mask] || "";
33
13
  if (id.length >= size)
34
14
  return id;
35
15
  }
36
16
  }
37
17
  };
38
- }
39
- function customAlphabet(alphabet, size = 21) {
40
- return customRandom(alphabet, size, random);
41
- }
18
+ };
19
+ var customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size | 0, random);
42
20
 
43
21
  // query/utils/random.ts
44
22
  var letter = "abcdefghijklmnopqrstuvwxyz";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevisual/api",
3
- "version": "0.0.47",
3
+ "version": "0.0.49",
4
4
  "description": "",
5
5
  "main": "mod.ts",
6
6
  "scripts": {
@@ -12,31 +12,31 @@
12
12
  "files": [
13
13
  "dist",
14
14
  "query",
15
+ "store",
15
16
  "mod.ts"
16
17
  ],
17
18
  "keywords": [],
18
19
  "author": "abearxiong <xiongxiao@xiongxiao.me> (https://www.xiongxiao.me)",
19
20
  "license": "MIT",
20
- "packageManager": "pnpm@10.28.2",
21
+ "packageManager": "pnpm@10.29.3",
21
22
  "type": "module",
22
23
  "devDependencies": {
23
24
  "@kevisual/cache": "^0.0.5",
24
25
  "@kevisual/code-builder": "^0.0.6",
25
- "@kevisual/query": "^0.0.39",
26
+ "@kevisual/query": "^0.0.40",
26
27
  "@kevisual/remote-app": "^0.0.4",
27
28
  "@kevisual/router": "^0.0.70",
28
29
  "@kevisual/types": "^0.0.12",
29
30
  "@kevisual/use-config": "^1.0.30",
30
- "@types/bun": "^1.3.8",
31
- "@types/crypto-js": "^4.2.2",
32
- "@types/node": "^25.2.0",
31
+ "@types/bun": "^1.3.9",
32
+ "@types/node": "^25.2.3",
33
33
  "@types/spark-md5": "^3.0.5",
34
- "crypto-js": "^4.2.0",
35
- "dotenv": "^17.2.3",
34
+ "dotenv": "^17.3.1",
36
35
  "fast-glob": "^3.3.3",
37
36
  "ws": "npm:@kevisual/ws"
38
37
  },
39
38
  "dependencies": {
39
+ "@kevisual/context": "^0.0.4",
40
40
  "@kevisual/js-filter": "^0.0.5",
41
41
  "@kevisual/load": "^0.0.6",
42
42
  "es-toolkit": "^1.44.0",
@@ -44,7 +44,9 @@
44
44
  "fuse.js": "^7.1.0",
45
45
  "nanoid": "^5.1.6",
46
46
  "path-browserify-esm": "^1.0.6",
47
- "spark-md5": "^3.0.2"
47
+ "sonner": "^2.0.7",
48
+ "spark-md5": "^3.0.2",
49
+ "zustand": "^5.0.11"
48
50
  },
49
51
  "exports": {
50
52
  ".": "./mod.ts",
@@ -54,8 +56,9 @@
54
56
  "./proxy": "./query/query-proxy/index.ts",
55
57
  "./secret": "./query/query-secret/index.ts",
56
58
  "./resources": "./query/query-resources/index.ts",
57
- "./query-secret": "./dist/query-secret.js",
58
59
  "./utils": "./dist/utils.js",
60
+ "./query-secret": "./dist/query-secret.js",
61
+ "./query-mark": "./dist/query-mark.js",
59
62
  "./query-upload": "./dist/query-upload.js",
60
63
  "./query-app": "./dist/query-app.js",
61
64
  "./query-proxy": "./dist/query-proxy.js",
@@ -63,6 +66,11 @@
63
66
  "./query-config": "./dist/query-config.js",
64
67
  "./query-login": "./dist/query-login.js",
65
68
  "./query-ai": "./dist/query-ai.js",
66
- "./query-resources": "./dist/query-resources.js"
69
+ "./query-resources": "./dist/query-resources.js",
70
+ "./store-mark": "./dist/store-mark.js",
71
+ "./store-auth": "./dist/store-auth.js",
72
+ "./src/*": "./src/*",
73
+ "./store/*": "./src/*",
74
+ "./query/*": "./query/*"
67
75
  }
68
76
  }
@@ -31,6 +31,8 @@ export type CacheLoginUser = {
31
31
  id?: string;
32
32
  accessToken?: string;
33
33
  refreshToken?: string;
34
+ accessTokenExpiresIn?: number;
35
+ createdAt?: number;
34
36
  };
35
37
  type CacheLogin = {
36
38
  loginUsers: CacheLoginUser[];
@@ -162,6 +164,8 @@ export class LoginCacheStore implements CacheStore<any> {
162
164
  this.cacheData.id = user.id;
163
165
  this.cacheData.accessToken = user.accessToken;
164
166
  this.cacheData.refreshToken = user.refreshToken;
167
+ this.cacheData.accessTokenExpiresIn = user.accessTokenExpiresIn;
168
+ this.cacheData.createdAt = user.createdAt;
165
169
  await this.setValue(this.cacheData);
166
170
  }
167
171