1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const HANDLE_KEY = '--stagehand-function-handle';
|
4 | class FunctionHandleRegistry {
|
5 | constructor(hydrateRemoteFunction) {
|
6 | this.hydrateRemoteFunction = hydrateRemoteFunction;
|
7 | this.nextFunctionHandle = 0;
|
8 | this.handlesByFunction = new Map();
|
9 | this.functionsByHandle = new Map();
|
10 | }
|
11 | dehydrate(root) {
|
12 | return walk(root, obj => {
|
13 | if (typeof obj === 'function') {
|
14 | return dehydrateHandle(this.lookupOrGenerateHandle(obj));
|
15 | }
|
16 | });
|
17 | }
|
18 | rehydrate(root) {
|
19 | return walk(root, obj => {
|
20 | if (isDehydratedHandle(obj)) {
|
21 | return this.hydrateRemoteFunction(obj[HANDLE_KEY]);
|
22 | }
|
23 | });
|
24 | }
|
25 | lookupFunction(handle) {
|
26 | return this.functionsByHandle.get(handle);
|
27 | }
|
28 | lookupHandle(f) {
|
29 | return this.handlesByFunction.get(f);
|
30 | }
|
31 | releaseFunction(f) {
|
32 | let handle = this.handlesByFunction.get(f);
|
33 | if (handle !== undefined) {
|
34 | this.functionsByHandle.delete(handle);
|
35 | }
|
36 | this.handlesByFunction.delete(f);
|
37 | }
|
38 | reset() {
|
39 | this.handlesByFunction.clear();
|
40 | this.functionsByHandle.clear();
|
41 | }
|
42 | lookupOrGenerateHandle(f) {
|
43 | let handle = this.lookupHandle(f);
|
44 | if (handle === undefined) {
|
45 | handle = this.generateHAndle();
|
46 | this.handlesByFunction.set(f, handle);
|
47 | this.functionsByHandle.set(handle, f);
|
48 | }
|
49 | return handle;
|
50 | }
|
51 | generateHAndle() {
|
52 | return this.nextFunctionHandle++;
|
53 | }
|
54 | }
|
55 | exports.default = FunctionHandleRegistry;
|
56 | function dehydrateHandle(handle) {
|
57 | return { [HANDLE_KEY]: handle };
|
58 | }
|
59 | function isHandle(maybeHandle) {
|
60 | return typeof maybeHandle === 'number';
|
61 | }
|
62 | function isDehydratedHandle(obj) {
|
63 | return obj && typeof obj === 'object' && isHandle(obj[HANDLE_KEY]);
|
64 | }
|
65 | function walk(obj, handler) {
|
66 | let result = handler(obj);
|
67 | if (result !== undefined) {
|
68 | return result;
|
69 | }
|
70 | if (Array.isArray(obj)) {
|
71 | return obj.map(el => walk(el, handler));
|
72 | }
|
73 | if (typeof obj === 'object' && obj) {
|
74 | if (Object.getPrototypeOf(obj) !== Object.prototype) {
|
75 | return obj;
|
76 | }
|
77 | let result = {};
|
78 | for (let key of Object.keys(obj)) {
|
79 | result[key] = walk(obj[key], handler);
|
80 | }
|
81 | return result;
|
82 | }
|
83 | return obj;
|
84 | }
|