@middy/util 2.5.1 → 3.0.0-alpha.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017-2021 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
3
+ Copyright (c) 2017-2022 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -47,7 +47,7 @@ Everyone is very welcome to contribute to this repository. Feel free to [raise i
47
47
 
48
48
  ## License
49
49
 
50
- Licensed under [MIT License](LICENSE). Copyright (c) 2017-2021 Luciano Mammino, will Farrell, and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
50
+ Licensed under [MIT License](LICENSE). Copyright (c) 2017-2022 Luciano Mammino, will Farrell, and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
51
51
 
52
52
  <a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy?ref=badge_large">
53
53
  <img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy.svg?type=large" alt="FOSSA Status" style="max-width:100%;">
package/codes.js ADDED
@@ -0,0 +1,66 @@
1
+ export default {
2
+ 100: 'Continue',
3
+ 101: 'Switching Protocols',
4
+ 102: 'Processing',
5
+ 103: 'Early Hints',
6
+ 200: 'OK',
7
+ 201: 'Created',
8
+ 202: 'Accepted',
9
+ 203: 'Non-Authoritative Information',
10
+ 204: 'No Content',
11
+ 205: 'Reset Content',
12
+ 206: 'Partial Content',
13
+ 207: 'Multi-Status',
14
+ 208: 'Already Reported',
15
+ 226: 'IM Used',
16
+ 300: 'Multiple Choices',
17
+ 301: 'Moved Permanently',
18
+ 302: 'Found',
19
+ 303: 'See Other',
20
+ 304: 'Not Modified',
21
+ 305: 'Use Proxy',
22
+ 306: '(Unused)',
23
+ 307: 'Temporary Redirect',
24
+ 308: 'Permanent Redirect',
25
+ 400: 'Bad Request',
26
+ 401: 'Unauthorized',
27
+ 402: 'Payment Required',
28
+ 403: 'Forbidden',
29
+ 404: 'Not Found',
30
+ 405: 'Method Not Allowed',
31
+ 406: 'Not Acceptable',
32
+ 407: 'Proxy Authentication Required',
33
+ 408: 'Request Timeout',
34
+ 409: 'Conflict',
35
+ 410: 'Gone',
36
+ 411: 'Length Required',
37
+ 412: 'Precondition Failed',
38
+ 413: 'Payload Too Large',
39
+ 414: 'URI Too Long',
40
+ 415: 'Unsupported Media Type',
41
+ 416: 'Range Not Satisfiable',
42
+ 417: 'Expectation Failed',
43
+ 418: "I'm a teapot",
44
+ 421: 'Misdirected Request',
45
+ 422: 'Unprocessable Entity',
46
+ 423: 'Locked',
47
+ 424: 'Failed Dependency',
48
+ 425: 'Unordered Collection',
49
+ 426: 'Upgrade Required',
50
+ 428: 'Precondition Required',
51
+ 429: 'Too Many Requests',
52
+ 431: 'Request Header Fields Too Large',
53
+ 451: 'Unavailable For Legal Reasons',
54
+ 500: 'Internal Server Error',
55
+ 501: 'Not Implemented',
56
+ 502: 'Bad Gateway',
57
+ 503: 'Service Unavailable',
58
+ 504: 'Gateway Timeout',
59
+ 505: 'HTTP Version Not Supported',
60
+ 506: 'Variant Also Negotiates',
61
+ 507: 'Insufficient Storage',
62
+ 508: 'Loop Detected',
63
+ 509: 'Bandwidth Limit Exceeded',
64
+ 510: 'Not Extended',
65
+ 511: 'Network Authentication Required'
66
+ }
package/index.d.ts CHANGED
@@ -1,16 +1,14 @@
1
1
  import middy from '@middy/core'
2
- import { captureAWSClient } from 'aws-xray-sdk'
3
2
 
4
3
  interface Options<Client, ClientOptions> {
5
4
  AwsClient?: new() => Client
6
5
  awsClientOptions?: Partial<ClientOptions>
7
6
  awsClientAssumeRole?: string
8
- awsClientCapture?: typeof captureAWSClient
7
+ awsClientCapture?: (service: Client) => Client
9
8
  fetchData?: { [key: string]: string }
10
9
  disablePrefetch?: boolean
11
10
  cacheKey?: string
12
11
  cacheExpiry?: number
13
- setToEnv?: boolean
14
12
  setToContext?: boolean
15
13
  }
16
14
 
@@ -40,6 +38,8 @@ declare function clearCache (keys?: string | string[] | null): void
40
38
 
41
39
  declare function jsonSafeParse (string: string, reviver?: (key: string, value: any) => any): any
42
40
 
43
- declare function normalizeHttpResponse (response: any, fallbackResponse?: any): any
41
+ declare function normalizeHttpResponse (request: any, fallbackResponse?: any): any
44
42
 
45
43
  declare function createError (code: number, message: string, properties?: Record<string, any>): HttpError
44
+
45
+ declare function modifyCache (cacheKey: string, value: any): void
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "2.5.1",
3
+ "version": "3.0.0-alpha.0",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
- "type": "commonjs",
5
+ "type": "module",
6
6
  "engines": {
7
- "node": ">=12"
7
+ "node": ">=14"
8
8
  },
9
9
  "engineStrict": true,
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "main": "index.js",
13
+ "exports": "./index.js",
14
14
  "types": "index.d.ts",
15
15
  "files": [
16
16
  "index.d.ts",
17
- "codes.json"
17
+ "codes.js"
18
18
  ],
19
19
  "scripts": {
20
20
  "test": "npm run test:unit",
@@ -44,12 +44,12 @@
44
44
  "url": "https://github.com/middyjs/middy/issues"
45
45
  },
46
46
  "devDependencies": {
47
- "@middy/core": "^2.5.1",
47
+ "@middy/core": "^3.0.0-alpha.0",
48
48
  "@types/aws-lambda": "^8.10.76",
49
- "@types/node": "^16.0.0",
49
+ "@types/node": "^17.0.0",
50
50
  "aws-sdk": "^2.939.0",
51
51
  "aws-xray-sdk": "^3.3.3"
52
52
  },
53
53
  "homepage": "https://github.com/middyjs/middy#readme",
54
- "gitHead": "df18e5eff7d73492a96a2ca4780a2eae45d1cedb"
54
+ "gitHead": "c533f62841c8a39d061d7b94f30ba178f002c8db"
55
55
  }
package/codes.json DELETED
@@ -1,66 +0,0 @@
1
- {
2
- "100": "Continue",
3
- "101": "Switching Protocols",
4
- "102": "Processing",
5
- "103": "Early Hints",
6
- "200": "OK",
7
- "201": "Created",
8
- "202": "Accepted",
9
- "203": "Non-Authoritative Information",
10
- "204": "No Content",
11
- "205": "Reset Content",
12
- "206": "Partial Content",
13
- "207": "Multi-Status",
14
- "208": "Already Reported",
15
- "226": "IM Used",
16
- "300": "Multiple Choices",
17
- "301": "Moved Permanently",
18
- "302": "Found",
19
- "303": "See Other",
20
- "304": "Not Modified",
21
- "305": "Use Proxy",
22
- "306": "(Unused)",
23
- "307": "Temporary Redirect",
24
- "308": "Permanent Redirect",
25
- "400": "Bad Request",
26
- "401": "Unauthorized",
27
- "402": "Payment Required",
28
- "403": "Forbidden",
29
- "404": "Not Found",
30
- "405": "Method Not Allowed",
31
- "406": "Not Acceptable",
32
- "407": "Proxy Authentication Required",
33
- "408": "Request Timeout",
34
- "409": "Conflict",
35
- "410": "Gone",
36
- "411": "Length Required",
37
- "412": "Precondition Failed",
38
- "413": "Payload Too Large",
39
- "414": "URI Too Long",
40
- "415": "Unsupported Media Type",
41
- "416": "Range Not Satisfiable",
42
- "417": "Expectation Failed",
43
- "418": "I'm a teapot",
44
- "421": "Misdirected Request",
45
- "422": "Unprocessable Entity",
46
- "423": "Locked",
47
- "424": "Failed Dependency",
48
- "425": "Unordered Collection",
49
- "426": "Upgrade Required",
50
- "428": "Precondition Required",
51
- "429": "Too Many Requests",
52
- "431": "Request Header Fields Too Large",
53
- "451": "Unavailable For Legal Reasons",
54
- "500": "Internal Server Error",
55
- "501": "Not Implemented",
56
- "502": "Bad Gateway",
57
- "503": "Service Unavailable",
58
- "504": "Gateway Timeout",
59
- "505": "HTTP Version Not Supported",
60
- "506": "Variant Also Negotiates",
61
- "507": "Insufficient Storage",
62
- "508": "Loop Detected",
63
- "509": "Bandwidth Limit Exceeded",
64
- "510": "Not Extended",
65
- "511": "Network Authentication Required"
66
- }
package/index.js DELETED
@@ -1,275 +0,0 @@
1
- "use strict";
2
-
3
- const {
4
- Agent
5
- } = require('https'); // const { NodeHttpHandler } = require('@aws-sdk/node-http-handler') // aws-sdk v3
6
-
7
-
8
- const awsClientDefaultOptions = {
9
- // AWS SDK v3
10
- // Docs: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/enforcing-tls.html
11
-
12
- /* requestHandler: new NodeHttpHandler({
13
- httpsAgent: new Agent(
14
- {
15
- secureProtocol: 'TLSv1_2_method'
16
- }
17
- )
18
- }) */
19
- // Docs: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/enforcing-tls.html
20
- httpOptions: {
21
- agent: new Agent({
22
- secureProtocol: 'TLSv1_2_method'
23
- })
24
- }
25
- };
26
-
27
- const createPrefetchClient = options => {
28
- const awsClientOptions = { ...awsClientDefaultOptions,
29
- ...options.awsClientOptions
30
- };
31
- const client = new options.AwsClient(awsClientOptions); // AWS XRay
32
-
33
- if (options.awsClientCapture) {
34
- return options.awsClientCapture(client);
35
- }
36
-
37
- return client;
38
- };
39
-
40
- const createClient = async (options, request) => {
41
- let awsClientCredentials = {}; // Role Credentials
42
-
43
- if (options.awsClientAssumeRole) {
44
- if (!request) throw new Error('Request required when assuming role');
45
- awsClientCredentials = await getInternal({
46
- credentials: options.awsClientAssumeRole
47
- }, request);
48
- }
49
-
50
- awsClientCredentials = { ...awsClientCredentials,
51
- ...options.awsClientOptions
52
- };
53
- return createPrefetchClient({ ...options,
54
- awsClientOptions: awsClientCredentials
55
- });
56
- };
57
-
58
- const canPrefetch = options => {
59
- return !(options !== null && options !== void 0 && options.awsClientAssumeRole) && !(options !== null && options !== void 0 && options.disablePrefetch);
60
- }; // Internal Context
61
-
62
-
63
- const getInternal = async (variables, request) => {
64
- if (!variables || !request) return {};
65
- let keys = [];
66
- let values = [];
67
-
68
- if (variables === true) {
69
- keys = values = Object.keys(request.internal);
70
- } else if (typeof variables === 'string') {
71
- keys = values = [variables];
72
- } else if (Array.isArray(variables)) {
73
- keys = values = variables;
74
- } else if (typeof variables === 'object') {
75
- keys = Object.keys(variables);
76
- values = Object.values(variables);
77
- }
78
-
79
- const promises = [];
80
-
81
- for (const internalKey of values) {
82
- var _valuePromise;
83
-
84
- // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
85
- const pathOptionKey = internalKey.split('.');
86
- const rootOptionKey = pathOptionKey.shift();
87
- let valuePromise = request.internal[rootOptionKey];
88
-
89
- if (typeof ((_valuePromise = valuePromise) === null || _valuePromise === void 0 ? void 0 : _valuePromise.then) !== 'function') {
90
- valuePromise = Promise.resolve(valuePromise);
91
- }
92
-
93
- promises.push(valuePromise.then(value => pathOptionKey.reduce((p, c) => p === null || p === void 0 ? void 0 : p[c], value)));
94
- } // ensure promise has resolved by the time it's needed
95
- // If one of the promises throws it will bubble up to @middy/core
96
-
97
-
98
- values = await Promise.allSettled(promises);
99
- const errors = values.filter(res => res.status === 'rejected').map(res => res.reason.message);
100
- if (errors.length) throw new Error(JSON.stringify(errors));
101
- return keys.reduce((obj, key, index) => ({ ...obj,
102
- [sanitizeKey(key)]: values[index].value
103
- }), {});
104
- };
105
-
106
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
107
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
108
-
109
- const sanitizeKey = key => {
110
- return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
111
- }; // fetch Cache
112
-
113
-
114
- const cache = {}; // key: { value:{fetchKey:Promise}, expiry }
115
-
116
- const processCache = (options, fetch = () => undefined, request) => {
117
- const {
118
- cacheExpiry,
119
- cacheKey
120
- } = options;
121
-
122
- if (cacheExpiry) {
123
- const cached = getCache(cacheKey);
124
- const unexpired = cached && (cacheExpiry < 0 || cached.expiry > Date.now());
125
-
126
- if (unexpired && cached.modified) {
127
- const value = fetch(request, cached.value);
128
- cache[cacheKey] = {
129
- value: { ...cached.value,
130
- ...value
131
- },
132
- expiry: cached.expiry
133
- };
134
- return cache[cacheKey];
135
- }
136
-
137
- if (unexpired) {
138
- return { ...cached,
139
- cache: true
140
- };
141
- }
142
- }
143
-
144
- const value = fetch(request);
145
- const expiry = Date.now() + cacheExpiry;
146
-
147
- if (cacheExpiry) {
148
- cache[cacheKey] = {
149
- value,
150
- expiry
151
- };
152
- }
153
-
154
- return {
155
- value,
156
- expiry
157
- };
158
- };
159
-
160
- const getCache = key => {
161
- return cache[key];
162
- }; // Used to remove parts of a cache
163
-
164
-
165
- const modifyCache = (cacheKey, value) => {
166
- if (!cache[cacheKey]) return;
167
- cache[cacheKey] = { ...cache[cacheKey],
168
- value,
169
- modified: true
170
- };
171
- };
172
-
173
- const clearCache = (keys = null) => {
174
- var _keys;
175
-
176
- keys = (_keys = keys) !== null && _keys !== void 0 ? _keys : Object.keys(cache);
177
- if (!Array.isArray(keys)) keys = [keys];
178
-
179
- for (const cacheKey of keys) {
180
- cache[cacheKey] = undefined;
181
- }
182
- };
183
-
184
- const jsonSafeParse = (string, reviver) => {
185
- if (typeof string !== 'string') return string;
186
- const firstChar = string[0];
187
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return string;
188
-
189
- try {
190
- return JSON.parse(string, reviver);
191
- } catch (e) {}
192
-
193
- return string;
194
- };
195
-
196
- const normalizeHttpResponse = response => {
197
- var _response$headers, _response;
198
-
199
- // May require updating to catch other types
200
- if (response === undefined) {
201
- response = {};
202
- } else if (Array.isArray(response) || typeof response !== 'object' || response === null) {
203
- response = {
204
- body: response
205
- };
206
- }
207
-
208
- response.headers = (_response$headers = (_response = response) === null || _response === void 0 ? void 0 : _response.headers) !== null && _response$headers !== void 0 ? _response$headers : {};
209
- return response;
210
- }; // smaller version of `http-errors`
211
-
212
-
213
- const statuses = require('./codes.json');
214
-
215
- const {
216
- inherits
217
- } = require('util');
218
-
219
- const createErrorRegexp = /[^a-zA-Z]/g;
220
-
221
- const createError = (code, message, properties = {}) => {
222
- const name = statuses[code].replace(createErrorRegexp, '');
223
- const className = name.substr(-5) !== 'Error' ? name + 'Error' : name;
224
-
225
- function HttpError(message) {
226
- // create the error object
227
- const msg = message !== null && message !== void 0 ? message : statuses[code];
228
- const err = new Error(msg); // capture a stack trace to the construction point
229
-
230
- Error.captureStackTrace(err, HttpError); // adjust the [[Prototype]]
231
-
232
- Object.setPrototypeOf(err, HttpError.prototype); // redefine the error message
233
-
234
- Object.defineProperty(err, 'message', {
235
- enumerable: true,
236
- configurable: true,
237
- value: msg,
238
- writable: true
239
- }); // redefine the error name
240
-
241
- Object.defineProperty(err, 'name', {
242
- enumerable: false,
243
- configurable: true,
244
- value: className,
245
- writable: true
246
- });
247
- return err;
248
- }
249
-
250
- inherits(HttpError, Error);
251
- const desc = Object.getOwnPropertyDescriptor(HttpError, 'name');
252
- desc.value = className;
253
- Object.defineProperty(HttpError, 'name', desc);
254
- Object.assign(HttpError.prototype, {
255
- status: code,
256
- statusCode: code,
257
- expose: code < 500
258
- }, properties);
259
- return new HttpError(message);
260
- };
261
-
262
- module.exports = {
263
- createPrefetchClient,
264
- createClient,
265
- canPrefetch,
266
- getInternal,
267
- sanitizeKey,
268
- processCache,
269
- getCache,
270
- modifyCache,
271
- clearCache,
272
- jsonSafeParse,
273
- normalizeHttpResponse,
274
- createError
275
- };