@solana/options 2.0.0-experimental.21e994f
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 +20 -0
- package/README.md +25 -0
- package/dist/index.browser.cjs +111 -0
- package/dist/index.browser.cjs.map +1 -0
- package/dist/index.browser.js +99 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/index.development.js +252 -0
- package/dist/index.development.js.map +1 -0
- package/dist/index.native.js +99 -0
- package/dist/index.native.js.map +1 -0
- package/dist/index.node.cjs +111 -0
- package/dist/index.node.cjs.map +1 -0
- package/dist/index.node.js +99 -0
- package/dist/index.node.js.map +1 -0
- package/dist/index.production.min.js +21 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/option-codec.d.ts +42 -0
- package/dist/types/option.d.ts +60 -0
- package/dist/types/unwrap-option-recursively.d.ts +30 -0
- package/dist/types/unwrap-option.d.ts +12 -0
- package/package.json +100 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { fixBytes, mergeBytes, combineCodec, assertFixedSizeCodec } from '@solana/codecs-core';
|
|
2
|
+
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
|
+
|
|
4
|
+
// src/option.ts
|
|
5
|
+
var some = (value) => ({ __option: "Some", value });
|
|
6
|
+
var none = () => ({ __option: "None" });
|
|
7
|
+
var isOption = (input) => !!(input && typeof input === "object" && "__option" in input && (input.__option === "Some" && "value" in input || input.__option === "None"));
|
|
8
|
+
var isSome = (option) => option.__option === "Some";
|
|
9
|
+
var isNone = (option) => option.__option === "None";
|
|
10
|
+
|
|
11
|
+
// src/unwrap-option.ts
|
|
12
|
+
function unwrapOption(option, fallback) {
|
|
13
|
+
if (isSome(option))
|
|
14
|
+
return option.value;
|
|
15
|
+
return fallback ? fallback() : null;
|
|
16
|
+
}
|
|
17
|
+
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
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
|
+
|
|
77
|
+
// src/unwrap-option-recursively.ts
|
|
78
|
+
function unwrapOptionRecursively(input, fallback) {
|
|
79
|
+
if (!input || ArrayBuffer.isView(input)) {
|
|
80
|
+
return input;
|
|
81
|
+
}
|
|
82
|
+
const next = (x) => fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x);
|
|
83
|
+
if (isOption(input)) {
|
|
84
|
+
if (isSome(input))
|
|
85
|
+
return next(input.value);
|
|
86
|
+
return fallback ? fallback() : null;
|
|
87
|
+
}
|
|
88
|
+
if (Array.isArray(input)) {
|
|
89
|
+
return input.map(next);
|
|
90
|
+
}
|
|
91
|
+
if (typeof input === "object") {
|
|
92
|
+
return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)]));
|
|
93
|
+
}
|
|
94
|
+
return input;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { getOptionCodec, getOptionDecoder, getOptionEncoder, isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
98
|
+
//# sourceMappingURL=out.js.map
|
|
99
|
+
//# sourceMappingURL=index.native.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,CAAC,KAAK,SAAU,QAAQ,QAAQ,SAAS,OAAO,OAAO,MAAM,MAAO,CAAkB;AAC9G;AAEA,SAAS,kBAAkB,MAAiB,QAAmB,OAAgB,aAAiC;AAC5G,MAAI,oBAAoB,KAAK,OAAO,WAAW;AAC/C,MAAI,YAAY,KAAK,cAAc,IAAI,OAAO,YAAY;AAC1D,MAAI,OAAO;AACP,yBAAqB,MAAM,wDAAwD;AACnF,yBAAqB,QAAQ,wDAAwD;AACrF,yBAAqB;AACrB,gBAAY,OAAO,YAAY,KAAK;AAAA,EACxC;AAEA,SAAO;AAAA,IACH,aAAa,eAAe,UAAU,KAAK,c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OAAO,MAAM;AACpD,eAAS;AACT,aAAO,CAAC,KAAK,KAAK,GAAG,QAAQ,cAAc,MAAM;AAAA,IACrD;AAAA,EACJ;AACJ;AAQO,SAAS,eACZ,MACA,UAA2C,CAAC,GACP;AACrC,SAAO,aAAa,iBAAoB,MAAM,OAAO,GAAG,iBAAoB,MAAM,OAAO,CAAC;AAC9F;;;AErEO,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 {\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"]}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var codecsCore = require('@solana/codecs-core');
|
|
4
|
+
var codecsNumbers = require('@solana/codecs-numbers');
|
|
5
|
+
|
|
6
|
+
// src/option.ts
|
|
7
|
+
var some = (value) => ({ __option: "Some", value });
|
|
8
|
+
var none = () => ({ __option: "None" });
|
|
9
|
+
var isOption = (input) => !!(input && typeof input === "object" && "__option" in input && (input.__option === "Some" && "value" in input || input.__option === "None"));
|
|
10
|
+
var isSome = (option) => option.__option === "Some";
|
|
11
|
+
var isNone = (option) => option.__option === "None";
|
|
12
|
+
|
|
13
|
+
// src/unwrap-option.ts
|
|
14
|
+
function unwrapOption(option, fallback) {
|
|
15
|
+
if (isSome(option))
|
|
16
|
+
return option.value;
|
|
17
|
+
return fallback ? fallback() : null;
|
|
18
|
+
}
|
|
19
|
+
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
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
|
+
|
|
79
|
+
// src/unwrap-option-recursively.ts
|
|
80
|
+
function unwrapOptionRecursively(input, fallback) {
|
|
81
|
+
if (!input || ArrayBuffer.isView(input)) {
|
|
82
|
+
return input;
|
|
83
|
+
}
|
|
84
|
+
const next = (x) => fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x);
|
|
85
|
+
if (isOption(input)) {
|
|
86
|
+
if (isSome(input))
|
|
87
|
+
return next(input.value);
|
|
88
|
+
return fallback ? fallback() : null;
|
|
89
|
+
}
|
|
90
|
+
if (Array.isArray(input)) {
|
|
91
|
+
return input.map(next);
|
|
92
|
+
}
|
|
93
|
+
if (typeof input === "object") {
|
|
94
|
+
return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)]));
|
|
95
|
+
}
|
|
96
|
+
return input;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
exports.getOptionCodec = getOptionCodec;
|
|
100
|
+
exports.getOptionDecoder = getOptionDecoder;
|
|
101
|
+
exports.getOptionEncoder = getOptionEncoder;
|
|
102
|
+
exports.isNone = isNone;
|
|
103
|
+
exports.isOption = isOption;
|
|
104
|
+
exports.isSome = isSome;
|
|
105
|
+
exports.none = none;
|
|
106
|
+
exports.some = some;
|
|
107
|
+
exports.unwrapOption = unwrapOption;
|
|
108
|
+
exports.unwrapOptionRecursively = unwrapOptionRecursively;
|
|
109
|
+
exports.wrapNullable = wrapNullable;
|
|
110
|
+
//# sourceMappingURL=out.js.map
|
|
111
|
+
//# sourceMappingURL=index.node.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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;AA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AC,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"]}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { fixBytes, mergeBytes, combineCodec, assertFixedSizeCodec } from '@solana/codecs-core';
|
|
2
|
+
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
|
+
|
|
4
|
+
// src/option.ts
|
|
5
|
+
var some = (value) => ({ __option: "Some", value });
|
|
6
|
+
var none = () => ({ __option: "None" });
|
|
7
|
+
var isOption = (input) => !!(input && typeof input === "object" && "__option" in input && (input.__option === "Some" && "value" in input || input.__option === "None"));
|
|
8
|
+
var isSome = (option) => option.__option === "Some";
|
|
9
|
+
var isNone = (option) => option.__option === "None";
|
|
10
|
+
|
|
11
|
+
// src/unwrap-option.ts
|
|
12
|
+
function unwrapOption(option, fallback) {
|
|
13
|
+
if (isSome(option))
|
|
14
|
+
return option.value;
|
|
15
|
+
return fallback ? fallback() : null;
|
|
16
|
+
}
|
|
17
|
+
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
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
|
+
|
|
77
|
+
// src/unwrap-option-recursively.ts
|
|
78
|
+
function unwrapOptionRecursively(input, fallback) {
|
|
79
|
+
if (!input || ArrayBuffer.isView(input)) {
|
|
80
|
+
return input;
|
|
81
|
+
}
|
|
82
|
+
const next = (x) => fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x);
|
|
83
|
+
if (isOption(input)) {
|
|
84
|
+
if (isSome(input))
|
|
85
|
+
return next(input.value);
|
|
86
|
+
return fallback ? fallback() : null;
|
|
87
|
+
}
|
|
88
|
+
if (Array.isArray(input)) {
|
|
89
|
+
return input.map(next);
|
|
90
|
+
}
|
|
91
|
+
if (typeof input === "object") {
|
|
92
|
+
return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)]));
|
|
93
|
+
}
|
|
94
|
+
return input;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { getOptionCodec, getOptionDecoder, getOptionEncoder, isNone, isOption, isSome, none, some, unwrapOption, unwrapOptionRecursively, wrapNullable };
|
|
98
|
+
//# sourceMappingURL=out.js.map
|
|
99
|
+
//# sourceMappingURL=index.node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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,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AAM,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"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
this.globalThis = this.globalThis || {};
|
|
2
|
+
this.globalThis.solanaWeb3 = (function (exports) {
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
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
|
+
|
|
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;
|
|
18
|
+
|
|
19
|
+
return exports;
|
|
20
|
+
|
|
21
|
+
})({});
|
|
@@ -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,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An implementation of the Rust Option type in JavaScript.
|
|
3
|
+
* It can be one of the following:
|
|
4
|
+
* - <code>{@link Some}<T></code>: Meaning there is a value of type T.
|
|
5
|
+
* - <code>{@link None}</code>: Meaning there is no value.
|
|
6
|
+
*/
|
|
7
|
+
export type Option<T> = Some<T> | None;
|
|
8
|
+
/**
|
|
9
|
+
* Defines a looser type that can be used when serializing an {@link Option}.
|
|
10
|
+
* This allows us to pass null or the Option value directly whilst still
|
|
11
|
+
* supporting the Option type for use-cases that need more type safety.
|
|
12
|
+
*/
|
|
13
|
+
export type OptionOrNullable<T> = Option<T> | T | null;
|
|
14
|
+
/**
|
|
15
|
+
* Represents an option of type `T` that has a value.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link Option}
|
|
18
|
+
*/
|
|
19
|
+
export type Some<T> = Readonly<{
|
|
20
|
+
__option: 'Some';
|
|
21
|
+
value: T;
|
|
22
|
+
}>;
|
|
23
|
+
/**
|
|
24
|
+
* Represents an option of type `T` that has no value.
|
|
25
|
+
*
|
|
26
|
+
* @see {@link Option}
|
|
27
|
+
*/
|
|
28
|
+
export type None = Readonly<{
|
|
29
|
+
__option: 'None';
|
|
30
|
+
}>;
|
|
31
|
+
/**
|
|
32
|
+
* Creates a new {@link Option} of type `T` that has a value.
|
|
33
|
+
*
|
|
34
|
+
* @see {@link Option}
|
|
35
|
+
*/
|
|
36
|
+
export declare const some: <T>(value: T) => Option<T>;
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new {@link Option} of type `T` that has no value.
|
|
39
|
+
*
|
|
40
|
+
* @see {@link Option}
|
|
41
|
+
*/
|
|
42
|
+
export declare const none: <T>() => Option<T>;
|
|
43
|
+
/**
|
|
44
|
+
* Whether the given data is an {@link Option}.
|
|
45
|
+
*/
|
|
46
|
+
export declare const isOption: <T = unknown>(input: unknown) => input is Option<T>;
|
|
47
|
+
/**
|
|
48
|
+
* Whether the given {@link Option} is a {@link Some}.
|
|
49
|
+
*/
|
|
50
|
+
export declare const isSome: <T>(option: Option<T>) => option is Readonly<{
|
|
51
|
+
__option: 'Some';
|
|
52
|
+
value: T;
|
|
53
|
+
}>;
|
|
54
|
+
/**
|
|
55
|
+
* Whether the given {@link Option} is a {@link None}.
|
|
56
|
+
*/
|
|
57
|
+
export declare const isNone: <T>(option: Option<T>) => option is Readonly<{
|
|
58
|
+
__option: 'None';
|
|
59
|
+
}>;
|
|
60
|
+
//# sourceMappingURL=option.d.ts.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { None, Some } from './option';
|
|
2
|
+
/**
|
|
3
|
+
* Lists all types that should not be recursively unwrapped.
|
|
4
|
+
*
|
|
5
|
+
* @see {@link UnwrappedOption}
|
|
6
|
+
*/
|
|
7
|
+
type UnUnwrappables = string | number | boolean | symbol | bigint | undefined | null | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Date;
|
|
8
|
+
/**
|
|
9
|
+
* A type that defines the recursive unwrapping of a type `T`
|
|
10
|
+
* such that all nested {@link Option} types are unwrapped.
|
|
11
|
+
*
|
|
12
|
+
* For each nested {@link Option} type, if the option is a {@link Some},
|
|
13
|
+
* it returns the type of its value, otherwise, it returns the provided
|
|
14
|
+
* fallback type `U` which defaults to `null`.
|
|
15
|
+
*/
|
|
16
|
+
export type UnwrappedOption<T, U = null> = T extends Some<infer TValue> ? UnwrappedOption<TValue, U> : T extends None ? U : T extends UnUnwrappables ? T : T extends object ? {
|
|
17
|
+
[key in keyof T]: UnwrappedOption<T[key], U>;
|
|
18
|
+
} : T extends Array<infer TItem> ? Array<UnwrappedOption<TItem, U>> : T;
|
|
19
|
+
/**
|
|
20
|
+
* Recursively go through a type `T` such that all
|
|
21
|
+
* nested {@link Option} types are unwrapped.
|
|
22
|
+
*
|
|
23
|
+
* For each nested {@link Option} type, if the option is a {@link Some},
|
|
24
|
+
* it returns its value, otherwise, it returns the provided fallback value
|
|
25
|
+
* which defaults to `null`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;
|
|
28
|
+
export declare function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;
|
|
29
|
+
export {};
|
|
30
|
+
//# sourceMappingURL=unwrap-option-recursively.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Option } from './option';
|
|
2
|
+
/**
|
|
3
|
+
* Unwraps the value of an {@link Option} of type `T`
|
|
4
|
+
* or returns a fallback value that defaults to `null`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function unwrapOption<T>(option: Option<T>): T | null;
|
|
7
|
+
export declare function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;
|
|
8
|
+
/**
|
|
9
|
+
* Wraps a nullable value into an {@link Option}.
|
|
10
|
+
*/
|
|
11
|
+
export declare const wrapNullable: <T>(nullable: T | null) => Option<T>;
|
|
12
|
+
//# sourceMappingURL=unwrap-option.d.ts.map
|