@mx-space/api-client 1.0.0-alpha.3 → 1.0.0-beta.0

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 (75) hide show
  1. package/build/index.cjs.js +980 -0
  2. package/build/index.cjs.js.map +1 -0
  3. package/build/index.cjs.min.js +2 -0
  4. package/build/index.cjs.min.js.map +1 -0
  5. package/build/index.esm.min.mjs +2 -0
  6. package/build/index.esm.min.mjs.map +1 -0
  7. package/build/index.esm.mjs +958 -0
  8. package/build/index.esm.mjs.map +1 -0
  9. package/build/index.umd.js +25 -31
  10. package/build/index.umd.js.map +1 -1
  11. package/build/index.umd.min.js +1 -1
  12. package/build/index.umd.min.js.map +1 -1
  13. package/{build → dist}/adaptors/axios.cjs +0 -0
  14. package/{build → dist}/adaptors/axios.cjs.map +0 -0
  15. package/dist/adaptors/axios.d.ts +31 -0
  16. package/{build → dist}/adaptors/axios.js +0 -0
  17. package/{build → dist}/adaptors/axios.js.map +0 -0
  18. package/{build → dist}/adaptors/axios.min.cjs +0 -0
  19. package/{build → dist}/adaptors/axios.min.cjs.map +0 -0
  20. package/{build → dist}/adaptors/axios.min.js +0 -0
  21. package/{build → dist}/adaptors/axios.min.js.map +0 -0
  22. package/{build → dist}/adaptors/axios.umd.js +0 -0
  23. package/{build → dist}/adaptors/axios.umd.js.map +0 -0
  24. package/{build → dist}/adaptors/axios.umd.min.js +0 -0
  25. package/{build → dist}/adaptors/axios.umd.min.js.map +0 -0
  26. package/{build → dist}/adaptors/ky.cjs +0 -0
  27. package/{build → dist}/adaptors/ky.cjs.map +0 -0
  28. package/dist/adaptors/ky.d.ts +41 -0
  29. package/{build → dist}/adaptors/ky.js +0 -0
  30. package/{build → dist}/adaptors/ky.js.map +0 -0
  31. package/{build → dist}/adaptors/ky.min.cjs +0 -0
  32. package/{build → dist}/adaptors/ky.min.cjs.map +0 -0
  33. package/{build → dist}/adaptors/ky.min.js +0 -0
  34. package/{build → dist}/adaptors/ky.min.js.map +0 -0
  35. package/{build → dist}/adaptors/ky.umd.js +0 -0
  36. package/{build → dist}/adaptors/ky.umd.js.map +0 -0
  37. package/{build → dist}/adaptors/ky.umd.min.js +0 -0
  38. package/{build → dist}/adaptors/ky.umd.min.js.map +0 -0
  39. package/{build → dist}/adaptors/umi-request.cjs +0 -0
  40. package/{build → dist}/adaptors/umi-request.cjs.map +0 -0
  41. package/dist/adaptors/umi-request.d.ts +31 -0
  42. package/{build → dist}/adaptors/umi-request.js +0 -0
  43. package/{build → dist}/adaptors/umi-request.js.map +0 -0
  44. package/{build → dist}/adaptors/umi-request.min.cjs +0 -0
  45. package/{build → dist}/adaptors/umi-request.min.cjs.map +0 -0
  46. package/{build → dist}/adaptors/umi-request.min.js +0 -0
  47. package/{build → dist}/adaptors/umi-request.min.js.map +0 -0
  48. package/{build → dist}/adaptors/umi-request.umd.js +0 -0
  49. package/{build → dist}/adaptors/umi-request.umd.js.map +0 -0
  50. package/{build → dist}/adaptors/umi-request.umd.min.js +0 -0
  51. package/{build → dist}/adaptors/umi-request.umd.min.js.map +0 -0
  52. package/{build → dist}/index.cjs +0 -0
  53. package/{build → dist}/index.cjs.map +0 -0
  54. package/{build → dist}/index.js +0 -0
  55. package/{build → dist}/index.js.map +0 -0
  56. package/{build → dist}/index.min.cjs +0 -0
  57. package/{build → dist}/index.min.cjs.map +0 -0
  58. package/{build → dist}/index.min.js +0 -0
  59. package/{build → dist}/index.min.js.map +0 -0
  60. package/dist/index.umd.js +992 -0
  61. package/dist/index.umd.js.map +1 -0
  62. package/dist/index.umd.min.js +2 -0
  63. package/dist/index.umd.min.js.map +1 -0
  64. package/package.json +26 -10
  65. package/adaptors/axios.ts +0 -44
  66. package/adaptors/ky.ts +0 -76
  67. package/adaptors/umi-request.ts +0 -38
  68. package/core/attach-request.ts +0 -43
  69. package/core/client.ts +0 -252
  70. package/core/error.ts +0 -10
  71. package/core/index.ts +0 -2
  72. package/utils/auto-bind.ts +0 -48
  73. package/utils/camelcase-keys.ts +0 -26
  74. package/utils/index.ts +0 -53
  75. package/utils/path.ts +0 -6
@@ -0,0 +1,980 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const isPlainObject = (obj) => isObject(obj) &&
6
+ Object.prototype.toString.call(obj) === '[object Object]' &&
7
+ Object.getPrototypeOf(obj) === Object.prototype;
8
+ const sortOrderToNumber = (order) => {
9
+ return ({
10
+ asc: 1,
11
+ desc: -1,
12
+ }[order] || 1);
13
+ };
14
+ const isObject = (obj) => obj && typeof obj === 'object';
15
+ const destructureData = (payload) => {
16
+ if (typeof payload !== 'object') {
17
+ return payload;
18
+ }
19
+ if (payload === null) {
20
+ return payload;
21
+ }
22
+ const data = payload.data;
23
+ const dataIsPlainObject = isPlainObject(data);
24
+ if (dataIsPlainObject && Object.keys(payload).length === 1) {
25
+ const d = Object.assign({}, data);
26
+ // attach raw onto new data
27
+ attachRawFromOneToAnthor(payload, d);
28
+ return d;
29
+ }
30
+ return payload;
31
+ };
32
+ const attachRawFromOneToAnthor = (from, to) => {
33
+ if (!from || !isObject(to)) {
34
+ return;
35
+ }
36
+ from.$raw &&
37
+ Object.defineProperty(to, '$raw', {
38
+ value: { ...from.$raw },
39
+ enumerable: false,
40
+ });
41
+ from.$request &&
42
+ Object.defineProperty(to, '$request', {
43
+ value: { ...from.$request },
44
+ enumerable: false,
45
+ });
46
+ };
47
+
48
+ // @ts-nocheck
49
+ // @copy: https://github.com/sindresorhus/auto-bind/blob/main/index.js
50
+ // Gets all non-builtin properties up the prototype chain.
51
+ const getAllProperties = (object) => {
52
+ const properties = new Set();
53
+ do {
54
+ for (const key of Reflect.ownKeys(object)) {
55
+ properties.add([object, key]);
56
+ }
57
+ } while ((object = Reflect.getPrototypeOf(object)) &&
58
+ object !== Object.prototype);
59
+ return properties;
60
+ };
61
+ function autoBind(self, { include, exclude } = {}) {
62
+ const filter = (key) => {
63
+ const match = (pattern) => typeof pattern === 'string' ? key === pattern : pattern.test(key);
64
+ if (include) {
65
+ return include.some(match);
66
+ }
67
+ if (exclude) {
68
+ return !exclude.some(match);
69
+ }
70
+ return true;
71
+ };
72
+ for (const [object, key] of getAllProperties(self.constructor.prototype)) {
73
+ if (key === 'constructor' || !filter(key)) {
74
+ continue;
75
+ }
76
+ const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
77
+ if (descriptor && typeof descriptor.value === 'function') {
78
+ self[key] = self[key].bind(self);
79
+ }
80
+ }
81
+ return self;
82
+ }
83
+
84
+ class AggregateController {
85
+ constructor(client) {
86
+ this.client = client;
87
+ this.base = 'aggregate';
88
+ this.name = 'aggregate';
89
+ autoBind(this);
90
+ }
91
+ get proxy() {
92
+ return this.client.proxy(this.base);
93
+ }
94
+ /**
95
+ * 获取聚合数据
96
+ */
97
+ getAggregateData() {
98
+ return this.proxy.get();
99
+ }
100
+ /**
101
+ * 获取最新发布的内容
102
+ */
103
+ getTop(size = 5) {
104
+ return this.proxy.top.get({ params: { size } });
105
+ }
106
+ getTimeline(options) {
107
+ const { sort, type, year } = options || {};
108
+ return this.proxy.timeline.get({
109
+ params: {
110
+ sort: sort && sortOrderToNumber(sort),
111
+ type,
112
+ year,
113
+ },
114
+ });
115
+ }
116
+ /**
117
+ * 获取聚合数据统计
118
+ */
119
+ getStat() {
120
+ return this.proxy.stat.get();
121
+ }
122
+ }
123
+
124
+ class RequestError extends Error {
125
+ constructor(message, status, path, raw) {
126
+ super(message);
127
+ this.status = status;
128
+ this.path = path;
129
+ this.raw = raw;
130
+ }
131
+ }
132
+
133
+ exports.CategoryType = void 0;
134
+ (function (CategoryType) {
135
+ CategoryType[CategoryType["Category"] = 0] = "Category";
136
+ CategoryType[CategoryType["Tag"] = 1] = "Tag";
137
+ })(exports.CategoryType || (exports.CategoryType = {}));
138
+
139
+ class CategoryController {
140
+ constructor(client) {
141
+ this.client = client;
142
+ this.name = 'category';
143
+ this.base = 'categories';
144
+ autoBind(this);
145
+ }
146
+ get proxy() {
147
+ return this.client.proxy(this.base);
148
+ }
149
+ getAllCategories() {
150
+ return this.proxy.get({
151
+ params: {
152
+ type: exports.CategoryType.Category,
153
+ },
154
+ });
155
+ }
156
+ getAllTags() {
157
+ return this.proxy.get({
158
+ params: {
159
+ type: exports.CategoryType.Tag,
160
+ },
161
+ });
162
+ }
163
+ async getCategoryDetail(ids) {
164
+ if (typeof ids === 'string') {
165
+ const data = await this.proxy.get({
166
+ params: {
167
+ ids,
168
+ },
169
+ });
170
+ const result = Object.values(data.entries)[0];
171
+ attachRawFromOneToAnthor(data, result);
172
+ return result;
173
+ }
174
+ else if (Array.isArray(ids)) {
175
+ const data = await this.proxy.get({
176
+ params: {
177
+ ids: ids.join(','),
178
+ },
179
+ });
180
+ const entries = data?.entries;
181
+ if (!entries) {
182
+ throw new RequestError('data structure error', 500, data.$request.path, data);
183
+ }
184
+ const map = new Map(Object.entries(entries).map(([id, value]) => [id.toLowerCase(), value]));
185
+ attachRawFromOneToAnthor(data, map);
186
+ return map;
187
+ }
188
+ }
189
+ async getCategoryByIdOrSlug(idOrSlug) {
190
+ const res = await this.proxy(idOrSlug).get();
191
+ return destructureData(res);
192
+ }
193
+ async getTagByName(name) {
194
+ const res = await this.proxy(name).get({
195
+ params: {
196
+ tag: 1,
197
+ },
198
+ });
199
+ return res;
200
+ }
201
+ }
202
+
203
+ class CommentController {
204
+ constructor(client) {
205
+ this.client = client;
206
+ this.base = 'comments';
207
+ this.name = 'comment';
208
+ autoBind(this);
209
+ }
210
+ get proxy() {
211
+ return this.client.proxy(this.base);
212
+ }
213
+ /**
214
+ * 根据 comment id 获取评论, 包括子评论
215
+ */
216
+ getById(id) {
217
+ return this.proxy(id).get();
218
+ }
219
+ /**
220
+ * 获取文章的评论列表
221
+ * @param refId 文章 Id
222
+ */
223
+ getByRefId(refId, pagination = {}) {
224
+ const { page, size } = pagination;
225
+ return this.proxy
226
+ .ref(refId)
227
+ .get({
228
+ params: { page: page || 1, size: size || 10 },
229
+ });
230
+ }
231
+ /**
232
+ * 评论
233
+ */
234
+ comment(refId, data) {
235
+ return this.proxy(refId).post({
236
+ data,
237
+ });
238
+ }
239
+ /**
240
+ * 回复评论
241
+ */
242
+ reply(commentId, data) {
243
+ return this.proxy.reply(commentId).post({
244
+ data,
245
+ });
246
+ }
247
+ }
248
+
249
+ class BaseCrudController {
250
+ constructor(client) {
251
+ this.client = client;
252
+ autoBind(this);
253
+ }
254
+ get proxy() {
255
+ return this.client.proxy(this.base);
256
+ }
257
+ getById(id) {
258
+ return this.proxy(id).get();
259
+ }
260
+ getAll() {
261
+ return this.proxy.all.get();
262
+ }
263
+ /**
264
+ * 带分页的查询
265
+ * @param page
266
+ * @param perPage
267
+ */
268
+ getAllPaginated(page, perPage, sortOption) {
269
+ return this.proxy.get({
270
+ params: { page, size: perPage, ...sortOption },
271
+ });
272
+ }
273
+ }
274
+
275
+ class LinkController extends BaseCrudController {
276
+ constructor(client) {
277
+ super(client);
278
+ this.client = client;
279
+ this.name = ['link', 'friend'];
280
+ this.base = 'links';
281
+ autoBind(this);
282
+ }
283
+ // 是否可以申请友链
284
+ async canApplyLink() {
285
+ const { can } = await this.proxy.audit.get();
286
+ return can;
287
+ }
288
+ // 申请友链
289
+ async applyLink(data) {
290
+ return await this.proxy.audit.post({ data });
291
+ }
292
+ }
293
+
294
+ class NoteController {
295
+ constructor(client) {
296
+ this.client = client;
297
+ this.base = 'notes';
298
+ this.name = 'note';
299
+ autoBind(this);
300
+ }
301
+ get proxy() {
302
+ return this.client.proxy(this.base);
303
+ }
304
+ /**
305
+ * 最新日记
306
+ */
307
+ getLatest() {
308
+ return this.proxy.latest.get();
309
+ }
310
+ getNoteById(...rest) {
311
+ const [id, password = undefined, singleResult = false] = rest;
312
+ if (typeof id === 'number') {
313
+ return this.proxy.nid(id.toString()).get({
314
+ params: { password, single: singleResult ? '1' : undefined },
315
+ });
316
+ }
317
+ else {
318
+ return this.proxy(id).get();
319
+ }
320
+ }
321
+ /**
322
+ * 日记列表分页
323
+ */
324
+ getList(page = 1, perPage = 10, options = {}) {
325
+ const { select, sortBy, sortOrder, year } = options;
326
+ return this.proxy.get({
327
+ params: {
328
+ page,
329
+ size: perPage,
330
+ select: select?.join(' '),
331
+ sortBy,
332
+ sortOrder,
333
+ year,
334
+ },
335
+ });
336
+ }
337
+ /**
338
+ * 获取当前日记的上下各 n / 2 篇日记
339
+ */
340
+ getMiddleList(id, size = 5) {
341
+ return this.proxy.list(id).get({
342
+ params: { size },
343
+ });
344
+ }
345
+ /**
346
+ * 喜欢这篇日记
347
+ */
348
+ likeIt(id) {
349
+ return this.proxy.like(id).get();
350
+ }
351
+ /**
352
+ * 获取专栏内的所有日记
353
+ */
354
+ getNoteByTopicId(topicId, page = 1, size = 10, sortOptions = {}) {
355
+ return this.proxy.topics(topicId).get({
356
+ params: { page, size, ...sortOptions },
357
+ });
358
+ }
359
+ }
360
+
361
+ class PageController {
362
+ constructor(client) {
363
+ this.client = client;
364
+ this.base = 'pages';
365
+ this.name = 'page';
366
+ autoBind(this);
367
+ }
368
+ get proxy() {
369
+ return this.client.proxy(this.base);
370
+ }
371
+ /**
372
+ * 页面列表
373
+ */
374
+ getList(page = 1, perPage = 10, options = {}) {
375
+ const { select, sortBy, sortOrder } = options;
376
+ return this.proxy.get({
377
+ params: {
378
+ page,
379
+ size: perPage,
380
+ select: select?.join(' '),
381
+ sortBy,
382
+ sortOrder,
383
+ },
384
+ });
385
+ }
386
+ /**
387
+ * 页面详情
388
+ */
389
+ getById(id) {
390
+ return this.proxy(id).get();
391
+ }
392
+ /**
393
+ * 根据路径获取页面
394
+ * @param slug 路径
395
+ * @returns
396
+ */
397
+ getBySlug(slug) {
398
+ return this.proxy.slug(slug).get({});
399
+ }
400
+ }
401
+
402
+ class PostController {
403
+ constructor(client) {
404
+ this.client = client;
405
+ this.base = 'posts';
406
+ this.name = 'post';
407
+ autoBind(this);
408
+ }
409
+ get proxy() {
410
+ return this.client.proxy(this.base);
411
+ }
412
+ /**
413
+ * 获取文章列表分页
414
+ * @param page
415
+ * @param perPage
416
+ * @returns
417
+ */
418
+ getList(page = 1, perPage = 10, options = {}) {
419
+ const { select, sortBy, sortOrder, year } = options;
420
+ return this.proxy.get({
421
+ params: {
422
+ page,
423
+ size: perPage,
424
+ select: select?.join(' '),
425
+ sortBy,
426
+ sortOrder,
427
+ year,
428
+ },
429
+ });
430
+ }
431
+ getPost(idOrCategoryName, slug) {
432
+ if (arguments.length == 1) {
433
+ return this.proxy(idOrCategoryName).get();
434
+ }
435
+ else {
436
+ return this.proxy(idOrCategoryName)(slug).get();
437
+ }
438
+ }
439
+ /**
440
+ * 获取最新的文章
441
+ */
442
+ getLatest() {
443
+ return this.proxy.latest.get();
444
+ }
445
+ /**
446
+ * 点赞
447
+ */
448
+ thumbsUp(id) {
449
+ return this.proxy('_thumbs-up').get({ params: { id } });
450
+ }
451
+ }
452
+
453
+ class ProjectController extends BaseCrudController {
454
+ constructor(client) {
455
+ super(client);
456
+ this.client = client;
457
+ this.base = 'projects';
458
+ this.name = 'project';
459
+ autoBind(this);
460
+ }
461
+ }
462
+
463
+ class RecentlyController {
464
+ constructor(client) {
465
+ this.client = client;
466
+ this.base = 'recently';
467
+ this.name = ['recently', 'shorthand'];
468
+ autoBind(this);
469
+ }
470
+ get proxy() {
471
+ return this.client.proxy(this.base);
472
+ }
473
+ /**
474
+ * 获取最新一条
475
+ */
476
+ getLatestOne() {
477
+ return this.proxy.latest.get();
478
+ }
479
+ getAll() {
480
+ return this.proxy.all.get();
481
+ }
482
+ getList(before, after, size) {
483
+ return this.proxy.get({
484
+ params: {
485
+ before,
486
+ after,
487
+ size,
488
+ },
489
+ });
490
+ }
491
+ }
492
+
493
+ class SayController extends BaseCrudController {
494
+ constructor(client) {
495
+ super(client);
496
+ this.client = client;
497
+ this.base = 'says';
498
+ this.name = 'say';
499
+ autoBind(this);
500
+ }
501
+ get proxy() {
502
+ return this.client.proxy(this.base);
503
+ }
504
+ /**
505
+ * 获取随机一条
506
+ */
507
+ getRandom() {
508
+ return this.proxy.random.get();
509
+ }
510
+ }
511
+
512
+ class SearchController {
513
+ constructor(client) {
514
+ this.client = client;
515
+ this.base = 'search';
516
+ this.name = 'search';
517
+ autoBind(this);
518
+ }
519
+ get proxy() {
520
+ return this.client.proxy(this.base);
521
+ }
522
+ search(type, keyword, options = {}) {
523
+ return this.proxy(type).get({
524
+ params: { keyword, ...options },
525
+ });
526
+ }
527
+ /**
528
+ * 从 algolya 搜索
529
+ * https://www.algolia.com/doc/api-reference/api-methods/search/
530
+ * @param keyword
531
+ * @param options
532
+ * @returns
533
+ */
534
+ searchByAlgolia(keyword, options) {
535
+ return this.proxy('algolia').get({ params: { keyword, ...options } });
536
+ }
537
+ }
538
+
539
+ class ServerlessController {
540
+ constructor(client) {
541
+ this.client = client;
542
+ this.base = 'serverless';
543
+ this.name = 'serverless';
544
+ autoBind(this);
545
+ }
546
+ get proxy() {
547
+ return this.client.proxy(this.base);
548
+ }
549
+ getByReferenceAndName(reference, name) {
550
+ return this.proxy(reference)(name).get();
551
+ }
552
+ }
553
+
554
+ class SnippetController {
555
+ constructor(client) {
556
+ this.client = client;
557
+ this.base = 'snippets';
558
+ this.name = 'snippet';
559
+ autoBind(this);
560
+ }
561
+ get proxy() {
562
+ return this.client.proxy(this.base);
563
+ }
564
+ // getById(id: string) {
565
+ // return this.proxy(id).get<Omit<SnippetModel, 'data'>>()
566
+ // }
567
+ getByReferenceAndName(reference, name) {
568
+ return this.proxy(reference)(name).get();
569
+ }
570
+ }
571
+
572
+ class TopicController extends BaseCrudController {
573
+ constructor(client) {
574
+ super(client);
575
+ this.client = client;
576
+ this.base = 'topics';
577
+ this.name = 'topic';
578
+ autoBind(this);
579
+ }
580
+ get proxy() {
581
+ return this.client.proxy(this.base);
582
+ }
583
+ getTopicBySlug(slug) {
584
+ return this.proxy.slug(slug).get();
585
+ }
586
+ }
587
+
588
+ class UserController {
589
+ constructor(client) {
590
+ this.client = client;
591
+ this.base = 'master';
592
+ this.name = ['user', 'master'];
593
+ autoBind(this);
594
+ }
595
+ get proxy() {
596
+ return this.client.proxy(this.base);
597
+ }
598
+ getMasterInfo() {
599
+ return this.proxy.get();
600
+ }
601
+ login(username, password) {
602
+ return this.proxy.login.post({
603
+ data: {
604
+ username,
605
+ password,
606
+ },
607
+ });
608
+ }
609
+ loginWithToken(token) {
610
+ return this.proxy.login.put({
611
+ params: token
612
+ ? {
613
+ token: `bearer ${token.replace(/^Bearer\s/i, '')}`,
614
+ }
615
+ : undefined,
616
+ });
617
+ }
618
+ checkTokenValid(token) {
619
+ return this.proxy.check_logged.get({
620
+ params: {
621
+ token: `bearer ${token.replace(/^Bearer\s/i, '')}`,
622
+ },
623
+ });
624
+ }
625
+ }
626
+
627
+ const allControllers = [
628
+ AggregateController,
629
+ CategoryController,
630
+ CommentController,
631
+ LinkController,
632
+ NoteController,
633
+ PageController,
634
+ PostController,
635
+ ProjectController,
636
+ RecentlyController,
637
+ TopicController,
638
+ SayController,
639
+ SearchController,
640
+ SnippetController,
641
+ ServerlessController,
642
+ UserController,
643
+ ];
644
+ const allContollerNames = [
645
+ 'aggregate',
646
+ 'category',
647
+ 'comment',
648
+ 'link',
649
+ 'note',
650
+ 'page',
651
+ 'post',
652
+ 'project',
653
+ 'topic',
654
+ 'recently',
655
+ 'say',
656
+ 'search',
657
+ 'snippet',
658
+ 'serverless',
659
+ 'user',
660
+ // alias,
661
+ 'friend',
662
+ 'master',
663
+ 'shorthand',
664
+ ];
665
+
666
+ const camelcaseKeys = (obj) => {
667
+ if (Array.isArray(obj)) {
668
+ return obj.map((x) => camelcaseKeys(x));
669
+ }
670
+ if (isPlainObject(obj)) {
671
+ return Object.keys(obj).reduce((result, key) => {
672
+ result[camelcase(key)] = camelcaseKeys(obj[key]);
673
+ return result;
674
+ }, {});
675
+ }
676
+ return obj;
677
+ };
678
+ function camelcase(str) {
679
+ return str.replace(/([-_][a-z])/gi, ($1) => {
680
+ return $1.toUpperCase().replace('-', '').replace('_', '');
681
+ });
682
+ }
683
+
684
+ const resolveFullPath = (endpoint, path) => {
685
+ if (!path.startsWith('/')) {
686
+ path = `/${path}`;
687
+ }
688
+ return `${endpoint}${path}`;
689
+ };
690
+
691
+ function attachRequestMethod(target) {
692
+ Object.defineProperty(target, '$$get', {
693
+ value(url, options) {
694
+ // HINT: method get only accept search params;
695
+ const { params = {}, ...rest } = options;
696
+ const qs = handleSearchParams(params);
697
+ return target.instance.get(`${url}${qs ? `${`?${qs}`}` : ''}`, rest);
698
+ },
699
+ });
700
+ ['put', 'post', 'patch', 'delete'].forEach((method) => {
701
+ Object.defineProperty(target, `$$${method}`, {
702
+ value(path, options) {
703
+ return target.instance[method](path, options);
704
+ },
705
+ });
706
+ });
707
+ }
708
+ // FIXME: only support string value
709
+ function handleSearchParams(obj) {
710
+ if (!obj && typeof obj !== 'object') {
711
+ throw new TypeError('params must be object.');
712
+ }
713
+ if (obj instanceof URLSearchParams) {
714
+ return obj.toString();
715
+ }
716
+ const search = new URLSearchParams();
717
+ Object.entries(obj).forEach(([k, v]) => {
718
+ if (typeof v === 'undefined' ||
719
+ Object.prototype.toString.call(v) === '[object Null]') {
720
+ return;
721
+ }
722
+ search.set(k, v);
723
+ });
724
+ return search.toString();
725
+ }
726
+
727
+ const methodPrefix = '_$';
728
+ class HTTPClient {
729
+ constructor(_endpoint, _adaptor, options = {}) {
730
+ this._endpoint = _endpoint;
731
+ this._adaptor = _adaptor;
732
+ this.options = options;
733
+ this._endpoint = _endpoint
734
+ .replace(/\/*$/, '')
735
+ .replace('localhost', '127.0.0.1');
736
+ this._proxy = this.buildRoute(this)();
737
+ options.transformResponse =
738
+ options.transformResponse || ((data) => camelcaseKeys(data));
739
+ this.initGetClient();
740
+ attachRequestMethod(this);
741
+ }
742
+ initGetClient() {
743
+ for (const name of allContollerNames) {
744
+ Object.defineProperty(this, name, {
745
+ get() {
746
+ const client = Reflect.get(this, `${methodPrefix}${name}`);
747
+ if (!client) {
748
+ throw new ReferenceError(`${name.charAt(0).toUpperCase() + name.slice(1)} Client not inject yet, please inject with client.injectClients(...)`);
749
+ }
750
+ return client;
751
+ },
752
+ configurable: false,
753
+ enumerable: false,
754
+ });
755
+ }
756
+ }
757
+ injectControllers(Controller, ...rest) {
758
+ Controller = Array.isArray(Controller) ? Controller : [Controller, ...rest];
759
+ for (const Client of Controller) {
760
+ const cl = new Client(this);
761
+ if (Array.isArray(cl.name)) {
762
+ for (const name of cl.name) {
763
+ attach.call(this, name, cl);
764
+ }
765
+ }
766
+ else {
767
+ attach.call(this, cl.name, cl);
768
+ }
769
+ }
770
+ function attach(name, cl) {
771
+ Object.defineProperty(this, `${methodPrefix}${name.toLowerCase()}`, {
772
+ get() {
773
+ return cl;
774
+ },
775
+ enumerable: false,
776
+ configurable: false,
777
+ });
778
+ }
779
+ }
780
+ get endpoint() {
781
+ return this._endpoint;
782
+ }
783
+ get instance() {
784
+ return this._adaptor;
785
+ }
786
+ request(options) {
787
+ return this[`$$${String(options.method || 'get').toLowerCase()}`](options.url, options);
788
+ }
789
+ get proxy() {
790
+ return this._proxy;
791
+ }
792
+ buildRoute(manager) {
793
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
794
+ const noop = () => { };
795
+ const methods = ['get', 'post', 'delete', 'patch', 'put'];
796
+ const reflectors = [
797
+ 'toString',
798
+ 'valueOf',
799
+ 'inspect',
800
+ 'constructor',
801
+ Symbol.toPrimitive,
802
+ ];
803
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
804
+ const that = this;
805
+ return () => {
806
+ const route = [''];
807
+ const handler = {
808
+ get(target, name) {
809
+ if (reflectors.includes(name))
810
+ return (withBase) => {
811
+ if (withBase) {
812
+ const path = resolveFullPath(that.endpoint, route.join('/'));
813
+ route.length = 0;
814
+ return path;
815
+ }
816
+ else {
817
+ const path = route.join('/');
818
+ route.length = 0;
819
+ return path.startsWith('/') ? path : `/${path}`;
820
+ }
821
+ };
822
+ if (methods.includes(name)) {
823
+ return async (options) => {
824
+ const url = resolveFullPath(that.endpoint, route.join('/'));
825
+ route.length = 0;
826
+ let res;
827
+ try {
828
+ res = await manager.request({
829
+ method: name,
830
+ ...options,
831
+ url,
832
+ });
833
+ }
834
+ catch (e) {
835
+ let message = e.message;
836
+ let code = e.code ||
837
+ e.status ||
838
+ e.statusCode ||
839
+ e.response?.status ||
840
+ e.response?.statusCode ||
841
+ e.response?.code ||
842
+ 500;
843
+ if (that.options.getCodeMessageFromException) {
844
+ const errorInfo = that.options.getCodeMessageFromException(e);
845
+ message = errorInfo.message || message;
846
+ code = errorInfo.code || code;
847
+ }
848
+ throw that.options.customThrowResponseError
849
+ ? that.options.customThrowResponseError(e)
850
+ : new RequestError(message, code, url, e);
851
+ }
852
+ const data = res.data;
853
+ if (!data) {
854
+ return null;
855
+ }
856
+ const transform = (Array.isArray(data) || isPlainObject(data)) &&
857
+ that.options.transformResponse
858
+ ? that.options.transformResponse(data)
859
+ : data;
860
+ if (transform && typeof transform === 'object') {
861
+ Object.defineProperty(transform, '$raw', {
862
+ get() {
863
+ return res;
864
+ },
865
+ enumerable: false,
866
+ configurable: false,
867
+ });
868
+ // attach request config onto response
869
+ Object.defineProperty(transform, '$request', {
870
+ get() {
871
+ return {
872
+ url,
873
+ method: name,
874
+ options,
875
+ };
876
+ },
877
+ enumerable: false,
878
+ });
879
+ }
880
+ return transform;
881
+ };
882
+ }
883
+ route.push(name);
884
+ return new Proxy(noop, handler);
885
+ },
886
+ // @ts-ignore
887
+ apply(target, _, args) {
888
+ route.push(...args.filter((x) => x !== null));
889
+ return new Proxy(noop, handler);
890
+ },
891
+ };
892
+ return new Proxy(noop, handler);
893
+ };
894
+ }
895
+ }
896
+ function createClient(adapter) {
897
+ return (endpoint, options) => {
898
+ const client = new HTTPClient(endpoint, adapter, options);
899
+ const { controllers } = options || {};
900
+ if (controllers) {
901
+ client.injectControllers(controllers);
902
+ }
903
+ return client;
904
+ };
905
+ }
906
+
907
+ exports.TimelineType = void 0;
908
+ (function (TimelineType) {
909
+ TimelineType[TimelineType["Post"] = 0] = "Post";
910
+ TimelineType[TimelineType["Note"] = 1] = "Note";
911
+ })(exports.TimelineType || (exports.TimelineType = {}));
912
+
913
+ exports.RefType = void 0;
914
+ (function (RefType) {
915
+ RefType["Page"] = "Page";
916
+ RefType["Post"] = "Post";
917
+ RefType["Note"] = "Note";
918
+ })(exports.RefType || (exports.RefType = {}));
919
+ exports.CommentState = void 0;
920
+ (function (CommentState) {
921
+ CommentState[CommentState["Unread"] = 0] = "Unread";
922
+ CommentState[CommentState["Read"] = 1] = "Read";
923
+ CommentState[CommentState["Junk"] = 2] = "Junk";
924
+ })(exports.CommentState || (exports.CommentState = {}));
925
+
926
+ exports.LinkType = void 0;
927
+ (function (LinkType) {
928
+ LinkType[LinkType["Friend"] = 0] = "Friend";
929
+ LinkType[LinkType["Collection"] = 1] = "Collection";
930
+ })(exports.LinkType || (exports.LinkType = {}));
931
+ exports.LinkState = void 0;
932
+ (function (LinkState) {
933
+ LinkState[LinkState["Pass"] = 0] = "Pass";
934
+ LinkState[LinkState["Audit"] = 1] = "Audit";
935
+ LinkState[LinkState["Outdate"] = 2] = "Outdate";
936
+ LinkState[LinkState["Banned"] = 3] = "Banned";
937
+ })(exports.LinkState || (exports.LinkState = {}));
938
+
939
+ exports.EnumPageType = void 0;
940
+ (function (EnumPageType) {
941
+ EnumPageType["md"] = "md";
942
+ EnumPageType["html"] = "html";
943
+ EnumPageType["frame"] = "frame";
944
+ })(exports.EnumPageType || (exports.EnumPageType = {}));
945
+
946
+ exports.RecentlyRefTypes = void 0;
947
+ (function (RecentlyRefTypes) {
948
+ RecentlyRefTypes["Post"] = "Post";
949
+ RecentlyRefTypes["Note"] = "Note";
950
+ RecentlyRefTypes["Page"] = "Page";
951
+ })(exports.RecentlyRefTypes || (exports.RecentlyRefTypes = {}));
952
+
953
+ exports.SnippetType = void 0;
954
+ (function (SnippetType) {
955
+ SnippetType["JSON"] = "json";
956
+ SnippetType["Function"] = "function";
957
+ SnippetType["Text"] = "text";
958
+ SnippetType["YAML"] = "yaml";
959
+ })(exports.SnippetType || (exports.SnippetType = {}));
960
+
961
+ exports.AggregateController = AggregateController;
962
+ exports.CategoryController = CategoryController;
963
+ exports.CommentController = CommentController;
964
+ exports.LinkController = LinkController;
965
+ exports.NoteController = NoteController;
966
+ exports.PageController = PageController;
967
+ exports.PostController = PostController;
968
+ exports.ProjectController = ProjectController;
969
+ exports.RecentlyController = RecentlyController;
970
+ exports.RequestError = RequestError;
971
+ exports.SayController = SayController;
972
+ exports.SearchController = SearchController;
973
+ exports.ServerlessController = ServerlessController;
974
+ exports.SnippetController = SnippetController;
975
+ exports.TopicController = TopicController;
976
+ exports.UserController = UserController;
977
+ exports.allContollerNames = allContollerNames;
978
+ exports.allControllers = allControllers;
979
+ exports.createClient = createClient;
980
+ //# sourceMappingURL=index.cjs.js.map