@whook/gcp-functions 9.0.1 → 10.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +8 -9
  2. package/dist/commands/testHTTPFunction.d.ts +1 -1
  3. package/dist/commands/testHTTPFunction.js +119 -150
  4. package/dist/commands/testHTTPFunction.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +182 -269
  7. package/dist/index.js.map +1 -1
  8. package/dist/libs/utils.js +16 -35
  9. package/dist/libs/utils.js.map +1 -1
  10. package/dist/services/_autoload.d.ts +3 -3
  11. package/dist/services/_autoload.js +83 -109
  12. package/dist/services/_autoload.js.map +1 -1
  13. package/dist/services/log.js +2 -12
  14. package/dist/services/log.js.map +1 -1
  15. package/dist/services/log.test.js +4 -9
  16. package/dist/services/log.test.js.map +1 -1
  17. package/dist/wrappers/googleHTTPFunction.js +246 -294
  18. package/dist/wrappers/googleHTTPFunction.js.map +1 -1
  19. package/package.json +47 -89
  20. package/src/commands/testHTTPFunction.ts +6 -13
  21. package/src/index.ts +36 -54
  22. package/src/libs/utils.ts +3 -4
  23. package/src/services/_autoload.ts +4 -3
  24. package/src/services/log.test.ts +1 -1
  25. package/src/wrappers/googleHTTPFunction.ts +6 -6
  26. package/dist/commands/testHTTPFunction.mjs +0 -136
  27. package/dist/commands/testHTTPFunction.mjs.map +0 -1
  28. package/dist/index.mjs +0 -265
  29. package/dist/index.mjs.map +0 -1
  30. package/dist/libs/utils.mjs +0 -27
  31. package/dist/libs/utils.mjs.map +0 -1
  32. package/dist/services/_autoload.mjs +0 -113
  33. package/dist/services/_autoload.mjs.map +0 -1
  34. package/dist/services/log.mjs +0 -4
  35. package/dist/services/log.mjs.map +0 -1
  36. package/dist/services/log.test.mjs +0 -7
  37. package/dist/services/log.test.mjs.map +0 -1
  38. package/dist/wrappers/googleHTTPFunction.mjs +0 -290
  39. package/dist/wrappers/googleHTTPFunction.mjs.map +0 -1
@@ -1,136 +0,0 @@
1
- import { loadLambda } from '../libs/utils';
2
- import { extra, service as _service } from 'knifecycle';
3
- import { readArgs } from '@whook/cli';
4
- import YError from 'yerror';
5
- import { dereferenceOpenAPIOperations, getOpenAPIOperations } from '@whook/http-router';
6
- import stream from 'stream';
7
- import camelCase from 'camelcase';
8
- const SEARCH_SEPARATOR = '?';
9
- const PATH_SEPARATOR = '/';
10
- export const definition = {
11
- description: 'A command for testing AWS HTTP lambda',
12
- example: `whook testHTTPLambda --name getPing`,
13
- arguments: {
14
- type: 'object',
15
- additionalProperties: false,
16
- required: ['name'],
17
- properties: {
18
- name: {
19
- description: 'Name of the lamda to run',
20
- type: 'string'
21
- },
22
- type: {
23
- description: 'Type of lambda to test',
24
- type: 'string',
25
- enum: ['main', 'index'],
26
- default: 'index'
27
- },
28
- contentType: {
29
- description: 'Content type of the payload',
30
- type: 'string',
31
- default: 'application/json'
32
- },
33
- parameters: {
34
- description: 'The HTTP call parameters',
35
- type: 'string',
36
- default: '{}'
37
- }
38
- }
39
- }
40
- };
41
- export default extra(definition, _service(initTestHTTPLambdaCommand, "testHTTPLambdaCommand", ["NODE_ENV", "PROJECT_DIR", "API", "log", "args"]));
42
-
43
- async function initTestHTTPLambdaCommand({
44
- NODE_ENV,
45
- PROJECT_DIR,
46
- API,
47
- log,
48
- args
49
- }) {
50
- return async () => {
51
- const {
52
- name,
53
- type,
54
- contentType,
55
- parameters: rawParameters
56
- } = readArgs(definition.arguments, args);
57
- const handler = await loadLambda({
58
- PROJECT_DIR,
59
- log
60
- }, NODE_ENV, name, type);
61
- const OPERATION = (await dereferenceOpenAPIOperations(API, getOpenAPIOperations(API))).find(({
62
- operationId
63
- }) => operationId === name);
64
-
65
- if (!OPERATION) {
66
- throw new YError('E_OPERATION_NOT_FOUND');
67
- }
68
-
69
- const hasBody = !!OPERATION.requestBody;
70
- const parameters = JSON.parse(rawParameters);
71
- const search = (OPERATION.parameters || []).filter(p => p.in === 'query').reduce((accSearch, p) => {
72
- if (null != parameters[p.name]) {
73
- return accSearch + (accSearch ? '&' : '') + p.name + '=' + parameters[p.name];
74
- }
75
-
76
- return accSearch;
77
- }, '');
78
- const path = OPERATION.path.split(PATH_SEPARATOR).map(part => {
79
- const matches = /^\{([\d\w]+)\}$/i.exec(part);
80
-
81
- if (matches) {
82
- return parameters[matches[1]];
83
- }
84
-
85
- return part;
86
- }).join(PATH_SEPARATOR);
87
- const gcpfRequest = {
88
- method: OPERATION.method,
89
- originalUrl: path + (search ? SEARCH_SEPARATOR + search : ''),
90
- headers: (OPERATION.parameters || []).filter(p => p.in === 'header').reduce((headerParameters, p) => {
91
- headerParameters[p.name] = parameters[camelCase(p.name)];
92
- return headerParameters;
93
- }, {}),
94
- rawBody: Buffer.from(hasBody ? contentType === 'application/json' ? parameters.body ? JSON.stringify(parameters.body) : '' : parameters.body || '' : '')
95
- };
96
-
97
- if (hasBody) {
98
- gcpfRequest.headers['content-type'] = `${contentType};charset=UTF-8`;
99
- }
100
-
101
- log('info', 'GCPF_REQUEST:', gcpfRequest);
102
- const response = {
103
- status: 0,
104
- headers: {},
105
- data: ''
106
- };
107
- await new Promise((resolve, reject) => {
108
- const gcpfResponse = new stream.PassThrough();
109
-
110
- gcpfResponse.set = (name, value) => {
111
- response.headers[name] = value;
112
- };
113
-
114
- gcpfResponse.status = code => {
115
- response.status = code;
116
- };
117
-
118
- handler(gcpfRequest, gcpfResponse).catch(reject);
119
- const chunks = [];
120
- gcpfResponse.once('end', () => {
121
- response.data = Buffer.concat(chunks).toString();
122
- resolve();
123
- });
124
- gcpfResponse.once('error', reject);
125
- gcpfResponse.on('readable', () => {
126
- let data;
127
-
128
- while (data = gcpfResponse.read()) {
129
- chunks.push(data);
130
- }
131
- });
132
- });
133
- log('info', 'SUCCESS:', response);
134
- };
135
- }
136
- //# sourceMappingURL=testHTTPFunction.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testHTTPFunction.mjs","names":["loadLambda","extra","autoService","readArgs","YError","dereferenceOpenAPIOperations","getOpenAPIOperations","stream","camelCase","SEARCH_SEPARATOR","PATH_SEPARATOR","definition","description","example","arguments","type","additionalProperties","required","properties","name","enum","default","contentType","parameters","initTestHTTPLambdaCommand","NODE_ENV","PROJECT_DIR","API","log","args","rawParameters","handler","OPERATION","find","operationId","hasBody","requestBody","JSON","parse","search","filter","p","in","reduce","accSearch","path","split","map","part","matches","exec","join","gcpfRequest","method","originalUrl","headers","headerParameters","rawBody","Buffer","from","body","stringify","response","status","data","Promise","resolve","reject","gcpfResponse","PassThrough","set","value","code","catch","chunks","once","concat","toString","on","read","push"],"sources":["../../src/commands/testHTTPFunction.ts"],"sourcesContent":["import { loadLambda } from '../libs/utils';\nimport { extra, autoService } from 'knifecycle';\nimport { readArgs } from '@whook/cli';\nimport YError from 'yerror';\nimport {\n dereferenceOpenAPIOperations,\n getOpenAPIOperations,\n} from '@whook/http-router';\nimport stream from 'stream';\nimport camelCase from 'camelcase';\nimport type {\n WhookCommandArgs,\n WhookCommandDefinition,\n WhookCommandNamedArgs,\n} from '@whook/cli';\nimport type { LogService } from 'common-services';\nimport type { OpenAPIV3 } from 'openapi-types';\n\nconst SEARCH_SEPARATOR = '?';\nconst PATH_SEPARATOR = '/';\n\nexport const definition: WhookCommandDefinition = {\n description: 'A command for testing AWS HTTP lambda',\n example: `whook testHTTPLambda --name getPing`,\n arguments: {\n type: 'object',\n additionalProperties: false,\n required: ['name'],\n properties: {\n name: {\n description: 'Name of the lamda to run',\n type: 'string',\n },\n type: {\n description: 'Type of lambda to test',\n type: 'string',\n enum: ['main', 'index'],\n default: 'index',\n },\n contentType: {\n description: 'Content type of the payload',\n type: 'string',\n default: 'application/json',\n },\n parameters: {\n description: 'The HTTP call parameters',\n type: 'string',\n default: '{}',\n },\n },\n },\n};\n\nexport default extra(definition, autoService(initTestHTTPLambdaCommand));\n\nasync function initTestHTTPLambdaCommand({\n NODE_ENV,\n PROJECT_DIR,\n API,\n log,\n args,\n}: {\n NODE_ENV: string;\n PROJECT_DIR: string;\n API: OpenAPIV3.Document;\n log: LogService;\n args: WhookCommandArgs;\n}) {\n return async () => {\n const {\n name,\n type,\n contentType,\n parameters: rawParameters,\n }: WhookCommandNamedArgs = readArgs(definition.arguments, args) as {\n name: string;\n type: string;\n contentType: string;\n parameters: string;\n };\n const handler = await loadLambda(\n { PROJECT_DIR, log },\n NODE_ENV,\n name,\n type,\n );\n const OPERATION = (\n await dereferenceOpenAPIOperations(API, getOpenAPIOperations(API))\n ).find(({ operationId }) => operationId === name);\n\n if (!OPERATION) {\n throw new YError('E_OPERATION_NOT_FOUND');\n }\n\n const hasBody = !!OPERATION.requestBody;\n const parameters = JSON.parse(rawParameters);\n const search = ((OPERATION.parameters || []) as OpenAPIV3.ParameterObject[])\n .filter((p) => p.in === 'query')\n .reduce((accSearch, p) => {\n if (null != parameters[p.name]) {\n return (\n accSearch +\n (accSearch ? '&' : '') +\n p.name +\n '=' +\n parameters[p.name]\n );\n }\n return accSearch;\n }, '');\n\n const path = OPERATION.path\n .split(PATH_SEPARATOR)\n\n .map((part) => {\n const matches = /^\\{([\\d\\w]+)\\}$/i.exec(part);\n\n if (matches) {\n return parameters[matches[1]];\n }\n return part;\n })\n .join(PATH_SEPARATOR);\n const gcpfRequest = {\n method: OPERATION.method,\n originalUrl: path + (search ? SEARCH_SEPARATOR + search : ''),\n headers: ((OPERATION.parameters || []) as OpenAPIV3.ParameterObject[])\n .filter((p) => p.in === 'header')\n .reduce((headerParameters, p) => {\n headerParameters[p.name] = parameters[camelCase(p.name)];\n return headerParameters;\n }, {}),\n rawBody: Buffer.from(\n hasBody\n ? contentType === 'application/json'\n ? parameters.body\n ? JSON.stringify(parameters.body)\n : ''\n : parameters.body || ''\n : '',\n ),\n };\n if (hasBody) {\n gcpfRequest.headers['content-type'] = `${contentType};charset=UTF-8`;\n }\n log('info', 'GCPF_REQUEST:', gcpfRequest as unknown as string);\n\n const response = {\n status: 0,\n headers: {},\n data: '',\n };\n await new Promise<void>((resolve, reject) => {\n const gcpfResponse = new stream.PassThrough();\n\n (gcpfResponse as any).set = (name: string, value: string): void => {\n response.headers[name] = value;\n };\n (gcpfResponse as any).status = (code: number): void => {\n response.status = code;\n };\n\n handler(gcpfRequest, gcpfResponse).catch(reject);\n\n const chunks = [] as Buffer[];\n\n gcpfResponse.once('end', () => {\n response.data = Buffer.concat(chunks).toString();\n resolve();\n });\n gcpfResponse.once('error', reject);\n gcpfResponse.on('readable', () => {\n let data: Buffer;\n while ((data = gcpfResponse.read())) {\n chunks.push(data);\n }\n });\n });\n log('info', 'SUCCESS:', response);\n };\n}\n"],"mappings":"AAAA,SAASA,UAAT,QAA2B,eAA3B;AACA,SAASC,KAAT,EAAgBC,OAAW,IAAXA,QAAhB,QAAmC,YAAnC;AACA,SAASC,QAAT,QAAyB,YAAzB;AACA,OAAOC,MAAP,MAAmB,QAAnB;AACA,SACEC,4BADF,EAEEC,oBAFF,QAGO,oBAHP;AAIA,OAAOC,MAAP,MAAmB,QAAnB;AACA,OAAOC,SAAP,MAAsB,WAAtB;AASA,MAAMC,gBAAgB,GAAG,GAAzB;AACA,MAAMC,cAAc,GAAG,GAAvB;AAEA,OAAO,MAAMC,UAAkC,GAAG;EAChDC,WAAW,EAAE,uCADmC;EAEhDC,OAAO,EAAG,qCAFsC;EAGhDC,SAAS,EAAE;IACTC,IAAI,EAAE,QADG;IAETC,oBAAoB,EAAE,KAFb;IAGTC,QAAQ,EAAE,CAAC,MAAD,CAHD;IAITC,UAAU,EAAE;MACVC,IAAI,EAAE;QACJP,WAAW,EAAE,0BADT;QAEJG,IAAI,EAAE;MAFF,CADI;MAKVA,IAAI,EAAE;QACJH,WAAW,EAAE,wBADT;QAEJG,IAAI,EAAE,QAFF;QAGJK,IAAI,EAAE,CAAC,MAAD,EAAS,OAAT,CAHF;QAIJC,OAAO,EAAE;MAJL,CALI;MAWVC,WAAW,EAAE;QACXV,WAAW,EAAE,6BADF;QAEXG,IAAI,EAAE,QAFK;QAGXM,OAA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zBK,CAAN;IA0BApC,GAAG,CAAC,MAAD,EAAS,UAAT,EAAqBkC,QAArB,CAAH;EACD,CA/GD;AAgHD"}
package/dist/index.mjs DELETED
@@ -1,265 +0,0 @@
1
- /* eslint global-require:0 */
2
- import fs from 'fs';
3
- import util from 'util';
4
- import path from 'path';
5
- import mkdirp from 'mkdirp';
6
- import cpr from 'cpr';
7
- import YError from 'yerror';
8
- import Knifecycle, { SPECIAL_PROPS, constant, initInitializerBuilder } from 'knifecycle';
9
- import { DEFAULT_BUILD_OPTIONS, initCompiler } from '@whook/whook';
10
- import initBuildAutoloader from './services/_autoload';
11
- import { dereferenceOpenAPIOperations, getOpenAPIOperations } from '@whook/http-router';
12
- export const DEFAULT_BUILD_PARALLELISM = 10;
13
- const readFileAsync = util.promisify(fs.readFile);
14
- const writeFileAsync = util.promisify(fs.writeFile);
15
- const cprAsync = util.promisify(cpr);
16
- const BUILD_DEFINITIONS = {
17
- http: {
18
- type: 'HTTP',
19
- wrapper: {
20
- name: 'wrapHandlerForGoogleHTTPFunction',
21
- path: path.join(__dirname, 'wrappers', 'googleHTTPFunction')
22
- },
23
- suffix: 'Wrapped'
24
- }
25
- };
26
- export async function prepareBuildEnvironment($ = new Knifecycle()) {
27
- $.register(constant('INITIALIZER_PATH_MAP', {
28
- ENV: '@whook/whook/dist/services/ProxyedENV',
29
- log: __dirname + '/services/log',
30
- time: 'common-services/dist/time',
31
- delay: 'common-services/dist/delay'
32
- }));
33
- $.register(initInitializerBuilder);
34
- $.register(initBuildAutoloader);
35
- $.register(initCompiler);
36
- $.register(constant('PORT', 1337));
37
- $.register(constant('HOST', 'localhost'));
38
- return $;
39
- }
40
- export async function runBuild(aPrepareBuildEnvironment) {
41
- try {
42
- const handlerName = process.argv[2];
43
- const $ = await aPrepareBuildEnvironment();
44
- const {
45
- NODE_ENV,
46
- BUILD_PARALLELISM,
47
- BUILD_OPTIONS,
48
- PROJECT_DIR,
49
- compiler,
50
- log,
51
- $autoload,
52
- API,
53
- buildInitializer
54
- } = await $.run(['NODE_ENV', '?BUILD_PARALLELISM', '?BUILD_OPTIONS', 'PROJECT_DIR', 'process', 'compiler', 'log', '$autoload', 'API', 'buildInitializer']);
55
- log('info', 'GCP Functions build Environment initialized 🚀🌕');
56
- const operations = (await dereferenceOpenAPIOperations(API, getOpenAPIOperations(API))).filter(operation => {
57
- if (handlerName) {
58
- const sourceOperationId = operation['x-whook'] && operation['x-whook'].sourceOperationId;
59
- return handlerName === operation.operationId || handlerName === sourceOperationId;
60
- }
61
-
62
- return true;
63
- });
64
- log('warning', `${operations.length} operations to process.`);
65
- await processOperations({
66
- NODE_ENV,
67
- BUILD_OPTIONS: BUILD_OPTIONS || DEFAULT_BUILD_OPTIONS,
68
- BUILD_PARALLELISM: BUILD_PARALLELISM || DEFAULT_BUILD_PARALLELISM,
69
- PROJECT_DIR,
70
- compiler,
71
- log,
72
- $autoload,
73
- buildInitializer
74
- }, operations);
75
- await $.destroy();
76
- } catch (err) {
77
- // eslint-disable-next-line
78
- console.error('💀 - Cannot launch the build:', err.stack, JSON.stringify(err.params, null, 2));
79
- process.exit(1);
80
- }
81
- }
82
-
83
- async function processOperations({
84
- NODE_ENV,
85
- BUILD_PARALLELISM,
86
- BUILD_OPTIONS,
87
- PROJECT_DIR,
88
- compiler,
89
- log,
90
- $autoload,
91
- buildInitializer
92
- }, operations) {
93
- const operationsLeft = operations.slice(BUILD_PARALLELISM);
94
- await Promise.all(operations.slice(0, BUILD_PARALLELISM).map(operation => buildAnyLambda({
95
- NODE_ENV,
96
- PROJECT_DIR,
97
- BUILD_OPTIONS,
98
- compiler,
99
- log,
100
- $autoload,
101
- buildInitializer
102
- }, operation)));
103
-
104
- if (operationsLeft.length) {
105
- log('info', operationsLeft.length, ' operations left.');
106
- return processOperations({
107
- NODE_ENV,
108
- BUILD_PARALLELISM,
109
- BUILD_OPTIONS,
110
- PROJECT_DIR,
111
- compiler,
112
- log,
113
- $autoload,
114
- buildInitializer
115
- }, operationsLeft);
116
- }
117
-
118
- log('info', 'No more operations.');
119
- }
120
-
121
- async function buildAnyLambda({
122
- NODE_ENV,
123
- PROJECT_DIR,
124
- BUILD_OPTIONS,
125
- compiler,
126
- log,
127
- $autoload,
128
- buildInitializer
129
- }, operation) {
130
- const {
131
- operationId
132
- } = operation;
133
-
134
- try {
135
- const whookConfig = operation['x-whook'] || {};
136
- const operationType = whookConfig.type || 'http';
137
- const sourceOperationId = whookConfig.sourceOperationId;
138
- const entryPoint = operationId;
139
- const finalEntryPoint = (sourceOperationId ? sourceOperationId : operationId) + ((operation['x-whook'] || {}).suffix || '');
140
- log('warning', `Building ${operationType} "${finalEntryPoint}"...`);
141
- const buildDefinition = BUILD_DEFINITIONS[operationType]; // eslint-disable-next-line
142
-
143
- const applyWrapper = require(buildDefinition.wrapper.path).default;
144
-
145
- const rootNode = await $autoload(entryPoint + (buildDefinition.suffix || ''));
146
- const lambdaPath = path.join(PROJECT_DIR, 'builds', NODE_ENV, finalEntryPoint);
147
- const finalHandlerInitializer = applyWrapper(rootNode.initializer);
148
- const initializerContent = await buildInitializer(finalHandlerInitializer[SPECIAL_PROPS.INJECT].map(name => name === 'OPERATION_API' ? `OPERATION_API>OPERATION_API_${finalEntryPoint}` : name), BUILD_OPTIONS);
149
- const indexContent = await buildLambdaIndex(rootNode, {
150
- name: buildDefinition.wrapper.name,
151
- path: buildDefinition.wrapper.path
152
- }, BUILD_OPTIONS);
153
- await mkdirp(lambdaPath);
154
- await Promise.all([copyStaticFiles({
155
- PROJECT_DIR,
156
- log
157
- }, lambdaPath, whookConfig.staticFiles || []), ensureFileAsync({
158
- log
159
- }, path.join(lambdaPath, 'initialize.js'), initializerContent), ensureFileAsync({
160
- log
161
- }, path.join(lambdaPath, 'main.js'), indexContent)]);
162
- await buildFinalLambda({
163
- compiler,
164
- log
165
- }, lambdaPath, whookConfig);
166
- } catch (err) {
167
- log('error', `Error building "${operationId}"...`);
168
- log('error-stack', err.stack || 'no_stack_trace');
169
- log('debug', JSON.stringify(err.params, null, 2));
170
- throw YError.wrap(err, 'E_LAMBDA_BUILD', operationId);
171
- }
172
- }
173
-
174
- async function buildLambdaIndex(rootNode, buildWrapper, options) {
175
- return `${options.modules === 'commonjs' ? `const pickModule = (m) => { return m && m.default || m; }
176
- const initHandler = pickModule(require('${rootNode.path}'));
177
- const ${buildWrapper.name} = pickModule(require('${buildWrapper.path}'));
178
- const { initialize } = require('./initialize');` : `import initHandler from '${rootNode.path}';
179
- import ${buildWrapper.name} from '${buildWrapper.path}';
180
- import { initialize } from './initialize';`}
181
-
182
- const handlerInitializer = ${buildWrapper.name}(
183
- initHandler
184
- );
185
-
186
- const handlerPromise = initialize()
187
- .then(handlerInitializer);
188
-
189
- ${options.modules === 'commonjs' ? 'module.exports = {}; module.exports.default = ' : 'export default '}function handler (req, res) {
190
- return handlerPromise
191
- .then(handler => handler(req, res));
192
- };
193
- `;
194
- }
195
-
196
- async function buildFinalLambda({
197
- compiler,
198
- log
199
- }, lambdaPath, whookConfig) {
200
- const entryPoint = `${lambdaPath}/main.js`;
201
- const {
202
- contents,
203
- mappings
204
- } = await compiler(entryPoint, whookConfig.compilerOptions);
205
- await Promise.all([ensureFileAsync({
206
- log
207
- }, `${lambdaPath}/index.js`, contents, 'utf-8'), mappings ? ensureFileAsync({
208
- log
209
- }, `${lambdaPath}/index.js.map`, mappings, 'utf-8') : Promise.resolve()]);
210
- }
211
-
212
- async function copyStaticFiles({
213
- PROJECT_DIR,
214
- log
215
- }, lambdaPath, staticFiles = []) {
216
- await Promise.all(staticFiles.map(async staticFile => await copyFiles({
217
- log
218
- }, path.join(PROJECT_DIR, 'node_modules', staticFile), path.join(lambdaPath, 'node_modules', staticFile))));
219
- }
220
-
221
- async function copyFiles({
222
- log
223
- }, source, destination) {
224
- let theError;
225
-
226
- try {
227
- await mkdirp(destination);
228
- const data = await readFileAsync(source, 'utf-8');
229
- await ensureFileAsync({
230
- log
231
- }, destination, data, 'utf-8');
232
- } catch (err) {
233
- theError = err;
234
- }
235
-
236
- if (theError) {
237
- if ('EISDIR' !== theError.code) {
238
- throw theError;
239
- }
240
-
241
- await cprAsync(source, destination, {
242
- overwrite: true
243
- });
244
- }
245
- }
246
-
247
- async function ensureFileAsync({
248
- log
249
- }, path, content, encoding = 'utf-8') {
250
- try {
251
- const oldContent = await readFileAsync(path, encoding);
252
-
253
- if (oldContent === content) {
254
- log('debug', `Ignore unchanged file: "${path}".`);
255
- return;
256
- }
257
- } catch (err) {
258
- log('debug', `Write new file: "${path}".`);
259
- return await writeFileAsync(path, content, encoding);
260
- }
261
-
262
- log('debug', `Write changed file: "${path}".`);
263
- return await writeFileAsync(path, content, encoding);
264
- }
265
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["fs","util","path","mkdirp","cpr","YError","Knifecycle","SPECIAL_PROPS","constant","initInitializerBuilder","DEFAULT_BUILD_OPTIONS","initCompiler","initBuildAutoloader","dereferenceOpenAPIOperations","getOpenAPIOperations","DEFAULT_BUILD_PARALLELISM","readFileAsync","promisify","readFile","writeFileAsync","writeFile","cprAsync","BUILD_DEFINITIONS","http","type","wrapper","name","join","__dirname","suffix","prepareBuildEnvironment","$","register","ENV","log","time","delay","runBuild","aPrepareBuildEnvironment","handlerName","process","argv","NODE_ENV","BUILD_PARALLELISM","BUILD_OPTIONS","PROJECT_DIR","compiler","$autoload","API","buildInitializer","run","operations","filter","operation","sourceOperationId","operationId","length","processOperations","destroy","err","console","error","stack","JSON","stringify","params","exit","operationsLeft","slice","Promise","all","map","buildAnyLambda","whookConfig","operationType","entryPoint","finalEntryPoint","buildDefinition","applyWrapper","require","default","rootNode","lambdaPath","finalHandlerInitializer","initializer","initializerContent","INJECT","indexContent","buildLambdaIndex","copyStaticFiles","staticFiles","ensureFileAsync","buildFinalLambda","wrap","buildWrapper","options","modules","contents","mappings","compilerOptions","resolve","staticFile","copyFiles","source","destination","theError","data","code","overwrite","content","encoding","oldContent"],"sources":["../src/index.ts"],"sourcesContent":["/* eslint global-require:0 */\nimport fs from 'fs';\nimport util from 'util';\nimport path from 'path';\nimport mkdirp from 'mkdirp';\nimport cpr from 'cpr';\nimport YError from 'yerror';\nimport Knifecycle, {\n SPECIAL_PROPS,\n constant,\n initInitializerBuilder,\n} from 'knifecycle';\nimport { DEFAULT_BUILD_OPTIONS, initCompiler } from '@whook/whook';\nimport initBuildAutoloader from './services/_autoload';\nimport {\n dereferenceOpenAPIOperations,\n getOpenAPIOperations,\n} from '@whook/http-router';\nimport type {\n Autoloader,\n Dependencies,\n BuildInitializer,\n Initializer,\n Service,\n} from 'knifecycle';\nimport type {\n WhookOperation,\n WhookCompilerConfig,\n WhookCompilerOptions,\n WhookCompilerService,\n} from '@whook/whook';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { LogService } from 'common-services';\nimport type { CprOptions } from 'cpr';\n\nexport const DEFAULT_BUILD_PARALLELISM = 10;\n\nexport type WhookGCPBuildConfig = {\n BUILD_PARALLELISM?: number;\n};\nexport type WhookAPIOperationGCPFunctionConfig = {\n type?: 'http';\n sourceOperationId?: string;\n staticFiles?: string[];\n compilerOptions?: WhookCompilerOptions;\n suffix?: string;\n};\n\nconst readFileAsync = util.promisify(fs.readFile) as (\n path: string,\n encoding: string,\n) => Promise<string>;\nconst writeFileAsync = util.promisify(fs.writeFile) as (\n path: string,\n content: string,\n encoding: string,\n) => Promise<void>;\nconst cprAsync = util.promisify(cpr) as (\n source: string,\n destination: string,\n options: CprOptions,\n) => Promise<string[]>;\n\nconst BUILD_DEFINITIONS: Record<\n NonNullable<WhookAPIOperationGCPFunctionConfig['type']>,\n {\n type: string;\n wrapper: { name: string; path: string };\n suffix?: string;\n }\n> = {\n http: {\n type: 'HTTP',\n wrapper: {\n name: 'wrapHandlerForGoogleHTTPFunction',\n path: path.join(__dirname, 'wrappers', 'googleHTTPFunction'),\n },\n suffix: 'Wrapped',\n },\n};\n\nexport async function prepareBuildEnvironment<T extends Knifecycle>(\n $: T = new Knifecycle() as T,\n): Promise<T> {\n $.register(\n constant('INITIALIZER_PATH_MAP', {\n ENV: '@whook/whook/dist/services/ProxyedENV',\n log: __dirname + '/services/log',\n time: 'common-services/dist/time',\n delay: 'common-services/dist/delay',\n }),\n );\n $.register(initInitializerBuilder);\n $.register(initBuildAutoloader);\n $.register(initCompiler);\n $.register(constant('PORT', 1337));\n $.register(constant('HOST', 'localhost'));\n\n return $;\n}\n\nexport async function runBuild(\n aPrepareBuildEnvironment: typeof prepareBuildEnvironment,\n): Promise<void> {\n try {\n const handlerName = process.argv[2];\n const $ = await aPrepareBuildEnvironment();\n const {\n NODE_ENV,\n BUILD_PARALLELISM,\n BUILD_OPTIONS,\n PROJECT_DIR,\n compiler,\n log,\n $autoload,\n API,\n buildInitializer,\n }: WhookGCPBuildConfig &\n Pick<WhookCompilerConfig, 'BUILD_OPTIONS'> & {\n NODE_ENV: string;\n PROJECT_DIR: string;\n compiler: WhookCompilerService;\n log: LogService;\n $autoload: Autoloader<Initializer<Dependencies, Service>>;\n API: OpenAPIV3.Document;\n buildInitializer: BuildInitializer;\n } = await $.run([\n 'NODE_ENV',\n '?BUILD_PARALLELISM',\n '?BUILD_OPTIONS',\n 'PROJECT_DIR',\n 'process',\n 'compiler',\n 'log',\n '$autoload',\n 'API',\n 'buildInitializer',\n ]);\n\n log('info', 'GCP Functions build Environment initialized 🚀🌕');\n\n const operations = (\n await dereferenceOpenAPIOperations(\n API,\n getOpenAPIOperations<WhookAPIOperationGCPFunctionConfig>(API),\n )\n ).filter((operation) => {\n if (handlerName) {\n const sourceOperationId =\n operation['x-whook'] && operation['x-whook'].sourceOperationId;\n\n return (\n handlerName === operation.operationId ||\n handlerName === sourceOperationId\n );\n }\n return true;\n });\n\n log('warning', `${operations.length} operations to process.`);\n await processOperations(\n {\n NODE_ENV,\n BUILD_OPTIONS: BUILD_OPTIONS || DEFAULT_BUILD_OPTIONS,\n BUILD_PARALLELISM: BUILD_PARALLELISM || DEFAULT_BUILD_PARALLELISM,\n PROJECT_DIR,\n compiler,\n log,\n $autoload,\n buildInitializer,\n },\n operations,\n );\n await $.destroy();\n } catch (err) {\n // eslint-disable-next-line\n console.error(\n '💀 - Cannot launch the build:',\n (err as YError).stack,\n JSON.stringify((err as YError).params, null, 2),\n );\n process.exit(1);\n }\n}\n\nasync function processOperations(\n {\n NODE_ENV,\n BUILD_PARALLELISM,\n BUILD_OPTIONS,\n PROJECT_DIR,\n compiler,\n log,\n $autoload,\n buildInitializer,\n }: Required<Pick<WhookCompilerConfig, 'BUILD_OPTIONS'>> & {\n NODE_ENV: string;\n BUILD_PARALLELISM: number;\n PROJECT_DIR: string;\n compiler: WhookCompilerService;\n log: LogService;\n $autoload: Autoloader<Initializer<Dependencies, Service>>;\n buildInitializer: BuildInitializer;\n },\n operations: WhookOperation<WhookAPIOperationGCPFunctionConfig>[],\n): Promise<void> {\n const operationsLeft = operations.slice(BUILD_PARALLELISM);\n\n await Promise.all(\n operations.slice(0, BUILD_PARALLELISM).map((operation) =>\n buildAnyLambda(\n {\n NODE_ENV,\n PROJECT_DIR,\n BUILD_OPTIONS,\n compiler,\n log,\n $autoload,\n buildInitializer,\n },\n operation,\n ),\n ),\n );\n\n if (operationsLeft.length) {\n log('info', operationsLeft.length, ' operations left.');\n return processOperations(\n {\n NODE_ENV,\n BUILD_PARALLELISM,\n BUILD_OPTIONS,\n PROJECT_DIR,\n compiler,\n log,\n $autoload,\n buildInitializer,\n },\n operationsLeft,\n );\n }\n log('info', 'No more operations.');\n}\n\nasync function buildAnyLambda(\n {\n NODE_ENV,\n PROJECT_DIR,\n BUILD_OPTIONS,\n compiler,\n log,\n $autoload,\n buildInitializer,\n }: Required<Pick<WhookCompilerConfig, 'BUILD_OPTIONS'>> & {\n NODE_ENV: string;\n PROJECT_DIR: string;\n compiler: WhookCompilerService;\n log: LogService;\n $autoload: Autoloader<Initializer<Dependencies, Service>>;\n buildInitializer: BuildInitializer;\n },\n operation: WhookOperation<WhookAPIOperationGCPFunctionConfig>,\n): Promise<void> {\n const { operationId } = operation;\n\n try {\n const whookConfig: WhookAPIOperationGCPFunctionConfig =\n operation['x-whook'] || {};\n const operationType = whookConfig.type || 'http';\n const sourceOperationId = whookConfig.sourceOperationId;\n const entryPoint = operationId;\n const finalEntryPoint =\n (sourceOperationId ? sourceOperationId : operationId) +\n ((operation['x-whook'] || {}).suffix || '');\n log('warning', `Building ${operationType} \"${finalEntryPoint}\"...`);\n const buildDefinition = BUILD_DEFINITIONS[operationType];\n // eslint-disable-next-line\n const applyWrapper = require(buildDefinition.wrapper.path).default;\n const rootNode = await $autoload(\n entryPoint + (buildDefinition.suffix || ''),\n );\n const lambdaPath = path.join(\n PROJECT_DIR,\n 'builds',\n NODE_ENV,\n finalEntryPoint,\n );\n const finalHandlerInitializer = applyWrapper(rootNode.initializer);\n\n const initializerContent = await buildInitializer(\n finalHandlerInitializer[SPECIAL_PROPS.INJECT].map((name) =>\n name === 'OPERATION_API'\n ? `OPERATION_API>OPERATION_API_${finalEntryPoint}`\n : name,\n ),\n BUILD_OPTIONS,\n );\n const indexContent = await buildLambdaIndex(\n rootNode,\n {\n name: buildDefinition.wrapper.name,\n path: buildDefinition.wrapper.path,\n },\n BUILD_OPTIONS,\n );\n\n await mkdirp(lambdaPath);\n await Promise.all([\n copyStaticFiles(\n { PROJECT_DIR, log },\n lambdaPath,\n whookConfig.staticFiles || [],\n ),\n ensureFileAsync(\n { log },\n path.join(lambdaPath, 'initialize.js'),\n initializerContent,\n ),\n ensureFileAsync({ log }, path.join(lambdaPath, 'main.js'), indexContent),\n ]);\n await buildFinalLambda({ compiler, log }, lambdaPath, whookConfig);\n } catch (err) {\n log('error', `Error building \"${operationId}\"...`);\n log('error-stack', (err as Error).stack || 'no_stack_trace');\n log('debug', JSON.stringify((err as YError).params, null, 2));\n throw YError.wrap(err as Error, 'E_LAMBDA_BUILD', operationId);\n }\n}\n\nasync function buildLambdaIndex(\n rootNode: { path: string },\n buildWrapper: { name: string; path: string },\n options: NonNullable<WhookCompilerConfig['BUILD_OPTIONS']>,\n): Promise<string> {\n return `${\n options.modules === 'commonjs'\n ? `const pickModule = (m) => { return m && m.default || m; }\nconst initHandler = pickModule(require('${rootNode.path}'));\nconst ${buildWrapper.name} = pickModule(require('${buildWrapper.path}'));\nconst { initialize } = require('./initialize');`\n : `import initHandler from '${rootNode.path}';\nimport ${buildWrapper.name} from '${buildWrapper.path}';\nimport { initialize } from './initialize';`\n }\n\nconst handlerInitializer = ${buildWrapper.name}(\n initHandler\n);\n\nconst handlerPromise = initialize()\n .then(handlerInitializer);\n\n${\n options.modules === 'commonjs'\n ? 'module.exports = {}; module.exports.default = '\n : 'export default '\n}function handler (req, res) {\n return handlerPromise\n .then(handler => handler(req, res));\n};\n`;\n}\n\nasync function buildFinalLambda(\n { compiler, log }: { compiler: WhookCompilerService; log: LogService },\n lambdaPath: string,\n whookConfig: WhookAPIOperationGCPFunctionConfig,\n): Promise<void> {\n const entryPoint = `${lambdaPath}/main.js`;\n const { contents, mappings } = await compiler(\n entryPoint,\n whookConfig.compilerOptions,\n );\n\n await Promise.all([\n ensureFileAsync({ log }, `${lambdaPath}/index.js`, contents, 'utf-8'),\n mappings\n ? ensureFileAsync(\n { log },\n `${lambdaPath}/index.js.map`,\n mappings,\n 'utf-8',\n )\n : Promise.resolve(),\n ]);\n}\n\nasync function copyStaticFiles(\n { PROJECT_DIR, log }: { PROJECT_DIR: string; log: LogService },\n lambdaPath: string,\n staticFiles: string[] = [],\n): Promise<void> {\n await Promise.all(\n staticFiles.map(\n async (staticFile) =>\n await copyFiles(\n { log },\n path.join(PROJECT_DIR, 'node_modules', staticFile),\n path.join(lambdaPath, 'node_modules', staticFile),\n ),\n ),\n );\n}\n\nasync function copyFiles(\n { log }: { log: LogService },\n source: string,\n destination: string,\n): Promise<void> {\n let theError;\n try {\n await mkdirp(destination);\n const data = await readFileAsync(source, 'utf-8');\n await ensureFileAsync({ log }, destination, data, 'utf-8');\n } catch (err) {\n theError = err;\n }\n if (theError) {\n if ('EISDIR' !== theError.code) {\n throw theError;\n }\n await cprAsync(source, destination, {\n overwrite: true,\n });\n }\n}\n\nasync function ensureFileAsync(\n { log }: { log: LogService },\n path: string,\n content: string,\n encoding = 'utf-8',\n): Promise<void> {\n try {\n const oldContent = await readFileAsync(path, encoding);\n\n if (oldContent === content) {\n log('debug', `Ignore unchanged file: \"${path}\".`);\n return;\n }\n } catch (err) {\n log('debug', `Write new file: \"${path}\".`);\n return await writeFileAsync(path, content, encoding);\n }\n log('debug', `Write changed file: \"${path}\".`);\n return await writeFileAsync(path, content, encoding);\n}\n"],"mappings":"AAAA;AACA,OAAOA,EAAP,MAAe,IAAf;AACA,OAAOC,IAAP,MAAiB,MAAjB;AACA,OAAOC,IAAP,MAAiB,MAAjB;AACA,OAAOC,MAAP,MAAmB,QAAnB;AACA,OAAOC,GAAP,MAAgB,KAAhB;AACA,OAAOC,MAAP,MAAmB,QAAnB;AACA,OAAOC,UAAP,IACEC,aADF,EAEEC,QAFF,EAGEC,sBAHF,QAIO,YAJP;AAKA,SAASC,qBAAT,EAAgCC,YAAhC,QAAoD,cAApD;AACA,OAAOC,mBAAP,MAAgC,sBAAhC;AACA,SACEC,4BADF,EAEEC,oBAFF,QAGO,oBAHP;AAqBA,OAAO,MAAMC,yBAAyB,GAAG,EAAlC;AAaP,MAAMC,aAAa,GAAGf,IAAI,CAACgB,SAAL,CAAejB,EAAE,CAACkB,QAAlB,CAAtB;AAIA,MAAMC,cAAc,GAAGlB,IAAI,CAACgB,SAAL,CAAejB,EAAE,CAACoB,SAAlB,CAAvB;AAKA,MAAMC,QAAQ,GAAGpB,IAAI,CAACgB,SAAL,CAAeb,GAAf,CAAjB;AAMA,MAAMkB,iBAOL,GAAG;EACFC,IAAI,EAAE;IACJC,IAAI,EAAE,MADF;IAEJC,OAAO,EAAE;MACPC,IAAI,EAAE,kCADC;MAEPxB,IAAI,EAAEA,IAAI,CAACyB,IAAL,CAAUC,SAAV,EAAqB,UAArB,EAAiC,oBAAjC;IAFC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D;;IACD,MAAMpF,QAAQ,CAACkF,MAAD,EAASC,WAAT,EAAsB;MAClCI,SAAS,EAAE;IADuB,CAAtB,CAAd;EAGD;AACF;;AAED,eAAejB,eAAf,CACE;EAAEzD;AAAF,CADF,EAEEhC,IAFF,EAGE2G,OAHF,EAIEC,QAAQ,GAAG,OAJb,EAKiB;EACf,IAAI;IACF,MAAMC,UAAU,GAAG,MAAM/F,aAAa,CAACd,IAAD,EAAO4G,QAAP,CAAtC;;IAEA,IAAIC,UAAU,KAAKF,OAAnB,EAA4B;MAC1B3E,GAAG,CAAC,OAAD,EAAW,2BAA0BhC,IAAK,IAA1C,CAAH;MACA;IACD;EACF,CAPD,CAOE,OAAOyD,GAAP,EAAY;IACZzB,GAAG,CAAC,OAAD,EAAW,oBAAmBhC,IAAK,IAAnC,CAAH;IACA,OAAO,MAAMiB,cAAc,CAACjB,IAAD,EAAO2G,OAAP,EAAgBC,QAAhB,CAA3B;EACD;;EACD5E,GAAG,CAAC,OAAD,EAAW,wBAAuBhC,IAAK,IAAvC,CAAH;EACA,OAAO,MAAMiB,cAAc,CAACjB,IAAD,EAAO2G,OAAP,EAAgBC,QAAhB,CAA3B;AACD"}
@@ -1,27 +0,0 @@
1
- import YError from 'yerror';
2
- import path from 'path';
3
- export async function loadLambda({
4
- PROJECT_DIR,
5
- log
6
- }, target, operationId, type) {
7
- const modulePath = path.join(PROJECT_DIR, 'builds', target, operationId, type);
8
- log('debug', `⛏️ - Loading lambda module at path "${modulePath}".`);
9
-
10
- try {
11
- // eslint-disable-next-line
12
- const module = require(modulePath);
13
-
14
- if (!module) {
15
- throw new YError('E_MODULE_NOT_FOUND', module);
16
- }
17
-
18
- if (!module.default) {
19
- throw new YError('E_LAMBDA_NOT_FOUND', module, Object.keys(module));
20
- }
21
-
22
- return module.default;
23
- } catch (err) {
24
- throw YError.wrap(err, 'E_LAMBDA_LOAD');
25
- }
26
- }
27
- //# sourceMappingURL=utils.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.mjs","names":["YError","path","loadLambda","PROJECT_DIR","log","target","operationId","type","modulePath","join","module","require","default","Object","keys","err","wrap"],"sources":["../../src/libs/utils.ts"],"sourcesContent":["import YError from 'yerror';\nimport path from 'path';\nimport type { LogService } from 'common-services';\n\nexport async function loadLambda(\n {\n PROJECT_DIR,\n log,\n }: {\n PROJECT_DIR: string;\n log: LogService;\n },\n target: string,\n operationId: string,\n type: string,\n): Promise<any> {\n const modulePath = path.join(\n PROJECT_DIR,\n 'builds',\n target,\n operationId,\n type,\n );\n\n log('debug', `⛏️ - Loading lambda module at path \"${modulePath}\".`);\n\n try {\n // eslint-disable-next-line\n const module = require(modulePath);\n\n if (!module) {\n throw new YError('E_MODULE_NOT_FOUND', module);\n }\n\n if (!module.default) {\n throw new YError('E_LAMBDA_NOT_FOUND', module, Object.keys(module));\n }\n\n return module.default;\n } catch (err) {\n throw YError.wrap(err as Error, 'E_LAMBDA_LOAD');\n }\n}\n"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,QAAnB;AACA,OAAOC,IAAP,MAAiB,MAAjB;AAGA,OAAO,eAAeC,UAAf,CACL;EACEC,WADF;EAEEC;AAFF,CADK,EAQLC,MARK,EASLC,WATK,EAULC,IAVK,EAWS;EACd,MAAMC,UAAU,GAAGP,IAAI,CAACQ,IAAL,CACjBN,WADiB,EAEjB,QAFiB,EAGjBE,MAHiB,EAIjBC,WAJiB,EAKjBC,IALiB,CAAnB;EAQAH,GAAG,CAAC,OAAD,EAAW,uCAAsCI,UAAW,IAA5D,CAAH;;EAEA,IAAI;IACF;IACA,MAAME,MAAM,GAAGC,OAAO,CAACH,UAAD,CAAtB;;IAEA,IAAI,CAACE,MAAL,EAAa;MACX,MAAM,IAAIV,MAAJ,CAAW,oBAAX,EAAiCU,MAAjC,CAAN;IACD;;IAED,IAAI,CAACA,MAAM,CAACE,OAAZ,EAAqB;MACnB,MAAM,IAAIZ,MAAJ,CAAW,oBAAX,EAAiCU,MAAjC,EAAyCG,MAAM,CAACC,IAAP,CAAYJ,MAAZ,CAAzC,CAAN;IACD;;IAED,OAAOA,MAAM,CAACE,OAAd;EACD,CAbD,CAaE,OAAOG,GAAP,EAAY;IACZ,MAAMf,MAAM,CAACgB,IAAP,CAAYD,GAAZ,EAA0B,eAA1B,CAAN;EACD;AACF"}
@@ -1,113 +0,0 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
- import { initAutoload, noop, cleanupOpenAPI } from '@whook/whook';
8
- import { SPECIAL_PROPS, wrapInitializer, constant, alsoInject } from 'knifecycle';
9
- import YError from 'yerror';
10
- import { dereferenceOpenAPIOperations, getOpenAPIOperations } from '@whook/http-router';
11
-
12
- const initializerWrapper = async ({
13
- BUILD_CONSTANTS = {},
14
- $injector,
15
- $instance,
16
- log = noop
17
- }, $autoload) => {
18
- let API;
19
- let OPERATION_APIS;
20
-
21
- const getAPIOperation = (() => {
22
- return async serviceName => {
23
- var _API$paths$OPERATION$, _OPERATION_API$paths$;
24
-
25
- // eslint-disable-next-line
26
- API = API || (await $injector(['API'])).API; // eslint-disable-next-line
27
-
28
- OPERATION_APIS = OPERATION_APIS || getOpenAPIOperations(API);
29
- const OPERATION = OPERATION_APIS.find(operation => serviceName === ((operation['x-whook'] || {}).sourceOperationId && 'OPERATION_API_' + (operation['x-whook'] || {}).sourceOperationId || 'OPERATION_API_' + operation.operationId) + ((operation['x-whook'] || {}).suffix || ''));
30
-
31
- if (!OPERATION) {
32
- log('error', '💥 - Unable to find a lambda operation definition!');
33
- throw new YError('E_OPERATION_NOT_FOUND', serviceName);
34
- } // eslint-disable-next-line
35
-
36
-
37
- const OPERATION_API = cleanupOpenAPI(_objectSpread(_objectSpread({}, API), {}, {
38
- paths: {
39
- [OPERATION.path]: {
40
- [OPERATION.method]: (_API$paths$OPERATION$ = API.paths[OPERATION.path]) === null || _API$paths$OPERATION$ === void 0 ? void 0 : _API$paths$OPERATION$[OPERATION.method]
41
- }
42
- }
43
- }));
44
- return _objectSpread(_objectSpread({}, OPERATION_API), {}, {
45
- paths: {
46
- [OPERATION.path]: {
47
- [OPERATION.method]: (await dereferenceOpenAPIOperations(OPERATION_API, [_objectSpread(_objectSpread({
48
- path: OPERATION.path,
49
- method: OPERATION.method
50
- }, (_OPERATION_API$paths$ = OPERATION_API.paths[OPERATION.path]) === null || _OPERATION_API$paths$ === void 0 ? void 0 : _OPERATION_API$paths$[OPERATION.method]), {}, {
51
- parameters: OPERATION.parameters
52
- })]))[0]
53
- }
54
- }
55
- });
56
- };
57
- })();
58
-
59
- log('debug', '🤖 - Initializing the `$autoload` build wrapper.');
60
- return async serviceName => {
61
- try {
62
- // TODO: add initializer map to knifecycle public API
63
- const initializer = $instance._initializers.get(serviceName);
64
-
65
- if (initializer && initializer[SPECIAL_PROPS.TYPE] === 'constant') {
66
- log('debug', `🤖 - Reusing a constant initializer directly from the Knifecycle instance: "${serviceName}".`);
67
- return {
68
- initializer,
69
- path: `instance://${serviceName}`
70
- };
71
- }
72
-
73
- if (serviceName.startsWith('OPERATION_API_')) {
74
- const OPERATION_API = await getAPIOperation(serviceName);
75
- return {
76
- initializer: constant(serviceName, OPERATION_API),
77
- path: `api://${serviceName}`
78
- };
79
- }
80
-
81
- if (BUILD_CONSTANTS[serviceName]) {
82
- return {
83
- initializer: constant(serviceName, BUILD_CONSTANTS[serviceName]),
84
- path: `constant://${serviceName}`
85
- };
86
- }
87
-
88
- return $autoload(serviceName);
89
- } catch (err) {
90
- log('error', `Build error while loading "${serviceName}".`);
91
- log('error-stack', err.stack || 'no_stack_trace');
92
- throw err;
93
- }
94
- };
95
- };
96
- /**
97
- * Wrap the _autoload service in order to build AWS
98
- * Lambda compatible code.
99
- * @param {Object} services
100
- * The services ENV depends on
101
- * @param {Object} services.NODE_ENV
102
- * The injected NODE_ENV value to add it to the build env
103
- * @param {Object} [services.PROXYED_ENV_VARS={}]
104
- * A list of environment variable names to proxy
105
- * @param {Object} [services.log=noop]
106
- * An optional logging service
107
- * @return {Promise<Object>}
108
- * A promise of an object containing the reshaped env vars.
109
- */
110
-
111
-
112
- export default alsoInject(['?BUILD_CONSTANTS', '$instance', '$injector', '?log'], wrapInitializer(initializerWrapper, initAutoload));
113
- //# sourceMappingURL=_autoload.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"_autoload.mjs","names":["initAutoload","noop","cleanupOpenAPI","SPECIAL_PROPS","wrapInitializer","constant","alsoInject","YError","dereferenceOpenAPIOperations","getOpenAPIOperations","initializerWrapper","BUILD_CONSTANTS","$injector","$instance","log","$autoload","API","OPERATION_APIS","getAPIOperation","serviceName","OPERATION","find","operation","sourceOperationId","operationId","suffix","OPERATION_API","paths","path","method","parameters","initializer","_initializers","get","TYPE","startsWith","err","stack"],"sources":["../../src/services/_autoload.ts"],"sourcesContent":["import { initAutoload, noop, cleanupOpenAPI } from '@whook/whook';\nimport Knifecycle, {\n SPECIAL_PROPS,\n wrapInitializer,\n constant,\n alsoInject,\n} from 'knifecycle';\nimport YError from 'yerror';\nimport {\n dereferenceOpenAPIOperations,\n getOpenAPIOperations,\n} from '@whook/http-router';\nimport type {\n Injector,\n Autoloader,\n Initializer,\n Dependencies,\n Service,\n ServiceInitializerWrapper,\n} from 'knifecycle';\nimport type { WhookBuildConstantsService } from '@whook/whook';\nimport type { WhookRawOperation } from '@whook/http-router';\nimport type { LogService } from 'common-services';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { WhookAPIOperationGCPFunctionConfig } from '..';\n\nconst initializerWrapper: ServiceInitializerWrapper<\n Autoloader<Initializer<Dependencies, Service>>,\n Dependencies\n> = (async (\n {\n BUILD_CONSTANTS = {},\n $injector,\n $instance,\n log = noop,\n }: {\n BUILD_CONSTANTS?: WhookBuildConstantsService;\n $injector: Injector<Service>;\n $instance: Knifecycle;\n log: LogService;\n },\n $autoload: Autoloader<Initializer<Dependencies, Service>>,\n): Promise<\n (serviceName: string) => Promise<{\n initializer: Initializer<Dependencies, Service>;\n path: string;\n }>\n> => {\n let API: OpenAPIV3.Document;\n let OPERATION_APIS: WhookRawOperation<WhookAPIOperationGCPFunctionConfig>[];\n const getAPIOperation = (() => {\n return async (serviceName) => {\n // eslint-disable-next-line\n API = API || (await $injector(['API'])).API;\n // eslint-disable-next-line\n OPERATION_APIS =\n OPERATION_APIS ||\n getOpenAPIOperations<WhookAPIOperationGCPFunctionConfig>(API);\n\n const OPERATION = OPERATION_APIS.find(\n (operation) =>\n serviceName ===\n (((operation['x-whook'] || {}).sourceOperationId &&\n 'OPERATION_API_' +\n (operation['x-whook'] || {}).sourceOperationId) ||\n 'OPERATION_API_' + operation.operationId) +\n ((operation['x-whook'] || {}).suffix || ''),\n );\n\n if (!OPERATION) {\n log('error', '💥 - Unable to find a lambda operation definition!');\n throw new YError('E_OPERATION_NOT_FOUND', serviceName);\n }\n\n // eslint-disable-next-line\n const OPERATION_API = cleanupOpenAPI({\n ...API,\n paths: {\n [OPERATION.path]: {\n [OPERATION.method]: API.paths[OPERATION.path]?.[OPERATION.method],\n },\n },\n });\n\n return {\n ...OPERATION_API,\n paths: {\n [OPERATION.path]: {\n [OPERATION.method]: (\n await dereferenceOpenAPIOperations(OPERATION_API, [\n {\n path: OPERATION.path,\n method: OPERATION.method,\n ...OPERATION_API.paths[OPERATION.path]?.[OPERATION.method],\n parameters: OPERATION.parameters,\n },\n ])\n )[0],\n },\n },\n };\n };\n })();\n\n log('debug', '🤖 - Initializing the `$autoload` build wrapper.');\n\n return async (serviceName) => {\n try {\n // TODO: add initializer map to knifecycle public API\n const initializer = ($instance as any)._initializers.get(serviceName);\n\n if (initializer && initializer[SPECIAL_PROPS.TYPE] === 'constant') {\n log(\n 'debug',\n `🤖 - Reusing a constant initializer directly from the Knifecycle instance: \"${serviceName}\".`,\n );\n return {\n initializer,\n path: `instance://${serviceName}`,\n };\n }\n\n if (serviceName.startsWith('OPERATION_API_')) {\n const OPERATION_API = await getAPIOperation(serviceName);\n\n return {\n initializer: constant(serviceName, OPERATION_API),\n path: `api://${serviceName}`,\n };\n }\n\n if (BUILD_CONSTANTS[serviceName]) {\n return {\n initializer: constant(serviceName, BUILD_CONSTANTS[serviceName]),\n path: `constant://${serviceName}`,\n };\n }\n\n return $autoload(serviceName);\n } catch (err) {\n log('error', `Build error while loading \"${serviceName}\".`);\n log('error-stack', (err as Error).stack || 'no_stack_trace');\n throw err;\n }\n };\n}) as any;\n\n/**\n * Wrap the _autoload service in order to build AWS\n * Lambda compatible code.\n * @param {Object} services\n * The services ENV depends on\n * @param {Object} services.NODE_ENV\n * The injected NODE_ENV value to add it to the build env\n * @param {Object} [services.PROXYED_ENV_VARS={}]\n * A list of environment variable names to proxy\n * @param {Object} [services.log=noop]\n * An optional logging service\n * @return {Promise<Object>}\n * A promise of an object containing the reshaped env vars.\n */\nexport default alsoInject(\n ['?BUILD_CONSTANTS', '$instance', '$injector', '?log'],\n wrapInitializer(initializerWrapper as any, initAutoload),\n);\n"],"mappings":";;;;;;AAAA,SAASA,YAAT,EAAuBC,IAAvB,EAA6BC,cAA7B,QAAmD,cAAnD;AACA,SACEC,aADF,EAEEC,eAFF,EAGEC,QAHF,EAIEC,UAJF,QAKO,YALP;AAMA,OAAOC,M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AAD,EAAcR,eAAe,CAACQ,WAAD,CAA7B,CADhB;UAELS,IAAI,EAAG,cAAaT,WAAY;QAF3B,CAAP;MAID;;MAED,OAAOJ,SAAS,CAACI,WAAD,CAAhB;IACD,CAhCD,CAgCE,OAAOiB,GAAP,EAAY;MACZtB,GAAG,CAAC,OAAD,EAAW,8BAA6BK,WAAY,IAApD,CAAH;MACAL,GAAG,CAAC,aAAD,EAAiBsB,GAAD,CAAeC,KAAf,IAAwB,gBAAxC,CAAH;MACA,MAAMD,GAAN;IACD;EACF,CAtCD;AAuCD,CAvHD;AAyHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,eAAe9B,UAAU,CACvB,CAAC,kBAAD,EAAqB,WAArB,EAAkC,WAAlC,EAA+C,MAA/C,CADuB,EAEvBF,eAAe,CAACM,kBAAD,EAA4BV,YAA5B,CAFQ,CAAzB"}
@@ -1,4 +0,0 @@
1
- import { service } from 'knifecycle'; // eslint-disable-next-line
2
-
3
- export default service(async () => console.log.bind(console), 'log');
4
- //# sourceMappingURL=log.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"log.mjs","names":["service","console","log","bind"],"sources":["../../src/services/log.ts"],"sourcesContent":["import { service } from 'knifecycle';\n\n// eslint-disable-next-line\nexport default service(async () => console.log.bind(console), 'log');\n"],"mappings":"AAAA,SAASA,OAAT,QAAwB,YAAxB,C,CAEA;;AACA,eAAeA,OAAO,CAAC,YAAYC,OAAO,CAACC,GAAR,CAAYC,IAAZ,CAAiBF,OAAjB,CAAb,EAAwC,KAAxC,CAAtB"}