@adobe-commerce/aio-toolkit 1.0.3 → 1.0.5

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.mjs CHANGED
@@ -396,15 +396,34 @@ var _FileRepository = class _FileRepository {
396
396
  async list() {
397
397
  const filesLib = await this.getFiles();
398
398
  const results = [];
399
- const existingFiles = await filesLib.list(`${this.filepath}/`);
399
+ const existingFiles = await this.metadata();
400
400
  if (existingFiles.length) {
401
- for (const { name } of existingFiles) {
402
- const buffer = await filesLib.read(`${name}`);
403
- results.push(JSON.parse(buffer.toString()));
401
+ for (const file of existingFiles) {
402
+ const buffer = await filesLib.read(`${file.name}`);
403
+ const data = JSON.parse(buffer.toString());
404
+ results.push({
405
+ ...data,
406
+ createdAt: file.creationTime.toISOString(),
407
+ updatedAt: file.lastModified.toISOString()
408
+ });
404
409
  }
405
410
  }
406
411
  return results;
407
412
  }
413
+ /**
414
+ * Lists file metadata without reading file contents
415
+ * Provides a lightweight alternative to list() for performance-critical operations
416
+ * @param id - Optional ID of a specific file to get metadata for
417
+ * @returns Promise<FileMetadata | FileMetadata[]> Single file metadata if id provided, array of all files otherwise
418
+ */
419
+ async metadata(id) {
420
+ const filesLib = await this.getFiles();
421
+ if (id) {
422
+ const filepath = `${this.filepath}/${id}.json`;
423
+ return await filesLib.getProperties(filepath);
424
+ }
425
+ return await filesLib.list(`${this.filepath}/`);
426
+ }
408
427
  /**
409
428
  * Loads a specific file by ID
410
429
  * @param id - The ID of the file to load
@@ -416,7 +435,13 @@ var _FileRepository = class _FileRepository {
416
435
  const existingFile = await filesLib.list(filepath);
417
436
  if (existingFile.length) {
418
437
  const buffer = await filesLib.read(filepath);
419
- return JSON.parse(buffer.toString());
438
+ const data = JSON.parse(buffer.toString());
439
+ const fileProps = await filesLib.getProperties(filepath);
440
+ return {
441
+ ...data,
442
+ createdAt: fileProps.creationTime.toISOString(),
443
+ updatedAt: fileProps.lastModified.toISOString()
444
+ };
420
445
  }
421
446
  return {};
422
447
  }
@@ -424,9 +449,12 @@ var _FileRepository = class _FileRepository {
424
449
  * Saves a file record to the repository
425
450
  * @param payload - The data to save
426
451
  * @param id - Optional ID for the file (sanitized to alphanumeric + underscore, takes precedence over payload.id)
452
+ * @param overwrite - Optional flag to control file write behavior:
453
+ * - true: Replace file entirely with payload (no merge)
454
+ * - false (default): Merge payload with existing file content
427
455
  * @returns Promise<string | null> The filename on success, null on failure
428
456
  */
429
- async save(payload = {}, id) {
457
+ async save(payload = {}, id, overwrite = false) {
430
458
  try {
431
459
  const filesLib = await this.getFiles();
432
460
  let fileId;
@@ -440,23 +468,26 @@ var _FileRepository = class _FileRepository {
440
468
  const filepath = `${this.filepath}/${fileId}.json`;
441
469
  const existingFile = await filesLib.list(filepath);
442
470
  if (existingFile.length) {
443
- const buffer = await filesLib.read(filepath);
444
- const existingData = JSON.parse(buffer.toString());
445
- payload = {
446
- ...payload,
447
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
448
- };
449
- payload = { ...existingData, ...payload };
471
+ if (overwrite) {
472
+ console.log(`Overwriting existing file: ${filepath}`);
473
+ payload = {
474
+ id: fileId,
475
+ ...payload
476
+ };
477
+ } else {
478
+ const buffer = await filesLib.read(filepath);
479
+ const existingData = JSON.parse(buffer.toString());
480
+ payload = { ...existingData, ...payload };
481
+ }
450
482
  await filesLib.delete(filepath);
451
483
  } else {
452
484
  payload = {
453
- ...payload,
454
485
  id: fileId,
455
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
456
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
486
+ ...payload
457
487
  };
458
488
  }
459
- await filesLib.write(filepath, JSON.stringify(payload));
489
+ const { createdAt, updatedAt, ...payloadWithoutTimestamps } = payload;
490
+ await filesLib.write(filepath, JSON.stringify(payloadWithoutTimestamps));
460
491
  return fileId;
461
492
  } catch (error) {
462
493
  console.error("Error saving file:", error);
@@ -521,28 +552,31 @@ var _CustomLogger = class _CustomLogger {
521
552
  /**
522
553
  * Log debug message if logger is available
523
554
  * @param message - Debug message to log
555
+ * @param args - Additional arguments to pass to logger
524
556
  */
525
- debug(message) {
557
+ debug(message, ...args) {
526
558
  if (this.logger && typeof this.logger.debug === "function") {
527
- this.logger.debug(message);
559
+ this.logger.debug(message, ...args);
528
560
  }
529
561
  }
530
562
  /**
531
563
  * Log info message if logger is available
532
564
  * @param message - Info message to log
565
+ * @param args - Additional arguments to pass to logger
533
566
  */
534
- info(message) {
567
+ info(message, ...args) {
535
568
  if (this.logger && typeof this.logger.info === "function") {
536
- this.logger.info(message);
569
+ this.logger.info(message, ...args);
537
570
  }
538
571
  }
539
572
  /**
540
573
  * Log error message if logger is available
541
574
  * @param message - Error message to log
575
+ * @param args - Additional arguments to pass to logger
542
576
  */
543
- error(message) {
577
+ error(message, ...args) {
544
578
  if (this.logger && typeof this.logger.error === "function") {
545
- this.logger.error(message);
579
+ this.logger.error(message, ...args);
546
580
  }
547
581
  }
548
582
  /**
@@ -642,6 +676,281 @@ __name(_PublishEvent, "PublishEvent");
642
676
  var PublishEvent = _PublishEvent;
643
677
  var publish_event_default = PublishEvent;
644
678
 
679
+ // src/framework/webhook-action/response/types.ts
680
+ var WebhookActionOperation = /* @__PURE__ */ ((WebhookActionOperation2) => {
681
+ WebhookActionOperation2["SUCCESS"] = "success";
682
+ WebhookActionOperation2["EXCEPTION"] = "exception";
683
+ WebhookActionOperation2["ADD"] = "add";
684
+ WebhookActionOperation2["REPLACE"] = "replace";
685
+ WebhookActionOperation2["REMOVE"] = "remove";
686
+ return WebhookActionOperation2;
687
+ })(WebhookActionOperation || {});
688
+
689
+ // src/framework/webhook-action/response/index.ts
690
+ var _WebhookActionResponse = class _WebhookActionResponse {
691
+ /**
692
+ * Creates a success response indicating the webhook was processed successfully.
693
+ *
694
+ * Use this method when the webhook has been processed without errors and
695
+ * no modifications to the payload are needed.
696
+ *
697
+ * @returns A success response object
698
+ *
699
+ * @example
700
+ * ```typescript
701
+ * const handler = WebhookAction.execute('process-order', [], [], async (params) => {
702
+ * // Process the order...
703
+ * await processOrder(params.order);
704
+ *
705
+ * // Return success
706
+ * return {
707
+ * statusCode: 200,
708
+ * body: WebhookActionResponse.success()
709
+ * };
710
+ * });
711
+ * ```
712
+ */
713
+ static success() {
714
+ return {
715
+ op: "success" /* SUCCESS */
716
+ };
717
+ }
718
+ /**
719
+ * Creates an exception response to report an error during webhook processing.
720
+ *
721
+ * Use this method to notify Adobe Commerce that an error occurred while
722
+ * processing the webhook. This helps with debugging and error tracking.
723
+ *
724
+ * @param message - Optional error message describing what went wrong
725
+ * @param exceptionClass - Optional exception class name for categorization (e.g., 'Magento\\Framework\\Exception\\LocalizedException')
726
+ * @returns An exception response object
727
+ *
728
+ * @example
729
+ * ```typescript
730
+ * const handler = WebhookAction.execute('validate-product', [], [], async (params) => {
731
+ * const product = await findProduct(params.sku);
732
+ *
733
+ * if (!product) {
734
+ * return {
735
+ * statusCode: 404,
736
+ * body: WebhookActionResponse.exception(
737
+ * `Product with SKU ${params.sku} not found`,
738
+ * 'Magento\\Framework\\Exception\\NoSuchEntityException'
739
+ * )
740
+ * };
741
+ * }
742
+ *
743
+ * return { statusCode: 200, body: WebhookActionResponse.success() };
744
+ * });
745
+ * ```
746
+ */
747
+ static exception(message, exceptionClass) {
748
+ const response = {
749
+ op: "exception" /* EXCEPTION */
750
+ };
751
+ if (message !== void 0) {
752
+ response.message = message;
753
+ }
754
+ if (exceptionClass !== void 0) {
755
+ response.class = exceptionClass;
756
+ }
757
+ return response;
758
+ }
759
+ /**
760
+ * Creates a response to add new data to the webhook payload.
761
+ *
762
+ * Use this method to inject additional data into the webhook payload that
763
+ * will be processed by Adobe Commerce. The data is added at the specified
764
+ * path using dot notation.
765
+ *
766
+ * @param path - Dot-notation path where the value should be added (e.g., 'order.items', 'customer.addresses')
767
+ * @param value - The value to add at the specified path
768
+ * @param instance - Optional instance identifier for tracking or reference purposes
769
+ * @returns An add response object
770
+ *
771
+ * @example
772
+ * ```typescript
773
+ * const handler = WebhookAction.execute('enrich-order', [], [], async (params) => {
774
+ * // Add loyalty points to the order
775
+ * return {
776
+ * statusCode: 200,
777
+ * body: WebhookActionResponse.add(
778
+ * 'order.loyalty',
779
+ * { points: 150, tier: 'gold' },
780
+ * params.order.id
781
+ * )
782
+ * };
783
+ * });
784
+ * ```
785
+ */
786
+ static add(path, value, instance) {
787
+ const response = {
788
+ op: "add" /* ADD */,
789
+ path,
790
+ value
791
+ };
792
+ if (instance !== void 0) {
793
+ response.instance = instance;
794
+ }
795
+ return response;
796
+ }
797
+ /**
798
+ * Creates a response to replace existing data in the webhook payload.
799
+ *
800
+ * Use this method to modify existing fields in the webhook payload.
801
+ * The existing value at the specified path will be replaced with the new value.
802
+ *
803
+ * @param path - Dot-notation path to the field that should be replaced (e.g., 'product.price', 'order.status')
804
+ * @param value - The new value to replace the existing value
805
+ * @param instance - Optional instance identifier for tracking or reference purposes
806
+ * @returns A replace response object
807
+ *
808
+ * @example
809
+ * ```typescript
810
+ * const handler = WebhookAction.execute('adjust-price', [], [], async (params) => {
811
+ * // Apply dynamic pricing
812
+ * const newPrice = await calculateDiscountedPrice(params.product.price);
813
+ *
814
+ * return {
815
+ * statusCode: 200,
816
+ * body: WebhookActionResponse.replace(
817
+ * 'product.price',
818
+ * newPrice,
819
+ * params.product.id
820
+ * )
821
+ * };
822
+ * });
823
+ * ```
824
+ */
825
+ static replace(path, value, instance) {
826
+ const response = {
827
+ op: "replace" /* REPLACE */,
828
+ path,
829
+ value
830
+ };
831
+ if (instance !== void 0) {
832
+ response.instance = instance;
833
+ }
834
+ return response;
835
+ }
836
+ /**
837
+ * Creates a response to remove data from the webhook payload.
838
+ *
839
+ * Use this method to remove fields from the webhook payload before it's
840
+ * processed by Adobe Commerce. This is useful for filtering sensitive data
841
+ * or removing unnecessary information.
842
+ *
843
+ * @param path - Dot-notation path to the field that should be removed (e.g., 'items.0', 'customer.internal_notes')
844
+ * @returns A remove response object
845
+ *
846
+ * @example
847
+ * ```typescript
848
+ * const handler = WebhookAction.execute('sanitize-customer', [], [], async (params) => {
849
+ * // Remove internal notes before processing
850
+ * return {
851
+ * statusCode: 200,
852
+ * body: WebhookActionResponse.remove('customer.internal_notes')
853
+ * };
854
+ * });
855
+ * ```
856
+ *
857
+ * @example
858
+ * ```typescript
859
+ * // Remove an item from an array
860
+ * return {
861
+ * statusCode: 200,
862
+ * body: WebhookActionResponse.remove('order.items.2')
863
+ * };
864
+ * ```
865
+ */
866
+ static remove(path) {
867
+ return {
868
+ op: "remove" /* REMOVE */,
869
+ path
870
+ };
871
+ }
872
+ };
873
+ __name(_WebhookActionResponse, "WebhookActionResponse");
874
+ var WebhookActionResponse = _WebhookActionResponse;
875
+ var response_default2 = WebhookActionResponse;
876
+
877
+ // src/framework/webhook-action/types.ts
878
+ var SignatureVerification = /* @__PURE__ */ ((SignatureVerification2) => {
879
+ SignatureVerification2["ENABLED"] = "enabled";
880
+ SignatureVerification2["DISABLED"] = "disabled";
881
+ return SignatureVerification2;
882
+ })(SignatureVerification || {});
883
+
884
+ // src/framework/webhook-action/index.ts
885
+ import crypto from "crypto";
886
+ var _WebhookAction = class _WebhookAction {
887
+ /**
888
+ * Execute a webhook action with validation and response handling.
889
+ *
890
+ * @param name - Name of the webhook action
891
+ * @param requiredParams - Required parameters in the webhook payload
892
+ * @param requiredHeaders - Required headers (e.g., signature headers)
893
+ * @param signatureVerification - Enable/disable signature verification
894
+ * @param action - Webhook action function returning WebhookActionResponse
895
+ * @returns Function that handles the webhook HTTP request
896
+ */
897
+ static execute(name = "webhook", requiredParams = [], requiredHeaders = [], signatureVerification = "disabled" /* DISABLED */, action = async () => response_default2.success()) {
898
+ const httpMethods = ["POST" /* POST */];
899
+ const verifySignature = /* @__PURE__ */ __name(async (params) => {
900
+ const signature = params.__ow_headers["x-adobe-commerce-webhook-signature"] || "";
901
+ if (!signature) {
902
+ return "Header `x-adobe-commerce-webhook-signature` not found. Make sure Webhooks signature is enabled in the Commerce instance.";
903
+ }
904
+ const body = params.__ow_body;
905
+ if (!body) {
906
+ return "Request body not found. Make sure the action is configured with `raw-http: true`.";
907
+ }
908
+ let publicKey = params.PUBLIC_KEY;
909
+ if (!publicKey && params.PUBLIC_KEY_BASE64) {
910
+ publicKey = atob(params.PUBLIC_KEY_BASE64);
911
+ }
912
+ if (!publicKey) {
913
+ return "Public key not found. Make sure the action is configured with the input `PUBLIC_KEY` or `PUBLIC_KEY_BASE64` and it is defined in .env file.";
914
+ }
915
+ try {
916
+ const verifier = crypto.createVerify("SHA256");
917
+ verifier.update(body);
918
+ const isSignatureValid = verifier.verify(publicKey, signature, "base64");
919
+ if (!isSignatureValid) {
920
+ return "The signature is invalid.";
921
+ }
922
+ } catch (error) {
923
+ return "The signature is invalid.";
924
+ }
925
+ return null;
926
+ }, "verifySignature");
927
+ const callback = /* @__PURE__ */ __name(async (params, ctx) => {
928
+ if (signatureVerification === "enabled" /* ENABLED */) {
929
+ const verificationErrorMessage = await verifySignature(params);
930
+ if (verificationErrorMessage) {
931
+ const verificationErrorResponse = response_default2.exception(verificationErrorMessage);
932
+ return response_default.success(JSON.stringify(verificationErrorResponse));
933
+ }
934
+ params = {
935
+ ...params,
936
+ ...JSON.parse(atob(params.__ow_body))
937
+ };
938
+ }
939
+ const errorMessage = validator_default.checkMissingRequestInputs(params, requiredParams, requiredHeaders) ?? "";
940
+ if (errorMessage) {
941
+ const errorMessageResponse = response_default2.exception(errorMessage);
942
+ return response_default.success(JSON.stringify(errorMessageResponse));
943
+ }
944
+ const response = await action(params, ctx);
945
+ return response_default.success(JSON.stringify(response));
946
+ }, "callback");
947
+ return runtime_action_default.execute(name, httpMethods, [], [], callback);
948
+ }
949
+ };
950
+ __name(_WebhookAction, "WebhookAction");
951
+ var WebhookAction = _WebhookAction;
952
+ var webhook_action_default = WebhookAction;
953
+
645
954
  // src/integration/bearer-token/index.ts
646
955
  var _BearerToken = class _BearerToken {
647
956
  /**
@@ -4471,7 +4780,7 @@ var onboard_events_default = OnboardEvents;
4471
4780
 
4472
4781
  // src/integration/infinite-loop-breaker/index.ts
4473
4782
  import { Core as Core5, State } from "@adobe/aio-sdk";
4474
- import crypto from "crypto";
4783
+ import crypto2 from "crypto";
4475
4784
  var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4476
4785
  // seconds
4477
4786
  /**
@@ -4551,7 +4860,7 @@ var _InfiniteLoopBreaker = class _InfiniteLoopBreaker {
4551
4860
  * @returns The fingerprint
4552
4861
  */
4553
4862
  static fingerPrint(data) {
4554
- const hash = crypto.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
4863
+ const hash = crypto2.createHash(_InfiniteLoopBreaker.FINGERPRINT_ALGORITHM);
4555
4864
  hash.update(JSON.stringify(data));
4556
4865
  return hash.digest(_InfiniteLoopBreaker.FINGERPRINT_ENCODING);
4557
4866
  }
@@ -4610,26 +4919,22 @@ var AdobeAuth = _AdobeAuth;
4610
4919
  var adobe_auth_default = AdobeAuth;
4611
4920
 
4612
4921
  // src/commerce/adobe-commerce-client/index.ts
4613
- import { Core as Core6 } from "@adobe/aio-sdk";
4614
4922
  import got from "got";
4615
4923
  var _AdobeCommerceClient = class _AdobeCommerceClient {
4616
4924
  /**
4617
4925
  * @param baseUrl
4618
4926
  * @param connection
4619
4927
  * @param logger
4928
+ * @param httpsOptions
4620
4929
  */
4621
- constructor(baseUrl, connection, logger = null) {
4930
+ constructor(baseUrl, connection, logger = null, httpsOptions) {
4622
4931
  if (!baseUrl) {
4623
4932
  throw new Error("Commerce URL must be provided");
4624
4933
  }
4625
4934
  this.baseUrl = baseUrl;
4626
4935
  this.connection = connection;
4627
- if (logger === null) {
4628
- logger = Core6.Logger("adobe-commerce-client", {
4629
- level: "debug"
4630
- });
4631
- }
4632
- this.logger = logger;
4936
+ this.httpsOptions = httpsOptions;
4937
+ this.logger = new custom_logger_default(logger);
4633
4938
  }
4634
4939
  /**
4635
4940
  * @param endpoint
@@ -4716,6 +5021,7 @@ var _AdobeCommerceClient = class _AdobeCommerceClient {
4716
5021
  headers: {
4717
5022
  "Content-Type": "application/json"
4718
5023
  },
5024
+ ...this.httpsOptions && { https: this.httpsOptions },
4719
5025
  hooks: {
4720
5026
  beforeRequest: [
4721
5027
  (options) => this.logger.debug(`Request [${options.method}] ${options.url}`)
@@ -4751,11 +5057,8 @@ __name(_AdobeCommerceClient, "AdobeCommerceClient");
4751
5057
  var AdobeCommerceClient = _AdobeCommerceClient;
4752
5058
  var adobe_commerce_client_default = AdobeCommerceClient;
4753
5059
 
4754
- // src/commerce/adobe-commerce-client/basic-auth-connection/index.ts
4755
- import { Core as Core8 } from "@adobe/aio-sdk";
4756
-
4757
5060
  // src/commerce/adobe-commerce-client/basic-auth-connection/generate-basic-auth-token/index.ts
4758
- import { State as State2, Core as Core7 } from "@adobe/aio-sdk";
5061
+ import { State as State2 } from "@adobe/aio-sdk";
4759
5062
  var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
4760
5063
  /**
4761
5064
  * @param baseUrl
@@ -4768,12 +5071,7 @@ var _GenerateBasicAuthToken = class _GenerateBasicAuthToken {
4768
5071
  this.username = username;
4769
5072
  this.password = password;
4770
5073
  this.key = "adobe_commerce_basic_auth_token";
4771
- if (logger === null) {
4772
- logger = Core7.Logger("adobe-commerce-client", {
4773
- level: "debug"
4774
- });
4775
- }
4776
- this.logger = logger;
5074
+ this.logger = new custom_logger_default(logger);
4777
5075
  }
4778
5076
  /**
4779
5077
  * @return string | null
@@ -4935,12 +5233,7 @@ var _BasicAuthConnection = class _BasicAuthConnection {
4935
5233
  this.baseUrl = baseUrl;
4936
5234
  this.username = username;
4937
5235
  this.password = password;
4938
- if (logger === null) {
4939
- logger = Core8.Logger("adobe-commerce-client", {
4940
- level: "debug"
4941
- });
4942
- }
4943
- this.logger = logger;
5236
+ this.logger = new custom_logger_default(logger);
4944
5237
  }
4945
5238
  /**
4946
5239
  * @param commerceGot
@@ -4951,7 +5244,7 @@ var _BasicAuthConnection = class _BasicAuthConnection {
4951
5244
  this.baseUrl,
4952
5245
  this.username,
4953
5246
  this.password,
4954
- this.logger
5247
+ this.logger.getLogger()
4955
5248
  );
4956
5249
  const token = await generateToken.execute();
4957
5250
  return commerceGot.extend({
@@ -4966,9 +5259,8 @@ var BasicAuthConnection = _BasicAuthConnection;
4966
5259
  var basic_auth_connection_default = BasicAuthConnection;
4967
5260
 
4968
5261
  // src/commerce/adobe-commerce-client/oauth1a-connection/index.ts
4969
- import { Core as Core9 } from "@adobe/aio-sdk";
4970
5262
  import Oauth1a from "oauth-1.0a";
4971
- import * as crypto2 from "crypto";
5263
+ import * as crypto3 from "crypto";
4972
5264
  var _Oauth1aConnection = class _Oauth1aConnection {
4973
5265
  /**
4974
5266
  * @param consumerKey
@@ -4982,12 +5274,7 @@ var _Oauth1aConnection = class _Oauth1aConnection {
4982
5274
  this.consumerSecret = consumerSecret;
4983
5275
  this.accessToken = accessToken;
4984
5276
  this.accessTokenSecret = accessTokenSecret;
4985
- if (logger === null) {
4986
- logger = Core9.Logger("adobe-commerce-client", {
4987
- level: "debug"
4988
- });
4989
- }
4990
- this.logger = logger;
5277
+ this.logger = new custom_logger_default(logger);
4991
5278
  }
4992
5279
  /**
4993
5280
  * @param commerceGot
@@ -5017,7 +5304,7 @@ var _Oauth1aConnection = class _Oauth1aConnection {
5017
5304
  secret: this.consumerSecret
5018
5305
  },
5019
5306
  signature_method: "HMAC-SHA256",
5020
- hash_function: /* @__PURE__ */ __name((baseString, key) => crypto2.createHmac("sha256", key).update(baseString).digest("base64"), "hash_function")
5307
+ hash_function: /* @__PURE__ */ __name((baseString, key) => crypto3.createHmac("sha256", key).update(baseString).digest("base64"), "hash_function")
5021
5308
  });
5022
5309
  const oauthToken = {
5023
5310
  key: this.accessToken,
@@ -5234,6 +5521,390 @@ __name(_ImsConnection, "ImsConnection");
5234
5521
  var ImsConnection = _ImsConnection;
5235
5522
  var ims_connection_default = ImsConnection;
5236
5523
 
5524
+ // src/commerce/shipping-carrier/method/index.ts
5525
+ var _ShippingCarrierMethod = class _ShippingCarrierMethod {
5526
+ constructor(carrierCode, method) {
5527
+ this.methodData = { carrier_code: carrierCode, method, additional_data: [] };
5528
+ }
5529
+ /**
5530
+ * Sets the display name for the shipping method
5531
+ *
5532
+ * @param methodTitle - Display name for the shipping method
5533
+ * @returns The rate builder instance for method chaining
5534
+ */
5535
+ setMethodTitle(methodTitle) {
5536
+ this.methodData.method_title = methodTitle;
5537
+ return this;
5538
+ }
5539
+ /**
5540
+ * Sets the price charged to the customer
5541
+ *
5542
+ * @param price - Price charged to the customer
5543
+ * @returns The rate builder instance for method chaining
5544
+ */
5545
+ setPrice(price) {
5546
+ this.methodData.price = price;
5547
+ return this;
5548
+ }
5549
+ /**
5550
+ * Sets the cost to the merchant
5551
+ *
5552
+ * @param cost - Cost to the merchant
5553
+ * @returns The rate builder instance for method chaining
5554
+ */
5555
+ setCost(cost) {
5556
+ this.methodData.cost = cost;
5557
+ return this;
5558
+ }
5559
+ /**
5560
+ * Adds additional data to the shipping method
5561
+ *
5562
+ * @param key - Key for the additional data
5563
+ * @param value - Value for the additional data
5564
+ * @returns The rate builder instance for method chaining
5565
+ *
5566
+ * @example
5567
+ * ```typescript
5568
+ * rate.addAdditionalData('delivery_time', '3-5 business days')
5569
+ * .addAdditionalData('tracking_available', true);
5570
+ * ```
5571
+ */
5572
+ addAdditionalData(key, value) {
5573
+ const additionalDataItem = { key, value };
5574
+ this.methodData.additional_data?.push(additionalDataItem);
5575
+ return this;
5576
+ }
5577
+ /**
5578
+ * Gets and returns the shipping carrier method data
5579
+ *
5580
+ * @returns The shipping carrier method data
5581
+ */
5582
+ getData() {
5583
+ return this.methodData;
5584
+ }
5585
+ };
5586
+ __name(_ShippingCarrierMethod, "ShippingCarrierMethod");
5587
+ var ShippingCarrierMethod = _ShippingCarrierMethod;
5588
+ var method_default = ShippingCarrierMethod;
5589
+
5590
+ // src/commerce/shipping-carrier/index.ts
5591
+ var _ShippingCarrier = class _ShippingCarrier {
5592
+ constructor(code, callback) {
5593
+ this.addedMethods = [];
5594
+ this.removedMethods = [];
5595
+ this.validateCarrierCode(code);
5596
+ this.carrierData = {
5597
+ code,
5598
+ active: true,
5599
+ tracking_available: true,
5600
+ shipping_labels_available: true
5601
+ };
5602
+ this.addedMethods = [];
5603
+ this.removedMethods = [];
5604
+ if (callback) {
5605
+ callback(this);
5606
+ }
5607
+ }
5608
+ /**
5609
+ * Validates that the carrier code contains only alphanumeric characters and underscores
5610
+ *
5611
+ * @param code - Carrier code to validate
5612
+ * @throws Error if code is invalid
5613
+ */
5614
+ validateCarrierCode(code) {
5615
+ if (!code || code.trim() === "") {
5616
+ throw new Error("Carrier code cannot be empty");
5617
+ }
5618
+ const validPattern = /^[a-zA-Z0-9_]+$/;
5619
+ if (!validPattern.test(code)) {
5620
+ throw new Error("Carrier code must contain only alphanumeric characters and underscores");
5621
+ }
5622
+ }
5623
+ /**
5624
+ * Validates that the method code contains only alphanumeric characters and underscores
5625
+ *
5626
+ * @param method - Method code to validate
5627
+ * @throws Error if method code is invalid
5628
+ */
5629
+ validateMethodCode(method) {
5630
+ if (!method || method.trim() === "") {
5631
+ throw new Error("Method code cannot be empty");
5632
+ }
5633
+ const validPattern = /^[a-zA-Z0-9_]+$/;
5634
+ if (!validPattern.test(method)) {
5635
+ throw new Error("Method code must contain only alphanumeric characters and underscores");
5636
+ }
5637
+ }
5638
+ /**
5639
+ * Sets the title for the shipping carrier
5640
+ *
5641
+ * @param title - Display title for the carrier
5642
+ * @returns The builder instance for method chaining
5643
+ *
5644
+ * @example
5645
+ * ```typescript
5646
+ * carrier.setTitle('FedEx Express');
5647
+ * ```
5648
+ */
5649
+ setTitle(title) {
5650
+ this.carrierData.title = title;
5651
+ return this;
5652
+ }
5653
+ /**
5654
+ * Sets the stores for the shipping carrier
5655
+ *
5656
+ * @param stores - Array of store codes
5657
+ * @returns The builder instance for method chaining
5658
+ *
5659
+ * @example
5660
+ * ```typescript
5661
+ * carrier.setStores(['default', 'store1', 'store2']);
5662
+ * ```
5663
+ */
5664
+ setStores(stores) {
5665
+ this.carrierData.stores = stores;
5666
+ return this;
5667
+ }
5668
+ /**
5669
+ * Sets the countries for the shipping carrier
5670
+ *
5671
+ * @param countries - Array of country codes
5672
+ * @returns The builder instance for method chaining
5673
+ *
5674
+ * @example
5675
+ * ```typescript
5676
+ * carrier.setCountries(['US', 'CA', 'MX']);
5677
+ * ```
5678
+ */
5679
+ setCountries(countries) {
5680
+ this.carrierData.countries = countries;
5681
+ return this;
5682
+ }
5683
+ /**
5684
+ * Sets the sort order for the shipping carrier
5685
+ *
5686
+ * @param sortOrder - Sort order number
5687
+ * @returns The builder instance for method chaining
5688
+ *
5689
+ * @example
5690
+ * ```typescript
5691
+ * carrier.setSortOrder(10);
5692
+ * ```
5693
+ */
5694
+ setSortOrder(sortOrder) {
5695
+ this.carrierData.sort_order = sortOrder;
5696
+ return this;
5697
+ }
5698
+ /**
5699
+ * Sets the active status for the shipping carrier
5700
+ *
5701
+ * @param active - Active status
5702
+ * @returns The builder instance for method chaining
5703
+ *
5704
+ * @example
5705
+ * ```typescript
5706
+ * carrier.setActive(true);
5707
+ * carrier.setActive(false);
5708
+ * ```
5709
+ */
5710
+ setActive(active) {
5711
+ this.carrierData.active = active;
5712
+ return this;
5713
+ }
5714
+ /**
5715
+ * Sets the tracking availability for the shipping carrier
5716
+ *
5717
+ * @param trackingAvailable - Tracking availability status
5718
+ * @returns The builder instance for method chaining
5719
+ *
5720
+ * @example
5721
+ * ```typescript
5722
+ * carrier.setTrackingAvailable(true);
5723
+ * carrier.setTrackingAvailable(false);
5724
+ * ```
5725
+ */
5726
+ setTrackingAvailable(trackingAvailable) {
5727
+ this.carrierData.tracking_available = trackingAvailable;
5728
+ return this;
5729
+ }
5730
+ /**
5731
+ * Sets the shipping labels availability for the shipping carrier
5732
+ *
5733
+ * @param shippingLabelsAvailable - Shipping labels availability status
5734
+ * @returns The builder instance for method chaining
5735
+ *
5736
+ * @example
5737
+ * ```typescript
5738
+ * carrier.setShippingLabelsAvailable(true);
5739
+ * carrier.setShippingLabelsAvailable(false);
5740
+ * ```
5741
+ */
5742
+ setShippingLabelsAvailable(shippingLabelsAvailable) {
5743
+ this.carrierData.shipping_labels_available = shippingLabelsAvailable;
5744
+ return this;
5745
+ }
5746
+ /**
5747
+ * Sets the carrier data from a ShippingCarrierData object
5748
+ * Note: The code property cannot be changed once set in the constructor
5749
+ *
5750
+ * @param carrierData - Carrier data object
5751
+ * @returns The builder instance for method chaining
5752
+ *
5753
+ * @example
5754
+ * ```typescript
5755
+ * carrier.setData({
5756
+ * code: 'fedex',
5757
+ * title: 'FedEx Express',
5758
+ * stores: ['default'],
5759
+ * countries: ['US', 'CA'],
5760
+ * sort_order: 10,
5761
+ * active: true,
5762
+ * tracking_available: true,
5763
+ * shipping_labels_available: true
5764
+ * });
5765
+ * ```
5766
+ */
5767
+ setData(carrierData) {
5768
+ const originalCode = this.carrierData.code;
5769
+ if (carrierData.code !== void 0) {
5770
+ this.validateCarrierCode(carrierData.code);
5771
+ }
5772
+ this.carrierData = { ...carrierData, code: originalCode };
5773
+ return this;
5774
+ }
5775
+ /**
5776
+ * Adds a shipping method to the carrier using a callback pattern
5777
+ *
5778
+ * @param method - Unique method for the shipping rate
5779
+ * @param callback - Optional callback function to configure the method
5780
+ * @returns The builder instance for method chaining
5781
+ *
5782
+ * @example
5783
+ * ```typescript
5784
+ * builder.addMethod('standard', (method) => {
5785
+ * method.setMethodTitle('Standard Shipping')
5786
+ * .setPrice(9.99)
5787
+ * .setCost(5.00)
5788
+ * .addAdditionalData('delivery_time', '3-5 business days');
5789
+ * });
5790
+ * ```
5791
+ */
5792
+ addMethod(method, callback) {
5793
+ this.validateMethodCode(method);
5794
+ const methodBuilder = new method_default(this.carrierData.code, method);
5795
+ if (callback) {
5796
+ callback(methodBuilder);
5797
+ }
5798
+ this.addedMethods.push(methodBuilder.getData());
5799
+ return this;
5800
+ }
5801
+ /**
5802
+ * Removes a shipping method from the carrier
5803
+ *
5804
+ * @param method - Method code to remove
5805
+ * @returns The builder instance for method chaining
5806
+ *
5807
+ * @example
5808
+ * ```typescript
5809
+ * builder.removeMethod('express');
5810
+ * ```
5811
+ */
5812
+ removeMethod(method) {
5813
+ this.validateMethodCode(method);
5814
+ this.removedMethods.push(method);
5815
+ return this;
5816
+ }
5817
+ /**
5818
+ * Gets and returns the shipping carrier data as a JSON object
5819
+ *
5820
+ * @returns The shipping carrier data
5821
+ *
5822
+ * @example
5823
+ * ```typescript
5824
+ * const carrierData = carrier.getData();
5825
+ * // Returns:
5826
+ * // {
5827
+ * // code: 'DPS',
5828
+ * // title: 'Demo Postal Service',
5829
+ * // stores: ['default'],
5830
+ * // countries: ['US', 'CA'],
5831
+ * // sort_order: 10,
5832
+ * // active: true,
5833
+ * // tracking_available: true,
5834
+ * // shipping_labels_available: true
5835
+ * // }
5836
+ * ```
5837
+ */
5838
+ getData() {
5839
+ return this.carrierData;
5840
+ }
5841
+ /**
5842
+ * Gets the list of methods that have been added to the carrier
5843
+ *
5844
+ * @returns Array of added shipping carrier methods
5845
+ *
5846
+ * @example
5847
+ * ```typescript
5848
+ * const addedMethods = carrier.getAddedMethods();
5849
+ * // Returns: [{ carrier_code: 'fedex', method: 'standard', ... }, ...]
5850
+ * ```
5851
+ */
5852
+ getAddedMethods() {
5853
+ return this.addedMethods;
5854
+ }
5855
+ /**
5856
+ * Gets the list of method codes that have been marked for removal
5857
+ *
5858
+ * @returns Array of method codes to be removed
5859
+ *
5860
+ * @example
5861
+ * ```typescript
5862
+ * const removedMethods = carrier.getRemovedMethods();
5863
+ * // Returns: ['overnight', 'express']
5864
+ * ```
5865
+ */
5866
+ getRemovedMethods() {
5867
+ return this.removedMethods;
5868
+ }
5869
+ };
5870
+ __name(_ShippingCarrier, "ShippingCarrier");
5871
+ var ShippingCarrier = _ShippingCarrier;
5872
+ var shipping_carrier_default = ShippingCarrier;
5873
+
5874
+ // src/commerce/shipping-carrier/response/index.ts
5875
+ var _ShippingCarrierResponse = class _ShippingCarrierResponse {
5876
+ constructor(carrier) {
5877
+ this.carrier = carrier;
5878
+ }
5879
+ /**
5880
+ * Generates and returns an array of WebhookActionResponse operations
5881
+ *
5882
+ * @returns Array of WebhookActionResponse operations
5883
+ *
5884
+ * @example
5885
+ * ```typescript
5886
+ * const carrier = new ShippingCarrier('fedex');
5887
+ * const response = new ShippingCarrierResponse(carrier);
5888
+ * const operations = response.generate();
5889
+ * ```
5890
+ */
5891
+ generate() {
5892
+ const operations = [];
5893
+ const addedMethods = this.carrier["addedMethods"];
5894
+ for (const method of addedMethods) {
5895
+ operations.push(response_default2.add("result", method));
5896
+ }
5897
+ const removedMethods = this.carrier["removedMethods"];
5898
+ for (const method of removedMethods) {
5899
+ operations.push(response_default2.add("result", { method, remove: true }));
5900
+ }
5901
+ return operations;
5902
+ }
5903
+ };
5904
+ __name(_ShippingCarrierResponse, "ShippingCarrierResponse");
5905
+ var ShippingCarrierResponse = _ShippingCarrierResponse;
5906
+ var response_default3 = ShippingCarrierResponse;
5907
+
5237
5908
  // src/experience/admin-ui-sdk/index.ts
5238
5909
  var _AdminUiSdk = class _AdminUiSdk {
5239
5910
  /**
@@ -5423,6 +6094,13 @@ export {
5423
6094
  rest_client_default as RestClient,
5424
6095
  runtime_action_default as RuntimeAction,
5425
6096
  response_default as RuntimeActionResponse,
5426
- validator_default as Validator
6097
+ shipping_carrier_default as ShippingCarrier,
6098
+ method_default as ShippingCarrierMethod,
6099
+ response_default3 as ShippingCarrierResponse,
6100
+ SignatureVerification,
6101
+ validator_default as Validator,
6102
+ webhook_action_default as WebhookAction,
6103
+ WebhookActionOperation,
6104
+ response_default2 as WebhookActionResponse
5427
6105
  };
5428
6106
  //# sourceMappingURL=index.mjs.map