@dpayglobal/dpay-node-sdk 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ Wszystkie istotne zmiany w tym projekcie są dokumentowane w tym pliku.
4
+ Format oparty na [Keep a Changelog](https://keepachangelog.com/pl/1.1.0/),
5
+ wersjonowanie zgodne z [SemVer](https://semver.org/lang/pl/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-07-22
10
+
11
+ Pierwsze wydanie. Parytet wire-protocol z SDK PHP `0.1.1` potwierdzony golden vectorami:
12
+ 23/23 żądania bajtowo identyczne, 503/503 wartości odpowiedzi zgodne.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,245 @@
1
+ # dpay Node.js SDK
2
+
3
+ Oficjalna biblioteka Node.js do integracji z API płatności [dpay.pl](https://dpay.pl).
4
+
5
+ ## Wymagania
6
+
7
+ - Node.js 20 lub nowszy
8
+ - Zero zależności runtime
9
+ - Typy TypeScript dołączone do paczki - osobny pakiet `@types/*` nie jest potrzebny
10
+
11
+ ## Instalacja
12
+
13
+ ```bash
14
+ npm install @dpayglobal/dpay-node-sdk
15
+ ```
16
+
17
+ Paczka jest budowana równolegle jako ESM i CJS, więc `import` i `require` działają
18
+ od razu, bez dodatkowej konfiguracji.
19
+
20
+ ## Szybki start
21
+
22
+ ```js
23
+ import { DPayClient, Money, TransactionType } from '@dpayglobal/dpay-node-sdk'
24
+
25
+ const dpay = new DPayClient({
26
+ service: 'nazwa_serwisu',
27
+ secretHash: 'twoj_secret_hash',
28
+ })
29
+
30
+ const payment = await dpay.payments.register({
31
+ amount: Money.pln(1050),
32
+ transactionType: TransactionType.TRANSFERS,
33
+ urls: {
34
+ success: 'https://twojsklep.pl/sukces',
35
+ fail: 'https://twojsklep.pl/blad',
36
+ ipn: 'https://twojsklep.pl/ipn',
37
+ },
38
+ description: 'Zamówienie #1234',
39
+ custom: 'order-1234',
40
+ })
41
+
42
+ if (payment.redirectUrl !== null) {
43
+ // przekieruj płatnika pod payment.redirectUrl
44
+ }
45
+ ```
46
+
47
+ ## Obsługa IPN
48
+
49
+ dpay uznaje IPN za dostarczony wyłącznie, gdy body odpowiedzi to dokładnie `OK`.
50
+ Kod HTTP nie jest sprawdzany. Zawsze porównaj kwotę z własnym zamówieniem -
51
+ payload IPN nie niesie waluty, więc `event.amount` to surowy string dziesiętny.
52
+
53
+ **Podpis liczy się z surowych bajtów żądania.** `express.json()` konsumuje strumień,
54
+ więc trasa IPN musi być zamontowana przed nim:
55
+
56
+ ```js
57
+ import express from 'express'
58
+ import { DPayClient, IPN_ACK, SignatureVerificationError } from '@dpayglobal/dpay-node-sdk'
59
+
60
+ const app = express()
61
+ const dpay = new DPayClient({ service: 'moj_sklep', secretHash: process.env.DPAY_SECRET_HASH })
62
+
63
+ app.post('/ipn', express.raw({ type: '*/*' }), async (req, res) => {
64
+ let event
65
+ try {
66
+ event = await dpay.ipn.constructEventFromRequest(req.body)
67
+ } catch (error) {
68
+ if (error instanceof SignatureVerificationError) return res.status(400).send('Invalid signature')
69
+ throw error
70
+ }
71
+
72
+ if (event.isTransfer || event.isCapture) {
73
+ await oznaczZamowienieJakoOplacone(event.id, event.amount)
74
+ }
75
+
76
+ res.send(IPN_ACK)
77
+ })
78
+
79
+ app.use(express.json())
80
+ ```
81
+
82
+ W Next.js (App Router) i Hono przekaż obiekt `Request` bezpośrednio:
83
+
84
+ ```js
85
+ export async function POST(request) {
86
+ const event = await dpay.ipn.constructEventFromRequest(request)
87
+ return new Response(IPN_ACK)
88
+ }
89
+ ```
90
+
91
+ ## Zwroty
92
+
93
+ ```js
94
+ import { Money } from '@dpayglobal/dpay-node-sdk'
95
+
96
+ await dpay.refunds.create({ transactionId: 'identyfikator-transakcji' })
97
+ await dpay.refunds.create({
98
+ transactionId: 'identyfikator-transakcji',
99
+ amount: Money.pln(500),
100
+ reason: 'reklamacja',
101
+ })
102
+
103
+ const availability = await dpay.refunds.checkAvailability({ transactionId: 'identyfikator-transakcji' })
104
+ if (availability.isAvailable) {
105
+ // ...
106
+ }
107
+ ```
108
+
109
+ ## Szczegóły transakcji i banki
110
+
111
+ ```js
112
+ const transaction = await dpay.payments.details('identyfikator-transakcji')
113
+ transaction.isPaid
114
+ transaction.availableRefundAmount.toDecimal()
115
+ transaction.refunds
116
+
117
+ const banks = await dpay.banks.forService()
118
+ ```
119
+
120
+ ## Karty S2S
121
+
122
+ ```js
123
+ import { CardData, CardEncryptor } from '@dpayglobal/dpay-node-sdk'
124
+
125
+ const publicKey = await dpay.cards.publicKey()
126
+ const encryptedCardData = new CardEncryptor().encrypt(
127
+ new CardData({ pan: '4111111111111111', cvv: '123', expiry: '12/28' }),
128
+ transactionId,
129
+ publicKey,
130
+ )
131
+
132
+ // deviceInfo to fingerprint przeglądarki płatnika, patrz DeviceInfoParams
133
+ const result = await dpay.cards.payOtp(transactionId, { deviceInfo, encryptedCardData })
134
+
135
+ if (result.requiresThreeDsForm) {
136
+ // zwróć result.threeDsFormHtml jako odpowiedź HTML
137
+ }
138
+ if (result.hasDccOffer) {
139
+ const offer = result.dccOffer
140
+ }
141
+ ```
142
+
143
+ Klucz publiczny jest rotowany - pobieraj go przed każdą próbą płatności.
144
+
145
+ ## Obsługa błędów
146
+
147
+ Wszystkie wyjątki SDK dziedziczą po `DPayError`.
148
+
149
+ ```js
150
+ import { ApiError, DPayError, InvalidRequestError, TransportError } from '@dpayglobal/dpay-node-sdk'
151
+
152
+ try {
153
+ const payment = await dpay.payments.register(params)
154
+ } catch (error) {
155
+ if (error instanceof InvalidRequestError) {
156
+ error.fieldErrors
157
+ } else if (error instanceof ApiError) {
158
+ error.httpStatus
159
+ error.errorCode
160
+ } else if (error instanceof TransportError) {
161
+ // błąd sieci - status płatności nieznany, użyj payments.details()
162
+ } else {
163
+ throw error
164
+ }
165
+ }
166
+ ```
167
+
168
+ Każdy błąd niesie też pole `type` (na przykład `'invalid_request_error'`) - stabilny
169
+ dyskryminator do użycia w `switch`, gdy `instanceof` zawodzi.
170
+
171
+ | Wyjątek | Kiedy |
172
+ |---|---|
173
+ | `AuthenticationError` | 401 - niepoprawny checksum |
174
+ | `InvalidRequestError` | 400, 422 |
175
+ | `AccessDeniedError` | 403 |
176
+ | `NotFoundError` | 404 |
177
+ | `RateLimitError` | 429 |
178
+ | `ApiServerError` | 5xx |
179
+ | `PaymentRejectedError` | rejestracja odrzucona przy HTTP 200 |
180
+ | `CardPaymentError` | płatność kartą odrzucona przy HTTP 200 |
181
+ | `SignatureVerificationError` | niepoprawny podpis IPN |
182
+ | `CardEncryptionError` | szyfrowanie danych karty nie powiodło się |
183
+ | `TransportError` | awaria sieci, timeout lub przerwanie przez `signal` |
184
+ | `DPayValueError` | niepoprawny argument - rzucany przed jakimkolwiek wywołaniem sieciowym |
185
+
186
+ ## Konfiguracja
187
+
188
+ | Opcja | Typ | Opis |
189
+ |---|---|---|
190
+ | `service` | `string` | Nazwa Punktu Płatności z panel.dpay.pl (wymagane) |
191
+ | `secretHash` | `string` | Klucz Secret Hash (wymagane) |
192
+ | `timeout` | `number` | Timeout HTTP w milisekundach (domyślnie 30000) |
193
+ | `httpClient` | `HttpClient` | Własny transport (proxy, retry, testy) |
194
+ | `baseUrls` | `Record<string, string>` | Nadpisanie hostów `apiPayments`, `panel`, `gateway` |
195
+ | `onRequest` | `(context) => void` | Wywoływane przed każdym żądaniem - `checksum` i dane karty są już ukryte |
196
+ | `onResponse` | `(context) => void` | Wywoływane po każdej odpowiedzi, która dotarła do SDK |
197
+
198
+ ## Anulowanie i timeouty
199
+
200
+ Każda metoda serwisu przyjmuje opcjonalny, ostatni argument `{ signal?, timeout? }`.
201
+
202
+ ```js
203
+ const controller = new AbortController()
204
+ setTimeout(() => controller.abort(), 5000)
205
+
206
+ await dpay.payments.details('identyfikator-transakcji', { signal: controller.signal })
207
+ ```
208
+
209
+ Timeout jest w milisekundach i domyślnie wynosi 30000 (patrz konfiguracja). Wartość podana
210
+ per wywołanie nadpisuje go tylko dla tego jednego wywołania:
211
+
212
+ ```js
213
+ await dpay.payments.details('identyfikator-transakcji', { timeout: 5000 })
214
+ ```
215
+
216
+ `signal` i timeout są łączone - żądanie kończy się na to, co nastąpi pierwsze. Przerwanie
217
+ i przekroczenie czasu mapują się na `TransportError` z zachowanym `cause`.
218
+
219
+ ## Testowanie integracji
220
+
221
+ ```js
222
+ import { DPayClient, Money, TransactionType } from '@dpayglobal/dpay-node-sdk'
223
+ import { MockHttpClient } from '@dpayglobal/dpay-node-sdk/testing'
224
+ import assert from 'node:assert/strict'
225
+
226
+ const transport = new MockHttpClient()
227
+ transport.queueJson(200, { transactionId: 'tx-1', msg: 'https://secure.dpay.pl/pay/1' })
228
+
229
+ const dpay = new DPayClient({ service: 'test', secretHash: 'test', httpClient: transport })
230
+ const payment = await dpay.payments.register({
231
+ amount: Money.pln(1050),
232
+ transactionType: TransactionType.TRANSFERS,
233
+ urls: {
234
+ success: 'https://twojsklep.pl/sukces',
235
+ fail: 'https://twojsklep.pl/blad',
236
+ ipn: 'https://twojsklep.pl/ipn',
237
+ },
238
+ })
239
+
240
+ assert.equal(transport.lastRequestBody.value, '10.50')
241
+ ```
242
+
243
+ ## Licencja
244
+
245
+ Apache-2.0
@@ -0,0 +1,121 @@
1
+ // src/internal/php.ts
2
+ var PRECISION = 14;
3
+ var INTEGER_FAST_PATH_LIMIT = 10 ** PRECISION;
4
+ function isPhpInt(value) {
5
+ return typeof value === "number" && Number.isInteger(value);
6
+ }
7
+ function isPhpBool(value) {
8
+ return typeof value === "boolean";
9
+ }
10
+ function isScalar(value) {
11
+ const type = typeof value;
12
+ return type === "number" || type === "boolean" || type === "string";
13
+ }
14
+ var PHP_WHITESPACE = String.raw`[ \t\n\r\v\f]`;
15
+ var PHP_NUMBER_GRAMMAR = String.raw`(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?`;
16
+ var PHP_NUMERIC_STRING = new RegExp(`^${PHP_WHITESPACE}*[+-]?${PHP_NUMBER_GRAMMAR}${PHP_WHITESPACE}*$`);
17
+ var PHP_LEADING_NUMBER = new RegExp(`^${PHP_WHITESPACE}*([+-]?${PHP_NUMBER_GRAMMAR})`);
18
+ function isNumeric(value) {
19
+ if (typeof value === "number") return true;
20
+ if (typeof value !== "string") return false;
21
+ return PHP_NUMERIC_STRING.test(value);
22
+ }
23
+ function phpStrval(value) {
24
+ if (value === null || value === void 0) return "";
25
+ if (typeof value === "boolean") return value ? "1" : "";
26
+ if (typeof value === "number") return numberToPhpString(value);
27
+ if (typeof value === "string") return value;
28
+ return String(value);
29
+ }
30
+ function numberToPhpString(value) {
31
+ if (Number.isNaN(value)) return "NAN";
32
+ if (value === Number.POSITIVE_INFINITY) return "INF";
33
+ if (value === Number.NEGATIVE_INFINITY) return "-INF";
34
+ if (Object.is(value, -0)) return "-0";
35
+ if (Number.isInteger(value) && Math.abs(value) < INTEGER_FAST_PATH_LIMIT) return String(value);
36
+ return formatG(value);
37
+ }
38
+ function formatG(value) {
39
+ const exponent = Number(value.toExponential(PRECISION - 1).split("e")[1]);
40
+ if (exponent < -4 || exponent >= PRECISION) {
41
+ const mantissa = stripTrailingZeros(value.toExponential(PRECISION - 1).split("e")[0]);
42
+ const normalized = mantissa.includes(".") ? mantissa : `${mantissa}.0`;
43
+ return `${normalized}E${exponent < 0 ? "-" : "+"}${Math.abs(exponent)}`;
44
+ }
45
+ return stripTrailingZeros(value.toFixed(Math.max(0, PRECISION - 1 - exponent)));
46
+ }
47
+ function stripTrailingZeros(text) {
48
+ if (!text.includes(".")) return text;
49
+ return text.replace(/\.?0+$/, "");
50
+ }
51
+ function phpRound(value) {
52
+ return value >= 0 ? Math.floor(value + 0.5) : Math.ceil(value - 0.5);
53
+ }
54
+ function clampToSafeInt(value) {
55
+ if (!Number.isFinite(value)) return 0;
56
+ const truncated = Math.trunc(value);
57
+ if (truncated > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER;
58
+ if (truncated < Number.MIN_SAFE_INTEGER) return Number.MIN_SAFE_INTEGER;
59
+ if (truncated === 0) return 0;
60
+ return truncated;
61
+ }
62
+ function phpInt(value) {
63
+ if (value === null || value === void 0) return 0;
64
+ if (typeof value === "boolean") return value ? 1 : 0;
65
+ if (typeof value === "number") return clampToSafeInt(value);
66
+ if (typeof value === "string") return clampToSafeInt(leadingNumber(value));
67
+ return 0;
68
+ }
69
+ function leadingNumber(text) {
70
+ const match = PHP_LEADING_NUMBER.exec(text);
71
+ return match === null ? 0 : Number(match[1]);
72
+ }
73
+ function phpJsonEncode(data, options) {
74
+ const encoded = JSON.stringify(data, (_key, value) => {
75
+ if (typeof value === "number" && !Number.isFinite(value)) {
76
+ throw new TypeError("Value is not JSON encodable");
77
+ }
78
+ return value;
79
+ });
80
+ if (encoded === void 0) throw new TypeError("Value is not JSON encodable");
81
+ return options?.escapeSlashes === true ? encoded.replaceAll("/", "\\/") : encoded;
82
+ }
83
+
84
+ // src/http/types.ts
85
+ var ApiResponse = class {
86
+ status;
87
+ headers;
88
+ body;
89
+ constructor(status, headers, body) {
90
+ this.status = status;
91
+ this.headers = Object.fromEntries(
92
+ Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value])
93
+ );
94
+ this.body = body;
95
+ }
96
+ /**
97
+ * Retrieve the response header value by name, performing a case-insensitive lookup.
98
+ * Returns `null` if the header was not present in the response.
99
+ */
100
+ getHeader(name) {
101
+ return this.headers[name.toLowerCase()] ?? null;
102
+ }
103
+ /**
104
+ * Attempt to decode the response body as JSON, returning the parsed value if it is a
105
+ * plain object or array, or `null` if the body is not valid JSON or the parsed value
106
+ * is a primitive (string, number, boolean, null).
107
+ */
108
+ decodeJson() {
109
+ let decoded;
110
+ try {
111
+ decoded = JSON.parse(this.body);
112
+ } catch {
113
+ return null;
114
+ }
115
+ return typeof decoded === "object" && decoded !== null ? decoded : null;
116
+ }
117
+ };
118
+
119
+ export { ApiResponse, isNumeric, isPhpBool, isPhpInt, isScalar, phpInt, phpJsonEncode, phpRound, phpStrval };
120
+ //# sourceMappingURL=chunk-SPQCX4N4.js.map
121
+ //# sourceMappingURL=chunk-SPQCX4N4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/php.ts","../src/http/types.ts"],"names":[],"mappings":";AAAA,IAAM,SAAA,GAAY,EAAA;AAClB,IAAM,0BAA0B,EAAA,IAAM,SAAA;AAE/B,SAAS,SAAS,KAAA,EAAyB;AAChD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,MAAA,CAAO,UAAU,KAAK,CAAA;AAC5D;AAEO,SAAS,UAAU,KAAA,EAAyB;AACjD,EAAA,OAAO,OAAO,KAAA,KAAU,SAAA;AAC1B;AAEO,SAAS,SAAS,KAAA,EAAyB;AAChD,EAAA,MAAM,OAAO,OAAO,KAAA;AACpB,EAAA,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,SAAA,IAAa,IAAA,KAAS,QAAA;AAC7D;AAEA,IAAM,iBAAiB,MAAA,CAAO,GAAA,CAAA,aAAA,CAAA;AAC9B,IAAM,qBAAqB,MAAA,CAAO,GAAA,CAAA,uCAAA,CAAA;AAClC,IAAM,kBAAA,GAAqB,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,cAAc,CAAA,MAAA,EAAS,kBAAkB,CAAA,EAAG,cAAc,CAAA,EAAA,CAAI,CAAA;AACxG,IAAM,qBAAqB,IAAI,MAAA,CAAO,IAAI,cAAc,CAAA,OAAA,EAAU,kBAAkB,CAAA,CAAA,CAAG,CAAA;AAEhF,SAAS,UAAU,KAAA,EAAyB;AACjD,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,IAAA;AACtC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,OA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AAAA,EAET,WAAA,CAAY,MAAA,EAAgB,OAAA,EAA2C,IAAA,EAAc;AACnF,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAU,MAAA,CAAO,WAAA;AAAA,MACpB,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,CAAE,IAAI,CAAC,CAAC,IAAA,EAAM,KAAK,MAAM,CAAC,IAAA,CAAK,WAAA,EAAY,EAAG,KAAK,CAAC;AAAA,KAC5E;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,IAAA,EAA6B;AACrC,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,WAAA,EAAa,CAAA,IAAK,IAAA;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAA,GAAsB;AACpB,IAAA,IAAI,OAAA;AACJ,IAAA,IAAI;AACF,MAAA,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA;AAAA,IAChC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,OAAO,OAAA,GAAU,IAAA;AAAA,EACrE;AACF","file":"chunk-SPQCX4N4.js","sourcesContent":["const PRECISION = 14\nconst INTEGER_FAST_PATH_LIMIT = 10 ** PRECISION\n\nexport function isPhpInt(value: unknown): boolean {\n return typeof value === 'number' && Number.isInteger(value)\n}\n\nexport function isPhpBool(value: unknown): boolean {\n return typeof value === 'boolean'\n}\n\nexport function isScalar(value: unknown): boolean {\n const type = typeof value\n return type === 'number' || type === 'boolean' || type === 'string'\n}\n\nconst PHP_WHITESPACE = String.raw`[ \\t\\n\\r\\v\\f]`\nconst PHP_NUMBER_GRAMMAR = String.raw`(?:\\d+\\.\\d*|\\.\\d+|\\d+)(?:[eE][+-]?\\d+)?`\nconst PHP_NUMERIC_STRING = new RegExp(`^${PHP_WHITESPACE}*[+-]?${PHP_NUMBER_GRAMMAR}${PHP_WHITESPACE}*$`)\nconst PHP_LEADING_NUMBER = new RegExp(`^${PHP_WHITESPACE}*([+-]?${PHP_NUMBER_GRAMMAR})`)\n\nexport function isNumeric(value: unknown): boolean {\n if (typeof value === 'number') return true\n if (typeof value !== 'string') return false\n return PHP_NUMERIC_STRING.test(value)\n}\n\nexport function phpStrval(value: unknown): string {\n if (value === null || value === undefined) return ''\n if (typeof value === 'boolean') return value ? '1' : ''\n if (typeof value === 'number') return numberToPhpString(value)\n if (typeof value === 'string') return value\n return String(value)\n}\n\nfunction numberToPhpString(value: number): string {\n if (Number.isNaN(value)) return 'NAN'\n if (value === Number.POSITIVE_INFINITY) return 'INF'\n if (value === Number.NEGATIVE_INFINITY) return '-INF'\n if (Object.is(value, -0)) return '-0'\n if (Number.isInteger(value) && Math.abs(value) < INTEGER_FAST_PATH_LIMIT) return String(value)\n return formatG(value)\n}\n\nfunction formatG(value: number): string {\n const exponent = Number(value.toExponential(PRECISION - 1).split('e')[1])\n if (exponent < -4 || exponent >= PRECISION) {\n const mantissa = stripTrailingZeros(value.toExponential(PRECISION - 1).split('e')[0] as string)\n const normalized = mantissa.includes('.') ? mantissa : `${mantissa}.0`\n return `${normalized}E${exponent < 0 ? '-' : '+'}${Math.abs(exponent)}`\n }\n return stripTrailingZeros(value.toFixed(Math.max(0, PRECISION - 1 - exponent)))\n}\n\nfunction stripTrailingZeros(text: string): string {\n if (!text.includes('.')) return text\n return text.replace(/\\.?0+$/, '')\n}\n\nexport function phpRound(value: number): number {\n return value >= 0 ? Math.floor(value + 0.5) : Math.ceil(value - 0.5)\n}\n\nfunction clampToSafeInt(value: number): number {\n if (!Number.isFinite(value)) return 0\n const truncated = Math.trunc(value)\n if (truncated > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER\n if (truncated < Number.MIN_SAFE_INTEGER) return Number.MIN_SAFE_INTEGER\n if (truncated === 0) return 0\n return truncated\n}\n\nexport function phpInt(value: unknown): number {\n if (value === null || value === undefined) return 0\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value === 'number') return clampToSafeInt(value)\n if (typeof value === 'string') return clampToSafeInt(leadingNumber(value))\n return 0\n}\n\nfunction leadingNumber(text: string): number {\n const match = PHP_LEADING_NUMBER.exec(text)\n return match === null ? 0 : Number(match[1] as string)\n}\n\nexport function phpJsonEncode(data: unknown, options?: { escapeSlashes?: boolean }): string {\n const encoded = JSON.stringify(data, (_key, value: unknown) => {\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new TypeError('Value is not JSON encodable')\n }\n return value\n })\n if (encoded === undefined) throw new TypeError('Value is not JSON encodable')\n return options?.escapeSlashes === true ? encoded.replaceAll('/', '\\\\/') : encoded\n}\n","/** A single outbound HTTP request built by the SDK. */\nexport interface ApiRequest {\n readonly method: 'GET' | 'POST'\n readonly url: string\n readonly headers: Readonly<Record<string, string>>\n readonly body: string | null\n readonly signal?: AbortSignal\n}\n\n/** A raw HTTP response handed back to the SDK. */\nexport class ApiResponse {\n readonly status: number\n readonly headers: Readonly<Record<string, string>>\n readonly body: string\n\n constructor(status: number, headers: Readonly<Record<string, string>>, body: string) {\n this.status = status\n this.headers = Object.fromEntries(\n Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),\n )\n this.body = body\n }\n\n /**\n * Retrieve the response header value by name, performing a case-insensitive lookup.\n * Returns `null` if the header was not present in the response.\n */\n getHeader(name: string): string | null {\n return this.headers[name.toLowerCase()] ?? null\n }\n\n /**\n * Attempt to decode the response body as JSON, returning the parsed value if it is a\n * plain object or array, or `null` if the body is not valid JSON or the parsed value\n * is a primitive (string, number, boolean, null).\n */\n decodeJson(): unknown {\n let decoded: unknown\n try {\n decoded = JSON.parse(this.body)\n } catch {\n return null\n }\n return typeof decoded === 'object' && decoded !== null ? decoded : null\n }\n}\n\n/**\n * Transport contract. Replace the default implementation to add proxying,\n * retries or request recording in tests.\n *\n * Critical invariant: the `request()` method must resolve to an `ApiResponse` for\n * every response the server actually sent, including 4xx and 5xx status codes.\n * It must reject with an error only when no response was obtained at all—that is,\n * for a genuine transport failure such as a connection reset, timeout, or abort.\n *\n * If your implementation rejects on 4xx or 5xx responses, the SDK will be unable\n * to map the status code to its typed error classes, and the SDK's error handling\n * will break silently.\n */\nexport interface HttpClient {\n /**\n * Execute an HTTP request and return the server's response. Must resolve with\n * an `ApiResponse` for every response, and reject only on transport failure.\n */\n request(request: ApiRequest): Promise<ApiResponse>\n}\n"]}