@promokit/js
Version:
JavaScript SDK for PromoKit marketing infrastructure
424 lines (407 loc) • 20.4 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Promo = {}));
})(this, (function (exports) { 'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var WaitlistAPI = /** @class */ (function () {
function WaitlistAPI(config, client) {
this.config = config;
this.client = client;
}
WaitlistAPI.prototype.create = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request('/waitlist/create', {
method: 'POST',
body: JSON.stringify(data),
})];
});
});
};
WaitlistAPI.prototype.getStats = function (projectId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/waitlist/".concat(projectId, "/stats"))];
});
});
};
WaitlistAPI.prototype.export = function (projectId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/waitlist/".concat(projectId, "/export"))];
});
});
};
WaitlistAPI.prototype.remove = function (projectId, email) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/waitlist/".concat(projectId, "/remove"), {
method: 'DELETE',
body: JSON.stringify({ email: email }),
})];
});
});
};
return WaitlistAPI;
}());
var TestimonialAPI = /** @class */ (function () {
function TestimonialAPI(config, client) {
this.config = config;
this.client = client;
}
TestimonialAPI.prototype.submit = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request('/testimonial/submit', {
method: 'POST',
body: JSON.stringify(data),
})];
});
});
};
TestimonialAPI.prototype.get = function (productId_1) {
return __awaiter(this, arguments, void 0, function (productId, options) {
var params;
if (options === void 0) { options = {}; }
return __generator(this, function (_a) {
params = new URLSearchParams();
if (options.limit)
params.append('limit', options.limit.toString());
if (options.offset)
params.append('offset', options.offset.toString());
if (options.status)
params.append('status', options.status);
return [2 /*return*/, this.client.request("/testimonial/".concat(productId, "?").concat(params.toString()))];
});
});
};
TestimonialAPI.prototype.approve = function (testimonialId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/testimonial/".concat(testimonialId, "/approve"), {
method: 'POST',
})];
});
});
};
TestimonialAPI.prototype.reject = function (testimonialId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/testimonial/".concat(testimonialId, "/reject"), {
method: 'POST',
})];
});
});
};
return TestimonialAPI;
}());
var ChangelogAPI = /** @class */ (function () {
function ChangelogAPI(config, client) {
this.config = config;
this.client = client;
}
ChangelogAPI.prototype.create = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request('/changelog/create', {
method: 'POST',
body: JSON.stringify(data),
})];
});
});
};
ChangelogAPI.prototype.get = function (projectId_1) {
return __awaiter(this, arguments, void 0, function (projectId, options) {
var params;
if (options === void 0) { options = {}; }
return __generator(this, function (_a) {
params = new URLSearchParams();
if (options.limit)
params.append('limit', options.limit.toString());
if (options.offset)
params.append('offset', options.offset.toString());
return [2 /*return*/, this.client.request("/changelog/".concat(projectId, "?").concat(params.toString()))];
});
});
};
ChangelogAPI.prototype.subscribe = function (projectId, email) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/changelog/".concat(projectId, "/subscribe"), {
method: 'POST',
body: JSON.stringify({ email: email }),
})];
});
});
};
ChangelogAPI.prototype.update = function (entryId, data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/changelog/".concat(entryId), {
method: 'PUT',
body: JSON.stringify(data),
})];
});
});
};
ChangelogAPI.prototype.delete = function (entryId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.client.request("/changelog/".concat(entryId), {
method: 'DELETE',
})];
});
});
};
return ChangelogAPI;
}());
var PromoError = /** @class */ (function (_super) {
__extends(PromoError, _super);
function PromoError(error) {
var _this = _super.call(this, error.message) || this;
_this.name = 'PromoError';
_this.status = error.status;
_this.statusText = error.statusText;
_this.details = error.details;
_this.endpoint = error.endpoint;
_this.timestamp = error.timestamp;
return _this;
}
Object.defineProperty(PromoError.prototype, "isNetworkError", {
get: function () {
return this.status === 0 || this.status >= 500;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isClientError", {
get: function () {
return this.status >= 400 && this.status < 500;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isConflictError", {
get: function () {
return this.status === 409;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isUnauthorizedError", {
get: function () {
return this.status === 401;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isForbiddenError", {
get: function () {
return this.status === 403;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isNotFoundError", {
get: function () {
return this.status === 404;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PromoError.prototype, "isRateLimitError", {
get: function () {
return this.status === 429;
},
enumerable: false,
configurable: true
});
PromoError.prototype.getUserFriendlyMessage = function () {
var _a;
switch (this.status) {
case 409:
if ((_a = this.endpoint) === null || _a === void 0 ? void 0 : _a.includes('/waitlist/create')) {
return 'This email is already on the waitlist. Check your inbox for your referral link!';
}
return 'This resource already exists.';
case 401:
return 'Authentication failed. Please check your API key.';
case 403:
return 'You don\'t have permission to access this resource.';
case 404:
return 'The requested resource was not found.';
case 429:
return 'Too many requests. Please try again in a few moments.';
case 0:
return 'Network error. Please check your internet connection.';
default:
if (this.isNetworkError) {
return 'Server error. Please try again later.';
}
return this.message || 'An unexpected error occurred.';
}
};
return PromoError;
}(Error));
var PromoClient = /** @class */ (function () {
function PromoClient(config) {
this.config = {
apiKey: config.apiKey,
};
this.waitlist = new WaitlistAPI(this.config, this);
this.testimonial = new TestimonialAPI(this.config, this);
this.changelog = new ChangelogAPI(this.config, this);
}
PromoClient.prototype.request = function (endpoint_1) {
return __awaiter(this, arguments, void 0, function (endpoint, options) {
var url, response, errorDetails, errorMessage, contentType, parseError_1, apiError, error_1, apiError;
if (options === void 0) { options = {}; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = "https://promokit.pro/api".concat(endpoint);
_a.label = 1;
case 1:
_a.trys.push([1, 11, , 12]);
return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { headers: __assign({ 'Authorization': "Bearer ".concat(this.config.apiKey), 'Content-Type': 'application/json' }, options.headers) }))];
case 2:
response = _a.sent();
if (!!response.ok) return [3 /*break*/, 10];
errorDetails = void 0;
errorMessage = response.statusText || 'API request failed';
_a.label = 3;
case 3:
_a.trys.push([3, 8, , 9]);
contentType = response.headers.get('content-type');
if (!(contentType && contentType.includes('application/json'))) return [3 /*break*/, 5];
return [4 /*yield*/, response.json()];
case 4:
errorDetails = _a.sent();
errorMessage = errorDetails.message || errorDetails.error || errorMessage;
return [3 /*break*/, 7];
case 5: return [4 /*yield*/, response.text()];
case 6:
errorDetails = _a.sent();
_a.label = 7;
case 7: return [3 /*break*/, 9];
case 8:
parseError_1 = _a.sent();
// If we can't parse the error response, use the status text
errorDetails = "Failed to parse error response: ".concat(parseError_1);
return [3 /*break*/, 9];
case 9:
apiError = {
status: response.status,
statusText: response.statusText,
message: errorMessage,
details: errorDetails,
endpoint: endpoint,
timestamp: new Date().toISOString(),
};
throw new PromoError(apiError);
case 10: return [2 /*return*/, response.json()];
case 11:
error_1 = _a.sent();
// Handle network errors (fetch throws)
if (error_1 instanceof PromoError) {
throw error_1;
}
apiError = {
status: 0,
statusText: 'Network Error',
message: error_1 instanceof Error ? error_1.message : 'Network request failed',
details: error_1,
endpoint: endpoint,
timestamp: new Date().toISOString(),
};
throw new PromoError(apiError);
case 12: return [2 /*return*/];
}
});
});
};
return PromoClient;
}());
exports.ChangelogAPI = ChangelogAPI;
exports.PromoClient = PromoClient;
exports.PromoError = PromoError;
exports.TestimonialAPI = TestimonialAPI;
exports.WaitlistAPI = WaitlistAPI;
}));
//# sourceMappingURL=index.umd.js.map