@tungoai/sdk 0.0.0-stage → 0.2.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -0
  3. package/README.kk.md +327 -0
  4. package/README.md +346 -2
  5. package/README.ru.md +327 -0
  6. package/dist/cjs/chat.d.ts +85 -0
  7. package/dist/cjs/chat.js +151 -0
  8. package/dist/cjs/client.d.ts +116 -0
  9. package/dist/cjs/client.js +223 -0
  10. package/dist/cjs/core.d.ts +210 -0
  11. package/dist/cjs/core.js +605 -0
  12. package/dist/cjs/errors.d.ts +212 -0
  13. package/dist/cjs/errors.js +410 -0
  14. package/dist/cjs/generated/resources.d.ts +1059 -0
  15. package/dist/cjs/generated/resources.js +1064 -0
  16. package/dist/cjs/generated/types.d.ts +4927 -0
  17. package/dist/cjs/generated/types.js +11 -0
  18. package/dist/cjs/index.d.ts +12 -0
  19. package/dist/cjs/index.js +80 -0
  20. package/dist/cjs/json.d.ts +10 -0
  21. package/dist/cjs/json.js +120 -0
  22. package/dist/cjs/money.d.ts +32 -0
  23. package/dist/cjs/money.js +141 -0
  24. package/dist/cjs/package.json +1 -0
  25. package/dist/cjs/pagination.d.ts +47 -0
  26. package/dist/cjs/pagination.js +113 -0
  27. package/dist/cjs/streaming.d.ts +74 -0
  28. package/dist/cjs/streaming.js +253 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +6 -0
  31. package/dist/cjs/webhooks.d.ts +74 -0
  32. package/dist/cjs/webhooks.js +248 -0
  33. package/dist/esm/chat.d.ts +85 -0
  34. package/dist/esm/chat.js +143 -0
  35. package/dist/esm/client.d.ts +116 -0
  36. package/dist/esm/client.js +219 -0
  37. package/dist/esm/core.d.ts +210 -0
  38. package/dist/esm/core.js +589 -0
  39. package/dist/esm/errors.d.ts +212 -0
  40. package/dist/esm/errors.js +381 -0
  41. package/dist/esm/generated/resources.d.ts +1059 -0
  42. package/dist/esm/generated/resources.js +1048 -0
  43. package/dist/esm/generated/types.d.ts +4927 -0
  44. package/dist/esm/generated/types.js +10 -0
  45. package/dist/esm/index.d.ts +12 -0
  46. package/dist/esm/index.js +11 -0
  47. package/dist/esm/json.d.ts +10 -0
  48. package/dist/esm/json.js +116 -0
  49. package/dist/esm/money.d.ts +32 -0
  50. package/dist/esm/money.js +137 -0
  51. package/dist/esm/package.json +1 -0
  52. package/dist/esm/pagination.d.ts +47 -0
  53. package/dist/esm/pagination.js +107 -0
  54. package/dist/esm/streaming.d.ts +74 -0
  55. package/dist/esm/streaming.js +247 -0
  56. package/dist/esm/version.d.ts +2 -0
  57. package/dist/esm/version.js +3 -0
  58. package/dist/esm/webhooks.d.ts +74 -0
  59. package/dist/esm/webhooks.js +239 -0
  60. package/package.json +67 -4
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
3
+ //
4
+ // Models of the Tungo Platform API. Descriptions come from the contract as they are.
5
+ // Integers: a JSON integer beyond 2^53 is decoded to a bigint instead of being rounded, so an
6
+ // integer the contract does not bound to 32 bits is typed `number | bigint` (it is a `number`
7
+ // unless the value is outside the safe range); integers the contract bounds are `number`.
8
+ // Fields the contract types as floating-point `number` are typed `number`: the API does not put
9
+ // integers of that size into them. See the README, "Money". Unknown fields and unknown enum
10
+ // values of a newer API version are passed through unchanged.
11
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
1
+ export type * from './generated/types.js';
2
+ export * from './generated/resources.js';
3
+ export { Tungo, Tungo as TungoClient, type ChatInput, type WaitOptions } from './client.js';
4
+ export { APIClient, APIPromise, StreamPromise, DEFAULT_BASE_URL, DEFAULT_LONG_RUNNING_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_STREAM_IDLE_TIMEOUT, DEFAULT_TIMEOUT, type ClientOptions, type Fetch, type LogEvent, type RequestOptions, type RequestSpec, type WithResponse, } from './core.js';
5
+ export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, type APIErrorType, type APIFieldError, type RateLimit, type WebhookVerificationReason, } from './errors.js';
6
+ export { SSEDecoder, Stream, type ResponseInfo, type ServerSentEvent } from './streaming.js';
7
+ export { Page, PagePromise, type CursorPageBody } from './pagination.js';
8
+ export { ChatAccumulator, ChatStream, ChatStreamPromise, accumulateChatStream, chatTurnError, type ChatStreamCallbacks, type ChatStreamResult, } from './chat.js';
9
+ export { DEFAULT_WEBHOOK_TOLERANCE_SECONDS, TungoHooks, TungoWebhooks, signHookPayload, verifyHookSignature, verifyWebhook, type HeadersLike, type HookPayload, type SendHookOptions, type VerifyWebhookOptions, } from './webhooks.js';
10
+ export { TungoKazakhstan, TungoMoney, isValidBinIin } from './money.js';
11
+ export { parseJSON, stringifyJSON } from './json.js';
12
+ export { VERSION } from './version.js';
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.stringifyJSON = exports.parseJSON = exports.isValidBinIin = exports.TungoMoney = exports.TungoKazakhstan = exports.verifyWebhook = exports.verifyHookSignature = exports.signHookPayload = exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.chatTurnError = exports.accumulateChatStream = exports.ChatStreamPromise = exports.ChatStream = exports.ChatAccumulator = exports.PagePromise = exports.Page = exports.Stream = exports.SSEDecoder = exports.WebhookVerificationError = exports.ValidationError = exports.UnavailableError = exports.TungoError = exports.TimeoutError = exports.PermissionError = exports.PaymentRequiredError = exports.NotFoundError = exports.MoneyError = exports.LimitError = exports.InvalidRequestError = exports.InternalServerError = exports.GoneError = exports.DecodeError = exports.ConnectionError = exports.ConflictError = exports.ConfigError = exports.AuthenticationError = exports.AbortError = exports.APIError = exports.DEFAULT_TIMEOUT = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_BASE_URL = exports.StreamPromise = exports.APIPromise = exports.APIClient = exports.TungoClient = exports.Tungo = void 0;
18
+ exports.VERSION = void 0;
19
+ __exportStar(require("./generated/resources.js"), exports);
20
+ var client_js_1 = require("./client.js");
21
+ Object.defineProperty(exports, "Tungo", { enumerable: true, get: function () { return client_js_1.Tungo; } });
22
+ Object.defineProperty(exports, "TungoClient", { enumerable: true, get: function () { return client_js_1.Tungo; } });
23
+ var core_js_1 = require("./core.js");
24
+ Object.defineProperty(exports, "APIClient", { enumerable: true, get: function () { return core_js_1.APIClient; } });
25
+ Object.defineProperty(exports, "APIPromise", { enumerable: true, get: function () { return core_js_1.APIPromise; } });
26
+ Object.defineProperty(exports, "StreamPromise", { enumerable: true, get: function () { return core_js_1.StreamPromise; } });
27
+ Object.defineProperty(exports, "DEFAULT_BASE_URL", { enumerable: true, get: function () { return core_js_1.DEFAULT_BASE_URL; } });
28
+ Object.defineProperty(exports, "DEFAULT_LONG_RUNNING_TIMEOUT", { enumerable: true, get: function () { return core_js_1.DEFAULT_LONG_RUNNING_TIMEOUT; } });
29
+ Object.defineProperty(exports, "DEFAULT_MAX_RETRIES", { enumerable: true, get: function () { return core_js_1.DEFAULT_MAX_RETRIES; } });
30
+ Object.defineProperty(exports, "DEFAULT_STREAM_IDLE_TIMEOUT", { enumerable: true, get: function () { return core_js_1.DEFAULT_STREAM_IDLE_TIMEOUT; } });
31
+ Object.defineProperty(exports, "DEFAULT_TIMEOUT", { enumerable: true, get: function () { return core_js_1.DEFAULT_TIMEOUT; } });
32
+ var errors_js_1 = require("./errors.js");
33
+ Object.defineProperty(exports, "APIError", { enumerable: true, get: function () { return errors_js_1.APIError; } });
34
+ Object.defineProperty(exports, "AbortError", { enumerable: true, get: function () { return errors_js_1.AbortError; } });
35
+ Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
36
+ Object.defineProperty(exports, "ConfigError", { enumerable: true, get: function () { return errors_js_1.ConfigError; } });
37
+ Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
38
+ Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_js_1.ConnectionError; } });
39
+ Object.defineProperty(exports, "DecodeError", { enumerable: true, get: function () { return errors_js_1.DecodeError; } });
40
+ Object.defineProperty(exports, "GoneError", { enumerable: true, get: function () { return errors_js_1.GoneError; } });
41
+ Object.defineProperty(exports, "InternalServerError", { enumerable: true, get: function () { return errors_js_1.InternalServerError; } });
42
+ Object.defineProperty(exports, "InvalidRequestError", { enumerable: true, get: function () { return errors_js_1.InvalidRequestError; } });
43
+ Object.defineProperty(exports, "LimitError", { enumerable: true, get: function () { return errors_js_1.LimitError; } });
44
+ Object.defineProperty(exports, "MoneyError", { enumerable: true, get: function () { return errors_js_1.MoneyError; } });
45
+ Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
46
+ Object.defineProperty(exports, "PaymentRequiredError", { enumerable: true, get: function () { return errors_js_1.PaymentRequiredError; } });
47
+ Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
48
+ Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_js_1.TimeoutError; } });
49
+ Object.defineProperty(exports, "TungoError", { enumerable: true, get: function () { return errors_js_1.TungoError; } });
50
+ Object.defineProperty(exports, "UnavailableError", { enumerable: true, get: function () { return errors_js_1.UnavailableError; } });
51
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_js_1.ValidationError; } });
52
+ Object.defineProperty(exports, "WebhookVerificationError", { enumerable: true, get: function () { return errors_js_1.WebhookVerificationError; } });
53
+ var streaming_js_1 = require("./streaming.js");
54
+ Object.defineProperty(exports, "SSEDecoder", { enumerable: true, get: function () { return streaming_js_1.SSEDecoder; } });
55
+ Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return streaming_js_1.Stream; } });
56
+ var pagination_js_1 = require("./pagination.js");
57
+ Object.defineProperty(exports, "Page", { enumerable: true, get: function () { return pagination_js_1.Page; } });
58
+ Object.defineProperty(exports, "PagePromise", { enumerable: true, get: function () { return pagination_js_1.PagePromise; } });
59
+ var chat_js_1 = require("./chat.js");
60
+ Object.defineProperty(exports, "ChatAccumulator", { enumerable: true, get: function () { return chat_js_1.ChatAccumulator; } });
61
+ Object.defineProperty(exports, "ChatStream", { enumerable: true, get: function () { return chat_js_1.ChatStream; } });
62
+ Object.defineProperty(exports, "ChatStreamPromise", { enumerable: true, get: function () { return chat_js_1.ChatStreamPromise; } });
63
+ Object.defineProperty(exports, "accumulateChatStream", { enumerable: true, get: function () { return chat_js_1.accumulateChatStream; } });
64
+ Object.defineProperty(exports, "chatTurnError", { enumerable: true, get: function () { return chat_js_1.chatTurnError; } });
65
+ var webhooks_js_1 = require("./webhooks.js");
66
+ Object.defineProperty(exports, "DEFAULT_WEBHOOK_TOLERANCE_SECONDS", { enumerable: true, get: function () { return webhooks_js_1.DEFAULT_WEBHOOK_TOLERANCE_SECONDS; } });
67
+ Object.defineProperty(exports, "TungoHooks", { enumerable: true, get: function () { return webhooks_js_1.TungoHooks; } });
68
+ Object.defineProperty(exports, "TungoWebhooks", { enumerable: true, get: function () { return webhooks_js_1.TungoWebhooks; } });
69
+ Object.defineProperty(exports, "signHookPayload", { enumerable: true, get: function () { return webhooks_js_1.signHookPayload; } });
70
+ Object.defineProperty(exports, "verifyHookSignature", { enumerable: true, get: function () { return webhooks_js_1.verifyHookSignature; } });
71
+ Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_js_1.verifyWebhook; } });
72
+ var money_js_1 = require("./money.js");
73
+ Object.defineProperty(exports, "TungoKazakhstan", { enumerable: true, get: function () { return money_js_1.TungoKazakhstan; } });
74
+ Object.defineProperty(exports, "TungoMoney", { enumerable: true, get: function () { return money_js_1.TungoMoney; } });
75
+ Object.defineProperty(exports, "isValidBinIin", { enumerable: true, get: function () { return money_js_1.isValidBinIin; } });
76
+ var json_js_1 = require("./json.js");
77
+ Object.defineProperty(exports, "parseJSON", { enumerable: true, get: function () { return json_js_1.parseJSON; } });
78
+ Object.defineProperty(exports, "stringifyJSON", { enumerable: true, get: function () { return json_js_1.stringifyJSON; } });
79
+ var version_js_1 = require("./version.js");
80
+ Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_js_1.VERSION; } });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Parses JSON text. Integers outside the safe range (beyond 2^53) are returned as `bigint`
3
+ * instead of being rounded. Throws `SyntaxError` on malformed input.
4
+ */
5
+ export declare function parseJSON(text: string): unknown;
6
+ /**
7
+ * Serialises a value to JSON. `bigint` values are written as plain JSON numbers with every digit.
8
+ * NaN and Infinity (which JSON cannot express) and unserialisable values raise a ValidationError.
9
+ */
10
+ export declare function stringifyJSON(value: unknown): string;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseJSON = parseJSON;
4
+ exports.stringifyJSON = stringifyJSON;
5
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
6
+ const errors_js_1 = require("./errors.js");
7
+ // JSON numbers are IEEE doubles in JavaScript, so an integer beyond 2^53 would silently lose its
8
+ // last digits. The two helpers below keep 64-bit integers exact: such a value is decoded to a
9
+ // bigint (and a bigint is encoded as a plain JSON number). Parsing and serialising themselves are
10
+ // always done by the platform's JSON implementation.
11
+ const TAG = 'tungo-int64:';
12
+ function nonce() {
13
+ const bytes = new Uint8Array(8);
14
+ crypto.getRandomValues(bytes);
15
+ let out = '';
16
+ for (const b of bytes)
17
+ out += b.toString(16).padStart(2, '0');
18
+ return out;
19
+ }
20
+ function isDigit(code) {
21
+ return code >= 48 && code <= 57;
22
+ }
23
+ /** Wraps every integer literal that is not a safe integer into a tagged string. Strings are skipped. */
24
+ function protectBigIntegers(text, prefix) {
25
+ const n = text.length;
26
+ let out = '';
27
+ let last = 0;
28
+ let i = 0;
29
+ while (i < n) {
30
+ const c = text.charCodeAt(i);
31
+ if (c === 34) {
32
+ i++;
33
+ while (i < n) {
34
+ const d = text.charCodeAt(i);
35
+ if (d === 92) {
36
+ i += 2;
37
+ }
38
+ else if (d === 34) {
39
+ break;
40
+ }
41
+ else {
42
+ i++;
43
+ }
44
+ }
45
+ i++;
46
+ continue;
47
+ }
48
+ if (c === 45 || isDigit(c)) {
49
+ const start = i;
50
+ if (c === 45)
51
+ i++;
52
+ const digits = i;
53
+ while (i < n && isDigit(text.charCodeAt(i)))
54
+ i++;
55
+ const next = i < n ? text.charCodeAt(i) : 0;
56
+ if (next === 46 || next === 101 || next === 69) {
57
+ while (i < n) {
58
+ const d = text.charCodeAt(i);
59
+ if (isDigit(d) || d === 46 || d === 101 || d === 69 || d === 43 || d === 45)
60
+ i++;
61
+ else
62
+ break;
63
+ }
64
+ continue;
65
+ }
66
+ if (i - digits >= 16) {
67
+ const literal = text.slice(start, i);
68
+ if (!Number.isSafeInteger(Number(literal))) {
69
+ out += text.slice(last, start) + '"\\u0000' + prefix + literal + '"';
70
+ last = i;
71
+ }
72
+ }
73
+ continue;
74
+ }
75
+ i++;
76
+ }
77
+ return last === 0 ? text : out + text.slice(last);
78
+ }
79
+ /**
80
+ * Parses JSON text. Integers outside the safe range (beyond 2^53) are returned as `bigint`
81
+ * instead of being rounded. Throws `SyntaxError` on malformed input.
82
+ */
83
+ function parseJSON(text) {
84
+ if (!/[0-9]{16}/.test(text))
85
+ return JSON.parse(text);
86
+ const prefix = TAG + nonce() + ':';
87
+ const marker = '\u0000' + prefix;
88
+ return JSON.parse(protectBigIntegers(text, prefix), (_key, value) => typeof value === 'string' && value.startsWith(marker) ? BigInt(value.slice(marker.length)) : value);
89
+ }
90
+ /**
91
+ * Serialises a value to JSON. `bigint` values are written as plain JSON numbers with every digit.
92
+ * NaN and Infinity (which JSON cannot express) and unserialisable values raise a ValidationError.
93
+ */
94
+ function stringifyJSON(value) {
95
+ const prefix = TAG + nonce() + ':';
96
+ let big = false;
97
+ let text;
98
+ try {
99
+ text = JSON.stringify(value, (_key, v) => {
100
+ if (typeof v === 'bigint') {
101
+ big = true;
102
+ return '\u0000' + prefix + v.toString();
103
+ }
104
+ if (typeof v === 'number' && !Number.isFinite(v)) {
105
+ throw new errors_js_1.ValidationError('The request contains ' + String(v) + ', which JSON cannot express');
106
+ }
107
+ return v;
108
+ });
109
+ }
110
+ catch (cause) {
111
+ if (cause instanceof errors_js_1.ValidationError)
112
+ throw cause;
113
+ throw new errors_js_1.ValidationError('The request body cannot be serialised to JSON', { cause });
114
+ }
115
+ if (text === undefined)
116
+ throw new errors_js_1.ValidationError('The request body cannot be serialised to JSON');
117
+ if (!big)
118
+ return text;
119
+ return text.replace(new RegExp('"\\\\u0000' + prefix + '(-?[0-9]+)"', 'g'), '$1');
120
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Money helpers. The API expresses amounts in tiyn (1/100 of a tenge) as 64-bit integers.
3
+ * Conversions are exact: no binary floating-point arithmetic is involved.
4
+ */
5
+ export declare const TungoMoney: {
6
+ /**
7
+ * Converts tenge to tiyn, rounding half away from zero to two places ("1.005" gives 101).
8
+ * Accepts a decimal string (`-?digits[.digits]`) or a number; a number is converted through its
9
+ * shortest decimal representation, so 1.005 also gives 101. Throws a MoneyError on malformed
10
+ * input, NaN, Infinity, or when the result is not a safe integer (use {@link toTiynBigInt} for
11
+ * amounts beyond 2^53 tiyn).
12
+ */
13
+ readonly toTiyn: (tenge: string | number) => number;
14
+ /** Like {@link toTiyn}, for the whole 64-bit range. */
15
+ readonly toTiynBigInt: (tenge: string | number) => bigint;
16
+ /** Tiyn as an exact decimal string of tenge: 4500050 gives "45000.50". */
17
+ readonly toTengeString: (tiyn: number | bigint | string) => string;
18
+ /**
19
+ * Formats tiyn for display: 4500000 gives "45 000,00 ₸". Known currencies get a symbol
20
+ * (KZT, USD, EUR, RUB); any other code is printed upper-cased after the amount.
21
+ */
22
+ readonly formatTiyn: (tiyn: number | bigint | string, currency?: string) => string;
23
+ };
24
+ /**
25
+ * Checks a Kazakhstani BIN or IIN: exactly 12 ASCII digits with a correct check digit.
26
+ * The value is not trimmed.
27
+ */
28
+ export declare function isValidBinIin(value: string): boolean;
29
+ /** Helpers for Kazakhstani identifiers. */
30
+ export declare const TungoKazakhstan: {
31
+ readonly isValidBinIin: typeof isValidBinIin;
32
+ };
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TungoKazakhstan = exports.TungoMoney = void 0;
4
+ exports.isValidBinIin = isValidBinIin;
5
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
6
+ const errors_js_1 = require("./errors.js");
7
+ const DECIMAL = /^(-?)([0-9]+)(?:\.([0-9]+))?$/;
8
+ const INT64_MAX = 9223372036854775807n;
9
+ const INT64_MIN = -9223372036854775808n;
10
+ /** The shortest decimal text that round-trips to the same double, without an exponent. */
11
+ function plainDecimal(value) {
12
+ const text = String(value);
13
+ const match = /^(-?)([0-9]+)(?:\.([0-9]+))?e([+-][0-9]+)$/.exec(text);
14
+ if (match === null)
15
+ return text;
16
+ const sign = match[1] ?? '';
17
+ const whole = match[2] ?? '';
18
+ const fraction = match[3] ?? '';
19
+ const exponent = Number(match[4]);
20
+ const digits = whole + fraction;
21
+ const point = whole.length + exponent;
22
+ if (point <= 0)
23
+ return sign + '0.' + '0'.repeat(-point) + digits;
24
+ if (point >= digits.length)
25
+ return sign + digits + '0'.repeat(point - digits.length);
26
+ return sign + digits.slice(0, point) + '.' + digits.slice(point);
27
+ }
28
+ function parseTiyn(input) {
29
+ let text;
30
+ if (typeof input === 'number') {
31
+ if (!Number.isFinite(input))
32
+ throw new errors_js_1.MoneyError('Cannot convert ' + String(input) + ' to tiyn');
33
+ text = plainDecimal(input);
34
+ }
35
+ else if (typeof input === 'string') {
36
+ text = input;
37
+ }
38
+ else {
39
+ throw new errors_js_1.MoneyError('An amount must be a decimal string or a number');
40
+ }
41
+ const match = DECIMAL.exec(text);
42
+ if (match === null || text.endsWith('\n')) {
43
+ throw new errors_js_1.MoneyError('Not a decimal amount: ' + JSON.stringify(text.length > 40 ? text.slice(0, 40) + '...' : text));
44
+ }
45
+ const fraction = (match[3] ?? '') + '000';
46
+ let tiyn = BigInt((match[2] ?? '0') + fraction.slice(0, 2));
47
+ if (fraction.charCodeAt(2) >= 53)
48
+ tiyn += 1n;
49
+ if (match[1] === '-')
50
+ tiyn = -tiyn;
51
+ if (tiyn > INT64_MAX || tiyn < INT64_MIN)
52
+ throw new errors_js_1.MoneyError('The amount does not fit into 64 bits of tiyn');
53
+ return tiyn;
54
+ }
55
+ function integerTiyn(tiyn) {
56
+ let value;
57
+ if (typeof tiyn === 'bigint') {
58
+ value = tiyn;
59
+ }
60
+ else if (typeof tiyn === 'number') {
61
+ if (!Number.isSafeInteger(tiyn))
62
+ throw new errors_js_1.MoneyError('Tiyn must be an integer (pass a bigint beyond 2^53): ' + String(tiyn));
63
+ value = BigInt(tiyn);
64
+ }
65
+ else if (typeof tiyn === 'string' && /^-?[0-9]+$/.test(tiyn) && !tiyn.endsWith('\n')) {
66
+ value = BigInt(tiyn);
67
+ }
68
+ else {
69
+ throw new errors_js_1.MoneyError('Tiyn must be an integer');
70
+ }
71
+ if (value > INT64_MAX || value < INT64_MIN)
72
+ throw new errors_js_1.MoneyError('The amount does not fit into 64 bits of tiyn');
73
+ return value;
74
+ }
75
+ const SYMBOLS = { KZT: '₸', USD: '$', EUR: '€', RUB: '₽' };
76
+ /**
77
+ * Money helpers. The API expresses amounts in tiyn (1/100 of a tenge) as 64-bit integers.
78
+ * Conversions are exact: no binary floating-point arithmetic is involved.
79
+ */
80
+ exports.TungoMoney = {
81
+ /**
82
+ * Converts tenge to tiyn, rounding half away from zero to two places ("1.005" gives 101).
83
+ * Accepts a decimal string (`-?digits[.digits]`) or a number; a number is converted through its
84
+ * shortest decimal representation, so 1.005 also gives 101. Throws a MoneyError on malformed
85
+ * input, NaN, Infinity, or when the result is not a safe integer (use {@link toTiynBigInt} for
86
+ * amounts beyond 2^53 tiyn).
87
+ */
88
+ toTiyn(tenge) {
89
+ const tiyn = parseTiyn(tenge);
90
+ const value = Number(tiyn);
91
+ if (!Number.isSafeInteger(value)) {
92
+ throw new errors_js_1.MoneyError('The amount exceeds the safe integer range of a JavaScript number: use toTiynBigInt');
93
+ }
94
+ return value === 0 ? 0 : value;
95
+ },
96
+ /** Like {@link toTiyn}, for the whole 64-bit range. */
97
+ toTiynBigInt(tenge) {
98
+ return parseTiyn(tenge);
99
+ },
100
+ /** Tiyn as an exact decimal string of tenge: 4500050 gives "45000.50". */
101
+ toTengeString(tiyn) {
102
+ const value = integerTiyn(tiyn);
103
+ const abs = value < 0n ? -value : value;
104
+ return (value < 0n ? '-' : '') + (abs / 100n).toString() + '.' + (abs % 100n).toString().padStart(2, '0');
105
+ },
106
+ /**
107
+ * Formats tiyn for display: 4500000 gives "45 000,00 ₸". Known currencies get a symbol
108
+ * (KZT, USD, EUR, RUB); any other code is printed upper-cased after the amount.
109
+ */
110
+ formatTiyn(tiyn, currency = 'KZT') {
111
+ const value = integerTiyn(tiyn);
112
+ const code = (typeof currency === 'string' ? currency : '').toUpperCase();
113
+ const symbol = code === '' ? '₸' : (SYMBOLS[code] ?? code);
114
+ const abs = value < 0n ? -value : value;
115
+ const whole = (abs / 100n).toString().replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ' ');
116
+ return (value < 0n ? '-' : '') + whole + ',' + (abs % 100n).toString().padStart(2, '0') + ' ' + symbol;
117
+ },
118
+ };
119
+ /**
120
+ * Checks a Kazakhstani BIN or IIN: exactly 12 ASCII digits with a correct check digit.
121
+ * The value is not trimmed.
122
+ */
123
+ function isValidBinIin(value) {
124
+ if (typeof value !== 'string' || value.length !== 12 || !/^[0-9]{12}$/.test(value) || value.endsWith('\n'))
125
+ return false;
126
+ const digits = [];
127
+ for (let i = 0; i < 12; i++)
128
+ digits.push(value.charCodeAt(i) - 48);
129
+ const control = (weights) => {
130
+ let sum = 0;
131
+ for (let i = 0; i < 11; i++)
132
+ sum += (digits[i] ?? 0) * weights(i);
133
+ return sum % 11;
134
+ };
135
+ let check = control((i) => i + 1);
136
+ if (check === 10)
137
+ check = control((i) => ((i + 2) % 11) + 1);
138
+ return check < 10 && check === digits[11];
139
+ }
140
+ /** Helpers for Kazakhstani identifiers. */
141
+ exports.TungoKazakhstan = { isValidBinIin };
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,47 @@
1
+ import { APIPromise, type APIClient, type RequestSpec, type WithResponse } from './core.js';
2
+ import type { ResponseInfo } from './streaming.js';
3
+ /** The shape every cursor-paginated response has. */
4
+ export interface CursorPageBody<Item> {
5
+ data: Item[];
6
+ next_cursor?: string | null;
7
+ }
8
+ /**
9
+ * One page of a cursor-paginated list. `data` holds the items of this page, `body` the complete
10
+ * typed response (totals and other fields next to `data`). Iterating the page with `for await`
11
+ * walks this page and every following one, fetching lazily.
12
+ */
13
+ export declare class Page<Item, Body extends CursorPageBody<Item> = CursorPageBody<Item>> implements AsyncIterable<Item> {
14
+ #private;
15
+ /** The items of this page. */
16
+ readonly data: Item[];
17
+ /** The cursor of the next page; null on the last page. */
18
+ readonly nextCursor: string | null;
19
+ /** The complete response body. */
20
+ readonly body: Body;
21
+ /** Status, headers, request id and rate limit of the response that carried this page. */
22
+ readonly response: ResponseInfo;
23
+ /** `seen` holds every cursor already requested in this walk; the client passes it from page to page. */
24
+ constructor(client: APIClient, spec: RequestSpec, result: WithResponse<Body>, seen?: ReadonlySet<string>);
25
+ /** True when the server announced another page. */
26
+ hasNextPage(): boolean;
27
+ /**
28
+ * Fetches the next page with the same filters. Throws when there is none, and when the server
29
+ * returned a cursor that this walk has already requested (this page's own cursor or any earlier
30
+ * one), which would loop forever.
31
+ */
32
+ getNextPage(): PagePromise<Item, Body>;
33
+ /** This page and every following one. */
34
+ iterPages(): AsyncGenerator<Page<Item, Body>, void, undefined>;
35
+ [Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
36
+ }
37
+ /**
38
+ * A promise of the first page that is also a lazy iterator over every item of every page:
39
+ * `for await (const item of client.proposals.list(co))`.
40
+ */
41
+ export declare class PagePromise<Item, Body extends CursorPageBody<Item> = CursorPageBody<Item>> extends APIPromise<Page<Item, Body>> implements AsyncIterable<Item> {
42
+ [Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
43
+ /** The pages one by one, fetched lazily. */
44
+ iterPages(): AsyncGenerator<Page<Item, Body>, void, undefined>;
45
+ }
46
+ /** Requests one page of a cursor-paginated list. */
47
+ export declare function requestPage<Item, Body extends CursorPageBody<Item> = CursorPageBody<Item>>(client: APIClient, spec: RequestSpec, seen?: ReadonlySet<string>): PagePromise<Item, Body>;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PagePromise = exports.Page = void 0;
4
+ exports.requestPage = requestPage;
5
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
6
+ const core_js_1 = require("./core.js");
7
+ const errors_js_1 = require("./errors.js");
8
+ /**
9
+ * One page of a cursor-paginated list. `data` holds the items of this page, `body` the complete
10
+ * typed response (totals and other fields next to `data`). Iterating the page with `for await`
11
+ * walks this page and every following one, fetching lazily.
12
+ */
13
+ class Page {
14
+ /** The items of this page. */
15
+ data;
16
+ /** The cursor of the next page; null on the last page. */
17
+ nextCursor;
18
+ /** The complete response body. */
19
+ body;
20
+ /** Status, headers, request id and rate limit of the response that carried this page. */
21
+ response;
22
+ #client;
23
+ #spec;
24
+ #seen;
25
+ /** `seen` holds every cursor already requested in this walk; the client passes it from page to page. */
26
+ constructor(client, spec, result, seen) {
27
+ const body = result.data;
28
+ const data = typeof body === 'object' && body !== null ? body.data : undefined;
29
+ if (!Array.isArray(data)) {
30
+ throw new errors_js_1.DecodeError('The response of ' + spec.method + ' ' + spec.path + ' is not a page: "data" is not an array', {
31
+ status: result.response.status,
32
+ requestId: result.response.requestId,
33
+ body: JSON.stringify(body) ?? '',
34
+ });
35
+ }
36
+ const next = body.next_cursor;
37
+ this.data = data;
38
+ this.nextCursor = typeof next === 'string' && next !== '' ? next : null;
39
+ this.body = result.data;
40
+ this.response = result.response;
41
+ this.#client = client;
42
+ this.#spec = spec;
43
+ const requested = spec.query?.cursor;
44
+ const all = new Set(seen);
45
+ if (typeof requested === 'string')
46
+ all.add(requested);
47
+ this.#seen = all;
48
+ }
49
+ /** True when the server announced another page. */
50
+ hasNextPage() {
51
+ return this.nextCursor !== null;
52
+ }
53
+ /**
54
+ * Fetches the next page with the same filters. Throws when there is none, and when the server
55
+ * returned a cursor that this walk has already requested (this page's own cursor or any earlier
56
+ * one), which would loop forever.
57
+ */
58
+ getNextPage() {
59
+ const cursor = this.nextCursor;
60
+ const query = (this.#spec.query ?? {});
61
+ if (cursor === null) {
62
+ return new PagePromise(Promise.reject(new errors_js_1.TungoError('There is no next page: check hasNextPage() first')));
63
+ }
64
+ if (this.#seen.has(cursor)) {
65
+ return new PagePromise(Promise.reject(new errors_js_1.TungoError('Pagination stopped: the server returned the same cursor again for ' + this.#spec.method + ' ' + this.#spec.path)));
66
+ }
67
+ return requestPage(this.#client, { ...this.#spec, query: { ...query, cursor } }, this.#seen);
68
+ }
69
+ /** This page and every following one. */
70
+ async *iterPages() {
71
+ yield this;
72
+ let next = this.hasNextPage() ? this.getNextPage() : null;
73
+ while (next !== null) {
74
+ const page = await next;
75
+ yield page;
76
+ next = page.hasNextPage() ? page.getNextPage() : null;
77
+ }
78
+ }
79
+ async *[Symbol.asyncIterator]() {
80
+ for await (const page of this.iterPages()) {
81
+ for (const item of page.data)
82
+ yield item;
83
+ }
84
+ }
85
+ }
86
+ exports.Page = Page;
87
+ /**
88
+ * A promise of the first page that is also a lazy iterator over every item of every page:
89
+ * `for await (const item of client.proposals.list(co))`.
90
+ */
91
+ class PagePromise extends core_js_1.APIPromise {
92
+ async *[Symbol.asyncIterator]() {
93
+ const page = await this;
94
+ yield* page;
95
+ }
96
+ /** The pages one by one, fetched lazily. */
97
+ async *iterPages() {
98
+ const page = await this;
99
+ yield* page.iterPages();
100
+ }
101
+ }
102
+ exports.PagePromise = PagePromise;
103
+ /** Requests one page of a cursor-paginated list. */
104
+ function requestPage(client, spec, seen) {
105
+ const result = client
106
+ .request(spec)
107
+ .withResponse()
108
+ .then((r) => {
109
+ const page = new Page(client, spec, r, seen);
110
+ return { data: page, response: r.response };
111
+ });
112
+ return new PagePromise(result);
113
+ }
@@ -0,0 +1,74 @@
1
+ import { type RateLimit } from './errors.js';
2
+ /** Status and headers of one HTTP response. */
3
+ export interface ResponseInfo {
4
+ /** HTTP status code. */
5
+ status: number;
6
+ /** Response headers. */
7
+ headers: Headers;
8
+ /** Value of the `x-request-id` header; quote it to support. */
9
+ requestId: string | null;
10
+ /** Rate-limit headers of THIS response (`x-ratelimit-*`), or null when absent. */
11
+ rateLimit: RateLimit | null;
12
+ /** How many attempts the request took (1 = no retries). */
13
+ attempts: number;
14
+ }
15
+ /** One dispatched server-sent event. */
16
+ export interface ServerSentEvent {
17
+ /** Event name; `message` when the stream did not name it. */
18
+ event: string;
19
+ /** The `data` lines joined with a line feed. */
20
+ data: string;
21
+ /** The last event id seen so far, or null. */
22
+ id: string | null;
23
+ /** Reconnection time in milliseconds, when this event's block set it. */
24
+ retry?: number;
25
+ }
26
+ /**
27
+ * Incremental parser of the `text/event-stream` format (WHATWG HTML, "interpreting an event
28
+ * stream"). Feed it the bytes as they arrive; it returns the events completed by each chunk.
29
+ * LF, CRLF and bare CR line endings, a leading BOM, comments, multi-line data and UTF-8
30
+ * sequences split across chunks are handled. An unterminated last event is dropped.
31
+ */
32
+ export declare class SSEDecoder {
33
+ #private;
34
+ /** Consumes one chunk and returns the events it completed. */
35
+ feed(chunk: Uint8Array): ServerSentEvent[];
36
+ }
37
+ /** What a {@link Stream} is built from. Created by the client; not meant to be constructed by hand. */
38
+ export interface StreamInit {
39
+ response: ResponseInfo;
40
+ body: ReadableStream<Uint8Array> | null;
41
+ /** Aborting it closes the connection. */
42
+ controller: AbortController;
43
+ /** The caller's signal, when one was passed. */
44
+ signal: AbortSignal | undefined;
45
+ /** Removes the listener that links the caller's signal to the controller. */
46
+ detach: () => void;
47
+ /** Milliseconds without a single byte after which the stream fails; 0 or Infinity disables the check. */
48
+ idleTimeout: number;
49
+ /** `METHOD /path/template` for error messages. */
50
+ route: string;
51
+ }
52
+ /**
53
+ * A server-sent event stream. Iterate it with `for await` to receive typed events as they arrive.
54
+ * Leaving the loop early, or calling {@link Stream.close}, closes the connection. A stream can be
55
+ * consumed once.
56
+ */
57
+ export declare class Stream<T> implements AsyncIterable<T> {
58
+ #private;
59
+ /** Status and headers of the response that opened the stream. */
60
+ readonly response: ResponseInfo;
61
+ constructor(init: StreamInit, decode: (event: ServerSentEvent, response: ResponseInfo) => T | undefined);
62
+ /** The id of the last event received so far (send it as `Last-Event-ID` to resume). */
63
+ get lastEventId(): string | null;
64
+ /** Closes the connection. Safe to call more than once; a running iteration ends quietly. */
65
+ close(): void;
66
+ /** The raw server-sent events (name, data text, id), including heart-beats. */
67
+ events(): AsyncGenerator<ServerSentEvent, void, undefined>;
68
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
69
+ }
70
+ /**
71
+ * Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
72
+ * skipped; data that is not valid JSON raises a DecodeError.
73
+ */
74
+ export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo): T | undefined;