1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | class Serializer {
|
4 | constructor() {
|
5 | this.nextFunctionHandle = 0;
|
6 | this.handlesByFunction = new Map();
|
7 | this.functionsByHandle = new Map();
|
8 | }
|
9 | dehydrate(root) {
|
10 | return walk(root, obj => {
|
11 | if (typeof obj === 'function') {
|
12 | return functionHandle(this.handleIdFor(obj));
|
13 | }
|
14 | });
|
15 | }
|
16 | rehydrate(root, options) {
|
17 | return walk(root, obj => {
|
18 | if (isFunctionHandle(obj)) {
|
19 | return (...params) => options.hydrateFunction(obj, params);
|
20 | }
|
21 | });
|
22 | }
|
23 | lookupFunction(handle) {
|
24 | return this.functionsByHandle.get(handle[HANDLE_ID]);
|
25 | }
|
26 | releaseFunction(f) {
|
27 | let handle = this.handlesByFunction.get(f);
|
28 | if (handle !== undefined) {
|
29 | this.functionsByHandle.delete(handle);
|
30 | }
|
31 | this.handlesByFunction.delete(f);
|
32 | }
|
33 | handleIdFor(f) {
|
34 | let handle = this.handlesByFunction.get(f);
|
35 | if (handle === undefined) {
|
36 | handle = this.nextFunctionHandle++;
|
37 | this.handlesByFunction.set(f, handle);
|
38 | this.functionsByHandle.set(handle, f);
|
39 | }
|
40 | return handle;
|
41 | }
|
42 | }
|
43 | exports.default = Serializer;
|
44 | const HANDLE_ID = '--stagehand-function-handle';
|
45 | function functionHandle(id) {
|
46 | return { [HANDLE_ID]: id };
|
47 | }
|
48 | function isFunctionHandle(obj) {
|
49 | return obj && typeof obj === 'object' && typeof obj[HANDLE_ID] === 'number';
|
50 | }
|
51 | function walk(obj, handler) {
|
52 | let result = handler(obj);
|
53 | if (result !== undefined) {
|
54 | return result;
|
55 | }
|
56 | if (Array.isArray(obj)) {
|
57 | return obj.map(el => walk(el, handler));
|
58 | }
|
59 | if (typeof obj === 'object' && obj) {
|
60 | if (Object.getPrototypeOf(obj) !== Object.prototype) {
|
61 | throw new Error('Unable to serialize non-POJO object');
|
62 | }
|
63 | let result = {};
|
64 | for (let key of Object.keys(obj)) {
|
65 | result[key] = walk(obj[key], handler);
|
66 | }
|
67 | return result;
|
68 | }
|
69 | return obj;
|
70 | }
|