@the-any-thing/mollie-api-client-inline-pem
Version:
Official Mollie API client for Node - inline pem file fork
1,661 lines (1,350 loc) • 84.1 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var axios = _interopDefault(require('axios'));
var fs = _interopDefault(require('fs'));
var https = _interopDefault(require('https'));
var path = _interopDefault(require('path'));
var lodash = require('lodash');
var url = require('url');
var querystring = _interopDefault(require('qs'));
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
var version = "3.2.0-2";
var commonHelpers = {
/**
* Converts this object to a plain one.
*/
toPlainObject: function toPlainObject() {
// Previously, we used Lodash' toPlainObject here. However, back then we used classes for our models instead of
// interfaces. This should have the same effect on the new object as _.toPlainObject had on the old ones: returning
// a plain object with no prototype.
return Object.assign({}, this);
}
};
/* eslint-enable @typescript-eslint/camelcase */
(function (OrderLineType) {
OrderLineType["physical"] = "physical";
OrderLineType["discount"] = "discount";
OrderLineType["digital"] = "digital";
OrderLineType["shipping_fee"] = "shipping_fee";
OrderLineType["store_credit"] = "store_credit";
OrderLineType["gift_card"] = "gift_card";
OrderLineType["surcharge"] = "surcharge";
})(exports.OrderLineType || (exports.OrderLineType = {}));
function injectPrototypes(input) {
return Object.assign(Object.create(commonHelpers), input);
}
/**
* The `Refund` model
*
* {@link IRefund}
*/
(function (RefundStatus) {
RefundStatus["queued"] = "queued";
RefundStatus["pending"] = "pending";
RefundStatus["processing"] = "processing";
RefundStatus["refunded"] = "refunded";
RefundStatus["failed"] = "failed";
})(exports.RefundStatus || (exports.RefundStatus = {}));
/**
* Payment Refund _links object
*
* @param payment - The API resource URL of the payment the refund belongs to.
* @param settlement - The API resource URL of the settlement this payment has been settled with. Not present if not yet settled.
* @param order - The API resource URL of the order the refund belongs to. Not present if the refund does not belong to an order.
*/
(function (RefundEmbed) {
RefundEmbed["payment"] = "payment";
})(exports.RefundEmbed || (exports.RefundEmbed = {}));
var refundHelpers = _objectSpread2({}, commonHelpers, {
/**
* The refund is queued until there is enough balance to process te refund.
* You can still cancel the refund.
*/
isQueued: function isQueued() {
return this.status === exports.RefundStatus.queued;
},
/**
* The refund will be sent to the bank on the next business day. You can still cancel the refund.
*/
isPending: function isPending() {
return this.status === exports.RefundStatus.pending;
},
/**
* The refund has been sent to the bank. The refund amount will be transferred to the consumer
* account as soon as possible.
*/
isProcessing: function isProcessing() {
return this.status === exports.RefundStatus.processing;
},
/**
* The refund amount has been transferred to the consumer.
*/
isRefunded: function isRefunded() {
return this.status === exports.RefundStatus.refunded;
},
/**
* The refund has failed during processing.
*/
isFailed: function isFailed() {
return this.status === exports.RefundStatus.failed;
}
});
function injectPrototypes$1(input) {
let lines;
if (input.lines != undefined) {
lines = input.lines.map(injectPrototypes);
}
return Object.assign(Object.create(refundHelpers), input, {
lines
});
}
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-enable @typescript-eslint/camelcase */
(function (Locale) {
Locale["en_US"] = "en_US";
Locale["nl_NL"] = "nl_NL";
Locale["nl_BE"] = "nl_BE";
Locale["fr_FR"] = "fr_FR";
Locale["fr_BE"] = "fr_BE";
Locale["de_DE"] = "de_DE";
Locale["de_AT"] = "de_AT";
Locale["de_CH"] = "de_CH";
Locale["es_ES"] = "es_ES";
Locale["ca_ES"] = "ca_ES";
Locale["pt_PT"] = "pt_PT";
Locale["it_IT"] = "it_IT";
Locale["nb_NO"] = "nb_NO";
Locale["sv_SE"] = "sv_SE";
Locale["fi_FI"] = "fi_FI";
Locale["da_DK"] = "da_DK";
Locale["is_IS"] = "is_IS";
Locale["hu_HU"] = "hu_HU";
Locale["pl_PL"] = "pl_PL";
Locale["lv_LV"] = "lv_LV";
Locale["lt_LT"] = "lt_LT";
})(exports.Locale || (exports.Locale = {}));
(function (PaymentMethod) {
PaymentMethod["applepay"] = "applepay";
PaymentMethod["bancontact"] = "bancontact";
PaymentMethod["banktransfer"] = "banktransfer";
PaymentMethod["belfius"] = "belfius";
PaymentMethod["creditcard"] = "creditcard";
PaymentMethod["directdebit"] = "directdebit";
PaymentMethod["eps"] = "eps";
PaymentMethod["giftcard"] = "giftcard";
PaymentMethod["giropay"] = "giropay";
PaymentMethod["ideal"] = "ideal";
PaymentMethod["inghomepay"] = "inghomepay";
PaymentMethod["kbc"] = "kbc";
PaymentMethod["klarnapaylater"] = "klarnapaylater";
PaymentMethod["klarnasliceit"] = "klarnasliceit";
PaymentMethod["paypal"] = "paypal";
PaymentMethod["paysafecard"] = "paysafecard";
PaymentMethod["przelewy24"] = "przelewy24";
PaymentMethod["sofort"] = "sofort";
})(exports.PaymentMethod || (exports.PaymentMethod = {}));
(function (HistoricPaymentMethod) {
HistoricPaymentMethod["bitcoin"] = "bitcoin";
})(exports.HistoricPaymentMethod || (exports.HistoricPaymentMethod = {}));
(function (ApiMode) {
ApiMode["test"] = "test";
ApiMode["live"] = "live";
})(exports.ApiMode || (exports.ApiMode = {}));
(function (SequenceType) {
SequenceType["oneoff"] = "oneoff";
SequenceType["first"] = "first";
SequenceType["recurring"] = "recurring";
})(exports.SequenceType || (exports.SequenceType = {}));
/**
* Payment Response Object.
*
* @param resource - Indicates the response contains a payment object.
* Will always contain `payment` for this endpoint.
* @param id - The identifier uniquely referring to this payment.
* Mollie assigns this identifier at payment creation time.
* For example `tr_7UhSN1zuXS`. Its ID will always be used
* by Mollie to refer to a certain payment.
* @param mode - The mode used to create this payment. Mode determines
* whether a payment is real (live mode) or a test payment.
* @param createdAt - The payment’s date and time of creation, in ISO
* 8601 format.
* @param status - The payment’s status. Please refer to the documentation
* regarding statuses for more info about which statuses
* occur at what point.
* @param isCancelable - Whether or not the payment can be canceled.
* @param authorizedAt - The date and time the payment became authorized,
* in ISO 8601 format. This parameter is omitted if
* the payment is not authorized (yet).
* @param paidAt - The date and time the payment became paid, in ISO 8601
* format. This parameter is omitted if the payment is not
* completed (yet).
* @param canceledAt - The date and time the payment was canceled, in
* ISO 8601 format. This parameter is omitted if the
* payment is not canceled (yet).
* @param expiresAt - The date and time the payment will expire, in
* ISO 8601 format.
* @param expiredAt - The date and time the payment was expired, in
* ISO 8601 format. This parameter is omitted if the
* payment did not expire (yet).
* @param failedAt - The date and time the payment failed, in ISO 8601 format.
* This parameter is omitted if the payment did not fail (yet).
* @param amount - The amount of the payment, e.g. `{"currency":"EUR", "value":"100.00"}`
* for a €100.00 payment.
* @param amountRefunded - The total amount that is already refunded. Only
* available when refunds are available for this payment.
* For some payment methods, this amount may be higher than
* the payment amount, for example to allow reimbursement of
* the costs for a return shipment to the customer.
* @param amountRemaining - The remaining amount that can be refunded. Only available
* when refunds are available for this payment.
* @param amountCaptured - The total amount that is already captured for this payment.
* Only available when this payment supports captures.
* @param description - A short description of the payment. The description is visible
* in the Dashboard and will be shown on the customer’s bank or card
* statement when possible.
* @param redirectUrl - The URL your customer will be redirected to after completing or
* canceling the payment process. (The URL will be `null` for
* recurring payments.)`
* @param webhookUrl - The URL Mollie will call as soon an important status change
* takes place.
* @param method - The payment method used for this payment, either forced on creation
* by specifying the method parameter, or chosen by the customer on our
* payment method selection screen. If the payment is only partially paid
* with a gift card, the method remains `giftcard`.
* @param metadata - The optional metadata you provided upon payment creation. Metadata
* can for example be used to link an order to a payment.
* @param locale - The customer’s locale, either forced on creation by specifying the locale
* parameter, or detected by us during checkout. Will be a full locale, for
* example `nl_NL`.
* @param countryCode - This optional field contains your customer’s ISO 3166-1 alpha-2
* country code, detected by us during checkout. For example: `BE`.
* This field is omitted if the country code was not detected.
* @param profileId - The identifier referring to the profile this payment was created on.
* For example, `pfl_QkEhN94Ba`.
* @param settlementAmount - This optional field will contain the amount that will be settled
* to your account, converted to the currency your account is settled
* in. It follows the same syntax as the amount property. Any amounts
* not settled by Mollie will not be reflected in this amount,
* e.g. PayPal or gift cards.
* @param settlementId - The identifier referring to the settlement this payment was settled with.
* For example, `stl_BkEjN2eBb`.
* @param customerId - If a customer was specified upon payment creation, the customer’s token
* will be available here as well. For example, `cst_XPn78q9CfT`.
* @param sequenceType - Indicates which type of payment this is in a recurring sequence. Set to
* first for first payments that allow the customer to agree to automatic
* recurring charges taking place on their account in the future.
* Set to recurring for payments where the customer’s card is charged
* automatically. Set to `oneoff` by default, which indicates the payment
* is a regular non-recurring payment.
* @param mandateId - If the payment is a first or recurring payment, this field will hold the
* ID of the mandate.
* @param subscriptionId - When implementing the Subscriptions API, any recurring charges
* resulting from the subscription will hold the ID of the subscription
* that triggered the payment.
* @param orderId - If the payment was created for an order, the ID of that order will
* be part of the response.
* @param applicationFee - The application fee, if the payment was created with one.
* @param _links - An object with several URL objects relevant to the payment. Every URL
* object will contain an `href` and a `type` field.
*
*/
(function (PaymentStatus) {
PaymentStatus["open"] = "open";
PaymentStatus["canceled"] = "canceled";
PaymentStatus["pending"] = "pending";
PaymentStatus["authorized"] = "authorized";
PaymentStatus["expired"] = "expired";
PaymentStatus["failed"] = "failed";
PaymentStatus["paid"] = "paid";
})(exports.PaymentStatus || (exports.PaymentStatus = {}));
/**
* Gift Card
*
* @param issuer - The ID of the gift card brand that was used during the payment.
* @param amount - The amount in EUR that was paid with this gift card.
* @param voucherNumber - The voucher number, with the last four digits masked. Example: `606436353088147****`
*/
(function (PaymentEmbed) {
PaymentEmbed["refunds"] = "refunds";
PaymentEmbed["chargebacks"] = "chargebacks";
})(exports.PaymentEmbed || (exports.PaymentEmbed = {}));
var paymentHelpers = _objectSpread2({}, commonHelpers, {
/**
* If the payment is open
*/
isOpen: function isOpen() {
return this.status === exports.PaymentStatus.open;
},
/**
* If the payment is authorized
*/
isAuthorized: function isAuthorized() {
return this.status === exports.PaymentStatus.authorized;
},
/**
* If the payment is paid
*/
isPaid: function isPaid() {
return this.paidAt != undefined;
},
/**
* If the payment is canceled
*/
isCanceled: function isCanceled() {
return this.status == exports.PaymentStatus.canceled;
},
/**
* If the payment is expired
*/
isExpired: function isExpired() {
return this.status == exports.PaymentStatus.expired;
},
/**
* If the payment is refundable
*
* @since 2.0.0-rc.2
*/
isRefundable: function isRefundable() {
return this.amountRemaining !== null;
},
/**
* Get the payment URL
*/
getPaymentUrl: function getPaymentUrl() {
return lodash.get(this._links, 'checkout.href', null);
},
/**
* Returns whether the payment has failed and cannot be completed with a different payment method.
*/
isFailed: function isFailed() {
return this.status == exports.PaymentStatus.failed;
},
/**
* Returns whether the payment is in this temporary status that can occur when the actual payment process has been
* started, but has not completed yet.
*/
isPending: function isPending() {
return this.status == exports.PaymentStatus.pending;
},
/**
* Returns whether there are refunds which belong to the payment.
*/
hasRefunds: function hasRefunds() {
return this._links.refunds != undefined;
},
/**
* Returns whether there are chargebacks which belong to the payment.
*/
hasChargebacks: function hasChargebacks() {
return this._links.chargebacks != undefined;
},
/**
* Returns whether `sequenceType` is set to `'first'`. If a `'first'` payment has been completed successfully, the
* consumer's account may be charged automatically using recurring payments.
*/
hasSequenceTypeFirst: function hasSequenceTypeFirst() {
return this.sequenceType == exports.SequenceType.first;
},
/**
* Returns whether `sequenceType` is set to `'recurring'`. This type of payment is processed without involving the
* consumer.
*/
hasSequenceTypeRecurring: function hasSequenceTypeRecurring() {
return this.sequenceType == exports.SequenceType.recurring;
},
/**
* Returns the URL your customer should visit to make the payment. This is where you should redirect the consumer to.
*
* Recurring payments don’t have a checkout URL.
*/
getCheckoutUrl: function getCheckoutUrl() {
if (this._links.checkout == undefined) {
return null;
}
return this._links.checkout.href;
},
canBeRefunded: function canBeRefunded() {
return this.amountRemaining != undefined;
},
canBePartiallyRefunded: function canBePartiallyRefunded() {
return this.amountRemaining != undefined;
},
/**
* Returns the total amount that is already refunded. For some payment methods, this amount may be higher than the
* payment amount, for example to allow reimbursement of the costs for a return shipment to the customer.
*/
getAmountRefunded: function getAmountRefunded() {
if (this.amountRefunded == undefined) {
return {
// Perhaps this zero-value should depend on the currency. If the currency is JPY (¥), for instance, the value
// should probably be "0"; not "0.00".
value: '0.00',
currency: this.amount.currency
};
}
return this.amountRefunded;
},
/**
* Returns the remaining amount that can be refunded.
*/
getAmountRemaining: function getAmountRemaining() {
if (this.amountRemaining == undefined) {
return {
// Perhaps this zero-value should depend on the currency. If the currency is JPY (¥), for instance, the value
// should probably be "0"; not "0.00".
value: '0.00',
currency: this.amount.currency
};
}
return this.amountRemaining;
}
});
function injectPrototypes$2(input) {
let _embedded;
if (input._embedded != undefined) {
_embedded = {};
if (input._embedded.chargebacks != undefined) {
_embedded.chargebacks = input._embedded.chargebacks.map(injectPrototypes$3);
}
if (input._embedded.refunds != undefined) {
_embedded.refunds = input._embedded.refunds.map(injectPrototypes$1);
}
}
return Object.assign(Object.create(paymentHelpers), input, {
_embedded
});
}
/**
* Chargeback Response object.
*
* @param resource - Indicates the response contains a Chargeback object.
* Will always contain `chargeback` for this endpoint.
* @param id - The chargeback’s unique identifier, for example `chb_n9z0tp`.
* @param amount - The amount charged back by the consumer.
* @param settlementAmount - This optional field will contain the amount that will be deducted from your account,
* converted to the currency your account is settled in. It follows the same syntax as
* the `amount` property. Note that for chargebacks, the `value` key of `settlementAmount`
* will be negative. Any amounts not settled by Mollie will not be reflected in this amount,
* e.g. PayPal chargebacks.
* @param createdAt - The date and time the chargeback was issued, in ISO 8601 format.
* @param reversedAt - The date and time the chargeback was reversed if applicable, in ISO 8601 format.
* @param paymentId - The unique identifier of the payment this chargeback was issued for. For example: `tr_7UhSN1zuXS`.
* The full payment object can be retrieved via the `payment` URL in the `_links` object.
* @param _links - An object with several URL objects relevant to the chargeback.
*
* @see https://docs.mollie.com/reference/v2/chargebacks-api/get-chargeback
*/
let ChargebackEmbed;
(function (ChargebackEmbed) {
ChargebackEmbed["payment"] = "payment";
})(ChargebackEmbed || (ChargebackEmbed = {}));
function injectPrototypes$3(input) {
let _embedded;
if (input._embedded != undefined) {
_embedded = {};
if (input._embedded.payments != undefined) {
_embedded.payments = input._embedded.payments.map(injectPrototypes$2);
}
}
return Object.assign(Object.create(commonHelpers), input);
}
class ApiError extends Error {
constructor(message, title, status, field, links) {
super(message);
this.title = title;
this.status = status;
this.field = field;
this.links = links;
this.name = 'ApiError';
}
/**
* Get the error message
*
* @since 3.0.0
*/
getMessage() {
return this.message;
}
/**
* Get the field name that contains an error
*
* @since 3.0.0
*/
getField() {
return this.field;
}
/**
* Get the API status code
*
* @since 3.0.0
*/
getStatusCode() {
return this.status;
}
/**
* Get the documentation URL
*
* @since 3.0.0
*/
getDocumentationUrl() {
return this.getUrl('documentation');
}
/**
* Get the dashboard URL
*
* @since 3.0.0
*/
getDashboardUrl() {
return this.getUrl('dashboard');
}
/**
* Check if the link exists
*
* @since 3.0.0
*/
hasLink(key) {
return lodash.has(this.links, key);
}
/***
* Retrieve a link by name
*
* @since 3.0.0
*/
getLink(key) {
return lodash.get(this.links, key);
}
/**
* @since 3.0.0
*/
getUrl(key) {
return lodash.get(this.getLink(key), 'href');
}
toString() {
return `ApiError: ${this.message}`;
}
/**
* Creates and returns an `ApiError` from the passed response.
*
* @since 3.0.0
*/
static createFromResponse(response) {
return new ApiError(lodash.get(response, 'data.detail', 'Received an error without a message'), lodash.get(response, 'data.title'), lodash.get(response, 'data.status'), lodash.get(response, 'data.field'), lodash.cloneDeep(lodash.get(response, 'data._links')));
}
}
/**
* Returns an array of the passed object's own enumerable string-keyed property `[key, value]` pairs.
*
* If support for Node.js < 7.0.0 is ever dropped, this function can be removed in favour of `Object.entries`.
*/
var getEntries = (() => {
if (Object.entries != undefined) {
return Object.entries;
}
return function getEntries(input) {
return Object.keys(input).map(key => [key, input[key]]);
};
})();
function stringifyQuery(input) {
return querystring.stringify(getEntries(input).reduce((result, [key, value]) => {
if (Array.isArray(value)) {
result[key] = value.join();
}
/* if (Array.isArray(value) == false) */
else {
result[key] = value;
}
return result;
}, {}), {
addQueryPrefix: true
});
}
class Resource {
constructor(httpClient) {
var _this = this;
this.httpClient = httpClient;
_defineProperty(this, "network", void 0);
/* eslint-disable no-var */
this.network = {
post: function () {
var _ref = _asyncToGenerator(function* (url, data) {
try {
var response = yield httpClient.post(url, data);
} catch (error) {
if (error.response != undefined) {
throw ApiError.createFromResponse(error.response);
}
throw new ApiError(error.message);
}
if (response.status == 204) {
return true;
}
return _this.injectPrototypes(response.data);
});
return function post(_x, _x2) {
return _ref.apply(this, arguments);
};
}(),
get: function () {
var _ref2 = _asyncToGenerator(function* (url, query = {}) {
try {
var response = yield httpClient.get(`${url}${stringifyQuery(query)}`);
} catch (error) {
if (error.response != undefined) {
throw ApiError.createFromResponse(error.response);
}
throw new ApiError(error.message);
}
return _this.injectPrototypes(response.data);
});
return function get(_x3) {
return _ref2.apply(this, arguments);
};
}(),
list: function () {
var _ref3 = _asyncToGenerator(function* (url, resourceName, query = {}) {
try {
var response = yield httpClient.get(`${url}${stringifyQuery(query)}`);
} catch (error) {
if (error.response != undefined) {
throw ApiError.createFromResponse(error.response);
}
throw new ApiError(error.message);
}
try {
var {
_embedded: embedded,
_links: links,
count
} = response.data;
} catch (error) {
throw new ApiError('Received unexpected response from the server');
}
return Object.assign(embedded[resourceName].map(_this.injectPrototypes), {
links,
count
});
});
return function list(_x4, _x5) {
return _ref3.apply(this, arguments);
};
}(),
patch: function () {
var _ref4 = _asyncToGenerator(function* (url, data) {
try {
var response = yield httpClient.patch(url, data);
} catch (error) {
if (error.response != undefined) {
throw ApiError.createFromResponse(error.response);
}
throw new ApiError(error.message);
}
return _this.injectPrototypes(response.data);
});
return function patch(_x6, _x7) {
return _ref4.apply(this, arguments);
};
}(),
delete: function () {
var _ref5 = _asyncToGenerator(function* (url, context) {
try {
var response = yield httpClient.delete(url, {
data: context
});
} catch (error) {
if (error.response != undefined) {
throw ApiError.createFromResponse(error.response);
}
throw new ApiError(error.message);
}
if (response.status == 204) {
return true;
}
return _this.injectPrototypes(response.data);
});
return function _delete(_x8, _x9) {
return _ref5.apply(this, arguments);
};
}()
};
/* eslint-enable no-var */
}
/**
* Injects `nextPage`, `nextPageCursor`, `previousPage`, and `previousPageCursor` into the passed list.
*/
injectPaginationHelpers(input, list, selfParameters) {
const {
links
} = input;
let nextPage;
let nextPageCursor;
if (links.next != null) {
const {
query
} = url.parse(links.next.href, true);
nextPage = list.bind(this, _objectSpread2({}, selfParameters, {}, query));
nextPageCursor = query.from;
}
let previousPage;
let previousPageCursor;
if (links.previous != null) {
const {
query
} = url.parse(links.previous.href, true);
previousPage = list.bind(this, _objectSpread2({}, selfParameters, {}, query));
previousPageCursor = query.from;
}
return Object.assign(input, {
nextPage,
nextPageCursor,
previousPage,
previousPageCursor
});
}
/**
* Injects prototypes ‒ where necessary ‒ into the response received from the Mollie server.
*/
injectPrototypes(input) {
return input;
}
}
class ParentedResource extends Resource {
constructor(...args) {
super(...args);
_defineProperty(this, "defaultParentId", void 0);
}
/**
* Returns the passed parent identifier, or `defaultParentId` as set by `withParent` if the former is `undefined`.
*/
getParentId(input) {
if (input == undefined) {
return this.defaultParentId;
}
return input;
}
/**
* Sets the default parent identifier for future calls to the methods of this resource to the identifier of the
* passed parent object. If `undefined` or `null` or an otherwise falsy value is passed, or an object with a falsy
* identifier, this method is a no-op.
*
* @since 1.1.1
*
* @deprecated 2.0.0. This method is not supported by the v2 API.
*/
withParent(parent) {
if (parent && parent.id) {
this.defaultParentId = parent.id;
}
return this;
}
}
/**
* Allows a promise-style method to be called callback-style.
*
* Behaves in one of two ways, depending on the type of the last argument:
* * If called with a function as the last argument, that argument is considered to be the callback. This function
* calls the passed method, forwarding the original arguments (save for the callback). A settlement of the promise
* returned during that call will be forwarded to the callback. This function then returns `true`.
* * If called with a last argument which is not a function, this function returns `false`.
*/
function renege(thisArgument, method, ...originalArguments) {
const candidate = originalArguments.pop();
if (typeof candidate == 'function') {
method.apply(thisArgument, originalArguments).then(result => void candidate(null, result), candidate);
return true;
}
return false;
}
class ChargebacksResource extends ParentedResource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$3);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
}
getResourceUrl() {
return 'chargebacks';
}
list(parameters = {}) {
if (renege(this, this.list, ...arguments)) return;
return this.network.list(this.getResourceUrl(), 'chargebacks', parameters).then(result => this.injectPaginationHelpers(result, this.list, parameters));
}
}
/**
* Mandate Response object
*
* @see https://docs.mollie.com/reference/v2/mandates-api/get-mandate
*/
(function (MandateMethod) {
MandateMethod["directdebit"] = "directdebit";
MandateMethod["creditcard"] = "creditcard";
MandateMethod["paypal"] = "paypal";
})(exports.MandateMethod || (exports.MandateMethod = {}));
(function (MandateStatus) {
MandateStatus["valid"] = "valid";
MandateStatus["invalid"] = "invalid";
MandateStatus["pending"] = "pending";
})(exports.MandateStatus || (exports.MandateStatus = {}));
var mandateHelpers = _objectSpread2({}, commonHelpers, {
/**
* If the mandate is valid
*/
isValid: function isValid() {
return this.status === exports.MandateStatus.valid;
}
});
function injectPrototypes$4(input) {
return Object.assign(Object.create(mandateHelpers), input);
}
const prefixes = new Map([['capture', 'cpt_'], ['chargeback', 'chb_'], ['customer', 'cst_'], ['mandate', 'mdt_'], ['order', 'ord_'], ['orderline', 'odl_'], ['organization', 'org_'], ['payment', 'tr_'], ['profile', 'pfl_'], ['refund', 're_'], ['shipment', 'shp_'], ['subscription', 'sub_']]);
/**
* Returns whether the passed identifier seems plausible (`true`); or is definitely invalid (`false`).
*/
function checkId(value, resource) {
if (typeof value != 'string') {
return false;
} // Examples of permission identifiers are 'payments.read' and 'refunds.write'. This function currently relies on the
// API to return an error if the identifier is unexpected, instead of returning a client-side check.
if (resource == 'permission') {
return true;
} // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return value.startsWith(prefixes.get(resource));
}
class CustomersMandatesResource extends ParentedResource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$4);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
_defineProperty(this, "cancel", this.revoke);
_defineProperty(this, "delete", this.revoke);
}
getResourceUrl(customerId) {
return `customers/${customerId}/mandates`;
}
create(parameters) {
if (renege(this, this.create, ...arguments)) return;
const customerId = this.getParentId(parameters.customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const data = _objectWithoutProperties(parameters, ["customerId"]);
return this.network.post(this.getResourceUrl(customerId), data);
}
/**
* Get a customer mandate by ID
*
* @since 1.2.0
*
* @see https://docs.mollie.com/reference/v2/mandates-api/get-mandate
*/
get(id, parameters) {
if (renege(this, this.get, ...arguments)) return;
if (!checkId(id, 'mandate')) {
throw new ApiError('The customers_mandate id is invalid');
} // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const _ref = parameters || {},
query = _objectWithoutProperties(_ref, ["customerId"]);
return this.network.get(`${this.getResourceUrl(customerId)}/${id}`, query);
}
/**
* Get all of a customer's mandates
*
* @since 3.0.0
*
* @see https://docs.mollie.com/reference/v2/mandates-api/list-mandates
*/
list(parameters) {
if (renege(this, this.list, ...arguments)) return; // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const _ref2 = parameters || {},
query = _objectWithoutProperties(_ref2, ["customerId"]);
return this.network.list(this.getResourceUrl(customerId), 'mandates', query).then(result => this.injectPaginationHelpers(result, this.list, parameters || {}));
}
/**
* Delete a customer subscription
*
* @since 2.0.0
*
* @see https://docs.mollie.com/reference/v2/mandates-api/revoke-mandate
*/
revoke(id, parameters) {
if (renege(this, this.revoke, ...arguments)) return;
if (!checkId(id, 'mandate')) {
throw new ApiError('The customers_mandate id is invalid');
} // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer is invalid');
}
const _ref3 = parameters || {},
context = _objectWithoutProperties(_ref3, ["customerId"]);
return this.network.delete(`${this.getResourceUrl(customerId)}/${id}`, context);
}
}
class CustomersPaymentsResource extends ParentedResource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$2);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
}
getResourceUrl(customerId) {
return `customers/${customerId}/payments`;
}
create(parameters) {
if (renege(this, this.create, ...arguments)) return;
const customerId = this.getParentId(parameters.customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const data = _objectWithoutProperties(parameters, ["customerId"]);
return this.network.post(this.getResourceUrl(customerId), data);
}
/**
* Get all of a customer's payments.
*
* @since 3.0.0
*
* @see https://docs.mollie.com/reference/v2/customers-api/list-customer-payments
*/
list(parameters) {
if (renege(this, this.list, ...arguments)) return; // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const _ref = parameters || {},
query = _objectWithoutProperties(_ref, ["customerId"]);
return this.network.list(this.getResourceUrl(customerId), 'payments', query).then(result => this.injectPaginationHelpers(result, this.list, parameters || {}));
}
}
/**
* Customer Response object.
*
* @see https://docs.mollie.com/reference/v2/customers-api/get-customer
*/
function injectPrototypes$5(input) {
return Object.assign(Object.create(commonHelpers), input);
}
class CustomersResource extends Resource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$5);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
_defineProperty(this, "cancel", this.delete);
}
getResourceUrl() {
return 'customers';
}
create(parameters) {
if (renege(this, this.create, ...arguments)) return;
return this.network.post(this.getResourceUrl(), parameters);
}
/**
* Retrieve a single customer by its ID
*
* @since 2.0.0
*
* @see https://docs.mollie.com/reference/v2/customers-api/get-customer
*/
get(id, parameters) {
if (renege(this, this.get, ...arguments)) return;
if (!checkId(id, 'customer')) {
throw new ApiError('The customer id is invalid');
}
return this.network.get(`${this.getResourceUrl()}/${id}`, parameters);
}
/**
* List customers
*
* @since 3.0.0
*
* @see https://docs.mollie.com/reference/v2/customers-api/list-customers
*/
list(parameters = {}) {
if (renege(this, this.list, ...arguments)) return;
return this.network.list(this.getResourceUrl(), 'customers', parameters).then(result => this.injectPaginationHelpers(result, this.list, parameters));
}
/**
* Update a customer
*
* @since 2.0.0
*
* @see https://docs.mollie.com/reference/v2/customers-api/update-customer
*/
update(id, parameters) {
if (renege(this, this.update, ...arguments)) return;
if (!checkId(id, 'customer')) {
throw new ApiError('The customer id is invalid');
}
return this.network.patch(`${this.getResourceUrl()}/${id}`, parameters);
}
/**
* Delete a customer
*
* @since 2.0.0
*
* @see https://docs.mollie.com/reference/v2/customers-api/delete-customer
*/
delete(id, parameters) {
if (renege(this, this.delete, ...arguments)) return;
if (!checkId(id, 'customer')) {
throw new ApiError('The customer id is invalid');
}
return this.network.delete(`${this.getResourceUrl()}/${id}`, parameters);
}
}
/**
* Subscription Response object.
*
* @see https://docs.mollie.com/reference/v2/subscriptions-api/get-subscription
*/
(function (SubscriptionStatus) {
SubscriptionStatus["pending"] = "pending";
SubscriptionStatus["active"] = "active";
SubscriptionStatus["canceled"] = "canceled";
SubscriptionStatus["suspended"] = "suspended";
SubscriptionStatus["completed"] = "completed";
})(exports.SubscriptionStatus || (exports.SubscriptionStatus = {}));
var subscriptionHelpers = _objectSpread2({}, commonHelpers, {
/**
* Get the webhook url
*/
getWebhookUrl: function getWebhookUrl() {
return this.webhookUrl;
},
/**
* If the subscription is active
*/
isActive: function isActive() {
return this.status === exports.SubscriptionStatus.active;
},
/**
* If the subscription is pending
*/
isPending: function isPending() {
return this.status === exports.SubscriptionStatus.pending;
},
/**
* If the subscription is completed
*/
isCompleted: function isCompleted() {
return this.status === exports.SubscriptionStatus.completed;
},
/**
* If the subscription is suspended
*/
isSuspended: function isSuspended() {
return this.status === exports.SubscriptionStatus.suspended;
},
/**
* If the subscription is canceled
*/
isCanceled: function isCanceled() {
return exports.SubscriptionStatus.canceled == this.status;
}
});
function injectPrototypes$6(input) {
return Object.assign(Object.create(subscriptionHelpers), input);
}
class CustomersSubscriptionsResource extends ParentedResource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$6);
_defineProperty(this, "delete", this.cancel);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
}
getResourceUrl(customerId) {
return `customers/${customerId}/subscriptions`;
}
create(parameters) {
if (renege(this, this.create, ...arguments)) return;
const customerId = this.getParentId(parameters.customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const data = _objectWithoutProperties(parameters, ["customerId"]);
return this.network.post(this.getResourceUrl(customerId), data);
}
/**
* Get a customer subscription.
*
* @since 1.3.2
*
* @see https://docs.mollie.com/reference/v2/subscriptions-api/get-subscription
*/
get(id, parameters) {
if (renege(this, this.get, ...arguments)) return;
if (!checkId(id, 'subscription')) {
throw new ApiError('The subscription id is invalid');
} // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const _ref = parameters || {},
query = _objectWithoutProperties(_ref, ["customerId"]);
return this.network.get(`${this.getResourceUrl(customerId)}/${id}`, query);
}
/**
* Get all customer's subscriptions.
*
* @since 3.0.0
*
* @see https://docs.mollie.com/reference/v2/subscriptions-api/list-subscriptions
*/
list(parameters) {
if (renege(this, this.list, ...arguments)) return; // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer id is invalid');
}
const _ref2 = parameters || {},
query = _objectWithoutProperties(_ref2, ["customerId"]);
return this.network.list(this.getResourceUrl(customerId), 'subscriptions', query).then(result => this.injectPaginationHelpers(result, this.list, parameters || {}));
}
/**
* Update a customer's subscription.
*
* @since 2.0.0
*
* @see https://docs.mollie.com/reference/v2/subscriptions-api/update-subscription
*/
update(id, parameters) {
if (renege(this, this.update, ...arguments)) return;
if (!checkId(id, 'subscription')) {
throw new ApiError('The subscription id is invalid');
}
const customerId = this.getParentId(parameters.customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer is invalid');
}
const data = _objectWithoutProperties(parameters, ["customerId"]);
return this.network.patch(`${this.getResourceUrl(customerId)}/${id}`, data);
}
/**
* Cancel a Subscription
*
* @since 1.3.2
*
* @see https://docs.mollie.com/reference/v2/subscriptions-api/cancel-subscription
*/
cancel(id, parameters) {
if (renege(this, this.cancel, ...arguments)) return;
if (!checkId(id, 'subscription')) {
throw new ApiError('The subscription id is invalid');
} // parameters || {} is used here, because in case withParent is used, parameters could be omitted.
const customerId = this.getParentId((parameters || {}).customerId);
if (!checkId(customerId, 'customer')) {
throw new ApiError('The customer is invalid');
}
const _ref3 = parameters || {},
context = _objectWithoutProperties(_ref3, ["customerId"]);
return this.network.delete(`${this.getResourceUrl(customerId)}/${id}`, context);
}
}
/**
* Method Response object.
*
* @param resource - Indicates the response contains a method object. Will always contain `method` for this endpoint.
* @param id - The unique identifier of the payment method. When used during payment creation, the payment method
* selection screen will be skipped.
* @param description - The full name of the payment method, translated in the optional locale passed.
* @param image - The URLs of images representing the payment method.
* @param pricing - See {@link IMethodPricing}
* @param _links - An object with several URL objects relevant to the payment method.
*
* @see https://docs.mollie.com/reference/v2/methods-api/get-method
*/
(function (MethodImageSize) {
MethodImageSize["size1x"] = "size1x";
MethodImageSize["size2x"] = "size2x";
MethodImageSize["svg"] = "svg";
})(exports.MethodImageSize || (exports.MethodImageSize = {}));
/**
* Pricing set of the payment method what will be include if you add the parameter.
*
* @param description - The area or product-type where the pricing is applied for, translated in the optional locale passed.
* @param fixed - The fixed price per transaction
* @param variable - A string containing the percentage what will be charged over the payment amount besides the fixed price.
*/
(function (MethodInclude) {
MethodInclude["issuers"] = "issuers";
MethodInclude["pricing"] = "pricing";
})(exports.MethodInclude || (exports.MethodInclude = {}));
var methodHelpers = _objectSpread2({}, commonHelpers, {
/**
* Method image URL
*
* @since 2.0.0
* @since 3.0.0 SVG support
*/
getImage: function getImage(size = exports.MethodImageSize.size2x) {
switch (size) {
case '1x':
case exports.MethodImageSize.size1x:
return this.image[exports.MethodImageSize.size1x];
case '2x':
case exports.MethodImageSize.size2x:
return this.image[exports.MethodImageSize.size2x];
case exports.MethodImageSize.svg:
return this.image[exports.MethodImageSize.svg];
default:
throw new ApiError(`Unexpected size: ${size}`);
}
}
});
function injectPrototypes$7(input) {
return Object.assign(Object.create(methodHelpers), input);
}
class MethodsResource extends Resource {
constructor(...args) {
super(...args);
_defineProperty(this, "injectPrototypes", injectPrototypes$7);
_defineProperty(this, "all", this.list);
_defineProperty(this, "page", this.list);
}
getResourceUrl() {
return 'methods';
}
get(id, parameters) {
if (renege(this, this.get, ...arguments)) return;
return this.network.get(`${this.getResourceUrl()}/${id}`, parameters);
}
/**
* Retrieve a list of Payment Methods
*
* @since 3.0.0
*
* @see https://docs.mollie.com/reference/v2/methods-api/list-methods
*/
list(parameters = {}) {
if (renege(this, this.list, ...arguments)) return;
return this.network.list(this.getResourceUrl(), 'methods', parameters).then(result => this.injectPaginationHelpers(result, this.list, parameters));
}
}
var onboardingHelpers = _objectSpread2({}, commonHelpers, {
needsData: function needsData() {
return this.status == 'needs-data';
},
isInReview: function isInReview() {
return this.status == 'in-review';
},
isCompleted: function isCompleted() {
return this.status == 'completed';
}
});
function injectPrototypes$8(input) {
return Object.assign(Object.create(onboardingHelpers), input);
}
class OnboardingResource extends Resource {
constructor(...args) {
super(...args);
_defin