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