@adobe-commerce/aio-toolkit 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,6 +6,9 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __export = (target, all) => {
10
13
  for (var name in all)
11
14
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -28,6 +31,612 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
31
  ));
29
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
33
 
34
+ // node_modules/tsup/assets/cjs_shims.js
35
+ var init_cjs_shims = __esm({
36
+ "node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ }
39
+ });
40
+
41
+ // src/framework/telemetry/helpers/input-error/index.ts
42
+ var _TelemetryInputError, TelemetryInputError;
43
+ var init_input_error = __esm({
44
+ "src/framework/telemetry/helpers/input-error/index.ts"() {
45
+ "use strict";
46
+ init_cjs_shims();
47
+ _TelemetryInputError = class _TelemetryInputError extends Error {
48
+ /**
49
+ * Creates a new TelemetryInputError
50
+ *
51
+ * @param message - Descriptive error message explaining the validation failure
52
+ */
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "TelemetryInputError";
56
+ if (Error.captureStackTrace) {
57
+ Error.captureStackTrace(this, _TelemetryInputError);
58
+ }
59
+ }
60
+ };
61
+ __name(_TelemetryInputError, "TelemetryInputError");
62
+ TelemetryInputError = _TelemetryInputError;
63
+ }
64
+ });
65
+
66
+ // src/framework/telemetry/new-relic/validator/index.ts
67
+ var _NewRelicTelemetryValidator, NewRelicTelemetryValidator;
68
+ var init_validator = __esm({
69
+ "src/framework/telemetry/new-relic/validator/index.ts"() {
70
+ "use strict";
71
+ init_cjs_shims();
72
+ init_input_error();
73
+ _NewRelicTelemetryValidator = class _NewRelicTelemetryValidator {
74
+ /**
75
+ * Checks if New Relic telemetry is configured
76
+ *
77
+ * Returns true if:
78
+ * - ENABLE_TELEMETRY is explicitly set to true
79
+ * - NEW_RELIC_TELEMETRY is explicitly set to true
80
+ *
81
+ * This method does NOT validate the completeness of configuration,
82
+ * it only checks if the provider is enabled.
83
+ *
84
+ * @param params - Runtime parameters to check
85
+ * @returns true if New Relic telemetry is enabled, false otherwise
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const validator = new NewRelicTelemetryValidator();
90
+ * const params = { ENABLE_TELEMETRY: true, NEW_RELIC_TELEMETRY: true };
91
+ * if (validator.isConfigured(params)) {
92
+ * // New Relic is enabled, proceed with initialization
93
+ * }
94
+ * ```
95
+ */
96
+ isConfigured(params) {
97
+ return params.ENABLE_TELEMETRY === true && params.NEW_RELIC_TELEMETRY === true;
98
+ }
99
+ /**
100
+ * Validates New Relic specific parameters
101
+ *
102
+ * IMPORTANT: Only call this method after checking isConfigured() returns true.
103
+ * This method assumes New Relic telemetry is enabled and validates that
104
+ * all required parameters are present.
105
+ *
106
+ * Required parameters when New Relic is enabled:
107
+ * - NEW_RELIC_SERVICE_NAME must be provided
108
+ * - NEW_RELIC_LICENSE_KEY must be provided
109
+ *
110
+ * @param params - Runtime parameters to validate
111
+ * @throws {TelemetryInputError} If NEW_RELIC_SERVICE_NAME is missing
112
+ * @throws {TelemetryInputError} If NEW_RELIC_LICENSE_KEY is missing
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * const validator = new NewRelicTelemetryValidator();
117
+ * const params = {
118
+ * ENABLE_TELEMETRY: true,
119
+ * NEW_RELIC_TELEMETRY: true,
120
+ * NEW_RELIC_SERVICE_NAME: "my-service",
121
+ * NEW_RELIC_LICENSE_KEY: "license-key"
122
+ * };
123
+ *
124
+ * if (validator.isConfigured(params)) {
125
+ * validator.validateConfiguration(params); // Validates required fields
126
+ * }
127
+ * ```
128
+ */
129
+ validateConfiguration(params) {
130
+ if (params.NEW_RELIC_SERVICE_NAME === void 0 || params.NEW_RELIC_SERVICE_NAME === null || params.NEW_RELIC_SERVICE_NAME === "") {
131
+ throw new TelemetryInputError("NEW_RELIC_SERVICE_NAME is required");
132
+ }
133
+ if (params.NEW_RELIC_LICENSE_KEY === void 0 || params.NEW_RELIC_LICENSE_KEY === null || params.NEW_RELIC_LICENSE_KEY === "") {
134
+ throw new TelemetryInputError("NEW_RELIC_LICENSE_KEY is required");
135
+ }
136
+ }
137
+ };
138
+ __name(_NewRelicTelemetryValidator, "NewRelicTelemetryValidator");
139
+ NewRelicTelemetryValidator = _NewRelicTelemetryValidator;
140
+ }
141
+ });
142
+
143
+ // src/framework/telemetry/helpers/resource-factory/index.ts
144
+ var import_aio_lib_telemetry, import_resources, _ResourceFactory, ResourceFactory;
145
+ var init_resource_factory = __esm({
146
+ "src/framework/telemetry/helpers/resource-factory/index.ts"() {
147
+ "use strict";
148
+ init_cjs_shims();
149
+ import_aio_lib_telemetry = require("@adobe/aio-lib-telemetry");
150
+ import_resources = require("@opentelemetry/resources");
151
+ _ResourceFactory = class _ResourceFactory {
152
+ /**
153
+ * Creates a resource with custom environment attributes
154
+ *
155
+ * Starts with the base Adobe I/O Runtime resource and optionally
156
+ * merges environment attributes. These attributes are useful for
157
+ * filtering and correlating telemetry data by deployment environment.
158
+ *
159
+ * Note: Request-specific data (like request IDs) should NOT be added to
160
+ * Resources as they are created once and reused across all requests.
161
+ * Use log attributes or span attributes for request-specific data.
162
+ *
163
+ * @param params - Runtime parameters containing optional ENVIRONMENT
164
+ * @param params.ENVIRONMENT - Environment name (e.g., "dev", "stage", "prod")
165
+ * @returns OpenTelemetry Resource with custom attributes if provided
166
+ *
167
+ * @example Without custom attributes
168
+ * ```typescript
169
+ * const factory = new ResourceFactory();
170
+ * const resource = factory.createWithEnvironment({});
171
+ * // Returns base Adobe I/O Runtime resource
172
+ * ```
173
+ *
174
+ * @example With environment
175
+ * ```typescript
176
+ * const factory = new ResourceFactory();
177
+ * const params = { ENVIRONMENT: "production" };
178
+ * const resource = factory.createWithEnvironment(params);
179
+ * // Returns resource with environment="production" attribute
180
+ * ```
181
+ */
182
+ createWithEnvironment(params) {
183
+ const baseResource = (0, import_aio_lib_telemetry.getAioRuntimeResource)();
184
+ const customAttributes = {};
185
+ if (params.ENVIRONMENT) {
186
+ customAttributes.environment = params.ENVIRONMENT;
187
+ }
188
+ if (Object.keys(customAttributes).length === 0) {
189
+ return baseResource;
190
+ }
191
+ const customResource = (0, import_resources.resourceFromAttributes)(
192
+ customAttributes
193
+ );
194
+ return baseResource.merge(customResource);
195
+ }
196
+ };
197
+ __name(_ResourceFactory, "ResourceFactory");
198
+ ResourceFactory = _ResourceFactory;
199
+ }
200
+ });
201
+
202
+ // src/framework/telemetry/helpers/success-checker/index.ts
203
+ var _SuccessChecker, SuccessChecker;
204
+ var init_success_checker = __esm({
205
+ "src/framework/telemetry/helpers/success-checker/index.ts"() {
206
+ "use strict";
207
+ init_cjs_shims();
208
+ _SuccessChecker = class _SuccessChecker {
209
+ /**
210
+ * Determines if an action execution was successful
211
+ *
212
+ * Success criteria:
213
+ * - Response has statusCode 200
214
+ * - Body does not contain an exception operation
215
+ *
216
+ * @param result - The action execution result
217
+ * @returns true if successful, false otherwise
218
+ *
219
+ * @example Success case
220
+ * ```typescript
221
+ * const checker = new SuccessChecker();
222
+ * const result = { statusCode: 200, body: { data: 'success' } };
223
+ * checker.execute(result); // true
224
+ * ```
225
+ *
226
+ * @example Failure case - wrong status code
227
+ * ```typescript
228
+ * const checker = new SuccessChecker();
229
+ * const result = { statusCode: 500, body: { error: 'Internal error' } };
230
+ * checker.execute(result); // false
231
+ * ```
232
+ *
233
+ * @example Failure case - exception in body
234
+ * ```typescript
235
+ * const checker = new SuccessChecker();
236
+ * const result = { statusCode: 200, body: { op: 'exception', message: 'Error' } };
237
+ * checker.execute(result); // false
238
+ * ```
239
+ */
240
+ execute(result) {
241
+ if (!result || typeof result !== "object") {
242
+ return false;
243
+ }
244
+ const actionResult = result;
245
+ if (actionResult.statusCode !== 200) {
246
+ return false;
247
+ }
248
+ if (actionResult.body && typeof actionResult.body === "object") {
249
+ return actionResult.body.op !== "exception";
250
+ }
251
+ return true;
252
+ }
253
+ };
254
+ __name(_SuccessChecker, "SuccessChecker");
255
+ SuccessChecker = _SuccessChecker;
256
+ }
257
+ });
258
+
259
+ // src/framework/telemetry/helpers/json-message-processor/index.ts
260
+ var _JsonMessageProcessor, JsonMessageProcessor;
261
+ var init_json_message_processor = __esm({
262
+ "src/framework/telemetry/helpers/json-message-processor/index.ts"() {
263
+ "use strict";
264
+ init_cjs_shims();
265
+ _JsonMessageProcessor = class _JsonMessageProcessor {
266
+ /**
267
+ * Creates a new JsonMessageProcessor
268
+ *
269
+ * @param wrappedProcessor - The log processor to wrap and enhance
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * const exporter = new OTLPLogExporterProto({
274
+ * url: "https://otlp.nr-data.net/v1/logs",
275
+ * headers: { "api-key": licenseKey }
276
+ * });
277
+ * const baseProcessor = new SimpleLogRecordProcessor(exporter);
278
+ * const processor = new JsonMessageProcessor(baseProcessor);
279
+ * ```
280
+ */
281
+ constructor(wrappedProcessor) {
282
+ this.wrappedProcessor = wrappedProcessor;
283
+ }
284
+ /**
285
+ * Parse JavaScript object notation and convert to proper object
286
+ *
287
+ * Handles Winston's util.inspect format which produces JavaScript
288
+ * object literals instead of JSON strings.
289
+ *
290
+ * Examples:
291
+ * - { key: 'value' } → {"key":"value"}
292
+ * - { 'accept-encoding': 'gzip' } → {"accept-encoding":"gzip"}
293
+ *
294
+ * @param str - JavaScript object notation string
295
+ * @returns Parsed object
296
+ * @throws Error if parsing fails
297
+ * @private
298
+ */
299
+ parseJavaScriptObjectNotation(str) {
300
+ const func = new Function("return (" + str + ")");
301
+ return func();
302
+ }
303
+ /**
304
+ * Flatten nested objects into dot-notation keys
305
+ *
306
+ * Converts nested structures like:
307
+ * { headers: { accept: '*' } }
308
+ *
309
+ * Into flat structure:
310
+ * { 'headers.accept': '*' }
311
+ *
312
+ * This makes all attributes searchable in observability platforms.
313
+ *
314
+ * @param obj - Object to flatten
315
+ * @param prefix - Current key prefix (used in recursion)
316
+ * @returns Flattened object with dot-notation keys
317
+ * @private
318
+ */
319
+ flattenObject(obj, prefix = "") {
320
+ const flattened = {};
321
+ for (const [key, value] of Object.entries(obj)) {
322
+ const newKey = prefix ? `${prefix}.${key}` : key;
323
+ if (value === null || value === void 0) {
324
+ flattened[newKey] = value;
325
+ } else if (Array.isArray(value)) {
326
+ flattened[newKey] = JSON.stringify(value);
327
+ } else if (typeof value === "object") {
328
+ if (Object.keys(value).length === 0) {
329
+ continue;
330
+ }
331
+ const nested = this.flattenObject(value, newKey);
332
+ Object.assign(flattened, nested);
333
+ } else {
334
+ flattened[newKey] = value;
335
+ }
336
+ }
337
+ return flattened;
338
+ }
339
+ /**
340
+ * Processes a log record by parsing JSON messages and extracting attributes
341
+ *
342
+ * This method intercepts log records, attempts to parse structured data
343
+ * from the message body, and merges extracted properties as attributes.
344
+ * Additionally, it extracts the log level from the severity information
345
+ * and adds it as a 'level' attribute for easier querying.
346
+ *
347
+ * The enhanced log record is then passed to the wrapped processor.
348
+ *
349
+ * @param logRecord - The log record to process
350
+ *
351
+ * @remarks
352
+ * Processing steps:
353
+ * 1. Extract log level from severityText or severityNumber
354
+ * 2. Add 'level' attribute (debug, info, warn, error, etc.)
355
+ * 3. Parse JSON bodies that start with '{'
356
+ * 4. Extract properties as individual attributes
357
+ * 5. Preserve 'message' field as primary log body
358
+ *
359
+ * Error handling:
360
+ * - Silently handles parsing errors to avoid breaking the logging pipeline
361
+ * - Failed parsing results in unmodified log record
362
+ */
363
+ onEmit(logRecord) {
364
+ try {
365
+ if (logRecord.severityText) {
366
+ logRecord.setAttribute("level", logRecord.severityText.toLowerCase());
367
+ } else if (logRecord.severityNumber !== void 0) {
368
+ const levelName = this.mapSeverityNumberToLevel(logRecord.severityNumber);
369
+ if (levelName) {
370
+ logRecord.setAttribute("level", levelName);
371
+ }
372
+ }
373
+ const body = logRecord.body;
374
+ if (typeof body === "string" && body.trim().startsWith("{")) {
375
+ let parsed = null;
376
+ try {
377
+ parsed = JSON.parse(body);
378
+ } catch {
379
+ try {
380
+ parsed = this.parseJavaScriptObjectNotation(body);
381
+ } catch {
382
+ }
383
+ }
384
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
385
+ const messageValue = parsed.message;
386
+ const { message, ...attributesObj } = parsed;
387
+ const flattenedAttributes = this.flattenObject(attributesObj);
388
+ Object.entries(flattenedAttributes).forEach(([key, value]) => {
389
+ if (value !== void 0 && value !== null) {
390
+ logRecord.setAttribute(key, value);
391
+ }
392
+ });
393
+ if (messageValue) {
394
+ logRecord.body = messageValue;
395
+ }
396
+ }
397
+ }
398
+ } catch {
399
+ }
400
+ this.wrappedProcessor.onEmit(logRecord);
401
+ }
402
+ /**
403
+ * Maps OpenTelemetry severity number to log level name
404
+ *
405
+ * OpenTelemetry defines severity numbers from 1-24:
406
+ * - 1-4: TRACE
407
+ * - 5-8: DEBUG
408
+ * - 9-12: INFO
409
+ * - 13-16: WARN
410
+ * - 17-20: ERROR
411
+ * - 21-24: FATAL
412
+ *
413
+ * @param severityNumber - OpenTelemetry severity number
414
+ * @returns Log level name (trace, debug, info, warn, error, fatal) or null
415
+ * @private
416
+ */
417
+ mapSeverityNumberToLevel(severityNumber) {
418
+ if (severityNumber >= 1 && severityNumber <= 4) return "trace";
419
+ if (severityNumber >= 5 && severityNumber <= 8) return "debug";
420
+ if (severityNumber >= 9 && severityNumber <= 12) return "info";
421
+ if (severityNumber >= 13 && severityNumber <= 16) return "warn";
422
+ if (severityNumber >= 17 && severityNumber <= 20) return "error";
423
+ if (severityNumber >= 21 && severityNumber <= 24) return "fatal";
424
+ return null;
425
+ }
426
+ /**
427
+ * Forces the processor to flush any pending log records
428
+ *
429
+ * Delegates to the wrapped processor's forceFlush method.
430
+ * Useful for ensuring logs are sent before application shutdown.
431
+ *
432
+ * @returns Promise that resolves when flush is complete
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * await processor.forceFlush();
437
+ * console.log("All logs have been sent");
438
+ * ```
439
+ */
440
+ async forceFlush() {
441
+ return this.wrappedProcessor.forceFlush();
442
+ }
443
+ /**
444
+ * Shuts down the processor and releases resources
445
+ *
446
+ * Delegates to the wrapped processor's shutdown method.
447
+ * Should be called when the application is terminating.
448
+ *
449
+ * @returns Promise that resolves when shutdown is complete
450
+ *
451
+ * @example
452
+ * ```typescript
453
+ * await processor.shutdown();
454
+ * console.log("Processor has been shut down");
455
+ * ```
456
+ */
457
+ async shutdown() {
458
+ return this.wrappedProcessor.shutdown();
459
+ }
460
+ };
461
+ __name(_JsonMessageProcessor, "JsonMessageProcessor");
462
+ JsonMessageProcessor = _JsonMessageProcessor;
463
+ }
464
+ });
465
+
466
+ // src/framework/telemetry/new-relic/index.ts
467
+ var new_relic_exports = {};
468
+ __export(new_relic_exports, {
469
+ default: () => new_relic_default
470
+ });
471
+ var import_aio_lib_telemetry2, import_otel, _NewRelicTelemetry, NewRelicTelemetry, new_relic_default;
472
+ var init_new_relic = __esm({
473
+ "src/framework/telemetry/new-relic/index.ts"() {
474
+ "use strict";
475
+ init_cjs_shims();
476
+ import_aio_lib_telemetry2 = require("@adobe/aio-lib-telemetry");
477
+ init_validator();
478
+ init_resource_factory();
479
+ init_success_checker();
480
+ import_otel = require("@adobe/aio-lib-telemetry/otel");
481
+ init_json_message_processor();
482
+ _NewRelicTelemetry = class _NewRelicTelemetry {
483
+ /**
484
+ * Constructor for New Relic telemetry
485
+ *
486
+ * @description Constructor for New Relic telemetry
487
+ * @example
488
+ * ```typescript
489
+ * const telemetry = new NewRelicTelemetry();
490
+ * ```
491
+ */
492
+ constructor() {
493
+ this.validator = new NewRelicTelemetryValidator();
494
+ this.successChecker = new SuccessChecker();
495
+ this.resourceFactory = new ResourceFactory();
496
+ }
497
+ /**
498
+ * Checks if New Relic telemetry can be initialized
499
+ *
500
+ * Determines if New Relic telemetry is properly configured without actually
501
+ * attempting initialization. Useful for provider chain fallback logic.
502
+ *
503
+ * @param params - Runtime parameters to check
504
+ * @returns true if New Relic is configured and can be initialized
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * const telemetry = new NewRelicTelemetry();
509
+ * if (telemetry.canInitialize(params)) {
510
+ * // New Relic is configured, use it
511
+ * } else {
512
+ * // Try next provider
513
+ * }
514
+ * ```
515
+ */
516
+ canInitialize(params) {
517
+ return this.validator.isConfigured(params);
518
+ }
519
+ /**
520
+ * Get the OpenTelemetry instrumentation configuration for New Relic
521
+ *
522
+ * Builds and returns the complete instrumentation configuration including:
523
+ * - Service name and preset instrumentations
524
+ * - Custom resource attributes (environment)
525
+ * - OTLP exporters for traces, metrics, and logs
526
+ * - Success/failure detection for actions
527
+ *
528
+ * This method is called internally by `instrumentEntrypoint` to configure
529
+ * telemetry before wrapping the action.
530
+ *
531
+ * @returns Complete entrypoint instrumentation configuration
532
+ * @throws {TelemetryInputError} If required parameters are missing (service name, license key)
533
+ *
534
+ * @example
535
+ * ```typescript
536
+ * const telemetry = new NewRelicTelemetry();
537
+ * const config = telemetry.getConfig();
538
+ * // Returns configuration with exporters, instrumentations, and resource attributes
539
+ * ```
540
+ */
541
+ getConfig() {
542
+ return {
543
+ ...(0, import_aio_lib_telemetry2.defineTelemetryConfig)((params) => {
544
+ if (!this.validator.isConfigured(params)) {
545
+ throw new Error("New Relic telemetry is not configured");
546
+ }
547
+ this.validator.validateConfiguration(params);
548
+ const serviceName = params.NEW_RELIC_SERVICE_NAME;
549
+ return {
550
+ sdkConfig: {
551
+ serviceName,
552
+ instrumentations: (0, import_aio_lib_telemetry2.getPresetInstrumentations)("simple"),
553
+ resource: this.resourceFactory.createWithEnvironment(params),
554
+ ...this.getExportersConfig(params)
555
+ }
556
+ };
557
+ }),
558
+ isSuccessful: this.successChecker.execute.bind(this.successChecker)
559
+ };
560
+ }
561
+ /**
562
+ * Configure New Relic exporters for traces, metrics, and logs
563
+ *
564
+ * Creates OTLP exporters for all three signal types (traces, metrics, logs)
565
+ * and configures them to send data to New Relic. Log processors are wrapped
566
+ * with JsonMessageProcessor for better attribute extraction.
567
+ *
568
+ * @param params - Runtime parameters containing NEW_RELIC_LICENSE_KEY and optional NEW_RELIC_URL
569
+ * @returns Configuration object with traceExporter, metricReaders, and logRecordProcessors
570
+ * @private
571
+ */
572
+ getExportersConfig(params) {
573
+ const licenseKey = params.NEW_RELIC_LICENSE_KEY;
574
+ const newRelicUrl = params.NEW_RELIC_URL || "https://otlp.nr-data.net";
575
+ const makeExporterConfig = /* @__PURE__ */ __name((endpoint) => {
576
+ return {
577
+ url: `${newRelicUrl}/${endpoint}`,
578
+ headers: {
579
+ "api-key": licenseKey
580
+ }
581
+ };
582
+ }, "makeExporterConfig");
583
+ return {
584
+ traceExporter: new import_otel.OTLPTraceExporterProto(makeExporterConfig("v1/traces")),
585
+ metricReaders: [
586
+ new import_otel.PeriodicExportingMetricReader({
587
+ exporter: new import_otel.OTLPMetricExporterProto(makeExporterConfig("v1/metrics"))
588
+ })
589
+ ],
590
+ logRecordProcessors: [
591
+ new JsonMessageProcessor(
592
+ new import_otel.SimpleLogRecordProcessor(new import_otel.OTLPLogExporterProto(makeExporterConfig("v1/logs")))
593
+ )
594
+ ]
595
+ };
596
+ }
597
+ /**
598
+ * Initialize telemetry instrumentation for a runtime action
599
+ *
600
+ * Wraps the provided action with OpenTelemetry instrumentation using
601
+ * New Relic as the backend. The instrumented action will automatically:
602
+ * - Create spans for the action execution
603
+ * - Export metrics during runtime
604
+ * - Forward logs to New Relic
605
+ * - Track success/failure status
606
+ *
607
+ * This method delegates to `instrumentEntrypoint` from `@adobe/aio-lib-telemetry`,
608
+ * passing the action and New Relic specific configuration.
609
+ *
610
+ * @param action - The runtime action function to instrument
611
+ * @returns The instrumented action function with telemetry enabled
612
+ * @throws {TelemetryInputError} If required configuration is missing
613
+ *
614
+ * @example
615
+ * ```typescript
616
+ * async function myAction(params: Record<string, unknown>) {
617
+ * const logger = Telemetry.createLogger("my-action", params);
618
+ * logger.info("Processing request");
619
+ *
620
+ * return { statusCode: 200, body: { success: true } };
621
+ * }
622
+ *
623
+ * const telemetry = new NewRelicTelemetry();
624
+ * const instrumentedAction = telemetry.initialize(myAction);
625
+ *
626
+ * // instrumentedAction now sends traces, metrics, and logs to New Relic
627
+ * export const main = instrumentedAction;
628
+ * ```
629
+ */
630
+ initialize(action) {
631
+ return (0, import_aio_lib_telemetry2.instrumentEntrypoint)(action, this.getConfig());
632
+ }
633
+ };
634
+ __name(_NewRelicTelemetry, "NewRelicTelemetry");
635
+ NewRelicTelemetry = _NewRelicTelemetry;
636
+ new_relic_default = NewRelicTelemetry;
637
+ }
638
+ });
639
+
31
640
  // src/index.ts
32
641
  var index_exports = {};
33
642
  __export(index_exports, {
@@ -50,6 +659,7 @@ __export(index_exports, {
50
659
  ImsToken: () => ims_token_default,
51
660
  InfiniteLoopBreaker: () => infinite_loop_breaker_default,
52
661
  IoEventsGlobals: () => IoEventsGlobals,
662
+ JsonMessageProcessor: () => JsonMessageProcessor,
53
663
  Oauth1aConnection: () => oauth1a_connection_default,
54
664
  OnboardCommerce: () => onboard_commerce_default,
55
665
  OnboardEvents: () => onboard_events_default,
@@ -68,17 +678,28 @@ __export(index_exports, {
68
678
  ShippingCarrierMethod: () => method_default,
69
679
  ShippingCarrierResponse: () => response_default3,
70
680
  SignatureVerification: () => SignatureVerification,
681
+ SuccessChecker: () => SuccessChecker,
682
+ Telemetry: () => telemetry_default,
683
+ TelemetryInputError: () => TelemetryInputError,
71
684
  Validator: () => validator_default,
72
685
  WebhookAction: () => webhook_action_default,
73
686
  WebhookActionOperation: () => WebhookActionOperation,
74
687
  WebhookActionResponse: () => response_default2
75
688
  });
76
689
  module.exports = __toCommonJS(index_exports);
690
+ init_cjs_shims();
691
+
692
+ // src/framework/index.ts
693
+ init_cjs_shims();
77
694
 
78
695
  // src/framework/runtime-action/index.ts
79
- var import_aio_sdk = require("@adobe/aio-sdk");
696
+ init_cjs_shims();
697
+
698
+ // src/framework/runtime-action/response/index.ts
699
+ init_cjs_shims();
80
700
 
81
701
  // src/framework/runtime-action/types.ts
702
+ init_cjs_shims();
82
703
  var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
83
704
  HttpStatus2[HttpStatus2["OK"] = 200] = "OK";
84
705
  HttpStatus2[HttpStatus2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
@@ -140,29 +761,8 @@ __name(_RuntimeActionResponse, "RuntimeActionResponse");
140
761
  var RuntimeActionResponse = _RuntimeActionResponse;
141
762
  var response_default = RuntimeActionResponse;
142
763
 
143
- // src/framework/runtime-action/parameters/index.ts
144
- var _Parameters = class _Parameters {
145
- /**
146
- * Returns a log-ready string of the action input parameters.
147
- * The `Authorization` header content will be replaced by '<hidden>'.
148
- *
149
- * @param params action input parameters.
150
- *
151
- * @returns string
152
- */
153
- static stringify(params) {
154
- let headers = params.__ow_headers || {};
155
- if (headers.authorization) {
156
- headers = { ...headers, authorization: "<hidden>" };
157
- }
158
- return JSON.stringify({ ...params, __ow_headers: headers });
159
- }
160
- };
161
- __name(_Parameters, "Parameters");
162
- var Parameters = _Parameters;
163
- var parameters_default = Parameters;
164
-
165
764
  // src/framework/runtime-action/validator/index.ts
765
+ init_cjs_shims();
166
766
  var _Validator = class _Validator {
167
767
  /**
168
768
  * Returns the list of missing keys given an object and its required keys.
@@ -227,91 +827,582 @@ __name(_Validator, "Validator");
227
827
  var Validator = _Validator;
228
828
  var validator_default = Validator;
229
829
 
830
+ // src/framework/telemetry/index.ts
831
+ init_cjs_shims();
832
+ var import_aio_sdk = require("@adobe/aio-sdk");
833
+ var _Telemetry = class _Telemetry {
834
+ /**
835
+ * Create a logger with standard configuration and automatic metadata injection.
836
+ *
837
+ * This method creates a structured logger and wraps it to automatically add
838
+ * contextual metadata to all log calls:
839
+ * - `x-adobe-commerce-request-id`: Extracted from `__ow_headers` (when present)
840
+ * - `action.type`: Extracted from `params.action_type` (when present)
841
+ *
842
+ * If ENABLE_TELEMETRY is true, uses OpenTelemetry logger (lazy-loaded); otherwise uses Core.Logger.
843
+ * The environment from params.ENVIRONMENT is set at the resource level and will
844
+ * automatically appear in all logs sent to New Relic if ENABLE_TELEMETRY is true.
845
+ *
846
+ * @param name - Logger name (typically action name)
847
+ * @param params - Runtime parameters containing LOG_LEVEL, optional ENABLE_TELEMETRY, ENVIRONMENT, action_type, and __ow_headers
848
+ * @returns Configured logger instance with automatic metadata injection
849
+ *
850
+ * @example Basic string message
851
+ * ```typescript
852
+ * const logger = Telemetry.createLogger("my-action", params);
853
+ * logger.info("Processing started");
854
+ * // Logs: "Processing started"
855
+ * ```
856
+ *
857
+ * @example JSON object message with automatic metadata
858
+ * ```typescript
859
+ * const logger = Telemetry.createLogger("my-action", {
860
+ * ...params,
861
+ * action_type: "webhook",
862
+ * __ow_headers: { 'x-adobe-commerce-request-id': 'req-123' }
863
+ * });
864
+ * logger.info({
865
+ * message: "User action completed",
866
+ * user_id: "123"
867
+ * });
868
+ * // In New Relic: {
869
+ * // message: "User action completed",
870
+ * // user_id: "123",
871
+ * // "x-adobe-commerce-request-id": "req-123",
872
+ * // "action.type": "webhook",
873
+ * // environment: "development",
874
+ * // ...
875
+ * // }
876
+ * ```
877
+ */
878
+ static createLogger(name, params) {
879
+ const logLevel = params.LOG_LEVEL || "info";
880
+ if (!params.ENABLE_TELEMETRY) {
881
+ const baseLogger = import_aio_sdk.Core.Logger(name, { level: logLevel });
882
+ return _Telemetry.wrapLogger(baseLogger, params);
883
+ }
884
+ let telemetryLogger = null;
885
+ let loadingPromise = null;
886
+ const fallbackLogger = import_aio_sdk.Core.Logger(name, { level: logLevel });
887
+ const loadTelemetryLogger = /* @__PURE__ */ __name(async () => {
888
+ if (telemetryLogger || loadingPromise) {
889
+ return;
890
+ }
891
+ loadingPromise = (async () => {
892
+ try {
893
+ const { getLogger } = await import("@adobe/aio-lib-telemetry");
894
+ telemetryLogger = getLogger(name, { level: logLevel });
895
+ } catch (error) {
896
+ telemetryLogger = fallbackLogger;
897
+ }
898
+ })();
899
+ await loadingPromise;
900
+ }, "loadTelemetryLogger");
901
+ loadTelemetryLogger().catch(() => {
902
+ });
903
+ const proxyLogger = {
904
+ debug: /* @__PURE__ */ __name((message) => {
905
+ const logger = telemetryLogger || fallbackLogger;
906
+ logger.debug(message);
907
+ }, "debug"),
908
+ info: /* @__PURE__ */ __name((message) => {
909
+ const logger = telemetryLogger || fallbackLogger;
910
+ logger.info(message);
911
+ }, "info"),
912
+ warn: /* @__PURE__ */ __name((message) => {
913
+ const logger = telemetryLogger || fallbackLogger;
914
+ logger.warn(message);
915
+ }, "warn"),
916
+ error: /* @__PURE__ */ __name((message) => {
917
+ const logger = telemetryLogger || fallbackLogger;
918
+ logger.error(message);
919
+ }, "error")
920
+ };
921
+ return _Telemetry.wrapLogger(proxyLogger, params);
922
+ }
923
+ /**
924
+ * Wrap a logger with automatic metadata injection
925
+ *
926
+ * @private
927
+ * @param baseLogger - The base logger to wrap
928
+ * @param params - Runtime parameters containing optional metadata
929
+ * @returns Wrapped logger with metadata injection
930
+ */
931
+ static wrapLogger(baseLogger, params) {
932
+ const metadata = {};
933
+ const headers = params.__ow_headers;
934
+ const requestId = headers?.["x-adobe-commerce-request-id"];
935
+ if (requestId && requestId !== "") {
936
+ metadata["x-adobe-commerce-request-id"] = requestId;
937
+ }
938
+ const actionType = params.action_type;
939
+ if (actionType && actionType !== "") {
940
+ metadata["action.type"] = actionType;
941
+ }
942
+ if (Object.keys(metadata).length === 0) {
943
+ return baseLogger;
944
+ }
945
+ const wrapper = {
946
+ debug: /* @__PURE__ */ __name((message) => {
947
+ if (typeof message === "object" && message !== null) {
948
+ baseLogger.debug({ ...metadata, ...message });
949
+ } else {
950
+ baseLogger.debug(message);
951
+ }
952
+ }, "debug"),
953
+ info: /* @__PURE__ */ __name((message) => {
954
+ if (typeof message === "object" && message !== null) {
955
+ baseLogger.info({ ...metadata, ...message });
956
+ } else {
957
+ baseLogger.info(message);
958
+ }
959
+ }, "info"),
960
+ warn: /* @__PURE__ */ __name((message) => {
961
+ if (typeof message === "object" && message !== null) {
962
+ baseLogger.warn({ ...metadata, ...message });
963
+ } else {
964
+ baseLogger.warn(message);
965
+ }
966
+ }, "warn"),
967
+ error: /* @__PURE__ */ __name((message) => {
968
+ if (typeof message === "object" && message !== null) {
969
+ baseLogger.error({ ...metadata, ...message });
970
+ } else {
971
+ baseLogger.error(message);
972
+ }
973
+ }, "error")
974
+ };
975
+ return {
976
+ ...baseLogger,
977
+ ...wrapper
978
+ };
979
+ }
980
+ /**
981
+ * Extract structured error information for logging
982
+ *
983
+ * Converts Error objects into a structured format suitable for logging
984
+ * and telemetry systems like New Relic.
985
+ *
986
+ * @param error - Error object or unknown error value
987
+ * @returns Structured error object with name, message, and stack trace
988
+ *
989
+ * @example
990
+ * ```typescript
991
+ * try {
992
+ * // some operation
993
+ * } catch (error) {
994
+ * logger.error("Operation failed", Telemetry.formatError(error));
995
+ * }
996
+ * ```
997
+ */
998
+ static formatError(error) {
999
+ if (error instanceof Error) {
1000
+ return {
1001
+ error_name: error.name,
1002
+ error_message: error.message,
1003
+ error_stack: error.stack
1004
+ };
1005
+ }
1006
+ return { error: String(error) };
1007
+ }
1008
+ /**
1009
+ * Initialize telemetry for a runtime action with provider fallback chain
1010
+ *
1011
+ * Attempts to initialize telemetry providers in the following order:
1012
+ * 1. New Relic (if NEW_RELIC_TELEMETRY=true)
1013
+ * 2. Grafana (if GRAFANA_TELEMETRY=true) - Future support
1014
+ * 3. Original action (no telemetry)
1015
+ *
1016
+ * Telemetry initialization is deferred to runtime when params are available.
1017
+ * This allows proper configuration detection and graceful fallback to the
1018
+ * next provider in the chain.
1019
+ *
1020
+ * **IMPORTANT**: If a provider is explicitly enabled (e.g., NEW_RELIC_TELEMETRY=true)
1021
+ * but has invalid configuration (missing API key, service name), a 500 error response
1022
+ * is returned to alert you of the misconfiguration. This prevents silently running
1023
+ * without telemetry when you expect it to be working.
1024
+ *
1025
+ * Environment Configuration:
1026
+ * Pass params.ENVIRONMENT to set the environment field in all logs.
1027
+ * This can be set via environment variables in your action configuration.
1028
+ *
1029
+ * @param action - The runtime action function to instrument
1030
+ * @returns The instrumented action ready for export
1031
+ *
1032
+ * @example Single provider (New Relic) - Valid configuration
1033
+ * ```typescript
1034
+ * // Environment:
1035
+ * // ENABLE_TELEMETRY=true
1036
+ * // NEW_RELIC_TELEMETRY=true
1037
+ * // NEW_RELIC_SERVICE_NAME=my-service
1038
+ * // NEW_RELIC_LICENSE_KEY=xxxxx
1039
+ *
1040
+ * export const main = Telemetry.initialize(myAction);
1041
+ * // ✅ Uses New Relic telemetry
1042
+ * ```
1043
+ *
1044
+ * @example New Relic enabled but misconfigured - Returns error response
1045
+ * ```typescript
1046
+ * // Environment:
1047
+ * // ENABLE_TELEMETRY=true
1048
+ * // NEW_RELIC_TELEMETRY=true
1049
+ * // NEW_RELIC_SERVICE_NAME=my-service
1050
+ * // Missing NEW_RELIC_LICENSE_KEY!
1051
+ *
1052
+ * export const main = Telemetry.initialize(myAction);
1053
+ * // ❌ Returns { error: { statusCode: 500, body: { error: "Telemetry configuration error: NEW_RELIC_LICENSE_KEY is required" } } }
1054
+ * // This is intentional - you want to know your telemetry config is broken!
1055
+ * ```
1056
+ *
1057
+ * @example Multi-provider fallback
1058
+ * ```typescript
1059
+ * // Environment:
1060
+ * // ENABLE_TELEMETRY=true
1061
+ * // NEW_RELIC_TELEMETRY=false // Skip New Relic
1062
+ * // GRAFANA_TELEMETRY=true // Use Grafana instead
1063
+ *
1064
+ * export const main = Telemetry.initialize(myAction);
1065
+ * // ✅ Skips New Relic, tries Grafana (when implemented)
1066
+ * ```
1067
+ *
1068
+ * @example No telemetry
1069
+ * ```typescript
1070
+ * // Environment:
1071
+ * // ENABLE_TELEMETRY=false (or not set)
1072
+ *
1073
+ * export const main = Telemetry.initialize(myAction);
1074
+ * // ✅ Returns original action without instrumentation
1075
+ * ```
1076
+ */
1077
+ static initialize(action) {
1078
+ return async (params) => {
1079
+ if (params.ENABLE_TELEMETRY && params.NEW_RELIC_TELEMETRY) {
1080
+ try {
1081
+ const { default: NewRelicTelemetry2 } = await Promise.resolve().then(() => (init_new_relic(), new_relic_exports));
1082
+ const newRelicTelemetry = new NewRelicTelemetry2();
1083
+ if (newRelicTelemetry.canInitialize(params)) {
1084
+ try {
1085
+ const instrumentedAction = newRelicTelemetry.initialize(action);
1086
+ return await instrumentedAction(params);
1087
+ } catch (error) {
1088
+ const errorMessage = error instanceof Error ? error.message : "Telemetry initialization failed";
1089
+ return response_default.error(
1090
+ 500 /* INTERNAL_ERROR */,
1091
+ `Telemetry configuration error: ${errorMessage}`
1092
+ );
1093
+ }
1094
+ }
1095
+ } catch (error) {
1096
+ const errorMessage = error instanceof Error ? error.message : "Failed to load telemetry module";
1097
+ return response_default.error(
1098
+ 500 /* INTERNAL_ERROR */,
1099
+ `Telemetry module error: ${errorMessage}`
1100
+ );
1101
+ }
1102
+ }
1103
+ return action(params);
1104
+ };
1105
+ }
1106
+ };
1107
+ __name(_Telemetry, "Telemetry");
1108
+ var Telemetry = _Telemetry;
1109
+ var telemetry_default = Telemetry;
1110
+
230
1111
  // src/framework/runtime-action/index.ts
231
1112
  var _RuntimeAction = class _RuntimeAction {
232
1113
  /**
233
- * @param name
234
- * @param httpMethods
235
- * @param requiredParams
236
- * @param requiredHeaders
237
- * @param action
238
- * @returns {(function(*): Promise<any>)|*}
1114
+ * Sets the action type for the next action execution
1115
+ * This is used for logging to identify different action types
1116
+ * (runtime-action, webhook-action, event-consumer-action, etc.)
1117
+ *
1118
+ * @param type - The action type identifier
1119
+ */
1120
+ static setActionType(type) {
1121
+ _RuntimeAction.actionType = type;
1122
+ }
1123
+ /**
1124
+ * Gets the current action type
1125
+ * @returns The current action type identifier
1126
+ */
1127
+ static getActionType() {
1128
+ return _RuntimeAction.actionType;
1129
+ }
1130
+ /**
1131
+ * Creates a runtime action handler with validation, logging, and telemetry
1132
+ *
1133
+ * Wraps a user-defined action function with standardized runtime functionality:
1134
+ * 1. Creates a structured logger with telemetry integration
1135
+ * 2. Logs action start, headers, and body at debug level
1136
+ * 3. Validates required parameters, headers, and HTTP methods
1137
+ * 4. Executes the user action with logger and headers context
1138
+ * 5. Logs the result and handles errors with appropriate status codes
1139
+ * 6. Integrates with OpenTelemetry for distributed tracing
1140
+ *
1141
+ * @param name - Action name used for logging and telemetry spans (default: 'main')
1142
+ * @param httpMethods - Allowed HTTP methods (GET, POST, etc.). Empty array allows all methods
1143
+ * @param requiredParams - Required parameter names in the request body
1144
+ * @param requiredHeaders - Required header names (case-insensitive)
1145
+ * @param action - User-defined action function that receives:
1146
+ * - params: All request parameters including __ow_* runtime parameters
1147
+ * - ctx: Context object with logger and headers
1148
+ * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint
1149
+ *
1150
+ * @example With All Options
1151
+ * ```typescript
1152
+ * const handler = RuntimeAction.execute(
1153
+ * 'processOrder',
1154
+ * [HttpMethod.POST],
1155
+ * ['orderId', 'customerId'],
1156
+ * ['authorization', 'x-api-key'],
1157
+ * async (params, { logger, headers }) => {
1158
+ * const { orderId, customerId } = params;
1159
+ * logger.info({ message: 'Processing order', orderId, customerId });
1160
+ *
1161
+ * // Your business logic here
1162
+ * const result = await processOrderLogic(orderId, customerId);
1163
+ *
1164
+ * return {
1165
+ * statusCode: 200,
1166
+ * body: { orderId, status: 'processed', result }
1167
+ * };
1168
+ * }
1169
+ * );
1170
+ * ```
1171
+ *
1172
+ * @example Minimal Configuration
1173
+ * ```typescript
1174
+ * const handler = RuntimeAction.execute('simpleAction', [], [], [], async (params, { logger }) => {
1175
+ * logger.info('Simple action executed');
1176
+ * return { statusCode: 200, body: { message: 'Success' } };
1177
+ * });
1178
+ * ```
239
1179
  */
240
1180
  static execute(name = "main", httpMethods = [], requiredParams = [], requiredHeaders = [], action = async (_params) => {
241
1181
  return { statusCode: 200 /* OK */, body: {} };
242
1182
  }) {
243
- return async (params) => {
244
- const logger = import_aio_sdk.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1183
+ const runtimeAction = /* @__PURE__ */ __name(async (params) => {
1184
+ if (!params.action_type) {
1185
+ params.action_type = _RuntimeAction.getActionType();
1186
+ }
1187
+ const logger = telemetry_default.createLogger(name, params);
245
1188
  try {
246
- logger.info(`Calling the ${name} action`);
247
- logger.debug(parameters_default.stringify(params));
1189
+ logger.debug({
1190
+ message: `${name}-started`,
1191
+ action_name: name
1192
+ });
1193
+ logger.debug({
1194
+ message: `${name}-headers`,
1195
+ headers: params.__ow_headers || {}
1196
+ });
1197
+ logger.debug({
1198
+ message: `${name}-body`,
1199
+ body: params.__ow_body || {}
1200
+ });
248
1201
  const validationError = _RuntimeAction.validateRequest(
249
1202
  params,
250
1203
  requiredParams,
251
1204
  requiredHeaders,
252
1205
  httpMethods,
253
- logger
1206
+ logger,
1207
+ name
254
1208
  );
255
1209
  if (validationError) {
256
1210
  return validationError;
257
1211
  }
258
1212
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
259
- logger.info(result);
1213
+ logger.debug({
1214
+ message: `${name}-completed`,
1215
+ result
1216
+ });
260
1217
  return result;
261
1218
  } catch (error) {
262
- logger.error(error);
1219
+ if (error instanceof Error) {
1220
+ logger.error({
1221
+ message: `${name}-failed`,
1222
+ error: error.message,
1223
+ stack: error.stack
1224
+ });
1225
+ } else {
1226
+ logger.error({
1227
+ message: `${name}-failed`,
1228
+ error
1229
+ });
1230
+ }
263
1231
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
264
1232
  }
265
- };
1233
+ }, "runtimeAction");
1234
+ return telemetry_default.initialize(runtimeAction);
266
1235
  }
267
- static validateRequest(params, requiredParams, requiredHeaders, httpMethods, logger) {
1236
+ /**
1237
+ * Validates incoming request against required parameters, headers, and HTTP methods
1238
+ *
1239
+ * This private method performs comprehensive request validation:
1240
+ * 1. Checks for missing required parameters in the request body
1241
+ * 2. Checks for missing required headers (case-insensitive)
1242
+ * 3. Validates the HTTP method against allowed methods list
1243
+ *
1244
+ * @param params - Request parameters including __ow_* runtime parameters
1245
+ * @param requiredParams - List of required parameter names to validate
1246
+ * @param requiredHeaders - List of required header names to validate (case-insensitive)
1247
+ * @param httpMethods - Allowed HTTP methods. Empty array skips HTTP method validation
1248
+ * @param logger - Logger instance for error logging (child logger with request ID if present)
1249
+ * @param name - Action name for logging
1250
+ * @returns RuntimeActionResponseType with error details if validation fails, null if valid
1251
+ *
1252
+ * @private
1253
+ *
1254
+ * @example Validation Error Response
1255
+ * ```typescript
1256
+ * // Missing parameter returns:
1257
+ * {
1258
+ * statusCode: 400,
1259
+ * body: { error: 'Missing required parameter: userId' }
1260
+ * }
1261
+ *
1262
+ * // Invalid HTTP method returns:
1263
+ * {
1264
+ * statusCode: 405,
1265
+ * body: { error: 'Invalid HTTP method: DELETE. Allowed methods are: GET, POST' }
1266
+ * }
1267
+ * ```
1268
+ */
1269
+ static validateRequest(params, requiredParams, requiredHeaders, httpMethods, logger, name) {
268
1270
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
269
1271
  if (errorMessage) {
1272
+ logger.error({
1273
+ message: `${name}-validation-failed`,
1274
+ error: errorMessage
1275
+ });
270
1276
  return response_default.error(400 /* BAD_REQUEST */, errorMessage);
271
1277
  }
272
1278
  const requestMethod = params.__ow_method?.toUpperCase();
273
1279
  if (httpMethods.length > 0 && !httpMethods.includes(requestMethod)) {
274
1280
  const errorMessage2 = `Invalid HTTP method: ${params.__ow_method}. Allowed methods are: ${httpMethods.join(", ")}`;
275
- logger.error(errorMessage2);
1281
+ logger.error({
1282
+ message: `${name}-validation-failed`,
1283
+ error: errorMessage2
1284
+ });
276
1285
  return response_default.error(405 /* METHOD_NOT_ALLOWED */, errorMessage2);
277
1286
  }
278
1287
  return null;
279
1288
  }
280
1289
  };
281
1290
  __name(_RuntimeAction, "RuntimeAction");
1291
+ /**
1292
+ * Private static property to store the action type for logging
1293
+ * Can be set using setActionType() before calling execute()
1294
+ */
1295
+ _RuntimeAction.actionType = "runtime-action";
282
1296
  var RuntimeAction = _RuntimeAction;
283
1297
  var runtime_action_default = RuntimeAction;
284
1298
 
1299
+ // src/framework/runtime-action/response/types.ts
1300
+ init_cjs_shims();
1301
+
1302
+ // src/framework/runtime-action/parameters/index.ts
1303
+ init_cjs_shims();
1304
+ var _Parameters = class _Parameters {
1305
+ /**
1306
+ * Returns a log-ready string of the action input parameters.
1307
+ * The `Authorization` header content will be replaced by '<hidden>'.
1308
+ *
1309
+ * @param params action input parameters.
1310
+ *
1311
+ * @returns string
1312
+ */
1313
+ static stringify(params) {
1314
+ let headers = params.__ow_headers || {};
1315
+ if (headers.authorization) {
1316
+ headers = { ...headers, authorization: "<hidden>" };
1317
+ }
1318
+ return JSON.stringify({ ...params, __ow_headers: headers });
1319
+ }
1320
+ };
1321
+ __name(_Parameters, "Parameters");
1322
+ var Parameters = _Parameters;
1323
+ var parameters_default = Parameters;
1324
+
285
1325
  // src/framework/event-consumer-action/index.ts
286
- var import_aio_sdk2 = require("@adobe/aio-sdk");
1326
+ init_cjs_shims();
287
1327
  var _EventConsumerAction = class _EventConsumerAction {
288
1328
  /**
289
- * @param name
290
- * @param requiredParams
291
- * @param requiredHeaders
292
- * @param action
293
- * @returns {(function(*): Promise<any>)|*}
1329
+ * Creates an event consumer action handler with telemetry integration
1330
+ *
1331
+ * This method wraps a user-defined action with:
1332
+ * - Structured logging (all logs automatically include x-adobe-commerce-request-id if present)
1333
+ * - Request validation for required parameters and headers
1334
+ * - OpenTelemetry instrumentation
1335
+ * - Standardized error handling
1336
+ *
1337
+ * @param name - Action name for logging and observability
1338
+ * @param requiredParams - List of required parameter names to validate
1339
+ * @param requiredHeaders - List of required header names to validate (case-insensitive)
1340
+ * @param action - User's event consumer function that receives params and context
1341
+ * @returns Wrapped action handler ready for OpenWhisk runtime
1342
+ *
1343
+ * @example
1344
+ * ```typescript
1345
+ * const handler = EventConsumerAction.execute(
1346
+ * 'webhook-processor',
1347
+ * ['eventType', 'eventData'],
1348
+ * ['x-webhook-signature'],
1349
+ * async (params, { logger, headers }) => {
1350
+ * logger.info({
1351
+ * message: 'Processing webhook',
1352
+ * eventType: params.eventType
1353
+ * });
1354
+ * // Process event...
1355
+ * return { statusCode: 200, body: { processed: true } };
1356
+ * }
1357
+ * );
1358
+ * ```
294
1359
  */
295
1360
  static execute(name = "main", requiredParams = [], requiredHeaders = [], action = async (_params) => {
296
1361
  return { statusCode: 200 /* OK */, body: {} };
297
1362
  }) {
298
- return async (params) => {
299
- const logger = import_aio_sdk2.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1363
+ const eventConsumerAction = /* @__PURE__ */ __name(async (params) => {
1364
+ params.action_type = "event-consumer-action";
1365
+ const logger = telemetry_default.createLogger(name, params);
300
1366
  try {
301
- logger.info(`Calling the ${name} action`);
302
- logger.debug(parameters_default.stringify(params));
1367
+ logger.debug({
1368
+ message: `${name}-started`,
1369
+ action_name: name
1370
+ });
1371
+ logger.debug({
1372
+ message: `${name}-headers`,
1373
+ headers: params.__ow_headers || {}
1374
+ });
1375
+ logger.debug({
1376
+ message: `${name}-parameters`,
1377
+ parameters: params
1378
+ });
303
1379
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) || "";
304
1380
  if (errorMessage) {
1381
+ logger.error({
1382
+ message: `${name}-validation-failed`,
1383
+ error: errorMessage
1384
+ });
305
1385
  return response_default.error(400 /* BAD_REQUEST */, errorMessage);
306
1386
  }
307
1387
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
308
- logger.info(result);
1388
+ logger.debug({
1389
+ message: `${name}-completed`,
1390
+ result
1391
+ });
309
1392
  return result;
310
1393
  } catch (error) {
311
- logger.error(error);
1394
+ if (error instanceof Error) {
1395
+ logger.error({
1396
+ error: error.message,
1397
+ stack: error.stack
1398
+ });
1399
+ } else {
1400
+ logger.error({ error });
1401
+ }
312
1402
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
313
1403
  }
314
- };
1404
+ }, "eventConsumerAction");
1405
+ return telemetry_default.initialize(eventConsumerAction);
315
1406
  }
316
1407
  };
317
1408
  __name(_EventConsumerAction, "EventConsumerAction");
@@ -319,6 +1410,7 @@ var EventConsumerAction = _EventConsumerAction;
319
1410
  var event_consumer_action_default = EventConsumerAction;
320
1411
 
321
1412
  // src/framework/graphql-action/index.ts
1413
+ init_cjs_shims();
322
1414
  var import_graphql = require("graphql");
323
1415
  var _GraphQlAction = class _GraphQlAction {
324
1416
  static execute(schema = `
@@ -396,6 +1488,7 @@ var GraphQlAction = _GraphQlAction;
396
1488
  var graphql_action_default = GraphQlAction;
397
1489
 
398
1490
  // src/framework/openwhisk/index.ts
1491
+ init_cjs_shims();
399
1492
  var import_openwhisk = __toESM(require("openwhisk"));
400
1493
  var _Openwhisk = class _Openwhisk {
401
1494
  /**
@@ -423,29 +1516,84 @@ var Openwhisk = _Openwhisk;
423
1516
  var openwhisk_default = Openwhisk;
424
1517
 
425
1518
  // src/framework/openwhisk-action/index.ts
426
- var import_aio_sdk3 = require("@adobe/aio-sdk");
1519
+ init_cjs_shims();
427
1520
  var _OpenwhiskAction = class _OpenwhiskAction {
428
1521
  /**
429
- * @param name
430
- * @param action
431
- * @returns {(function(*): Promise<any>)|*}
1522
+ * Creates an OpenWhisk webhook action handler with logging and telemetry
1523
+ *
1524
+ * Wraps a user-defined action function with standardized runtime functionality:
1525
+ * 1. Creates a structured logger with telemetry integration
1526
+ * 2. Logs action start with structured data
1527
+ * 3. Logs request parameters at debug level
1528
+ * 4. Executes the user action with logger and headers context
1529
+ * 5. Logs the result and handles errors with appropriate status codes
1530
+ * 6. Integrates with OpenTelemetry for distributed tracing
1531
+ *
1532
+ * The logger automatically includes x-adobe-commerce-request-id and action.type
1533
+ * (if present) in all log messages.
1534
+ *
1535
+ * @param name - Action name used for logging and telemetry spans (default: 'main')
1536
+ * @param action - User-defined action function that receives:
1537
+ * - params: All request parameters including __ow_* runtime parameters
1538
+ * - ctx: Context object with logger and headers
1539
+ * @returns Wrapped action function ready to be exported as Adobe I/O Runtime entrypoint
1540
+ *
1541
+ * @example Complete Example
1542
+ * ```typescript
1543
+ * const handler = OpenwhiskAction.execute(
1544
+ * 'processWebhook',
1545
+ * async (params, { logger, headers }) => {
1546
+ * logger.info({ message: 'Webhook received', event: params.event });
1547
+ *
1548
+ * // Your webhook processing logic here
1549
+ * const result = await processWebhookData(params);
1550
+ *
1551
+ * return {
1552
+ * statusCode: 200,
1553
+ * body: { status: 'processed', result }
1554
+ * };
1555
+ * }
1556
+ * );
1557
+ * ```
432
1558
  */
433
1559
  static execute(name = "main", action = async (_params) => {
434
1560
  return { statusCode: 200 /* OK */, body: {} };
435
1561
  }) {
436
- return async (params) => {
437
- const logger = import_aio_sdk3.Core.Logger(name, { level: params.LOG_LEVEL || "info" });
1562
+ const openwhiskAction = /* @__PURE__ */ __name(async (params) => {
1563
+ params.action_type = "openwhisk-action";
1564
+ const logger = telemetry_default.createLogger(name, params);
438
1565
  try {
439
- logger.info(`Calling the ${name} webhook action`);
440
- logger.debug(parameters_default.stringify(params));
1566
+ logger.debug({
1567
+ message: `${name}-started`,
1568
+ action_name: name
1569
+ });
1570
+ logger.debug({
1571
+ message: `${name}-params`,
1572
+ params
1573
+ });
441
1574
  const result = await action(params, { logger, headers: params.__ow_headers || {} });
442
- logger.info(result);
1575
+ logger.debug({
1576
+ message: `${name}-completed`,
1577
+ result
1578
+ });
443
1579
  return result;
444
1580
  } catch (error) {
445
- logger.error(error);
1581
+ if (error instanceof Error) {
1582
+ logger.error({
1583
+ message: `${name}-failed`,
1584
+ error: error.message,
1585
+ stack: error.stack
1586
+ });
1587
+ } else {
1588
+ logger.error({
1589
+ message: `${name}-failed`,
1590
+ error
1591
+ });
1592
+ }
446
1593
  return response_default.error(500 /* INTERNAL_ERROR */, "server error");
447
1594
  }
448
- };
1595
+ }, "openwhiskAction");
1596
+ return telemetry_default.initialize(openwhiskAction);
449
1597
  }
450
1598
  };
451
1599
  __name(_OpenwhiskAction, "OpenwhiskAction");
@@ -453,7 +1601,8 @@ var OpenwhiskAction = _OpenwhiskAction;
453
1601
  var openwhisk_action_default = OpenwhiskAction;
454
1602
 
455
1603
  // src/framework/repository/file-repository/index.ts
456
- var import_aio_sdk4 = require("@adobe/aio-sdk");
1604
+ init_cjs_shims();
1605
+ var import_aio_sdk2 = require("@adobe/aio-sdk");
457
1606
  var _FileRepository = class _FileRepository {
458
1607
  /**
459
1608
  * Creates a new FileRepository instance
@@ -600,7 +1749,7 @@ var _FileRepository = class _FileRepository {
600
1749
  */
601
1750
  async getFiles() {
602
1751
  if (!this.files) {
603
- this.files = await import_aio_sdk4.Files.init();
1752
+ this.files = await import_aio_sdk2.Files.init();
604
1753
  }
605
1754
  return this.files;
606
1755
  }
@@ -609,12 +1758,17 @@ __name(_FileRepository, "FileRepository");
609
1758
  var FileRepository = _FileRepository;
610
1759
  var file_repository_default = FileRepository;
611
1760
 
1761
+ // src/framework/repository/file-repository/types.ts
1762
+ init_cjs_shims();
1763
+
612
1764
  // src/framework/publish-event/index.ts
613
- var import_aio_sdk5 = require("@adobe/aio-sdk");
1765
+ init_cjs_shims();
1766
+ var import_aio_sdk3 = require("@adobe/aio-sdk");
614
1767
  var import_cloudevents = require("cloudevents");
615
1768
  var import_uuid = require("uuid");
616
1769
 
617
1770
  // src/framework/custom-logger/index.ts
1771
+ init_cjs_shims();
618
1772
  var _CustomLogger = class _CustomLogger {
619
1773
  /**
620
1774
  * @param logger - External logger instance (can be null)
@@ -723,7 +1877,7 @@ var _PublishEvent = class _PublishEvent {
723
1877
  ...subject && { subject }
724
1878
  });
725
1879
  this.customLogger.debug(`Constructed CloudEvent with ID: ${eventId}`);
726
- const eventsClient = await import_aio_sdk5.Events.init(this.imsOrgId, this.apiKey, this.accessToken);
1880
+ const eventsClient = await import_aio_sdk3.Events.init(this.imsOrgId, this.apiKey, this.accessToken);
727
1881
  this.customLogger.debug("Adobe I/O Events client initialized successfully");
728
1882
  await eventsClient.publishEvent(cloudEvent);
729
1883
  const publishedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -749,7 +1903,17 @@ __name(_PublishEvent, "PublishEvent");
749
1903
  var PublishEvent = _PublishEvent;
750
1904
  var publish_event_default = PublishEvent;
751
1905
 
1906
+ // src/framework/publish-event/types.ts
1907
+ init_cjs_shims();
1908
+
1909
+ // src/framework/webhook-action/index.ts
1910
+ init_cjs_shims();
1911
+
1912
+ // src/framework/webhook-action/response/index.ts
1913
+ init_cjs_shims();
1914
+
752
1915
  // src/framework/webhook-action/response/types.ts
1916
+ init_cjs_shims();
753
1917
  var WebhookActionOperation = /* @__PURE__ */ ((WebhookActionOperation2) => {
754
1918
  WebhookActionOperation2["SUCCESS"] = "success";
755
1919
  WebhookActionOperation2["EXCEPTION"] = "exception";
@@ -948,6 +2112,7 @@ var WebhookActionResponse = _WebhookActionResponse;
948
2112
  var response_default2 = WebhookActionResponse;
949
2113
 
950
2114
  // src/framework/webhook-action/types.ts
2115
+ init_cjs_shims();
951
2116
  var SignatureVerification = /* @__PURE__ */ ((SignatureVerification2) => {
952
2117
  SignatureVerification2["ENABLED"] = "enabled";
953
2118
  SignatureVerification2["DISABLED"] = "disabled";
@@ -998,9 +2163,14 @@ var _WebhookAction = class _WebhookAction {
998
2163
  return null;
999
2164
  }, "verifySignature");
1000
2165
  const callback = /* @__PURE__ */ __name(async (params, ctx) => {
2166
+ const { logger } = ctx;
1001
2167
  if (signatureVerification === "enabled" /* ENABLED */) {
1002
2168
  const verificationErrorMessage = await verifySignature(params);
1003
2169
  if (verificationErrorMessage) {
2170
+ logger.error({
2171
+ message: `${name}-signature-verification-failed`,
2172
+ error: verificationErrorMessage
2173
+ });
1004
2174
  const verificationErrorResponse = response_default2.exception(verificationErrorMessage);
1005
2175
  return response_default.success(JSON.stringify(verificationErrorResponse));
1006
2176
  }
@@ -1011,12 +2181,17 @@ var _WebhookAction = class _WebhookAction {
1011
2181
  }
1012
2182
  const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
1013
2183
  if (errorMessage) {
2184
+ logger.error({
2185
+ message: `${name}-validation-failed`,
2186
+ error: errorMessage
2187
+ });
1014
2188
  const errorMessageResponse = response_default2.exception(errorMessage);
1015
2189
  return response_default.success(JSON.stringify(errorMessageResponse));
1016
2190
  }
1017
2191
  const response = await action(params, ctx);
1018
2192
  return response_default.success(JSON.stringify(response));
1019
2193
  }, "callback");
2194
+ runtime_action_default.setActionType("webhook-action");
1020
2195
  return runtime_action_default.execute(name, httpMethods, [], [], callback);
1021
2196
  }
1022
2197
  };
@@ -1025,10 +2200,12 @@ var WebhookAction = _WebhookAction;
1025
2200
  var webhook_action_default = WebhookAction;
1026
2201
 
1027
2202
  // src/framework/ims-token/index.ts
1028
- var import_aio_sdk6 = require("@adobe/aio-sdk");
2203
+ init_cjs_shims();
2204
+ var import_aio_sdk4 = require("@adobe/aio-sdk");
1029
2205
 
1030
2206
  // src/commerce/adobe-auth/index.ts
1031
- var import_aio_lib_ims = require("@adobe/aio-lib-ims");
2207
+ init_cjs_shims();
2208
+ var aioLibIms = __toESM(require("@adobe/aio-lib-ims"));
1032
2209
  var _AdobeAuth = class _AdobeAuth {
1033
2210
  /**
1034
2211
  * Retrieves an authentication token from Adobe IMS
@@ -1061,9 +2238,9 @@ var _AdobeAuth = class _AdobeAuth {
1061
2238
  ims_org_id: imsOrgId,
1062
2239
  scopes
1063
2240
  };
1064
- await import_aio_lib_ims.context.setCurrent(currentContext);
1065
- await import_aio_lib_ims.context.set(currentContext, config);
1066
- return await (0, import_aio_lib_ims.getToken)();
2241
+ await aioLibIms.context.setCurrent(currentContext);
2242
+ await aioLibIms.context.set(currentContext, config);
2243
+ return await aioLibIms.getToken();
1067
2244
  }
1068
2245
  };
1069
2246
  __name(_AdobeAuth, "AdobeAuth");
@@ -1071,6 +2248,7 @@ var AdobeAuth = _AdobeAuth;
1071
2248
  var adobe_auth_default = AdobeAuth;
1072
2249
 
1073
2250
  // src/integration/bearer-token/index.ts
2251
+ init_cjs_shims();
1074
2252
  var _BearerToken = class _BearerToken {
1075
2253
  /**
1076
2254
  * Extracts the Bearer token from HTTP request headers and returns detailed token information.
@@ -1219,6 +2397,9 @@ var _ImsToken = class _ImsToken {
1219
2397
  /**
1220
2398
  * Creates an instance of ImsToken
1221
2399
  *
2400
+ * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.
2401
+ * See class documentation for migration examples.
2402
+ *
1222
2403
  * @param clientId - OAuth client ID for Adobe IMS authentication
1223
2404
  * @param clientSecret - OAuth client secret for Adobe IMS authentication
1224
2405
  * @param technicalAccountId - Technical account ID for service-to-service authentication
@@ -1245,6 +2426,10 @@ var _ImsToken = class _ImsToken {
1245
2426
  /**
1246
2427
  * Executes IMS token generation or retrieves a cached token
1247
2428
  *
2429
+ * @deprecated Use `AdobeAuth.getToken()` directly and implement caching in your application.
2430
+ * The built-in caching mechanism has reliability issues with the State API.
2431
+ * See class documentation for migration examples.
2432
+ *
1248
2433
  * This method first checks for a cached token. If a valid cached token exists,
1249
2434
  * it returns that. Otherwise, it generates a new token, caches it, and returns it.
1250
2435
  *
@@ -1327,6 +2512,14 @@ var _ImsToken = class _ImsToken {
1327
2512
  /**
1328
2513
  * Caches the IMS token in the state store with TTL
1329
2514
  *
2515
+ * @deprecated This method has issues with State API reliability. Use application-level caching instead.
2516
+ *
2517
+ * **Known Issues:**
2518
+ * - State API may not be available in all runtime environments
2519
+ * - Hard-coded 10-minute buffer may not suit all use cases
2520
+ * - Minimum 60-minute TTL is opinionated and inflexible
2521
+ * - No retry mechanism for State API failures
2522
+ *
1330
2523
  * @param result - The token result containing the token and expiration time
1331
2524
  * @returns A promise that resolves to true if caching succeeded, false otherwise
1332
2525
  * @private
@@ -1352,6 +2545,13 @@ var _ImsToken = class _ImsToken {
1352
2545
  /**
1353
2546
  * Retrieves a cached IMS token from the state store
1354
2547
  *
2548
+ * @deprecated This method has issues with State API reliability. Use application-level caching instead.
2549
+ *
2550
+ * **Known Issues:**
2551
+ * - State API may not be available in all runtime environments
2552
+ * - No validation of cached token expiry
2553
+ * - Silent failures may return null without proper error context
2554
+ *
1355
2555
  * @returns A promise that resolves to the cached token string or null if not found
1356
2556
  * @private
1357
2557
  */
@@ -1377,6 +2577,14 @@ var _ImsToken = class _ImsToken {
1377
2577
  /**
1378
2578
  * Initializes and returns the state store instance
1379
2579
  *
2580
+ * @deprecated This method relies on State API which has reliability issues.
2581
+ * Use application-level caching instead.
2582
+ *
2583
+ * **Known Issues:**
2584
+ * - State API initialization may fail silently
2585
+ * - Not available outside Adobe I/O Runtime environments
2586
+ * - Caches the state instance which may become stale
2587
+ *
1380
2588
  * @returns A promise that resolves to the state instance or null if initialization fails
1381
2589
  * @private
1382
2590
  */
@@ -1384,7 +2592,7 @@ var _ImsToken = class _ImsToken {
1384
2592
  if (this.state === void 0) {
1385
2593
  try {
1386
2594
  this.customLogger.debug("Initializing State API for token caching");
1387
- this.state = await import_aio_sdk6.State.init();
2595
+ this.state = await import_aio_sdk4.State.init();
1388
2596
  } catch (error) {
1389
2597
  this.customLogger.error(`Failed to initialize State API: ${error.message}`);
1390
2598
  this.state = null;
@@ -1397,7 +2605,14 @@ __name(_ImsToken, "ImsToken");
1397
2605
  var ImsToken = _ImsToken;
1398
2606
  var ims_token_default = ImsToken;
1399
2607
 
2608
+ // src/framework/ims-token/types.ts
2609
+ init_cjs_shims();
2610
+
2611
+ // src/framework/runtime-api-gateway-service/index.ts
2612
+ init_cjs_shims();
2613
+
1400
2614
  // src/integration/rest-client/index.ts
2615
+ init_cjs_shims();
1401
2616
  var import_node_fetch = __toESM(require("node-fetch"));
1402
2617
  var _RestClient = class _RestClient {
1403
2618
  /**
@@ -1574,44 +2789,26 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1574
2789
  /**
1575
2790
  * Creates an instance of RuntimeApiGatewayService
1576
2791
  *
1577
- * @param clientId - OAuth client ID for Adobe IMS authentication
1578
- * @param clientSecret - OAuth client secret for Adobe IMS authentication
1579
- * @param technicalAccountId - Technical account ID for service-to-service authentication
1580
- * @param technicalAccountEmail - Technical account email for service-to-service authentication
1581
- * @param imsOrgId - IMS organization ID
1582
- * @param scopes - Array of scopes required for the token
1583
2792
  * @param namespace - The Adobe I/O Runtime namespace identifier
2793
+ * @param imsOrgId - IMS organization ID
2794
+ * @param imsToken - Bearer token string for authentication
1584
2795
  * @param logger - Optional logger instance for logging operations
1585
2796
  * @example
1586
2797
  * ```typescript
1587
2798
  * const service = new RuntimeApiGatewayService(
1588
- * 'client-id',
1589
- * 'client-secret',
1590
- * 'tech-account-id',
1591
- * 'tech@example.com',
1592
- * 'org-id',
1593
- * ['openid', 'AdobeID'],
1594
- * 'my-namespace-12345',
1595
- * logger // optional
2799
+ * 'test-namespace',
2800
+ * 'org-id@AdobeOrg',
2801
+ * 'bearer-token-string',
2802
+ * logger
1596
2803
  * );
1597
2804
  * ```
1598
2805
  */
1599
- constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, namespace, logger = null) {
2806
+ constructor(namespace, imsOrgId, imsToken, logger = null) {
1600
2807
  this.namespace = namespace;
1601
2808
  this.imsOrgId = imsOrgId;
1602
- this.customLogger = new custom_logger_default(logger);
1603
- this.imsToken = new ims_token_default(
1604
- clientId,
1605
- clientSecret,
1606
- technicalAccountId,
1607
- technicalAccountEmail,
1608
- imsOrgId,
1609
- scopes,
1610
- logger,
1611
- "runtime_api_gateway_token",
1612
- "runtime-api-gateway-context"
1613
- );
2809
+ this.imsToken = imsToken;
1614
2810
  this.restClient = new rest_client_default();
2811
+ this.customLogger = new custom_logger_default(logger);
1615
2812
  }
1616
2813
  /**
1617
2814
  * Builds the complete API endpoint URL
@@ -1626,21 +2823,13 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1626
2823
  /**
1627
2824
  * Gets the authenticated headers for API requests
1628
2825
  *
1629
- * @returns A promise that resolves with the headers object including authentication
1630
- * @throws {Error} If token generation fails
2826
+ * @returns Headers object including authentication
1631
2827
  * @private
1632
2828
  */
1633
- async getAuthenticatedHeaders() {
1634
- this.customLogger.debug("Generating authenticated headers for API request");
1635
- const token = await this.imsToken.execute();
1636
- if (!token) {
1637
- this.customLogger.error("Failed to generate IMS token for authenticated headers");
1638
- throw new Error("Failed to generate IMS token");
1639
- }
1640
- this.customLogger.debug("Successfully generated authenticated headers");
2829
+ getAuthenticatedHeaders() {
1641
2830
  return {
1642
2831
  "Content-Type": "application/json",
1643
- Authorization: `Bearer ${token}`,
2832
+ Authorization: `Bearer ${this.imsToken}`,
1644
2833
  "x-gw-ims-org-id": this.imsOrgId
1645
2834
  };
1646
2835
  }
@@ -1664,7 +2853,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1664
2853
  try {
1665
2854
  const url = this.buildEndpoint(endpoint);
1666
2855
  this.customLogger.info(`Performing GET request to: ${url}`);
1667
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
2856
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1668
2857
  this.customLogger.debug(`GET headers: ${JSON.stringify(headers)}`);
1669
2858
  const response = await this.restClient.get(url, headers, false);
1670
2859
  this.customLogger.debug(`GET response: ${JSON.stringify(response)}`);
@@ -1698,7 +2887,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1698
2887
  const url = this.buildEndpoint(endpoint);
1699
2888
  this.customLogger.info(`Performing POST request to: ${url}`);
1700
2889
  this.customLogger.debug(`POST payload: ${JSON.stringify(payload)}`);
1701
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
2890
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1702
2891
  this.customLogger.debug(`POST headers: ${JSON.stringify(headers)}`);
1703
2892
  const response = await this.restClient.post(url, headers, payload, false);
1704
2893
  this.customLogger.debug(`POST response: ${JSON.stringify(response)}`);
@@ -1732,7 +2921,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1732
2921
  const url = this.buildEndpoint(endpoint);
1733
2922
  this.customLogger.info(`Performing PUT request to: ${url}`);
1734
2923
  this.customLogger.debug(`PUT payload: ${JSON.stringify(payload)}`);
1735
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
2924
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1736
2925
  this.customLogger.debug(`PUT headers: ${JSON.stringify(headers)}`);
1737
2926
  const response = await this.restClient.put(url, headers, payload, false);
1738
2927
  this.customLogger.debug(`PUT response: ${JSON.stringify(response)}`);
@@ -1764,7 +2953,7 @@ var _RuntimeApiGatewayService = class _RuntimeApiGatewayService {
1764
2953
  try {
1765
2954
  const url = this.buildEndpoint(endpoint);
1766
2955
  this.customLogger.info(`Performing DELETE request to: ${url}`);
1767
- const headers = { ...await this.getAuthenticatedHeaders(), ...additionalHeaders };
2956
+ const headers = { ...this.getAuthenticatedHeaders(), ...additionalHeaders };
1768
2957
  this.customLogger.debug(`DELETE headers: ${JSON.stringify(headers)}`);
1769
2958
  const response = await this.restClient.delete(url, headers, false);
1770
2959
  this.customLogger.debug(`DELETE response: ${JSON.stringify(response)}`);
@@ -1782,10 +2971,35 @@ __name(_RuntimeApiGatewayService, "RuntimeApiGatewayService");
1782
2971
  _RuntimeApiGatewayService.BASE_URL = "https://adobeioruntime.net/apis";
1783
2972
  var RuntimeApiGatewayService = _RuntimeApiGatewayService;
1784
2973
 
2974
+ // src/framework/telemetry/types.ts
2975
+ init_cjs_shims();
2976
+
2977
+ // src/framework/index.ts
2978
+ init_input_error();
2979
+ init_success_checker();
2980
+ init_json_message_processor();
2981
+
2982
+ // src/integration/index.ts
2983
+ init_cjs_shims();
2984
+
1785
2985
  // src/integration/onboard-events/index.ts
1786
- var import_aio_sdk7 = require("@adobe/aio-sdk");
2986
+ init_cjs_shims();
2987
+ var import_aio_sdk5 = require("@adobe/aio-sdk");
2988
+
2989
+ // src/integration/onboard-events/create-providers/index.ts
2990
+ init_cjs_shims();
2991
+
2992
+ // src/io-events/index.ts
2993
+ init_cjs_shims();
2994
+
2995
+ // src/io-events/provider/index.ts
2996
+ init_cjs_shims();
2997
+
2998
+ // src/io-events/provider/list/index.ts
2999
+ init_cjs_shims();
1787
3000
 
1788
3001
  // src/io-events/types.ts
3002
+ init_cjs_shims();
1789
3003
  var IoEventsGlobals = {
1790
3004
  BASE_URL: "https://api.adobe.io",
1791
3005
  STATUS_CODES: {
@@ -2022,6 +3236,7 @@ var List = _List;
2022
3236
  var list_default = List;
2023
3237
 
2024
3238
  // src/io-events/provider/get/index.ts
3239
+ init_cjs_shims();
2025
3240
  var _Get = class _Get {
2026
3241
  /**
2027
3242
  * Constructor for Get provider service
@@ -2198,6 +3413,7 @@ var Get = _Get;
2198
3413
  var get_default = Get;
2199
3414
 
2200
3415
  // src/io-events/provider/create/index.ts
3416
+ init_cjs_shims();
2201
3417
  var _Create = class _Create {
2202
3418
  /**
2203
3419
  * Constructor for Create provider service
@@ -2365,6 +3581,7 @@ var Create = _Create;
2365
3581
  var create_default = Create;
2366
3582
 
2367
3583
  // src/io-events/provider/delete/index.ts
3584
+ init_cjs_shims();
2368
3585
  var _Delete = class _Delete {
2369
3586
  /**
2370
3587
  * Creates an instance of Delete service
@@ -2691,7 +3908,11 @@ __name(_ProviderManager, "ProviderManager");
2691
3908
  var ProviderManager = _ProviderManager;
2692
3909
  var provider_default = ProviderManager;
2693
3910
 
3911
+ // src/io-events/event-metadata/index.ts
3912
+ init_cjs_shims();
3913
+
2694
3914
  // src/io-events/event-metadata/list/index.ts
3915
+ init_cjs_shims();
2695
3916
  var _List2 = class _List2 {
2696
3917
  /**
2697
3918
  * Creates an instance of List service
@@ -2882,6 +4103,7 @@ __name(_List2, "List");
2882
4103
  var List2 = _List2;
2883
4104
 
2884
4105
  // src/io-events/event-metadata/get/index.ts
4106
+ init_cjs_shims();
2885
4107
  var _Get2 = class _Get2 {
2886
4108
  /**
2887
4109
  * Creates an instance of Get service
@@ -3052,6 +4274,7 @@ __name(_Get2, "Get");
3052
4274
  var Get2 = _Get2;
3053
4275
 
3054
4276
  // src/io-events/event-metadata/create/index.ts
4277
+ init_cjs_shims();
3055
4278
  var _Create2 = class _Create2 {
3056
4279
  /**
3057
4280
  * Constructor for Create event metadata service
@@ -3316,6 +4539,7 @@ var Create2 = _Create2;
3316
4539
  var create_default2 = Create2;
3317
4540
 
3318
4541
  // src/io-events/event-metadata/delete/index.ts
4542
+ init_cjs_shims();
3319
4543
  var _Delete2 = class _Delete2 {
3320
4544
  /**
3321
4545
  * Constructor for Delete event metadata service
@@ -3625,7 +4849,11 @@ __name(_EventMetadataManager, "EventMetadataManager");
3625
4849
  var EventMetadataManager = _EventMetadataManager;
3626
4850
  var event_metadata_default = EventMetadataManager;
3627
4851
 
4852
+ // src/io-events/registration/index.ts
4853
+ init_cjs_shims();
4854
+
3628
4855
  // src/io-events/registration/create/index.ts
4856
+ init_cjs_shims();
3629
4857
  var _Create3 = class _Create3 {
3630
4858
  /**
3631
4859
  * Initialize the Create service
@@ -3810,6 +5038,7 @@ var Create3 = _Create3;
3810
5038
  var create_default3 = Create3;
3811
5039
 
3812
5040
  // src/io-events/registration/delete/index.ts
5041
+ init_cjs_shims();
3813
5042
  var _Delete3 = class _Delete3 {
3814
5043
  /**
3815
5044
  * Initialize the Delete service
@@ -3928,6 +5157,7 @@ var Delete3 = _Delete3;
3928
5157
  var delete_default2 = Delete3;
3929
5158
 
3930
5159
  // src/io-events/registration/get/index.ts
5160
+ init_cjs_shims();
3931
5161
  var _Get3 = class _Get3 {
3932
5162
  /**
3933
5163
  * Initialize the Get service
@@ -4047,6 +5277,7 @@ var Get3 = _Get3;
4047
5277
  var get_default2 = Get3;
4048
5278
 
4049
5279
  // src/io-events/registration/list/index.ts
5280
+ init_cjs_shims();
4050
5281
  var _List3 = class _List3 {
4051
5282
  /**
4052
5283
  * Initialize the List service
@@ -4510,6 +5741,7 @@ var CreateProviders = _CreateProviders;
4510
5741
  var create_providers_default = CreateProviders;
4511
5742
 
4512
5743
  // src/integration/onboard-events/create-events/index.ts
5744
+ init_cjs_shims();
4513
5745
  var _CreateEvents = class _CreateEvents {
4514
5746
  /**
4515
5747
  * Creates a new CreateEvents instance
@@ -4725,6 +5957,7 @@ var CreateEvents = _CreateEvents;
4725
5957
  var create_events_default = CreateEvents;
4726
5958
 
4727
5959
  // src/integration/onboard-events/create-registrations/index.ts
5960
+ init_cjs_shims();
4728
5961
  var _CreateRegistrations = class _CreateRegistrations {
4729
5962
  /**
4730
5963
  * Creates a new CreateRegistrations instance
@@ -4998,6 +6231,7 @@ var CreateRegistrations = _CreateRegistrations;
4998
6231
  var create_registrations_default = CreateRegistrations;
4999
6232
 
5000
6233
  // src/integration/onboard-events/input-parser/index.ts
6234
+ init_cjs_shims();
5001
6235
  var _InputParser = class _InputParser {
5002
6236
  constructor(input) {
5003
6237
  this.entities = {
@@ -5096,7 +6330,7 @@ var _OnboardEvents = class _OnboardEvents {
5096
6330
  throw new Error("Access token is required");
5097
6331
  }
5098
6332
  const loggerName = projectName.toLowerCase().replace(/[^a-z0-9\s-_]/g, "").replace(/\s+/g, "-").replace(/_{2,}/g, "_").replace(/-{2,}/g, "-").trim().concat("-onboard-events");
5099
- this.logger = import_aio_sdk7.Core.Logger(loggerName, { level: "debug" });
6333
+ this.logger = import_aio_sdk5.Core.Logger(loggerName, { level: "debug" });
5100
6334
  this.createProviders = new create_providers_default(
5101
6335
  consumerId,
5102
6336
  projectId,
@@ -5292,7 +6526,8 @@ var OnboardEvents = _OnboardEvents;
5292
6526
  var onboard_events_default = OnboardEvents;
5293
6527
 
5294
6528
  // src/integration/infinite-loop-breaker/index.ts
5295
- var import_aio_sdk8 = require("@adobe/aio-sdk");
6529
+ init_cjs_shims();
6530
+ var import_aio_sdk6 = require("@adobe/aio-sdk");
5296
6531
  var import_crypto3 = __toESM(require("crypto"));
5297
6532
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5298
6533
  // seconds
@@ -5310,7 +6545,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5310
6545
  event
5311
6546
  }) {
5312
6547
  const logLevel = process.env.LOG_LEVEL || "info";
5313
- const logger = import_aio_sdk8.Core.Logger("infiniteLoopBreaker", { level: logLevel });
6548
+ const logger = import_aio_sdk6.Core.Logger("infiniteLoopBreaker", { level: logLevel });
5314
6549
  logger.debug(`Checking for potential infinite loop for event: ${event}`);
5315
6550
  if (!eventTypes.includes(event)) {
5316
6551
  logger.debug(`Event type ${event} is not in the infinite loop event types list`);
@@ -5318,7 +6553,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5318
6553
  }
5319
6554
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
5320
6555
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
5321
- const state = await import_aio_sdk8.State.init();
6556
+ const state = await import_aio_sdk6.State.init();
5322
6557
  const persistedFingerPrint = await state.get(key);
5323
6558
  if (!persistedFingerPrint) {
5324
6559
  logger.debug(`No persisted fingerprint found for key ${key}`);
@@ -5339,7 +6574,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
5339
6574
  static async storeFingerPrint(keyFn, fingerprintFn, ttl) {
5340
6575
  const key = typeof keyFn === "function" ? keyFn() : keyFn;
5341
6576
  const data = typeof fingerprintFn === "function" ? fingerprintFn() : fingerprintFn;
5342
- const state = await import_aio_sdk8.State.init();
6577
+ const state = await import_aio_sdk6.State.init();
5343
6578
  await state.put(key, _InfiniteLoopBreaker.fingerPrint(data), {
5344
6579
  ttl: ttl !== void 0 ? ttl : _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL
5345
6580
  });
@@ -5388,7 +6623,11 @@ _InfiniteLoopBreaker.DEFAULT_INFINITE_LOOP_BREAKER_TTL = 60;
5388
6623
  var InfiniteLoopBreaker = _InfiniteLoopBreaker;
5389
6624
  var infinite_loop_breaker_default = InfiniteLoopBreaker;
5390
6625
 
6626
+ // src/integration/onboard-commerce/index.ts
6627
+ init_cjs_shims();
6628
+
5391
6629
  // src/integration/onboard-commerce/configure-provider/index.ts
6630
+ init_cjs_shims();
5392
6631
  var import_aio_services_kit = require("@adobe-commerce/aio-services-kit");
5393
6632
  var _ConfigureProvider = class _ConfigureProvider {
5394
6633
  /**
@@ -5915,7 +7154,11 @@ __name(_OnboardCommerce, "OnboardCommerce");
5915
7154
  var OnboardCommerce = _OnboardCommerce;
5916
7155
  var onboard_commerce_default = OnboardCommerce;
5917
7156
 
7157
+ // src/commerce/index.ts
7158
+ init_cjs_shims();
7159
+
5918
7160
  // src/commerce/adobe-commerce-client/index.ts
7161
+ init_cjs_shims();
5919
7162
  var import_got = __toESM(require("got"));
5920
7163
  var _AdobeCommerceClient = class _AdobeCommerceClient {
5921
7164
  /**
@@ -6054,8 +7297,12 @@ __name(_AdobeCommerceClient, "AdobeCommerceClient");
6054
7297
  var AdobeCommerceClient = _AdobeCommerceClient;
6055
7298
  var adobe_commerce_client_default = AdobeCommerceClient;
6056
7299
 
7300
+ // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
7301
+ init_cjs_shims();
7302
+
6057
7303
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
6058
- var import_aio_sdk9 = require("@adobe/aio-sdk");
7304
+ init_cjs_shims();
7305
+ var import_aio_sdk7 = require("@adobe/aio-sdk");
6059
7306
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
6060
7307
  /**
6061
7308
  * @param baseUrl
@@ -6205,7 +7452,7 @@ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
6205
7452
  async getState() {
6206
7453
  if (this.state === void 0) {
6207
7454
  try {
6208
- this.state = await import_aio_sdk9.State.init();
7455
+ this.state = await import_aio_sdk7.State.init();
6209
7456
  } catch (error) {
6210
7457
  this.logger.debug("State API initialization failed, running without caching");
6211
7458
  this.state = null;
@@ -6256,6 +7503,7 @@ var BasicAuthConnection = _BasicAuthConnection;
6256
7503
  var basic_auth_connection_default = BasicAuthConnection;
6257
7504
 
6258
7505
  // src/commerce/adobe-commerce-client/oauth1a-connection/index.ts
7506
+ init_cjs_shims();
6259
7507
  var import_oauth_1 = __toESM(require("oauth-1.0a"));
6260
7508
  var crypto3 = __toESM(require("crypto"));
6261
7509
  var _Oauth1aConnection = class _Oauth1aConnection {
@@ -6315,51 +7563,41 @@ var Oauth1aConnection = _Oauth1aConnection;
6315
7563
  var oauth1a_connection_default = Oauth1aConnection;
6316
7564
 
6317
7565
  // src/commerce/adobe-commerce-client/ims-connection/index.ts
7566
+ init_cjs_shims();
6318
7567
  var _ImsConnection = class _ImsConnection {
6319
7568
  /**
6320
- * @param clientId
6321
- * @param clientSecret
6322
- * @param technicalAccountId
6323
- * @param technicalAccountEmail
6324
- * @param imsOrgId
6325
- * @param scopes
6326
- * @param logger
7569
+ * Creates an instance of ImsConnection
7570
+ *
7571
+ * @param imsToken - Bearer token string for IMS authentication (generate using AdobeAuth)
7572
+ * @param logger - Optional logger instance for logging operations
7573
+ * @example
7574
+ * ```typescript
7575
+ * const token = await AdobeAuth.getToken(...);
7576
+ * const connection = new ImsConnection(token, logger);
7577
+ * ```
6327
7578
  */
6328
- constructor(clientId, clientSecret, technicalAccountId, technicalAccountEmail, imsOrgId, scopes, logger = null) {
6329
- this.clientId = clientId;
6330
- this.clientSecret = clientSecret;
6331
- this.technicalAccountId = technicalAccountId;
6332
- this.technicalAccountEmail = technicalAccountEmail;
6333
- this.imsOrgId = imsOrgId;
6334
- this.scopes = scopes;
7579
+ constructor(imsToken, logger = null) {
7580
+ this.imsToken = imsToken;
6335
7581
  this.customLogger = new custom_logger_default(logger);
6336
7582
  }
6337
7583
  /**
6338
- * @param commerceGot
7584
+ * Extends the Commerce Got client with IMS authentication headers
7585
+ *
7586
+ * @param commerceGot - The Got instance to extend with authentication
7587
+ * @returns Promise<any> - Extended Got instance with authentication headers
7588
+ * @throws {Error} If token is invalid or empty
6339
7589
  */
6340
7590
  async extend(commerceGot) {
6341
7591
  this.customLogger.info("Using Commerce client with IMS authentication");
6342
- const tokenGenerator = new ims_token_default(
6343
- this.clientId,
6344
- this.clientSecret,
6345
- this.technicalAccountId,
6346
- this.technicalAccountEmail,
6347
- this.imsOrgId,
6348
- this.scopes,
6349
- this.customLogger.getLogger(),
6350
- "adobe_commerce_ims_token",
6351
- // Use specific cache key for commerce client
6352
- "adobe-commerce-client"
6353
- // Use adobe-commerce-client context for backward compatibility
6354
- );
6355
- const token = await tokenGenerator.execute();
6356
- if (token === null) {
7592
+ if (!this.imsToken || this.imsToken.trim() === "") {
6357
7593
  throw new Error("Failed to generate or retrieve IMS token");
6358
7594
  }
6359
- this.customLogger.info(`IMS token being extended to header: ${token.substring(0, 10)}...`);
7595
+ this.customLogger.info(
7596
+ `IMS token being extended to header: ${this.imsToken.substring(0, 10)}...`
7597
+ );
6360
7598
  return commerceGot.extend({
6361
7599
  headers: {
6362
- Authorization: `Bearer ${token}`
7600
+ Authorization: `Bearer ${this.imsToken}`
6363
7601
  }
6364
7602
  });
6365
7603
  }
@@ -6368,7 +7606,11 @@ __name(_ImsConnection, "ImsConnection");
6368
7606
  var ImsConnection = _ImsConnection;
6369
7607
  var ims_connection_default = ImsConnection;
6370
7608
 
7609
+ // src/commerce/shipping-carrier/index.ts
7610
+ init_cjs_shims();
7611
+
6371
7612
  // src/commerce/shipping-carrier/method/index.ts
7613
+ init_cjs_shims();
6372
7614
  var _ShippingCarrierMethod = class _ShippingCarrierMethod {
6373
7615
  constructor(carrierCode, method) {
6374
7616
  this.methodData = { carrier_code: carrierCode, method, additional_data: [] };
@@ -6719,6 +7961,7 @@ var ShippingCarrier = _ShippingCarrier;
6719
7961
  var shipping_carrier_default = ShippingCarrier;
6720
7962
 
6721
7963
  // src/commerce/shipping-carrier/response/index.ts
7964
+ init_cjs_shims();
6722
7965
  var _ShippingCarrierResponse = class _ShippingCarrierResponse {
6723
7966
  constructor(carrier) {
6724
7967
  this.carrier = carrier;
@@ -6752,7 +7995,11 @@ __name(_ShippingCarrierResponse, "ShippingCarrierResponse");
6752
7995
  var ShippingCarrierResponse = _ShippingCarrierResponse;
6753
7996
  var response_default3 = ShippingCarrierResponse;
6754
7997
 
7998
+ // src/experience/index.ts
7999
+ init_cjs_shims();
8000
+
6755
8001
  // src/experience/admin-ui-sdk/index.ts
8002
+ init_cjs_shims();
6756
8003
  var _AdminUiSdk = class _AdminUiSdk {
6757
8004
  /**
6758
8005
  * Creates a new AdminUiSdk instance
@@ -6932,6 +8179,7 @@ var AdminUiSdk = _AdminUiSdk;
6932
8179
  ImsToken,
6933
8180
  InfiniteLoopBreaker,
6934
8181
  IoEventsGlobals,
8182
+ JsonMessageProcessor,
6935
8183
  Oauth1aConnection,
6936
8184
  OnboardCommerce,
6937
8185
  OnboardEvents,
@@ -6950,6 +8198,9 @@ var AdminUiSdk = _AdminUiSdk;
6950
8198
  ShippingCarrierMethod,
6951
8199
  ShippingCarrierResponse,
6952
8200
  SignatureVerification,
8201
+ SuccessChecker,
8202
+ Telemetry,
8203
+ TelemetryInputError,
6953
8204
  Validator,
6954
8205
  WebhookAction,
6955
8206
  WebhookActionOperation,