| 1 |
/* ************************************************************************ */ |
| 2 |
/* */ |
| 3 |
/* This file is part of Frama-C. */ |
| 4 |
/* */ |
| 5 |
/* Copyright (C) 2007-2022 */ |
| 6 |
/* CEA (Commissariat à l'énergie atomique et aux énergies */ |
| 7 |
/* alternatives) */ |
| 8 |
/* */ |
| 9 |
/* you can redistribute it and/or modify it under the terms of the GNU */ |
| 10 |
/* Lesser General Public License as published by the Free Software */ |
| 11 |
/* Foundation, version 2.1. */ |
| 12 |
/* */ |
| 13 |
/* It is distributed in the hope that it will be useful, */ |
| 14 |
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ |
| 15 |
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ |
| 16 |
/* GNU Lesser General Public License for more details. */ |
| 17 |
/* */ |
| 18 |
/* See the GNU Lesser General Public License version 2.1 */ |
| 19 |
/* for more details (enclosed in the file licenses/LGPLv2.1). */ |
| 20 |
/* */ |
| 21 |
/* ************************************************************************ */ |
| 22 |
|
| 23 |
/* eslint-disable @typescript-eslint/no-explicit-any, no-console */ |
| 24 |
|
| 25 |
// -------------------------------------------------------------------------- |
| 26 |
// --- JSON Utilities |
| 27 |
// -------------------------------------------------------------------------- |
| 28 |
|
| 29 |
/** |
| 30 |
Safe JSON utilities. |
| 31 |
@packageDocumentation |
| 32 |
@module dome/data/json |
| 33 |
*/ |
| 34 |
|
| 35 |
import { DEVEL } from 'dome/system'; |
| 36 |
|
| 37 |
export type json = |
| 38 |
undefined | null | boolean | number | string | |
| 39 |
json[] | { [key: string]: json }; |
| 40 |
|
| 41 |
export type jobject = { [key: string]: json }; |
| 42 |
|
| 43 |
/** |
| 44 |
Parse without _revivals_. |
| 45 |
Returned data is guaranteed to have only [[json]] type. |
| 46 |
If an error occurs and `noError` is set to `true`, |
| 47 |
the function returns `undefined` and logs the error in console |
| 48 |
(DEVEL mode only). |
| 49 |
*/ |
| 50 |
export function parse(text: string, noError = false): json { |
| 51 |
if (noError) { |
| 52 |
try { |
| 53 |
return JSON.parse(text); |
| 54 |
} catch (err) { |
| 55 |
if (DEVEL) console.error('[Dome.json] Invalid format:', err); |
| 56 |
return undefined; |
| 57 |
} |
| 58 |
} else |
| 59 |
return JSON.parse(text); |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
Export JSON (or any data) as a compact string. |
| 64 |
*/ |
| 65 |
export function stringify(js: any): string { |
| 66 |
return JSON.stringify(js, undefined, 0); |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
Export JSON (or any data) as a string with indentation. |
| 71 |
*/ |
| 72 |
export function pretty(js: any): string { |
| 73 |
return JSON.stringify(js, undefined, 2); |
| 74 |
} |
| 75 |
|
| 76 |
// -------------------------------------------------------------------------- |
| 77 |
// --- SAFE Decoder |
| 78 |
// -------------------------------------------------------------------------- |
| 79 |
|
| 80 |
/** Decoder for values of type `D`. |
| 81 |
You can abbreviate `Safe<D | undefined>` with `Loose<D>`. */ |
| 82 |
export interface Safe<D> { |
| 83 |
(js?: json): D; |
| 84 |
} |
| 85 |
|
| 86 |
/** Decoder for values of type `D`, if any. |
| 87 |
Same as `Safe<D | undefined>`. */ |
| 88 |
export interface Loose<D> { |
| 89 |
(js?: json): D | undefined; |
| 90 |
} |
| 91 |
|
| 92 |
/** |
| 93 |
Encoder for value of type `D`. |
| 94 |
In most cases, you only need [[identity]]. |
| 95 |
*/ |
| 96 |
export interface Encoder<D> { |
| 97 |
(v: D): json; |
| 98 |
} |
| 99 |
|
| 100 |
/** Can be used for most encoders. */ |
| 101 |
export function identity<A>(v: A): A { return v; } |
| 102 |
|
| 103 |
// -------------------------------------------------------------------------- |
| 104 |
// --- Primitives |
| 105 |
// -------------------------------------------------------------------------- |
| 106 |
|
| 107 |
/** 'null' or 'undefined'. */ |
| 108 |
export const jNull: Loose<null> = (js: json) => |
| 109 |
js === null ? null : undefined; |
| 110 |
|
| 111 |
/** Identity. */ |
| 112 |
export const jAny: Safe<json> = (js: json) => js; |
| 113 |
|
| 114 |
/** JSON Object. */ |
| 115 |
export const jObj: Loose<jobject> = (js: json) => ( |
| 116 |
typeof js === 'object' && !Array.isArray(js) && js !== null ? js : undefined |
| 117 |
); |
| 118 |
|
| 119 |
/** Primitive JSON number or `undefined`. */ |
| 120 |
export const jNumber: Loose<number> = (js: json) => ( |
| 121 |
typeof js === 'number' && !Number.isNaN(js) ? js : undefined |
| 122 |
); |
| 123 |
|
| 124 |
/** Primitive JSON number, rounded to integer, or `undefined`. */ |
| 125 |
export const jInt: Loose<number> = (js: json) => ( |
| 126 |
typeof js === 'number' && !Number.isNaN(js) ? Math.round(js) : undefined |
| 127 |
); |
| 128 |
|
| 129 |
/** Primitive JSON number or `0`. */ |
| 130 |
export const jZero: Safe<number> = (js: json) => ( |
| 131 |
typeof js === 'number' && !Number.isNaN(js) ? js : 0 |
| 132 |
); |
| 133 |
|
| 134 |
/** Primitive JSON boolean or `undefined`. */ |
| 135 |
export const jBoolean: Loose<boolean> = (js: json) => ( |
| 136 |
typeof js === 'boolean' ? js : undefined |
| 137 |
); |
| 138 |
|
| 139 |
/** Primitive JSON boolean or `true`. */ |
| 140 |
export const jTrue: Safe<boolean> = (js: json) => ( |
| 141 |
typeof js === 'boolean' ? js : true |
| 142 |
); |
| 143 |
|
| 144 |
/** Primitive JSON boolean or `false`. */ |
| 145 |
export const jFalse: Safe<boolean> = (js: json) => ( |
| 146 |
typeof js === 'boolean' ? js : false |
| 147 |
); |
| 148 |
|
| 149 |
/** Primitive JSON string or `undefined`. */ |
| 150 |
export const jString: Loose<string> = (js: json) => ( |
| 151 |
typeof js === 'string' ? js : undefined |
| 152 |
); |
| 153 |
|
| 154 |
/** JSON constant. |
| 155 |
Capture the tag or returns `undefined`. |
| 156 |
Can be used with [[jUnion]], although [[jEnum]] |
| 157 |
might be more efficient. |
| 158 |
*/ |
| 159 |
export function jTag<A>(tg: A): Loose<A> { |
| 160 |
return (js: json) => (Object.is(js, tg) ? tg : undefined); |
| 161 |
} |
| 162 |
|
| 163 |
/** |
| 164 |
Lookup tags in a dictionary. |
| 165 |
Can be used directly for enum types, eg. `jEnum(myEnumType)`. |
| 166 |
*/ |
| 167 |
export function jEnum<A>(d: { [tag: string]: A }): Loose<A> { |
| 168 |
return (v: json) => (typeof v === 'string' ? d[v] : undefined); |
| 169 |
} |
| 170 |
|
| 171 |
/** |
| 172 |
One of the enumerated _constants_ or `undefined`. |
| 173 |
The typechecker will prevent you from listing values that are not in |
| 174 |
type `A`. However, it will not protected you from missings constants in `A`. |
| 175 |
*/ |
| 176 |
export function jTags<A>(...values: ((string | number) & A)[]): Loose<A> { |
| 177 |
const m = new Map<string | number, A>(); |
| 178 |
values.forEach((v) => m.set(v, v)); |
| 179 |
return (v: json) => (typeof v === 'string' ? m.get(v) : undefined); |
| 180 |
} |
| 181 |
|
| 182 |
/** |
| 183 |
Refine a loose decoder with some default value. |
| 184 |
The default value is returned when the provided JSON is `undefined` or |
| 185 |
when the loose decoder returns `undefined`. |
| 186 |
*/ |
| 187 |
export function jDefault<A>( |
| 188 |
fn: Loose<A>, |
| 189 |
defaultValue: A, |
| 190 |
): Safe<A> { |
| 191 |
return (js: json) => ( |
| 192 |
js === undefined ? defaultValue : (fn(js) ?? defaultValue) |
| 193 |
); |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
Force returning `undefined` or a default value for |
| 198 |
`undefined` _or_ `null` JSON input. |
| 199 |
Typically useful to leverage an existing `Safe<A>` decoder. |
| 200 |
*/ |
| 201 |
export function jOption<A>(fn: Safe<A>, defaultValue?: A): Loose<A> { |
| 202 |
return (js: json) => ( |
| 203 |
js === undefined || js === null ? defaultValue : fn(js) |
| 204 |
); |
| 205 |
} |
| 206 |
|
| 207 |
/** |
| 208 |
Fail when the loose decoder returns `undefined`. |
| 209 |
See also [[jCatch]] and [[jTry]]. |
| 210 |
*/ |
| 211 |
export function jFail<A>(fn: Loose<A>, error: string | Error): Safe<A> { |
| 212 |
return (js: json) => { |
| 213 |
const d = fn(js); |
| 214 |
if (d !== undefined) return d; |
| 215 |
throw (typeof (error) === 'string' ? new Error(error) : error); |
| 216 |
}; |
| 217 |
} |
| 218 |
|
| 219 |
/** |
| 220 |
Provide a fallback value in case of undefined value or error. |
| 221 |
See also [[jFail]] and [[jTry]]. |
| 222 |
*/ |
| 223 |
export function jCatch<A>(fn: Loose<A>, fallBack: A): Safe<A> { |
| 224 |
return (js: json) => { |
| 225 |
try { |
| 226 |
return fn(js) ?? fallBack; |
| 227 |
} catch (err) { |
| 228 |
if (DEVEL) console.warn('[Dome.json]', err); |
| 229 |
return fallBack; |
| 230 |
} |
| 231 |
}; |
| 232 |
} |
| 233 |
|
| 234 |
/** |
| 235 |
Provides an (optional) default value in case of error or undefined value. |
| 236 |
See also [[jFail]] and [[jCatch]]. |
| 237 |
*/ |
| 238 |
export function jTry<A>(fn: Loose<A>, defaultValue?: A): Loose<A> { |
| 239 |
return (js: json) => { |
| 240 |
try { |
| 241 |
return fn(js) ?? defaultValue; |
| 242 |
} catch (err) { |
| 243 |
if (DEVEL) console.warn('[Dome.json]', err); |
| 244 |
return defaultValue; |
| 245 |
} |
| 246 |
}; |
| 247 |
} |
| 248 |
|
| 249 |
/** |
| 250 |
Converts maps to dictionaries. |
| 251 |
*/ |
| 252 |
export function jMap<A>(fn: Loose<A>): Safe<Map<string, A>> { |
| 253 |
return (js: json) => { |
| 254 |
const m = new Map<string, A>(); |
| 255 |
if (js !== null && typeof js === 'object' && !Array.isArray(js)) { |
| 256 |
const keys = Object.keys(js); |
| 257 |
keys.forEach((k) => { |
| 258 |
const v = fn(js[k]); |
| 259 |
if (v !== undefined) m.set(k, v); |
| 260 |
}); |
| 261 |
} |
| 262 |
return m; |
| 263 |
}; |
| 264 |
} |
| 265 |
|
| 266 |
/** |
| 267 |
Converts dictionaries to maps. |
| 268 |
*/ |
| 269 |
export function eMap<A>(fn: Encoder<A>): Encoder<Map<string, undefined | A>> { |
| 270 |
return (m) => { |
| 271 |
const js: json = {}; |
| 272 |
m.forEach((v, k) => { |
| 273 |
if (v !== undefined) { |
| 274 |
const u = fn(v); |
| 275 |
if (u !== undefined) js[k] = u; |
| 276 |
} |
| 277 |
}); |
| 278 |
return js; |
| 279 |
}; |
| 280 |
} |
| 281 |
|
| 282 |
/** |
| 283 |
Apply the decoder on each item of a JSON array, or return `[]` otherwise. |
| 284 |
Can be also applied on a _loose_ decoder, but you will get |
| 285 |
an array with possibly `undefined` elements. Use [[jList]] |
| 286 |
to discard undefined elements, or use a true _safe_ decoder. |
| 287 |
*/ |
| 288 |
export function jArray<A>(fn: Safe<A>): Safe<A[]> { |
| 289 |
return (js: json) => (Array.isArray(js) ? js.map(fn) : []); |
| 290 |
} |
| 291 |
|
| 292 |
/** |
| 293 |
Apply the loose decoder on each item of a JSON array, discarding |
| 294 |
all `undefined` elements. To keep the all possibly undefined array entries, |
| 295 |
use [[jArray]] instead. |
| 296 |
*/ |
| 297 |
export function jList<A>(fn: Loose<A>): Safe<A[]> { |
| 298 |
return (js: json) => { |
| 299 |
const buffer: A[] = []; |
| 300 |
if (Array.isArray(js)) js.forEach((vj) => { |
| 301 |
const d = fn(vj); |
| 302 |
if (d !== undefined) buffer.push(d); |
| 303 |
}); |
| 304 |
return buffer; |
| 305 |
}; |
| 306 |
} |
| 307 |
|
| 308 |
/** |
| 309 |
Exports all non-undefined elements. |
| 310 |
*/ |
| 311 |
export function eList<A>(fn: Encoder<A>): Encoder<(A | undefined)[]> { |
| 312 |
return (m) => { |
| 313 |
const js: json[] = []; |
| 314 |
m.forEach((v) => { |
| 315 |
if (v !== undefined) { |
| 316 |
const u = fn(v); |
| 317 |
if (u !== undefined) js.push(u); |
| 318 |
} |
| 319 |
}); |
| 320 |
return js; |
| 321 |
}; |
| 322 |
} |
| 323 |
|
| 324 |
/** Apply a pair of decoders to JSON pairs, or return `undefined`. */ |
| 325 |
export function jPair<A, B>( |
| 326 |
fa: Safe<A>, |
| 327 |
fb: Safe<B>, |
| 328 |
): Loose<[A, B]> { |
| 329 |
return (js: json) => (Array.isArray(js) ? [ |
| 330 |
fa(js[0]), |
| 331 |
fb(js[1]), |
| 332 |
] : undefined); |
| 333 |
} |
| 334 |
|
| 335 |
/** Similar to [[jPair]]. */ |
| 336 |
export function jTriple<A, B, C>( |
| 337 |
fa: Safe<A>, |
| 338 |
fb: Safe<B>, |
| 339 |
fc: Safe<C>, |
| 340 |
): Loose<[A, B, C]> { |
| 341 |
return (js: json) => (Array.isArray(js) ? [ |
| 342 |
fa(js[0]), |
| 343 |
fb(js[1]), |
| 344 |
fc(js[2]), |
| 345 |
] : undefined); |
| 346 |
} |
| 347 |
|
| 348 |
/** Similar to [[jPair]]. */ |
| 349 |
export function jTuple4<A, B, C, D>( |
| 350 |
fa: Safe<A>, |
| 351 |
fb: Safe<B>, |
| 352 |
fc: Safe<C>, |
| 353 |
fd: Safe<D>, |
| 354 |
): Loose<[A, B, C, D]> { |
| 355 |
return (js: json) => (Array.isArray(js) ? [ |
| 356 |
fa(js[0]), |
| 357 |
fb(js[1]), |
| 358 |
fc(js[2]), |
| 359 |
fd(js[3]), |
| 360 |
] : undefined); |
| 361 |
} |
| 362 |
|
| 363 |
/** Similar to [[jPair]]. */ |
| 364 |
export function jTuple5<A, B, C, D, E>( |
| 365 |
fa: Safe<A>, |
| 366 |
fb: Safe<B>, |
| 367 |
fc: Safe<C>, |
| 368 |
fd: Safe<D>, |
| 369 |
fe: Safe<E>, |
| 370 |
): Loose<[A, B, C, D, E]> { |
| 371 |
return (js: json) => (Array.isArray(js) ? [ |
| 372 |
fa(js[0]), |
| 373 |
fb(js[1]), |
| 374 |
fc(js[2]), |
| 375 |
fd(js[3]), |
| 376 |
fe(js[4]), |
| 377 |
] : undefined); |
| 378 |
} |
| 379 |
|
| 380 |
/** |
| 381 |
Decoders for each property of object type `A`. |
| 382 |
Optional fields in `A` can be assigned a loose decoder. |
| 383 |
*/ |
| 384 |
export type Props<A> = { |
| 385 |
[P in keyof A]: Safe<A[P]>; |
| 386 |
}; |
| 387 |
|
| 388 |
/** |
| 389 |
Decode an object given the decoders of its fields. |
| 390 |
Returns `undefined` for non-object JSON. |
| 391 |
*/ |
| 392 |
export function jObject<A>(fp: Props<A>): Loose<A> { |
| 393 |
return (js: json) => { |
| 394 |
if (js !== null && typeof js === 'object' && !Array.isArray(js)) { |
| 395 |
const buffer = {} as A; |
| 396 |
const keys = Object.keys(fp); |
| 397 |
keys.forEach((k) => { |
| 398 |
const fn = fp[k as keyof A]; |
| 399 |
if (fn !== undefined) { |
| 400 |
const fj = js[k]; |
| 401 |
if (fj !== undefined) { |
| 402 |
const fv = fn(fj); |
| 403 |
if (fv !== undefined) buffer[k as keyof A] = fv; |
| 404 |
} |
| 405 |
} |
| 406 |
}); |
| 407 |
return buffer; |
| 408 |
} |
| 409 |
return undefined; |
| 410 |
}; |
| 411 |
} |
| 412 |
|
| 413 |
/** |
| 414 |
Returns the first decoder result that is not undefined. |
| 415 |
*/ |
| 416 |
export function jUnion<A>(...cases: Loose<A>[]): Loose<A> { |
| 417 |
return (js: json) => { |
| 418 |
for (let i = 0; i < cases.length; i++) { |
| 419 |
const fv = cases[i](js); |
| 420 |
if (fv !== undefined) return fv; |
| 421 |
} |
| 422 |
return undefined; |
| 423 |
}; |
| 424 |
} |
| 425 |
|
| 426 |
/** |
| 427 |
Encoders for each property of object type `A`. |
| 428 |
*/ |
| 429 |
export type EProps<A> = { |
| 430 |
[P in keyof A]?: Encoder<A[P]>; |
| 431 |
}; |
| 432 |
|
| 433 |
/** |
| 434 |
Encode an object given the provided encoders by fields. |
| 435 |
The exported JSON object has only original |
| 436 |
fields with some specified encoder. |
| 437 |
*/ |
| 438 |
export function eObject<A>(fp: EProps<A>): Encoder<A> { |
| 439 |
return (m: A) => { |
| 440 |
const js: json = {}; |
| 441 |
const keys = Object.keys(fp); |
| 442 |
keys.forEach((k) => { |
| 443 |
const fn = fp[k as keyof A]; |
| 444 |
if (fn !== undefined) { |
| 445 |
const fv = m[k as keyof A]; |
| 446 |
if (fv !== undefined) { |
| 447 |
const r = fn(fv); |
| 448 |
if (r !== undefined) js[k] = r; |
| 449 |
} |
| 450 |
} |
| 451 |
}); |
| 452 |
return js; |
| 453 |
}; |
| 454 |
} |
| 455 |
|
| 456 |
// Intentionnaly internal and only declared |
| 457 |
// eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 458 |
declare const tag: unique symbol; |
| 459 |
|
| 460 |
/** Phantom type. */ |
| 461 |
export type phantom<K, A> = A & { tag: K }; |
| 462 |
|
| 463 |
export function forge<K, A>(_tag: K, data: A): phantom<K, A> { |
| 464 |
return data as any; |
| 465 |
} |
| 466 |
|
| 467 |
/** String key with kind. |
| 468 |
Can be used as a `string` but shall be created with [forge]. */ |
| 469 |
export type key<K> = phantom<K, string>; |
| 470 |
|
| 471 |
/** Number index with kind. |
| 472 |
Can be used as a `number` but shall be created with [forge]. */ |
| 473 |
export type index<K> = phantom<K, number>; |
| 474 |
|
| 475 |
/** Decoder for `key<K>` strings. */ |
| 476 |
export function jKey<K>(kd: K): Loose<key<K>> { |
| 477 |
return (js: json) => (typeof js === 'string' ? forge(kd, js) : undefined); |
| 478 |
} |
| 479 |
|
| 480 |
/** Decoder for `index<K>` numbers. */ |
| 481 |
export function jIndex<K>(kd: K): Loose<index<K>> { |
| 482 |
return (js: json) => (typeof js === 'number' ? forge(kd, js) : undefined); |
| 483 |
} |
| 484 |
|
| 485 |
/** Dictionaries. */ |
| 486 |
export type dict<A> = { [key: string]: A }; |
| 487 |
|
| 488 |
/** |
| 489 |
Decode a JSON dictionary, discarding all inconsistent entries. |
| 490 |
If the JSON contains no valid entry, still returns `{}`. |
| 491 |
*/ |
| 492 |
export function jDict<A>(fn: Loose<A>): Safe<dict<A>> { |
| 493 |
return (js: json) => { |
| 494 |
const buffer: dict<A> = {}; |
| 495 |
if (js !== null && typeof js === 'object' && !Array.isArray(js)) { |
| 496 |
const keys = Object.keys(js); |
| 497 |
keys.forEach((key) => { |
| 498 |
const fd = js[key]; |
| 499 |
if (fd !== undefined) { |
| 500 |
const fv = fn(fd); |
| 501 |
if (fv !== undefined) buffer[key] = fv; |
| 502 |
} |
| 503 |
}); |
| 504 |
} |
| 505 |
return buffer; |
| 506 |
}; |
| 507 |
} |
| 508 |
|
| 509 |
/** |
| 510 |
Encode a dictionary into JSON, discarding all inconsistent entries. |
| 511 |
If the dictionary contains no valid entry, still returns `{}`. |
| 512 |
*/ |
| 513 |
export function eDict<A>(fn: Encoder<A>): Encoder<dict<A>> { |
| 514 |
return (d: dict<A>) => { |
| 515 |
const js: json = {}; |
| 516 |
const keys = Object.keys(d); |
| 517 |
keys.forEach((k) => { |
| 518 |
const fv = d[k]; |
| 519 |
if (fv !== undefined) { |
| 520 |
const fr = fn(fv); |
| 521 |
if (fr !== undefined) js[k] = fr; |
| 522 |
} |
| 523 |
}); |
| 524 |
return js; |
| 525 |
}; |
| 526 |
} |
| 527 |
|
| 528 |
// -------------------------------------------------------------------------- |