@isroilov_an/paylov 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,458 @@
1
+ import { A as readConfig, D as createCardsResource, F as createHttpClient, G as asTiyin, H as asJsonObject, J as fieldOf, K as asUnixDateTime, M as readSurfaceTransport, O as everyLiteral, P as TokenManager, Q as sumToTiyin, R as ClientLifecycle, U as asNonEmptyString, V as DecodeFailure, W as asRecord, X as readFields, Y as isRecord, Z as formatSum, _ as createHoldsResource, a as minorUnitsOf, at as PaylovProtocolError, b as createGatewayResource, c as createTransactionsResource, ct as isPaylovApiError, d as createSubMerchantsResource, h as createPaymentsResource, i as decodeCheckoutAmount, it as PaylovInputError, j as readParams, k as readCallSignal, lt as isPaylovError, n as PaylovOnboarding, nt as PaylovClientClosedError, o as readCheckoutAmount, ot as configError, p as createSplitsResource, q as asUuid, r as CHECKOUT_CURRENCIES, rt as PaylovConnectionError, st as invalidInput, tt as PaylovApiError, ut as isPaylovOutcomeUnknown, w as createFiscalizationResource } from "./client-DOu4B-bL.js";
2
+ import { hash, timingSafeEqual } from "node:crypto";
3
+ // src/client.ts
4
+ /**
5
+ * Server-side client for the Paylov payment gateway.
6
+ *
7
+ * Create one long-lived instance per merchant credential set per process and share it across
8
+ * requests. It keeps the OAuth2 token pair in memory and refreshes it transparently; tokens are
9
+ * not coordinated across processes.
10
+ *
11
+ * @example
12
+ * import { PaylovClient } from '@isroilov_an/paylov';
13
+ *
14
+ * const paylov = new PaylovClient({
15
+ * baseUrl: 'https://dev.gw.paylov.uz',
16
+ * consumerKey: paylovConsumerKey,
17
+ * consumerSecret: paylovConsumerSecret,
18
+ * username: paylovUsername,
19
+ * password: paylovPassword,
20
+ * });
21
+ * // ... on shutdown:
22
+ * await paylov.close();
23
+ *
24
+ * @throws {@link PaylovInputError} `sdk_config_error` for malformed configuration.
25
+ */
26
+ var PaylovClient = class {
27
+ /**
28
+ * Gateway liveness and the bank list. See docs/usage/setup.md.
29
+ * @example await paylov.gateway.getStatus({ signal: AbortSignal.timeout(5_000) });
30
+ */
31
+ gateway;
32
+ /**
33
+ * Card Bind links, PAN binding, saved cards and the phone check. Moves no money.
34
+ * See docs/usage/cards.md.
35
+ * @example const cards = await paylov.cards.list({ userId: 'user-42' });
36
+ */
37
+ cards;
38
+ /**
39
+ * Receipt payments with a saved card, one-off PAN payments and refunds. See
40
+ * docs/usage/payments.md.
41
+ * @example await paylov.payments.pay({ transactionId, cardId, userId: 'user-42' });
42
+ */
43
+ payments;
44
+ /**
45
+ * Transaction lookups, paid-transaction listings and RRNs. See docs/usage/transactions.md.
46
+ * @example const transaction = await paylov.transactions.get({ transactionId });
47
+ */
48
+ transactions;
49
+ /**
50
+ * Two-phase card holds: create, capture once, release. See docs/usage/holds.md.
51
+ * @example await paylov.holds.release({ transactionId: holdTransactionId });
52
+ */
53
+ holds;
54
+ /**
55
+ * Splits of a paid transaction between recipients. See docs/usage/splits.md.
56
+ * @example const shares = await paylov.splits.get({ transactionId });
57
+ */
58
+ splits;
59
+ /**
60
+ * OFD fiscal receipts and activity-type checks. See docs/usage/fiscalization.md.
61
+ * @example const receipt = await paylov.fiscalization.registerReceipt({ transactionId, items });
62
+ */
63
+ fiscalization;
64
+ /**
65
+ * Sub-merchant registration for splits. See docs/usage/splits.md.
66
+ * @example const { subMerchantId } = await paylov.subMerchants.create(subMerchantParams);
67
+ */
68
+ subMerchants;
69
+ #auth;
70
+ constructor(config) {
71
+ const params = readConfig(config, "PaylovClient config");
72
+ const transport = readSurfaceTransport(params);
73
+ const lifecycle = new ClientLifecycle();
74
+ this.#auth = new TokenManager({
75
+ http: createHttpClient(transport),
76
+ lifecycle,
77
+ consumerKey: params.string("consumerKey"),
78
+ consumerSecret: params.string("consumerSecret"),
79
+ username: params.string("username"),
80
+ password: params.string("password")
81
+ });
82
+ const http = createHttpClient({
83
+ ...transport,
84
+ lifecycle,
85
+ auth: this.#auth
86
+ });
87
+ const anonymousHttp = createHttpClient({
88
+ ...transport,
89
+ lifecycle
90
+ });
91
+ this.gateway = createGatewayResource(http, anonymousHttp);
92
+ this.cards = createCardsResource(http);
93
+ this.payments = createPaymentsResource(http);
94
+ this.transactions = createTransactionsResource(http);
95
+ this.holds = createHoldsResource(http);
96
+ this.splits = createSplitsResource(http);
97
+ this.fiscalization = createFiscalizationResource(http);
98
+ this.subMerchants = createSubMerchantsResource(http);
99
+ }
100
+ /**
101
+ * Closes the client, waits for a token grant already under way, then revokes the access token
102
+ * (`POST /merchant/oauth2/revoke/`, sent without `Authorization`). The SDK assumes the revoked
103
+ * token stops authorizing at once on production; on the development gateway it keeps working.
104
+ * Every later call throws `PaylovClientClosedError` `sdk_client_closed`. A request still in
105
+ * flight may also fail with it once the revocation lands; Paylov rejected it before running it,
106
+ * so it had no effect. Settle requests before closing to keep their results. Concurrent calls
107
+ * share one revocation. Resolves once the client is closed locally even when the revocation fails or
108
+ * `signal` abandons the wait: the revoke attempt's `logger` events report its outcome, metadata
109
+ * only.
110
+ *
111
+ * @throws {@link PaylovInputError} `sdk_invalid_input` for options without an `AbortSignal`.
112
+ *
113
+ * @example
114
+ * process.once('SIGTERM', () => {
115
+ * void paylov.close({ signal: AbortSignal.timeout(5_000) });
116
+ * });
117
+ */
118
+ async close(options) {
119
+ await this.#auth.close(readCallSignal(options, "client.close"));
120
+ }
121
+ };
122
+ // src/checkout/link.ts
123
+ /** Pure hosted-checkout link generation. */
124
+ /** Paylov's hosted-checkout host. The page exists on production only. */
125
+ const CHECKOUT_BASE_URL = "https://my.paylov.uz/checkout/create/";
126
+ /**
127
+ * Characters the checkout page can carry in an account key or value. The page splits the
128
+ * decoded query on `&` and `=` and never percent-decodes, so a character that the form encoding
129
+ * escapes (here, or in the vendor's Python reference) reaches `transaction.check` in a different
130
+ * form than the merchant sent, and a raw `=` would truncate the value.
131
+ */
132
+ const ACCOUNT_TOKEN = /^[A-Za-z0-9._-]+$/;
133
+ /**
134
+ * Builds a hosted-checkout URL the customer opens in a browser. Pure: Paylov creates the check
135
+ * only when the page loads, so an unknown merchant or an out-of-range amount surfaces there.
136
+ * Moves no money; the customer pays on Paylov's page.
137
+ *
138
+ * The link is **not signed**: anyone who sees it can alter the amount, the currency or the
139
+ * account. Your `transaction.check` handler must re-validate all three against your own order
140
+ * record. The return redirect carries no outcome; rely on `transaction.perform`.
141
+ *
142
+ * @example
143
+ * const url = createCheckoutUrl({
144
+ * merchantId: paylovMerchantId,
145
+ * amount: { currency: 860, amountTiyin: 50_000 }, // 500.00 SUM
146
+ * account: { order_id: 'A-1001' },
147
+ * returnUrl: 'https://shop.example/checkout/return',
148
+ * });
149
+ *
150
+ * @throws {@link PaylovInputError} `sdk_invalid_amount` for the amount, `sdk_invalid_input` for
151
+ * any other field. Every failure is local; messages name the field, never a value.
152
+ */
153
+ function createCheckoutUrl(params) {
154
+ const method = "createCheckoutUrl";
155
+ const input = readParams(params, method);
156
+ const merchantId = input.string("merchantId");
157
+ const amount = readCheckoutAmount(input, "amount");
158
+ const account = input.stringRecord("account", ACCOUNT_TOKEN);
159
+ if (Object.hasOwn(account, "__proto__")) throw invalidInput(`${method}: account must not have a __proto__ key`, "account", "format");
160
+ const returnUrl = input.url("returnUrl");
161
+ const convertTo = input.optionalLiteral("convertTo", CHECKOUT_CURRENCIES);
162
+ const query = new URLSearchParams([
163
+ ["merchant_id", merchantId],
164
+ ["amount", String(minorUnitsOf(amount))],
165
+ ["return_url", returnUrl],
166
+ ...Object.entries(account).map(([key, value]) => [`account.${key}`, value]),
167
+ ["amount_in_tiyin", "True"],
168
+ ["currency_id", String(amount.currency)],
169
+ ...convertTo === void 0 ? [] : [["convert_to", String(convertTo)]]
170
+ ]).toString();
171
+ return `${CHECKOUT_BASE_URL}${Buffer.from(query, "utf8").toString("base64")}`;
172
+ }
173
+ // src/webhooks/decoders.ts
174
+ /** Decoding of authenticated webhook bodies; a decode failure is an outcome, never a throw. */
175
+ function invalid(reason) {
176
+ return {
177
+ kind: "invalid",
178
+ reason
179
+ };
180
+ }
181
+ function isCallbackId(value) {
182
+ return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
183
+ }
184
+ function parseJsonBytes(bytes) {
185
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
186
+ }
187
+ /** A parsed JSON object or array, as a body parser builds it; never a stream or class instance. */
188
+ function isParsedContainer(value) {
189
+ const prototype = Object.getPrototypeOf(value);
190
+ return prototype === Object.prototype || prototype === Array.prototype || prototype === null;
191
+ }
192
+ /** Throws on anything that is not JSON, including values `JSON.stringify` maps to `undefined`. */
193
+ function parseJsonBody(body) {
194
+ if (typeof body === "string") return JSON.parse(body);
195
+ if (body instanceof Uint8Array) return parseJsonBytes(body);
196
+ if (body instanceof ArrayBuffer) return parseJsonBytes(new Uint8Array(body));
197
+ if (typeof body === "object" && body !== null && !isParsedContainer(body)) throw new TypeError("unreadable webhook body");
198
+ return JSON.parse(JSON.stringify(body));
199
+ }
200
+ const decodeParamsAmount = (value, path) => {
201
+ const params = asRecord(value, path);
202
+ const amount = decodeCheckoutAmount(params["amount_tiyin"], params["currency"]);
203
+ if (amount === void 0) throw new DecodeFailure(path);
204
+ return amount;
205
+ };
206
+ function decodeCheckOrPerform(method, id, value) {
207
+ const params = readFields(value, "params");
208
+ const account = params("account", asJsonObject);
209
+ const amount = decodeParamsAmount(value, "params");
210
+ if (method === "transaction.check") return {
211
+ kind: method,
212
+ id,
213
+ account,
214
+ amount
215
+ };
216
+ return {
217
+ kind: method,
218
+ id,
219
+ transactionId: params("transaction_id", asUuid),
220
+ account,
221
+ amount
222
+ };
223
+ }
224
+ function decodeCancel(value) {
225
+ const params = readFields(value, "params");
226
+ return {
227
+ kind: "transaction.cancel",
228
+ transactionId: params("transaction_id", asUuid),
229
+ account: params("account", asJsonObject),
230
+ amountTiyin: params("amount_in_tiyin", asTiyin),
231
+ cancelledAt: params("cancel_time", asUnixDateTime)
232
+ };
233
+ }
234
+ function decodeDeposit(value) {
235
+ const params = readFields(value, "params");
236
+ return {
237
+ kind: "merchant.deposit",
238
+ depositId: params("id", asUuid),
239
+ merchantId: params("merchant", asNonEmptyString),
240
+ source: params("type", asNonEmptyString),
241
+ amountTiyin: params("amount_in_tiyin", asTiyin),
242
+ createdAt: params("create_time", asUnixDateTime)
243
+ };
244
+ }
245
+ const JSON_RPC_METHODS = [
246
+ "transaction.check",
247
+ "transaction.perform",
248
+ "transaction.cancel",
249
+ "merchant.deposit"
250
+ ];
251
+ function decodeJsonRpc(envelope) {
252
+ if (envelope["jsonrpc"] !== "2.0") return invalid("invalid_request");
253
+ const method = JSON_RPC_METHODS.find((name) => name === envelope["method"]);
254
+ if (method === void 0) return invalid("unknown_method");
255
+ const params = envelope["params"];
256
+ if (method === "transaction.cancel") return decodeCancel(params);
257
+ if (method === "merchant.deposit") return decodeDeposit(params);
258
+ if (!isRecord(params)) return invalid("invalid_params");
259
+ const id = envelope["id"];
260
+ if (!isCallbackId(id)) return invalid("invalid_request");
261
+ return decodeCheckOrPerform(method, id, params);
262
+ }
263
+ function decodeCardBind(envelope) {
264
+ const field = readFields(envelope, "body");
265
+ return {
266
+ kind: "card.bind",
267
+ token: field("token", asNonEmptyString),
268
+ userId: field("userId", asNonEmptyString),
269
+ status: field("status", asNonEmptyString),
270
+ cardId: field("card", fieldOf("cardId", asUuid))
271
+ };
272
+ }
273
+ function decodeWebhook(body) {
274
+ let envelope;
275
+ try {
276
+ envelope = parseJsonBody(body);
277
+ } catch {
278
+ return invalid("malformed_body");
279
+ }
280
+ if (!isRecord(envelope)) return invalid("invalid_request");
281
+ try {
282
+ if ("jsonrpc" in envelope) return decodeJsonRpc(envelope);
283
+ if ("token" in envelope) return decodeCardBind(envelope);
284
+ } catch (error) {
285
+ if (error instanceof DecodeFailure) return invalid("invalid_params");
286
+ throw error;
287
+ }
288
+ return invalid("invalid_request");
289
+ }
290
+ // src/webhooks/receiver.ts
291
+ /** Inbound Paylov webhook authentication. */
292
+ function sha256(value) {
293
+ return hash("sha256", value, "buffer");
294
+ }
295
+ /** The single Authorization header value; a repeated header is never a single value. */
296
+ function readAuthorization(headers) {
297
+ if (headers instanceof Headers) return headers.get("authorization");
298
+ if (!isRecord(headers)) return void 0;
299
+ const key = Object.keys(headers).find((name) => name.toLowerCase() === "authorization");
300
+ const value = key === void 0 ? void 0 : headers[key];
301
+ return Array.isArray(value) && value.length === 1 ? value[0] : value;
302
+ }
303
+ function decodeBasicCredentials(header) {
304
+ if (typeof header !== "string") return void 0;
305
+ const token = /^Basic[\t ]+([A-Za-z0-9+/]+={0,2})$/i.exec(header)?.[1];
306
+ if (token === void 0 || token.length % 4 !== 0) return void 0;
307
+ let decoded;
308
+ try {
309
+ decoded = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(token, "base64"));
310
+ } catch {
311
+ return;
312
+ }
313
+ const separator = decoded.indexOf(":");
314
+ if (separator < 0) return void 0;
315
+ return [decoded.slice(0, separator), decoded.slice(separator + 1)];
316
+ }
317
+ /**
318
+ * Authenticates and decodes Paylov webhooks: checkout `transaction.check` and
319
+ * `transaction.perform`, the `transaction.cancel` and `merchant.deposit` notifications, and the
320
+ * Card Bind notification. Moves no money and keeps no state.
321
+ *
322
+ * `receive` never throws for anything a request carries. It checks `POST` and HTTP Basic
323
+ * credentials in constant time, then returns a decoded event or `{ kind: 'invalid', reason }`.
324
+ * The caller owns everything after:
325
+ * - answer check and perform with HTTP 200 and `createWebhookResponse(event, decision)`;
326
+ * - acknowledge `transaction.cancel`, `merchant.deposit` and `card.bind` with any 2xx once
327
+ * handled;
328
+ * - deduplicate: `transaction.perform` and `transaction.cancel` on `transactionId`,
329
+ * `merchant.deposit` on `depositId`, `card.bind` on `token`. Paylov retries cancel and deposit
330
+ * up to 3 times at 60 s intervals. It documents no retry of check and perform, and the SDK
331
+ * assumes none and that only an `accept` answer to perform completes the payment;
332
+ * - choose the HTTP response for invalid input; Paylov documents none.
333
+ *
334
+ * @example
335
+ * const receiver = new PaylovWebhookReceiver({
336
+ * login: webhookLoginFromSecretManager,
337
+ * password: webhookPasswordFromSecretManager,
338
+ * });
339
+ * const event = receiver.receive({ method: req.method, headers: req.headers, body: rawBody });
340
+ * switch (event.kind) {
341
+ * case 'transaction.check':
342
+ * return reply(200, createWebhookResponse(event, await decideCheck(event)));
343
+ * case 'merchant.deposit':
344
+ * await recordDepositOnce(event.depositId, event.amountTiyin);
345
+ * return reply(200);
346
+ * case 'invalid':
347
+ * return reply(event.reason === 'unauthorized' ? 401 : 400);
348
+ * }
349
+ *
350
+ * @throws {@link PaylovInputError} `sdk_config_error` for a missing login or password, or a login
351
+ * containing a colon.
352
+ */
353
+ var PaylovWebhookReceiver = class {
354
+ #loginHash;
355
+ #passwordHash;
356
+ constructor(config) {
357
+ const surface = "PaylovWebhookReceiver config";
358
+ const params = readConfig(config, surface);
359
+ const login = params.string("login");
360
+ if (login.includes(":")) throw configError(`${surface}: login must not contain a colon`, "login", "format");
361
+ this.#loginHash = sha256(login);
362
+ this.#passwordHash = sha256(params.string("password"));
363
+ }
364
+ /**
365
+ * Authenticates and decodes one inbound webhook. Never throws for anything the request
366
+ * carries. Pass the body already read, as text, bytes or parsed JSON: an unread stream such as
367
+ * a Fetch `Request`'s `body` is answered `malformed_body`.
368
+ *
369
+ * @example
370
+ * const event = receiver.receive({
371
+ * method: request.method,
372
+ * headers: request.headers,
373
+ * body: new Uint8Array(await request.arrayBuffer()),
374
+ * });
375
+ * if (event.kind === 'transaction.cancel') await markCancelledOnce(event.transactionId);
376
+ */
377
+ receive(input) {
378
+ if (!isRecord(input)) return invalid("invalid_request");
379
+ if (input.method !== "POST") return invalid("unsupported_http_method");
380
+ if (!this.#isAuthorized(input.headers)) return invalid("unauthorized");
381
+ return decodeWebhook(input.body);
382
+ }
383
+ #isAuthorized(headers) {
384
+ const credentials = decodeBasicCredentials(readAuthorization(headers));
385
+ if (credentials === void 0) return false;
386
+ const loginMatches = timingSafeEqual(sha256(credentials[0]), this.#loginHash);
387
+ const passwordMatches = timingSafeEqual(sha256(credentials[1]), this.#passwordHash);
388
+ return loginMatches && passwordMatches;
389
+ }
390
+ };
391
+ // src/webhooks/responses.ts
392
+ /** Answers to `transaction.check` and `transaction.perform`. */
393
+ const DECISIONS = everyLiteral()([
394
+ "accept",
395
+ "maintenance",
396
+ "invalid_amount",
397
+ "order_not_found"
398
+ ]);
399
+ const RESULTS = {
400
+ accept: {
401
+ status: "0",
402
+ statusText: "OK"
403
+ },
404
+ maintenance: {
405
+ status: "3",
406
+ statusText: "Maintenance"
407
+ },
408
+ invalid_amount: {
409
+ status: "5",
410
+ statusText: "Invalid amount"
411
+ },
412
+ order_not_found: {
413
+ status: "303",
414
+ statusText: "Order not found"
415
+ }
416
+ };
417
+ const METHOD = "createWebhookResponse";
418
+ /**
419
+ * Builds the documented JSON-RPC answer to a `transaction.check` or `transaction.perform`
420
+ * event, with the status {@link WebhookDecision} maps `decision` to. Send it as the JSON body of
421
+ * an HTTP 200. Moves no money; for perform, answer `accept` only after the payment is applied to
422
+ * the order.
423
+ *
424
+ * @throws {@link PaylovInputError} `sdk_invalid_input` for an event that is not a check or
425
+ * perform event with a JSON-RPC id, or an unknown decision or a blank custom text.
426
+ *
427
+ * @example
428
+ * const order = await orders.find(event.account);
429
+ * const decision = order === undefined ? 'order_not_found' : 'accept';
430
+ * reply(200, createWebhookResponse(event, decision));
431
+ */
432
+ function createWebhookResponse(event, decision) {
433
+ const input = readParams({
434
+ event,
435
+ decision
436
+ }, METHOD);
437
+ return {
438
+ jsonrpc: "2.0",
439
+ id: input.object("event", readCallbackId),
440
+ result: resultOf(input)
441
+ };
442
+ }
443
+ function readCallbackId(event) {
444
+ event.literal("kind", ["transaction.check", "transaction.perform"]);
445
+ const id = event.raw("id");
446
+ if (!isCallbackId(id)) throw invalidInput(`${METHOD}: event.id must be a JSON-RPC id`, "event.id", "type");
447
+ return id;
448
+ }
449
+ function resultOf(input) {
450
+ if (typeof input.raw("decision") === "object") return {
451
+ status: "+1",
452
+ statusText: input.object("decision", (custom) => custom.string("custom"))
453
+ };
454
+ return { ...RESULTS[input.literal("decision", DECISIONS)] };
455
+ }
456
+ export { PaylovApiError, PaylovClient, PaylovClientClosedError, PaylovConnectionError, PaylovInputError, PaylovOnboarding, PaylovProtocolError, PaylovWebhookReceiver, createCheckoutUrl, createWebhookResponse, formatSum, isPaylovApiError, isPaylovError, isPaylovOutcomeUnknown, sumToTiyin };
457
+
458
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/client.ts","../src/checkout/link.ts","../src/webhooks/decoders.ts","../src/webhooks/receiver.ts","../src/webhooks/responses.ts"],"sourcesContent":["import { TokenManager } from './core/auth.js';\nimport { readSurfaceTransport } from './core/config.js';\nimport { createHttpClient } from './core/http.js';\nimport { ClientLifecycle } from './core/lifecycle.js';\nimport { readCallSignal, readConfig } from './core/params.js';\nimport type { PaylovCallOptions, PaylovTransportConfig } from './core/types.js';\nimport { createCardsResource, type CardsResource } from './cards/resource.js';\nimport {\n createFiscalizationResource,\n type FiscalizationResource,\n} from './fiscalization/resource.js';\nimport { createGatewayResource, type GatewayResource } from './gateway/resource.js';\nimport { createHoldsResource, type HoldsResource } from './holds/resource.js';\nimport { createPaymentsResource, type PaymentsResource } from './payments/resource.js';\nimport { createSplitsResource, type SplitsResource } from './splits/resource.js';\nimport { createSubMerchantsResource, type SubMerchantsResource } from './subMerchants/resource.js';\nimport { createTransactionsResource, type TransactionsResource } from './transactions/resource.js';\n\n/** Configuration for `PaylovClient`. Retries are not configurable: only GET requests retry. */\nexport interface PaylovClientConfig extends PaylovTransportConfig {\n /**\n * Gateway origin with no path: DEV `https://dev.gw.paylov.uz`, PROD `https://gw2.paylov.uz`.\n * Required, with no default. Must use `https`; a path, including `/merchant`, is rejected.\n */\n readonly baseUrl: string;\n readonly consumerKey: string;\n /** Secret. Never logged, never quoted in an error message. */\n readonly consumerSecret: string;\n readonly username: string;\n /** Secret. Never logged, never quoted in an error message. */\n readonly password: string;\n}\n\n/**\n * Server-side client for the Paylov payment gateway.\n *\n * Create one long-lived instance per merchant credential set per process and share it across\n * requests. It keeps the OAuth2 token pair in memory and refreshes it transparently; tokens are\n * not coordinated across processes.\n *\n * @example\n * import { PaylovClient } from '@isroilov_an/paylov';\n *\n * const paylov = new PaylovClient({\n * baseUrl: 'https://dev.gw.paylov.uz',\n * consumerKey: paylovConsumerKey,\n * consumerSecret: paylovConsumerSecret,\n * username: paylovUsername,\n * password: paylovPassword,\n * });\n * // ... on shutdown:\n * await paylov.close();\n *\n * @throws {@link PaylovInputError} `sdk_config_error` for malformed configuration.\n */\nexport class PaylovClient {\n /**\n * Gateway liveness and the bank list. See docs/usage/setup.md.\n * @example await paylov.gateway.getStatus({ signal: AbortSignal.timeout(5_000) });\n */\n readonly gateway: GatewayResource;\n /**\n * Card Bind links, PAN binding, saved cards and the phone check. Moves no money.\n * See docs/usage/cards.md.\n * @example const cards = await paylov.cards.list({ userId: 'user-42' });\n */\n readonly cards: CardsResource;\n /**\n * Receipt payments with a saved card, one-off PAN payments and refunds. See\n * docs/usage/payments.md.\n * @example await paylov.payments.pay({ transactionId, cardId, userId: 'user-42' });\n */\n readonly payments: PaymentsResource;\n /**\n * Transaction lookups, paid-transaction listings and RRNs. See docs/usage/transactions.md.\n * @example const transaction = await paylov.transactions.get({ transactionId });\n */\n readonly transactions: TransactionsResource;\n /**\n * Two-phase card holds: create, capture once, release. See docs/usage/holds.md.\n * @example await paylov.holds.release({ transactionId: holdTransactionId });\n */\n readonly holds: HoldsResource;\n /**\n * Splits of a paid transaction between recipients. See docs/usage/splits.md.\n * @example const shares = await paylov.splits.get({ transactionId });\n */\n readonly splits: SplitsResource;\n /**\n * OFD fiscal receipts and activity-type checks. See docs/usage/fiscalization.md.\n * @example const receipt = await paylov.fiscalization.registerReceipt({ transactionId, items });\n */\n readonly fiscalization: FiscalizationResource;\n /**\n * Sub-merchant registration for splits. See docs/usage/splits.md.\n * @example const { subMerchantId } = await paylov.subMerchants.create(subMerchantParams);\n */\n readonly subMerchants: SubMerchantsResource;\n\n readonly #auth: TokenManager;\n\n constructor(config: PaylovClientConfig) {\n const params = readConfig(config, 'PaylovClient config');\n const transport = readSurfaceTransport(params);\n const lifecycle = new ClientLifecycle();\n // The token transport has neither auth nor the lifecycle: grants never recurse into the\n // manager, and revocation still runs after the client is closed.\n this.#auth = new TokenManager({\n http: createHttpClient(transport),\n lifecycle,\n consumerKey: params.string('consumerKey'),\n consumerSecret: params.string('consumerSecret'),\n username: params.string('username'),\n password: params.string('password'),\n });\n const http = createHttpClient({ ...transport, lifecycle, auth: this.#auth });\n const anonymousHttp = createHttpClient({ ...transport, lifecycle });\n\n this.gateway = createGatewayResource(http, anonymousHttp);\n this.cards = createCardsResource(http);\n this.payments = createPaymentsResource(http);\n this.transactions = createTransactionsResource(http);\n this.holds = createHoldsResource(http);\n this.splits = createSplitsResource(http);\n this.fiscalization = createFiscalizationResource(http);\n this.subMerchants = createSubMerchantsResource(http);\n }\n\n /**\n * Closes the client, waits for a token grant already under way, then revokes the access token\n * (`POST /merchant/oauth2/revoke/`, sent without `Authorization`). The SDK assumes the revoked\n * token stops authorizing at once on production; on the development gateway it keeps working.\n * Every later call throws `PaylovClientClosedError` `sdk_client_closed`. A request still in\n * flight may also fail with it once the revocation lands; Paylov rejected it before running it,\n * so it had no effect. Settle requests before closing to keep their results. Concurrent calls\n * share one revocation. Resolves once the client is closed locally even when the revocation fails or\n * `signal` abandons the wait: the revoke attempt's `logger` events report its outcome, metadata\n * only.\n *\n * @throws {@link PaylovInputError} `sdk_invalid_input` for options without an `AbortSignal`.\n *\n * @example\n * process.once('SIGTERM', () => {\n * void paylov.close({ signal: AbortSignal.timeout(5_000) });\n * });\n */\n async close(options?: PaylovCallOptions): Promise<void> {\n await this.#auth.close(readCallSignal(options, 'client.close'));\n }\n}\n","/** Pure hosted-checkout link generation. */\n\nimport { invalidInput } from '../core/errors.js';\nimport { readParams } from '../core/params.js';\nimport {\n CHECKOUT_CURRENCIES,\n minorUnitsOf,\n readCheckoutAmount,\n type CheckoutAmount,\n type CheckoutCurrency,\n} from '../shared/checkoutAmount.js';\n\n/** Paylov's hosted-checkout host. The page exists on production only. */\nconst CHECKOUT_BASE_URL = 'https://my.paylov.uz/checkout/create/';\n\n/**\n * Characters the checkout page can carry in an account key or value. The page splits the\n * decoded query on `&` and `=` and never percent-decodes, so a character that the form encoding\n * escapes (here, or in the vendor's Python reference) reaches `transaction.check` in a different\n * form than the merchant sent, and a raw `=` would truncate the value.\n */\nconst ACCOUNT_TOKEN = /^[A-Za-z0-9._-]+$/;\n\n/** Parameters for {@link createCheckoutUrl}. */\nexport interface CreateCheckoutUrlParams {\n /** Public merchant id (UUID). */\n readonly merchantId: string;\n /** Amount in the minor unit of its currency, sent with `amount_in_tiyin=True`. */\n readonly amount: CheckoutAmount;\n /**\n * Merchant order fields, sent as `account.<key>=<value>`. Paylov documents them in the\n * `transaction.check` / `transaction.perform` callbacks, where the check handler matches its\n * order by them, but its test environment stores none of them for a checkout: keep your own\n * mapping from order to link too. Keys and values are limited to `A-Z a-z 0-9 . _ -`.\n */\n readonly account: Readonly<Record<string, string>>;\n /** Absolute `http(s)` URL the customer returns to. Paylov appends no payment outcome. */\n readonly returnUrl: string;\n /**\n * `convert_to`: the currency the page converts the amount into, at the Central Bank rate, when\n * the check is created. Each webhook states its own currency; the SDK expects the check and\n * perform webhooks in the converted currency and amount, which Paylov does not state outright.\n */\n readonly convertTo?: CheckoutCurrency;\n}\n\n/**\n * Builds a hosted-checkout URL the customer opens in a browser. Pure: Paylov creates the check\n * only when the page loads, so an unknown merchant or an out-of-range amount surfaces there.\n * Moves no money; the customer pays on Paylov's page.\n *\n * The link is **not signed**: anyone who sees it can alter the amount, the currency or the\n * account. Your `transaction.check` handler must re-validate all three against your own order\n * record. The return redirect carries no outcome; rely on `transaction.perform`.\n *\n * @example\n * const url = createCheckoutUrl({\n * merchantId: paylovMerchantId,\n * amount: { currency: 860, amountTiyin: 50_000 }, // 500.00 SUM\n * account: { order_id: 'A-1001' },\n * returnUrl: 'https://shop.example/checkout/return',\n * });\n *\n * @throws {@link PaylovInputError} `sdk_invalid_amount` for the amount, `sdk_invalid_input` for\n * any other field. Every failure is local; messages name the field, never a value.\n */\nexport function createCheckoutUrl(params: CreateCheckoutUrlParams): string {\n const method = 'createCheckoutUrl';\n const input = readParams(params, method);\n const merchantId = input.string('merchantId');\n const amount = readCheckoutAmount(input, 'amount');\n const account = input.stringRecord('account', ACCOUNT_TOKEN);\n // The page assigns `account[key] = value`; for `__proto__` that is a silent no-op.\n if (Object.hasOwn(account, '__proto__')) {\n throw invalidInput(`${method}: account must not have a __proto__ key`, 'account', 'format');\n }\n const returnUrl = input.url('returnUrl');\n const convertTo = input.optionalLiteral('convertTo', CHECKOUT_CURRENCIES);\n\n // Form-encoded like the vendor's Python `urlencode` reference, then standard padded base64:\n // the page decodes it with `atob`, which rejects base64url.\n const query = new URLSearchParams([\n ['merchant_id', merchantId],\n ['amount', String(minorUnitsOf(amount))],\n ['return_url', returnUrl],\n ...Object.entries(account).map(([key, value]): [string, string] => [`account.${key}`, value]),\n ['amount_in_tiyin', 'True'],\n ['currency_id', String(amount.currency)],\n ...(convertTo === undefined ? [] : [['convert_to', String(convertTo)]]),\n ]).toString();\n return `${CHECKOUT_BASE_URL}${Buffer.from(query, 'utf8').toString('base64')}`;\n}\n","/** Decoding of authenticated webhook bodies; a decode failure is an outcome, never a throw. */\n\nimport {\n asJsonObject,\n asNonEmptyString,\n asRecord,\n asTiyin,\n asUnixDateTime,\n asUuid,\n fieldOf,\n isRecord,\n DecodeFailure,\n readFields,\n type Decoder,\n} from '../core/decoding.js';\nimport { decodeCheckoutAmount, type CheckoutAmount } from '../shared/checkoutAmount.js';\nimport type {\n InvalidWebhook,\n InvalidWebhookReason,\n WebhookCallbackId,\n WebhookOutcome,\n} from './types.js';\n\nexport function invalid(reason: InvalidWebhookReason): InvalidWebhook {\n return { kind: 'invalid', reason };\n}\n\nexport function isCallbackId(value: unknown): value is WebhookCallbackId {\n return typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));\n}\n\nfunction parseJsonBytes(bytes: Uint8Array): unknown {\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n}\n\n/** A parsed JSON object or array, as a body parser builds it; never a stream or class instance. */\nfunction isParsedContainer(value: object): boolean {\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === Array.prototype || prototype === null;\n}\n\n/** Throws on anything that is not JSON, including values `JSON.stringify` maps to `undefined`. */\nfunction parseJsonBody(body: unknown): unknown {\n if (typeof body === 'string') return JSON.parse(body);\n if (body instanceof Uint8Array) return parseJsonBytes(body);\n if (body instanceof ArrayBuffer) return parseJsonBytes(new Uint8Array(body));\n // A stream, `Blob` or other object would re-serialize as `{}` and pass for a request.\n if (typeof body === 'object' && body !== null && !isParsedContainer(body)) {\n throw new TypeError('unreadable webhook body');\n }\n // A parsed value is re-serialized so decoding reads a plain snapshot.\n return JSON.parse(JSON.stringify(body));\n}\n\n// Check and perform carry `amount_tiyin`; cancel and deposit carry `amount_in_tiyin`. The\n// asymmetry is documented, and only the minor-unit field is read: no rounding rule is stated for\n// the whole-currency `amount`.\nconst decodeParamsAmount: Decoder<CheckoutAmount> = (value, path) => {\n const params = asRecord(value, path);\n const amount = decodeCheckoutAmount(params['amount_tiyin'], params['currency']);\n if (amount === undefined) throw new DecodeFailure(path);\n return amount;\n};\n\nfunction decodeCheckOrPerform(\n method: 'transaction.check' | 'transaction.perform',\n id: WebhookCallbackId,\n value: unknown,\n): WebhookOutcome {\n const params = readFields(value, 'params');\n const account = params('account', asJsonObject);\n const amount = decodeParamsAmount(value, 'params');\n if (method === 'transaction.check') return { kind: method, id, account, amount };\n return { kind: method, id, transactionId: params('transaction_id', asUuid), account, amount };\n}\n\nfunction decodeCancel(value: unknown): WebhookOutcome {\n const params = readFields(value, 'params');\n return {\n kind: 'transaction.cancel',\n transactionId: params('transaction_id', asUuid),\n account: params('account', asJsonObject),\n amountTiyin: params('amount_in_tiyin', asTiyin),\n cancelledAt: params('cancel_time', asUnixDateTime),\n };\n}\n\nfunction decodeDeposit(value: unknown): WebhookOutcome {\n const params = readFields(value, 'params');\n return {\n kind: 'merchant.deposit',\n depositId: params('id', asUuid),\n // Opaque: the docs example is the numeric string \"125\".\n merchantId: params('merchant', asNonEmptyString),\n source: params('type', asNonEmptyString),\n amountTiyin: params('amount_in_tiyin', asTiyin),\n createdAt: params('create_time', asUnixDateTime),\n };\n}\n\nconst JSON_RPC_METHODS = [\n 'transaction.check',\n 'transaction.perform',\n 'transaction.cancel',\n 'merchant.deposit',\n] as const;\n\nfunction decodeJsonRpc(envelope: Readonly<Record<string, unknown>>): WebhookOutcome {\n if (envelope['jsonrpc'] !== '2.0') return invalid('invalid_request');\n const method = JSON_RPC_METHODS.find((name) => name === envelope['method']);\n if (method === undefined) return invalid('unknown_method');\n const params = envelope['params'];\n if (method === 'transaction.cancel') return decodeCancel(params);\n if (method === 'merchant.deposit') return decodeDeposit(params);\n if (!isRecord(params)) return invalid('invalid_params');\n const id = envelope['id'];\n if (!isCallbackId(id)) return invalid('invalid_request');\n return decodeCheckOrPerform(method, id, params);\n}\n\n// The card itself is unauthenticated processor data; its id is enough to read it through the\n// authenticated cards API.\nfunction decodeCardBind(envelope: Readonly<Record<string, unknown>>): WebhookOutcome {\n const field = readFields(envelope, 'body');\n return {\n kind: 'card.bind',\n token: field('token', asNonEmptyString),\n userId: field('userId', asNonEmptyString),\n status: field('status', asNonEmptyString),\n cardId: field('card', fieldOf('cardId', asUuid)),\n };\n}\n\nexport function decodeWebhook(body: unknown): WebhookOutcome {\n let envelope: unknown;\n try {\n envelope = parseJsonBody(body);\n } catch {\n return invalid('malformed_body');\n }\n if (!isRecord(envelope)) return invalid('invalid_request');\n // Every field failure, nesting deeper than the JSON copy allows included, is `invalid_params`;\n // any other exception is an SDK bug and propagates.\n try {\n if ('jsonrpc' in envelope) return decodeJsonRpc(envelope);\n if ('token' in envelope) return decodeCardBind(envelope);\n } catch (error) {\n if (error instanceof DecodeFailure) return invalid('invalid_params');\n throw error;\n }\n return invalid('invalid_request');\n}\n","/** Inbound Paylov webhook authentication. */\n\nimport { hash, timingSafeEqual } from 'node:crypto';\n\nimport { configError } from '../core/errors.js';\nimport { isRecord } from '../core/decoding.js';\nimport { readConfig } from '../core/params.js';\nimport { decodeWebhook, invalid } from './decoders.js';\nimport type { PaylovWebhookReceiverConfig, WebhookInput, WebhookOutcome } from './types.js';\n\nfunction sha256(value: string): Buffer {\n return hash('sha256', value, 'buffer');\n}\n\n/** The single Authorization header value; a repeated header is never a single value. */\nfunction readAuthorization(headers: unknown): unknown {\n if (headers instanceof Headers) return headers.get('authorization');\n if (!isRecord(headers)) return undefined;\n const key = Object.keys(headers).find((name) => name.toLowerCase() === 'authorization');\n const value = key === undefined ? undefined : headers[key];\n return Array.isArray(value) && value.length === 1 ? value[0] : value;\n}\n\nfunction decodeBasicCredentials(header: unknown): readonly [string, string] | undefined {\n if (typeof header !== 'string') return undefined;\n const match = /^Basic[\\t ]+([A-Za-z0-9+/]+={0,2})$/i.exec(header);\n const token = match?.[1];\n if (token === undefined || token.length % 4 !== 0) return undefined;\n\n let decoded: string;\n try {\n decoded = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(token, 'base64'));\n } catch {\n return undefined;\n }\n\n const separator = decoded.indexOf(':');\n if (separator < 0) return undefined;\n return [decoded.slice(0, separator), decoded.slice(separator + 1)];\n}\n\n/**\n * Authenticates and decodes Paylov webhooks: checkout `transaction.check` and\n * `transaction.perform`, the `transaction.cancel` and `merchant.deposit` notifications, and the\n * Card Bind notification. Moves no money and keeps no state.\n *\n * `receive` never throws for anything a request carries. It checks `POST` and HTTP Basic\n * credentials in constant time, then returns a decoded event or `{ kind: 'invalid', reason }`.\n * The caller owns everything after:\n * - answer check and perform with HTTP 200 and `createWebhookResponse(event, decision)`;\n * - acknowledge `transaction.cancel`, `merchant.deposit` and `card.bind` with any 2xx once\n * handled;\n * - deduplicate: `transaction.perform` and `transaction.cancel` on `transactionId`,\n * `merchant.deposit` on `depositId`, `card.bind` on `token`. Paylov retries cancel and deposit\n * up to 3 times at 60 s intervals. It documents no retry of check and perform, and the SDK\n * assumes none and that only an `accept` answer to perform completes the payment;\n * - choose the HTTP response for invalid input; Paylov documents none.\n *\n * @example\n * const receiver = new PaylovWebhookReceiver({\n * login: webhookLoginFromSecretManager,\n * password: webhookPasswordFromSecretManager,\n * });\n * const event = receiver.receive({ method: req.method, headers: req.headers, body: rawBody });\n * switch (event.kind) {\n * case 'transaction.check':\n * return reply(200, createWebhookResponse(event, await decideCheck(event)));\n * case 'merchant.deposit':\n * await recordDepositOnce(event.depositId, event.amountTiyin);\n * return reply(200);\n * case 'invalid':\n * return reply(event.reason === 'unauthorized' ? 401 : 400);\n * }\n *\n * @throws {@link PaylovInputError} `sdk_config_error` for a missing login or password, or a login\n * containing a colon.\n */\nexport class PaylovWebhookReceiver {\n readonly #loginHash: Buffer;\n readonly #passwordHash: Buffer;\n\n constructor(config: PaylovWebhookReceiverConfig) {\n const surface = 'PaylovWebhookReceiver config';\n const params = readConfig(config, surface);\n const login = params.string('login');\n // RFC 7617 splits credentials at the first colon, so such a login could never authenticate.\n if (login.includes(':')) {\n throw configError(`${surface}: login must not contain a colon`, 'login', 'format');\n }\n this.#loginHash = sha256(login);\n this.#passwordHash = sha256(params.string('password'));\n }\n\n /**\n * Authenticates and decodes one inbound webhook. Never throws for anything the request\n * carries. Pass the body already read, as text, bytes or parsed JSON: an unread stream such as\n * a Fetch `Request`'s `body` is answered `malformed_body`.\n *\n * @example\n * const event = receiver.receive({\n * method: request.method,\n * headers: request.headers,\n * body: new Uint8Array(await request.arrayBuffer()),\n * });\n * if (event.kind === 'transaction.cancel') await markCancelledOnce(event.transactionId);\n */\n receive(input: WebhookInput): WebhookOutcome {\n if (!isRecord(input)) return invalid('invalid_request');\n if (input.method !== 'POST') return invalid('unsupported_http_method');\n if (!this.#isAuthorized(input.headers)) return invalid('unauthorized');\n return decodeWebhook(input.body);\n }\n\n #isAuthorized(headers: unknown): boolean {\n const credentials = decodeBasicCredentials(readAuthorization(headers));\n if (credentials === undefined) return false;\n // Compare both digests before combining, so a login mismatch costs the same time.\n const loginMatches = timingSafeEqual(sha256(credentials[0]), this.#loginHash);\n const passwordMatches = timingSafeEqual(sha256(credentials[1]), this.#passwordHash);\n return loginMatches && passwordMatches;\n }\n}\n","/** Answers to `transaction.check` and `transaction.perform`. */\n\nimport { invalidInput } from '../core/errors.js';\nimport { everyLiteral, readParams, type Params } from '../core/params.js';\nimport { isCallbackId } from './decoders.js';\nimport type {\n TransactionCheckEvent,\n TransactionPerformEvent,\n WebhookCallbackId,\n WebhookDecision,\n WebhookResponseBody,\n} from './types.js';\n\ntype WebhookResult = WebhookResponseBody['result'];\ntype DecisionWord = Exclude<WebhookDecision, object>;\n\nconst DECISIONS = everyLiteral<DecisionWord>()([\n 'accept',\n 'maintenance',\n 'invalid_amount',\n 'order_not_found',\n]);\n\nconst RESULTS: Readonly<Record<DecisionWord, WebhookResult>> = {\n accept: { status: '0', statusText: 'OK' },\n maintenance: { status: '3', statusText: 'Maintenance' },\n invalid_amount: { status: '5', statusText: 'Invalid amount' },\n order_not_found: { status: '303', statusText: 'Order not found' },\n};\n\nconst METHOD = 'createWebhookResponse';\n\n/**\n * Builds the documented JSON-RPC answer to a `transaction.check` or `transaction.perform`\n * event, with the status {@link WebhookDecision} maps `decision` to. Send it as the JSON body of\n * an HTTP 200. Moves no money; for perform, answer `accept` only after the payment is applied to\n * the order.\n *\n * @throws {@link PaylovInputError} `sdk_invalid_input` for an event that is not a check or\n * perform event with a JSON-RPC id, or an unknown decision or a blank custom text.\n *\n * @example\n * const order = await orders.find(event.account);\n * const decision = order === undefined ? 'order_not_found' : 'accept';\n * reply(200, createWebhookResponse(event, decision));\n */\nexport function createWebhookResponse(\n event: TransactionCheckEvent | TransactionPerformEvent,\n decision: WebhookDecision,\n): WebhookResponseBody {\n const input = readParams({ event, decision }, METHOD);\n const id = input.object('event', readCallbackId);\n return { jsonrpc: '2.0', id, result: resultOf(input) };\n}\n\nfunction readCallbackId(event: Params): WebhookCallbackId {\n event.literal('kind', ['transaction.check', 'transaction.perform']);\n const id = event.raw('id');\n if (!isCallbackId(id)) {\n throw invalidInput(`${METHOD}: event.id must be a JSON-RPC id`, 'event.id', 'type');\n }\n return id;\n}\n\nfunction resultOf(input: Params): WebhookResult {\n if (typeof input.raw('decision') === 'object') {\n return {\n status: '+1',\n statusText: input.object('decision', (custom) => custom.string('custom')),\n };\n }\n return { ...RESULTS[input.literal('decision', DECISIONS)] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,eAAb,MAA0B;;;;;CAKxB;;;;;;CAMA;;;;;;CAMA;;;;;CAKA;;;;;CAKA;;;;;CAKA;;;;;CAKA;;;;;CAKA;CAEA;CAEA,YAAY,QAA4B;EACtC,MAAM,SAAS,WAAW,QAAQ,qBAAqB;EACvD,MAAM,YAAY,qBAAqB,MAAM;EAC7C,MAAM,YAAY,IAAI,gBAAgB;EAGtC,KAAK,QAAQ,IAAI,aAAa;GAC5B,MAAM,iBAAiB,SAAS;GAChC;GACA,aAAa,OAAO,OAAO,aAAa;GACxC,gBAAgB,OAAO,OAAO,gBAAgB;GAC9C,UAAU,OAAO,OAAO,UAAU;GAClC,UAAU,OAAO,OAAO,UAAU;EACpC,CAAC;EACD,MAAM,OAAO,iBAAiB;GAAE,GAAG;GAAW;GAAW,MAAM,KAAK;EAAM,CAAC;EAC3E,MAAM,gBAAgB,iBAAiB;GAAE,GAAG;GAAW;EAAU,CAAC;EAElE,KAAK,UAAU,sBAAsB,MAAM,aAAa;EACxD,KAAK,QAAQ,oBAAoB,IAAI;EACrC,KAAK,WAAW,uBAAuB,IAAI;EAC3C,KAAK,eAAe,2BAA2B,IAAI;EACnD,KAAK,QAAQ,oBAAoB,IAAI;EACrC,KAAK,SAAS,qB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