@1337exp/2pack 0.0.0-stage → 2.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The only error type 2pack throws for bad data. `code` says what went wrong, `path` where
3
+ * (for example `players[3].hp`). Decoding hostile bytes throws nothing else.
4
+ * Единственный тип ошибки 2pack для плохих данных. `code` говорит, что не так, `path` где
5
+ * (например `players[3].hp`). Разбор враждебных байтов не бросает ничего другого.
6
+ */
7
+ export class PackError extends Error {
8
+ code;
9
+ /** Field names and array indexes from the root down to the failing value. / Путь от корня до значения с ошибкой. */
10
+ path = [];
11
+ #detail;
12
+ constructor(code, detail) {
13
+ super(detail);
14
+ this.name = 'PackError';
15
+ this.code = code;
16
+ this.#detail = detail;
17
+ }
18
+ /** @internal Called while the error travels up through objects and arrays. */
19
+ addPath(segment) {
20
+ this.path.unshift(segment);
21
+ this.message = `${this.#detail} (at ${formatPath(this.path)})`;
22
+ }
23
+ }
24
+ function formatPath(path) {
25
+ let out = '';
26
+ for (const seg of path)
27
+ out += typeof seg === 'number' ? `[${seg}]` : out ? `.${seg}` : seg;
28
+ return out;
29
+ }
30
+ /** @internal */
31
+ export function fail(code, detail) {
32
+ throw new PackError(code, detail);
33
+ }
@@ -0,0 +1,3 @@
1
+ export { PackError, type PackErrorCode } from './errors.js';
2
+ export type { Codec, Infer, Value } from './codec.js';
3
+ export { added, array, bool, bytes, define, enumOf, f32, f64, i16, i32, i64, i8, optional, quant, str, u16, u32, u64, u8, varint, varuint, type BytesOptions, type DefineOptions, type QuantOptions, type Shape, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { PackError } from './errors.js';
2
+ export { added, array, bool, bytes, define, enumOf, f32, f64, i16, i32, i64, i8, optional, quant, str, u16, u32, u64, u8, varint, varuint, } from './types.js';
@@ -0,0 +1,107 @@
1
+ import { type Codec, type Value } from './codec.js';
2
+ /** `true` / `false`, 1 byte. */
3
+ export declare const bool: Codec<boolean>;
4
+ /** Unsigned 8-bit integer. / Беззнаковое 8 бит. */
5
+ export declare const u8: Codec<number>;
6
+ /** Signed 8-bit integer. / Знаковое 8 бит. */
7
+ export declare const i8: Codec<number>;
8
+ /** Unsigned 16-bit integer, little-endian. / Беззнаковое 16 бит. */
9
+ export declare const u16: Codec<number>;
10
+ /** Signed 16-bit integer, little-endian. / Знаковое 16 бит. */
11
+ export declare const i16: Codec<number>;
12
+ /** Unsigned 32-bit integer, little-endian. / Беззнаковое 32 бита. */
13
+ export declare const u32: Codec<number>;
14
+ /** Signed 32-bit integer, little-endian. / Знаковое 32 бита. */
15
+ export declare const i32: Codec<number>;
16
+ /** Unsigned 64-bit integer, always a `bigint`. / Беззнаковое 64 бита, всегда `bigint`. */
17
+ export declare const u64: Codec<bigint>;
18
+ /** Signed 64-bit integer, always a `bigint`. / Знаковое 64 бита, всегда `bigint`. */
19
+ export declare const i64: Codec<bigint>;
20
+ /** IEEE 754 single precision. `NaN` and `±Infinity` survive. / Одинарная точность. */
21
+ export declare const f32: Codec<number>;
22
+ /** IEEE 754 double precision. `NaN` and `±Infinity` survive. / Двойная точность. */
23
+ export declare const f64: Codec<number>;
24
+ /** Unsigned LEB128, `0 … 2^32-1`, 1 to 5 bytes: small numbers cost one byte. / Малые числа занимают 1 байт. */
25
+ export declare const varuint: Codec<number>;
26
+ /** Zigzag + LEB128, `-2^31 … 2^31-1`: small magnitudes cost one byte whatever the sign. */
27
+ export declare const varint: Codec<number>;
28
+ /**
29
+ * UTF-8 string of at most `maxBytes` **bytes** (not characters). A longer string is an error, never truncated.
30
+ * Строка UTF-8 не длиннее `maxBytes` **байт** (не символов). Длиннее: ошибка, без обрезки.
31
+ */
32
+ export declare function str(maxBytes: number): Codec<string>;
33
+ export interface BytesOptions {
34
+ /**
35
+ * Return a view into the input instead of a copy. Zero-copy, but the result is only valid while the input
36
+ * buffer is not reused: network libraries often reuse theirs.
37
+ * Вернуть окно во входной буфер вместо копии. Без копирования, но результат живёт, пока вход не
38
+ * переиспользован (сетевые библиотеки часто переиспользуют свои буферы).
39
+ */
40
+ view?: boolean;
41
+ }
42
+ /**
43
+ * Raw bytes, at most `maxBytes`. Decoded as a copy by default.
44
+ * Сырые байты, не больше `maxBytes`. По умолчанию при чтении копируются.
45
+ */
46
+ export declare function bytes(maxBytes: number, options?: BytesOptions): Codec<Uint8Array>;
47
+ /**
48
+ * A list of `item`s, at most `maxCount` of them.
49
+ * Список из `item`, не больше `maxCount` штук.
50
+ */
51
+ export declare function array<T>(item: Codec<T>, maxCount: number): Codec<T[]>;
52
+ /**
53
+ * A value that may be absent: `undefined` (typed) or `null` (accepted at runtime, so JSON-shaped data works) when
54
+ * packing, `undefined` when unpacking. In `define`, the field may be left out. Costs 1 byte.
55
+ * Значение, которого может не быть: при упаковке `undefined` (по типам) или `null` (принимается в рантайме, чтобы
56
+ * данные из JSON не ломались), при чтении `undefined`. В `define` поле можно не указывать. Стоит 1 байт.
57
+ */
58
+ export declare function optional<T>(item: Codec<T>): Codec<T | undefined>;
59
+ /**
60
+ * One of a fixed list of names, stored as its index (1 byte for up to 256 names, else 2).
61
+ * Одно из имён фиксированного списка; хранится индексом (1 байт до 256 имён, иначе 2).
62
+ */
63
+ export declare function enumOf<const N extends readonly string[]>(names: N): Codec<N[number]>;
64
+ export interface QuantOptions {
65
+ /** Clamp out-of-range values into `[min, max]` instead of throwing. `NaN` always throws. */
66
+ clamp?: boolean;
67
+ }
68
+ /**
69
+ * A number in `[min, max]` stored as an unsigned `bits`-bit integer (8, 16 or 32): the error is at most half a
70
+ * step, `(max - min) / (2^bits - 1) / 2`. Positions, angles, ratios.
71
+ * Число из `[min, max]`, хранится беззнаковым целым в `bits` бит (8, 16 или 32): ошибка не больше полушага.
72
+ * Координаты, углы, доли.
73
+ */
74
+ export declare function quant(min: number, max: number, bits: 8 | 16 | 32, options?: QuantOptions): Codec<number>;
75
+ /** The shape passed to `define`: field name to codec. / Описание для `define`: имя поля, кодек. */
76
+ export type Shape = Record<string, Codec<any>>;
77
+ /**
78
+ * Mark a field of a record as added in a newer version of the schema. A packet written by an older writer ends
79
+ * before this field; then the reader fills it with `fallback`. The writer always writes it. Added fields must be
80
+ * the LAST fields of the record, and a record that has any can only be the top-level codec. See docs/spec.md,
81
+ * "Evolution".
82
+ * Пометить поле записи как добавленное в новой версии схемы. Пакет старого писателя кончается до этого поля,
83
+ * тогда читатель подставляет `fallback`. Писатель пишет его всегда. Добавленные поля должны идти ПОСЛЕДНИМИ,
84
+ * а запись с такими полями может быть только верхнего уровня. См. docs/spec.md, «Evolution».
85
+ */
86
+ export declare function added<T>(item: Codec<T>, fallback: T): Codec<T>;
87
+ export interface DefineOptions {
88
+ /**
89
+ * Off by default: a record is STRICT and any byte after its last field is an error. Turn this on to let the
90
+ * record's readers ignore bytes after the last field they know (fields a NEWER writer appended). Declare it
91
+ * from the first version of a message: a reader built without it rejects such packets. `added(...)` does not
92
+ * turn it on. Costs nothing on the wire; the price is that extra bytes are no longer reported as an error.
93
+ * Top-level codec only.
94
+ * По умолчанию выключено: запись СТРОГАЯ, любой байт после последнего поля это ошибка. Включите, чтобы
95
+ * читатели записи игнорировали байты после последнего известного поля (поля, дописанные БОЛЕЕ НОВЫМ
96
+ * писателем). Объявляйте с первой версии сообщения: читатель без этой опции такие пакеты отвергает.
97
+ * `added(...)` её не включает. На проводе бесплатно, но лишние байты больше не ошибка.
98
+ */
99
+ extensible?: boolean;
100
+ }
101
+ /**
102
+ * A record with named fields, written in declaration order. Names are not stored in the packet.
103
+ * Fields wrapped in `added(...)` (at the end) make it evolvable: see `added`.
104
+ * Запись с именованными полями, пишется в порядке объявления. Имена в пакет не попадают.
105
+ * Поля в `added(...)` (в конце) делают запись развиваемой: см. `added`.
106
+ */
107
+ export declare function define<S extends Shape>(shape: S, options?: DefineOptions): Codec<Value<S>>;