@solana/options 2.0.0-experimental.f4b7fd3 → 2.0.0-experimental.fc4e943
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/LICENSE +1 -1
- package/dist/index.browser.cjs +64 -0
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +62 -3
- package/dist/index.browser.js.map +1 -1
- package/dist/index.development.js +199 -0
- package/dist/index.development.js.map +1 -1
- package/dist/index.native.js +62 -1
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +64 -0
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +62 -1
- package/dist/index.node.js.map +1 -1
- package/dist/index.production.min.js +12 -9
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/option-codec.d.ts +42 -0
- package/dist/types/option-codec.d.ts.map +1 -0
- package/dist/types/option.d.ts.map +1 -0
- package/dist/types/unwrap-option-recursively.d.ts.map +1 -0
- package/dist/types/unwrap-option.d.ts.map +1 -0
- package/package.json +4 -4
package/LICENSE
CHANGED
package/dist/index.browser.cjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var codecsCore = require('@solana/codecs-core');
|
|
4
|
+
var codecsNumbers = require('@solana/codecs-numbers');
|
|
5
|
+
|
|
3
6
|
// src/option.ts
|
|
4
7
|
var some = (value) => ({ __option: "Some", value });
|
|
5
8
|
var none = () => ({ __option: "None" });
|
|
@@ -15,6 +18,64 @@ function unwrapOption(option, fallback) {
|
|
|
15
18
|
}
|
|
16
19
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
17
20
|
|
|
21
|
+
// src/option-codec.ts
|
|
22
|
+
function sumCodecSizes(sizes) {
|
|
23
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
24
|
+
}
|
|
25
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
26
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
27
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
28
|
+
if (fixed) {
|
|
29
|
+
codecsCore.assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
30
|
+
codecsCore.assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
31
|
+
descriptionSuffix += "; fixed";
|
|
32
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
36
|
+
fixedSize,
|
|
37
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function getOptionEncoder(item, options = {}) {
|
|
41
|
+
const prefix = options.prefix ?? codecsNumbers.getU8Encoder();
|
|
42
|
+
const fixed = options.fixed ?? false;
|
|
43
|
+
return {
|
|
44
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
45
|
+
encode: (optionOrNullable) => {
|
|
46
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
47
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
48
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
49
|
+
itemBytes = fixed ? codecsCore.fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
50
|
+
return codecsCore.mergeBytes([prefixByte, itemBytes]);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function getOptionDecoder(item, options = {}) {
|
|
55
|
+
const prefix = options.prefix ?? codecsNumbers.getU8Decoder();
|
|
56
|
+
const fixed = options.fixed ?? false;
|
|
57
|
+
return {
|
|
58
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
59
|
+
decode: (bytes, offset = 0) => {
|
|
60
|
+
if (bytes.length - offset <= 0) {
|
|
61
|
+
return [none(), offset];
|
|
62
|
+
}
|
|
63
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
64
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
65
|
+
offset = prefixOffset;
|
|
66
|
+
if (isSome2 === 0) {
|
|
67
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
68
|
+
}
|
|
69
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
70
|
+
offset = newOffset;
|
|
71
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function getOptionCodec(item, options = {}) {
|
|
76
|
+
return codecsCore.combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
77
|
+
}
|
|
78
|
+
|
|
18
79
|
// src/unwrap-option-recursively.ts
|
|
19
80
|
function unwrapOptionRecursively(input, fallback) {
|
|
20
81
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -35,6 +96,9 @@ function unwrapOptionRecursively(input, fallback) {
|
|
|
35
96
|
return input;
|
|
36
97
|
}
|
|
37
98
|
|
|
99
|
+
exports.getOptionCodec = getOptionCodec;
|
|
100
|
+
exports.getOptionDecoder = getOptionDecoder;
|
|
101
|
+
exports.getOptionEncoder = getOptionEncoder;
|
|
38
102
|
exports.isNone = isNone;
|
|
39
103
|
exports.isOption = isOption;
|
|
40
104
|
exports.isSome = isSome;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAA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rC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
package/dist/index.browser.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { fixBytes, mergeBytes, combineCodec, assertFixedSizeCodec } from '@solana/codecs-core';
|
|
2
|
+
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
|
+
|
|
1
4
|
// src/option.ts
|
|
2
5
|
var some = (value) => ({ __option: "Some", value });
|
|
3
6
|
var none = () => ({ __option: "None" });
|
|
@@ -13,6 +16,64 @@ function unwrapOption(option, fallback) {
|
|
|
13
16
|
}
|
|
14
17
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
15
18
|
|
|
19
|
+
// src/option-codec.ts
|
|
20
|
+
function sumCodecSizes(sizes) {
|
|
21
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
22
|
+
}
|
|
23
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
24
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
25
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
26
|
+
if (fixed) {
|
|
27
|
+
assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
28
|
+
assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
29
|
+
descriptionSuffix += "; fixed";
|
|
30
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
34
|
+
fixedSize,
|
|
35
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function getOptionEncoder(item, options = {}) {
|
|
39
|
+
const prefix = options.prefix ?? getU8Encoder();
|
|
40
|
+
const fixed = options.fixed ?? false;
|
|
41
|
+
return {
|
|
42
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
43
|
+
encode: (optionOrNullable) => {
|
|
44
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
45
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
46
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
47
|
+
itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
48
|
+
return mergeBytes([prefixByte, itemBytes]);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function getOptionDecoder(item, options = {}) {
|
|
53
|
+
const prefix = options.prefix ?? getU8Decoder();
|
|
54
|
+
const fixed = options.fixed ?? false;
|
|
55
|
+
return {
|
|
56
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
57
|
+
decode: (bytes, offset = 0) => {
|
|
58
|
+
if (bytes.length - offset <= 0) {
|
|
59
|
+
return [none(), offset];
|
|
60
|
+
}
|
|
61
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
62
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
63
|
+
offset = prefixOffset;
|
|
64
|
+
if (isSome2 === 0) {
|
|
65
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
66
|
+
}
|
|
67
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
68
|
+
offset = newOffset;
|
|
69
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function getOptionCodec(item, options = {}) {
|
|
74
|
+
return combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
75
|
+
}
|
|
76
|
+
|
|
16
77
|
// src/unwrap-option-recursively.ts
|
|
17
78
|
function unwrapOptionRecursively(input, fallback) {
|
|
18
79
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -33,6 +94,4 @@ function unwrapOptionRecursively(input, fallback) {
|
|
|
33
94
|
return input;
|
|
34
95
|
}
|
|
35
96
|
|
|
36
|
-
export { isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
37
|
-
//# sourceMappingURL=out.js.map
|
|
38
|
-
//# sourceMappingURL=index.browser.js.map
|
|
97
|
+
export { getOptionCodec, getOptionDecoder, getOptionEncoder, isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9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WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
@@ -9,6 +9,144 @@ this.globalThis.solanaWeb3 = (function (exports) {
|
|
|
9
9
|
var isSome = (option) => option.__option === "Some";
|
|
10
10
|
var isNone = (option) => option.__option === "None";
|
|
11
11
|
|
|
12
|
+
// ../codecs-core/dist/index.browser.js
|
|
13
|
+
function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
|
|
14
|
+
if (bytes.length - offset <= 0) {
|
|
15
|
+
throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
|
|
19
|
+
const bytesLength = bytes.length - offset;
|
|
20
|
+
if (bytesLength < expected) {
|
|
21
|
+
throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function assertFixedSizeCodec(data, message) {
|
|
25
|
+
if (data.fixedSize === null) {
|
|
26
|
+
throw new Error(message ?? "Expected a fixed-size codec, got a variable-size one.");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
var mergeBytes = (byteArrays) => {
|
|
30
|
+
const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);
|
|
31
|
+
if (nonEmptyByteArrays.length === 0) {
|
|
32
|
+
return byteArrays.length ? byteArrays[0] : new Uint8Array();
|
|
33
|
+
}
|
|
34
|
+
if (nonEmptyByteArrays.length === 1) {
|
|
35
|
+
return nonEmptyByteArrays[0];
|
|
36
|
+
}
|
|
37
|
+
const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);
|
|
38
|
+
const result = new Uint8Array(totalLength);
|
|
39
|
+
let offset = 0;
|
|
40
|
+
nonEmptyByteArrays.forEach((arr) => {
|
|
41
|
+
result.set(arr, offset);
|
|
42
|
+
offset += arr.length;
|
|
43
|
+
});
|
|
44
|
+
return result;
|
|
45
|
+
};
|
|
46
|
+
var padBytes = (bytes, length) => {
|
|
47
|
+
if (bytes.length >= length)
|
|
48
|
+
return bytes;
|
|
49
|
+
const paddedBytes = new Uint8Array(length).fill(0);
|
|
50
|
+
paddedBytes.set(bytes);
|
|
51
|
+
return paddedBytes;
|
|
52
|
+
};
|
|
53
|
+
var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
|
|
54
|
+
function combineCodec(encoder, decoder, description) {
|
|
55
|
+
if (encoder.fixedSize !== decoder.fixedSize) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
if (encoder.maxSize !== decoder.maxSize) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
if (description === void 0 && encoder.description !== decoder.description) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
decode: decoder.decode,
|
|
72
|
+
description: description ?? encoder.description,
|
|
73
|
+
encode: encoder.encode,
|
|
74
|
+
fixedSize: encoder.fixedSize,
|
|
75
|
+
maxSize: encoder.maxSize
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ../codecs-numbers/dist/index.browser.js
|
|
80
|
+
function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
|
|
81
|
+
if (value < min || value > max) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function sharedNumberFactory(input) {
|
|
88
|
+
let littleEndian;
|
|
89
|
+
let defaultDescription = input.name;
|
|
90
|
+
if (input.size > 1) {
|
|
91
|
+
littleEndian = !("endian" in input.options) || input.options.endian === 0;
|
|
92
|
+
defaultDescription += littleEndian ? "(le)" : "(be)";
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
description: input.options.description ?? defaultDescription,
|
|
96
|
+
fixedSize: input.size,
|
|
97
|
+
littleEndian,
|
|
98
|
+
maxSize: input.size
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function numberEncoderFactory(input) {
|
|
102
|
+
const codecData = sharedNumberFactory(input);
|
|
103
|
+
return {
|
|
104
|
+
description: codecData.description,
|
|
105
|
+
encode(value) {
|
|
106
|
+
if (input.range) {
|
|
107
|
+
assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
|
|
108
|
+
}
|
|
109
|
+
const arrayBuffer = new ArrayBuffer(input.size);
|
|
110
|
+
input.set(new DataView(arrayBuffer), value, codecData.littleEndian);
|
|
111
|
+
return new Uint8Array(arrayBuffer);
|
|
112
|
+
},
|
|
113
|
+
fixedSize: codecData.fixedSize,
|
|
114
|
+
maxSize: codecData.maxSize
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function numberDecoderFactory(input) {
|
|
118
|
+
const codecData = sharedNumberFactory(input);
|
|
119
|
+
return {
|
|
120
|
+
decode(bytes, offset = 0) {
|
|
121
|
+
assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);
|
|
122
|
+
assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);
|
|
123
|
+
const view = new DataView(toArrayBuffer(bytes, offset, input.size));
|
|
124
|
+
return [input.get(view, codecData.littleEndian), offset + input.size];
|
|
125
|
+
},
|
|
126
|
+
description: codecData.description,
|
|
127
|
+
fixedSize: codecData.fixedSize,
|
|
128
|
+
maxSize: codecData.maxSize
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function toArrayBuffer(bytes, offset, length) {
|
|
132
|
+
const bytesOffset = bytes.byteOffset + (offset ?? 0);
|
|
133
|
+
const bytesLength = length ?? bytes.byteLength;
|
|
134
|
+
return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
|
|
135
|
+
}
|
|
136
|
+
var getU8Encoder = (options = {}) => numberEncoderFactory({
|
|
137
|
+
name: "u8",
|
|
138
|
+
options,
|
|
139
|
+
range: [0, Number("0xff")],
|
|
140
|
+
set: (view, value) => view.setUint8(0, value),
|
|
141
|
+
size: 1
|
|
142
|
+
});
|
|
143
|
+
var getU8Decoder = (options = {}) => numberDecoderFactory({
|
|
144
|
+
get: (view) => view.getUint8(0),
|
|
145
|
+
name: "u8",
|
|
146
|
+
options,
|
|
147
|
+
size: 1
|
|
148
|
+
});
|
|
149
|
+
|
|
12
150
|
// src/unwrap-option.ts
|
|
13
151
|
function unwrapOption(option, fallback) {
|
|
14
152
|
if (isSome(option))
|
|
@@ -17,6 +155,64 @@ this.globalThis.solanaWeb3 = (function (exports) {
|
|
|
17
155
|
}
|
|
18
156
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
19
157
|
|
|
158
|
+
// src/option-codec.ts
|
|
159
|
+
function sumCodecSizes(sizes) {
|
|
160
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
161
|
+
}
|
|
162
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
163
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
164
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
165
|
+
if (fixed) {
|
|
166
|
+
assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
167
|
+
assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
168
|
+
descriptionSuffix += "; fixed";
|
|
169
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
173
|
+
fixedSize,
|
|
174
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function getOptionEncoder(item, options = {}) {
|
|
178
|
+
const prefix = options.prefix ?? getU8Encoder();
|
|
179
|
+
const fixed = options.fixed ?? false;
|
|
180
|
+
return {
|
|
181
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
182
|
+
encode: (optionOrNullable) => {
|
|
183
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
184
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
185
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
186
|
+
itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
187
|
+
return mergeBytes([prefixByte, itemBytes]);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function getOptionDecoder(item, options = {}) {
|
|
192
|
+
const prefix = options.prefix ?? getU8Decoder();
|
|
193
|
+
const fixed = options.fixed ?? false;
|
|
194
|
+
return {
|
|
195
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
196
|
+
decode: (bytes, offset = 0) => {
|
|
197
|
+
if (bytes.length - offset <= 0) {
|
|
198
|
+
return [none(), offset];
|
|
199
|
+
}
|
|
200
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
201
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
202
|
+
offset = prefixOffset;
|
|
203
|
+
if (isSome2 === 0) {
|
|
204
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
205
|
+
}
|
|
206
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
207
|
+
offset = newOffset;
|
|
208
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function getOptionCodec(item, options = {}) {
|
|
213
|
+
return combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
214
|
+
}
|
|
215
|
+
|
|
20
216
|
// src/unwrap-option-recursively.ts
|
|
21
217
|
function unwrapOptionRecursively(input, fallback) {
|
|
22
218
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -37,6 +233,9 @@ this.globalThis.solanaWeb3 = (function (exports) {
|
|
|
37
233
|
return input;
|
|
38
234
|
}
|
|
39
235
|
|
|
236
|
+
exports.getOptionCodec = getOptionCodec;
|
|
237
|
+
exports.getOptionDecoder = getOptionDecoder;
|
|
238
|
+
exports.getOptionEncoder = getOptionEncoder;
|
|
40
239
|
exports.isNone = isNone;
|
|
41
240
|
exports.isOption = isOption;
|
|
42
241
|
exports.isSome = isSome;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../../codecs-core/src/assertions.ts","../../codecs-core/src/bytes.ts","../../codecs-core/src/combine-codec.ts","../../codecs-numbers/src/assertions.ts","../../codecs-numbers/src/f32.ts","../../codecs-numbers/src/utils.ts","../../codecs-numbers/src/u16.ts","../../codecs-numbers/src/u32.ts","../src/unwrap-option.ts","../src/option-codec.ts","../src/unwrap-option-recursively.ts"],"names":["combineCodec","isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ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AO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","/**\n * Asserts that a given number is between a given range.\n */\nexport function assertNumberIsBetweenForCodec(\n codecDescription: string,\n min: number | bigint,\n max: number | bigint,\n value: number | bigint\n) {\n if (value < min || value > max) {\n // TODO: Coded error.\n throw new Error(\n `Codec [${codecDescription}] expected number to be in the range [${min}, ${max}], got ${value}.`\n );\n }\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getF32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'f32',\n options,\n set: (view, value, le) => view.setFloat32(0, value, le),\n size: 4,\n });\n\nexport const getF32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getFloat32(0, le),\n name: 'f32',\n options,\n size: 4,\n });\n\nexport const getF32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getF32Encoder(options), getF32Decoder(options));\n","import {\n assertByteArrayHasEnoughBytesForCodec,\n assertByteArrayIsNotEmptyForCodec,\n CodecData,\n Decoder,\n Encoder,\n} from '@solana/codecs-core';\n\nimport { assertNumberIsBetweenForCodec } from './assertions';\nimport { Endian, NumberCodecOptions, SingleByteNumberCodecOptions } from './common';\n\ntype NumberFactorySharedInput = {\n name: string;\n size: number;\n options: SingleByteNumberCodecOptions | NumberCodecOptions;\n};\n\ntype NumberFactoryEncoderInput<T> = NumberFactorySharedInput & {\n range?: [number | bigint, number | bigint];\n set: (view: DataView, value: T, littleEndian?: boolean) => void;\n};\n\ntype NumberFactoryDecoderInput<T> = NumberFactorySharedInput & {\n get: (view: DataView, littleEndian?: boolean) => T;\n};\n\nfunction sharedNumberFactory(input: NumberFactorySharedInput): CodecData & { littleEndian: boolean | undefined } {\n let littleEndian: boolean | undefined;\n let defaultDescription: string = input.name;\n\n if (input.size > 1) {\n littleEndian = !('endian' in input.options) || input.options.endian === Endian.LITTLE;\n defaultDescription += littleEndian ? '(le)' : '(be)';\n }\n\n return {\n description: input.options.description ?? defaultDescription,\n fixedSize: input.size,\n littleEndian,\n maxSize: input.size,\n };\n}\n\nexport function numberEncoderFactory<T extends number | bigint>(input: NumberFactoryEncoderInput<T>): Encoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n description: codecData.description,\n encode(value: T): Uint8Array {\n if (input.range) {\n assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);\n }\n const arrayBuffer = new ArrayBuffer(input.size);\n input.set(new DataView(arrayBuffer), value, codecData.littleEndian);\n return new Uint8Array(arrayBuffer);\n },\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\nexport function numberDecoderFactory<T extends number | bigint>(input: NumberFactoryDecoderInput<T>): Decoder<T> {\n const codecData = sharedNumberFactory(input);\n\n return {\n decode(bytes, offset = 0): [T, number] {\n assertByteArrayIsNotEmptyForCodec(codecData.description, bytes, offset);\n assertByteArrayHasEnoughBytesForCodec(codecData.description, input.size, bytes, offset);\n const view = new DataView(toArrayBuffer(bytes, offset, input.size));\n return [input.get(view, codecData.littleEndian), offset + input.size];\n },\n description: codecData.description,\n fixedSize: codecData.fixedSize,\n maxSize: codecData.maxSize,\n };\n}\n\n/**\n * Helper function to ensure that the ArrayBuffer is converted properly from a Uint8Array\n * Source: https://stackoverflow.com/questions/37228285/uint8array-to-arraybuffer\n */\nfunction toArrayBuffer(bytes: Uint8Array, offset?: number, length?: number): ArrayBuffer {\n const bytesOffset = bytes.byteOffset + (offset ?? 0);\n const bytesLength = length ?? bytes.byteLength;\n return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);\n}\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU16Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u16',\n options,\n range: [0, Number('0xffff')],\n set: (view, value, le) => view.setUint16(0, value, le),\n size: 2,\n });\n\nexport const getU16Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint16(0, le),\n name: 'u16',\n options,\n size: 2,\n });\n\nexport const getU16Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU16Encoder(options), getU16Decoder(options));\n","import { Codec, combineCodec, Decoder, Encoder } from '@solana/codecs-core';\n\nimport { NumberCodecOptions } from './common';\nimport { numberDecoderFactory, numberEncoderFactory } from './utils';\n\nexport const getU32Encoder = (options: NumberCodecOptions = {}): Encoder<number> =>\n numberEncoderFactory({\n name: 'u32',\n options,\n range: [0, Number('0xffffffff')],\n set: (view, value, le) => view.setUint32(0, value, le),\n size: 4,\n });\n\nexport const getU32Decoder = (options: NumberCodecOptions = {}): Decoder<number> =>\n numberDecoderFactory({\n get: (view, le) => view.getUint32(0, le),\n name: 'u32',\n options,\n size: 4,\n });\n\nexport const getU32Codec = (options: NumberCodecOptions = {}): Codec<number> =>\n combineCodec(getU32Encoder(options), getU32Decoder(options));\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
package/dist/index.native.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { fixBytes, mergeBytes, combineCodec, assertFixedSizeCodec } from '@solana/codecs-core';
|
|
2
|
+
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
|
+
|
|
1
4
|
// src/option.ts
|
|
2
5
|
var some = (value) => ({ __option: "Some", value });
|
|
3
6
|
var none = () => ({ __option: "None" });
|
|
@@ -13,6 +16,64 @@ function unwrapOption(option, fallback) {
|
|
|
13
16
|
}
|
|
14
17
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
15
18
|
|
|
19
|
+
// src/option-codec.ts
|
|
20
|
+
function sumCodecSizes(sizes) {
|
|
21
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
22
|
+
}
|
|
23
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
24
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
25
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
26
|
+
if (fixed) {
|
|
27
|
+
assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
28
|
+
assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
29
|
+
descriptionSuffix += "; fixed";
|
|
30
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
34
|
+
fixedSize,
|
|
35
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function getOptionEncoder(item, options = {}) {
|
|
39
|
+
const prefix = options.prefix ?? getU8Encoder();
|
|
40
|
+
const fixed = options.fixed ?? false;
|
|
41
|
+
return {
|
|
42
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
43
|
+
encode: (optionOrNullable) => {
|
|
44
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
45
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
46
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
47
|
+
itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
48
|
+
return mergeBytes([prefixByte, itemBytes]);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function getOptionDecoder(item, options = {}) {
|
|
53
|
+
const prefix = options.prefix ?? getU8Decoder();
|
|
54
|
+
const fixed = options.fixed ?? false;
|
|
55
|
+
return {
|
|
56
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
57
|
+
decode: (bytes, offset = 0) => {
|
|
58
|
+
if (bytes.length - offset <= 0) {
|
|
59
|
+
return [none(), offset];
|
|
60
|
+
}
|
|
61
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
62
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
63
|
+
offset = prefixOffset;
|
|
64
|
+
if (isSome2 === 0) {
|
|
65
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
66
|
+
}
|
|
67
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
68
|
+
offset = newOffset;
|
|
69
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function getOptionCodec(item, options = {}) {
|
|
74
|
+
return combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
75
|
+
}
|
|
76
|
+
|
|
16
77
|
// src/unwrap-option-recursively.ts
|
|
17
78
|
function unwrapOptionRecursively(input, fallback) {
|
|
18
79
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -33,6 +94,6 @@ function unwrapOptionRecursively(input, fallback) {
|
|
|
33
94
|
return input;
|
|
34
95
|
}
|
|
35
96
|
|
|
36
|
-
export { isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
97
|
+
export { getOptionCodec, getOptionDecoder, getOptionEncoder, isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
37
98
|
//# sourceMappingURL=out.js.map
|
|
38
99
|
//# sourceMappingURL=index.native.js.map
|
package/dist/index.native.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9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WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
package/dist/index.node.cjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var codecsCore = require('@solana/codecs-core');
|
|
4
|
+
var codecsNumbers = require('@solana/codecs-numbers');
|
|
5
|
+
|
|
3
6
|
// src/option.ts
|
|
4
7
|
var some = (value) => ({ __option: "Some", value });
|
|
5
8
|
var none = () => ({ __option: "None" });
|
|
@@ -15,6 +18,64 @@ function unwrapOption(option, fallback) {
|
|
|
15
18
|
}
|
|
16
19
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
17
20
|
|
|
21
|
+
// src/option-codec.ts
|
|
22
|
+
function sumCodecSizes(sizes) {
|
|
23
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
24
|
+
}
|
|
25
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
26
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
27
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
28
|
+
if (fixed) {
|
|
29
|
+
codecsCore.assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
30
|
+
codecsCore.assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
31
|
+
descriptionSuffix += "; fixed";
|
|
32
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
36
|
+
fixedSize,
|
|
37
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function getOptionEncoder(item, options = {}) {
|
|
41
|
+
const prefix = options.prefix ?? codecsNumbers.getU8Encoder();
|
|
42
|
+
const fixed = options.fixed ?? false;
|
|
43
|
+
return {
|
|
44
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
45
|
+
encode: (optionOrNullable) => {
|
|
46
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
47
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
48
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
49
|
+
itemBytes = fixed ? codecsCore.fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
50
|
+
return codecsCore.mergeBytes([prefixByte, itemBytes]);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function getOptionDecoder(item, options = {}) {
|
|
55
|
+
const prefix = options.prefix ?? codecsNumbers.getU8Decoder();
|
|
56
|
+
const fixed = options.fixed ?? false;
|
|
57
|
+
return {
|
|
58
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
59
|
+
decode: (bytes, offset = 0) => {
|
|
60
|
+
if (bytes.length - offset <= 0) {
|
|
61
|
+
return [none(), offset];
|
|
62
|
+
}
|
|
63
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
64
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
65
|
+
offset = prefixOffset;
|
|
66
|
+
if (isSome2 === 0) {
|
|
67
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
68
|
+
}
|
|
69
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
70
|
+
offset = newOffset;
|
|
71
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function getOptionCodec(item, options = {}) {
|
|
76
|
+
return codecsCore.combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
77
|
+
}
|
|
78
|
+
|
|
18
79
|
// src/unwrap-option-recursively.ts
|
|
19
80
|
function unwrapOptionRecursively(input, fallback) {
|
|
20
81
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -35,6 +96,9 @@ function unwrapOptionRecursively(input, fallback) {
|
|
|
35
96
|
return input;
|
|
36
97
|
}
|
|
37
98
|
|
|
99
|
+
exports.getOptionCodec = getOptionCodec;
|
|
100
|
+
exports.getOptionDecoder = getOptionDecoder;
|
|
101
|
+
exports.getOptionEncoder = getOptionEncoder;
|
|
38
102
|
exports.isNone = isNone;
|
|
39
103
|
exports.isOption = isOption;
|
|
40
104
|
exports.isSome = isSome;
|
package/dist/index.node.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9DpF;AAAA,EACI;AAAA,EAIA;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc,oBAA+D;;;ACH/E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,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AAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
package/dist/index.node.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { fixBytes, mergeBytes, combineCodec, assertFixedSizeCodec } from '@solana/codecs-core';
|
|
2
|
+
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
|
+
|
|
1
4
|
// src/option.ts
|
|
2
5
|
var some = (value) => ({ __option: "Some", value });
|
|
3
6
|
var none = () => ({ __option: "None" });
|
|
@@ -13,6 +16,64 @@ function unwrapOption(option, fallback) {
|
|
|
13
16
|
}
|
|
14
17
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
15
18
|
|
|
19
|
+
// src/option-codec.ts
|
|
20
|
+
function sumCodecSizes(sizes) {
|
|
21
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
22
|
+
}
|
|
23
|
+
function optionCodecHelper(item, prefix, fixed, description) {
|
|
24
|
+
let descriptionSuffix = `; ${prefix.description}`;
|
|
25
|
+
let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;
|
|
26
|
+
if (fixed) {
|
|
27
|
+
assertFixedSizeCodec(item, "Fixed options can only be used with fixed-size codecs.");
|
|
28
|
+
assertFixedSizeCodec(prefix, "Fixed options can only be used with fixed-size prefix.");
|
|
29
|
+
descriptionSuffix += "; fixed";
|
|
30
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
description: description ?? `option(${item.description + descriptionSuffix})`,
|
|
34
|
+
fixedSize,
|
|
35
|
+
maxSize: sumCodecSizes([prefix.maxSize, item.maxSize])
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function getOptionEncoder(item, options = {}) {
|
|
39
|
+
const prefix = options.prefix ?? getU8Encoder();
|
|
40
|
+
const fixed = options.fixed ?? false;
|
|
41
|
+
return {
|
|
42
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
43
|
+
encode: (optionOrNullable) => {
|
|
44
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
45
|
+
const prefixByte = prefix.encode(Number(isSome(option)));
|
|
46
|
+
let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();
|
|
47
|
+
itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize) : itemBytes;
|
|
48
|
+
return mergeBytes([prefixByte, itemBytes]);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function getOptionDecoder(item, options = {}) {
|
|
53
|
+
const prefix = options.prefix ?? getU8Decoder();
|
|
54
|
+
const fixed = options.fixed ?? false;
|
|
55
|
+
return {
|
|
56
|
+
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
57
|
+
decode: (bytes, offset = 0) => {
|
|
58
|
+
if (bytes.length - offset <= 0) {
|
|
59
|
+
return [none(), offset];
|
|
60
|
+
}
|
|
61
|
+
const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);
|
|
62
|
+
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
63
|
+
offset = prefixOffset;
|
|
64
|
+
if (isSome2 === 0) {
|
|
65
|
+
return [none(), fixed ? fixedOffset : offset];
|
|
66
|
+
}
|
|
67
|
+
const [value, newOffset] = item.decode(bytes, offset);
|
|
68
|
+
offset = newOffset;
|
|
69
|
+
return [some(value), fixed ? fixedOffset : offset];
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function getOptionCodec(item, options = {}) {
|
|
74
|
+
return combineCodec(getOptionEncoder(item, options), getOptionDecoder(item, options));
|
|
75
|
+
}
|
|
76
|
+
|
|
16
77
|
// src/unwrap-option-recursively.ts
|
|
17
78
|
function unwrapOptionRecursively(input, fallback) {
|
|
18
79
|
if (!input || ArrayBuffer.isView(input)) {
|
|
@@ -33,6 +94,6 @@ function unwrapOptionRecursively(input, fallback) {
|
|
|
33
94
|
return input;
|
|
34
95
|
}
|
|
35
96
|
|
|
36
|
-
export { isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
97
|
+
export { getOptionCodec, getOptionDecoder, getOptionEncoder, isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
37
98
|
//# sourceMappingURL=out.js.map
|
|
38
99
|
//# sourceMappingURL=index.node.js.map
|
package/dist/index.node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":[],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;ACtD7E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ACqCzG,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9DpF;AAAA,EACI;AAAA,EAIA;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc,oBAA+D;;;ACH/E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ADmBhH,SAAS,cAAc,OAAyC;AAC5D,SAAO,MAAM,OAAO,CAA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type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
@@ -2,16 +2,19 @@ this.globalThis = this.globalThis || {};
|
|
|
2
2
|
this.globalThis.solanaWeb3 = (function (exports) {
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
5
|
-
var
|
|
5
|
+
var p=e=>({__option:"Some",value:e}),s=()=>({__option:"None"}),u=e=>!!(e&&typeof e=="object"&&"__option"in e&&(e.__option==="Some"&&"value"in e||e.__option==="None")),f=e=>e.__option==="Some",L=e=>e.__option==="None";function m(e,n,t=0){if(n.length-t<=0)throw new Error(`Codec [${e}] cannot decode empty byte arrays.`)}function l(e,n,t,r=0){let o=t.length-r;if(o<n)throw new Error(`Codec [${e}] expected ${n} bytes, got ${o}.`)}function g(e,n){if(e.fixedSize===null)throw new Error(n??"Expected a fixed-size codec, got a variable-size one.")}var z=e=>{let n=e.filter(i=>i.length);if(n.length===0)return e.length?e[0]:new Uint8Array;if(n.length===1)return n[0];let t=n.reduce((i,a)=>i+a.length,0),r=new Uint8Array(t),o=0;return n.forEach(i=>{r.set(i,o),o+=i.length;}),r},E=(e,n)=>{if(e.length>=n)return e;let t=new Uint8Array(n).fill(0);return t.set(e),t},U=(e,n)=>E(e.length<=n?e:e.slice(0,n),n);function x(e,n,t){if(e.fixedSize!==n.fixedSize)throw new Error(`Encoder and decoder must have the same fixed size, got [${e.fixedSize}] and [${n.fixedSize}].`);if(e.maxSize!==n.maxSize)throw new Error(`Encoder and decoder must have the same max size, got [${e.maxSize}] and [${n.maxSize}].`);if(t===void 0&&e.description!==n.description)throw new Error(`Encoder and decoder must have the same description, got [${e.description}] and [${n.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`);return {decode:n.decode,description:t??e.description,encode:e.encode,fixedSize:e.fixedSize,maxSize:e.maxSize}}function B(e,n,t,r){if(r<n||r>t)throw new Error(`Codec [${e}] expected number to be in the range [${n}, ${t}], got ${r}.`)}function T(e){let n,t=e.name;return e.size>1&&(n=!("endian"in e.options)||e.options.endian===0,t+=n?"(le)":"(be)"),{description:e.options.description??t,fixedSize:e.size,littleEndian:n,maxSize:e.size}}function b(e){let n=T(e);return {description:n.description,encode(t){e.range&&B(e.name,e.range[0],e.range[1],t);let r=new ArrayBuffer(e.size);return e.set(new DataView(r),t,n.littleEndian),new Uint8Array(r)},fixedSize:n.fixedSize,maxSize:n.maxSize}}function N(e){let n=T(e);return {decode(t,r=0){m(n.description,t,r),l(n.description,e.size,t,r);let o=new DataView(D(t,r,e.size));return [e.get(o,n.littleEndian),r+e.size]},description:n.description,fixedSize:n.fixedSize,maxSize:n.maxSize}}function D(e,n,t){let r=e.byteOffset+(n??0),o=t??e.byteLength;return e.buffer.slice(r,r+o)}var S=(e={})=>b({name:"u8",options:e,range:[0,+"0xff"],set:(n,t)=>n.setUint8(0,t),size:1}),O=(e={})=>N({get:n=>n.getUint8(0),name:"u8",options:e,size:1});function q(e,n){return f(e)?e.value:n?n():null}var v=e=>e!==null?p(e):s();function A(e){return e.reduce((n,t)=>n===null||t===null?null:n+t,0)}function w(e,n,t,r){let o=`; ${n.description}`,i=e.fixedSize===0?n.fixedSize:null;return t&&(g(e,"Fixed options can only be used with fixed-size codecs."),g(n,"Fixed options can only be used with fixed-size prefix."),o+="; fixed",i=n.fixedSize+e.fixedSize),{description:r??`option(${e.description+o})`,fixedSize:i,maxSize:A([n.maxSize,e.maxSize])}}function _(e,n={}){let t=n.prefix??S(),r=n.fixed??!1;return {...w(e,t,r,n.description),encode:o=>{let i=u(o)?o:v(o),a=t.encode(Number(f(i))),c=f(i)?e.encode(i.value):new Uint8Array;return c=r?U(c,e.fixedSize):c,z([a,c])}}}function F(e,n={}){let t=n.prefix??O(),r=n.fixed??!1;return {...w(e,t,r,n.description),decode:(o,i=0)=>{if(o.length-i<=0)return [s(),i];let a=i+(t.fixedSize??0)+(e.fixedSize??0),[c,C]=t.decode(o,i);if(i=C,c===0)return [s(),r?a:i];let[y,I]=e.decode(o,i);return i=I,[p(y),r?a:i]}}}function se(e,n={}){return x(_(e,n),F(e,n))}function h(e,n){if(!e||ArrayBuffer.isView(e))return e;let t=r=>n?h(r,n):h(r);return u(e)?f(e)?t(e.value):n?n():null:Array.isArray(e)?e.map(t):typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,t(o)])):e}
|
|
6
6
|
|
|
7
|
-
exports.
|
|
8
|
-
exports.
|
|
9
|
-
exports.
|
|
10
|
-
exports.
|
|
11
|
-
exports.
|
|
12
|
-
exports.
|
|
13
|
-
exports.
|
|
14
|
-
exports.
|
|
7
|
+
exports.getOptionCodec = se;
|
|
8
|
+
exports.getOptionDecoder = F;
|
|
9
|
+
exports.getOptionEncoder = _;
|
|
10
|
+
exports.isNone = L;
|
|
11
|
+
exports.isOption = u;
|
|
12
|
+
exports.isSome = f;
|
|
13
|
+
exports.none = s;
|
|
14
|
+
exports.some = p;
|
|
15
|
+
exports.unwrapOption = q;
|
|
16
|
+
exports.unwrapOptionRecursively = h;
|
|
17
|
+
exports.wrapNullable = v;
|
|
15
18
|
|
|
16
19
|
return exports;
|
|
17
20
|
|
package/dist/types/index.d.ts
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,6BAA6B,CAAC"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { BaseCodecOptions, Codec, Decoder, Encoder } from '@solana/codecs-core';
|
|
2
|
+
import { NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';
|
|
3
|
+
import { Option, OptionOrNullable } from './option';
|
|
4
|
+
/** Defines the options for option codecs. */
|
|
5
|
+
export type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {
|
|
6
|
+
/**
|
|
7
|
+
* The codec to use for the boolean prefix.
|
|
8
|
+
* @defaultValue u8 prefix.
|
|
9
|
+
*/
|
|
10
|
+
prefix?: TPrefix;
|
|
11
|
+
/**
|
|
12
|
+
* Whether the item codec should be of fixed size.
|
|
13
|
+
*
|
|
14
|
+
* When this is true, a `None` value will skip the bytes that would
|
|
15
|
+
* have been used for the item. Note that this will only work if the
|
|
16
|
+
* item codec is of fixed size.
|
|
17
|
+
* @defaultValue `false`
|
|
18
|
+
*/
|
|
19
|
+
fixed?: boolean;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Creates a encoder for an optional value using `null` as the `None` value.
|
|
23
|
+
*
|
|
24
|
+
* @param item - The encoder to use for the value that may be present.
|
|
25
|
+
* @param options - A set of options for the encoder.
|
|
26
|
+
*/
|
|
27
|
+
export declare function getOptionEncoder<T>(item: Encoder<T>, options?: OptionCodecOptions<NumberEncoder>): Encoder<OptionOrNullable<T>>;
|
|
28
|
+
/**
|
|
29
|
+
* Creates a decoder for an optional value using `null` as the `None` value.
|
|
30
|
+
*
|
|
31
|
+
* @param item - The decoder to use for the value that may be present.
|
|
32
|
+
* @param options - A set of options for the decoder.
|
|
33
|
+
*/
|
|
34
|
+
export declare function getOptionDecoder<T>(item: Decoder<T>, options?: OptionCodecOptions<NumberDecoder>): Decoder<Option<T>>;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a codec for an optional value using `null` as the `None` value.
|
|
37
|
+
*
|
|
38
|
+
* @param item - The codec to use for the value that may be present.
|
|
39
|
+
* @param options - A set of options for the codec.
|
|
40
|
+
*/
|
|
41
|
+
export declare function getOptionCodec<T, U extends T = T>(item: Codec<T, U>, options?: OptionCodecOptions<NumberCodec>): Codec<OptionOrNullable<T>, Option<U>>;
|
|
42
|
+
//# sourceMappingURL=option-codec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"option-codec.d.ts","sourceRoot":"","sources":["../../src/option-codec.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,gBAAgB,EAChB,KAAK,EAGL,OAAO,EACP,OAAO,EAGV,MAAM,qBAAqB,CAAC;AAC7B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SAAS,IAAI,GACd,CAAC,GACD,CAAC,SAAS,cAAc,GACxB,CAAC,GACD,CAAC,SAAS,MAAM,GAChB;KAAG,GAAG,IAAI,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;CAAE,GAChD,CAAC,SAAS,KAAK,CAAC,MAAM,KAAK,CAAC,GAC5B,KAAK,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,GAChC,CAAC,CAAC;AAER;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;AACzE,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unwrap-option.d.ts","sourceRoot":"","sources":["../../src/unwrap-option.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAQ,MAAM,UAAU,CAAC;AAEtD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAC7D,wBAAgB,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAMhF;;GAEG;AACH,eAAO,MAAM,YAAY,sCAAyF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solana/options",
|
|
3
|
-
"version": "2.0.0-experimental.
|
|
3
|
+
"version": "2.0.0-experimental.fc4e943",
|
|
4
4
|
"description": "Managing and serializing Rust-like Option types in JavaScript",
|
|
5
5
|
"exports": {
|
|
6
6
|
"browser": {
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
"node": ">=17.4"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@solana/codecs-core": "2.0.0-experimental.
|
|
53
|
-
"@solana/codecs-numbers": "2.0.0-experimental.
|
|
52
|
+
"@solana/codecs-core": "2.0.0-experimental.fc4e943",
|
|
53
|
+
"@solana/codecs-numbers": "2.0.0-experimental.fc4e943"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@solana/eslint-config-solana": "^1.0.2",
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"compile:typedefs": "tsc -p ./tsconfig.declarations.json",
|
|
88
88
|
"dev": "jest -c node_modules/test-config/jest-dev.config.ts --rootDir . --watch",
|
|
89
89
|
"publish-packages": "pnpm publish --tag experimental --access public --no-git-checks",
|
|
90
|
-
"style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/*",
|
|
90
|
+
"style:fix": "pnpm eslint --fix src/* && pnpm prettier -w src/* package.json",
|
|
91
91
|
"test:lint": "jest -c node_modules/test-config/jest-lint.config.ts --rootDir . --silent",
|
|
92
92
|
"test:prettier": "jest -c node_modules/test-config/jest-prettier.config.ts --rootDir . --silent",
|
|
93
93
|
"test:treeshakability:browser": "agadoo dist/index.browser.js",
|