@pkpayplus/core 0.0.0-stage → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PKPay+
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @pkpayplus/core
2
+
3
+ The universal shared core engine, HTTP client, iframe dialog controller, event listeners, and domain models for the **PKPay+** SDK ecosystem.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@pkpayplus/core.svg)](https://www.npmjs.com/package/@pkpayplus/core)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ---
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install @pkpayplus/core
14
+ # or
15
+ pnpm add @pkpayplus/core
16
+ ```
17
+
18
+ ---
19
+
20
+ ## What's Included
21
+
22
+ - **`HTTPClient`**: Universal fetch-based HTTP transport with retries, exponential backoff, and standard PKPay+ error translation (`PKPayPlusAuthenticationError`, `PKPayPlusInvalidRequestError`, `PKPayPlusRateLimitError`, etc.).
23
+ - **`createCheckoutDialog`**: Headless DOM dialog/overlay injector for rendering secure PKPay+ iframe checkout.
24
+ - **`setupPostMessageListener`**: Type-safe cross-origin postMessage event listener (`pkpayplus:ready`, `pkpayplus:success`, `pkpayplus:close`).
25
+ - **TypeScript Types**: Complete definitions for `CheckoutSession`, `Product`, `Price`, `PaymentLink`, and checkout events.
26
+
27
+ ---
28
+
29
+ ## License
30
+
31
+ MIT © [PKPay+](https://pkpayplus.com)
2
32
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/dist/index.cjs ADDED
@@ -0,0 +1,522 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ HTTPClient: () => HTTPClient,
24
+ PKPayPlusAPIConnectionError: () => PKPayPlusAPIConnectionError,
25
+ PKPayPlusAuthenticationError: () => PKPayPlusAuthenticationError,
26
+ PKPayPlusError: () => PKPayPlusError,
27
+ PKPayPlusInvalidRequestError: () => PKPayPlusInvalidRequestError,
28
+ PKPayPlusRateLimitError: () => PKPayPlusRateLimitError,
29
+ PKPayPlusSecurityError: () => PKPayPlusSecurityError,
30
+ Webhooks: () => Webhooks,
31
+ assertClientKey: () => assertClientKey,
32
+ assertServerEnvironment: () => assertServerEnvironment,
33
+ assertServerKey: () => assertServerKey,
34
+ createCheckoutDialog: () => createCheckoutDialog,
35
+ detectModeFromKey: () => detectModeFromKey,
36
+ normalizeUrl: () => normalizeUrl,
37
+ setupPostMessageListener: () => setupPostMessageListener
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/events.ts
42
+ function setupPostMessageListener(handlers) {
43
+ let expectedOrigin = "";
44
+ try {
45
+ const urlObj = new URL(handlers.targetUrl, window.location.href);
46
+ expectedOrigin = urlObj.origin;
47
+ } catch {
48
+ expectedOrigin = "";
49
+ }
50
+ const listener = (event) => {
51
+ if (expectedOrigin && event.origin !== expectedOrigin && !event.origin.includes("pkpayplus.com")) {
52
+ return;
53
+ }
54
+ const payload = event.data;
55
+ if (!payload || typeof payload !== "object") {
56
+ return;
57
+ }
58
+ const eventType = payload.type || payload.event;
59
+ switch (eventType) {
60
+ case "pkpayplus:loaded":
61
+ case "pkpay:loaded":
62
+ handlers.onLoaded?.();
63
+ break;
64
+ case "pkpayplus:completed":
65
+ case "pkpayplus:success":
66
+ case "pkpay:completed":
67
+ case "payment.succeeded":
68
+ handlers.onSuccess?.({
69
+ sessionId: payload.sessionId || payload.session_id || payload.data?.sessionId || "",
70
+ ...payload.data || {}
71
+ });
72
+ break;
73
+ case "pkpayplus:canceled":
74
+ case "pkpayplus:cancelled":
75
+ case "pkpay:canceled":
76
+ handlers.onCancel?.();
77
+ break;
78
+ case "pkpayplus:error":
79
+ case "pkpay:error":
80
+ handlers.onError?.({
81
+ message: payload.message || payload.error?.message || "Payment failed",
82
+ code: payload.code || payload.error?.code,
83
+ ...payload.error || {}
84
+ });
85
+ break;
86
+ default:
87
+ break;
88
+ }
89
+ };
90
+ window.addEventListener("message", listener);
91
+ return () => {
92
+ window.removeEventListener("message", listener);
93
+ };
94
+ }
95
+
96
+ // src/dialog.ts
97
+ var DIALOG_STYLE_ID = "pkpayplus-dialog-styles";
98
+ function injectDialogStyles() {
99
+ if (typeof document === "undefined" || document.getElementById(DIALOG_STYLE_ID)) {
100
+ return;
101
+ }
102
+ const style = document.createElement("style");
103
+ style.id = DIALOG_STYLE_ID;
104
+ style.textContent = `
105
+ .pkpayplus-overlay {
106
+ position: fixed;
107
+ top: 0;
108
+ left: 0;
109
+ width: 100vw;
110
+ height: 100vh;
111
+ background: rgba(15, 23, 42, 0.65);
112
+ backdrop-filter: blur(4px);
113
+ -webkit-backdrop-filter: blur(4px);
114
+ z-index: 999999;
115
+ display: flex;
116
+ align-items: center;
117
+ justify-content: center;
118
+ opacity: 0;
119
+ transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1);
120
+ box-sizing: border-box;
121
+ padding: 16px;
122
+ }
123
+ .pkpayplus-overlay.pkpayplus-visible {
124
+ opacity: 1;
125
+ }
126
+ .pkpayplus-dialog {
127
+ position: relative;
128
+ width: 100%;
129
+ max-width: 480px;
130
+ height: 92vh;
131
+ max-height: 720px;
132
+ background: #ffffff;
133
+ border-radius: 16px;
134
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.35);
135
+ overflow: hidden;
136
+ transform: scale(0.96) translateY(12px);
137
+ transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);
138
+ display: flex;
139
+ flex-direction: column;
140
+ }
141
+ .pkpayplus-visible .pkpayplus-dialog {
142
+ transform: scale(1) translateY(0);
143
+ }
144
+ .pkpayplus-iframe {
145
+ width: 100%;
146
+ height: 100%;
147
+ border: none;
148
+ flex: 1;
149
+ background: transparent;
150
+ }
151
+ .pkpayplus-close-btn {
152
+ position: absolute;
153
+ top: 12px;
154
+ right: 12px;
155
+ width: 32px;
156
+ height: 32px;
157
+ border-radius: 50%;
158
+ background: rgba(241, 245, 249, 0.9);
159
+ border: 1px solid rgba(203, 213, 225, 0.8);
160
+ cursor: pointer;
161
+ display: flex;
162
+ align-items: center;
163
+ justify-content: center;
164
+ color: #475569;
165
+ font-size: 18px;
166
+ line-height: 1;
167
+ z-index: 10;
168
+ transition: background 0.15s ease, transform 0.1s ease;
169
+ }
170
+ .pkpayplus-close-btn:hover {
171
+ background: #e2e8f0;
172
+ color: #0f172a;
173
+ transform: scale(1.05);
174
+ }
175
+ @media (max-width: 640px) {
176
+ .pkpayplus-overlay {
177
+ padding: 0;
178
+ }
179
+ .pkpayplus-dialog {
180
+ max-width: 100%;
181
+ height: 100%;
182
+ max-height: 100vh;
183
+ border-radius: 0;
184
+ }
185
+ }
186
+ `;
187
+ document.head.appendChild(style);
188
+ }
189
+ function createCheckoutDialog(options) {
190
+ if (typeof document === "undefined") {
191
+ throw new Error(
192
+ "createCheckoutDialog can only be invoked in a browser environment with window and document."
193
+ );
194
+ }
195
+ injectDialogStyles();
196
+ const previousOverflow = document.body.style.overflow;
197
+ document.body.style.overflow = "hidden";
198
+ const overlay = document.createElement("div");
199
+ overlay.className = "pkpayplus-overlay";
200
+ const dialog = document.createElement("div");
201
+ dialog.className = "pkpayplus-dialog";
202
+ const closeBtn = document.createElement("button");
203
+ closeBtn.className = "pkpayplus-close-btn";
204
+ closeBtn.setAttribute("aria-label", "Close PKPay+ Checkout");
205
+ closeBtn.innerHTML = "×";
206
+ const iframe = document.createElement("iframe");
207
+ iframe.className = "pkpayplus-iframe";
208
+ iframe.src = options.url;
209
+ iframe.setAttribute("allow", "payment *; camera *");
210
+ iframe.setAttribute("title", "PKPay+ Secure Checkout");
211
+ dialog.appendChild(closeBtn);
212
+ dialog.appendChild(iframe);
213
+ overlay.appendChild(dialog);
214
+ document.body.appendChild(overlay);
215
+ requestAnimationFrame(() => {
216
+ overlay.classList.add("pkpayplus-visible");
217
+ });
218
+ let isClosed = false;
219
+ const cleanup = () => {
220
+ if (isClosed) return;
221
+ isClosed = true;
222
+ document.body.style.overflow = previousOverflow;
223
+ overlay.classList.remove("pkpayplus-visible");
224
+ cleanupEvents();
225
+ window.removeEventListener("keydown", handleKeyDown);
226
+ setTimeout(() => {
227
+ if (overlay.parentNode) {
228
+ overlay.parentNode.removeChild(overlay);
229
+ }
230
+ }, 250);
231
+ };
232
+ const handleClose = () => {
233
+ cleanup();
234
+ options.onCancel?.();
235
+ };
236
+ const handleKeyDown = (e) => {
237
+ if (e.key === "Escape") {
238
+ handleClose();
239
+ }
240
+ };
241
+ closeBtn.addEventListener("click", handleClose);
242
+ window.addEventListener("keydown", handleKeyDown);
243
+ const cleanupEvents = setupPostMessageListener({
244
+ targetUrl: options.url,
245
+ onLoaded: () => options.onLoaded?.(),
246
+ onSuccess: (data) => {
247
+ cleanup();
248
+ options.onSuccess?.(data);
249
+ },
250
+ onCancel: () => {
251
+ cleanup();
252
+ options.onCancel?.();
253
+ },
254
+ onError: (error) => {
255
+ cleanup();
256
+ options.onError?.(error);
257
+ }
258
+ });
259
+ return {
260
+ close: cleanup,
261
+ iframe,
262
+ container: overlay
263
+ };
264
+ }
265
+
266
+ // src/errors.ts
267
+ var PKPayPlusError = class extends Error {
268
+ statusCode;
269
+ code;
270
+ raw;
271
+ constructor(message, options) {
272
+ super(message);
273
+ this.name = "PKPayPlusError";
274
+ this.statusCode = options?.statusCode;
275
+ this.code = options?.code;
276
+ this.raw = options?.raw;
277
+ Object.setPrototypeOf(this, new.target.prototype);
278
+ }
279
+ };
280
+ var PKPayPlusAuthenticationError = class extends PKPayPlusError {
281
+ constructor(message = "Invalid or inactive PKPay+ API key") {
282
+ super(message, { statusCode: 401, code: "authentication_error" });
283
+ this.name = "PKPayPlusAuthenticationError";
284
+ }
285
+ };
286
+ var PKPayPlusInvalidRequestError = class extends PKPayPlusError {
287
+ constructor(message, raw) {
288
+ super(message, { statusCode: 400, code: "invalid_request_error", raw });
289
+ this.name = "PKPayPlusInvalidRequestError";
290
+ }
291
+ };
292
+ var PKPayPlusRateLimitError = class extends PKPayPlusError {
293
+ constructor(message = "PKPay+ API rate limit exceeded") {
294
+ super(message, { statusCode: 429, code: "rate_limit_error" });
295
+ this.name = "PKPayPlusRateLimitError";
296
+ }
297
+ };
298
+ var PKPayPlusAPIConnectionError = class extends PKPayPlusError {
299
+ constructor(message = "Failed to connect to PKPay+ API") {
300
+ super(message, { statusCode: 0, code: "connection_error" });
301
+ this.name = "PKPayPlusAPIConnectionError";
302
+ }
303
+ };
304
+ var PKPayPlusSecurityError = class extends PKPayPlusError {
305
+ constructor(message) {
306
+ super(message, { statusCode: 403, code: "security_violation" });
307
+ this.name = "PKPayPlusSecurityError";
308
+ }
309
+ };
310
+
311
+ // src/utils.ts
312
+ function detectModeFromKey(key) {
313
+ if (typeof key === "string" && (key.startsWith("pk_test_") || key.startsWith("sk_test_"))) {
314
+ return "test";
315
+ }
316
+ return "live";
317
+ }
318
+ function assertServerEnvironment() {
319
+ if (typeof window !== "undefined") {
320
+ console.error(
321
+ "[PKPayPlus Security Warning]: You are running server code in a browser environment. Secret keys must remain strictly on your backend server!"
322
+ );
323
+ }
324
+ }
325
+ function assertClientKey(key) {
326
+ if (typeof key === "string" && (key.startsWith("sk_live_") || key.startsWith("sk_test_"))) {
327
+ throw new PKPayPlusSecurityError(
328
+ "You passed a Secret Key (sk_...) to a Client SDK instance. Secret keys must never be exposed to browser clients. Use your Publishable Key (pk_...) instead."
329
+ );
330
+ }
331
+ }
332
+ function assertServerKey(key) {
333
+ if (typeof key === "string" && (key.startsWith("pk_live_") || key.startsWith("pk_test_"))) {
334
+ console.warn(
335
+ "[PKPayPlus Warning]: You passed a Publishable Key (pk_...) to the Server SDK. The server SDK requires your Secret Key (sk_...) to authorize administrative operations."
336
+ );
337
+ }
338
+ }
339
+ function normalizeUrl(baseUrl, path) {
340
+ const base = baseUrl.replace(/\/+$/, "");
341
+ const cleanPath = path.replace(/^\/+/, "");
342
+ return `${base}/${cleanPath}`;
343
+ }
344
+
345
+ // src/http.ts
346
+ var HTTPClient = class {
347
+ secretKey;
348
+ merchantId;
349
+ baseUrl;
350
+ timeout;
351
+ maxRetries;
352
+ constructor(options) {
353
+ if (!options?.secretKey) {
354
+ throw new PKPayPlusAuthenticationError(
355
+ 'Missing required "secretKey" in PKPayPlus configuration'
356
+ );
357
+ }
358
+ if (!options?.merchantId) {
359
+ throw new PKPayPlusInvalidRequestError(
360
+ 'Missing required "merchantId" in PKPayPlus configuration'
361
+ );
362
+ }
363
+ assertServerEnvironment();
364
+ assertServerKey(options.secretKey);
365
+ this.secretKey = options.secretKey;
366
+ this.merchantId = options.merchantId;
367
+ this.baseUrl = options.baseUrl || "https://api.pkpayplus.com";
368
+ this.timeout = options.timeout ?? 1e4;
369
+ this.maxRetries = options.maxRetries ?? 2;
370
+ }
371
+ getMerchantId() {
372
+ return this.merchantId;
373
+ }
374
+ getBaseUrl() {
375
+ return this.baseUrl;
376
+ }
377
+ async request(method, path, options) {
378
+ let fullUrl = normalizeUrl(this.baseUrl, path);
379
+ if (options?.query) {
380
+ const searchParams = new URLSearchParams();
381
+ for (const [key, value] of Object.entries(options.query)) {
382
+ if (value !== void 0 && value !== null) {
383
+ searchParams.append(key, String(value));
384
+ }
385
+ }
386
+ const qs = searchParams.toString();
387
+ if (qs) {
388
+ fullUrl += (fullUrl.includes("?") ? "&" : "?") + qs;
389
+ }
390
+ }
391
+ const headers = {
392
+ Authorization: `Bearer ${this.secretKey}`,
393
+ Accept: "application/json",
394
+ "PKPayPlus-Version": "2026-10-01",
395
+ ...options?.headers || {}
396
+ };
397
+ if (options?.body) {
398
+ headers["Content-Type"] = "application/json";
399
+ }
400
+ if (options?.idempotencyKey) {
401
+ headers["Idempotency-Key"] = options.idempotencyKey;
402
+ }
403
+ let attempts = 0;
404
+ const maxAttempts = 1 + this.maxRetries;
405
+ while (attempts < maxAttempts) {
406
+ attempts++;
407
+ try {
408
+ const controller = new AbortController();
409
+ const timer = setTimeout(() => controller.abort(), this.timeout);
410
+ const response = await fetch(fullUrl, {
411
+ method,
412
+ headers,
413
+ body: options?.body ? JSON.stringify(options.body) : void 0,
414
+ signal: controller.signal
415
+ });
416
+ clearTimeout(timer);
417
+ const contentType = response.headers.get("content-type") || "";
418
+ const isJson = contentType.includes("application/json");
419
+ const rawText = await response.text();
420
+ const responseData = isJson && rawText ? JSON.parse(rawText) : rawText;
421
+ if (!response.ok) {
422
+ this.handleHttpError(response.status, responseData);
423
+ }
424
+ return responseData;
425
+ } catch (err) {
426
+ const isLastAttempt = attempts >= maxAttempts;
427
+ const isAbort = err?.name === "AbortError";
428
+ if (err instanceof PKPayPlusError && err.statusCode && err.statusCode < 500) {
429
+ throw err;
430
+ }
431
+ if (isLastAttempt) {
432
+ if (err instanceof PKPayPlusError) {
433
+ throw err;
434
+ }
435
+ if (isAbort) {
436
+ throw new PKPayPlusAPIConnectionError(`Request timed out after ${this.timeout}ms`);
437
+ }
438
+ throw new PKPayPlusAPIConnectionError(
439
+ err?.message || "Network request failed"
440
+ );
441
+ }
442
+ const delay = Math.min(100 * 2 ** (attempts - 1) + Math.random() * 50, 2e3);
443
+ await new Promise((resolve) => setTimeout(resolve, delay));
444
+ }
445
+ }
446
+ throw new PKPayPlusAPIConnectionError("Failed request after multiple retry attempts");
447
+ }
448
+ handleHttpError(status, data) {
449
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : typeof data === "object" && data !== null && "error" in data ? String(data.error) : `Request failed with HTTP status ${status}`;
450
+ if (status === 401) {
451
+ throw new PKPayPlusAuthenticationError(message);
452
+ }
453
+ if (status === 429) {
454
+ throw new PKPayPlusRateLimitError(message);
455
+ }
456
+ if (status >= 400 && status < 500) {
457
+ throw new PKPayPlusInvalidRequestError(message, data);
458
+ }
459
+ throw new PKPayPlusError(message, { statusCode: status, raw: data });
460
+ }
461
+ };
462
+
463
+ // src/webhooks.ts
464
+ var import_node_crypto = require("crypto");
465
+ var Webhooks = class {
466
+ constructEvent(options) {
467
+ const { payload, signatureHeader, webhookSecret } = options;
468
+ if (!payload) {
469
+ throw new PKPayPlusSecurityError("Missing webhook payload");
470
+ }
471
+ if (!signatureHeader) {
472
+ throw new PKPayPlusSecurityError("Missing webhook signature header (x-pkpayplus-signature)");
473
+ }
474
+ if (!webhookSecret) {
475
+ throw new PKPayPlusSecurityError("Missing webhook secret");
476
+ }
477
+ const payloadString = typeof payload === "string" ? payload : Buffer.isBuffer(payload) ? payload.toString("utf8") : JSON.stringify(payload);
478
+ const expectedSignature = (0, import_node_crypto.createHmac)("sha256", webhookSecret).update(payloadString, "utf8").digest("hex");
479
+ let candidateSignature = signatureHeader.trim();
480
+ if (candidateSignature.includes("v1=")) {
481
+ const parts = candidateSignature.split(",");
482
+ const v1Part = parts.find((p) => p.trim().startsWith("v1="));
483
+ if (v1Part) {
484
+ candidateSignature = v1Part.trim().substring(3);
485
+ }
486
+ }
487
+ const expectedBuffer = Buffer.from(expectedSignature, "hex");
488
+ const candidateBuffer = Buffer.from(candidateSignature, "hex");
489
+ if (expectedBuffer.length !== candidateBuffer.length || !(0, import_node_crypto.timingSafeEqual)(expectedBuffer, candidateBuffer)) {
490
+ throw new PKPayPlusSecurityError("Webhook signature verification failed");
491
+ }
492
+ try {
493
+ const parsed = typeof payload === "string" || Buffer.isBuffer(payload) ? JSON.parse(payloadString) : payload;
494
+ return parsed;
495
+ } catch {
496
+ throw new PKPayPlusSecurityError("Failed to parse webhook JSON payload");
497
+ }
498
+ }
499
+ generateSignature(payload, secret) {
500
+ const payloadString = typeof payload === "string" ? payload : Buffer.isBuffer(payload) ? payload.toString("utf8") : JSON.stringify(payload);
501
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(payloadString, "utf8").digest("hex");
502
+ }
503
+ };
504
+ // Annotate the CommonJS export names for ESM import in node:
505
+ 0 && (module.exports = {
506
+ HTTPClient,
507
+ PKPayPlusAPIConnectionError,
508
+ PKPayPlusAuthenticationError,
509
+ PKPayPlusError,
510
+ PKPayPlusInvalidRequestError,
511
+ PKPayPlusRateLimitError,
512
+ PKPayPlusSecurityError,
513
+ Webhooks,
514
+ assertClientKey,
515
+ assertServerEnvironment,
516
+ assertServerKey,
517
+ createCheckoutDialog,
518
+ detectModeFromKey,
519
+ normalizeUrl,
520
+ setupPostMessageListener
521
+ });
522
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/events.ts","../src/dialog.ts","../src/errors.ts","../src/utils.ts","../src/http.ts","../src/webhooks.ts"],"sourcesContent":["export * from './dialog';\nexport * from './errors';\nexport * from './events';\nexport * from './http';\nexport * from './types';\nexport * from './utils';\nexport * from './webhooks';\n","export interface PostMessageHandlers {\n targetUrl: string;\n onLoaded?: () => void;\n onSuccess?: (data: { sessionId: string; [key: string]: unknown }) => void;\n onCancel?: () => void;\n onError?: (error: { message: string; code?: string; [key: string]: unknown }) => void;\n}\n\nexport function setupPostMessageListener(handlers: PostMessageHandlers): () => void {\n let expectedOrigin = '';\n try {\n const urlObj = new URL(handlers.targetUrl, window.location.href);\n expectedOrigin = urlObj.origin;\n } catch {\n expectedOrigin = '';\n }\n\n const listener = (event: MessageEvent) => {\n if (\n expectedOrigin &&\n event.origin !== expectedOrigin &&\n !event.origin.includes('pkpayplus.com')\n ) {\n return;\n }\n\n const payload = event.data;\n if (!payload || typeof payload !== 'object') {\n return;\n }\n\n const eventType = payload.type || payload.event;\n\n switch (eventType) {\n case 'pkpayplus:loaded':\n case 'pkpay:loaded':\n handlers.onLoaded?.();\n break;\n\n case 'pkpayplus:completed':\n case 'pkpayplus:success':\n case 'pkpay:completed':\n case 'payment.succeeded':\n handlers.onSuccess?.({\n sessionId: payload.sessionId || payload.session_id || payload.data?.sessionId || '',\n ...(payload.data || {}),\n });\n break;\n\n case 'pkpayplus:canceled':\n case 'pkpayplus:cancelled':\n case 'pkpay:canceled':\n handlers.onCancel?.();\n break;\n\n case 'pkpayplus:error':\n case 'pkpay:error':\n handlers.onError?.({\n message: payload.message || payload.error?.message || 'Payment failed',\n code: payload.code || payload.error?.code,\n ...(payload.error || {}),\n });\n break;\n\n default:\n break;\n }\n };\n\n window.addEventListener('message', listener);\n\n return () => {\n window.removeEventListener('message', listener);\n };\n}\n","import { setupPostMessageListener } from './events';\nimport type { DialogController, OpenDialogOptions } from './types';\n\nconst DIALOG_STYLE_ID = 'pkpayplus-dialog-styles';\n\nfunction injectDialogStyles(): void {\n if (typeof document === 'undefined' || document.getElementById(DIALOG_STYLE_ID)) {\n return;\n }\n\n const style = document.createElement('style');\n style.id = DIALOG_STYLE_ID;\n style.textContent = `\n .pkpayplus-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: rgba(15, 23, 42, 0.65);\n backdrop-filter: blur(4px);\n -webkit-backdrop-filter: blur(4px);\n z-index: 999999;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1);\n box-sizing: border-box;\n padding: 16px;\n }\n .pkpayplus-overlay.pkpayplus-visible {\n opacity: 1;\n }\n .pkpayplus-dialog {\n position: relative;\n width: 100%;\n max-width: 480px;\n height: 92vh;\n max-height: 720px;\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.35);\n overflow: hidden;\n transform: scale(0.96) translateY(12px);\n transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);\n display: flex;\n flex-direction: column;\n }\n .pkpayplus-visible .pkpayplus-dialog {\n transform: scale(1) translateY(0);\n }\n .pkpayplus-iframe {\n width: 100%;\n height: 100%;\n border: none;\n flex: 1;\n background: transparent;\n }\n .pkpayplus-close-btn {\n position: absolute;\n top: 12px;\n right: 12px;\n width: 32px;\n height: 32px;\n border-radius: 50%;\n background: rgba(241, 245, 249, 0.9);\n border: 1px solid rgba(203, 213, 225, 0.8);\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #475569;\n font-size: 18px;\n line-height: 1;\n z-index: 10;\n transition: background 0.15s ease, transform 0.1s ease;\n }\n .pkpayplus-close-btn:hover {\n background: #e2e8f0;\n color: #0f172a;\n transform: scale(1.05);\n }\n @media (max-width: 640px) {\n .pkpayplus-overlay {\n padding: 0;\n }\n .pkpayplus-dialog {\n max-width: 100%;\n height: 100%;\n max-height: 100vh;\n border-radius: 0;\n }\n }\n `;\n document.head.appendChild(style);\n}\n\nexport function createCheckoutDialog(options: OpenDialogOptions): DialogController {\n if (typeof document === 'undefined') {\n throw new Error(\n 'createCheckoutDialog can only be invoked in a browser environment with window and document.'\n );\n }\n\n injectDialogStyles();\n\n const previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n const overlay = document.createElement('div');\n overlay.className = 'pkpayplus-overlay';\n\n const dialog = document.createElement('div');\n dialog.className = 'pkpayplus-dialog';\n\n const closeBtn = document.createElement('button');\n closeBtn.className = 'pkpayplus-close-btn';\n closeBtn.setAttribute('aria-label', 'Close PKPay+ Checkout');\n closeBtn.innerHTML = '&times;';\n\n const iframe = document.createElement('iframe');\n iframe.className = 'pkpayplus-iframe';\n iframe.src = options.url;\n iframe.setAttribute('allow', 'payment *; camera *');\n iframe.setAttribute('title', 'PKPay+ Secure Checkout');\n\n dialog.appendChild(closeBtn);\n dialog.appendChild(iframe);\n overlay.appendChild(dialog);\n document.body.appendChild(overlay);\n\n requestAnimationFrame(() => {\n overlay.classList.add('pkpayplus-visible');\n });\n\n let isClosed = false;\n\n const cleanup = () => {\n if (isClosed) return;\n isClosed = true;\n\n document.body.style.overflow = previousOverflow;\n overlay.classList.remove('pkpayplus-visible');\n cleanupEvents();\n window.removeEventListener('keydown', handleKeyDown);\n\n setTimeout(() => {\n if (overlay.parentNode) {\n overlay.parentNode.removeChild(overlay);\n }\n }, 250);\n };\n\n const handleClose = () => {\n cleanup();\n options.onCancel?.();\n };\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n handleClose();\n }\n };\n\n closeBtn.addEventListener('click', handleClose);\n window.addEventListener('keydown', handleKeyDown);\n\n const cleanupEvents = setupPostMessageListener({\n targetUrl: options.url,\n onLoaded: () => options.onLoaded?.(),\n onSuccess: (data) => {\n cleanup();\n options.onSuccess?.(data);\n },\n onCancel: () => {\n cleanup();\n options.onCancel?.();\n },\n onError: (error) => {\n cleanup();\n options.onError?.(error);\n },\n });\n\n return {\n close: cleanup,\n iframe,\n container: overlay,\n };\n}\n","export class PKPayPlusError extends Error {\n public readonly statusCode?: number;\n public readonly code?: string;\n public readonly raw?: unknown;\n\n constructor(message: string, options?: { statusCode?: number; code?: string; raw?: unknown }) {\n super(message);\n this.name = 'PKPayPlusError';\n this.statusCode = options?.statusCode;\n this.code = options?.code;\n this.raw = options?.raw;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class PKPayPlusAuthenticationError extends PKPayPlusError {\n constructor(message = 'Invalid or inactive PKPay+ API key') {\n super(message, { statusCode: 401, code: 'authentication_error' });\n this.name = 'PKPayPlusAuthenticationError';\n }\n}\n\nexport class PKPayPlusInvalidRequestError extends PKPayPlusError {\n constructor(message: string, raw?: unknown) {\n super(message, { statusCode: 400, code: 'invalid_request_error', raw });\n this.name = 'PKPayPlusInvalidRequestError';\n }\n}\n\nexport class PKPayPlusRateLimitError extends PKPayPlusError {\n constructor(message = 'PKPay+ API rate limit exceeded') {\n super(message, { statusCode: 429, code: 'rate_limit_error' });\n this.name = 'PKPayPlusRateLimitError';\n }\n}\n\nexport class PKPayPlusAPIConnectionError extends PKPayPlusError {\n constructor(message = 'Failed to connect to PKPay+ API') {\n super(message, { statusCode: 0, code: 'connection_error' });\n this.name = 'PKPayPlusAPIConnectionError';\n }\n}\n\nexport class PKPayPlusSecurityError extends PKPayPlusError {\n constructor(message: string) {\n super(message, { statusCode: 403, code: 'security_violation' });\n this.name = 'PKPayPlusSecurityError';\n }\n}\n","import { PKPayPlusSecurityError } from './errors';\nimport type { EnvironmentMode } from './types';\n\nexport function detectModeFromKey(key: string): EnvironmentMode {\n if (typeof key === 'string' && (key.startsWith('pk_test_') || key.startsWith('sk_test_'))) {\n return 'test';\n }\n return 'live';\n}\n\nexport function assertServerEnvironment(): void {\n if (typeof window !== 'undefined') {\n console.error(\n '[PKPayPlus Security Warning]: You are running server code in a browser environment. ' +\n 'Secret keys must remain strictly on your backend server!'\n );\n }\n}\n\nexport function assertClientKey(key: string): void {\n if (typeof key === 'string' && (key.startsWith('sk_live_') || key.startsWith('sk_test_'))) {\n throw new PKPayPlusSecurityError(\n 'You passed a Secret Key (sk_...) to a Client SDK instance. ' +\n 'Secret keys must never be exposed to browser clients. Use your Publishable Key (pk_...) instead.'\n );\n }\n}\n\nexport function assertServerKey(key: string): void {\n if (typeof key === 'string' && (key.startsWith('pk_live_') || key.startsWith('pk_test_'))) {\n console.warn(\n '[PKPayPlus Warning]: You passed a Publishable Key (pk_...) to the Server SDK. ' +\n 'The server SDK requires your Secret Key (sk_...) to authorize administrative operations.'\n );\n }\n}\n\nexport function normalizeUrl(baseUrl: string, path: string): string {\n const base = baseUrl.replace(/\\/+$/, '');\n const cleanPath = path.replace(/^\\/+/, '');\n return `${base}/${cleanPath}`;\n}\n","import {\n PKPayPlusAPIConnectionError,\n PKPayPlusAuthenticationError,\n PKPayPlusError,\n PKPayPlusInvalidRequestError,\n PKPayPlusRateLimitError,\n} from './errors';\nimport type { PKPayPlusServerOptions } from './types';\nimport { assertServerEnvironment, assertServerKey, normalizeUrl } from './utils';\n\nexport class HTTPClient {\n private readonly secretKey: string;\n private readonly merchantId: string;\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly maxRetries: number;\n\n constructor(options: PKPayPlusServerOptions) {\n if (!options?.secretKey) {\n throw new PKPayPlusAuthenticationError(\n 'Missing required \"secretKey\" in PKPayPlus configuration'\n );\n }\n if (!options?.merchantId) {\n throw new PKPayPlusInvalidRequestError(\n 'Missing required \"merchantId\" in PKPayPlus configuration'\n );\n }\n\n assertServerEnvironment();\n assertServerKey(options.secretKey);\n\n this.secretKey = options.secretKey;\n this.merchantId = options.merchantId;\n this.baseUrl = options.baseUrl || 'https://api.pkpayplus.com';\n this.timeout = options.timeout ?? 10000;\n this.maxRetries = options.maxRetries ?? 2;\n }\n\n public getMerchantId(): string {\n return this.merchantId;\n }\n\n public getBaseUrl(): string {\n return this.baseUrl;\n }\n\n public async request<T = unknown>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n options?: {\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n }\n ): Promise<T> {\n let fullUrl = normalizeUrl(this.baseUrl, path);\n\n if (options?.query) {\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n }\n const qs = searchParams.toString();\n if (qs) {\n fullUrl += (fullUrl.includes('?') ? '&' : '?') + qs;\n }\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.secretKey}`,\n Accept: 'application/json',\n 'PKPayPlus-Version': '2026-10-01',\n ...(options?.headers || {}),\n };\n\n if (options?.body) {\n headers['Content-Type'] = 'application/json';\n }\n\n if (options?.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n let attempts = 0;\n const maxAttempts = 1 + this.maxRetries;\n\n while (attempts < maxAttempts) {\n attempts++;\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n\n const response = await fetch(fullUrl, {\n method,\n headers,\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timer);\n\n const contentType = response.headers.get('content-type') || '';\n const isJson = contentType.includes('application/json');\n const rawText = await response.text();\n const responseData = isJson && rawText ? JSON.parse(rawText) : rawText;\n\n if (!response.ok) {\n this.handleHttpError(response.status, responseData);\n }\n\n return responseData as T;\n } catch (err: unknown) {\n const isLastAttempt = attempts >= maxAttempts;\n const isAbort = (err as Error)?.name === 'AbortError';\n\n if (err instanceof PKPayPlusError && err.statusCode && err.statusCode < 500) {\n throw err;\n }\n\n if (isLastAttempt) {\n if (err instanceof PKPayPlusError) {\n throw err;\n }\n if (isAbort) {\n throw new PKPayPlusAPIConnectionError(`Request timed out after ${this.timeout}ms`);\n }\n throw new PKPayPlusAPIConnectionError(\n (err as Error)?.message || 'Network request failed'\n );\n }\n\n const delay = Math.min(100 * 2 ** (attempts - 1) + Math.random() * 50, 2000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new PKPayPlusAPIConnectionError('Failed request after multiple retry attempts');\n }\n\n private handleHttpError(status: number, data: unknown): never {\n const message =\n typeof data === 'object' && data !== null && 'message' in data\n ? String((data as { message: unknown }).message)\n : typeof data === 'object' && data !== null && 'error' in data\n ? String((data as { error: unknown }).error)\n : `Request failed with HTTP status ${status}`;\n\n if (status === 401) {\n throw new PKPayPlusAuthenticationError(message);\n }\n if (status === 429) {\n throw new PKPayPlusRateLimitError(message);\n }\n if (status >= 400 && status < 500) {\n throw new PKPayPlusInvalidRequestError(message, data);\n }\n\n throw new PKPayPlusError(message, { statusCode: status, raw: data });\n }\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { PKPayPlusSecurityError } from './errors';\nimport type { PKPayPlusWebhookEvent } from './types';\n\nexport interface ConstructWebhookEventOptions {\n payload: string | Buffer | Record<string, unknown>;\n signatureHeader: string;\n webhookSecret: string;\n tolerance?: number;\n}\n\nexport class Webhooks {\n public constructEvent<T = Record<string, unknown>>(\n options: ConstructWebhookEventOptions\n ): PKPayPlusWebhookEvent<T> {\n const { payload, signatureHeader, webhookSecret } = options;\n\n if (!payload) {\n throw new PKPayPlusSecurityError('Missing webhook payload');\n }\n if (!signatureHeader) {\n throw new PKPayPlusSecurityError('Missing webhook signature header (x-pkpayplus-signature)');\n }\n if (!webhookSecret) {\n throw new PKPayPlusSecurityError('Missing webhook secret');\n }\n\n const payloadString =\n typeof payload === 'string'\n ? payload\n : Buffer.isBuffer(payload)\n ? payload.toString('utf8')\n : JSON.stringify(payload);\n\n const expectedSignature = createHmac('sha256', webhookSecret)\n .update(payloadString, 'utf8')\n .digest('hex');\n\n let candidateSignature = signatureHeader.trim();\n if (candidateSignature.includes('v1=')) {\n const parts = candidateSignature.split(',');\n const v1Part = parts.find((p) => p.trim().startsWith('v1='));\n if (v1Part) {\n candidateSignature = v1Part.trim().substring(3);\n }\n }\n\n const expectedBuffer = Buffer.from(expectedSignature, 'hex');\n const candidateBuffer = Buffer.from(candidateSignature, 'hex');\n\n if (\n expectedBuffer.length !== candidateBuffer.length ||\n !timingSafeEqual(expectedBuffer, candidateBuffer)\n ) {\n throw new PKPayPlusSecurityError('Webhook signature verification failed');\n }\n\n try {\n const parsed =\n typeof payload === 'string' || Buffer.isBuffer(payload)\n ? JSON.parse(payloadString)\n : payload;\n\n return parsed as PKPayPlusWebhookEvent<T>;\n } catch {\n throw new PKPayPlusSecurityError('Failed to parse webhook JSON payload');\n }\n }\n\n public generateSignature(\n payload: string | Buffer | Record<string, unknown>,\n secret: string\n ): string {\n const payloadString =\n typeof payload === 'string'\n ? payload\n : Buffer.isBuffer(payload)\n ? payload.toString('utf8')\n : JSON.stringify(payload);\n\n return createHmac('sha256', secret).update(payloadString, 'utf8').digest('hex');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,SAAS,yBAAyB,UAA2C;AAClF,MAAI,iBAAiB;AACrB,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,SAAS,WAAW,OAAO,SAAS,IAAI;AAC/D,qBAAiB,OAAO;AAAA,EAC1B,QAAQ;AACN,qBAAiB;AAAA,EACnB;AAEA,QAAM,WAAW,CAAC,UAAwB;AACxC,QACE,kBACA,MAAM,WAAW,kBACjB,CA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