@vectorx/functions-framework 0.1.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 (69) hide show
  1. package/README.md +141 -0
  2. package/bin/rcb-ff.js +149 -0
  3. package/lib/async-context.js +61 -0
  4. package/lib/config.js +10 -0
  5. package/lib/constants.js +10 -0
  6. package/lib/error.js +47 -0
  7. package/lib/framework.js +195 -0
  8. package/lib/function-loader.js +63 -0
  9. package/lib/function-registry.js +20 -0
  10. package/lib/function-wrapper.js +113 -0
  11. package/lib/index.js +23 -0
  12. package/lib/logger.js +160 -0
  13. package/lib/middlewares/index.js +19 -0
  14. package/lib/middlewares/middle-apm-injection.js +37 -0
  15. package/lib/middlewares/middle-async-context.js +27 -0
  16. package/lib/middlewares/middle-common-logger.js +67 -0
  17. package/lib/middlewares/middle-context-injection.js +33 -0
  18. package/lib/middlewares/middle-event-id.js +20 -0
  19. package/lib/middlewares/middle-function-route.js +26 -0
  20. package/lib/middlewares/middle-logs-request.js +48 -0
  21. package/lib/middlewares/middle-open-gw-request.js +29 -0
  22. package/lib/request.js +162 -0
  23. package/lib/router.js +51 -0
  24. package/lib/server.js +67 -0
  25. package/lib/sse.js +176 -0
  26. package/lib/types.js +2 -0
  27. package/lib/unified-responder.js +64 -0
  28. package/lib/user-logger.js +54 -0
  29. package/lib/utils/apm.config.js +7 -0
  30. package/lib/utils/apm.js +140 -0
  31. package/lib/utils/common.js +5 -0
  32. package/lib/utils/console-intercept.js +58 -0
  33. package/lib/utils/error-stack.js +30 -0
  34. package/lib/utils/helper.js +88 -0
  35. package/lib/utils/machineId.js +72 -0
  36. package/package.json +75 -0
  37. package/types/async-context.d.ts +17 -0
  38. package/types/config.d.ts +1 -0
  39. package/types/constants.d.ts +2 -0
  40. package/types/error.d.ts +20 -0
  41. package/types/framework.d.ts +29 -0
  42. package/types/function-loader.d.ts +26 -0
  43. package/types/function-registry.d.ts +4 -0
  44. package/types/function-wrapper.d.ts +3 -0
  45. package/types/index.d.ts +7 -0
  46. package/types/logger.d.ts +62 -0
  47. package/types/middlewares/index.d.ts +8 -0
  48. package/types/middlewares/middle-apm-injection.d.ts +2 -0
  49. package/types/middlewares/middle-async-context.d.ts +2 -0
  50. package/types/middlewares/middle-common-logger.d.ts +2 -0
  51. package/types/middlewares/middle-context-injection.d.ts +4 -0
  52. package/types/middlewares/middle-event-id.d.ts +2 -0
  53. package/types/middlewares/middle-function-route.d.ts +4 -0
  54. package/types/middlewares/middle-logs-request.d.ts +3 -0
  55. package/types/middlewares/middle-open-gw-request.d.ts +2 -0
  56. package/types/request.d.ts +46 -0
  57. package/types/router.d.ts +15 -0
  58. package/types/server.d.ts +32 -0
  59. package/types/sse.d.ts +23 -0
  60. package/types/types.d.ts +18 -0
  61. package/types/unified-responder.d.ts +15 -0
  62. package/types/user-logger.d.ts +5 -0
  63. package/types/utils/apm.config.d.ts +6 -0
  64. package/types/utils/apm.d.ts +21 -0
  65. package/types/utils/common.d.ts +2 -0
  66. package/types/utils/console-intercept.d.ts +6 -0
  67. package/types/utils/error-stack.d.ts +5 -0
  68. package/types/utils/helper.d.ts +7 -0
  69. package/types/utils/machineId.d.ts +2 -0
package/lib/request.js ADDED
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Request = void 0;
16
+ const stream_1 = require("stream");
17
+ const node_fetch_1 = __importDefault(require("node-fetch"));
18
+ const helper_1 = require("./utils/helper");
19
+ function headersInit2Indexable(h) {
20
+ if (isHeaders(h)) {
21
+ const ret = {};
22
+ h.forEach((val, key) => {
23
+ ret[key] = val;
24
+ });
25
+ return ret;
26
+ }
27
+ return h;
28
+ function isHeaders(h) {
29
+ return h instanceof Headers;
30
+ }
31
+ }
32
+ class Request {
33
+ constructor(config = {}) {
34
+ const { timeout, timeoutMsg, restrictedMethods, defaultHeaders = {} } = config;
35
+ this.defaultHeaders = defaultHeaders;
36
+ this.timeout = timeout || 0;
37
+ this.timeoutMsg = timeoutMsg || "请求超时";
38
+ this.restrictedMethods = restrictedMethods || ["get", "post", "upload", "download"];
39
+ }
40
+ get(options) {
41
+ return this.request(Object.assign(Object.assign({}, options), { method: "get" }), this.restrictedMethods.includes("get"));
42
+ }
43
+ post(options) {
44
+ return this.request(Object.assign(Object.assign({}, options), { method: "post" }), this.restrictedMethods.includes("post"));
45
+ }
46
+ put(options) {
47
+ return this.request(Object.assign(Object.assign({}, options), { method: "put" }));
48
+ }
49
+ upload(options) {
50
+ var _a;
51
+ const { data: _data, file, name, method, headers = {} } = options;
52
+ if (file === undefined || name === undefined) {
53
+ throw new Error("file and name is required");
54
+ }
55
+ const data = (0, helper_1.obj2StrRecord)(_data !== null && _data !== void 0 ? _data : {});
56
+ const loweredMethod = method === null || method === void 0 ? void 0 : method.toLowerCase();
57
+ const reqMethod = (_a = ["post", "put"].find((m) => m === loweredMethod)) !== null && _a !== void 0 ? _a : "put";
58
+ if (reqMethod === "post") {
59
+ const formData = new FormData();
60
+ Object.keys(data).forEach((key) => {
61
+ formData.append(key, data[key]);
62
+ });
63
+ formData.append("key", name);
64
+ formData.append("file", file);
65
+ return this.request(Object.assign(Object.assign({}, options), { data: formData, method: reqMethod }), this.restrictedMethods.includes("upload"));
66
+ }
67
+ return this.request(Object.assign(Object.assign({}, options), { method: "put", headers, body: file }), this.restrictedMethods.includes("upload"));
68
+ }
69
+ download(options) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ const { data } = yield this.get(Object.assign(Object.assign({}, options), { headers: {}, responseType: "blob" }));
72
+ return {
73
+ statusCode: 200,
74
+ tempFilePath: options.url,
75
+ data,
76
+ };
77
+ });
78
+ }
79
+ request(options_1) {
80
+ return __awaiter(this, arguments, void 0, function* (options, enableAbort = false) {
81
+ const { url, headers: _headers = {}, data, responseType, withCredentials, body, method: _method } = options, headers = Object.assign(Object.assign({}, this.defaultHeaders), (0, helper_1.obj2StrRecord)(_headers)), method = String(_method).toLowerCase() || "get";
82
+ let queryParams = {};
83
+ if (method === "get" || method === "head") {
84
+ queryParams = Object.assign(Object.assign({}, (data || {})), (body && typeof body === "object" ? body : {}));
85
+ }
86
+ else {
87
+ queryParams = method === "get" ? data : {};
88
+ }
89
+ const realUrl = (0, helper_1.formatUrl)("https", url !== null && url !== void 0 ? url : "", queryParams), controller = new AbortController(), { signal } = controller;
90
+ let timer;
91
+ if (enableAbort && this.timeout) {
92
+ timer = setTimeout(() => {
93
+ console.warn(this.timeoutMsg);
94
+ controller.abort(new Error(this.timeoutMsg));
95
+ }, this.timeout);
96
+ }
97
+ let payload;
98
+ if (method !== "get" && method !== "head") {
99
+ if ((0, helper_1.isFormData)(data)) {
100
+ payload = data;
101
+ }
102
+ else if (headers["content-type"] === "application/x-www-form-urlencoded") {
103
+ payload = (0, helper_1.toQueryString)(data !== null && data !== void 0 ? data : {});
104
+ }
105
+ else if (body) {
106
+ payload = body;
107
+ }
108
+ else {
109
+ payload = data ? JSON.stringify(data) : undefined;
110
+ }
111
+ }
112
+ const requestOptions = Object.assign(Object.assign({ method,
113
+ headers }, (payload !== undefined && { body: payload })), { credentials: withCredentials ? "include" : "same-origin", signal });
114
+ try {
115
+ const response = yield (0, node_fetch_1.default)(realUrl, requestOptions), result = {
116
+ header: {},
117
+ statusCode: response.status,
118
+ };
119
+ try {
120
+ result.data = responseType === "blob" ? yield response.blob() : yield response.json();
121
+ }
122
+ catch (_) {
123
+ result.data = responseType === "blob" ? yield response.blob() : yield response.text();
124
+ }
125
+ const { headers } = response;
126
+ headers.forEach((val, key) => (result.header[key.toLowerCase()] = val));
127
+ return result;
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ }
132
+ });
133
+ }
134
+ fetch(options) {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ const { url, enableAbort = false, stream = false } = options, abortController = new AbortController();
137
+ let timer = undefined;
138
+ if (enableAbort && this.timeout) {
139
+ timer = setTimeout(() => {
140
+ console.warn(this.timeoutMsg);
141
+ abortController.abort(new Error(this.timeoutMsg));
142
+ }, this.timeout);
143
+ }
144
+ const res = yield (yield node_fetch_1.default)(url, Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, this.defaultHeaders), (options.headers ? headersInit2Indexable(options.headers) : {})), body: options.body, signal: abortController.signal }))
145
+ .then((x) => {
146
+ clearTimeout(timer);
147
+ return x;
148
+ })
149
+ .catch((x) => {
150
+ clearTimeout(timer);
151
+ return Promise.reject(x);
152
+ });
153
+ const ret = {
154
+ data: stream ? (res.body ? stream_1.Readable.toWeb(res.body) : res.body) : res.json(),
155
+ statusCode: res.status,
156
+ header: res.headers,
157
+ };
158
+ return ret;
159
+ });
160
+ }
161
+ }
162
+ exports.Request = Request;
package/lib/router.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Router = void 0;
4
+ exports.routeFunction = routeFunction;
5
+ const radix3_1 = require("radix3");
6
+ const function_registry_1 = require("./function-registry");
7
+ class Router {
8
+ constructor(config) {
9
+ this.routes = new Map();
10
+ this.router = (0, radix3_1.createRouter)({
11
+ strictTrailingSlash: false,
12
+ });
13
+ for (const route of config.routes) {
14
+ if (route.path) {
15
+ const p = route.path.endsWith("/") ? route.path : route.path + "/";
16
+ if (this.routes.has(p)) {
17
+ continue;
18
+ }
19
+ this.routes.set(p, route);
20
+ this.routes.set(p + "**", route);
21
+ }
22
+ }
23
+ for (const [path, route] of this.routes.entries()) {
24
+ this.addRoute(path, route);
25
+ }
26
+ }
27
+ addRoute(path, route) {
28
+ this.router.insert(path, route);
29
+ }
30
+ findRoute(path) {
31
+ const found = this.router.lookup(path);
32
+ if (!found) {
33
+ return null;
34
+ }
35
+ if (found.params) {
36
+ delete found.params;
37
+ }
38
+ return found;
39
+ }
40
+ }
41
+ exports.Router = Router;
42
+ function routeFunction(router, path) {
43
+ const matchedRoute = router.findRoute(path);
44
+ if (matchedRoute) {
45
+ return {
46
+ routeDefinition: matchedRoute,
47
+ handleFunction: (0, function_registry_1.getRegisteredFunction)((0, function_registry_1.buildFnId)("@fn", matchedRoute.functionName)),
48
+ };
49
+ }
50
+ return {};
51
+ }
package/lib/server.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createServer = createServer;
16
+ const http_1 = __importDefault(require("http"));
17
+ const koa_1 = __importDefault(require("koa"));
18
+ const koa_body_1 = require("koa-body");
19
+ const raw_body_1 = __importDefault(require("raw-body"));
20
+ const error_1 = require("./error");
21
+ const middlewares_1 = require("./middlewares");
22
+ const unified_responder_1 = require("./unified-responder");
23
+ function corsMiddleware() {
24
+ return (ctx, next) => __awaiter(this, void 0, void 0, function* () {
25
+ ctx.set("Access-Control-Allow-Origin", "*");
26
+ ctx.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
27
+ ctx.set("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, Referer, referrer");
28
+ ctx.set("Access-Control-Max-Age", "86400");
29
+ if (ctx.method === "OPTIONS") {
30
+ ctx.status = 204;
31
+ return;
32
+ }
33
+ yield next();
34
+ });
35
+ }
36
+ function createServer(options, router, projectConfig) {
37
+ const app = new koa_1.default();
38
+ app.use(corsMiddleware());
39
+ app.use((0, middlewares_1.logsQueryMiddleware)());
40
+ app.use((0, middlewares_1.contextInjectionMiddleware)(options, projectConfig));
41
+ app.use((0, middlewares_1.eventIdMiddleware)());
42
+ app.use((0, middlewares_1.apmMiddleware)());
43
+ app.use((0, middlewares_1.asyncContextMiddleware)());
44
+ app.use((0, middlewares_1.loggerMiddleware)());
45
+ app.use((0, koa_body_1.koaBody)({
46
+ multipart: true,
47
+ patchKoa: true,
48
+ onError: (err, ctx) => {
49
+ return (0, unified_responder_1.sendResponse)(ctx, undefined, (0, error_1.newBadRequestErr)(err), 400);
50
+ },
51
+ }));
52
+ app.use((ctx, next) => __awaiter(this, void 0, void 0, function* () {
53
+ if (!(ctx.request.files || ctx.request.body || ctx.state.isTimeout)) {
54
+ try {
55
+ ctx.rawBody = yield (0, raw_body_1.default)(ctx.req);
56
+ }
57
+ catch (err) {
58
+ return (0, unified_responder_1.sendResponse)(ctx, undefined, (0, error_1.newBadRequestErr)(err), 400);
59
+ }
60
+ }
61
+ yield next();
62
+ }));
63
+ app.use((0, middlewares_1.openGwRequestMiddleware)(projectConfig.agentId));
64
+ app.use((0, middlewares_1.functionRouteMiddleware)(router, projectConfig));
65
+ const httpServer = http_1.default.createServer(app.callback());
66
+ return httpServer;
67
+ }
package/lib/sse.js ADDED
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ServerSentEvent = void 0;
37
+ const events_1 = require("events");
38
+ const stream_1 = require("stream");
39
+ const util = __importStar(require("util"));
40
+ const helper_1 = require("./utils/helper");
41
+ const kDefaultEncoder = new util.TextEncoder();
42
+ class ServerSentEvent extends events_1.EventEmitter {
43
+ constructor(ctx) {
44
+ super();
45
+ this.closed = false;
46
+ this.encoder = kDefaultEncoder;
47
+ this.ctx = ctx;
48
+ this.stream = new stream_1.PassThrough({
49
+ objectMode: false,
50
+ });
51
+ this.stream.pipe(ctx.res);
52
+ ctx.respond = false;
53
+ ctx.req.once("close", () => {
54
+ this.emit("close");
55
+ this.closed = true;
56
+ });
57
+ if (ctx.req.socket) {
58
+ ctx.req.socket.setTimeout(0);
59
+ ctx.req.socket.setNoDelay(true);
60
+ ctx.req.socket.setKeepAlive(true, 0);
61
+ }
62
+ const headers = {
63
+ "Content-Type": "text/event-stream",
64
+ "Cache-Control": "no-cache",
65
+ Connection: "keep-alive",
66
+ };
67
+ if (ctx.state && ctx.state.eventID) {
68
+ headers["X-Request-Id"] = ctx.state.eventID;
69
+ }
70
+ ctx.set(headers);
71
+ ctx.status = 200;
72
+ ctx.flushHeaders();
73
+ for (const key of ["ctx", "stream", "encoder"]) {
74
+ Object.defineProperty(this, key, {
75
+ configurable: false,
76
+ enumerable: false,
77
+ writable: false,
78
+ });
79
+ }
80
+ }
81
+ setEncoder(encoder) {
82
+ this.encoder = encoder;
83
+ }
84
+ emitMessage(event, data) {
85
+ if (this.closed)
86
+ return false;
87
+ const message = {
88
+ event,
89
+ data,
90
+ };
91
+ return this.send(message);
92
+ }
93
+ emit(event, ...args) {
94
+ return super.emit(event, ...args);
95
+ }
96
+ send(event) {
97
+ const encoder = this.encoder;
98
+ const stream = this.stream;
99
+ if (this.closed) {
100
+ return false;
101
+ }
102
+ const events = Array.isArray(event) ? event : [event];
103
+ const bufs = [];
104
+ for (const event of events) {
105
+ if (Buffer.isBuffer(event)) {
106
+ bufs.push(event);
107
+ }
108
+ else if (typeof event === "string") {
109
+ bufs.push(Buffer.from(encoder.encode(event)));
110
+ }
111
+ else if ((0, helper_1.isPlainObject)(event)) {
112
+ const msgs = eventToMsgs(event);
113
+ for (const msg of msgs) {
114
+ if (Buffer.isBuffer(msg)) {
115
+ bufs.push(msg);
116
+ }
117
+ else {
118
+ bufs.push(Buffer.from(encoder.encode(msg)));
119
+ }
120
+ }
121
+ }
122
+ }
123
+ const buf = Buffer.concat(bufs);
124
+ if (Buffer.byteLength(buf) > 0) {
125
+ return stream.write(Buffer.concat(bufs));
126
+ }
127
+ return false;
128
+ }
129
+ end(msg) {
130
+ if (msg) {
131
+ this.send(msg);
132
+ }
133
+ this.stream.end();
134
+ this.ctx.res.end();
135
+ this.closed = true;
136
+ }
137
+ get isClosed() {
138
+ return this.closed;
139
+ }
140
+ }
141
+ exports.ServerSentEvent = ServerSentEvent;
142
+ function eventToMsgs(event) {
143
+ const msgs = [];
144
+ if ("comment" in event) {
145
+ msgs.push(`: ${event.comment}\n`);
146
+ }
147
+ if ("event" in event) {
148
+ msgs.push(`event: ${event.event}\n`);
149
+ }
150
+ if ("id" in event) {
151
+ msgs.push(`id: ${event.id}\n`);
152
+ }
153
+ if ("retry" in event) {
154
+ msgs.push(`retry: ${event.retry}\n`);
155
+ }
156
+ if ("data" in event) {
157
+ msgs.push(toDataEventString(event.data));
158
+ }
159
+ if (msgs.length > 0) {
160
+ msgs.push("\n");
161
+ }
162
+ return msgs;
163
+ }
164
+ function toDataEventString(data) {
165
+ if (Buffer.isBuffer(data)) {
166
+ return Buffer.concat([Buffer.from("data: "), data, Buffer.from("\n")]);
167
+ }
168
+ if ((0, helper_1.isPlainObject)(data)) {
169
+ return toDataEventString(JSON.stringify(data));
170
+ }
171
+ const dataStr = typeof data !== "string" ? `${data}` : data;
172
+ return dataStr
173
+ .split(/[\r\n]+/)
174
+ .map((line) => `data: ${line}\n`)
175
+ .join("");
176
+ }
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendResponse = sendResponse;
4
+ const error_1 = require("./error");
5
+ const logger_1 = require("./logger");
6
+ function sendResponse(ctx, data, error, errStatusCode = 500, withStack = true) {
7
+ if (error) {
8
+ if (!ctx.response) {
9
+ return;
10
+ }
11
+ const errorStack = (0, error_1.decorateErrorStack)(error.cause);
12
+ logger_1.functionsLogger.log(logger_1.LogType.ACCESS, logger_1.LogLevel.ERROR, error.message, {
13
+ code: error.code,
14
+ stack: errorStack,
15
+ statusCode: errStatusCode,
16
+ });
17
+ console.error(`[ERROR] ${error.message}\n${errorStack}`);
18
+ ctx.status = errStatusCode;
19
+ if (withStack) {
20
+ data = {
21
+ code: error.code,
22
+ message: error.message,
23
+ stack: errorStack,
24
+ requestId: ctx.state.eventID,
25
+ };
26
+ }
27
+ else {
28
+ data = {
29
+ code: error.code,
30
+ message: error.message,
31
+ requestId: ctx.state.eventID,
32
+ };
33
+ }
34
+ }
35
+ if (isIntegrationResponse(data)) {
36
+ return sendIntegrationResponse(ctx, data);
37
+ }
38
+ if (typeof data === "undefined" || data === null) {
39
+ ctx.status = 204;
40
+ }
41
+ else {
42
+ ctx.body = data;
43
+ }
44
+ const eResult = data;
45
+ if (eResult && eResult.code) {
46
+ ctx.state.errorResult = {
47
+ code: eResult.code,
48
+ message: eResult.message,
49
+ };
50
+ }
51
+ return;
52
+ }
53
+ function isIntegrationResponse(result) {
54
+ if (typeof result !== "object" || !result) {
55
+ return false;
56
+ }
57
+ const { statusCode, headers } = result;
58
+ return typeof statusCode === "number" && typeof headers === "object";
59
+ }
60
+ function sendIntegrationResponse(ctx, result) {
61
+ ctx.set(result.headers);
62
+ ctx.body = result.body;
63
+ ctx.status = result.statusCode;
64
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.takeUserCodeLogs = takeUserCodeLogs;
4
+ exports.pushUserCodeLogs = pushUserCodeLogs;
5
+ exports.addUserCodeLog = addUserCodeLog;
6
+ exports.getUserCodeLogs = getUserCodeLogs;
7
+ const async_context_1 = require("./async-context");
8
+ const logger_1 = require("./logger");
9
+ const USER_CODE_LOGS_MAX_COUNT = 100;
10
+ const USER_CODE_LOGS_FLUSH_TIMER_TIMEOUT = 1000;
11
+ function lazyInitUserCodeLogs() {
12
+ const currentContext = (0, async_context_1.getCurrentAsyncContext)();
13
+ if (currentContext && currentContext.userCodeLogs === undefined) {
14
+ currentContext.userCodeLogs = [];
15
+ }
16
+ }
17
+ function takeUserCodeLogs() {
18
+ lazyInitUserCodeLogs();
19
+ const context = (0, async_context_1.getCurrentAsyncContext)();
20
+ if (context !== undefined) {
21
+ const logs = context.userCodeLogs || [];
22
+ context.userCodeLogs = [];
23
+ return logs;
24
+ }
25
+ return [];
26
+ }
27
+ function pushUserCodeLogs(log) {
28
+ lazyInitUserCodeLogs();
29
+ const context = (0, async_context_1.getCurrentAsyncContext)();
30
+ if (context === null || context === void 0 ? void 0 : context.userCodeLogs) {
31
+ context.userCodeLogs.push(log);
32
+ }
33
+ }
34
+ function addUserCodeLog(log) {
35
+ var _a;
36
+ lazyInitUserCodeLogs();
37
+ const userCodeLogs = ((_a = (0, async_context_1.getCurrentAsyncContext)()) === null || _a === void 0 ? void 0 : _a.userCodeLogs) || [];
38
+ if (userCodeLogs.length >= USER_CODE_LOGS_MAX_COUNT) {
39
+ logger_1.functionsLogger.logUserCodelog();
40
+ }
41
+ const currentContext = (0, async_context_1.getCurrentAsyncContext)();
42
+ if (currentContext && currentContext.done && !currentContext.userCodeLogsFlushTimer) {
43
+ currentContext.userCodeLogsFlushTimer = setTimeout(() => {
44
+ logger_1.functionsLogger.logUserCodelog();
45
+ currentContext.userCodeLogsFlushTimer = undefined;
46
+ }, USER_CODE_LOGS_FLUSH_TIMER_TIMEOUT);
47
+ }
48
+ pushUserCodeLogs(log);
49
+ }
50
+ function getUserCodeLogs() {
51
+ lazyInitUserCodeLogs();
52
+ const context = (0, async_context_1.getCurrentAsyncContext)();
53
+ return (context === null || context === void 0 ? void 0 : context.userCodeLogs) || [];
54
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultConfig = exports.APM_MEASUREMENT_NAME = void 0;
4
+ exports.APM_MEASUREMENT_NAME = "vectorx_kit_agent_runtime";
5
+ exports.defaultConfig = {
6
+ endpoint: "https://apm-fe.xiaohongshu.com/api/data",
7
+ };