blob: e7cdecdbab5e91d7ab1b5903c7760b18ef6ba520 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
import { Ok, Error, CustomType } from './gleam.mjs'
import { bit_string_to_string } from '../../gleam_stdlib/dist/gleam_stdlib.mjs'
export class DecodeError extends CustomType {
get __gleam_prelude_variant__() {
return "DecodeError";
}
}
export class UnexpectedEndOfInput extends CustomType {
static isInstance(err) {
return err.message === 'Unexpected end of JSON input'
}
get __gleam_prelude_variant__() {
return "UnexpectedEndOfInput"
}
}
export class UnexpectedByte extends CustomType {
static regex = /Unexpected token (.) in JSON at position (\d+)/
static isInstance(err) {
return this.regex.test(err)
}
constructor(err) {
super()
const match = UnexpectedByte.regex.exec(err.message)
this.byte = "0x" + match[1].charCodeAt(0).toString(16).toUpperCase()
this.position = Number(match[2])
}
get __gleam_prelude_variant__() {
return `UnexpectedByte`;
}
}
export class UnexpectedSequence extends CustomType {
static isInstance(err) {
return false
}
get __gleam_prelude_variant__() {
return "UnexpectedSequence";
}
}
export class UnexpectedFormat extends CustomType {
static isInstance(err) {
return false
}
constructor(decodeErrs) {
super()
this[0] = decodeErrs
}
get __gleam_prelude_variant__() {
return "UnexpectedFormat";
}
}
export function json_to_string(json) {
return JSON.stringify(json)
}
export function object_from(entries) {
return Object.fromEntries(entries)
}
export function array(list) {
return list.toArray()
}
export function do_null() {
return null
}
export function identity(x) {
return x
}
export function decode(bit_string) {
const stringResult = bit_string_to_string(bit_string)
if (!stringResult.isOk()) return stringResult
try {
const result = JSON.parse(stringResult[0])
return new Ok(result)
} catch (err) {
return getJsonDecodeError(err)
}
}
function getJsonDecodeError(stdErr) {
const ErrClass = [
UnexpectedByte,
UnexpectedEndOfInput,
UnexpectedFormat,
UnexpectedSequence,
].find((klass) => klass.isInstance(stdErr))
if (ErrClass) return new Error(new ErrClass(stdErr))
else return new Error()
}
|