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

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 (5) hide show
  1. package/README.md +3 -2
  2. package/index.d.ts +74 -7
  3. package/index.js +276 -245
  4. package/package.json +4 -10
  5. package/index.cjs +0 -279
package/README.md CHANGED
@@ -19,8 +19,9 @@
19
19
  <a href="https://snyk.io/test/github/middyjs/middy">
20
20
  <img src="https://snyk.io/test/github/middyjs/middy/badge.svg" alt="Known Vulnerabilities" data-canonical-src="https://snyk.io/test/github/middyjs/middy" style="max-width:100%;">
21
21
  </a>
22
- <a href="https://lgtm.com/projects/g/middyjs/middy/context:javascript">
23
- <img src="https://img.shields.io/lgtm/grade/javascript/g/middyjs/middy.svg?logo=lgtm&logoWidth=18" alt="Language grade: JavaScript" style="max-width:100%;">
22
+ <a href="https://github.com/middyjs/middy/actions/workflows/sast.yml">
23
+ <img src="https://github.com/middyjs/middy/actions/workflows/sast.yml/badge.svg
24
+ ?branch=main&event=push" alt="CodeQL" style="max-width:100%;">
24
25
  </a>
25
26
  <a href="https://bestpractices.coreinfrastructure.org/projects/5280">
26
27
  <img src="https://bestpractices.coreinfrastructure.org/projects/5280/badge" alt="Core Infrastructure Initiative (CII) Best Practices" style="max-width:100%;">
package/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import middy from '@middy/core'
2
+ import { Context as LambdaContext } from 'aws-lambda'
3
+ import { ArrayValues, Choose, DeepAwaited, IsUnknown, SanitizeKey, SanitizeKeys } from './type-utils'
2
4
 
3
5
  interface Options<Client, ClientOptions> {
4
- AwsClient?: new (...args: any[]) => Client
6
+ AwsClient?: new (...[config]: [any] | any) => Client
5
7
  awsClientOptions?: Partial<ClientOptions>
6
8
  awsClientAssumeRole?: string
7
9
  awsClientCapture?: (service: Client) => Client
@@ -12,7 +14,7 @@ interface Options<Client, ClientOptions> {
12
14
  setToContext?: boolean
13
15
  }
14
16
 
15
- type HttpError = Error & {
17
+ declare class HttpError extends Error {
16
18
  status: number
17
19
  statusCode: number
18
20
  expose: boolean
@@ -33,12 +35,77 @@ declare function canPrefetch<Client, ClientOptions> (
33
35
  options: Options<Client, ClientOptions>
34
36
  ): boolean
35
37
 
36
- declare function getInternal (
37
- variables: any,
38
- request: middy.Request
39
- ): Promise<any>
38
+ type InternalOutput<TVariables> = TVariables extends string[] ? { [key in TVariables[number]]: unknown } : never
39
+
40
+ // get an empty object if false is passed
41
+ declare function getInternal<
42
+ TContext extends LambdaContext,
43
+ TInternal extends Record<string, unknown>
44
+ > (
45
+ variables: false,
46
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
47
+ ): Promise<{}>
48
+
49
+ // get all internal values if true is passed (with promises resolved)
50
+ declare function getInternal<
51
+ TContext extends LambdaContext,
52
+ TInternal extends Record<string, unknown>
53
+ > (
54
+ variables: true,
55
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
56
+ ): Promise<DeepAwaited<TInternal>>
57
+
58
+ // get a single value
59
+ declare function getInternal<
60
+ TContext extends LambdaContext,
61
+ TInternal extends Record<string, unknown>,
62
+ TVars extends keyof TInternal | string
63
+ > (
64
+ variables: TVars,
65
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
66
+ ): TVars extends keyof TInternal
67
+ ? Promise<DeepAwaited<{ [_ in SanitizeKey<TVars>]: TInternal[TVars] }>>
68
+ : TVars extends string
69
+ ? IsUnknown<Choose<DeepAwaited<TInternal>, TVars>> extends true
70
+ ? unknown // could not find the path
71
+ : Promise<{ [_ in SanitizeKey<TVars>]: Choose<DeepAwaited<TInternal>, TVars> }>
72
+ : unknown // path is not a string or a keyof TInternal
73
+
74
+ // get multiple values
75
+ declare function getInternal<
76
+ TContext extends LambdaContext,
77
+ TInternal extends Record<string, unknown>,
78
+ TVars extends Array<keyof TInternal | string>
79
+ > (
80
+ variables: TVars,
81
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
82
+ ): Promise<SanitizeKeys<{
83
+ [TVar in ArrayValues<TVars>]:
84
+ TVar extends keyof TInternal
85
+ ? DeepAwaited<TInternal[TVar]>
86
+ : TVar extends string
87
+ ? Choose<DeepAwaited<TInternal>, TVar>
88
+ : unknown // path is not a string or a keyof TInternal
89
+ }>>
90
+
91
+ // remap object
92
+ declare function getInternal<
93
+ TContext extends LambdaContext,
94
+ TInternal extends Record<string, unknown>,
95
+ TMap extends Record<string, keyof TInternal | string>
96
+ > (
97
+ variables: TMap,
98
+ request: middy.Request<unknown, unknown, unknown, TContext, TInternal>
99
+ ): Promise<{
100
+ [P in keyof TMap]:
101
+ TMap[P] extends keyof TInternal
102
+ ? DeepAwaited<TInternal[TMap[P]]>
103
+ : TMap[P] extends string
104
+ ? Choose<DeepAwaited<TInternal>, TMap[P]>
105
+ : unknown // path is not a string or a keyof TInternal
106
+ }>
40
107
 
41
- declare function sanitizeKey (key: string): string
108
+ declare function sanitizeKey<T extends string> (key: T): SanitizeKey<T>
42
109
 
43
110
  declare function processCache<Client, ClientOptions> (
44
111
  options: Options<Client, ClientOptions>,
package/index.js CHANGED
@@ -1,253 +1,284 @@
1
- export const createPrefetchClient = (options)=>{
2
- const { awsClientOptions } = options;
3
- const client = new options.AwsClient(awsClientOptions);
4
- if (options.awsClientCapture && options.disablePrefetch) {
5
- return options.awsClientCapture(client);
6
- } else if (options.awsClientCapture) {
7
- console.warn('Unable to apply X-Ray outside of handler invocation scope.');
8
- }
9
- return client;
10
- };
11
- export const createClient = async (options, request)=>{
12
- let awsClientCredentials = {};
13
- if (options.awsClientAssumeRole) {
14
- if (!request) {
15
- throw new Error('Request required when assuming role');
16
- }
17
- awsClientCredentials = await getInternal({
18
- credentials: options.awsClientAssumeRole
19
- }, request);
20
- }
21
- awsClientCredentials = {
22
- ...awsClientCredentials,
23
- ...options.awsClientOptions
24
- };
25
- return createPrefetchClient({
26
- ...options,
27
- awsClientOptions: awsClientCredentials
28
- });
29
- };
30
- export const canPrefetch = (options = {})=>{
31
- return !options.awsClientAssumeRole && !options.disablePrefetch;
32
- };
33
- export const getInternal = async (variables, request)=>{
34
- if (!variables || !request) return {};
35
- let keys = [];
36
- let values = [];
37
- if (variables === true) {
38
- keys = values = Object.keys(request.internal);
39
- } else if (typeof variables === 'string') {
40
- keys = values = [
41
- variables
42
- ];
43
- } else if (Array.isArray(variables)) {
44
- keys = values = variables;
45
- } else if (typeof variables === 'object') {
46
- keys = Object.keys(variables);
47
- values = Object.values(variables);
48
- }
49
- const promises = [];
50
- for (const internalKey of values){
51
- const pathOptionKey = internalKey.split('.');
52
- const rootOptionKey = pathOptionKey.shift();
53
- let valuePromise = request.internal[rootOptionKey];
54
- if (!isPromise(valuePromise)) {
55
- valuePromise = Promise.resolve(valuePromise);
56
- }
57
- promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
58
- }
59
- values = await Promise.allSettled(promises);
60
- const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
61
- if (errors.length) {
62
- throw new Error('Failed to resolve internal values', {
63
- cause: errors
64
- });
65
- }
66
- return keys.reduce((obj, key, index)=>({
67
- ...obj,
68
- [sanitizeKey(key)]: values[index].value
69
- }), {});
70
- };
71
- const isPromise = (promise)=>typeof promise?.then === 'function';
72
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
73
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
74
- export const sanitizeKey = (key)=>{
75
- return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
76
- };
77
- const cache = {};
78
- export const processCache = (options, fetch = ()=>undefined, request)=>{
79
- const { cacheExpiry , cacheKey } = options;
80
- if (cacheExpiry) {
81
- const cached = getCache(cacheKey);
82
- const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
83
- if (unexpired && cached.modified) {
84
- const value = fetch(request, cached.value);
85
- cache[cacheKey] = Object.create({
86
- value: {
87
- ...cached.value,
88
- ...value
89
- },
90
- expiry: cached.expiry
91
- });
92
- return cache[cacheKey];
93
- }
94
- if (unexpired) {
95
- return {
96
- ...cached,
97
- cache: true
98
- };
99
- }
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
+ })
100
24
  }
101
- const value = fetch(request);
102
- const expiry = Date.now() + cacheExpiry;
103
- if (cacheExpiry) {
104
- const refresh = cacheExpiry > 0 ? setInterval(()=>processCache(options, fetch, request), cacheExpiry) : undefined;
105
- cache[cacheKey] = {
106
- value,
107
- expiry,
108
- refresh
109
- };
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
+
46
+ // 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)
110
69
  }
111
- return {
112
- value,
113
- expiry
114
- };
115
- };
116
- export const getCache = (key)=>{
117
- if (!cache[key]) return {};
118
- return cache[key];
119
- };
120
- export const modifyCache = (cacheKey, value)=>{
121
- if (!cache[cacheKey]) return;
122
- clearInterval(cache[cacheKey]?.refresh);
123
- cache[cacheKey] = {
124
- ...cache[cacheKey],
125
- value,
126
- modified: true
127
- };
128
- };
129
- export const clearCache = (keys = null)=>{
130
- keys = keys ?? Object.keys(cache);
131
- if (!Array.isArray(keys)) keys = [
132
- keys
133
- ];
134
- for (const cacheKey of keys){
135
- clearInterval(cache[cacheKey]?.refresh);
136
- cache[cacheKey] = undefined;
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
+
103
+ // fetch Cache
104
+ 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]
137
120
  }
138
- };
139
- export const jsonSafeParse = (text, reviver)=>{
140
- if (typeof text !== 'string') return text;
141
- const firstChar = text[0];
142
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
143
- try {
144
- return JSON.parse(text, reviver);
145
- } catch (e) {}
146
- return text;
147
- };
148
- export const jsonSafeStringify = (value, replacer, space)=>{
149
- try {
150
- return JSON.stringify(value, replacer, space);
151
- } catch (e) {}
152
- return value;
153
- };
154
- export const normalizeHttpResponse = (request)=>{
155
- let { response } = request;
156
- if (typeof response === 'undefined') {
157
- response = {};
158
- } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
159
- response = {
160
- statusCode: 200,
161
- body: response
162
- };
121
+ if (unexpired) {
122
+ return { ...cached, cache: true }
163
123
  }
164
- response.statusCode ??= 500;
165
- response.headers ??= {};
166
- request.response = response;
167
- return response;
168
- };
169
- const createErrorRegexp = /[^a-zA-Z]/g;
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
+
145
+ // 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
170
198
  export class HttpError extends Error {
171
- constructor(code, message, options = {}){
172
- if (message && typeof message !== 'string') {
173
- options = message;
174
- message = undefined;
175
- }
176
- message ??= httpErrorCodes[code];
177
- super(message, options);
178
- const name = httpErrorCodes[code].replace(createErrorRegexp, '');
179
- this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
180
- this.status = this.statusCode = code;
181
- this.expose = options.expose ?? code < 500;
199
+ constructor (code, message, options = {}) {
200
+ if (message && typeof message !== 'string') {
201
+ options = message
202
+ message = undefined
182
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
+ }
214
+
215
+ export const createError = (code, message, properties = {}) => {
216
+ return new HttpError(code, message, properties)
183
217
  }
184
- export const createError = (code, message, properties = {})=>{
185
- return new HttpError(code, message, properties);
186
- };
187
- const httpErrorCodes = {
188
- 100: 'Continue',
189
- 101: 'Switching Protocols',
190
- 102: 'Processing',
191
- 103: 'Early Hints',
192
- 200: 'OK',
193
- 201: 'Created',
194
- 202: 'Accepted',
195
- 203: 'Non-Authoritative Information',
196
- 204: 'No Content',
197
- 205: 'Reset Content',
198
- 206: 'Partial Content',
199
- 207: 'Multi-Status',
200
- 208: 'Already Reported',
201
- 226: 'IM Used',
202
- 300: 'Multiple Choices',
203
- 301: 'Moved Permanently',
204
- 302: 'Found',
205
- 303: 'See Other',
206
- 304: 'Not Modified',
207
- 305: 'Use Proxy',
208
- 306: '(Unused)',
209
- 307: 'Temporary Redirect',
210
- 308: 'Permanent Redirect',
211
- 400: 'Bad Request',
212
- 401: 'Unauthorized',
213
- 402: 'Payment Required',
214
- 403: 'Forbidden',
215
- 404: 'Not Found',
216
- 405: 'Method Not Allowed',
217
- 406: 'Not Acceptable',
218
- 407: 'Proxy Authentication Required',
219
- 408: 'Request Timeout',
220
- 409: 'Conflict',
221
- 410: 'Gone',
222
- 411: 'Length Required',
223
- 412: 'Precondition Failed',
224
- 413: 'Payload Too Large',
225
- 414: 'URI Too Long',
226
- 415: 'Unsupported Media Type',
227
- 416: 'Range Not Satisfiable',
228
- 417: 'Expectation Failed',
229
- 418: "I'm a teapot",
230
- 421: 'Misdirected Request',
231
- 422: 'Unprocessable Entity',
232
- 423: 'Locked',
233
- 424: 'Failed Dependency',
234
- 425: 'Unordered Collection',
235
- 426: 'Upgrade Required',
236
- 428: 'Precondition Required',
237
- 429: 'Too Many Requests',
238
- 431: 'Request Header Fields Too Large',
239
- 451: 'Unavailable For Legal Reasons',
240
- 500: 'Internal Server Error',
241
- 501: 'Not Implemented',
242
- 502: 'Bad Gateway',
243
- 503: 'Service Unavailable',
244
- 504: 'Gateway Timeout',
245
- 505: 'HTTP Version Not Supported',
246
- 506: 'Variant Also Negotiates',
247
- 507: 'Insufficient Storage',
248
- 508: 'Loop Detected',
249
- 509: 'Bandwidth Limit Exceeded',
250
- 510: 'Not Extended',
251
- 511: 'Network Authentication Required'
252
- };
253
218
 
219
+ 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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "5.0.0-alpha.0",
3
+ "version": "5.0.0-alpha.1",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
5
  "type": "module",
6
6
  "engines": {
@@ -10,24 +10,18 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "main": "./index.cjs",
14
13
  "module": "./index.js",
15
14
  "exports": {
16
15
  ".": {
17
16
  "import": {
18
17
  "types": "./index.d.ts",
19
18
  "default": "./index.js"
20
- },
21
- "require": {
22
- "types": "./index.d.ts",
23
- "default": "./index.cjs"
24
19
  }
25
20
  }
26
21
  },
27
22
  "types": "index.d.ts",
28
23
  "files": [
29
24
  "index.js",
30
- "index.cjs",
31
25
  "index.d.ts",
32
26
  "codes.js"
33
27
  ],
@@ -61,9 +55,9 @@
61
55
  },
62
56
  "devDependencies": {
63
57
  "@aws-sdk/client-ssm": "^3.0.0",
64
- "@middy/core": "5.0.0-alpha.0",
58
+ "@middy/core": "5.0.0-alpha.1",
65
59
  "@types/aws-lambda": "^8.10.76",
66
- "@types/node": "^18.0.0",
60
+ "@types/node": "^20.0.0",
67
61
  "aws-xray-sdk": "^3.3.3"
68
62
  },
69
63
  "homepage": "https://middy.js.org",
@@ -71,5 +65,5 @@
71
65
  "type": "github",
72
66
  "url": "https://github.com/sponsors/willfarrell"
73
67
  },
74
- "gitHead": "08c35e3dba9efdad0b86666ce206ce302cc65d07"
68
+ "gitHead": "ebce8d5df8783077fa49ba62ee9be20e8486a7f1"
75
69
  }
package/index.cjs DELETED
@@ -1,279 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- createPrefetchClient: ()=>createPrefetchClient,
13
- createClient: ()=>createClient,
14
- canPrefetch: ()=>canPrefetch,
15
- getInternal: ()=>getInternal,
16
- sanitizeKey: ()=>sanitizeKey,
17
- processCache: ()=>processCache,
18
- getCache: ()=>getCache,
19
- modifyCache: ()=>modifyCache,
20
- clearCache: ()=>clearCache,
21
- jsonSafeParse: ()=>jsonSafeParse,
22
- jsonSafeStringify: ()=>jsonSafeStringify,
23
- normalizeHttpResponse: ()=>normalizeHttpResponse,
24
- HttpError: ()=>HttpError,
25
- createError: ()=>createError
26
- });
27
- const createPrefetchClient = (options)=>{
28
- const { awsClientOptions } = options;
29
- const client = new options.AwsClient(awsClientOptions);
30
- if (options.awsClientCapture && options.disablePrefetch) {
31
- return options.awsClientCapture(client);
32
- } else if (options.awsClientCapture) {
33
- console.warn('Unable to apply X-Ray outside of handler invocation scope.');
34
- }
35
- return client;
36
- };
37
- const createClient = async (options, request)=>{
38
- let awsClientCredentials = {};
39
- if (options.awsClientAssumeRole) {
40
- if (!request) {
41
- throw new Error('Request required when assuming role');
42
- }
43
- awsClientCredentials = await getInternal({
44
- credentials: options.awsClientAssumeRole
45
- }, request);
46
- }
47
- awsClientCredentials = {
48
- ...awsClientCredentials,
49
- ...options.awsClientOptions
50
- };
51
- return createPrefetchClient({
52
- ...options,
53
- awsClientOptions: awsClientCredentials
54
- });
55
- };
56
- const canPrefetch = (options = {})=>{
57
- return !options.awsClientAssumeRole && !options.disablePrefetch;
58
- };
59
- const getInternal = async (variables, request)=>{
60
- if (!variables || !request) return {};
61
- let keys = [];
62
- let values = [];
63
- if (variables === true) {
64
- keys = values = Object.keys(request.internal);
65
- } else if (typeof variables === 'string') {
66
- keys = values = [
67
- variables
68
- ];
69
- } else if (Array.isArray(variables)) {
70
- keys = values = variables;
71
- } else if (typeof variables === 'object') {
72
- keys = Object.keys(variables);
73
- values = Object.values(variables);
74
- }
75
- const promises = [];
76
- for (const internalKey of values){
77
- const pathOptionKey = internalKey.split('.');
78
- const rootOptionKey = pathOptionKey.shift();
79
- let valuePromise = request.internal[rootOptionKey];
80
- if (!isPromise(valuePromise)) {
81
- valuePromise = Promise.resolve(valuePromise);
82
- }
83
- promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
84
- }
85
- values = await Promise.allSettled(promises);
86
- const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
87
- if (errors.length) {
88
- throw new Error('Failed to resolve internal values', {
89
- cause: errors
90
- });
91
- }
92
- return keys.reduce((obj, key, index)=>({
93
- ...obj,
94
- [sanitizeKey(key)]: values[index].value
95
- }), {});
96
- };
97
- const isPromise = (promise)=>typeof promise?.then === 'function';
98
- const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
99
- const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
100
- const sanitizeKey = (key)=>{
101
- return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
102
- };
103
- const cache = {};
104
- const processCache = (options, fetch = ()=>undefined, request)=>{
105
- const { cacheExpiry , cacheKey } = options;
106
- if (cacheExpiry) {
107
- const cached = getCache(cacheKey);
108
- const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
109
- if (unexpired && cached.modified) {
110
- const value = fetch(request, cached.value);
111
- cache[cacheKey] = Object.create({
112
- value: {
113
- ...cached.value,
114
- ...value
115
- },
116
- expiry: cached.expiry
117
- });
118
- return cache[cacheKey];
119
- }
120
- if (unexpired) {
121
- return {
122
- ...cached,
123
- cache: true
124
- };
125
- }
126
- }
127
- const value = fetch(request);
128
- const expiry = Date.now() + cacheExpiry;
129
- if (cacheExpiry) {
130
- const refresh = cacheExpiry > 0 ? setInterval(()=>processCache(options, fetch, request), cacheExpiry) : undefined;
131
- cache[cacheKey] = {
132
- value,
133
- expiry,
134
- refresh
135
- };
136
- }
137
- return {
138
- value,
139
- expiry
140
- };
141
- };
142
- const getCache = (key)=>{
143
- if (!cache[key]) return {};
144
- return cache[key];
145
- };
146
- const modifyCache = (cacheKey, value)=>{
147
- if (!cache[cacheKey]) return;
148
- clearInterval(cache[cacheKey]?.refresh);
149
- cache[cacheKey] = {
150
- ...cache[cacheKey],
151
- value,
152
- modified: true
153
- };
154
- };
155
- const clearCache = (keys = null)=>{
156
- keys = keys ?? Object.keys(cache);
157
- if (!Array.isArray(keys)) keys = [
158
- keys
159
- ];
160
- for (const cacheKey of keys){
161
- clearInterval(cache[cacheKey]?.refresh);
162
- cache[cacheKey] = undefined;
163
- }
164
- };
165
- const jsonSafeParse = (text, reviver)=>{
166
- if (typeof text !== 'string') return text;
167
- const firstChar = text[0];
168
- if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
169
- try {
170
- return JSON.parse(text, reviver);
171
- } catch (e) {}
172
- return text;
173
- };
174
- const jsonSafeStringify = (value, replacer, space)=>{
175
- try {
176
- return JSON.stringify(value, replacer, space);
177
- } catch (e) {}
178
- return value;
179
- };
180
- const normalizeHttpResponse = (request)=>{
181
- let { response } = request;
182
- if (typeof response === 'undefined') {
183
- response = {};
184
- } else if (typeof response?.statusCode === 'undefined' && typeof response?.body === 'undefined' && typeof response?.headers === 'undefined') {
185
- response = {
186
- statusCode: 200,
187
- body: response
188
- };
189
- }
190
- response.statusCode ??= 500;
191
- response.headers ??= {};
192
- request.response = response;
193
- return response;
194
- };
195
- const createErrorRegexp = /[^a-zA-Z]/g;
196
- class HttpError extends Error {
197
- constructor(code, message, options = {}){
198
- if (message && typeof message !== 'string') {
199
- options = message;
200
- message = undefined;
201
- }
202
- message ??= httpErrorCodes[code];
203
- super(message, options);
204
- const name = httpErrorCodes[code].replace(createErrorRegexp, '');
205
- this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
206
- this.status = this.statusCode = code;
207
- this.expose = options.expose ?? code < 500;
208
- }
209
- }
210
- const createError = (code, message, properties = {})=>{
211
- return new HttpError(code, message, properties);
212
- };
213
- const httpErrorCodes = {
214
- 100: 'Continue',
215
- 101: 'Switching Protocols',
216
- 102: 'Processing',
217
- 103: 'Early Hints',
218
- 200: 'OK',
219
- 201: 'Created',
220
- 202: 'Accepted',
221
- 203: 'Non-Authoritative Information',
222
- 204: 'No Content',
223
- 205: 'Reset Content',
224
- 206: 'Partial Content',
225
- 207: 'Multi-Status',
226
- 208: 'Already Reported',
227
- 226: 'IM Used',
228
- 300: 'Multiple Choices',
229
- 301: 'Moved Permanently',
230
- 302: 'Found',
231
- 303: 'See Other',
232
- 304: 'Not Modified',
233
- 305: 'Use Proxy',
234
- 306: '(Unused)',
235
- 307: 'Temporary Redirect',
236
- 308: 'Permanent Redirect',
237
- 400: 'Bad Request',
238
- 401: 'Unauthorized',
239
- 402: 'Payment Required',
240
- 403: 'Forbidden',
241
- 404: 'Not Found',
242
- 405: 'Method Not Allowed',
243
- 406: 'Not Acceptable',
244
- 407: 'Proxy Authentication Required',
245
- 408: 'Request Timeout',
246
- 409: 'Conflict',
247
- 410: 'Gone',
248
- 411: 'Length Required',
249
- 412: 'Precondition Failed',
250
- 413: 'Payload Too Large',
251
- 414: 'URI Too Long',
252
- 415: 'Unsupported Media Type',
253
- 416: 'Range Not Satisfiable',
254
- 417: 'Expectation Failed',
255
- 418: "I'm a teapot",
256
- 421: 'Misdirected Request',
257
- 422: 'Unprocessable Entity',
258
- 423: 'Locked',
259
- 424: 'Failed Dependency',
260
- 425: 'Unordered Collection',
261
- 426: 'Upgrade Required',
262
- 428: 'Precondition Required',
263
- 429: 'Too Many Requests',
264
- 431: 'Request Header Fields Too Large',
265
- 451: 'Unavailable For Legal Reasons',
266
- 500: 'Internal Server Error',
267
- 501: 'Not Implemented',
268
- 502: 'Bad Gateway',
269
- 503: 'Service Unavailable',
270
- 504: 'Gateway Timeout',
271
- 505: 'HTTP Version Not Supported',
272
- 506: 'Variant Also Negotiates',
273
- 507: 'Insufficient Storage',
274
- 508: 'Loop Detected',
275
- 509: 'Bandwidth Limit Exceeded',
276
- 510: 'Not Extended',
277
- 511: 'Network Authentication Required'
278
- };
279
-