@middy/util 3.0.0-alpha.6 → 3.0.0-alpha.7

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