@uniformdev/mesh-sdk 17.7.1-alpha.34 → 18.0.1-alpha.3

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/dist/index.esm.js CHANGED
@@ -1 +1,605 @@
1
- import I from"mitt";var S=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var E=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},c=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,c.prototype),this.name="ClientDestroyedError"}};var T=()=>{let n=()=>{},e=()=>{},o=new Promise((t,s)=>{n=t,e=s});return{resolve:n,reject:e,promise:o}},u=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),g=(n,e)=>{let{[e]:o,...t}=n;return t},L=n=>({message:n.message,name:n.name,stack:n.stack}),V=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},D=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=L(e)),{...n,serialization:o,data:e}},M=n=>n.serialization==="error"?{...n,data:V(n.data)}:n;var p=class{constructor({debug:e=!1,requestTimeout:o=E}={}){this.debug=e,this.requestTimeout=o,this.channel=T(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=u(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=g(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,i=()=>{this.responseSubscriptions=g(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=g(this.responseSubscriptions,a)};return new Promise((l,f)=>{let y,x=(R,O)=>{clearTimeout(y),i(),r(),O.type==="error_response"?f(R):l(R)},C=()=>{clearTimeout(y),f(new c)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=C,y=setTimeout(()=>{i(),r(),f(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(s,a)=>{try{let i=await o(s,a);this.postMessage("response",e,i,a.id)}catch(i){this.postMessage("error_response",e,i,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=g(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new c;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=M(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,s){let{port:a}=await this.getChannel();if(this.destroyed)throw new c;let i=D({type:e,apiVersion:"framepost/v1",key:o,data:t,id:u(),requestId:s});return this.logger.log("posting message from child to parent",i),a.postMessage(i),i}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return D({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:u()})}destroy(){this.destroyed=!0,this.channel.reject(new c),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var h=class extends p{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return S("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function v({dialogResponseHandlers:n}){let e=new h({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let s=n[t.dialogId];!s||(t.value?s.resolve({value:t.value,dialogId:t.dialogId}):t.error&&s.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{await e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,s)=>{let a={uniformMeshLocationValue:t,options:s};await e.request("setValue",a)},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async t=>{var i;if(P((i=t.options)==null?void 0:i.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",t),a=s==null?void 0:s.dialogId;if(!!a)return new Promise((r,l)=>{n[a]={resolve:r,reject:l}})},closeDialog:async t=>{await e.request("closeDialog",t)},getDataResource:async t=>await e.request("getDataResource",t,{timeout:3e4})}}}function P(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var m,b=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==m){m=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==m&&(m=l,n==null||n(l))},s=()=>{t()},a=e?void 0:new MutationObserver(s),i={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",s)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",s)},updateHeight:t};return e||i.enableAutoResizing(),i};var k={},w=!1;async function se({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!w){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");w=!0;let o=await v({dialogResponseHandlers:k}),{initData:t,parent:s}=o,a={events:I(),getCurrentLocation:()=>{let i={getDataResource:s.getDataResource,type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>i.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValue(t.locationValue,r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r)}}:void 0};return i},currentWindow:b({onHeightChange:i=>{s.resize(i)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:i,options:r})=>{let l=await s.openDialog({dialogType:"location",dialogData:{locationKey:i},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:i}){await s.closeDialog({dialogId:i,dialogType:"location"})},openConfirmationDialog:async({titleText:i,bodyText:r})=>{let l=await s.openDialog({dialogType:"confirm",dialogData:{titleText:i,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async i=>{let r=await s.openDialog({dialogType:"location",dialogData:{},options:i==null?void 0:i.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,w=!1,a}}export{se as initializeUniformMeshSDK};
1
+ // src/sdk.ts
2
+ import mitt from "mitt";
3
+
4
+ // src/framepost/logger.ts
5
+ var getLogger = (prefix, debug) => {
6
+ if (debug) {
7
+ return {
8
+ log(message, ...params) {
9
+ return console.log(`${prefix}: ${message}`, ...params);
10
+ },
11
+ error(message, ...params) {
12
+ return console.error(`${prefix}: ${message}`, ...params);
13
+ }
14
+ };
15
+ } else {
16
+ return {
17
+ log() {
18
+ return;
19
+ },
20
+ error() {
21
+ return;
22
+ }
23
+ };
24
+ }
25
+ };
26
+
27
+ // src/framepost/constants.ts
28
+ var DEFAULT_REQUEST_TIMEOUT = 5e3;
29
+
30
+ // src/framepost/errors.ts
31
+ var RequestTimeoutError = class extends Error {
32
+ constructor() {
33
+ super("Request timed out");
34
+ Object.setPrototypeOf(this, RequestTimeoutError.prototype);
35
+ this.name = "RequestTimeoutError";
36
+ }
37
+ };
38
+ var ClientDestroyedError = class extends Error {
39
+ constructor() {
40
+ super("Client destroyed");
41
+ Object.setPrototypeOf(this, ClientDestroyedError.prototype);
42
+ this.name = "ClientDestroyedError";
43
+ }
44
+ };
45
+
46
+ // src/framepost/utils.ts
47
+ var defer = () => {
48
+ let resolve = () => {
49
+ return;
50
+ };
51
+ let reject = () => {
52
+ return;
53
+ };
54
+ const promise = new Promise((res, rej) => {
55
+ resolve = res;
56
+ reject = rej;
57
+ });
58
+ return {
59
+ resolve,
60
+ reject,
61
+ promise
62
+ };
63
+ };
64
+ var randomInsecureId = (len = 16) => [...Array(len)].map(() => (~~(Math.random() * 36)).toString(36)).join("");
65
+ var omit = (object, key) => {
66
+ const { [key]: _, ...rest } = object;
67
+ return rest;
68
+ };
69
+ var serializeError = (error) => {
70
+ return {
71
+ message: error.message,
72
+ name: error.name,
73
+ stack: error.stack
74
+ };
75
+ };
76
+ var deserializeError = ({ name, message, stack }) => {
77
+ switch (name) {
78
+ case RequestTimeoutError.name: {
79
+ return new RequestTimeoutError();
80
+ }
81
+ default: {
82
+ const e = new Error(message);
83
+ e.name = name;
84
+ e.stack = stack;
85
+ return e;
86
+ }
87
+ }
88
+ };
89
+ var serialize = (message) => {
90
+ let data = message.data;
91
+ let serialization = "none" /* NONE */;
92
+ if (data instanceof Error) {
93
+ serialization = "error" /* ERROR */;
94
+ data = serializeError(data);
95
+ }
96
+ return {
97
+ ...message,
98
+ serialization,
99
+ data
100
+ };
101
+ };
102
+ var deserialize = (message) => {
103
+ if (message.serialization === "error" /* ERROR */) {
104
+ return {
105
+ ...message,
106
+ data: deserializeError(message.data)
107
+ };
108
+ }
109
+ return message;
110
+ };
111
+
112
+ // src/framepost/shared.ts
113
+ var SharedClient = class {
114
+ constructor({ debug = false, requestTimeout = DEFAULT_REQUEST_TIMEOUT } = {}) {
115
+ this.debug = debug;
116
+ this.requestTimeout = requestTimeout;
117
+ this.channel = defer();
118
+ this.eventSubscriptions = {};
119
+ this.responseSubscriptions = {};
120
+ this.requestSubscriptions = {};
121
+ this.onDestroyRequestHandlers = {};
122
+ this.destroyed = false;
123
+ this.logger = this.getLogger();
124
+ this.getChannel().then(() => {
125
+ this.logger.log("Secure parent <-> child channel established");
126
+ }).catch((reason) => {
127
+ this.logger.log(reason);
128
+ });
129
+ }
130
+ async send(eventType, data) {
131
+ return this.postMessage("event" /* EVENT */, eventType, data);
132
+ }
133
+ on(eventType, handler) {
134
+ if (!this.eventSubscriptions[eventType]) {
135
+ this.eventSubscriptions[eventType] = {};
136
+ }
137
+ const id = randomInsecureId(8);
138
+ this.eventSubscriptions[eventType][id] = handler;
139
+ this.logger.log(`Registered handler for event "${eventType}"`);
140
+ return () => {
141
+ this.eventSubscriptions[eventType] = omit(this.eventSubscriptions[eventType], id);
142
+ this.logger.log(`Unsubscribed handler for event ${eventType}`);
143
+ };
144
+ }
145
+ async request(requestKey, data, options = {}) {
146
+ const sentMessage = await this.postMessage("request" /* REQUEST */, requestKey, data);
147
+ const requestId = sentMessage.id;
148
+ const unsubscribeResponseHandler = () => {
149
+ this.responseSubscriptions = omit(this.responseSubscriptions, requestId);
150
+ };
151
+ const clearOnDestroy = () => {
152
+ this.onDestroyRequestHandlers = omit(this.responseSubscriptions, requestId);
153
+ };
154
+ return new Promise((resolve, reject) => {
155
+ let timer;
156
+ const responseHandler = (response, message) => {
157
+ clearTimeout(timer);
158
+ unsubscribeResponseHandler();
159
+ clearOnDestroy();
160
+ if (message.type === "error_response" /* ERROR_RESPONSE */) {
161
+ reject(response);
162
+ } else {
163
+ resolve(response);
164
+ }
165
+ };
166
+ const onDestroyHandler = () => {
167
+ clearTimeout(timer);
168
+ reject(new ClientDestroyedError());
169
+ };
170
+ this.responseSubscriptions[requestId] = responseHandler;
171
+ this.onDestroyRequestHandlers[requestId] = onDestroyHandler;
172
+ timer = setTimeout(() => {
173
+ unsubscribeResponseHandler();
174
+ clearOnDestroy();
175
+ reject(new RequestTimeoutError());
176
+ }, options.timeout || this.requestTimeout);
177
+ });
178
+ }
179
+ onRequest(requestKey, requestHandler) {
180
+ const requestEventHandler = async (requestData, requestMessage) => {
181
+ try {
182
+ const response = await requestHandler(requestData, requestMessage);
183
+ this.postMessage("response" /* RESPONSE */, requestKey, response, requestMessage.id);
184
+ } catch (e) {
185
+ this.postMessage("error_response" /* ERROR_RESPONSE */, requestKey, e, requestMessage.id);
186
+ }
187
+ };
188
+ this.requestSubscriptions[requestKey] = requestEventHandler;
189
+ return () => {
190
+ this.requestSubscriptions = omit(this.requestSubscriptions, requestKey);
191
+ };
192
+ }
193
+ async getChannel() {
194
+ await this.channel.promise;
195
+ if (this.destroyed) {
196
+ throw new ClientDestroyedError();
197
+ }
198
+ return this.channel.promise;
199
+ }
200
+ async messageListener(ev) {
201
+ try {
202
+ await this.getChannel();
203
+ const isValidMessage = this.isValidMessage(ev);
204
+ const message = deserialize(ev.data);
205
+ if (isValidMessage) {
206
+ switch (message.type) {
207
+ case "event" /* EVENT */: {
208
+ this.handleEvent(message);
209
+ break;
210
+ }
211
+ case "request" /* REQUEST */: {
212
+ this.handleRequest(message);
213
+ break;
214
+ }
215
+ case "error_response" /* ERROR_RESPONSE */:
216
+ case "response" /* RESPONSE */: {
217
+ this.handleResponse(message);
218
+ break;
219
+ }
220
+ }
221
+ } else {
222
+ this.logger.error("Invalid message format. Skipping.");
223
+ }
224
+ } catch (e) {
225
+ this.logger.error(e);
226
+ }
227
+ }
228
+ handleEvent(message) {
229
+ const subscriptions = this.eventSubscriptions[message.key];
230
+ if (subscriptions) {
231
+ Object.values(subscriptions).forEach((handler) => handler(message.data, message));
232
+ }
233
+ }
234
+ handleRequest(message) {
235
+ const handler = this.requestSubscriptions[message.key];
236
+ if (handler) {
237
+ handler(message.data, message);
238
+ this.logger.log(`Handled request type ${message.key}`);
239
+ }
240
+ }
241
+ handleResponse(message) {
242
+ const requestId = message.requestId;
243
+ const handler = requestId && this.responseSubscriptions[requestId];
244
+ if (handler) {
245
+ handler(message.data, message);
246
+ }
247
+ }
248
+ async postMessage(type, key, data, requestId) {
249
+ const { port } = await this.getChannel();
250
+ if (this.destroyed) {
251
+ throw new ClientDestroyedError();
252
+ }
253
+ const message = serialize({
254
+ type,
255
+ apiVersion: "framepost/v1" /* v1 */,
256
+ key,
257
+ data,
258
+ id: randomInsecureId(),
259
+ requestId
260
+ });
261
+ this.logger.log(`posting message from child to parent`, message);
262
+ port.postMessage(message);
263
+ return message;
264
+ }
265
+ initListener(ev) {
266
+ if (this.isInitMessage(ev)) {
267
+ this.onChannelInit(ev);
268
+ if (this.messagePort) {
269
+ this.messagePort.onmessage = this.messageListener.bind(this);
270
+ }
271
+ this.resolveChannel(ev);
272
+ } else {
273
+ this.logger.error("Invalid message format. Skipping.");
274
+ }
275
+ }
276
+ isValidMessage(ev) {
277
+ const message = ev.data;
278
+ return message.type && message.id && message.apiVersion === "framepost/v1" /* v1 */;
279
+ }
280
+ isInitMessage(ev) {
281
+ return this.isValidMessage(ev) && ev.data.type === "channel_init" /* CHANNEL_INIT */;
282
+ }
283
+ resolveChannel(ev) {
284
+ if (this.messagePort) {
285
+ const channel = {
286
+ port: this.messagePort,
287
+ origin: ev.origin,
288
+ context: ev.data.data
289
+ };
290
+ this.channel.resolve(channel);
291
+ }
292
+ }
293
+ getInitMessage(context) {
294
+ const message = serialize({
295
+ type: "channel_init" /* CHANNEL_INIT */,
296
+ apiVersion: "framepost/v1" /* v1 */,
297
+ key: "",
298
+ data: context,
299
+ id: randomInsecureId()
300
+ });
301
+ return message;
302
+ }
303
+ destroy() {
304
+ this.destroyed = true;
305
+ this.channel.reject(new ClientDestroyedError());
306
+ if (this.messagePort) {
307
+ this.messagePort.close();
308
+ }
309
+ Object.values(this.onDestroyRequestHandlers).forEach((destroy) => destroy());
310
+ }
311
+ };
312
+
313
+ // src/framepost/child.ts
314
+ var ChildClient = class extends SharedClient {
315
+ constructor(options = {}) {
316
+ super(options);
317
+ this.context = options.context || null;
318
+ this.initListener = this.initListener.bind(this);
319
+ window.addEventListener("message", this.initListener);
320
+ }
321
+ getLogger() {
322
+ return getLogger("child-client", this.debug);
323
+ }
324
+ onChannelInit(ev) {
325
+ window.removeEventListener("message", this.initListener);
326
+ this.messagePort = ev.ports[0];
327
+ const message = this.getInitMessage(this.context);
328
+ this.logger.log(`channel init, posting init message from child to parent`, message);
329
+ this.messagePort.postMessage(message);
330
+ }
331
+ destroy() {
332
+ super.destroy();
333
+ window.removeEventListener("message", this.initListener);
334
+ }
335
+ };
336
+
337
+ // src/sdkComms.ts
338
+ async function connectToParent({
339
+ dialogResponseHandlers
340
+ }) {
341
+ const client = new ChildClient({ debug: false });
342
+ window.parent.postMessage("parents just don't understand", "*");
343
+ const initData = await client.request("initialize");
344
+ client.onRequest("dialog-value", async (data) => {
345
+ const handler = dialogResponseHandlers[data.dialogId];
346
+ if (!handler) {
347
+ return;
348
+ }
349
+ if (data.value) {
350
+ handler.resolve({ value: data.value, dialogId: data.dialogId });
351
+ } else if (data.error) {
352
+ handler.reject(data.error);
353
+ }
354
+ delete dialogResponseHandlers[data.dialogId];
355
+ });
356
+ return {
357
+ initData,
358
+ parent: {
359
+ resize: async (height) => {
360
+ await client.request("resize", { height });
361
+ },
362
+ getValue: async () => {
363
+ const res = await client.request("getValue");
364
+ return res == null ? void 0 : res.data;
365
+ },
366
+ setValue: async (value, options) => {
367
+ const message = { uniformMeshLocationValue: value, options };
368
+ await client.request("setValue", message);
369
+ },
370
+ getMetadata: async () => {
371
+ const res = await client.request("getMetadata");
372
+ return res == null ? void 0 : res.data;
373
+ },
374
+ openDialog: async (message) => {
375
+ var _a;
376
+ if (getByteSize((_a = message.options) == null ? void 0 : _a.params) > 1e5) {
377
+ throw new Error(`Dialog parameters object is too large, maximum size is 100KB`);
378
+ }
379
+ const res = await client.request(
380
+ "openDialog",
381
+ message
382
+ );
383
+ const dialogId = res == null ? void 0 : res.dialogId;
384
+ if (!dialogId) {
385
+ return;
386
+ }
387
+ return new Promise((resolve, reject) => {
388
+ dialogResponseHandlers[dialogId] = { resolve, reject };
389
+ });
390
+ },
391
+ closeDialog: async (message) => {
392
+ await client.request("closeDialog", message);
393
+ },
394
+ getDataResource: async (message) => {
395
+ return await client.request("getDataResource", message, {
396
+ timeout: 3e4
397
+ });
398
+ }
399
+ }
400
+ };
401
+ }
402
+ function getByteSize(val) {
403
+ if (!val || typeof Blob === "undefined") {
404
+ return 0;
405
+ }
406
+ try {
407
+ const serialized = JSON.stringify(val);
408
+ const size = new Blob([serialized]).size;
409
+ return size;
410
+ } catch (error) {
411
+ throw new Error("Error calculating object size: " + error.message);
412
+ }
413
+ }
414
+
415
+ // src/sdkWindow.ts
416
+ var oldHeight;
417
+ var createSdkWindow = ({
418
+ onHeightChange,
419
+ autoResizingDisabled
420
+ }) => {
421
+ if (typeof window === "undefined") {
422
+ return;
423
+ }
424
+ const windowInstance = window;
425
+ const updateHeight = (height) => {
426
+ if (height && height !== oldHeight) {
427
+ oldHeight = height;
428
+ onHeightChange == null ? void 0 : onHeightChange(height);
429
+ return;
430
+ }
431
+ const windowHeight = `${Math.ceil(
432
+ windowInstance.document.documentElement.getBoundingClientRect().height
433
+ )}px`;
434
+ if (windowHeight !== oldHeight) {
435
+ oldHeight = windowHeight;
436
+ onHeightChange == null ? void 0 : onHeightChange(windowHeight);
437
+ }
438
+ };
439
+ const heightCallback = () => {
440
+ updateHeight();
441
+ };
442
+ const observer = autoResizingDisabled ? void 0 : new MutationObserver(heightCallback);
443
+ const sdkWindow = {
444
+ instance: windowInstance,
445
+ height: windowInstance.document.documentElement.getBoundingClientRect().height,
446
+ observer,
447
+ enableAutoResizing: () => {
448
+ observer == null ? void 0 : observer.observe(document.body, {
449
+ attributes: true,
450
+ childList: true,
451
+ subtree: true,
452
+ characterData: true
453
+ });
454
+ windowInstance.addEventListener("resize", heightCallback);
455
+ },
456
+ disableAutoResizing: () => {
457
+ observer == null ? void 0 : observer.disconnect();
458
+ windowInstance.removeEventListener("resize", heightCallback);
459
+ },
460
+ updateHeight
461
+ };
462
+ if (!autoResizingDisabled) {
463
+ sdkWindow.enableAutoResizing();
464
+ }
465
+ return sdkWindow;
466
+ };
467
+
468
+ // src/sdk.ts
469
+ var sdkDialogResponseHandlers = {};
470
+ var initializing = false;
471
+ async function initializeUniformMeshSDK({
472
+ autoResizingDisabled
473
+ } = {}) {
474
+ var _a;
475
+ if (typeof window !== "undefined" && typeof window.UniformMeshSDK === "undefined" && !initializing) {
476
+ if (typeof window.parent === "undefined" || window.parent == window) {
477
+ throw new Error(
478
+ `It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.`
479
+ );
480
+ }
481
+ initializing = true;
482
+ const connectResult = await connectToParent({
483
+ dialogResponseHandlers: sdkDialogResponseHandlers
484
+ });
485
+ const { initData: contextData, parent } = connectResult;
486
+ const sdk = {
487
+ events: mitt(),
488
+ getCurrentLocation: () => {
489
+ const location = {
490
+ getDataResource: parent.getDataResource,
491
+ type: contextData.locationType,
492
+ isReadOnly: contextData.isReadOnly,
493
+ getValue: () => {
494
+ return location.value;
495
+ },
496
+ value: contextData.locationValue,
497
+ setValue: async (value, options) => {
498
+ if (contextData.dialogContext) {
499
+ console.warn(
500
+ "Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."
501
+ );
502
+ }
503
+ contextData.locationValue = value;
504
+ sdk.events.emit("onValueChanged", { newValue: value });
505
+ await parent.setValue(value, options);
506
+ },
507
+ getMetadata: () => contextData.locationMetadata,
508
+ metadata: contextData.locationMetadata,
509
+ setValidationResult: async (value) => {
510
+ await location.setValue(contextData.locationValue, value);
511
+ },
512
+ dialogContext: contextData.dialogContext ? {
513
+ ...contextData.dialogContext,
514
+ params: contextData.locationMetadata.dialogParams,
515
+ returnDialogValue: async (value) => {
516
+ contextData.locationValue = value;
517
+ sdk.events.emit("onValueChanged", { newValue: value });
518
+ await parent.setValue(value);
519
+ }
520
+ } : void 0
521
+ };
522
+ return location;
523
+ },
524
+ currentWindow: createSdkWindow({
525
+ onHeightChange: (height) => {
526
+ parent.resize(height);
527
+ },
528
+ autoResizingDisabled: ((_a = contextData.dialogContext) == null ? void 0 : _a.contentHeight) ? true : autoResizingDisabled
529
+ }),
530
+ version: contextData.uniformApiVersion,
531
+ openLocationDialog: async ({
532
+ locationKey,
533
+ options
534
+ }) => {
535
+ const result = await parent.openDialog({
536
+ dialogType: "location",
537
+ dialogData: { locationKey },
538
+ options
539
+ });
540
+ if (!result) {
541
+ return;
542
+ }
543
+ return {
544
+ dialogId: result.dialogId,
545
+ value: result.value,
546
+ closeDialog: async () => {
547
+ await parent.closeDialog({
548
+ dialogId: result.dialogId,
549
+ dialogType: "location"
550
+ });
551
+ }
552
+ };
553
+ },
554
+ async closeLocationDialog({ dialogId }) {
555
+ await parent.closeDialog({ dialogId, dialogType: "location" });
556
+ },
557
+ openConfirmationDialog: async ({ titleText, bodyText }) => {
558
+ const result = await parent.openDialog({
559
+ dialogType: "confirm",
560
+ dialogData: { titleText, bodyText }
561
+ });
562
+ if (!result) {
563
+ return;
564
+ }
565
+ return {
566
+ dialogId: result.dialogId,
567
+ value: result.value,
568
+ closeDialog: async () => {
569
+ await parent.closeDialog({ dialogId: void 0, dialogType: "confirm" });
570
+ }
571
+ };
572
+ },
573
+ openCurrentLocationDialog: async (options) => {
574
+ const result = await parent.openDialog({
575
+ dialogType: "location",
576
+ dialogData: {},
577
+ options: options == null ? void 0 : options.options
578
+ });
579
+ if (!result) {
580
+ return;
581
+ }
582
+ return {
583
+ dialogId: result.dialogId,
584
+ value: result.value,
585
+ closeDialog: async () => {
586
+ await parent.closeDialog({
587
+ dialogId: void 0,
588
+ dialogType: "location"
589
+ });
590
+ }
591
+ };
592
+ },
593
+ closeCurrentLocationDialog: async () => {
594
+ await parent.closeDialog({ dialogId: void 0, dialogType: "location" });
595
+ },
596
+ dialogContext: contextData.dialogContext
597
+ };
598
+ window.UniformMeshSDK = sdk;
599
+ initializing = false;
600
+ return sdk;
601
+ }
602
+ }
603
+ export {
604
+ initializeUniformMeshSDK
605
+ };