@woodger/t-invest-node-sdk 0.5.4 → 0.5.5

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 (47) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/application/services/unary-limiter.js +35 -8
  3. package/dist/bootstrap/args/command-options.d.ts +7 -1
  4. package/dist/bootstrap/args/command-options.js +10 -3
  5. package/dist/bootstrap/cli/help-catalog.d.ts +7 -7
  6. package/dist/bootstrap/cli/help-catalog.js +20 -26
  7. package/dist/bootstrap/cli/registry.d.ts +1 -1
  8. package/dist/bootstrap/commands/broker-report/cli.js +1 -1
  9. package/dist/bootstrap/commands/dividends-foreign-issuer/cli.js +1 -1
  10. package/dist/bootstrap/commands/order-book/cli.d.ts +3 -3
  11. package/dist/bootstrap/commands/order-book/cli.js +1 -1
  12. package/dist/bootstrap/commands/stream-run/config.d.ts +29 -6
  13. package/dist/bootstrap/commands/stream-run/config.js +17 -54
  14. package/dist/bootstrap/commands/stream-run/reporter.js +2 -0
  15. package/dist/bootstrap/commands/stream-run/request.mapper.js +70 -40
  16. package/dist/bootstrap/commands/stream-run/stream-session.js +7 -2
  17. package/dist/bootstrap/t-invest-node-sdk.js +13 -11
  18. package/dist/generated/common.js +2 -2
  19. package/dist/generated/google/api/field_behavior.js +2 -2
  20. package/dist/generated/google/protobuf/descriptor.js +2 -2
  21. package/dist/generated/google/protobuf/timestamp.js +2 -2
  22. package/dist/generated/instruments.js +2 -2
  23. package/dist/generated/marketdata.js +2 -2
  24. package/dist/generated/operations.js +2 -2
  25. package/dist/generated/orders.js +2 -2
  26. package/dist/generated/sandbox.js +2 -2
  27. package/dist/generated/signals.js +2 -2
  28. package/dist/generated/stoporders.js +2 -2
  29. package/dist/generated/users.js +2 -2
  30. package/dist/infrastructure/transport/grpc/sdk-call-error.js +5 -6
  31. package/dist/infrastructure/transport/grpc/sdk-client.d.ts +2 -2
  32. package/docs/architecture.md +4 -2
  33. package/docs/clean-architecture/adapters.md +7 -124
  34. package/docs/clean-architecture/api-commands.md +6 -160
  35. package/docs/clean-architecture/application.md +101 -1
  36. package/docs/clean-architecture/cli-output-boundaries.md +72 -29
  37. package/docs/clean-architecture/dto.md +9 -100
  38. package/docs/clean-architecture/index.md +6 -44
  39. package/docs/cli-reference.md +132 -0
  40. package/docs/cli-stream-configuration.md +5 -3
  41. package/docs/cli-stream-reference.md +5 -2
  42. package/docs/guides/custom-unary-limiter.md +11 -7
  43. package/docs/guides/errors-and-lifecycle.md +21 -0
  44. package/docs/index.md +2 -3
  45. package/docs/roadmap.md +1 -28
  46. package/package.json +9 -8
  47. package/readme.md +5 -41
package/CHANGELOG.md CHANGED
@@ -13,6 +13,32 @@
13
13
 
14
14
  ## [Не выпущено]
15
15
 
16
+ ## [0.5.5] - 2026-10-02
17
+
18
+ ### Изменено
19
+
20
+ - `icore` обновлён до 2.2.4 с исправлениями разрешения и типизации команд, потокового вывода и рендеринга таблиц и CSV.
21
+ - Тип gRPC-клиента выводится из service definition; публичные service interfaces SDK сохранены. Внутренний stream config описан вариантами по `stream`, а построение bidirectional и server-side requests объединено в request mapper.
22
+ - Очередь встроенного unary limiter-а удаляет отменённые requests за O(1), сохраняя FIFO, pacing и cancellation semantics.
23
+ - Общие описания CLI-параметров cursor pagination разделяются production и Sandbox командами. Справка проверяется на согласованность со schemas по именам опций, обязательности, choices и defaults.
24
+ - Все тесты используют строгие assertions. Добавлены проверки границ денежных значений и валидации stream config; тесты unary limiter-а проверяют время выдачи permits, FIFO и отмену без привязки к разбиению ожидания на таймеры.
25
+ - Пользовательский список CLI-команд и compatibility aliases вынесен в `docs/cli-reference.md`. Заметки о DTO объединены с application-слоем, а адаптеры — с границами вывода CLI; прежние страницы DTO и адаптеров сохранены как навигация к перенесённым разделам. README, roadmap и тестовые политики сокращены за счёт повторов и однотипных примеров. Запреты на добавление и удаление поведения уточнены для изменений вне требований задачи.
26
+ - `@bufbuild/protobuf` обновлён до 2.16.0, `@types/node` — до 26.6.4, `oxlint` — до 1.86.0, `oxlint-tsgolint` — до 7.0.2003, `protoc` — до 36.2.0, `ts-proto` — до 2.12.4. После перегенерации 12 proto-модулей изменились только заголовки с версиями инструментов; generated API остался прежним.
27
+
28
+ ### Исправлено
29
+
30
+ - CLI-справка показывает поддерживаемый alias `1hour` для свечей и defaults фильтров поиска инструментов и cursor pagination. Принимаемые опции и поведение команд не изменены.
31
+ - `stream run` распознаёт `subscription` в `orders.tradesStream` и фильтрует подтверждения подписки через `includeSubscriptionEvents` до подсчёта `maxEvents`, включая raw-вывод.
32
+ - Коды ошибок сертификатов внутри provider gRPC `UNAVAILABLE` больше не меняют `SdkError.source` на `tls`; распознавание локальных TLS diagnostics сохранено.
33
+ - CLI проверяет границы protobuf `int32` для глубины стакана и страниц отчётов. Значения выше `2147483647` отклоняются как usage errors до создания SDK; проверки остальных безопасных целых и public SDK DTO не изменены.
34
+ - `stream run` штатно завершает реальный gRPC stream по `maxEvents`: iterator закрывается до отмены session signal, поэтому достижение лимита не превращается в ошибку с кодом завершения `1`. Для pending read при таймауте сохранена отмена перед закрытием iterator.
35
+ - Пример собственного rolling-window limiter-а консервативно обрабатывает дробные квоты. Справочники stream CLI уточняют вывод статусов подписок, отсутствие поля `action` и общее значение `waitingClose` в одном запросе. Быстрый старт README компилируется с текущими TypeScript-настройками проекта.
36
+ - `nice-grpc-common` объявлен прямой runtime-зависимостью, поскольку публичные generated declarations импортируют его types. TypeScript Consumer-а больше не зависит от hoisting транзитивного пакета из `nice-grpc`.
37
+
38
+ ### Безопасность
39
+
40
+ - В lockfile `@grpc/grpc-js` обновлён до 1.14.5 с исправлениями [GHSA-m9gg-hp2v-232j](https://github.com/grpc/grpc-node/security/advisories/GHSA-m9gg-hp2v-232j) и [GHSA-f596-whhp-79r4](https://github.com/grpc/grpc-node/security/advisories/GHSA-f596-whhp-79r4).
41
+
16
42
  ## [0.5.4] - 2026-09-14
17
43
 
18
44
  ### Добавлено
@@ -43,6 +43,8 @@ class InMemoryUnaryLimiter {
43
43
  const request = {
44
44
  intervalMs,
45
45
  signal: context.signal,
46
+ previous: schedule.tail,
47
+ next: undefined,
46
48
  resolve,
47
49
  reject,
48
50
  onAbort: () => {
@@ -50,7 +52,13 @@ class InMemoryUnaryLimiter {
50
52
  }
51
53
  };
52
54
  context.signal.addEventListener('abort', request.onAbort, { once: true });
53
- schedule.pendingRequests.push(request);
55
+ if (schedule.tail === undefined) {
56
+ schedule.head = request;
57
+ }
58
+ else {
59
+ schedule.tail.next = request;
60
+ }
61
+ schedule.tail = request;
54
62
  this.start(schedule);
55
63
  });
56
64
  }
@@ -61,7 +69,8 @@ class InMemoryUnaryLimiter {
61
69
  maxRequests: quota.maxRequests,
62
70
  windowMs: quota.windowMs,
63
71
  nextAvailableAt: 0,
64
- pendingRequests: [],
72
+ head: undefined,
73
+ tail: undefined,
65
74
  timer: undefined
66
75
  };
67
76
  this.schedules.set(quota.bucket, schedule);
@@ -73,7 +82,7 @@ class InMemoryUnaryLimiter {
73
82
  return schedule;
74
83
  }
75
84
  start(schedule) {
76
- if (schedule.timer !== undefined || schedule.pendingRequests.length === 0) {
85
+ if (schedule.timer !== undefined || schedule.head === undefined) {
77
86
  return;
78
87
  }
79
88
  const time = performance.now();
@@ -100,10 +109,11 @@ class InMemoryUnaryLimiter {
100
109
  }, Math.min(delay, maxTimerDelayMs));
101
110
  }
102
111
  dispatch(schedule, scheduledAt) {
103
- const request = schedule.pendingRequests.shift();
112
+ const request = schedule.head;
104
113
  if (request === undefined) {
105
114
  return;
106
115
  }
116
+ this.removeRequest(schedule, request);
107
117
  request.signal.removeEventListener('abort', request.onAbort);
108
118
  const dispatchedAt = Math.max(scheduledAt, performance.now());
109
119
  schedule.nextAvailableAt = dispatchedAt + request.intervalMs;
@@ -111,12 +121,13 @@ class InMemoryUnaryLimiter {
111
121
  this.start(schedule);
112
122
  }
113
123
  cancel(schedule, request) {
114
- const requestIndex = schedule.pendingRequests.indexOf(request);
115
- if (requestIndex < 0) {
124
+ if (schedule.head !== request
125
+ && request.previous === undefined
126
+ && request.next === undefined) {
116
127
  return;
117
128
  }
118
- const isHead = requestIndex === 0;
119
- schedule.pendingRequests.splice(requestIndex, 1);
129
+ const isHead = schedule.head === request;
130
+ this.removeRequest(schedule, request);
120
131
  request.signal.removeEventListener('abort', request.onAbort);
121
132
  if (isHead) {
122
133
  this.clearTimer(schedule);
@@ -126,6 +137,22 @@ class InMemoryUnaryLimiter {
126
137
  this.start(schedule);
127
138
  }
128
139
  }
140
+ removeRequest(schedule, request) {
141
+ if (request.previous === undefined) {
142
+ schedule.head = request.next;
143
+ }
144
+ else {
145
+ request.previous.next = request.next;
146
+ }
147
+ if (request.next === undefined) {
148
+ schedule.tail = request.previous;
149
+ }
150
+ else {
151
+ request.next.previous = request.previous;
152
+ }
153
+ request.previous = undefined;
154
+ request.next = undefined;
155
+ }
129
156
  clearTimer(schedule) {
130
157
  const timer = schedule.timer;
131
158
  if (timer === undefined) {
@@ -34,10 +34,16 @@ export declare const positiveSafeIntegerOption: {
34
34
  readonly min: 1;
35
35
  readonly max: number;
36
36
  };
37
+ export declare const positiveInt32Option: {
38
+ readonly type: 'number';
39
+ readonly integer: true;
40
+ readonly min: 1;
41
+ readonly max: 2147483647;
42
+ };
37
43
  export declare function withSdkOptions<const TSchemas extends readonly OptionsSchema[]>(...schemas: TSchemas): MergeOptionsSchemas<readonly [typeof sdkOptionsSchema, ...TSchemas]>;
38
44
  export declare function parseCommaSeparatedStringListOption(value: string, name: string): string[];
39
45
  export declare function parseDateTimeOption(value: string, name: string): Date;
40
46
  export declare function requireStringOption(value: string | undefined, name: string): string;
41
47
  export declare function parseRequiredDateTimeOption(value: string | undefined, name: string): Date;
42
- export declare function parseOptionalNonNegativeIntegerOption(value: string | undefined, name: string): number;
48
+ export declare function parseOptionalNonNegativeInt32Option(value: string | undefined, name: string): number;
43
49
  export {};
@@ -10,13 +10,13 @@
10
10
  * сборки generated requests или форматирования provider responses.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.positiveSafeIntegerOption = exports.sdkOptionsSchema = void 0;
13
+ exports.positiveInt32Option = exports.positiveSafeIntegerOption = exports.sdkOptionsSchema = void 0;
14
14
  exports.withSdkOptions = withSdkOptions;
15
15
  exports.parseCommaSeparatedStringListOption = parseCommaSeparatedStringListOption;
16
16
  exports.parseDateTimeOption = parseDateTimeOption;
17
17
  exports.requireStringOption = requireStringOption;
18
18
  exports.parseRequiredDateTimeOption = parseRequiredDateTimeOption;
19
- exports.parseOptionalNonNegativeIntegerOption = parseOptionalNonNegativeIntegerOption;
19
+ exports.parseOptionalNonNegativeInt32Option = parseOptionalNonNegativeInt32Option;
20
20
  const icore_1 = require("icore");
21
21
  exports.sdkOptionsSchema = {
22
22
  token: {
@@ -38,6 +38,10 @@ exports.positiveSafeIntegerOption = {
38
38
  min: 1,
39
39
  max: Number.MAX_SAFE_INTEGER
40
40
  };
41
+ exports.positiveInt32Option = {
42
+ ...exports.positiveSafeIntegerOption,
43
+ max: 2_147_483_647
44
+ };
41
45
  function withSdkOptions(...schemas) {
42
46
  return (0, icore_1.mergeOptionsSchema)(exports.sdkOptionsSchema, ...schemas);
43
47
  }
@@ -70,7 +74,7 @@ function requireStringOption(value, name) {
70
74
  function parseRequiredDateTimeOption(value, name) {
71
75
  return parseDateTimeOption(requireStringOption(value, name), name);
72
76
  }
73
- function parseOptionalNonNegativeIntegerOption(value, name) {
77
+ function parseOptionalNonNegativeInt32Option(value, name) {
74
78
  if (value === undefined) {
75
79
  return 0;
76
80
  }
@@ -81,6 +85,9 @@ function parseOptionalNonNegativeIntegerOption(value, name) {
81
85
  if (!Number.isSafeInteger(parsed)) {
82
86
  throw new icore_1.CliUsageError(`Expected '--${name}' as integer greater than or equal to 0`);
83
87
  }
88
+ if (parsed > 2_147_483_647) {
89
+ throw new icore_1.CliUsageError(`Expected '--${name}' to be less than or equal to 2147483647`);
90
+ }
84
91
  return parsed;
85
92
  }
86
93
  const rfc3339DateTimePattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;
@@ -58,7 +58,7 @@ export declare const commandHelp: {
58
58
  readonly sdkCall: 'sdk.marketData.getCandles';
59
59
  readonly grpcMethod: 'MarketDataService/GetCandles';
60
60
  readonly usage: readonly ["t-invest-node-sdk market candles --instrument-id=ID --from=ISO --to=ISO --interval=INTERVAL [options]"];
61
- readonly required: readonly ["--instrument-id=ID FIGI or instrument UID", "--from=ISO Start timestamp, inclusive", "--to=ISO End timestamp, inclusive", "--interval=INTERVAL 1min|2min|3min|5min|10min|15min|30min|hour|2hour|4hour|day|week|month"];
61
+ readonly required: readonly ["--instrument-id=ID FIGI or instrument UID", "--from=ISO Start timestamp, inclusive", "--to=ISO End timestamp, inclusive", "--interval=INTERVAL 1min|2min|3min|5min|10min|15min|30min|hour|1hour|2hour|4hour|day|week|month"];
62
62
  readonly optional: readonly ["--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|csv Output format (default: json)"];
63
63
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
64
64
  readonly examples: readonly ["t-invest-node-sdk market candles --instrument-id=BBG00QPYJ5H0 --from=2026-06-19T00:00:00Z --to=2026-06-19T01:00:00Z --interval=1min --format=csv"];
@@ -80,7 +80,7 @@ export declare const commandHelp: {
80
80
  readonly grpcMethod: 'InstrumentsService/FindInstrument';
81
81
  readonly usage: readonly ["t-invest-node-sdk instrument search --query=TEXT [options]"];
82
82
  readonly required: readonly ["--query=TEXT Search query"];
83
- readonly optional: readonly ["--instrument-kind=KIND unspecified|bond|share|currency|etf|futures|sp|option|clearing-certificate", "--api-trade-available Only instrument available for API trading", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
83
+ readonly optional: readonly ["--instrument-kind=KIND unspecified|bond|share|currency|etf|futures|sp|option|clearing-certificate (default: unspecified)", "--api-trade-available Only instrument available for API trading (default: false)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
84
84
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
85
85
  readonly examples: readonly ["t-invest-node-sdk instrument search --query=TCSG", "t-invest-node-sdk instrument search --query=TCSG --instrument-kind=share --api-trade-available --format=json"];
86
86
  };
@@ -372,7 +372,7 @@ export declare const commandHelp: {
372
372
  readonly sdkCall: 'sdk.marketData.getOrderBook';
373
373
  readonly grpcMethod: 'MarketDataService/GetOrderBook';
374
374
  readonly usage: readonly ["t-invest-node-sdk market order-book --instrument-id=ID --depth=DEPTH [options]"];
375
- readonly required: readonly ["--instrument-id=ID FIGI or instrument UID", "--depth=DEPTH Order book depth as positive integer"];
375
+ readonly required: readonly ["--instrument-id=ID FIGI or instrument UID", "--depth=DEPTH Order book depth as integer from 1 to 2147483647"];
376
376
  readonly optional: readonly ["--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
377
377
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
378
378
  readonly examples: readonly ["t-invest-node-sdk market order-book --instrument-id=BBG00QPYJ5H0 --depth=10", "t-invest-node-sdk market order-book --instrument-id=instrument-uid --depth=20 --format=json"];
@@ -467,7 +467,7 @@ export declare const commandHelp: {
467
467
  readonly grpcMethod: 'OperationsService/GetOperationsByCursor';
468
468
  readonly usage: readonly ["t-invest-node-sdk operation page --account-id=ID [options]"];
469
469
  readonly required: readonly ["--account-id=ID Account identifier from account list"];
470
- readonly optional: readonly ["--instrument-id=ID Optional FIGI or instrument UID filter", "--from=ISO Optional start timestamp, inclusive", "--to=ISO Optional end timestamp, inclusive", "--cursor=CURSOR Cursor returned as nextCursor by the previous page", "--limit=N Page size from 1 to 1000; provider default is used when omitted", "--operation-type=TYPE Generated OperationType name; comma-separated list is allowed", "--state=STATE unspecified|executed|canceled|progress (default: unspecified)", "--without-commissions Exclude commissions", "--without-trades Exclude trades", "--without-overnights Exclude overnight operations", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
470
+ readonly optional: readonly ["--instrument-id=ID Optional FIGI or instrument UID filter", "--from=ISO Optional start timestamp, inclusive", "--to=ISO Optional end timestamp, inclusive", "--cursor=CURSOR Cursor returned as nextCursor by the previous page", "--limit=N Page size from 1 to 1000; provider default is used when omitted", "--operation-type=TYPE Generated OperationType name; comma-separated list is allowed", "--state=STATE unspecified|executed|canceled|progress (default: unspecified)", "--without-commissions Exclude commissions (default: false)", "--without-trades Exclude trades (default: false)", "--without-overnights Exclude overnight operations (default: false)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
471
471
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
472
472
  readonly examples: readonly ["t-invest-node-sdk operation page --account-id=2000000000 --limit=100", "t-invest-node-sdk operation page --account-id=2000000000 --cursor=NEXT --format=json"];
473
473
  readonly notes: readonly ["The command returns one page; pass nextCursor as --cursor to request the next page.", "Cursor pagination is explicit: the CLI does not loop through pages automatically.", "Use --limit to control page size when replaying a cursor flow in scripts.", "The command validates only CLI syntax and date ordering; API range limits remain provider-side."];
@@ -478,7 +478,7 @@ export declare const commandHelp: {
478
478
  readonly grpcMethod: 'OperationsService/GetBrokerReport';
479
479
  readonly usage: readonly ["t-invest-node-sdk operation broker-report --account-id=ID --from=ISO --to=ISO [options]", "t-invest-node-sdk operation broker-report --task-id=ID [options]"];
480
480
  readonly required: readonly ["Generate mode: --account-id=ID --from=ISO --to=ISO", "Page mode: --task-id=ID"];
481
- readonly optional: readonly ["--page=N Report page number, only with --task-id (default: 0)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
481
+ readonly optional: readonly ["--page=N Report page number from 0 to 2147483647, only with --task-id (default: 0)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
482
482
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
483
483
  readonly examples: readonly ["t-invest-node-sdk operation broker-report --account-id=2000000000 --from=2026-06-01T00:00:00Z --to=2026-06-19T00:00:00Z", "t-invest-node-sdk operation broker-report --task-id=TASK --page=1 --format=json"];
484
484
  readonly notes: readonly ["The command maps the generated oneof contract to two CLI modes: generate by period or get a page by task id.", "Generate mode starts a report task; page mode reads an existing report task page.", "Use --task-id returned by generate mode for later page requests.", "The command validates only CLI syntax and date ordering; API range limits remain provider-side."];
@@ -489,7 +489,7 @@ export declare const commandHelp: {
489
489
  readonly grpcMethod: 'OperationsService/GetDividendsForeignIssuer';
490
490
  readonly usage: readonly ["t-invest-node-sdk operation foreign-dividends-report --account-id=ID --from=ISO --to=ISO [options]", "t-invest-node-sdk operation foreign-dividends-report --task-id=ID [options]"];
491
491
  readonly required: readonly ["Generate mode: --account-id=ID --from=ISO --to=ISO", "Page mode: --task-id=ID"];
492
- readonly optional: readonly ["--page=N Report page number, only with --task-id (default: 0)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
492
+ readonly optional: readonly ["--page=N Report page number from 0 to 2147483647, only with --task-id (default: 0)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
493
493
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
494
494
  readonly examples: readonly ["t-invest-node-sdk operation foreign-dividends-report --account-id=2000000000 --from=2026-01-01T00:00:00Z --to=2026-12-31T00:00:00Z", "t-invest-node-sdk operation foreign-dividends-report --task-id=TASK --page=1 --format=json"];
495
495
  readonly notes: readonly ["The command maps the generated oneof contract to two CLI modes: generate by period or get a page by task id.", "Generate mode starts a report task; page mode reads an existing report task page.", "Use --task-id returned by generate mode for later page requests.", "The command validates only CLI syntax and date ordering; API range limits remain provider-side."];
@@ -687,7 +687,7 @@ export declare const commandHelp: {
687
687
  readonly grpcMethod: 'SandboxService/GetSandboxOperationsByCursor';
688
688
  readonly usage: readonly ["t-invest-node-sdk sandbox operation page --account-id=ID [options]"];
689
689
  readonly required: readonly ["--account-id=ID Sandbox account identifier from sandbox account list"];
690
- readonly optional: readonly ["--instrument-id=ID Optional FIGI or instrument UID filter", "--from=ISO Optional start timestamp, inclusive", "--to=ISO Optional end timestamp, inclusive", "--cursor=CURSOR Cursor returned as nextCursor by the previous page", "--limit=N Page size from 1 to 1000; provider default is used when omitted", "--operation-type=TYPE Generated OperationType name; comma-separated list is allowed", "--state=STATE unspecified|executed|canceled|progress (default: unspecified)", "--without-commissions Exclude commissions", "--without-trades Exclude trades", "--without-overnights Exclude overnight operations", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
690
+ readonly optional: readonly ["--instrument-id=ID Optional FIGI or instrument UID filter", "--from=ISO Optional start timestamp, inclusive", "--to=ISO Optional end timestamp, inclusive", "--cursor=CURSOR Cursor returned as nextCursor by the previous page", "--limit=N Page size from 1 to 1000; provider default is used when omitted", "--operation-type=TYPE Generated OperationType name; comma-separated list is allowed", "--state=STATE unspecified|executed|canceled|progress (default: unspecified)", "--without-commissions Exclude commissions (default: false)", "--without-trades Exclude trades (default: false)", "--without-overnights Exclude overnight operations (default: false)", "--token=TOKEN OAuth token, overrides T_INVEST_TOKEN", "--endpoint=HOST:PORT gRPC endpoint, overrides T_INVEST_ENDPOINT", "--app-name=NAME Optional x-app-name metadata value", "--insecure Disable TLS for local or test endpoints", "--format=json|table Output format (default: table)"];
691
691
  readonly environment: readonly ["T_INVEST_TOKEN", "T_INVEST_ENDPOINT"];
692
692
  readonly examples: readonly ["t-invest-node-sdk sandbox operation page --account-id=2000000000 --limit=100", "t-invest-node-sdk sandbox operation page --account-id=2000000000 --cursor=NEXT --format=json"];
693
693
  readonly notes: readonly ["The command returns one page; pass nextCursor as --cursor to request the next page.", "The command validates only CLI syntax and date ordering; API range limits remain provider-side."];
@@ -20,6 +20,18 @@ const sdkEnvironment = [
20
20
  const tableFormatOption = '--format=json|table Output format (default: table)';
21
21
  const csvFormatOption = '--format=json|csv Output format (default: json)';
22
22
  const jsonlFormatOption = '--format=jsonl Output format (default: jsonl)';
23
+ const operationPageOptions = [
24
+ '--instrument-id=ID Optional FIGI or instrument UID filter',
25
+ '--from=ISO Optional start timestamp, inclusive',
26
+ '--to=ISO Optional end timestamp, inclusive',
27
+ '--cursor=CURSOR Cursor returned as nextCursor by the previous page',
28
+ '--limit=N Page size from 1 to 1000; provider default is used when omitted',
29
+ '--operation-type=TYPE Generated OperationType name; comma-separated list is allowed',
30
+ '--state=STATE unspecified|executed|canceled|progress (default: unspecified)',
31
+ '--without-commissions Exclude commissions (default: false)',
32
+ '--without-trades Exclude trades (default: false)',
33
+ '--without-overnights Exclude overnight operations (default: false)'
34
+ ];
23
35
  exports.commandHelp = {
24
36
  'account list': {
25
37
  description: 'Print user accounts',
@@ -102,7 +114,7 @@ exports.commandHelp = {
102
114
  '--instrument-id=ID FIGI or instrument UID',
103
115
  '--from=ISO Start timestamp, inclusive',
104
116
  '--to=ISO End timestamp, inclusive',
105
- '--interval=INTERVAL 1min|2min|3min|5min|10min|15min|30min|hour|2hour|4hour|day|week|month'
117
+ '--interval=INTERVAL 1min|2min|3min|5min|10min|15min|30min|hour|1hour|2hour|4hour|day|week|month'
106
118
  ],
107
119
  optional: [
108
120
  ...sdkConnectionOptions,
@@ -149,8 +161,8 @@ exports.commandHelp = {
149
161
  '--query=TEXT Search query'
150
162
  ],
151
163
  optional: [
152
- '--instrument-kind=KIND unspecified|bond|share|currency|etf|futures|sp|option|clearing-certificate',
153
- '--api-trade-available Only instrument available for API trading',
164
+ '--instrument-kind=KIND unspecified|bond|share|currency|etf|futures|sp|option|clearing-certificate (default: unspecified)',
165
+ '--api-trade-available Only instrument available for API trading (default: false)',
154
166
  ...sdkConnectionOptions,
155
167
  tableFormatOption
156
168
  ],
@@ -790,7 +802,7 @@ exports.commandHelp = {
790
802
  ],
791
803
  required: [
792
804
  '--instrument-id=ID FIGI or instrument UID',
793
- '--depth=DEPTH Order book depth as positive integer'
805
+ '--depth=DEPTH Order book depth as integer from 1 to 2147483647'
794
806
  ],
795
807
  optional: [
796
808
  ...sdkConnectionOptions,
@@ -1013,16 +1025,7 @@ exports.commandHelp = {
1013
1025
  '--account-id=ID Account identifier from account list'
1014
1026
  ],
1015
1027
  optional: [
1016
- '--instrument-id=ID Optional FIGI or instrument UID filter',
1017
- '--from=ISO Optional start timestamp, inclusive',
1018
- '--to=ISO Optional end timestamp, inclusive',
1019
- '--cursor=CURSOR Cursor returned as nextCursor by the previous page',
1020
- '--limit=N Page size from 1 to 1000; provider default is used when omitted',
1021
- '--operation-type=TYPE Generated OperationType name; comma-separated list is allowed',
1022
- '--state=STATE unspecified|executed|canceled|progress (default: unspecified)',
1023
- '--without-commissions Exclude commissions',
1024
- '--without-trades Exclude trades',
1025
- '--without-overnights Exclude overnight operations',
1028
+ ...operationPageOptions,
1026
1029
  ...sdkConnectionOptions,
1027
1030
  tableFormatOption
1028
1031
  ],
@@ -1051,7 +1054,7 @@ exports.commandHelp = {
1051
1054
  'Page mode: --task-id=ID'
1052
1055
  ],
1053
1056
  optional: [
1054
- '--page=N Report page number, only with --task-id (default: 0)',
1057
+ '--page=N Report page number from 0 to 2147483647, only with --task-id (default: 0)',
1055
1058
  ...sdkConnectionOptions,
1056
1059
  tableFormatOption
1057
1060
  ],
@@ -1080,7 +1083,7 @@ exports.commandHelp = {
1080
1083
  'Page mode: --task-id=ID'
1081
1084
  ],
1082
1085
  optional: [
1083
- '--page=N Report page number, only with --task-id (default: 0)',
1086
+ '--page=N Report page number from 0 to 2147483647, only with --task-id (default: 0)',
1084
1087
  ...sdkConnectionOptions,
1085
1088
  tableFormatOption
1086
1089
  ],
@@ -1525,16 +1528,7 @@ exports.commandHelp = {
1525
1528
  '--account-id=ID Sandbox account identifier from sandbox account list'
1526
1529
  ],
1527
1530
  optional: [
1528
- '--instrument-id=ID Optional FIGI or instrument UID filter',
1529
- '--from=ISO Optional start timestamp, inclusive',
1530
- '--to=ISO Optional end timestamp, inclusive',
1531
- '--cursor=CURSOR Cursor returned as nextCursor by the previous page',
1532
- '--limit=N Page size from 1 to 1000; provider default is used when omitted',
1533
- '--operation-type=TYPE Generated OperationType name; comma-separated list is allowed',
1534
- '--state=STATE unspecified|executed|canceled|progress (default: unspecified)',
1535
- '--without-commissions Exclude commissions',
1536
- '--without-trades Exclude trades',
1537
- '--without-overnights Exclude overnight operations',
1531
+ ...operationPageOptions,
1538
1532
  ...sdkConnectionOptions,
1539
1533
  tableFormatOption
1540
1534
  ],
@@ -1012,7 +1012,7 @@ export declare const commandLineCommands: import("icore").Commands<readonly [Wit
1012
1012
  readonly type: 'number';
1013
1013
  readonly integer: true;
1014
1014
  readonly min: 1;
1015
- readonly max: number;
1015
+ readonly max: 2147483647;
1016
1016
  readonly required: true;
1017
1017
  };
1018
1018
  readonly format: {
@@ -58,7 +58,7 @@ function createBrokerReportRequest(options) {
58
58
  return {
59
59
  getBrokerReportRequest: {
60
60
  taskId,
61
- page: (0, command_options_1.parseOptionalNonNegativeIntegerOption)(options.page, 'page')
61
+ page: (0, command_options_1.parseOptionalNonNegativeInt32Option)(options.page, 'page')
62
62
  },
63
63
  generateBrokerReportRequest: undefined
64
64
  };
@@ -58,7 +58,7 @@ function createDividendsForeignIssuerRequest(options) {
58
58
  return {
59
59
  getDivForeignIssuerReport: {
60
60
  taskId,
61
- page: (0, command_options_1.parseOptionalNonNegativeIntegerOption)(options.page, 'page')
61
+ page: (0, command_options_1.parseOptionalNonNegativeInt32Option)(options.page, 'page')
62
62
  },
63
63
  generateDivForeignIssuerReport: undefined
64
64
  };
@@ -36,7 +36,7 @@ declare const orderBookOptionsSchema: {
36
36
  readonly type: 'number';
37
37
  readonly integer: true;
38
38
  readonly min: 1;
39
- readonly max: number;
39
+ readonly max: 2147483647;
40
40
  readonly required: true;
41
41
  };
42
42
  readonly format: {
@@ -68,7 +68,7 @@ export declare function createOrderBookCommand(createSdk?: OrderBookSdkFactory):
68
68
  readonly type: 'number';
69
69
  readonly integer: true;
70
70
  readonly min: 1;
71
- readonly max: number;
71
+ readonly max: 2147483647;
72
72
  readonly required: true;
73
73
  };
74
74
  readonly format: {
@@ -100,7 +100,7 @@ export declare const orderBookCommand: Omit<import("icore").CommandDefinition<{
100
100
  readonly type: 'number';
101
101
  readonly integer: true;
102
102
  readonly min: 1;
103
- readonly max: number;
103
+ readonly max: 2147483647;
104
104
  readonly required: true;
105
105
  };
106
106
  readonly format: {
@@ -23,7 +23,7 @@ const orderBookCommandPath = ['market', 'order-book'];
23
23
  const defaultOrderBookSdkFactory = (options) => new t_invest_node_sdk_1.TInvestNodeSDK(options);
24
24
  const orderBookDepthOptionsSchema = {
25
25
  depth: {
26
- ...command_options_1.positiveSafeIntegerOption,
26
+ ...command_options_1.positiveInt32Option,
27
27
  required: true
28
28
  }
29
29
  };
@@ -3,12 +3,12 @@
3
3
  *
4
4
  * Здесь допустимы:
5
5
  * - валидация stream config до создания SDK;
6
- * - mapping typed config в generated stream requests;
6
+ * - нормализация полей проверенной конфигурации;
7
7
  * - runtime defaults для долгоживущих stream-команд;
8
8
  *
9
9
  * Здесь не должно быть SDK calls или stdout/stderr output logic.
10
10
  */
11
- import { type MarketDataRequest, SubscriptionInterval } from '../../../generated/marketdata';
11
+ import { SubscriptionInterval } from '../../../generated/marketdata';
12
12
  export declare const streamRunStreamNames: readonly ['marketdata.marketDataStream', 'marketdata.marketDataServerSideStream', 'operations.portfolioStream', 'operations.positionsStream', 'orders.tradesStream'];
13
13
  export type StreamRunStreamName = typeof streamRunStreamNames[number];
14
14
  export type StreamRunRuntime = {
@@ -21,11 +21,34 @@ export type StreamRunRuntime = {
21
21
  raw: boolean;
22
22
  };
23
23
  export type StreamRunConfig = {
24
- stream: StreamRunStreamName;
25
- accounts?: string[];
26
- requests?: MarketDataRequest[];
27
- subscriptions?: MarketDataSubscriptions;
28
24
  runtime: StreamRunRuntime;
25
+ } & ({
26
+ stream: 'marketdata.marketDataStream';
27
+ requests: MarketDataStreamRequestConfig[];
28
+ accounts?: never;
29
+ subscriptions?: never;
30
+ } | {
31
+ stream: 'marketdata.marketDataServerSideStream';
32
+ subscriptions: MarketDataSubscriptions;
33
+ accounts?: never;
34
+ requests?: never;
35
+ } | {
36
+ stream: 'operations.portfolioStream' | 'operations.positionsStream' | 'orders.tradesStream';
37
+ accounts: string[];
38
+ requests?: never;
39
+ subscriptions?: never;
40
+ });
41
+ export type MarketDataStreamRequestConfig = {
42
+ type: 'subscribeCandles';
43
+ instruments: CandleSubscriptionConfig[];
44
+ } | {
45
+ type: 'subscribeOrderBook';
46
+ instruments: OrderBookSubscriptionConfig[];
47
+ } | {
48
+ type: 'subscribeTrades' | 'subscribeInfo' | 'subscribeLastPrice';
49
+ instruments: InstrumentSubscriptionConfig[];
50
+ } | {
51
+ type: 'getMySubscriptions';
29
52
  };
30
53
  export type MarketDataSubscriptions = {
31
54
  candles?: CandleSubscriptionConfig[] | undefined;
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Здесь допустимы:
6
6
  * - валидация stream config до создания SDK;
7
- * - mapping typed config в generated stream requests;
7
+ * - нормализация полей проверенной конфигурации;
8
8
  * - runtime defaults для долгоживущих stream-команд;
9
9
  *
10
10
  * Здесь не должно быть SDK calls или stdout/stderr output logic.
@@ -157,72 +157,30 @@ function parseMarketDataStreamRequest(value) {
157
157
  .map((item) => parseCandleSubscription(item, 'requests[].instruments[]'));
158
158
  validateCandlesWaitingClose(instruments);
159
159
  return {
160
- subscribeCandlesRequest: {
161
- subscriptionAction: marketdata_1.SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
162
- instruments: instruments.map((item) => marketdata_1.CandleInstrument.create({
163
- interval: item.interval,
164
- instrumentId: item.instrumentId
165
- })),
166
- waitingClose: resolveCandlesWaitingClose(instruments)
167
- }
160
+ type: requestType,
161
+ instruments
168
162
  };
169
163
  }
170
164
  case 'subscribeOrderBook':
171
165
  rejectUnknownFields(request, new Set(['type', 'instruments']), 'requests[]');
172
166
  return {
173
- subscribeOrderBookRequest: {
174
- subscriptionAction: marketdata_1.SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
175
- instruments: parseArray(request['instruments'], 'requests[].instruments')
176
- .map((item) => parseOrderBookSubscription(item, 'requests[].instruments[]'))
177
- .map((item) => marketdata_1.OrderBookInstrument.create({
178
- depth: item.depth,
179
- instrumentId: item.instrumentId,
180
- orderBookType: marketdata_1.OrderBookType.ORDERBOOK_TYPE_UNSPECIFIED
181
- }))
182
- }
167
+ type: requestType,
168
+ instruments: parseArray(request['instruments'], 'requests[].instruments')
169
+ .map((item) => parseOrderBookSubscription(item, 'requests[].instruments[]'))
183
170
  };
184
171
  case 'subscribeTrades':
185
- rejectUnknownFields(request, new Set(['type', 'instruments']), 'requests[]');
186
- return {
187
- subscribeTradesRequest: {
188
- subscriptionAction: marketdata_1.SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
189
- instruments: parseArray(request['instruments'], 'requests[].instruments')
190
- .map((item) => parseInstrumentSubscription(item, 'requests[].instruments[]'))
191
- .map((item) => marketdata_1.TradeInstrument.create({
192
- instrumentId: item.instrumentId
193
- })),
194
- tradeSource: marketdata_1.TradeSourceType.TRADE_SOURCE_UNSPECIFIED,
195
- withOpenInterest: false
196
- }
197
- };
198
172
  case 'subscribeInfo':
199
- rejectUnknownFields(request, new Set(['type', 'instruments']), 'requests[]');
200
- return {
201
- subscribeInfoRequest: {
202
- subscriptionAction: marketdata_1.SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
203
- instruments: parseArray(request['instruments'], 'requests[].instruments')
204
- .map((item) => parseInstrumentSubscription(item, 'requests[].instruments[]'))
205
- .map((item) => marketdata_1.InfoInstrument.create({
206
- instrumentId: item.instrumentId
207
- }))
208
- }
209
- };
210
173
  case 'subscribeLastPrice':
211
174
  rejectUnknownFields(request, new Set(['type', 'instruments']), 'requests[]');
212
175
  return {
213
- subscribeLastPriceRequest: {
214
- subscriptionAction: marketdata_1.SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
215
- instruments: parseArray(request['instruments'], 'requests[].instruments')
216
- .map((item) => parseInstrumentSubscription(item, 'requests[].instruments[]'))
217
- .map((item) => marketdata_1.LastPriceInstrument.create({
218
- instrumentId: item.instrumentId
219
- }))
220
- }
176
+ type: requestType,
177
+ instruments: parseArray(request['instruments'], 'requests[].instruments')
178
+ .map((item) => parseInstrumentSubscription(item, 'requests[].instruments[]'))
221
179
  };
222
180
  case 'getMySubscriptions':
223
181
  rejectUnknownFields(request, new Set(['type']), 'requests[]');
224
182
  return {
225
- getMySubscriptions: {}
183
+ type: requestType
226
184
  };
227
185
  }
228
186
  }
@@ -271,9 +229,14 @@ function parseCandleSubscription(value, path) {
271
229
  function parseOrderBookSubscription(value, path) {
272
230
  const orderBook = requireObject(value, path);
273
231
  rejectUnknownFields(orderBook, new Set(['instrumentId', 'depth']), path);
232
+ const instrumentId = parseInstrumentId(orderBook['instrumentId'], `${path}.instrumentId`);
233
+ const depth = parsePositiveInteger(orderBook['depth'], `${path}.depth`);
234
+ if (depth > 2_147_483_647) {
235
+ throw new icore_1.CliUsageError(`Expected '${path}.depth' to be less than or equal to 2147483647`);
236
+ }
274
237
  return {
275
- instrumentId: parseInstrumentId(orderBook['instrumentId'], `${path}.instrumentId`),
276
- depth: parsePositiveInteger(orderBook['depth'], `${path}.depth`)
238
+ instrumentId,
239
+ depth
277
240
  };
278
241
  }
279
242
  function parseInstrumentSubscription(value, path) {
@@ -25,6 +25,7 @@ const streamEventFields = [
25
25
  'orderbook',
26
26
  'tradingStatus',
27
27
  'lastPrice',
28
+ 'subscription',
28
29
  'subscriptions',
29
30
  'portfolio',
30
31
  'position',
@@ -37,6 +38,7 @@ const subscriptionEventTypes = new Set([
37
38
  'subscribeTradesResponse',
38
39
  'subscribeInfoResponse',
39
40
  'subscribeLastPriceResponse',
41
+ 'subscription',
40
42
  'subscriptions'
41
43
  ]);
42
44
  function formatStreamRunResponse(response, options) {