@middy/util 3.0.2 → 3.1.0-rc.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-2022 Luciano Mammino, will Farrell and the [Middy team](https://github.com/middyjs/middy/graphs/contributors)
3
+ Copyright (c) 2017-2022 [Luciano Mammino](https://github.com/lmammino), [will Farrell](https://github.com/willfarrell) 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
@@ -9,8 +9,8 @@
9
9
  <a href="https://packagephobia.com/result?p=@middy/util">
10
10
  <img src="https://packagephobia.com/badge?p=@middy/util" alt="npm install size" style="max-width:100%;">
11
11
  </a>
12
- <a href="https://github.com/middyjs/middy/actions">
13
- <img src="https://github.com/middyjs/middy/workflows/Tests/badge.svg" alt="GitHub Actions test status badge" style="max-width:100%;">
12
+ <a href="https://github.com/middyjs/middy/actions/workflows/tests.yml">
13
+ <img src="https://github.com/middyjs/middy/actions/workflows/tests.yml/badge.svg?branch=main&event=push" alt="GitHub Actions CI status badge" style="max-width:100%;">
14
14
  </a>
15
15
  <br/>
16
16
  <a href="https://standardjs.com/">
@@ -33,6 +33,7 @@
33
33
  <img src="https://img.shields.io/badge/StackOverflow-[middy]-yellow" alt="Ask questions on StackOverflow" style="max-width:100%;">
34
34
  </a>
35
35
  </p>
36
+ <p>You can read the documentation at: <a href="https://middy.js.org/docs/intro/utilities">https://middy.js.org/docs/intro/utilities</a></p>
36
37
  </div>
37
38
 
38
39
 
@@ -57,7 +58,7 @@ Everyone is very welcome to contribute to this repository. Feel free to [raise i
57
58
 
58
59
  ## License
59
60
 
60
- Licensed under [MIT License](LICENSE). Copyright (c) 2017-2022 Luciano Mammino, will Farrell, and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
61
+ Licensed under [MIT License](LICENSE). Copyright (c) 2017-2022 [Luciano Mammino](https://github.com/lmammino), [will Farrell](https://github.com/willfarrell), and the [Middy team](https://github.com/middyjs/middy/graphs/contributors).
61
62
 
62
63
  <a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy?ref=badge_large">
63
64
  <img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fmiddyjs%2Fmiddy.svg?type=large" alt="FOSSA Status" style="max-width:100%;">
package/index.cjs CHANGED
@@ -1,3 +1,283 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createError=exports.normalizeHttpResponse=exports.jsonSafeStringify=exports.jsonSafeParse=exports.clearCache=exports.modifyCache=exports.getCache=exports.processCache=exports.sanitizeKey=exports.getInternal=exports.canPrefetch=exports.createClient=exports.createPrefetchClient=exports.awsClientDefaultOptions=void 0;var _https=require("https");var _response;const awsClientDefaultOptions={httpOptions:{agent:new _https.Agent({secureProtocol:"TLSv1_2_method"})}};exports.awsClientDefaultOptions=awsClientDefaultOptions;const createPrefetchClient=options=>{const awsClientOptions={...awsClientDefaultOptions,...options.awsClientOptions};const client=new options.AwsClient(awsClientOptions);if(options.awsClientCapture&&options.disablePrefetch){return options.awsClientCapture(client)}else if(options.awsClientCapture){console.warn("Unable to apply X-Ray outside of handler invocation scope.")}return client};exports.createPrefetchClient=createPrefetchClient;const createClient=async(options,request)=>{let awsClientCredentials={};if(options.awsClientAssumeRole){if(!request){throw new Error("Request required when assuming role")}awsClientCredentials=await getInternal({credentials:options.awsClientAssumeRole},request)}awsClientCredentials={...awsClientCredentials,...options.awsClientOptions};return createPrefetchClient({...options,awsClientOptions:awsClientCredentials})};exports.createClient=createClient;const canPrefetch=(options={})=>{return!options.awsClientAssumeRole&&!options.disablePrefetch};exports.canPrefetch=canPrefetch;const getInternal=async(variables,request)=>{if(!variables||!request)return{};let keys=[];let values=[];if(variables===true){keys=values=Object.keys(request.internal)}else if(typeof variables==="string"){keys=values=[variables]}else if(Array.isArray(variables)){keys=values=variables}else if(typeof variables==="object"){keys=Object.keys(variables);values=Object.values(variables)}const promises=[];for(const internalKey of values){const pathOptionKey=internalKey.split(".");const rootOptionKey=pathOptionKey.shift();let valuePromise=request.internal[rootOptionKey];if(!isPromise(valuePromise)){valuePromise=Promise.resolve(valuePromise)}promises.push(valuePromise.then(value=>pathOptionKey.reduce((p,c)=>p?.[c],value)))}values=await Promise.allSettled(promises);const errors=values.filter(res=>res.status==="rejected").map(res=>res.reason);if(errors.length){const error=new Error("Failed to resolve internal values");error.cause=errors;throw error}return keys.reduce((obj,key,index)=>({...obj,[sanitizeKey(key)]:values[index].value}),{})};exports.getInternal=getInternal;const isPromise=promise=>typeof promise?.then==="function";const sanitizeKeyPrefixLeadingNumber=/^([0-9])/;const sanitizeKeyRemoveDisallowedChar=/[^a-zA-Z0-9]+/g;const sanitizeKey=key=>{return key.replace(sanitizeKeyPrefixLeadingNumber,"_$1").replace(sanitizeKeyRemoveDisallowedChar,"_")};exports.sanitizeKey=sanitizeKey;const cache={};const processCache=(options,fetch=()=>undefined,request)=>{const{cacheExpiry,cacheKey}=options;if(cacheExpiry){const cached=getCache(cacheKey);const unexpired=cached.expiry&&(cacheExpiry<0||cached.expiry>Date.now());if(unexpired&&cached.modified){const value=fetch(request,cached.value);cache[cacheKey]={value:{...cached.value,...value},expiry:cached.expiry};return cache[cacheKey]}if(unexpired){return{...cached,cache:true}}}const value=fetch(request);const expiry=Date.now()+cacheExpiry;if(cacheExpiry){cache[cacheKey]={value,expiry}}return{value,expiry}};exports.processCache=processCache;const getCache=key=>{if(!cache[key])return{};return cache[key]};exports.getCache=getCache;const modifyCache=(cacheKey,value)=>{if(!cache[cacheKey])return;cache[cacheKey]={...cache[cacheKey],value,modified:true}};exports.modifyCache=modifyCache;const clearCache=(keys=null)=>{keys=keys??Object.keys(cache);if(!Array.isArray(keys))keys=[keys];for(const cacheKey of keys){cache[cacheKey]=undefined}};exports.clearCache=clearCache;const jsonSafeParse=(text,reviver)=>{if(typeof text!=="string")return text;const firstChar=text[0];if(firstChar!=="{"&&firstChar!=="["&&firstChar!=='"')return text;try{return JSON.parse(text,reviver)}catch(e){}return text};exports.jsonSafeParse=jsonSafeParse;const jsonSafeStringify=(value,replacer,space)=>{try{return JSON.stringify(value,replacer,space)}catch(e){}return value};exports.jsonSafeStringify=jsonSafeStringify;const normalizeHttpResponse=request=>{let{response}=request;if(response===undefined){response={}}else if(response?.statusCode===undefined&&response?.body===undefined&&response?.headers===undefined){response={body:response}}(_response=response).headers??(_response.headers={});request.response=response;return response};exports.normalizeHttpResponse=normalizeHttpResponse;const createErrorRegexp=/[^a-zA-Z]/g;class HttpError extends Error{constructor(code,message,options={}){if(message&& typeof message!=="string"){options=message;message=undefined}message??(message=httpErrorCodes[code]);super(message);this.cause=options.cause;const name=httpErrorCodes[code].replace(createErrorRegexp,"");this.name=name.substr(-5)!=="Error"?name+"Error":name;this.status=this.statusCode=code;this.expose=options.expose??code<500}}exports.HttpError=HttpError;const createError=(code,message,properties={})=>{return new HttpError(code,message,properties)};exports.createError=createError;const httpErrorCodes={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"(Unused)",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports.createError = exports.normalizeHttpResponse = exports.jsonSafeStringify = exports.jsonSafeParse = exports.clearCache = exports.modifyCache = exports.getCache = exports.processCache = exports.sanitizeKey = exports.getInternal = exports.canPrefetch = exports.createClient = exports.createPrefetchClient = exports.awsClientDefaultOptions = void 0;
6
+ var _https = require("https");
7
+ var _response;
8
+ const awsClientDefaultOptions = {
9
+ httpOptions: {
10
+ agent: new _https.Agent({
11
+ keepAlive: true,
12
+ secureProtocol: 'TLSv1_2_method'
13
+ })
14
+ }
15
+ };
16
+ exports.awsClientDefaultOptions = awsClientDefaultOptions;
17
+ const createPrefetchClient = (options)=>{
18
+ const awsClientOptions = {
19
+ ...awsClientDefaultOptions,
20
+ ...options.awsClientOptions
21
+ };
22
+ const client = new options.AwsClient(awsClientOptions);
23
+ if (options.awsClientCapture && options.disablePrefetch) {
24
+ return options.awsClientCapture(client);
25
+ } else if (options.awsClientCapture) {
26
+ console.warn('Unable to apply X-Ray outside of handler invocation scope.');
27
+ }
28
+ return client;
29
+ };
30
+ exports.createPrefetchClient = createPrefetchClient;
31
+ const createClient = async (options, request)=>{
32
+ let awsClientCredentials = {};
33
+ if (options.awsClientAssumeRole) {
34
+ if (!request) {
35
+ throw new Error('Request required when assuming role');
36
+ }
37
+ awsClientCredentials = await getInternal({
38
+ credentials: options.awsClientAssumeRole
39
+ }, request);
40
+ }
41
+ awsClientCredentials = {
42
+ ...awsClientCredentials,
43
+ ...options.awsClientOptions
44
+ };
45
+ return createPrefetchClient({
46
+ ...options,
47
+ awsClientOptions: awsClientCredentials
48
+ });
49
+ };
50
+ exports.createClient = createClient;
51
+ const canPrefetch = (options = {})=>{
52
+ return !options.awsClientAssumeRole && !options.disablePrefetch;
53
+ };
54
+ exports.canPrefetch = canPrefetch;
55
+ const getInternal = async (variables, request)=>{
56
+ if (!variables || !request) return {};
57
+ let keys = [];
58
+ let values = [];
59
+ if (variables === true) {
60
+ keys = values = Object.keys(request.internal);
61
+ } else if (typeof variables === 'string') {
62
+ keys = values = [
63
+ variables
64
+ ];
65
+ } else if (Array.isArray(variables)) {
66
+ keys = values = variables;
67
+ } else if (typeof variables === 'object') {
68
+ keys = Object.keys(variables);
69
+ values = Object.values(variables);
70
+ }
71
+ const promises = [];
72
+ for (const internalKey of values){
73
+ const pathOptionKey = internalKey.split('.');
74
+ const rootOptionKey = pathOptionKey.shift();
75
+ let valuePromise = request.internal[rootOptionKey];
76
+ if (!isPromise(valuePromise)) {
77
+ valuePromise = Promise.resolve(valuePromise);
78
+ }
79
+ promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
80
+ }
81
+ values = await Promise.allSettled(promises);
82
+ const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
83
+ if (errors.length) {
84
+ const error = new Error('Failed to resolve internal values');
85
+ error.cause = errors;
86
+ throw error;
87
+ }
88
+ return keys.reduce((obj, key, index)=>({
89
+ ...obj,
90
+ [sanitizeKey(key)]: values[index].value
91
+ }), {});
92
+ };
93
+ exports.getInternal = getInternal;
94
+ const isPromise = (promise)=>typeof promise?.then === 'function';
95
+ const sanitizeKeyPrefixLeadingNumber = /^([0-9])/;
96
+ const sanitizeKeyRemoveDisallowedChar = /[^a-zA-Z0-9]+/g;
97
+ const sanitizeKey = (key)=>{
98
+ return key.replace(sanitizeKeyPrefixLeadingNumber, '_$1').replace(sanitizeKeyRemoveDisallowedChar, '_');
99
+ };
100
+ exports.sanitizeKey = sanitizeKey;
101
+ const cache = {};
102
+ const processCache = (options, fetch = ()=>undefined, request)=>{
103
+ const { cacheExpiry , cacheKey } = options;
104
+ if (cacheExpiry) {
105
+ const cached = getCache(cacheKey);
106
+ const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
107
+ if (unexpired && cached.modified) {
108
+ const value = fetch(request, cached.value);
109
+ cache[cacheKey] = {
110
+ value: {
111
+ ...cached.value,
112
+ ...value
113
+ },
114
+ expiry: cached.expiry
115
+ };
116
+ return cache[cacheKey];
117
+ }
118
+ if (unexpired) {
119
+ return {
120
+ ...cached,
121
+ cache: true
122
+ };
123
+ }
124
+ }
125
+ const value = fetch(request);
126
+ const expiry = Date.now() + cacheExpiry;
127
+ if (cacheExpiry) {
128
+ cache[cacheKey] = {
129
+ value,
130
+ expiry
131
+ };
132
+ }
133
+ return {
134
+ value,
135
+ expiry
136
+ };
137
+ };
138
+ exports.processCache = processCache;
139
+ const getCache = (key)=>{
140
+ if (!cache[key]) return {};
141
+ return cache[key];
142
+ };
143
+ exports.getCache = getCache;
144
+ const modifyCache = (cacheKey, value)=>{
145
+ if (!cache[cacheKey]) return;
146
+ cache[cacheKey] = {
147
+ ...cache[cacheKey],
148
+ value,
149
+ modified: true
150
+ };
151
+ };
152
+ exports.modifyCache = modifyCache;
153
+ const clearCache = (keys = null)=>{
154
+ keys = keys ?? Object.keys(cache);
155
+ if (!Array.isArray(keys)) keys = [
156
+ keys
157
+ ];
158
+ for (const cacheKey of keys){
159
+ cache[cacheKey] = undefined;
160
+ }
161
+ };
162
+ exports.clearCache = clearCache;
163
+ const jsonSafeParse = (text, reviver)=>{
164
+ if (typeof text !== 'string') return text;
165
+ const firstChar = text[0];
166
+ if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
167
+ try {
168
+ return JSON.parse(text, reviver);
169
+ } catch (e) {}
170
+ return text;
171
+ };
172
+ exports.jsonSafeParse = jsonSafeParse;
173
+ const jsonSafeStringify = (value, replacer, space)=>{
174
+ try {
175
+ return JSON.stringify(value, replacer, space);
176
+ } catch (e) {}
177
+ return value;
178
+ };
179
+ exports.jsonSafeStringify = jsonSafeStringify;
180
+ const normalizeHttpResponse = (request)=>{
181
+ let { response } = request;
182
+ if (response === undefined) {
183
+ response = {};
184
+ } else if (response?.statusCode === undefined && response?.body === undefined && response?.headers === undefined) {
185
+ response = {
186
+ body: response
187
+ };
188
+ }
189
+ (_response = response).headers ?? (_response.headers = {});
190
+ request.response = response;
191
+ return response;
192
+ };
193
+ exports.normalizeHttpResponse = normalizeHttpResponse;
194
+ const createErrorRegexp = /[^a-zA-Z]/g;
195
+ class HttpError extends Error {
196
+ constructor(code, message, options = {}){
197
+ if (message && typeof message !== 'string') {
198
+ options = message;
199
+ message = undefined;
200
+ }
201
+ message ?? (message = httpErrorCodes[code]);
202
+ super(message);
203
+ this.cause = options.cause;
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
+ exports.HttpError = HttpError;
211
+ const createError = (code, message, properties = {})=>{
212
+ return new HttpError(code, message, properties);
213
+ };
214
+ exports.createError = createError;
215
+ const httpErrorCodes = {
216
+ 100: 'Continue',
217
+ 101: 'Switching Protocols',
218
+ 102: 'Processing',
219
+ 103: 'Early Hints',
220
+ 200: 'OK',
221
+ 201: 'Created',
222
+ 202: 'Accepted',
223
+ 203: 'Non-Authoritative Information',
224
+ 204: 'No Content',
225
+ 205: 'Reset Content',
226
+ 206: 'Partial Content',
227
+ 207: 'Multi-Status',
228
+ 208: 'Already Reported',
229
+ 226: 'IM Used',
230
+ 300: 'Multiple Choices',
231
+ 301: 'Moved Permanently',
232
+ 302: 'Found',
233
+ 303: 'See Other',
234
+ 304: 'Not Modified',
235
+ 305: 'Use Proxy',
236
+ 306: '(Unused)',
237
+ 307: 'Temporary Redirect',
238
+ 308: 'Permanent Redirect',
239
+ 400: 'Bad Request',
240
+ 401: 'Unauthorized',
241
+ 402: 'Payment Required',
242
+ 403: 'Forbidden',
243
+ 404: 'Not Found',
244
+ 405: 'Method Not Allowed',
245
+ 406: 'Not Acceptable',
246
+ 407: 'Proxy Authentication Required',
247
+ 408: 'Request Timeout',
248
+ 409: 'Conflict',
249
+ 410: 'Gone',
250
+ 411: 'Length Required',
251
+ 412: 'Precondition Failed',
252
+ 413: 'Payload Too Large',
253
+ 414: 'URI Too Long',
254
+ 415: 'Unsupported Media Type',
255
+ 416: 'Range Not Satisfiable',
256
+ 417: 'Expectation Failed',
257
+ 418: "I'm a teapot",
258
+ 421: 'Misdirected Request',
259
+ 422: 'Unprocessable Entity',
260
+ 423: 'Locked',
261
+ 424: 'Failed Dependency',
262
+ 425: 'Unordered Collection',
263
+ 426: 'Upgrade Required',
264
+ 428: 'Precondition Required',
265
+ 429: 'Too Many Requests',
266
+ 431: 'Request Header Fields Too Large',
267
+ 451: 'Unavailable For Legal Reasons',
268
+ 500: 'Internal Server Error',
269
+ 501: 'Not Implemented',
270
+ 502: 'Bad Gateway',
271
+ 503: 'Service Unavailable',
272
+ 504: 'Gateway Timeout',
273
+ 505: 'HTTP Version Not Supported',
274
+ 506: 'Variant Also Negotiates',
275
+ 507: 'Insufficient Storage',
276
+ 508: 'Loop Detected',
277
+ 509: 'Bandwidth Limit Exceeded',
278
+ 510: 'Not Extended',
279
+ 511: 'Network Authentication Required'
280
+ };
281
+
2
282
 
3
283
  //# sourceMappingURL=index.cjs.map
package/index.js CHANGED
@@ -1,3 +1,263 @@
1
- var _response;import{Agent}from"https";export const awsClientDefaultOptions={httpOptions:{agent:new Agent({secureProtocol:"TLSv1_2_method"})}};export const createPrefetchClient=options=>{const awsClientOptions={...awsClientDefaultOptions,...options.awsClientOptions};const client=new options.AwsClient(awsClientOptions);if(options.awsClientCapture&&options.disablePrefetch){return options.awsClientCapture(client)}else if(options.awsClientCapture){console.warn("Unable to apply X-Ray outside of handler invocation scope.")}return client};export const createClient=async(options,request)=>{let awsClientCredentials={};if(options.awsClientAssumeRole){if(!request){throw new Error("Request required when assuming role")}awsClientCredentials=await getInternal({credentials:options.awsClientAssumeRole},request)}awsClientCredentials={...awsClientCredentials,...options.awsClientOptions};return createPrefetchClient({...options,awsClientOptions:awsClientCredentials})};export const canPrefetch=(options={})=>{return!options.awsClientAssumeRole&&!options.disablePrefetch};export const getInternal=async(variables,request)=>{if(!variables||!request)return{};let keys=[];let values=[];if(variables===true){keys=values=Object.keys(request.internal)}else if(typeof variables==="string"){keys=values=[variables]}else if(Array.isArray(variables)){keys=values=variables}else if(typeof variables==="object"){keys=Object.keys(variables);values=Object.values(variables)}const promises=[];for(const internalKey of values){const pathOptionKey=internalKey.split(".");const rootOptionKey=pathOptionKey.shift();let valuePromise=request.internal[rootOptionKey];if(!isPromise(valuePromise)){valuePromise=Promise.resolve(valuePromise)}promises.push(valuePromise.then(value=>pathOptionKey.reduce((p,c)=>p?.[c],value)))}values=await Promise.allSettled(promises);const errors=values.filter(res=>res.status==="rejected").map(res=>res.reason);if(errors.length){const error=new Error("Failed to resolve internal values");error.cause=errors;throw error}return keys.reduce((obj,key,index)=>({...obj,[sanitizeKey(key)]:values[index].value}),{})};const isPromise=promise=>typeof promise?.then==="function";const sanitizeKeyPrefixLeadingNumber=/^([0-9])/;const sanitizeKeyRemoveDisallowedChar=/[^a-zA-Z0-9]+/g;export const sanitizeKey=key=>{return key.replace(sanitizeKeyPrefixLeadingNumber,"_$1").replace(sanitizeKeyRemoveDisallowedChar,"_")};const cache={};export const processCache=(options,fetch=()=>undefined,request)=>{const{cacheExpiry,cacheKey}=options;if(cacheExpiry){const cached=getCache(cacheKey);const unexpired=cached.expiry&&(cacheExpiry<0||cached.expiry>Date.now());if(unexpired&&cached.modified){const value=fetch(request,cached.value);cache[cacheKey]={value:{...cached.value,...value},expiry:cached.expiry};return cache[cacheKey]}if(unexpired){return{...cached,cache:true}}}const value=fetch(request);const expiry=Date.now()+cacheExpiry;if(cacheExpiry){cache[cacheKey]={value,expiry}}return{value,expiry}};export const getCache=key=>{if(!cache[key])return{};return cache[key]};export const modifyCache=(cacheKey,value)=>{if(!cache[cacheKey])return;cache[cacheKey]={...cache[cacheKey],value,modified:true}};export const clearCache=(keys=null)=>{keys=keys??Object.keys(cache);if(!Array.isArray(keys))keys=[keys];for(const cacheKey of keys){cache[cacheKey]=undefined}};export const jsonSafeParse=(text,reviver)=>{if(typeof text!=="string")return text;const firstChar=text[0];if(firstChar!=="{"&&firstChar!=="["&&firstChar!=='"')return text;try{return JSON.parse(text,reviver)}catch(e){}return text};export const jsonSafeStringify=(value,replacer,space)=>{try{return JSON.stringify(value,replacer,space)}catch(e){}return value};export const normalizeHttpResponse=request=>{let{response}=request;if(response===undefined){response={}}else if(response?.statusCode===undefined&&response?.body===undefined&&response?.headers===undefined){response={body:response}}(_response=response).headers??(_response.headers={});request.response=response;return response};const createErrorRegexp=/[^a-zA-Z]/g;export class HttpError extends Error{constructor(code,message,options={}){if(message&& typeof message!=="string"){options=message;message=undefined}message??(message=httpErrorCodes[code]);super(message);this.cause=options.cause;const name=httpErrorCodes[code].replace(createErrorRegexp,"");this.name=name.substr(-5)!=="Error"?name+"Error":name;this.status=this.statusCode=code;this.expose=options.expose??code<500}}export const createError=(code,message,properties={})=>{return new HttpError(code,message,properties)};const httpErrorCodes={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"(Unused)",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}
1
+ var _response;
2
+ import { Agent } from 'https';
3
+ export const awsClientDefaultOptions = {
4
+ httpOptions: {
5
+ agent: new Agent({
6
+ keepAlive: true,
7
+ secureProtocol: 'TLSv1_2_method'
8
+ })
9
+ }
10
+ };
11
+ export const createPrefetchClient = (options)=>{
12
+ const awsClientOptions = {
13
+ ...awsClientDefaultOptions,
14
+ ...options.awsClientOptions
15
+ };
16
+ const client = new options.AwsClient(awsClientOptions);
17
+ if (options.awsClientCapture && options.disablePrefetch) {
18
+ return options.awsClientCapture(client);
19
+ } else if (options.awsClientCapture) {
20
+ console.warn('Unable to apply X-Ray outside of handler invocation scope.');
21
+ }
22
+ return client;
23
+ };
24
+ export const createClient = async (options, request)=>{
25
+ let awsClientCredentials = {};
26
+ if (options.awsClientAssumeRole) {
27
+ if (!request) {
28
+ throw new Error('Request required when assuming role');
29
+ }
30
+ awsClientCredentials = await getInternal({
31
+ credentials: options.awsClientAssumeRole
32
+ }, request);
33
+ }
34
+ awsClientCredentials = {
35
+ ...awsClientCredentials,
36
+ ...options.awsClientOptions
37
+ };
38
+ return createPrefetchClient({
39
+ ...options,
40
+ awsClientOptions: awsClientCredentials
41
+ });
42
+ };
43
+ export const canPrefetch = (options = {})=>{
44
+ return !options.awsClientAssumeRole && !options.disablePrefetch;
45
+ };
46
+ export const getInternal = async (variables, request)=>{
47
+ if (!variables || !request) return {};
48
+ let keys = [];
49
+ let values = [];
50
+ if (variables === true) {
51
+ keys = values = Object.keys(request.internal);
52
+ } else if (typeof variables === 'string') {
53
+ keys = values = [
54
+ variables
55
+ ];
56
+ } else if (Array.isArray(variables)) {
57
+ keys = values = variables;
58
+ } else if (typeof variables === 'object') {
59
+ keys = Object.keys(variables);
60
+ values = Object.values(variables);
61
+ }
62
+ const promises = [];
63
+ for (const internalKey of values){
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);
69
+ }
70
+ promises.push(valuePromise.then((value)=>pathOptionKey.reduce((p, c)=>p?.[c], value)));
71
+ }
72
+ values = await Promise.allSettled(promises);
73
+ const errors = values.filter((res)=>res.status === 'rejected').map((res)=>res.reason);
74
+ if (errors.length) {
75
+ const error = new Error('Failed to resolve internal values');
76
+ error.cause = errors;
77
+ throw error;
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
+ };
90
+ const cache = {};
91
+ export const processCache = (options, fetch = ()=>undefined, request)=>{
92
+ const { cacheExpiry , cacheKey } = options;
93
+ if (cacheExpiry) {
94
+ const cached = getCache(cacheKey);
95
+ const unexpired = cached.expiry && (cacheExpiry < 0 || cached.expiry > Date.now());
96
+ if (unexpired && cached.modified) {
97
+ const value = fetch(request, cached.value);
98
+ cache[cacheKey] = {
99
+ value: {
100
+ ...cached.value,
101
+ ...value
102
+ },
103
+ expiry: cached.expiry
104
+ };
105
+ return cache[cacheKey];
106
+ }
107
+ if (unexpired) {
108
+ return {
109
+ ...cached,
110
+ cache: true
111
+ };
112
+ }
113
+ }
114
+ const value = fetch(request);
115
+ const expiry = Date.now() + cacheExpiry;
116
+ if (cacheExpiry) {
117
+ cache[cacheKey] = {
118
+ value,
119
+ expiry
120
+ };
121
+ }
122
+ return {
123
+ value,
124
+ expiry
125
+ };
126
+ };
127
+ export const getCache = (key)=>{
128
+ if (!cache[key]) return {};
129
+ return cache[key];
130
+ };
131
+ export const modifyCache = (cacheKey, value)=>{
132
+ if (!cache[cacheKey]) return;
133
+ cache[cacheKey] = {
134
+ ...cache[cacheKey],
135
+ value,
136
+ modified: true
137
+ };
138
+ };
139
+ export const clearCache = (keys = null)=>{
140
+ keys = keys ?? Object.keys(cache);
141
+ if (!Array.isArray(keys)) keys = [
142
+ keys
143
+ ];
144
+ for (const cacheKey of keys){
145
+ cache[cacheKey] = undefined;
146
+ }
147
+ };
148
+ export const jsonSafeParse = (text, reviver)=>{
149
+ if (typeof text !== 'string') return text;
150
+ const firstChar = text[0];
151
+ if (firstChar !== '{' && firstChar !== '[' && firstChar !== '"') return text;
152
+ try {
153
+ return JSON.parse(text, reviver);
154
+ } catch (e) {}
155
+ return text;
156
+ };
157
+ export const jsonSafeStringify = (value, replacer, space)=>{
158
+ try {
159
+ return JSON.stringify(value, replacer, space);
160
+ } catch (e) {}
161
+ return value;
162
+ };
163
+ export const normalizeHttpResponse = (request)=>{
164
+ let { response } = request;
165
+ if (response === undefined) {
166
+ response = {};
167
+ } else if (response?.statusCode === undefined && response?.body === undefined && response?.headers === undefined) {
168
+ response = {
169
+ body: response
170
+ };
171
+ }
172
+ (_response = response).headers ?? (_response.headers = {});
173
+ request.response = response;
174
+ return response;
175
+ };
176
+ const createErrorRegexp = /[^a-zA-Z]/g;
177
+ export class HttpError extends Error {
178
+ constructor(code, message, options = {}){
179
+ if (message && typeof message !== 'string') {
180
+ options = message;
181
+ message = undefined;
182
+ }
183
+ message ?? (message = httpErrorCodes[code]);
184
+ super(message);
185
+ this.cause = options.cause;
186
+ const name = httpErrorCodes[code].replace(createErrorRegexp, '');
187
+ this.name = name.substr(-5) !== 'Error' ? name + 'Error' : name;
188
+ this.status = this.statusCode = code;
189
+ this.expose = options.expose ?? code < 500;
190
+ }
191
+ }
192
+ export const createError = (code, message, properties = {})=>{
193
+ return new HttpError(code, message, properties);
194
+ };
195
+ const httpErrorCodes = {
196
+ 100: 'Continue',
197
+ 101: 'Switching Protocols',
198
+ 102: 'Processing',
199
+ 103: 'Early Hints',
200
+ 200: 'OK',
201
+ 201: 'Created',
202
+ 202: 'Accepted',
203
+ 203: 'Non-Authoritative Information',
204
+ 204: 'No Content',
205
+ 205: 'Reset Content',
206
+ 206: 'Partial Content',
207
+ 207: 'Multi-Status',
208
+ 208: 'Already Reported',
209
+ 226: 'IM Used',
210
+ 300: 'Multiple Choices',
211
+ 301: 'Moved Permanently',
212
+ 302: 'Found',
213
+ 303: 'See Other',
214
+ 304: 'Not Modified',
215
+ 305: 'Use Proxy',
216
+ 306: '(Unused)',
217
+ 307: 'Temporary Redirect',
218
+ 308: 'Permanent Redirect',
219
+ 400: 'Bad Request',
220
+ 401: 'Unauthorized',
221
+ 402: 'Payment Required',
222
+ 403: 'Forbidden',
223
+ 404: 'Not Found',
224
+ 405: 'Method Not Allowed',
225
+ 406: 'Not Acceptable',
226
+ 407: 'Proxy Authentication Required',
227
+ 408: 'Request Timeout',
228
+ 409: 'Conflict',
229
+ 410: 'Gone',
230
+ 411: 'Length Required',
231
+ 412: 'Precondition Failed',
232
+ 413: 'Payload Too Large',
233
+ 414: 'URI Too Long',
234
+ 415: 'Unsupported Media Type',
235
+ 416: 'Range Not Satisfiable',
236
+ 417: 'Expectation Failed',
237
+ 418: "I'm a teapot",
238
+ 421: 'Misdirected Request',
239
+ 422: 'Unprocessable Entity',
240
+ 423: 'Locked',
241
+ 424: 'Failed Dependency',
242
+ 425: 'Unordered Collection',
243
+ 426: 'Upgrade Required',
244
+ 428: 'Precondition Required',
245
+ 429: 'Too Many Requests',
246
+ 431: 'Request Header Fields Too Large',
247
+ 451: 'Unavailable For Legal Reasons',
248
+ 500: 'Internal Server Error',
249
+ 501: 'Not Implemented',
250
+ 502: 'Bad Gateway',
251
+ 503: 'Service Unavailable',
252
+ 504: 'Gateway Timeout',
253
+ 505: 'HTTP Version Not Supported',
254
+ 506: 'Variant Also Negotiates',
255
+ 507: 'Insufficient Storage',
256
+ 508: 'Loop Detected',
257
+ 509: 'Bandwidth Limit Exceeded',
258
+ 510: 'Not Extended',
259
+ 511: 'Network Authentication Required'
260
+ };
261
+
2
262
 
3
263
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/util",
3
- "version": "3.0.2",
3
+ "version": "3.1.0-rc.0",
4
4
  "description": "🛵 The stylish Node.js middleware engine for AWS Lambda (util package)",
5
5
  "type": "module",
6
6
  "engines": {
@@ -10,11 +10,17 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
+ "main": "./index.cjs",
13
14
  "exports": {
14
15
  ".": {
15
- "import": "./index.js",
16
- "require": "./index.cjs",
17
- "types": "./index.d.ts"
16
+ "import": {
17
+ "types": "./index.d.ts",
18
+ "default": "./index.js"
19
+ },
20
+ "require": {
21
+ "types": "./index.d.ts",
22
+ "default": "./index.cjs"
23
+ }
18
24
  }
19
25
  },
20
26
  "types": "index.d.ts",
@@ -53,12 +59,12 @@
53
59
  "url": "https://github.com/middyjs/middy/issues"
54
60
  },
55
61
  "devDependencies": {
56
- "@middy/core": "^3.0.2",
62
+ "@middy/core": "3.1.0-rc.0",
57
63
  "@types/aws-lambda": "^8.10.76",
58
64
  "@types/node": "^17.0.0",
59
65
  "aws-sdk": "^2.939.0",
60
66
  "aws-xray-sdk": "^3.3.3"
61
67
  },
62
68
  "homepage": "https://middy.js.org",
63
- "gitHead": "983649b8359ea32a786e75dfc2953aeee8ec6052"
69
+ "gitHead": "03a8794d3cdb4319eca49ba4c55420bea5d66430"
64
70
  }