@faasjs/http 0.0.3-beta.63 → 0.0.3-beta.64

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 (3) hide show
  1. package/dist/index.js +189 -15
  2. package/dist/index.mjs +180 -10
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -29,7 +29,166 @@ __export(src_exports, {
29
29
  useHttp: () => useHttp
30
30
  });
31
31
  module.exports = __toCommonJS(src_exports);
32
- var import_func = require("@faasjs/func");
32
+
33
+ // ../logger/src/index.ts
34
+ var import_util = require("util");
35
+ var LevelColor = ((LevelColor2) => {
36
+ LevelColor2[LevelColor2["debug"] = 90 /* GRAY */] = "debug";
37
+ LevelColor2[LevelColor2["info"] = 32 /* GREEN */] = "info";
38
+ LevelColor2[LevelColor2["warn"] = 33 /* ORANGE */] = "warn";
39
+ LevelColor2[LevelColor2["error"] = 31 /* RED */] = "error";
40
+ return LevelColor2;
41
+ })(LevelColor || {});
42
+ var LevelPriority = {
43
+ debug: 0,
44
+ info: 1,
45
+ warn: 2,
46
+ error: 3
47
+ };
48
+ var Logger = class {
49
+ /**
50
+ * @param label {string} Prefix label
51
+ */
52
+ constructor(label) {
53
+ this.colorfyOutput = true;
54
+ if (label)
55
+ this.label = label;
56
+ this.silent = !process.env.FaasLog && process.env.npm_config_argv && JSON.parse(process.env.npm_config_argv).original.includes("--silent");
57
+ if (["remote", "mono"].includes(process.env.FaasMode))
58
+ this.colorfyOutput = false;
59
+ this.level = process.env.FaasLog ? LevelPriority[process.env.FaasLog.toLowerCase()] : 0;
60
+ this.cachedTimers = {};
61
+ this.size = 1e3;
62
+ this.stdout = console.log;
63
+ this.stderr = console.error;
64
+ }
65
+ /**
66
+ * @param message {string} message
67
+ * @param args {...any=} arguments
68
+ */
69
+ debug(message, ...args) {
70
+ this.log("debug", message, ...args);
71
+ return this;
72
+ }
73
+ /**
74
+ * @param message {string} message
75
+ * @param args {...any=} arguments
76
+ */
77
+ info(message, ...args) {
78
+ this.log("info", message, ...args);
79
+ return this;
80
+ }
81
+ /**
82
+ * @param message {string} message
83
+ * @param args {...any=} arguments
84
+ */
85
+ warn(message, ...args) {
86
+ this.log("warn", message, ...args);
87
+ return this;
88
+ }
89
+ /**
90
+ * @param message {any} message or Error object
91
+ * @param args {...any=} arguments
92
+ */
93
+ error(message, ...args) {
94
+ let stack = false;
95
+ [message].concat(Array.from(args)).forEach((e) => {
96
+ if (e.stack) {
97
+ stack = true;
98
+ this.log("error", e.stack);
99
+ }
100
+ });
101
+ if (!stack)
102
+ this.log("error", message, ...args);
103
+ return this;
104
+ }
105
+ /**
106
+ * @param key {string} timer's label
107
+ * @param level [string=debug] 日志级别,支持 debug、info、warn、error
108
+ */
109
+ time(key, level = "debug") {
110
+ this.cachedTimers[key] = {
111
+ level,
112
+ time: (/* @__PURE__ */ new Date()).getTime()
113
+ };
114
+ return this;
115
+ }
116
+ /**
117
+ * @param key {string} timer's label
118
+ * @param message {string} message
119
+ * @param args {...any=} arguments
120
+ */
121
+ timeEnd(key, message, ...args) {
122
+ if (this.cachedTimers[key]) {
123
+ const timer = this.cachedTimers[key];
124
+ message = message + " +%ims";
125
+ args.push((/* @__PURE__ */ new Date()).getTime() - timer.time);
126
+ this[timer.level](message, ...args);
127
+ delete this.cachedTimers[key];
128
+ } else {
129
+ this.warn("timeEnd not found key %s", key);
130
+ this.debug(message);
131
+ }
132
+ return this;
133
+ }
134
+ /**
135
+ * @param message {string} message
136
+ * @param args {...any=} arguments
137
+ */
138
+ raw(message, ...args) {
139
+ if (this.silent)
140
+ return this;
141
+ this.stdout((0, import_util.format)(message, ...args));
142
+ return this;
143
+ }
144
+ /**
145
+ * @param color {number} color code
146
+ * @param message {string} message
147
+ */
148
+ colorfy(color, message) {
149
+ return `\x1B[0${color}m${message}\x1B[39m`;
150
+ }
151
+ log(level, message, ...args) {
152
+ if (this.silent)
153
+ return this;
154
+ if (LevelPriority[level] < this.level)
155
+ return this;
156
+ let output = level.toUpperCase() + " " + (this.label ? `[${this.label}] ` : "") + (0, import_util.format)(message, ...args);
157
+ if (this.colorfyOutput && level !== "error")
158
+ output = this.colorfy(LevelColor[level], output);
159
+ else if (!this.colorfyOutput)
160
+ output = output.replace(/\n/g, "");
161
+ if (!output)
162
+ return this;
163
+ if (output.length > this.size && !["error", "warn"].includes(level))
164
+ output = output.slice(0, this.size - 100) + "..." + output.slice(output.length - 100);
165
+ if (level === "error")
166
+ this.stderr(output);
167
+ else
168
+ this.stdout(output);
169
+ return this;
170
+ }
171
+ };
172
+
173
+ // ../func/src/index.ts
174
+ var import_crypto = require("crypto");
175
+ var plugins = [];
176
+ function usePlugin(plugin) {
177
+ if (!plugins.find((p) => p.name === plugin.name))
178
+ plugins.push(plugin);
179
+ if (!plugin.mount)
180
+ plugin.mount = async function(data) {
181
+ if (plugin.onMount)
182
+ await plugin.onMount({
183
+ config: (data == null ? void 0 : data.config) || /* @__PURE__ */ Object.create(null),
184
+ event: /* @__PURE__ */ Object.create(null),
185
+ context: /* @__PURE__ */ Object.create(null),
186
+ logger: new Logger(plugin.name)
187
+ }, async () => Promise.resolve());
188
+ return plugin;
189
+ };
190
+ return plugin;
191
+ }
33
192
 
34
193
  // ../deep_merge/src/index.ts
35
194
  var shouldMerge = function(item) {
@@ -58,11 +217,8 @@ function deepMerge(...sources) {
58
217
  return acc;
59
218
  }
60
219
 
61
- // src/index.ts
62
- var import_logger = require("@faasjs/logger");
63
-
64
220
  // src/session.ts
65
- var import_crypto = require("crypto");
221
+ var import_crypto2 = require("crypto");
66
222
  var Session = class {
67
223
  constructor(cookie, config) {
68
224
  this.cookie = cookie;
@@ -70,7 +226,7 @@ var Session = class {
70
226
  console.warn("Session's secret is missing.");
71
227
  this.config = Object.assign({
72
228
  key: "key",
73
- secret: (0, import_crypto.randomBytes)(128).toString("hex"),
229
+ secret: (0, import_crypto2.randomBytes)(128).toString("hex"),
74
230
  salt: "salt",
75
231
  signedSalt: "signedSalt",
76
232
  keylen: 64,
@@ -78,14 +234,14 @@ var Session = class {
78
234
  digest: "sha256",
79
235
  cipherName: "aes-256-cbc"
80
236
  }, config);
81
- this.secret = (0, import_crypto.pbkdf2Sync)(
237
+ this.secret = (0, import_crypto2.pbkdf2Sync)(
82
238
  this.config.secret,
83
239
  this.config.salt,
84
240
  this.config.iterations,
85
241
  this.config.keylen / 2,
86
242
  this.config.digest
87
243
  );
88
- this.signedSecret = (0, import_crypto.pbkdf2Sync)(
244
+ this.signedSecret = (0, import_crypto2.pbkdf2Sync)(
89
245
  this.config.secret,
90
246
  this.config.signedSalt,
91
247
  this.config.iterations,
@@ -106,11 +262,11 @@ var Session = class {
106
262
  encode(text) {
107
263
  if (typeof text !== "string")
108
264
  text = JSON.stringify(text);
109
- const iv = (0, import_crypto.randomBytes)(16);
110
- const cipher = (0, import_crypto.createCipheriv)(this.config.cipherName, this.secret, iv);
265
+ const iv = (0, import_crypto2.randomBytes)(16);
266
+ const cipher = (0, import_crypto2.createCipheriv)(this.config.cipherName, this.secret, iv);
111
267
  const encrypted = Buffer.concat([cipher.update(text), cipher.final()]).toString("base64");
112
268
  const main = Buffer.from([encrypted, iv.toString("base64")].join("--")).toString("base64");
113
- const hmac = (0, import_crypto.createHmac)(this.config.digest, this.signedSecret);
269
+ const hmac = (0, import_crypto2.createHmac)(this.config.digest, this.signedSecret);
114
270
  hmac.update(main);
115
271
  const digest = hmac.digest("hex");
116
272
  return main + "--" + digest;
@@ -118,7 +274,7 @@ var Session = class {
118
274
  decode(text) {
119
275
  text = decodeURIComponent(text);
120
276
  const signedParts = text.split("--");
121
- const hmac = (0, import_crypto.createHmac)(this.config.digest, this.signedSecret);
277
+ const hmac = (0, import_crypto2.createHmac)(this.config.digest, this.signedSecret);
122
278
  hmac.update(signedParts[0]);
123
279
  const digest = hmac.digest("hex");
124
280
  if (signedParts[1] !== digest)
@@ -127,7 +283,7 @@ var Session = class {
127
283
  const parts = message.split("--").map(function(part2) {
128
284
  return Buffer.from(part2, "base64");
129
285
  });
130
- const cipher = (0, import_crypto.createDecipheriv)(this.config.cipherName, this.secret, parts[1]);
286
+ const cipher = (0, import_crypto2.createDecipheriv)(this.config.cipherName, this.secret, parts[1]);
131
287
  const part = Buffer.from(cipher.update(parts[0])).toString("utf8");
132
288
  const final = cipher.final("utf8");
133
289
  const decrypt = [part, final].join("");
@@ -437,7 +593,7 @@ var Http = class {
437
593
  var _a;
438
594
  data.dependencies["@faasjs/http"] = "*";
439
595
  await next();
440
- const logger = new import_logger.Logger(this.name);
596
+ const logger = new Logger(this.name);
441
597
  logger.debug("Generate api gateway's config");
442
598
  logger.debug("%j", data);
443
599
  const config = data.config.plugins ? deepMerge(data.config.plugins[this.name || this.type], { config: this.config }) : { config: this.config };
@@ -570,10 +726,20 @@ var Http = class {
570
726
  delete data.response.headers["Content-Encoding"];
571
727
  }
572
728
  }
729
+ /**
730
+ * set header
731
+ * @param key {string} key
732
+ * @param value {*} value
733
+ */
573
734
  setHeader(key, value) {
574
735
  this.response.headers[key] = value;
575
736
  return this;
576
737
  }
738
+ /**
739
+ * set Content-Type
740
+ * @param type {string} 类型
741
+ * @param charset {string} 编码
742
+ */
577
743
  setContentType(type, charset = "utf-8") {
578
744
  if (ContentType[type])
579
745
  this.setHeader("Content-Type", `${ContentType[type]}; charset=${charset}`);
@@ -581,17 +747,25 @@ var Http = class {
581
747
  this.setHeader("Content-Type", `${type}; charset=${charset}`);
582
748
  return this;
583
749
  }
750
+ /**
751
+ * set status code
752
+ * @param code {number} 状态码
753
+ */
584
754
  setStatusCode(code) {
585
755
  this.response.statusCode = code;
586
756
  return this;
587
757
  }
758
+ /**
759
+ * set body
760
+ * @param body {*} 内容
761
+ */
588
762
  setBody(body) {
589
763
  this.response.body = body;
590
764
  return this;
591
765
  }
592
766
  };
593
767
  function useHttp(config) {
594
- return (0, import_func.usePlugin)(new Http(config));
768
+ return usePlugin(new Http(config));
595
769
  }
596
770
  // Annotate the CommonJS export names for ESM import in node:
597
771
  0 && (module.exports = {
package/dist/index.mjs CHANGED
@@ -6,10 +6,165 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  throw new Error('Dynamic require of "' + x + '" is not supported');
7
7
  });
8
8
 
9
- // src/index.ts
10
- import {
11
- usePlugin
12
- } from "@faasjs/func";
9
+ // ../logger/src/index.ts
10
+ import { format } from "util";
11
+ var LevelColor = ((LevelColor2) => {
12
+ LevelColor2[LevelColor2["debug"] = 90 /* GRAY */] = "debug";
13
+ LevelColor2[LevelColor2["info"] = 32 /* GREEN */] = "info";
14
+ LevelColor2[LevelColor2["warn"] = 33 /* ORANGE */] = "warn";
15
+ LevelColor2[LevelColor2["error"] = 31 /* RED */] = "error";
16
+ return LevelColor2;
17
+ })(LevelColor || {});
18
+ var LevelPriority = {
19
+ debug: 0,
20
+ info: 1,
21
+ warn: 2,
22
+ error: 3
23
+ };
24
+ var Logger = class {
25
+ /**
26
+ * @param label {string} Prefix label
27
+ */
28
+ constructor(label) {
29
+ this.colorfyOutput = true;
30
+ if (label)
31
+ this.label = label;
32
+ this.silent = !process.env.FaasLog && process.env.npm_config_argv && JSON.parse(process.env.npm_config_argv).original.includes("--silent");
33
+ if (["remote", "mono"].includes(process.env.FaasMode))
34
+ this.colorfyOutput = false;
35
+ this.level = process.env.FaasLog ? LevelPriority[process.env.FaasLog.toLowerCase()] : 0;
36
+ this.cachedTimers = {};
37
+ this.size = 1e3;
38
+ this.stdout = console.log;
39
+ this.stderr = console.error;
40
+ }
41
+ /**
42
+ * @param message {string} message
43
+ * @param args {...any=} arguments
44
+ */
45
+ debug(message, ...args) {
46
+ this.log("debug", message, ...args);
47
+ return this;
48
+ }
49
+ /**
50
+ * @param message {string} message
51
+ * @param args {...any=} arguments
52
+ */
53
+ info(message, ...args) {
54
+ this.log("info", message, ...args);
55
+ return this;
56
+ }
57
+ /**
58
+ * @param message {string} message
59
+ * @param args {...any=} arguments
60
+ */
61
+ warn(message, ...args) {
62
+ this.log("warn", message, ...args);
63
+ return this;
64
+ }
65
+ /**
66
+ * @param message {any} message or Error object
67
+ * @param args {...any=} arguments
68
+ */
69
+ error(message, ...args) {
70
+ let stack = false;
71
+ [message].concat(Array.from(args)).forEach((e) => {
72
+ if (e.stack) {
73
+ stack = true;
74
+ this.log("error", e.stack);
75
+ }
76
+ });
77
+ if (!stack)
78
+ this.log("error", message, ...args);
79
+ return this;
80
+ }
81
+ /**
82
+ * @param key {string} timer's label
83
+ * @param level [string=debug] 日志级别,支持 debug、info、warn、error
84
+ */
85
+ time(key, level = "debug") {
86
+ this.cachedTimers[key] = {
87
+ level,
88
+ time: (/* @__PURE__ */ new Date()).getTime()
89
+ };
90
+ return this;
91
+ }
92
+ /**
93
+ * @param key {string} timer's label
94
+ * @param message {string} message
95
+ * @param args {...any=} arguments
96
+ */
97
+ timeEnd(key, message, ...args) {
98
+ if (this.cachedTimers[key]) {
99
+ const timer = this.cachedTimers[key];
100
+ message = message + " +%ims";
101
+ args.push((/* @__PURE__ */ new Date()).getTime() - timer.time);
102
+ this[timer.level](message, ...args);
103
+ delete this.cachedTimers[key];
104
+ } else {
105
+ this.warn("timeEnd not found key %s", key);
106
+ this.debug(message);
107
+ }
108
+ return this;
109
+ }
110
+ /**
111
+ * @param message {string} message
112
+ * @param args {...any=} arguments
113
+ */
114
+ raw(message, ...args) {
115
+ if (this.silent)
116
+ return this;
117
+ this.stdout(format(message, ...args));
118
+ return this;
119
+ }
120
+ /**
121
+ * @param color {number} color code
122
+ * @param message {string} message
123
+ */
124
+ colorfy(color, message) {
125
+ return `\x1B[0${color}m${message}\x1B[39m`;
126
+ }
127
+ log(level, message, ...args) {
128
+ if (this.silent)
129
+ return this;
130
+ if (LevelPriority[level] < this.level)
131
+ return this;
132
+ let output = level.toUpperCase() + " " + (this.label ? `[${this.label}] ` : "") + format(message, ...args);
133
+ if (this.colorfyOutput && level !== "error")
134
+ output = this.colorfy(LevelColor[level], output);
135
+ else if (!this.colorfyOutput)
136
+ output = output.replace(/\n/g, "");
137
+ if (!output)
138
+ return this;
139
+ if (output.length > this.size && !["error", "warn"].includes(level))
140
+ output = output.slice(0, this.size - 100) + "..." + output.slice(output.length - 100);
141
+ if (level === "error")
142
+ this.stderr(output);
143
+ else
144
+ this.stdout(output);
145
+ return this;
146
+ }
147
+ };
148
+
149
+ // ../func/src/index.ts
150
+ import { randomBytes } from "crypto";
151
+ var plugins = [];
152
+ function usePlugin(plugin) {
153
+ if (!plugins.find((p) => p.name === plugin.name))
154
+ plugins.push(plugin);
155
+ if (!plugin.mount)
156
+ plugin.mount = async function(data) {
157
+ if (plugin.onMount)
158
+ await plugin.onMount({
159
+ config: (data == null ? void 0 : data.config) || /* @__PURE__ */ Object.create(null),
160
+ event: /* @__PURE__ */ Object.create(null),
161
+ context: /* @__PURE__ */ Object.create(null),
162
+ logger: new Logger(plugin.name)
163
+ }, async () => Promise.resolve());
164
+ return plugin;
165
+ };
166
+ return plugin;
167
+ }
13
168
 
14
169
  // ../deep_merge/src/index.ts
15
170
  var shouldMerge = function(item) {
@@ -38,12 +193,9 @@ function deepMerge(...sources) {
38
193
  return acc;
39
194
  }
40
195
 
41
- // src/index.ts
42
- import { Logger } from "@faasjs/logger";
43
-
44
196
  // src/session.ts
45
197
  import {
46
- randomBytes,
198
+ randomBytes as randomBytes2,
47
199
  pbkdf2Sync,
48
200
  createCipheriv,
49
201
  createHmac,
@@ -56,7 +208,7 @@ var Session = class {
56
208
  console.warn("Session's secret is missing.");
57
209
  this.config = Object.assign({
58
210
  key: "key",
59
- secret: randomBytes(128).toString("hex"),
211
+ secret: randomBytes2(128).toString("hex"),
60
212
  salt: "salt",
61
213
  signedSalt: "signedSalt",
62
214
  keylen: 64,
@@ -92,7 +244,7 @@ var Session = class {
92
244
  encode(text) {
93
245
  if (typeof text !== "string")
94
246
  text = JSON.stringify(text);
95
- const iv = randomBytes(16);
247
+ const iv = randomBytes2(16);
96
248
  const cipher = createCipheriv(this.config.cipherName, this.secret, iv);
97
249
  const encrypted = Buffer.concat([cipher.update(text), cipher.final()]).toString("base64");
98
250
  const main = Buffer.from([encrypted, iv.toString("base64")].join("--")).toString("base64");
@@ -560,10 +712,20 @@ var Http = class {
560
712
  delete data.response.headers["Content-Encoding"];
561
713
  }
562
714
  }
715
+ /**
716
+ * set header
717
+ * @param key {string} key
718
+ * @param value {*} value
719
+ */
563
720
  setHeader(key, value) {
564
721
  this.response.headers[key] = value;
565
722
  return this;
566
723
  }
724
+ /**
725
+ * set Content-Type
726
+ * @param type {string} 类型
727
+ * @param charset {string} 编码
728
+ */
567
729
  setContentType(type, charset = "utf-8") {
568
730
  if (ContentType[type])
569
731
  this.setHeader("Content-Type", `${ContentType[type]}; charset=${charset}`);
@@ -571,10 +733,18 @@ var Http = class {
571
733
  this.setHeader("Content-Type", `${type}; charset=${charset}`);
572
734
  return this;
573
735
  }
736
+ /**
737
+ * set status code
738
+ * @param code {number} 状态码
739
+ */
574
740
  setStatusCode(code) {
575
741
  this.response.statusCode = code;
576
742
  return this;
577
743
  }
744
+ /**
745
+ * set body
746
+ * @param body {*} 内容
747
+ */
578
748
  setBody(body) {
579
749
  this.response.body = body;
580
750
  return this;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faasjs/http",
3
- "version": "0.0.3-beta.63",
3
+ "version": "0.0.3-beta.64",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -23,8 +23,8 @@
23
23
  "dist"
24
24
  ],
25
25
  "dependencies": {
26
- "@faasjs/func": "^0.0.3-beta.63",
27
- "@faasjs/logger": "^0.0.3-beta.63"
26
+ "@faasjs/func": "^0.0.3-beta.64",
27
+ "@faasjs/logger": "^0.0.3-beta.64"
28
28
  },
29
29
  "engines": {
30
30
  "npm": ">=8.0.0",