@middy/util 5.0.0-alpha.1 → 5.0.0-alpha.2

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 (2) hide show
  1. package/index.js +262 -272
  2. package/package.json +2 -2
package/index.js CHANGED
@@ -1,284 +1,274 @@
1
- export const createPrefetchClient = (options) => {
2
- const { awsClientOptions } = options
3
- const client = new options.AwsClient(awsClientOptions)
4
-
5
- // AWS XRay
6
- if (options.awsClientCapture && options.disablePrefetch) {
7
- return options.awsClientCapture(client)
8
- } else if (options.awsClientCapture) {
9
- console.warn('Unable to apply X-Ray outside of handler invocation scope.')
10
- }
11
-
12
- return client
13
- }
14
-
15
- export const createClient = async (options, request) => {
16
- let awsClientCredentials = {}
17
-
18
- // Role Credentials
19
- if (options.awsClientAssumeRole) {
20
- if (!request) {
21
- throw new Error('Request required when assuming role', {
22
- cause: { package: '@middy/util' }
23
- })
1
+ export const createPrefetchClient = (options)=>{
2
+ const { awsClientOptions } = options;
3
+ const client = new options.AwsClient(awsClientOptions);
4
+ // AWS XRay
5
+ if (options.awsClientCapture && options.disablePrefetch) {
6
+ return options.awsClientCapture(client);
7
+ } else if (options.awsClientCapture) {
8
+ console.warn('Unable to apply X-Ray outside of handler invocation scope.');
24
9
  }
25
- awsClientCredentials = await getInternal(
26
- { credentials: options.awsClientAssumeRole },
27
- request
28
- )
29
- }
30
-
31
- awsClientCredentials = {
32
- ...awsClientCredentials,
33
- ...options.awsClientOptions
34
- }
35
-
36
- return createPrefetchClient({
37
- ...options,
38
- awsClientOptions: awsClientCredentials
39
- })
40
- }
41
-
42
- export const canPrefetch = (options = {}) => {
43
- return !options.awsClientAssumeRole && !options.disablePrefetch
44
- }
45
-
10
+ return client;
11
+ };
12
+ export const createClient = async (options, request)=>{
13
+ let awsClientCredentials = {};
14
+ // Role Credentials
15
+ if (options.awsClientAssumeRole) {
16
+ if (!request) {
17
+ throw new Error('Request required when assuming role', {
18
+ cause: {
19
+ package: '@middy/util'
20
+ }
21
+ });
22
+ }
23
+ awsClientCredentials = await getInternal({
24
+ credentials: options.awsClientAssumeRole
25
+ }, request);
26
+ }
27
+ awsClientCredentials = {
28
+ ...awsClientCredentials,
29
+ ...options.awsClientOptions
30
+ };
31
+ return createPrefetchClient({
32
+ ...options,
33
+ awsClientOptions: awsClientCredentials
34
+ });
35
+ };
36
+ export const canPrefetch = (options = {})=>{
37
+ return !options.awsClientAssumeRole && !options.disablePrefetch;
38
+ };
46
39
  // Internal Context
47
- export const getInternal = async (variables, request) => {
48
- if (!variables || !request) return {}
49
- let keys = []
50
- let values = []
51
- if (variables === true) {
52
- keys = values = Object.keys(request.internal)
53
- } else if (typeof variables === 'string') {
54
- keys = values = [variables]
55
- } else if (Array.isArray(variables)) {
56
- keys = values = variables
57
- } else if (typeof variables === 'object') {
58
- keys = Object.keys(variables)
59
- values = Object.values(variables)
60
- }
61
- const promises = []
62
- for (const internalKey of values) {
63
- // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
64
- const pathOptionKey = internalKey.split('.')
65
- const rootOptionKey = pathOptionKey.shift()
66
- let valuePromise = request.internal[rootOptionKey]
67
- if (!isPromise(valuePromise)) {
68
- valuePromise = Promise.resolve(valuePromise)
40
+ export const getInternal = async (variables, request)=>{
41
+ if (!variables || !request) return {};
42
+ let keys = [];
43
+ let values = [];
44
+ if (variables === true) {
45
+ keys = values = Object.keys(request.internal);
46
+ } else if (typeof variables === 'string') {
47
+ keys = values = [
48
+ variables
49
+ ];
50
+ } else if (Array.isArray(variables)) {
51
+ keys = values = variables;
52
+ } else if (typeof variables === 'object') {
53
+ keys = Object.keys(variables);
54
+ values = Object.values(variables);
69
55
  }
70
- promises.push(
71
- valuePromise.then((value) =>
72
- pathOptionKey.reduce((p, c) => p?.[c], value)
73
- )
74
- )
75
- }
76
- // ensure promise has resolved by the time it's needed
77
- // If one of the promises throws it will bubble up to @middy/core
78
- values = await Promise.allSettled(promises)
79
- const errors = values
80
- .filter((res) => res.status === 'rejected')
81
- .map((res) => res.reason)
82
- if (errors.length) {
83
- throw new Error('Failed to resolve internal values', {
84
- cause: { package: '@middy/util', data: errors }
85
- })
86
- }
87
- return keys.reduce(
88
- (obj, key, index) => ({ ...obj, [sanitizeKey(key)]: values[index].value }),
89
- {}
90
- )
91
- }
92
-
93
- const isPromise = (promise) => typeof promise?.then === 'function'
94
-
95
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/
96
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g
97
- export const sanitizeKey = (key) => {
98
- return key
99
- .replace(sanitizeKeyPrefixLeadingNumber, '_$1')
100
- .replace(sanitizeKeyRemoveDisallowedChar, '_')
101
- }
102
-
56
+ const promises = [];
57
+ for (const internalKey of values){
58
+ // 'internal.key.sub_value' -> { [key]: internal.key.sub_value }
59
+ const pathOptionKey = internalKey.split('.');
60
+ const rootOptionKey = pathOptionKey.shift();
61
+ let valuePromise = request.internal[rootOptionKey];
62
+ if (!isPromise(valuePromise)) {
63
+ valuePromise = Promise.resolve(valuePromise);
64
+ }
65
+ promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
66
+ }
67
+ // ensure promise has resolved by the time it's needed
68
+ // If one of the promises throws it will bubble up to @middy/core
69
+ values = await Promise.allSettled(promises);
70
+ const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
71
+ if (errors.length) {
72
+ throw new Error('Failed to resolve internal values', {
73
+ cause: {
74
+ package: '@middy/util',
75
+ data: errors
76
+ }
77
+ });
78
+ }
79
+ return keys.reduce((obj, key, index)=>({
80
+ ...obj,
81
+ [sanitizeKey(key)]: values[index].value
82
+ }), {});
83
+ };
84
+ const isPromise = (promise)=>typeof promise?.then === 'function';
85
+ const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
86
+ const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
87
+ export const sanitizeKey = (key)=>{
88
+ return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
89
+ };
103
90
  // fetch Cache
104
91
  const cache = {} // key: { value:{fetchKey:Promise}, expiry }
105
- export const processCache = (options, fetch = () => undefined, request) => {
106
- let { cacheKey, cacheKeyExpiry, cacheExpiry } = options
107
- cacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry
108
- if (cacheExpiry) {
109
- const cached = getCache(cacheKey)
110
- const unexpired =
111
- cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now())
112
-
113
- if (unexpired && cached.modified) {
114
- const value = fetch(request, cached.value)
115
- cache[cacheKey] = Object.create({
116
- value: { ...cached.value, ...value },
117
- expiry: cached.expiry
118
- })
119
- return cache[cacheKey]
92
+ ;
93
+ export const processCache = (options, fetch = ()=>undefined, request)=>{
94
+ let { cacheKey, cacheKeyExpiry, cacheExpiry } = options;
95
+ cacheExpiry = cacheKeyExpiry?.[cacheKey] ?? cacheExpiry;
96
+ if (cacheExpiry) {
97
+ const cached = getCache(cacheKey);
98
+ const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
99
+ if (unexpired && cached.modified) {
100
+ const value = fetch(request, cached.value);
101
+ cache[cacheKey] = Object.create({
102
+ value: {
103
+ ...cached.value,
104
+ ...value
105
+ },
106
+ expiry: cached.expiry
107
+ });
108
+ return cache[cacheKey];
109
+ }
110
+ if (unexpired) {
111
+ return {
112
+ ...cached,
113
+ cache: true
114
+ };
115
+ }
120
116
  }
121
- if (unexpired) {
122
- return { ...cached, cache: true }
117
+ const value = fetch(request);
118
+ const now = Date.now();
119
+ // secrets-manager overrides to unix timestamp
120
+ const expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry;
121
+ const duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry;
122
+ if (cacheExpiry) {
123
+ const refresh = duration > 0 ? setInterval(()=>processCache(options, fetch, request), duration) : undefined;
124
+ cache[cacheKey] = {
125
+ value,
126
+ expiry,
127
+ refresh
128
+ };
123
129
  }
124
- }
125
- const value = fetch(request)
126
- const now = Date.now()
127
- // secrets-manager overrides to unix timestamp
128
- const expiry = cacheExpiry > 86400000 ? cacheExpiry : now + cacheExpiry
129
- const duration = cacheExpiry > 86400000 ? cacheExpiry - now : cacheExpiry
130
- if (cacheExpiry) {
131
- const refresh =
132
- duration > 0
133
- ? setInterval(() => processCache(options, fetch, request), duration)
134
- : undefined
135
- cache[cacheKey] = { value, expiry, refresh }
136
- }
137
- return { value, expiry }
138
- }
139
-
140
- export const getCache = (key) => {
141
- if (!cache[key]) return {}
142
- return cache[key]
143
- }
144
-
130
+ return {
131
+ value,
132
+ expiry
133
+ };
134
+ };
135
+ export const getCache = (key)=>{
136
+ if (!cache[key]) return {};
137
+ return cache[key];
138
+ };
145
139
  // Used to remove parts of a cache
146
- export const modifyCache = (cacheKey, value) => {
147
- if (!cache[cacheKey]) return
148
- clearInterval(cache[cacheKey]?.refresh)
149
- cache[cacheKey] = { ...cache[cacheKey], value, modified: true }
150
- }
151
-
152
- export const clearCache = (keys = null) => {
153
- keys = keys ?? Object.keys(cache)
154
- if (!Array.isArray(keys)) keys = [keys]
155
- for (const cacheKey of keys) {
156
- clearInterval(cache[cacheKey]?.refresh)
157
- cache[cacheKey] = undefined
158
- }
159
- }
160
-
161
- export const jsonSafeParse = (text, reviver) => {
162
- if (typeof text !== 'string') return text
163
- const firstChar = text[0]
164
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text
165
- try {
166
- return JSON.parse(text, reviver)
167
- } catch (e) {}
168
-
169
- return text
170
- }
171
-
172
- export const jsonSafeStringify = (value, replacer, space) => {
173
- try {
174
- return JSON.stringify(value, replacer, space)
175
- } catch (e) {}
176
-
177
- return value
178
- }
179
-
180
- export const normalizeHttpResponse = (request) => {
181
- let { response } = request
182
- if (typeof response === 'undefined') {
183
- response = {}
184
- } else if (
185
- typeof response?.statusCode === 'undefined' &&
186
- typeof response?.body === 'undefined' &&
187
- typeof response?.headers === 'undefined'
188
- ) {
189
- response = { statusCode: 200, body: response }
190
- }
191
- response.statusCode ??= 500
192
- response.headers ??= {}
193
- request.response = response
194
- return response
195
- }
196
-
197
- const createErrorRegexp = /[^a-zA-Z]/g
140
+ export const modifyCache = (cacheKey, value)=>{
141
+ if (!cache[cacheKey]) return;
142
+ clearInterval(cache[cacheKey]?.refresh);
143
+ cache[cacheKey] = {
144
+ ...cache[cacheKey],
145
+ value,
146
+ modified: true
147
+ };
148
+ };
149
+ export const clearCache = (keys = null)=>{
150
+ keys = keys ?? Object.keys(cache);
151
+ if (!Array.isArray(keys)) keys = [
152
+ keys
153
+ ];
154
+ for (const cacheKey of keys){
155
+ clearInterval(cache[cacheKey]?.refresh);
156
+ cache[cacheKey] = undefined;
157
+ }
158
+ };
159
+ export const jsonSafeParse = (text, reviver)=>{
160
+ if (typeof text !== 'string') return text;
161
+ const firstChar = text[0];
162
+ if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
163
+ try {
164
+ return JSON.parse(text, reviver);
165
+ } catch (e) {}
166
+ return text;
167
+ };
168
+ export const jsonSafeStringify = (value, replacer, space)=>{
169
+ try {
170
+ return JSON.stringify(value, replacer, space);
171
+ } catch (e) {}
172
+ return value;
173
+ };
174
+ export const normalizeHttpResponse = (request)=>{
175
+ let { response } = request;
176
+ if (typeof response === 'undefined') {
177
+ response = {};
178
+ } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
179
+ response = {
180
+ statusCode: 200,
181
+ body: response
182
+ };
183
+ }
184
+ response.statusCode ??= 500;
185
+ response.headers ??= {};
186
+ request.response = response;
187
+ return response;
188
+ };
189
+ const createErrorRegexp = /[^a-zA-Z]/g;
198
190
  export class HttpError extends Error {
199
- constructor (code, message, options = {}) {
200
- if (message && typeof message !== 'string') {
201
- options = message
202
- message = undefined
191
+ constructor(code, message, options = {}){
192
+ if (message && typeof message !== 'string') {
193
+ options = message;
194
+ message = undefined;
195
+ }
196
+ message ??= httpErrorCodes[code];
197
+ super(message, options);
198
+ const name = httpErrorCodes[code].replace(createErrorRegexp, '');
199
+ this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
200
+ this.status = this.statusCode = code // setting `status` for backwards compatibility w/ `http-errors`
201
+ ;
202
+ this.expose = options.expose ?? code < 500;
203
203
  }
204
- message ??= httpErrorCodes[code]
205
- super(message, options)
206
-
207
- const name = httpErrorCodes[code].replace(createErrorRegexp, '')
208
- this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name
209
-
210
- this.status = this.statusCode = code // setting `status` for backwards compatibility w/ `http-errors`
211
- this.expose = options.expose ?? code < 500
212
- }
213
204
  }
214
-
215
- export const createError = (code, message, properties = {}) => {
216
- return new HttpError(code, message, properties)
217
- }
218
-
205
+ export const createError = (code, message, properties = {})=>{
206
+ return new HttpError(code, message, properties);
207
+ };
219
208
  const httpErrorCodes = {
220
- 100: 'Continue',
221
- 101: 'Switching Protocols',
222
- 102: 'Processing',
223
- 103: 'Early Hints',
224
- 200: 'OK',
225
- 201: 'Created',
226
- 202: 'Accepted',
227
- 203: 'Non-Authoritative Information',
228
- 204: 'No Content',
229
- 205: 'Reset Content',
230
- 206: 'Partial Content',
231
- 207: 'Multi-Status',
232
- 208: 'Already Reported',
233
- 226: 'IM Used',
234
- 300: 'Multiple Choices',
235
- 301: 'Moved Permanently',
236
- 302: 'Found',
237
- 303: 'See Other',
238
- 304: 'Not Modified',
239
- 305: 'Use Proxy',
240
- 306: '(Unused)',
241
- 307: 'Temporary Redirect',
242
- 308: 'Permanent Redirect',
243
- 400: 'Bad Request',
244
- 401: 'Unauthorized',
245
- 402: 'Payment Required',
246
- 403: 'Forbidden',
247
- 404: 'Not Found',
248
- 405: 'Method Not Allowed',
249
- 406: 'Not Acceptable',
250
- 407: 'Proxy Authentication Required',
251
- 408: 'Request Timeout',
252
- 409: 'Conflict',
253
- 410: 'Gone',
254
- 411: 'Length Required',
255
- 412: 'Precondition Failed',
256
- 413: 'Payload Too Large',
257
- 414: 'URI Too Long',
258
- 415: 'Unsupported Media Type',
259
- 416: 'Range Not Satisfiable',
260
- 417: 'Expectation Failed',
261
- 418: "I'm a teapot",
262
- 421: 'Misdirected Request',
263
- 422: 'Unprocessable Entity',
264
- 423: 'Locked',
265
- 424: 'Failed Dependency',
266
- 425: 'Unordered Collection',
267
- 426: 'Upgrade Required',
268
- 428: 'Precondition Required',
269
- 429: 'Too Many Requests',
270
- 431: 'Request Header Fields Too Large',
271
- 451: 'Unavailable For Legal Reasons',
272
- 500: 'Internal Server Error',
273
- 501: 'Not Implemented',
274
- 502: 'Bad Gateway',
275
- 503: 'Service Unavailable',
276
- 504: 'Gateway Timeout',
277
- 505: 'HTTP Version Not Supported',
278
- 506: 'Variant Also Negotiates',
279
- 507: 'Insufficient Storage',
280
- 508: 'Loop Detected',
281
- 509: 'Bandwidth Limit Exceeded',
282
- 510: 'Not Extended',
283
- 511: 'Network Authentication Required'
284
- }
209
+ 100: 'Continue',
210
+ 101: 'Switching Protocols',
211
+ 102: 'Processing',
212
+ 103: 'Early Hints',
213
+ 200: 'OK',
214
+ 201: 'Created',
215
+ 202: 'Accepted',
216
+ 203: 'Non-Authoritative Information',
217
+ 204: 'No Content',
218
+ 205: 'Reset Content',
219
+ 206: 'Partial Content',
220
+ 207: 'Multi-Status',
221
+ 208: 'Already Reported',
222
+ 226: 'IM Used',
223
+ 300: 'Multiple Choices',
224
+ 301: 'Moved Permanently',
225
+ 302: 'Found',
226
+ 303: 'See Other',
227
+ 304: 'Not Modified',
228
+ 305: 'Use Proxy',
229
+ 306: '(Unused)',
230
+ 307: 'Temporary Redirect',
231
+ 308: 'Permanent Redirect',
232
+ 400: 'Bad Request',
233
+ 401: 'Unauthorized',
234
+ 402: 'Payment Required',
235
+ 403: 'Forbidden',
236
+ 404: 'Not Found',
237
+ 405: 'Method Not Allowed',
238
+ 406: 'Not Acceptable',
239
+ 407: 'Proxy Authentication Required',
240
+ 408: 'Request Timeout',
241
+ 409: 'Conflict',
242
+ 410: 'Gone',
243
+ 411: 'Length Required',
244
+ 412: 'Precondition Failed',
245
+ 413: 'Payload Too Large',
246
+ 414: 'URI Too Long',
247
+ 415: 'Unsupported Media Type',
248
+ 416: 'Range Not Satisfiable',
249
+ 417: 'Expectation Failed',
250
+ 418: "I'm a teapot",
251
+ 421: 'Misdirected Request',
252
+ 422: 'Unprocessable Entity',
253
+ 423: 'Locked',
254
+ 424: 'Failed Dependency',
255
+ 425: 'Unordered Collection',
256
+ 426: 'Upgrade Required',
257
+ 428: 'Precondition Required',
258
+ 429: 'Too Many Requests',
259
+ 431: 'Request Header Fields Too Large',
260
+ 451: 'Unavailable For Legal Reasons',
261
+ 500: 'Internal Server Error',
262
+ 501: 'Not Implemented',
263
+ 502: 'Bad Gateway',
264
+ 503: 'Service Unavailable',
265
+ 504: 'Gateway Timeout',
266
+ 505: 'HTTP Version Not Supported',
267
+ 506: 'Variant Also Negotiates',
268
+ 507: 'Insufficient Storage',
269
+ 508: 'Loop Detected',
270
+ 509: 'Bandwidth Limit Exceeded',
271
+ 510: 'Not Extended',
272
+ 511: 'Network Authentication Required'
273
+ };
274
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "5.0.0-alpha.1",
3
+ "version": "5.0.0-alpha.2",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
5
  "type": "module",
6
6
  "engines": {
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@aws-sdk/client-ssm": "^3.0.0",
58
- "@middy/core": "5.0.0-alpha.1",
58
+ "@middy/core": "5.0.0-alpha.2",
59
59
  "@types/aws-lambda": "^8.10.76",
60
60
  "@types/node": "^20.0.0",
61
61
  "aws-xray-sdk": "^3.3.3"