@gugananuvem/aws-local-simulator 1.0.15 → 1.0.16

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 (77) hide show
  1. package/README.md +789 -594
  2. package/bin/aws-local-simulator.js +63 -63
  3. package/package.json +2 -2
  4. package/src/config/config-loader.js +114 -114
  5. package/src/config/default-config.js +68 -68
  6. package/src/config/env-loader.js +68 -68
  7. package/src/index.js +146 -146
  8. package/src/index.mjs +123 -123
  9. package/src/server.js +227 -227
  10. package/src/services/apigateway/index.js +75 -73
  11. package/src/services/apigateway/server.js +570 -507
  12. package/src/services/apigateway/simulator.js +1261 -1261
  13. package/src/services/athena/index.js +75 -75
  14. package/src/services/athena/server.js +101 -101
  15. package/src/services/athena/simulador.js +998 -998
  16. package/src/services/athena/simulator.js +346 -346
  17. package/src/services/cloudformation/index.js +106 -106
  18. package/src/services/cloudformation/server.js +417 -417
  19. package/src/services/cloudformation/simulador.js +1045 -1045
  20. package/src/services/cloudtrail/index.js +84 -84
  21. package/src/services/cloudtrail/server.js +235 -235
  22. package/src/services/cloudtrail/simulador.js +719 -719
  23. package/src/services/cloudwatch/index.js +84 -84
  24. package/src/services/cloudwatch/server.js +366 -366
  25. package/src/services/cloudwatch/simulador.js +1173 -1173
  26. package/src/services/cognito/index.js +79 -79
  27. package/src/services/cognito/server.js +301 -301
  28. package/src/services/cognito/simulator.js +1655 -1655
  29. package/src/services/config/index.js +96 -96
  30. package/src/services/config/server.js +215 -215
  31. package/src/services/config/simulador.js +1260 -1260
  32. package/src/services/dynamodb/index.js +74 -74
  33. package/src/services/dynamodb/server.js +125 -125
  34. package/src/services/dynamodb/simulator.js +630 -630
  35. package/src/services/ecs/index.js +65 -65
  36. package/src/services/ecs/server.js +235 -235
  37. package/src/services/ecs/simulator.js +844 -844
  38. package/src/services/eventbridge/index.js +89 -89
  39. package/src/services/eventbridge/server.js +209 -209
  40. package/src/services/eventbridge/simulator.js +684 -684
  41. package/src/services/index.js +45 -45
  42. package/src/services/kms/index.js +75 -75
  43. package/src/services/kms/server.js +67 -67
  44. package/src/services/kms/simulator.js +324 -324
  45. package/src/services/lambda/handler-loader.js +183 -183
  46. package/src/services/lambda/index.js +78 -78
  47. package/src/services/lambda/route-registry.js +274 -274
  48. package/src/services/lambda/server.js +145 -145
  49. package/src/services/lambda/simulator.js +199 -199
  50. package/src/services/parameter-store/index.js +80 -80
  51. package/src/services/parameter-store/server.js +50 -50
  52. package/src/services/parameter-store/simulator.js +201 -201
  53. package/src/services/s3/index.js +73 -73
  54. package/src/services/s3/server.js +329 -329
  55. package/src/services/s3/simulator.js +565 -565
  56. package/src/services/secret-manager/index.js +80 -80
  57. package/src/services/secret-manager/server.js +50 -50
  58. package/src/services/secret-manager/simulator.js +171 -171
  59. package/src/services/sns/index.js +89 -89
  60. package/src/services/sns/server.js +580 -580
  61. package/src/services/sns/simulator.js +1482 -1482
  62. package/src/services/sqs/index.js +98 -93
  63. package/src/services/sqs/server.js +349 -349
  64. package/src/services/sqs/simulator.js +441 -441
  65. package/src/services/sts/index.js +37 -37
  66. package/src/services/sts/server.js +144 -144
  67. package/src/services/sts/simulator.js +69 -69
  68. package/src/services/xray/index.js +83 -83
  69. package/src/services/xray/server.js +308 -308
  70. package/src/services/xray/simulador.js +994 -994
  71. package/src/template/aws-config-template.js +87 -87
  72. package/src/template/aws-config-template.mjs +90 -90
  73. package/src/template/config-template.json +203 -203
  74. package/src/utils/aws-config.js +91 -91
  75. package/src/utils/cloudtrail-audit.js +129 -129
  76. package/src/utils/local-store.js +83 -83
  77. package/src/utils/logger.js +59 -59
@@ -1,199 +1,199 @@
1
- /**
2
- * Lambda Simulator - Simula execução de funções Lambda
3
- */
4
-
5
- const HandlerLoader = require("./handler-loader");
6
- const logger = require("../../utils/logger");
7
- const { CloudTrailAudit } = require("../../utils/cloudtrail-audit");
8
-
9
- class LambdaSimulator {
10
- constructor(config) {
11
- this.config = config;
12
- this.lambdas = new Map(); // functionName -> { handler, env, config }
13
- this.environment = { ...process.env };
14
- this.audit = new CloudTrailAudit("lambda.amazonaws.com");
15
- }
16
-
17
- async initialize() {
18
- logger.debug("Inicializando Lambda Simulator...");
19
-
20
- // Build global lambda defaults from config.global
21
- const globalDefaults = this.config.global || {};
22
- this.globalEnv = globalDefaults.env || {};
23
- this.globalTimeout = globalDefaults.timeout || null;
24
- this.globalMemorySize = globalDefaults.memorySize || null;
25
-
26
- if (this.config.lambdas && this.config.lambdas.length > 0) {
27
- for (const lambdaConfig of this.config.lambdas) {
28
- await this.registerLambda(lambdaConfig);
29
- }
30
- }
31
-
32
- logger.debug(`✅ ${this.lambdas.size} Lambdas registradas`);
33
- }
34
-
35
- async registerLambda(lambdaConfig) {
36
- try {
37
- const { name, handler: handlerPath, type = "auto" } = lambdaConfig;
38
-
39
- if (!name) {
40
- logger.warn(`Lambda sem nome ignorada: ${JSON.stringify(lambdaConfig)}`);
41
- return;
42
- }
43
-
44
- // Merge: global env as base, lambda-specific env overrides
45
- const env = {
46
- ...(this.globalEnv || {}),
47
- ...(lambdaConfig.env || {}),
48
- };
49
-
50
- const timeout = lambdaConfig.timeout ?? this.globalTimeout ?? 30;
51
- const memorySize = lambdaConfig.memorySize ?? this.globalMemorySize ?? 128;
52
-
53
- const handler = await HandlerLoader.load(handlerPath, type);
54
- if (handler != undefined) {
55
- this.lambdas.set(name, {
56
- name,
57
- handler,
58
- handlerPath,
59
- handlerName: handler.name || "anonymous",
60
- env,
61
- timeout,
62
- memorySize,
63
- type,
64
- registeredAt: new Date().toISOString(),
65
- });
66
- }
67
- logger.debug(`✅ Lambda registrada: ${name} -> ${handlerPath}`);
68
- } catch (error) {
69
- if (error.message.indexOf("Handler não encontrado") == -1){
70
- logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`, error);
71
- throw error;
72
- }else{
73
- logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`);
74
- }
75
- }
76
- }
77
-
78
- async invoke(functionName, event, invocationType = "RequestResponse") {
79
- const lambda = this.lambdas.get(functionName);
80
-
81
- if (!lambda) {
82
- throw new Error(`Function not found: ${functionName}`);
83
- }
84
-
85
- this.applyEnvironment(lambda.env);
86
- logger.debug(`🎯 Invocando Lambda: ${functionName}`);
87
-
88
- if (invocationType === "Event") {
89
- this.executeHandler(lambda.handler, event).catch((err) => logger.error(`❌ Async Lambda error (${functionName}):`, err));
90
- return { StatusCode: 202 };
91
- }
92
-
93
- const result = await this.executeHandler(lambda.handler, event);
94
- this.audit.record({
95
- eventName: "Invoke",
96
- readOnly: false,
97
- resources: [{ ARN: `arn:aws:lambda:local:000000000000:function:${functionName}`, type: "AWS::Lambda::Function" }],
98
- requestParameters: { functionName, invocationType },
99
- });
100
- return { StatusCode: result.statusCode || 200, Payload: result };
101
- }
102
-
103
- async executeHandler(handler, event) {
104
- try {
105
- const context = this.createContext();
106
- const result = await handler(event, context);
107
- return result;
108
- } catch (error) {
109
- logger.error("❌ Erro no handler:", error);
110
- return {
111
- statusCode: 500,
112
- body: JSON.stringify({ error: "Internal Server Error", message: error.message }),
113
- };
114
- }
115
- }
116
-
117
- createContext() {
118
- return {
119
- awsRequestId: Math.random().toString(36).substring(7),
120
- functionName: "local-lambda",
121
- functionVersion: "$LATEST",
122
- invokedFunctionArn: "arn:aws:lambda:local:000000000000:function:local-lambda",
123
- memoryLimitInMB: "1024",
124
- logGroupName: "/aws/lambda/local-lambda",
125
- logStreamName: "local-stream",
126
- getRemainingTimeInMillis: () => 30000,
127
- callbackWaitsForEmptyEventLoop: true,
128
- identity: null,
129
- clientContext: null,
130
- };
131
- }
132
-
133
- applyEnvironment(env) {
134
- for (const [key, value] of Object.entries(env)) {
135
- process.env[key] = value;
136
- this.environment[key] = value;
137
- }
138
- }
139
-
140
- setEnvironmentVariable(key, value) {
141
- process.env[key] = value;
142
- this.environment[key] = value;
143
- }
144
-
145
- getEnvironmentVariables() {
146
- return { ...this.environment };
147
- }
148
-
149
- listLambdas() {
150
- return Array.from(this.lambdas.values()).map((l) => ({
151
- name: l.name,
152
- handlerName: l.handlerName,
153
- handlerPath: l.handlerPath,
154
- type: l.type,
155
- env: l.env,
156
- registeredAt: l.registeredAt,
157
- }));
158
- }
159
-
160
- getLambda(name) {
161
- return this.lambdas.get(name);
162
- }
163
-
164
- getLambdasCount() {
165
- return this.lambdas.size;
166
- }
167
-
168
- async reloadLambdas() {
169
- logger.info("🔄 Recarregando Lambdas...");
170
-
171
- for (const [name, lambda] of this.lambdas.entries()) {
172
- try {
173
- const newHandler = await HandlerLoader.reload(lambda.handlerPath, lambda.type);
174
- lambda.handler = newHandler;
175
- lambda.handlerName = newHandler.name || "anonymous";
176
- logger.debug(`✅ Lambda recarregada: ${name}`);
177
- } catch (error) {
178
- logger.error(`❌ Erro ao recarregar Lambda ${name}:`, error);
179
- }
180
- }
181
-
182
- logger.info(`✅ ${this.lambdas.size} Lambdas recarregadas`);
183
- }
184
-
185
- getStats() {
186
- return {
187
- totalLambdas: this.lambdas.size,
188
- lambdas: this.listLambdas().map((l) => ({ name: l.name, handler: l.handlerName })),
189
- };
190
- }
191
-
192
- async reset() {
193
- await this.reloadLambdas();
194
- this.environment = { ...process.env };
195
- logger.debug("Lambda: Estado resetado");
196
- }
197
- }
198
-
199
- module.exports = LambdaSimulator;
1
+ /**
2
+ * Lambda Simulator - Simula execução de funções Lambda
3
+ */
4
+
5
+ const HandlerLoader = require("./handler-loader");
6
+ const logger = require("../../utils/logger");
7
+ const { CloudTrailAudit } = require("../../utils/cloudtrail-audit");
8
+
9
+ class LambdaSimulator {
10
+ constructor(config) {
11
+ this.config = config;
12
+ this.lambdas = new Map(); // functionName -> { handler, env, config }
13
+ this.environment = { ...process.env };
14
+ this.audit = new CloudTrailAudit("lambda.amazonaws.com");
15
+ }
16
+
17
+ async initialize() {
18
+ logger.debug("Inicializando Lambda Simulator...");
19
+
20
+ // Build global lambda defaults from config.global
21
+ const globalDefaults = this.config.global || {};
22
+ this.globalEnv = globalDefaults.env || {};
23
+ this.globalTimeout = globalDefaults.timeout || null;
24
+ this.globalMemorySize = globalDefaults.memorySize || null;
25
+
26
+ if (this.config.lambdas && this.config.lambdas.length > 0) {
27
+ for (const lambdaConfig of this.config.lambdas) {
28
+ await this.registerLambda(lambdaConfig);
29
+ }
30
+ }
31
+
32
+ logger.debug(`✅ ${this.lambdas.size} Lambdas registradas`);
33
+ }
34
+
35
+ async registerLambda(lambdaConfig) {
36
+ try {
37
+ const { name, handler: handlerPath, type = "auto" } = lambdaConfig;
38
+
39
+ if (!name) {
40
+ logger.warn(`Lambda sem nome ignorada: ${JSON.stringify(lambdaConfig)}`);
41
+ return;
42
+ }
43
+
44
+ // Merge: global env as base, lambda-specific env overrides
45
+ const env = {
46
+ ...(this.globalEnv || {}),
47
+ ...(lambdaConfig.env || {}),
48
+ };
49
+
50
+ const timeout = lambdaConfig.timeout ?? this.globalTimeout ?? 30;
51
+ const memorySize = lambdaConfig.memorySize ?? this.globalMemorySize ?? 128;
52
+
53
+ const handler = await HandlerLoader.load(handlerPath, type);
54
+ if (handler != undefined) {
55
+ this.lambdas.set(name, {
56
+ name,
57
+ handler,
58
+ handlerPath,
59
+ handlerName: handler.name || "anonymous",
60
+ env,
61
+ timeout,
62
+ memorySize,
63
+ type,
64
+ registeredAt: new Date().toISOString(),
65
+ });
66
+ }
67
+ logger.debug(`✅ Lambda registrada: ${name} -> ${handlerPath}`);
68
+ } catch (error) {
69
+ if (error.message.indexOf("Handler não encontrado") == -1){
70
+ logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`, error);
71
+ throw error;
72
+ }else{
73
+ logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`);
74
+ }
75
+ }
76
+ }
77
+
78
+ async invoke(functionName, event, invocationType = "RequestResponse") {
79
+ const lambda = this.lambdas.get(functionName);
80
+
81
+ if (!lambda) {
82
+ throw new Error(`Function not found: ${functionName}`);
83
+ }
84
+
85
+ this.applyEnvironment(lambda.env);
86
+ logger.debug(`🎯 Invocando Lambda: ${functionName}`);
87
+
88
+ if (invocationType === "Event") {
89
+ this.executeHandler(lambda.handler, event).catch((err) => logger.error(`❌ Async Lambda error (${functionName}):`, err));
90
+ return { StatusCode: 202 };
91
+ }
92
+
93
+ const result = await this.executeHandler(lambda.handler, event);
94
+ this.audit.record({
95
+ eventName: "Invoke",
96
+ readOnly: false,
97
+ resources: [{ ARN: `arn:aws:lambda:local:000000000000:function:${functionName}`, type: "AWS::Lambda::Function" }],
98
+ requestParameters: { functionName, invocationType },
99
+ });
100
+ return { StatusCode: result.statusCode || 200, Payload: result };
101
+ }
102
+
103
+ async executeHandler(handler, event) {
104
+ try {
105
+ const context = this.createContext();
106
+ const result = await handler(event, context);
107
+ return result;
108
+ } catch (error) {
109
+ logger.error("❌ Erro no handler:", error);
110
+ return {
111
+ statusCode: 500,
112
+ body: JSON.stringify({ error: "Internal Server Error", message: error.message }),
113
+ };
114
+ }
115
+ }
116
+
117
+ createContext() {
118
+ return {
119
+ awsRequestId: Math.random().toString(36).substring(7),
120
+ functionName: "local-lambda",
121
+ functionVersion: "$LATEST",
122
+ invokedFunctionArn: "arn:aws:lambda:local:000000000000:function:local-lambda",
123
+ memoryLimitInMB: "1024",
124
+ logGroupName: "/aws/lambda/local-lambda",
125
+ logStreamName: "local-stream",
126
+ getRemainingTimeInMillis: () => 30000,
127
+ callbackWaitsForEmptyEventLoop: true,
128
+ identity: null,
129
+ clientContext: null,
130
+ };
131
+ }
132
+
133
+ applyEnvironment(env) {
134
+ for (const [key, value] of Object.entries(env)) {
135
+ process.env[key] = value;
136
+ this.environment[key] = value;
137
+ }
138
+ }
139
+
140
+ setEnvironmentVariable(key, value) {
141
+ process.env[key] = value;
142
+ this.environment[key] = value;
143
+ }
144
+
145
+ getEnvironmentVariables() {
146
+ return { ...this.environment };
147
+ }
148
+
149
+ listLambdas() {
150
+ return Array.from(this.lambdas.values()).map((l) => ({
151
+ name: l.name,
152
+ handlerName: l.handlerName,
153
+ handlerPath: l.handlerPath,
154
+ type: l.type,
155
+ env: l.env,
156
+ registeredAt: l.registeredAt,
157
+ }));
158
+ }
159
+
160
+ getLambda(name) {
161
+ return this.lambdas.get(name);
162
+ }
163
+
164
+ getLambdasCount() {
165
+ return this.lambdas.size;
166
+ }
167
+
168
+ async reloadLambdas() {
169
+ logger.info("🔄 Recarregando Lambdas...");
170
+
171
+ for (const [name, lambda] of this.lambdas.entries()) {
172
+ try {
173
+ const newHandler = await HandlerLoader.reload(lambda.handlerPath, lambda.type);
174
+ lambda.handler = newHandler;
175
+ lambda.handlerName = newHandler.name || "anonymous";
176
+ logger.debug(`✅ Lambda recarregada: ${name}`);
177
+ } catch (error) {
178
+ logger.error(`❌ Erro ao recarregar Lambda ${name}:`, error);
179
+ }
180
+ }
181
+
182
+ logger.info(`✅ ${this.lambdas.size} Lambdas recarregadas`);
183
+ }
184
+
185
+ getStats() {
186
+ return {
187
+ totalLambdas: this.lambdas.size,
188
+ lambdas: this.listLambdas().map((l) => ({ name: l.name, handler: l.handlerName })),
189
+ };
190
+ }
191
+
192
+ async reset() {
193
+ await this.reloadLambdas();
194
+ this.environment = { ...process.env };
195
+ logger.debug("Lambda: Estado resetado");
196
+ }
197
+ }
198
+
199
+ module.exports = LambdaSimulator;
@@ -1,80 +1,80 @@
1
- 'use strict';
2
-
3
- /**
4
- * @fileoverview Parameter Store Service
5
- * Porta padrão: 4002
6
- */
7
-
8
- const http = require('http');
9
- const path = require('path');
10
- const { ParameterStoreSimulator } = require('./simulator');
11
- const { ParameterStoreServer } = require('./server');
12
- const LocalStore = require('../../utils/local-store');
13
-
14
- class ParameterStoreService {
15
- constructor(config) {
16
- this.config = config;
17
- this.logger = require('../../utils/logger');
18
- this.name = 'parameter-store';
19
- this.port = config?.ports?.parameterStore || config?.services?.parameterStore?.port || 4002;
20
- this.store = null;
21
- this.simulator = null;
22
- this.httpServer = null;
23
- this.isRunning = false;
24
- }
25
-
26
- async initialize() {
27
- this.logger.debug(`Inicializando Parameter Store Service na porta ${this.port}...`);
28
- const dataDir = process.env.AWS_LOCAL_SIMULATOR_DATA_DIR;
29
- this.store = new LocalStore(path.join(dataDir, 'parameter-store'));
30
- this.simulator = new ParameterStoreSimulator(this.store, this.logger, this.config);
31
- await this.simulator.initialize();
32
- this.app = new ParameterStoreServer(this.simulator, this.logger, this.config).getApp();
33
- this.logger.debug('Parameter Store Service inicializado');
34
- }
35
-
36
- injectDependencies(server) {
37
- const ct = server.getService('cloudtrail');
38
- if (ct?.simulator) this.simulator.audit.setTrail(ct.simulator);
39
- }
40
-
41
- async start() {
42
- if (this.isRunning) return;
43
- return new Promise((resolve, reject) => {
44
- this.httpServer = http.createServer(this.app);
45
- this.httpServer.listen(this.port, () => {
46
- this.isRunning = true;
47
- this.logger.debug(`Parameter Store rodando na porta ${this.port}`);
48
- resolve();
49
- });
50
- this.httpServer.on('error', reject);
51
- });
52
- }
53
-
54
- async stop() {
55
- if (!this.isRunning || !this.httpServer) return;
56
- return new Promise((resolve) => {
57
- this.httpServer.close(() => {
58
- this.isRunning = false;
59
- resolve();
60
- });
61
- });
62
- }
63
-
64
- async reset() {
65
- await this.simulator.reset();
66
- }
67
-
68
- getStatus() {
69
- return {
70
- running: this.isRunning,
71
- port: this.port,
72
- endpoint: `http://localhost:${this.port}`,
73
- parameters: this.simulator?.parameters.size || 0,
74
- };
75
- }
76
-
77
- getSimulator() { return this.simulator; }
78
- }
79
-
80
- module.exports = { ParameterStoreService };
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview Parameter Store Service
5
+ * Porta padrão: 4002
6
+ */
7
+
8
+ const http = require('http');
9
+ const path = require('path');
10
+ const { ParameterStoreSimulator } = require('./simulator');
11
+ const { ParameterStoreServer } = require('./server');
12
+ const LocalStore = require('../../utils/local-store');
13
+
14
+ class ParameterStoreService {
15
+ constructor(config) {
16
+ this.config = config;
17
+ this.logger = require('../../utils/logger');
18
+ this.name = 'parameter-store';
19
+ this.port = config?.ports?.parameterStore || config?.services?.parameterStore?.port || 4002;
20
+ this.store = null;
21
+ this.simulator = null;
22
+ this.httpServer = null;
23
+ this.isRunning = false;
24
+ }
25
+
26
+ async initialize() {
27
+ this.logger.debug(`Inicializando Parameter Store Service na porta ${this.port}...`);
28
+ const dataDir = process.env.AWS_LOCAL_SIMULATOR_DATA_DIR;
29
+ this.store = new LocalStore(path.join(dataDir, 'parameter-store'));
30
+ this.simulator = new ParameterStoreSimulator(this.store, this.logger, this.config);
31
+ await this.simulator.initialize();
32
+ this.app = new ParameterStoreServer(this.simulator, this.logger, this.config).getApp();
33
+ this.logger.debug('Parameter Store Service inicializado');
34
+ }
35
+
36
+ injectDependencies(server) {
37
+ const ct = server.getService('cloudtrail');
38
+ if (ct?.simulator) this.simulator.audit.setTrail(ct.simulator);
39
+ }
40
+
41
+ async start() {
42
+ if (this.isRunning) return;
43
+ return new Promise((resolve, reject) => {
44
+ this.httpServer = http.createServer(this.app);
45
+ this.httpServer.listen(this.port, () => {
46
+ this.isRunning = true;
47
+ this.logger.debug(`Parameter Store rodando na porta ${this.port}`);
48
+ resolve();
49
+ });
50
+ this.httpServer.on('error', reject);
51
+ });
52
+ }
53
+
54
+ async stop() {
55
+ if (!this.isRunning || !this.httpServer) return;
56
+ return new Promise((resolve) => {
57
+ this.httpServer.close(() => {
58
+ this.isRunning = false;
59
+ resolve();
60
+ });
61
+ });
62
+ }
63
+
64
+ async reset() {
65
+ await this.simulator.reset();
66
+ }
67
+
68
+ getStatus() {
69
+ return {
70
+ running: this.isRunning,
71
+ port: this.port,
72
+ endpoint: `http://localhost:${this.port}`,
73
+ parameters: this.simulator?.parameters.size || 0,
74
+ };
75
+ }
76
+
77
+ getSimulator() { return this.simulator; }
78
+ }
79
+
80
+ module.exports = { ParameterStoreService };
@@ -1,50 +1,50 @@
1
- 'use strict';
2
-
3
- const express = require('express');
4
- const cors = require('cors');
5
-
6
- class ParameterStoreServer {
7
- constructor(simulator, logger, config) {
8
- this.simulator = simulator; this.logger = logger; this.config = config;
9
- this.app = express();
10
- this._setupMiddleware(); this._setupRoutes();
11
- }
12
- _setupMiddleware() {
13
- if (this.config.cors?.enabled !== false) this.app.use(cors({ origin: this.config.cors?.origin || '*' }));
14
- this.app.use(express.json({ limit: '5mb', type: ['application/json', 'application/x-amz-json-1.1'] }));
15
- }
16
- _getOperation(target) {
17
- const map = {
18
- 'AmazonSSM.PutParameter': 'putParameter',
19
- 'AmazonSSM.GetParameter': 'getParameter',
20
- 'AmazonSSM.GetParameters': 'getParameters',
21
- 'AmazonSSM.GetParametersByPath': 'getParametersByPath',
22
- 'AmazonSSM.DeleteParameter': 'deleteParameter',
23
- 'AmazonSSM.DeleteParameters': 'deleteParameters',
24
- 'AmazonSSM.DescribeParameters': 'describeParameters',
25
- 'AmazonSSM.GetParameterHistory': 'getParameterHistory',
26
- 'AmazonSSM.AddTagsToResource': 'addTagsToResource',
27
- 'AmazonSSM.RemoveTagsFromResource': 'removeTagsFromResource',
28
- };
29
- return map[target];
30
- }
31
- _setupRoutes() {
32
- this.app.get('/__admin/health', (req, res) => res.json({ status: 'healthy', service: 'parameter-store', timestamp: new Date().toISOString() }));
33
- this.app.post('/', async (req, res) => {
34
- const target = req.headers['x-amz-target'];
35
- const operation = this._getOperation(target);
36
- if (!operation) return res.status(400).json({ __type: 'InvalidAction', message: `Unknown: ${target}` });
37
- try {
38
- const result = await this.simulator[operation](req.body || {});
39
- res.json(result || {});
40
- } catch (err) {
41
- this.logger.error(`ParameterStore ${target}: ${err.message}`, 'parameter-store');
42
- const statusCodes = { ParameterNotFound: 400, ParameterAlreadyExists: 400, ParameterPatternMismatch: 400 };
43
- res.status(statusCodes[err.code] || 500).json({ __type: err.code || 'InternalServerError', message: err.message });
44
- }
45
- });
46
- }
47
- getApp() { return this.app; }
48
- }
49
-
50
- module.exports = { ParameterStoreServer };
1
+ 'use strict';
2
+
3
+ const express = require('express');
4
+ const cors = require('cors');
5
+
6
+ class ParameterStoreServer {
7
+ constructor(simulator, logger, config) {
8
+ this.simulator = simulator; this.logger = logger; this.config = config;
9
+ this.app = express();
10
+ this._setupMiddleware(); this._setupRoutes();
11
+ }
12
+ _setupMiddleware() {
13
+ if (this.config.cors?.enabled !== false) this.app.use(cors({ origin: this.config.cors?.origin || '*' }));
14
+ this.app.use(express.json({ limit: '5mb', type: ['application/json', 'application/x-amz-json-1.1'] }));
15
+ }
16
+ _getOperation(target) {
17
+ const map = {
18
+ 'AmazonSSM.PutParameter': 'putParameter',
19
+ 'AmazonSSM.GetParameter': 'getParameter',
20
+ 'AmazonSSM.GetParameters': 'getParameters',
21
+ 'AmazonSSM.GetParametersByPath': 'getParametersByPath',
22
+ 'AmazonSSM.DeleteParameter': 'deleteParameter',
23
+ 'AmazonSSM.DeleteParameters': 'deleteParameters',
24
+ 'AmazonSSM.DescribeParameters': 'describeParameters',
25
+ 'AmazonSSM.GetParameterHistory': 'getParameterHistory',
26
+ 'AmazonSSM.AddTagsToResource': 'addTagsToResource',
27
+ 'AmazonSSM.RemoveTagsFromResource': 'removeTagsFromResource',
28
+ };
29
+ return map[target];
30
+ }
31
+ _setupRoutes() {
32
+ this.app.get('/__admin/health', (req, res) => res.json({ status: 'healthy', service: 'parameter-store', timestamp: new Date().toISOString() }));
33
+ this.app.post('/', async (req, res) => {
34
+ const target = req.headers['x-amz-target'];
35
+ const operation = this._getOperation(target);
36
+ if (!operation) return res.status(400).json({ __type: 'InvalidAction', message: `Unknown: ${target}` });
37
+ try {
38
+ const result = await this.simulator[operation](req.body || {});
39
+ res.json(result || {});
40
+ } catch (err) {
41
+ this.logger.error(`ParameterStore ${target}: ${err.message}`, 'parameter-store');
42
+ const statusCodes = { ParameterNotFound: 400, ParameterAlreadyExists: 400, ParameterPatternMismatch: 400 };
43
+ res.status(statusCodes[err.code] || 500).json({ __type: err.code || 'InternalServerError', message: err.message });
44
+ }
45
+ });
46
+ }
47
+ getApp() { return this.app; }
48
+ }
49
+
50
+ module.exports = { ParameterStoreServer };