@hlw-uni-mp/request 1.0.5 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,9 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target2, all) => {
8
+ var __export = (target, all) => {
9
9
  for (var name in all)
10
- __defProp(target2, name, { get: all[name], enumerable: true });
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
@@ -17,12 +17,12 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
21
  // If the importer is in node compatibility mode or this is not an ESM
22
22
  // file that has been converted to a CommonJS file using a Babel-
23
23
  // compatible transform (i.e. "__esModule" has not been set), then set
24
24
  // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
@@ -31,8 +31,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  HttpError: () => HttpError,
34
- InterceptorManager: () => InterceptorManager,
35
- UniHttpClient: () => UniHttpClient,
36
34
  calculateSign: () => calculateSign,
37
35
  client: () => client,
38
36
  default: () => index_default,
@@ -51,8 +49,7 @@ __export(index_exports, {
51
49
  setupHttp: () => setupHttp,
52
50
  sha256: () => sha256,
53
51
  sortString: () => sortString,
54
- uploadFile: () => uploadFile,
55
- uploadOss: () => uploadOss
52
+ uploadFile: () => uploadFile
56
53
  });
57
54
  module.exports = __toCommonJS(index_exports);
58
55
 
@@ -149,15 +146,7 @@ function bytesToBase64(bytes) {
149
146
  return res;
150
147
  }
151
148
  function stringToUtf8(str) {
152
- if (typeof TextEncoder !== "undefined") {
153
- return new TextEncoder().encode(str);
154
- }
155
- const code = unescape(encodeURIComponent(str));
156
- const bytes = new Uint8Array(code.length);
157
- for (let i = 0; i < code.length; i++) {
158
- bytes[i] = code.charCodeAt(i);
159
- }
160
- return bytes;
149
+ return new TextEncoder().encode(str);
161
150
  }
162
151
  function modPow(base, exp, mod) {
163
152
  let res = 1n;
@@ -320,40 +309,6 @@ function calculateSign(options) {
320
309
  return sha256(raw);
321
310
  }
322
311
 
323
- // src/oss.ts
324
- async function uploadOss(oss, source) {
325
- const filePath = typeof source === "string" ? source : source.path || source.tempFilePath || "";
326
- const name = oss.filename || filePath.split("/").pop() || "file";
327
- const formData = {
328
- key: oss.key || "",
329
- success_action_status: oss.successActionStatus || "200"
330
- };
331
- if (oss.policy) formData.policy = oss.policy;
332
- if (oss.OSSAccessKeyId) formData.OSSAccessKeyId = oss.OSSAccessKeyId;
333
- if (oss.signature) formData.signature = oss.signature;
334
- if (oss["x-oss-security-token"]) formData["x-oss-security-token"] = String(oss["x-oss-security-token"]);
335
- const target2 = oss.host || "";
336
- return new Promise((resolve, reject) => {
337
- uni.uploadFile({
338
- url: target2,
339
- filePath,
340
- name: "file",
341
- formData,
342
- header: {
343
- "Content-Disposition": `inline;filename=${encodeURIComponent(name || "file")}`
344
- },
345
- success: (res) => {
346
- if (res.statusCode === 200 || res.statusCode === 204) {
347
- resolve(oss.url || "");
348
- } else {
349
- reject(new Error(`\u4E0A\u4F20\u963F\u91CC\u4E91\u5931\u8D25 (${res.statusCode}): ${res.data || ""}`));
350
- }
351
- },
352
- fail: (error) => reject(new Error(error.errMsg || "\u4E0A\u4F20\u963F\u91CC\u4E91\u5931\u8D25"))
353
- });
354
- });
355
- }
356
-
357
312
  // src/upload.ts
358
313
  function getFileExt(filePath) {
359
314
  const ext = filePath.split("?")[0].split(".").pop()?.toLowerCase() || "";
@@ -445,250 +400,150 @@ var HttpError = class extends Error {
445
400
  this.config = options?.config;
446
401
  }
447
402
  };
448
- var InterceptorManager = class {
449
- constructor() {
450
- this.handlers = [];
451
- }
452
- use(fulfilled, rejected) {
453
- this.handlers.push({ fulfilled, rejected });
454
- return this.handlers.length - 1;
455
- }
456
- eject(id) {
457
- if (this.handlers[id]) {
458
- this.handlers[id] = null;
459
- }
460
- }
461
- forEach(fn) {
462
- for (const h of this.handlers) {
463
- if (h !== null) fn(h);
464
- }
465
- }
466
- };
467
- var UniHttpClient = class {
468
- constructor(options = {}) {
469
- this.defaults = {
470
- baseURL: "",
471
- timeout: 15e3,
472
- headers: {
473
- "Content-Type": "application/json",
474
- Accept: "application/json"
475
- }
476
- };
477
- this.interceptors = {
478
- request: new InterceptorManager(),
479
- response: new InterceptorManager()
480
- };
481
- if (options.baseURL) this.defaults.baseURL = options.baseURL.replace(/\/+$/, "");
482
- if (options.timeout) this.defaults.timeout = options.timeout;
483
- if (options.headers) this.defaults.headers = { ...this.defaults.headers, ...options.headers };
484
- }
485
- async request(config) {
486
- const cfg = {
487
- method: "GET",
488
- ...config,
489
- baseURL: config.baseURL ?? this.defaults.baseURL,
490
- headers: { ...this.defaults.headers, ...config.headers },
491
- timeout: config.timeout ?? this.defaults.timeout
492
- };
493
- const requestChain = [];
494
- this.interceptors.request.forEach((h) => {
495
- requestChain.push(h.fulfilled, h.rejected);
496
- });
497
- let promise = Promise.resolve(cfg);
498
- while (requestChain.length) {
499
- promise = promise.then(requestChain.shift(), requestChain.shift());
500
- }
501
- let responsePromise = promise.then(async (finalConfig) => {
502
- const fullUrl = this.resolveUrl(finalConfig.url, finalConfig.baseURL);
503
- return this.send(fullUrl, finalConfig);
504
- });
505
- const responseChain = [];
506
- this.interceptors.response.forEach((h) => {
507
- responseChain.push(h.fulfilled, h.rejected);
508
- });
509
- while (responseChain.length) {
510
- responsePromise = responsePromise.then(responseChain.shift(), responseChain.shift());
511
- }
512
- return responsePromise;
513
- }
514
- get(url, config) {
515
- return this.request({ ...config, url, method: "GET" });
516
- }
517
- post(url, data, config) {
518
- return this.request({ ...config, url, method: "POST", data });
519
- }
520
- put(url, data, config) {
521
- return this.request({ ...config, url, method: "PUT", data });
522
- }
523
- delete(url, config) {
524
- return this.request({ ...config, url, method: "DELETE" });
525
- }
526
- resolveUrl(url, baseURL) {
527
- if (/^(https?:)?\/\//.test(url) || url.startsWith("file://")) return url;
528
- const base = (baseURL || this.defaults.baseURL || "").replace(/\/+$/, "");
529
- const path = url.startsWith("/") ? url : `/${url}`;
530
- return base ? `${base}${path}` : path;
531
- }
532
- send(url, cfg) {
533
- return new Promise((resolve, reject) => {
534
- const isGet = (cfg.method || "GET").toUpperCase() === "GET";
535
- const requestData = isGet ? cfg.params ?? cfg.data : cfg.data ?? cfg.params;
536
- const method = cfg.method?.toUpperCase() || "GET";
537
- uni.request({
538
- url,
539
- method,
540
- data: requestData,
541
- header: cfg.headers,
542
- timeout: cfg.timeout,
543
- success: (res) => {
544
- const response = {
545
- data: res.data,
546
- status: res.statusCode,
547
- statusText: String(res.statusCode),
548
- headers: res.header || {},
549
- config: cfg
550
- };
551
- if (res.statusCode >= 200 && res.statusCode < 300) {
552
- resolve(response);
553
- } else {
554
- const body = res.data;
555
- const msg = typeof body?.msg === "string" ? body.msg : `\u8BF7\u6C42\u5931\u8D25: ${res.statusCode}`;
556
- reject(new HttpError(msg, { response, status: res.statusCode, config: cfg }));
557
- }
558
- },
559
- fail: (errorResult) => {
560
- reject(new HttpError(errorResult.errMsg || "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25", { config: cfg }));
561
- }
562
- });
563
- });
564
- }
565
- };
566
- var target = null;
567
403
  var currentOptions = {};
568
404
  var lastToastTime = 0;
569
- function handleUnauthorized(message, callback) {
405
+ function resolveUrl(url, baseURL) {
406
+ if (/^(https?:)?\/\//.test(url) || url.startsWith("file://")) {
407
+ return url;
408
+ }
409
+ const base = (baseURL || currentOptions.baseURL || "").replace(/\/+$/, "");
410
+ const path = url.startsWith("/") ? url : `/${url}`;
411
+ return base ? `${base}${path}` : path;
412
+ }
413
+ function handleUnauthorized(message) {
570
414
  const now = Date.now();
571
415
  if (now - lastToastTime > 3e3) {
572
416
  lastToastTime = now;
573
417
  uni.showToast({ title: message, icon: "none" });
574
418
  }
575
- if (callback) {
576
- callback(message);
577
- }
419
+ currentOptions.onUnauthorized?.(message);
578
420
  }
579
- function getClient() {
580
- if (target) {
581
- if (currentOptions.baseURL && !target.defaults.baseURL) {
582
- target.defaults.baseURL = currentOptions.baseURL;
583
- }
584
- return target;
585
- }
586
- const base = currentOptions.baseURL || "";
587
- const inst = new UniHttpClient({
588
- baseURL: base,
589
- timeout: currentOptions.timeout || 15e3
421
+ function buildSecurityHeaders(config) {
422
+ const devInfo = currentOptions.getDevice?.() || getDevice();
423
+ const token = currentOptions.getToken?.() || "";
424
+ const timestamp = Date.now();
425
+ const nonce = Math.random().toString(36).substring(2, 12);
426
+ const pubKey = currentOptions.publicKey || "";
427
+ const secret = currentOptions.secret || "";
428
+ const contextPayload = JSON.stringify({ ...devInfo, token });
429
+ const cipher = pubKey ? encryptRsa(contextPayload, pubKey) : encodeURIComponent(contextPayload);
430
+ const signData = config.data || config.params || {};
431
+ const sign = calculateSign({
432
+ timestamp,
433
+ nonce,
434
+ context: cipher,
435
+ secret,
436
+ data: signData
590
437
  });
591
- inst.interceptors.request.use(
592
- async (config) => {
593
- const devInfo = currentOptions.getDevice?.() || getDevice();
594
- const token = currentOptions.getToken?.() || "";
595
- const time = Date.now();
596
- const nonce = Math.random().toString(36).substring(2, 12);
597
- const payload = {
598
- ...devInfo,
599
- token
600
- };
601
- const jsonStr = JSON.stringify(payload);
602
- const pubKey = currentOptions.publicKey || "";
603
- const secret = currentOptions.secret || "";
604
- let cipher = "";
605
- if (pubKey) {
606
- cipher = encryptRsa(jsonStr, pubKey);
607
- } else {
608
- cipher = encodeURIComponent(jsonStr);
609
- }
610
- const signData = config.data || config.params || {};
611
- const sign = calculateSign({
612
- timestamp: time,
613
- nonce,
614
- context: cipher,
615
- secret,
616
- data: signData
617
- });
618
- config.headers = config.headers || {};
619
- config.headers["X-Client-Timestamp"] = String(time);
620
- config.headers["X-Client-Nonce"] = nonce;
621
- config.headers["X-Client-Sign"] = sign;
622
- config.headers["X-Client-Context"] = cipher;
623
- if ("appid" in devInfo && devInfo.appid) {
624
- config.headers["x-appid"] = String(devInfo.appid);
625
- }
626
- return config;
627
- },
628
- (error) => Promise.reject(error)
629
- );
630
- inst.interceptors.response.use(
631
- async (response) => {
632
- const res = response.data;
633
- if (res && (res.code === 401 || res.code === 403)) {
634
- const message = res.msg || "\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55";
635
- handleUnauthorized(message, currentOptions.onUnauthorized);
636
- }
637
- return response;
638
- },
639
- (error) => {
640
- const httpErr = error instanceof HttpError ? error : void 0;
641
- const status = httpErr?.status ?? httpErr?.response?.status;
642
- const body = httpErr?.response?.data;
643
- const message = body?.msg || (error instanceof Error ? error.message : "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38");
644
- if (status === 401 || status === 403) {
645
- handleUnauthorized(message, currentOptions.onUnauthorized);
438
+ const headers = {
439
+ "Content-Type": "application/json",
440
+ Accept: "application/json",
441
+ ...config.headers,
442
+ "X-Client-Timestamp": String(timestamp),
443
+ "X-Client-Nonce": nonce,
444
+ "X-Client-Sign": sign,
445
+ "X-Client-Context": cipher
446
+ };
447
+ if ("appid" in devInfo && devInfo.appid) {
448
+ headers["x-appid"] = String(devInfo.appid);
449
+ }
450
+ return headers;
451
+ }
452
+ function sendRequest(url, config) {
453
+ return new Promise((resolve, reject) => {
454
+ const method = config.method?.toUpperCase() || "GET";
455
+ const isGet = method === "GET";
456
+ const requestData = isGet ? config.params ?? config.data : config.data ?? config.params;
457
+ uni.request({
458
+ url,
459
+ method,
460
+ data: requestData,
461
+ header: config.headers,
462
+ timeout: config.timeout ?? currentOptions.timeout ?? 15e3,
463
+ success: (res) => {
464
+ const response = {
465
+ data: res.data,
466
+ status: res.statusCode,
467
+ statusText: String(res.statusCode),
468
+ headers: res.header || {},
469
+ config
470
+ };
471
+ if (res.statusCode >= 200 && res.statusCode < 300) {
472
+ resolve(response);
473
+ } else {
474
+ const body = res.data;
475
+ const msg = typeof body?.msg === "string" ? body.msg : `\u8BF7\u6C42\u5931\u8D25: ${res.statusCode}`;
476
+ reject(new HttpError(msg, { response, status: res.statusCode, config }));
477
+ }
478
+ },
479
+ fail: (err) => {
480
+ reject(new HttpError(err.errMsg || "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25", { config }));
646
481
  }
647
- return Promise.reject(error);
648
- }
649
- );
650
- target = inst;
651
- return inst;
482
+ });
483
+ });
652
484
  }
653
- function setupHttp(options = {}) {
654
- currentOptions = { ...currentOptions, ...options };
655
- if (target && options.baseURL) {
656
- target.defaults.baseURL = options.baseURL;
485
+ async function request(config) {
486
+ const finalConfig = {
487
+ method: "GET",
488
+ ...config,
489
+ headers: buildSecurityHeaders(config)
490
+ };
491
+ const fullUrl = resolveUrl(finalConfig.url, finalConfig.baseURL);
492
+ try {
493
+ const response = await sendRequest(fullUrl, finalConfig);
494
+ const resData = response.data;
495
+ if (resData && (resData.code === 401 || resData.code === 403)) {
496
+ handleUnauthorized(resData.msg || "\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55");
497
+ }
498
+ return resData;
499
+ } catch (error) {
500
+ const httpErr = error instanceof HttpError ? error : void 0;
501
+ const status = httpErr?.status ?? httpErr?.response?.status;
502
+ const body = httpErr?.response?.data;
503
+ const message = body?.msg || (error instanceof Error ? error.message : "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38");
504
+ if (status === 401 || status === 403) {
505
+ handleUnauthorized(message);
506
+ }
507
+ return Promise.reject(error);
657
508
  }
658
- return getClient();
659
509
  }
660
- function request(config) {
661
- return getClient().request(config).then((res) => res.data);
510
+ function get(url, params, config) {
511
+ return request({ ...config, url, method: "GET", params });
662
512
  }
663
- function get(url, params) {
664
- return request({ url, method: "GET", params });
513
+ function post(url, data, config) {
514
+ return request({ ...config, url, method: "POST", data });
665
515
  }
666
- function post(url, data) {
667
- return request({ url, method: "POST", data });
516
+ function put(url, data, config) {
517
+ return request({ ...config, url, method: "PUT", data });
668
518
  }
669
- function put(url, data) {
670
- return request({ url, method: "PUT", data });
519
+ function del(url, params, config) {
520
+ return request({ ...config, url, method: "DELETE", params });
521
+ }
522
+ var http = {
523
+ request,
524
+ get,
525
+ post,
526
+ put,
527
+ delete: del,
528
+ del,
529
+ setup: setupHttp,
530
+ getOptions: getHttpOptions
531
+ };
532
+ var client = http;
533
+ function getClient() {
534
+ return http;
671
535
  }
672
- function del(url, params) {
673
- return request({ url, method: "DELETE", params });
536
+ function setupHttp(options = {}) {
537
+ currentOptions = { ...currentOptions, ...options };
538
+ return http;
674
539
  }
675
540
  function getHttpOptions() {
676
541
  return currentOptions;
677
542
  }
678
- var client = new Proxy({}, {
679
- get(_, prop) {
680
- const inst = getClient();
681
- const val = Reflect.get(inst, prop);
682
- return typeof val === "function" ? val.bind(inst) : val;
683
- }
684
- });
685
- var http = client;
686
543
  var index_default = request;
687
544
  // Annotate the CommonJS export names for ESM import in node:
688
545
  0 && (module.exports = {
689
546
  HttpError,
690
- InterceptorManager,
691
- UniHttpClient,
692
547
  calculateSign,
693
548
  client,
694
549
  del,
@@ -706,6 +561,5 @@ var index_default = request;
706
561
  setupHttp,
707
562
  sha256,
708
563
  sortString,
709
- uploadFile,
710
- uploadOss
564
+ uploadFile
711
565
  });