@knot-technologies/seatmap 0.3.1-dev.0 → 0.4.0-dev.0

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.cjs CHANGED
@@ -20,1101 +20,616 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- mountSeatmap: () => mountSeatmap,
24
- resolveSeatmapEnvironment: () => import_seatmap_types6.resolveSeatmapEnvironment
23
+ mountSeatmap: () => mountSeatmap
25
24
  });
26
25
  module.exports = __toCommonJS(index_exports);
27
26
 
28
- // ../seatmap-rpc/src/envelope.ts
29
- var RPC_PROTOCOL_VERSION = 1;
30
- function isRecord(value) {
31
- return typeof value === "object" && value !== null;
32
- }
33
- function hasOwn(value, key) {
34
- return Object.prototype.hasOwnProperty.call(value, key);
35
- }
36
- function isRpcErrorShape(value) {
37
- return isRecord(value) && typeof value.code === "string" && typeof value.message === "string";
38
- }
39
- function isRpcRequest(value) {
40
- return value.kind === "request" && typeof value.id === "string" && typeof value.method === "string" && hasOwn(value, "args") && typeof value.channelId === "string" && value.channelId.length > 0 && value.version === RPC_PROTOCOL_VERSION;
41
- }
42
- function isRpcResponse(value) {
43
- if (value.kind !== "response" || typeof value.id !== "string" || typeof value.ok !== "boolean" || typeof value.channelId !== "string" || value.channelId.length === 0 || value.version !== RPC_PROTOCOL_VERSION) {
27
+ // ../seatmap-rpc/dist/envelope.js
28
+ var PROTOCOL_VERSION = 1;
29
+ var ENVELOPE_TYPES = [
30
+ "request",
31
+ "reply",
32
+ "event",
33
+ "hello"
34
+ ];
35
+ function isEnvelopeType(value) {
36
+ return ENVELOPE_TYPES.includes(value);
37
+ }
38
+ function isEnvelope(value) {
39
+ if (typeof value !== "object" || value === null) {
44
40
  return false;
45
41
  }
46
- if (value.ok) return hasOwn(value, "result");
47
- return isRpcErrorShape(value.error);
48
- }
49
- function isRpcEvent(value) {
50
- return value.kind === "event" && typeof value.name === "string" && hasOwn(value, "payload") && typeof value.channelId === "string" && value.channelId.length > 0 && value.version === RPC_PROTOCOL_VERSION;
51
- }
52
- function isRpcHello(value) {
53
- return value.kind === "hello" && (value.role === "engine" || value.role === "facade") && typeof value.build === "string" && typeof value.channelId === "string" && value.channelId.length > 0 && typeof value.version === "number" && Number.isFinite(value.version);
54
- }
55
- function isRpcMessage(value) {
56
- if (!isRecord(value)) return false;
57
- return isRpcRequest(value) || isRpcResponse(value) || isRpcEvent(value) || isRpcHello(value);
42
+ const candidate = value;
43
+ return candidate.protocolVersion === PROTOCOL_VERSION && typeof candidate.channelId === "string" && isEnvelopeType(candidate.type);
58
44
  }
59
45
 
60
- // ../seatmap-rpc/src/errors.ts
46
+ // ../seatmap-rpc/dist/endpoint.js
61
47
  var RpcError = class extends Error {
62
48
  code;
63
- data;
64
- constructor(shape) {
65
- super(shape.message);
49
+ method;
50
+ constructor(code, message, method) {
51
+ super(message);
66
52
  this.name = "RpcError";
67
- this.code = shape.code;
68
- this.data = shape.data;
69
- }
70
- toShape() {
71
- return { code: this.code, message: this.message, data: this.data };
53
+ this.code = code;
54
+ this.method = method;
72
55
  }
73
56
  };
74
- var RpcTimeoutError = class extends RpcError {
75
- constructor(method, ms) {
76
- super({
77
- code: "RPC_TIMEOUT",
78
- message: `RPC '${method}' timed out after ${ms}ms`
79
- });
80
- this.name = "RpcTimeoutError";
81
- }
82
- };
83
- var RpcVersionError = class extends RpcError {
84
- constructor(local, remote) {
85
- super({
86
- code: "RPC_VERSION_MISMATCH",
87
- message: `RPC protocol mismatch: local v${local}, remote v${remote}`,
88
- data: { local, remote }
89
- });
90
- this.name = "RpcVersionError";
91
- }
92
- };
93
- function fromShape(shape) {
94
- return new RpcError(shape);
95
- }
96
-
97
- // ../seatmap-rpc/src/windowTransport.ts
98
- function createWindowTransport(opts) {
99
- if (opts.targetOrigin === "*") {
100
- throw new Error("window transport targetOrigin must not be '*'");
101
- }
102
- return {
103
- post(message) {
104
- opts.target.postMessage(message, opts.targetOrigin);
105
- },
106
- onMessage(handler) {
107
- const listener = (event) => {
108
- if (!opts.acceptOrigin(event.origin)) return;
109
- if (event.source !== opts.target) return;
110
- if (!isRpcMessage(event.data)) return;
111
- handler(event.data);
112
- };
113
- opts.local.addEventListener("message", listener);
114
- return () => opts.local.removeEventListener("message", listener);
115
- }
116
- };
117
- }
118
-
119
- // ../seatmap-rpc/src/endpoint.ts
120
- var RpcEndpoint = class {
121
- transport;
122
- role;
123
- build;
124
- channelId;
125
- timeoutMs;
126
- off;
127
- pending = /* @__PURE__ */ new Map();
128
- handlers = /* @__PURE__ */ new Map();
129
- listeners = /* @__PURE__ */ new Map();
130
- helloFromPeer = null;
131
- helloWaiters = /* @__PURE__ */ new Set();
132
- seq = 0;
133
- disposed = false;
134
- constructor(opts) {
135
- this.transport = opts.transport;
136
- this.role = opts.role;
137
- this.build = opts.build;
138
- this.channelId = opts.channelId ?? "default";
139
- this.timeoutMs = opts.timeoutMs ?? 1e4;
140
- this.off = this.transport.onMessage((m) => this.onMessage(m));
141
- }
142
- request(method, args) {
143
- if (this.disposed) {
144
- return Promise.reject(
145
- new RpcError({ code: "RPC_DISPOSED", message: "endpoint disposed" })
146
- );
57
+ function createEndpoint({ transport, channelId, requestTimeoutMs = 1e4 }) {
58
+ const pending = /* @__PURE__ */ new Map();
59
+ const eventHandlers = /* @__PURE__ */ new Map();
60
+ const requestHandlers = /* @__PURE__ */ new Map();
61
+ let nextId = 1;
62
+ let closed = false;
63
+ const detach = transport.onMessage((message) => {
64
+ if (!isEnvelope(message) || message.channelId !== channelId) {
65
+ return;
147
66
  }
148
- const id = `${this.role}:${++this.seq}`;
149
- const req = {
150
- kind: "request",
151
- id,
152
- method,
153
- args,
154
- channelId: this.channelId,
155
- version: RPC_PROTOCOL_VERSION
156
- };
157
- return new Promise((resolve, reject) => {
158
- const timer = setTimeout(() => {
159
- this.pending.delete(id);
160
- reject(new RpcTimeoutError(method, this.timeoutMs));
161
- }, this.timeoutMs);
162
- this.pending.set(id, {
163
- resolve,
164
- reject,
165
- timer,
166
- method
167
- });
168
- try {
169
- this.transport.post(req);
170
- } catch (err) {
171
- clearTimeout(timer);
172
- this.pending.delete(id);
173
- reject(err);
174
- }
175
- });
176
- }
177
- handle(method, handler) {
178
- this.assertActive();
179
- this.handlers.set(method, handler);
180
- }
181
- emit(name, payload) {
182
- this.assertActive();
183
- this.transport.post({
184
- kind: "event",
185
- name,
186
- payload,
187
- channelId: this.channelId,
188
- version: RPC_PROTOCOL_VERSION
189
- });
190
- }
191
- on(name, listener) {
192
- this.assertActive();
193
- let set = this.listeners.get(name);
194
- if (!set) {
195
- set = /* @__PURE__ */ new Set();
196
- this.listeners.set(name, set);
67
+ if (message.type === "reply") {
68
+ settleReply(message);
69
+ return;
197
70
  }
198
- set.add(listener);
199
- return () => {
200
- set.delete(listener);
201
- };
202
- }
203
- handshake() {
204
- if (this.disposed) {
205
- return Promise.reject(this.disposedError());
71
+ if (message.type === "request") {
72
+ void serveRequest(message);
73
+ return;
206
74
  }
207
- try {
208
- this.transport.post({
209
- kind: "hello",
210
- role: this.role,
211
- build: this.build,
212
- channelId: this.channelId,
213
- version: RPC_PROTOCOL_VERSION
214
- });
215
- } catch (err) {
216
- return Promise.reject(err);
75
+ if (message.type === "event" && typeof message.event === "string") {
76
+ eventHandlers.get(message.event)?.forEach((handler) => handler(message.payload));
217
77
  }
218
- if (this.helloFromPeer) {
219
- const hello = this.helloFromPeer;
220
- return Promise.resolve().then(() => this.settleHello(hello));
78
+ });
79
+ function settleReply(message) {
80
+ if (typeof message.id !== "number") {
81
+ return;
221
82
  }
222
- return new Promise((resolve, reject) => {
223
- this.helloWaiters.add({ resolve, reject });
224
- });
225
- }
226
- dispose() {
227
- if (this.disposed) return;
228
- this.disposed = true;
229
- this.off();
230
- const err = this.disposedError();
231
- for (const p of this.pending.values()) {
232
- clearTimeout(p.timer);
233
- p.reject(err);
83
+ const settlers = pending.get(message.id);
84
+ if (!settlers) {
85
+ return;
234
86
  }
235
- this.pending.clear();
236
- for (const waiter of this.helloWaiters) {
237
- waiter.reject(err);
87
+ pending.delete(message.id);
88
+ clearTimeout(settlers.timeout);
89
+ if (message.error) {
90
+ settlers.reject(new RpcError(message.error.code, message.error.message, message.error.method));
91
+ return;
238
92
  }
239
- this.helloWaiters.clear();
240
- this.handlers.clear();
241
- this.listeners.clear();
242
- }
243
- disposedError() {
244
- return new RpcError({ code: "RPC_DISPOSED", message: "endpoint disposed" });
93
+ settlers.resolve(message.result);
245
94
  }
246
- assertActive() {
247
- if (this.disposed) throw this.disposedError();
95
+ function sendMethodError(message, error) {
96
+ transport.send({
97
+ protocolVersion: PROTOCOL_VERSION,
98
+ channelId,
99
+ type: "reply",
100
+ id: message.id,
101
+ error: {
102
+ code: error.code,
103
+ message: error.message,
104
+ method: error.method ?? message.method
105
+ }
106
+ });
248
107
  }
249
- settleHello(hello) {
250
- if (hello.version !== RPC_PROTOCOL_VERSION) {
251
- throw new RpcVersionError(RPC_PROTOCOL_VERSION, hello.version);
108
+ async function serveRequest(message) {
109
+ if (typeof message.id !== "number" || typeof message.method !== "string") {
110
+ return;
252
111
  }
253
- return { build: hello.build };
254
- }
255
- onMessage(message) {
256
- if (this.disposed) return;
257
- if (!isRpcMessage(message)) return;
258
- if (message.channelId !== this.channelId) return;
259
- if (message.kind === "request") void this.onRequest(message);
260
- else if (message.kind === "response") this.onResponse(message);
261
- else if (message.kind === "event") this.onEvent(message);
262
- else if (message.kind === "hello") this.onHello(message);
263
- }
264
- async onRequest(req) {
265
- if (this.disposed) return;
266
- const handler = this.handlers.get(req.method);
112
+ const handler = requestHandlers.get(message.method);
267
113
  if (!handler) {
268
- if (this.disposed) return;
269
- this.transport.post({
270
- kind: "response",
271
- id: req.id,
272
- ok: false,
273
- error: {
274
- code: "RPC_METHOD_NOT_FOUND",
275
- message: `no handler for '${req.method}'`
276
- },
277
- channelId: this.channelId,
278
- version: RPC_PROTOCOL_VERSION
279
- });
114
+ sendMethodError(message, new RpcError("METHOD_NOT_IMPLEMENTED", `Method '${message.method}' is not implemented`, message.method));
280
115
  return;
281
116
  }
282
117
  try {
283
- const result = await handler(req.args);
284
- if (this.disposed) return;
285
- this.transport.post({
286
- kind: "response",
287
- id: req.id,
288
- ok: true,
289
- result,
290
- channelId: this.channelId,
291
- version: RPC_PROTOCOL_VERSION
292
- });
293
- } catch (err) {
294
- if (this.disposed) return;
295
- const shape = err instanceof RpcError ? err.toShape() : { code: "RPC_HANDLER_ERROR", message: String(err) };
296
- this.transport.post({
297
- kind: "response",
298
- id: req.id,
299
- ok: false,
300
- error: shape,
301
- channelId: this.channelId,
302
- version: RPC_PROTOCOL_VERSION
118
+ const result = await handler(message.params);
119
+ transport.send({
120
+ protocolVersion: PROTOCOL_VERSION,
121
+ channelId,
122
+ type: "reply",
123
+ id: message.id,
124
+ result
303
125
  });
126
+ } catch (error) {
127
+ sendMethodError(message, error instanceof RpcError ? error : new RpcError("ENGINE_INCOMPATIBLE", error instanceof Error ? error.message : "RPC handler failed", message.method));
304
128
  }
305
129
  }
306
- onResponse(res) {
307
- if (this.disposed) return;
308
- const pending = this.pending.get(res.id);
309
- if (!pending) return;
310
- clearTimeout(pending.timer);
311
- this.pending.delete(res.id);
312
- if (res.ok) pending.resolve(res.result);
313
- else pending.reject(fromShape(res.error));
314
- }
315
- onEvent(evt) {
316
- if (this.disposed) return;
317
- const set = this.listeners.get(evt.name);
318
- if (!set) return;
319
- for (const l of [...set]) l(evt.payload);
320
- }
321
- onHello(hello) {
322
- if (this.disposed) return;
323
- this.helloFromPeer = { build: hello.build, version: hello.version };
324
- try {
325
- const peer = this.settleHello(this.helloFromPeer);
326
- for (const waiter of this.helloWaiters) {
327
- waiter.resolve(peer);
130
+ return {
131
+ request(method, params) {
132
+ if (closed) {
133
+ return Promise.reject(new RpcError("CHART_DESTROYED", "The chart has been destroyed", method));
328
134
  }
329
- } catch (err) {
330
- for (const waiter of this.helloWaiters) {
331
- waiter.reject(err);
135
+ const id = nextId++;
136
+ return new Promise((resolve, reject) => {
137
+ const timeout = setTimeout(() => {
138
+ pending.delete(id);
139
+ reject(new RpcError("ENGINE_UNREACHABLE", `Engine did not reply to '${method}' within ${requestTimeoutMs}ms`, method));
140
+ }, requestTimeoutMs);
141
+ pending.set(id, { resolve, reject, method, timeout });
142
+ try {
143
+ transport.send({
144
+ protocolVersion: PROTOCOL_VERSION,
145
+ channelId,
146
+ type: "request",
147
+ id,
148
+ method,
149
+ params
150
+ });
151
+ } catch {
152
+ clearTimeout(timeout);
153
+ pending.delete(id);
154
+ reject(new RpcError("ENGINE_UNREACHABLE", `Engine is unreachable for '${method}'`, method));
155
+ }
156
+ });
157
+ },
158
+ handle(method, handler) {
159
+ requestHandlers.set(method, handler);
160
+ return () => {
161
+ if (requestHandlers.get(method) === handler) {
162
+ requestHandlers.delete(method);
163
+ }
164
+ };
165
+ },
166
+ emit(event, payload) {
167
+ if (closed) {
168
+ return;
332
169
  }
170
+ transport.send({
171
+ protocolVersion: PROTOCOL_VERSION,
172
+ channelId,
173
+ type: "event",
174
+ event,
175
+ payload
176
+ });
177
+ },
178
+ on(event, handler) {
179
+ const forEvent = eventHandlers.get(event) ?? /* @__PURE__ */ new Set();
180
+ forEvent.add(handler);
181
+ eventHandlers.set(event, forEvent);
182
+ return () => {
183
+ forEvent.delete(handler);
184
+ };
185
+ },
186
+ close() {
187
+ if (closed) {
188
+ return;
189
+ }
190
+ closed = true;
191
+ detach();
192
+ pending.forEach(({ reject, method, timeout }) => {
193
+ clearTimeout(timeout);
194
+ reject(new RpcError("CHART_DESTROYED", "The chart has been destroyed", method));
195
+ });
196
+ pending.clear();
197
+ eventHandlers.clear();
198
+ requestHandlers.clear();
199
+ transport.close();
333
200
  }
334
- this.helloWaiters.clear();
335
- }
336
- };
337
-
338
- // ../seatmap-rpc/src/internal.ts
339
- var ENGINE_RESIZED = "engineResized";
340
- function isEngineResizedPayload(value) {
341
- return typeof value === "object" && value !== null && "height" in value && typeof value.height === "number" && Number.isFinite(value.height) && value.height > 0;
201
+ };
342
202
  }
343
203
 
344
- // src/mountSeatmap.ts
345
- var import_seatmap_types5 = require("@knot-technologies/seatmap-types");
346
-
347
- // src/createChart.ts
348
- var import_seatmap_types = require("@knot-technologies/seatmap-types");
349
-
350
- // src/configSerialization.ts
351
- var ON_CALLBACK_KEY = /^on[A-Z]/;
352
- var FUNCTION_HATCHES = /* @__PURE__ */ new Set(["objectColor", "tooltipText"]);
353
- var FACADE_ONLY_KEYS = /* @__PURE__ */ new Set(["environment"]);
354
- function stringifyFunctionHatch(key, value) {
355
- if (typeof value !== "function") {
356
- throw new TypeError(
357
- `@knot-technologies/seatmap: ${key} must be a function`
358
- );
359
- }
360
- return value.toString();
361
- }
362
- function serializePricing(pricing) {
363
- const out = { ...pricing };
364
- if (pricing.priceFormatter !== void 0) {
365
- out.priceFormatter = stringifyFunctionHatch(
366
- "pricing.priceFormatter",
367
- pricing.priceFormatter
368
- );
369
- }
370
- return out;
371
- }
372
- function serializeConfigForWire(config, options = {}) {
373
- const out = {};
374
- for (const [key, value] of Object.entries(config)) {
375
- if (ON_CALLBACK_KEY.test(key)) continue;
376
- if (FACADE_ONLY_KEYS.has(key)) continue;
377
- if (value === void 0 && options.skipUndefined) continue;
378
- if (FUNCTION_HATCHES.has(key)) {
379
- out[key] = value === void 0 ? void 0 : stringifyFunctionHatch(key, value);
380
- continue;
204
+ // ../seatmap-rpc/dist/windowTransport.js
205
+ function createWindowTransport({ target, targetOrigin, channelId }) {
206
+ if (targetOrigin === "*") {
207
+ throw new Error("A wildcard target origin is not allowed; pass the exact engine origin");
208
+ }
209
+ const listeners = /* @__PURE__ */ new Set();
210
+ const receive = (event) => {
211
+ if (event.origin !== targetOrigin || event.source !== target) {
212
+ return;
381
213
  }
382
- if (key === "pricing") {
383
- out.pricing = value === void 0 ? void 0 : serializePricing(value);
384
- continue;
214
+ if (!isEnvelope(event.data) || event.data.channelId !== channelId) {
215
+ return;
385
216
  }
386
- out[key] = value;
387
- }
388
- return out;
389
- }
390
-
391
- // src/createChart.ts
392
- function createChart(deps) {
393
- const { endpoint, getHoldState, holdBestAvailable: holdBestAvailable2, teardown, changeConfig } = deps;
394
- const req = (method, args) => endpoint.request(method, args);
217
+ listeners.forEach((listener) => listener(event.data));
218
+ };
219
+ window.addEventListener("message", receive);
395
220
  return {
396
- selectObjects: (ids) => req("selectObjects", ids),
397
- deselectObjects: (ids) => req("deselectObjects", ids),
398
- clearSelection: () => req("clearSelection", void 0),
399
- listSelectedObjects: () => req("listSelectedObjects", void 0),
400
- trySelectObjects: (ids) => req("trySelectObjects", ids),
401
- doSelectObjects: (ids) => req("doSelectObjects", ids),
402
- setObjectQuantity: (id, quantity) => req("setObjectQuantity", [id, quantity]),
403
- highlightObjects: (ids, color) => req("highlightObjects", [ids, color]),
404
- clearHighlights: () => req("clearHighlights", void 0),
405
- pulse: (ids) => req("pulse", ids),
406
- unpulse: (ids) => req("unpulse", ids),
407
- spotlight: (ids) => req("spotlight", ids),
408
- clearSpotlight: () => req("clearSpotlight", void 0),
409
- setSpotlightObjects: (ids) => req("setSpotlightObjects", ids),
410
- disableObjects: (ids) => req("disableObjects", ids),
411
- enableObjects: (ids) => req("enableObjects", ids),
412
- setMetadata: (entries) => req("setMetadata", entries),
413
- setCategoryMetadata: (entries) => req("setCategoryMetadata", entries),
414
- selectCategories: (keys) => req("selectCategories", keys),
415
- deselectCategories: (keys) => req("deselectCategories", keys),
416
- listCategories: () => req(
417
- "listCategories",
418
- void 0
419
- ),
420
- findObject: (label) => req("findObject", label),
421
- holdBestAvailable: holdBestAvailable2,
422
- resetView: () => req("resetView", void 0),
423
- zoomToObjects: (ids) => req("zoomToObjects", ids),
424
- zoomToSelectedObjects: () => req("zoomToSelectedObjects", void 0),
425
- zoomToSection: (sectionId) => req("zoomToSection", sectionId),
426
- changeConfig: async (patch) => {
427
- (0, import_seatmap_types.runtimeConfigPatchKeys)(patch);
428
- if (changeConfig !== void 0) {
429
- await changeConfig(patch);
430
- return;
431
- }
432
- await req("changeConfig", serializeConfigForWire(patch));
221
+ send(envelope) {
222
+ target.postMessage(envelope, targetOrigin);
223
+ },
224
+ onMessage(listener) {
225
+ listeners.add(listener);
226
+ return () => {
227
+ listeners.delete(listener);
228
+ };
433
229
  },
434
- destroy: () => teardown(),
435
- get holdState() {
436
- return getHoldState();
230
+ close() {
231
+ window.removeEventListener("message", receive);
232
+ listeners.clear();
437
233
  }
438
234
  };
439
235
  }
440
236
 
441
- // src/dom.ts
442
- var defaultDomFactory = {
443
- createFrame(container, src) {
444
- const iframe = container.ownerDocument.createElement("iframe");
445
- iframe.src = src;
446
- iframe.setAttribute("allow", "fullscreen");
447
- iframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
448
- iframe.setAttribute("title", "KNOT Seatmap");
449
- iframe.style.border = "0";
450
- iframe.style.background = "transparent";
451
- iframe.style.display = "block";
452
- iframe.style.width = "100%";
453
- iframe.style.height = "100%";
454
- iframe.style.overflow = "hidden";
455
- iframe.style.colorScheme = "normal";
456
- container.appendChild(iframe);
457
- const contentWindow = iframe.contentWindow;
458
- if (!contentWindow) {
459
- iframe.remove();
460
- throw new Error(
461
- "@knot-technologies/seatmap: iframe.contentWindow is null"
462
- );
463
- }
464
- return {
465
- iframe,
466
- contentWindow,
467
- remove: () => iframe.remove()
468
- };
469
- }
470
- };
471
-
472
- // src/endpoints.ts
473
- var import_seatmap_types2 = require("@knot-technologies/seatmap-types");
474
- var DEFAULT_API_BASE_URL = "";
475
- var DEFAULT_SSE_BASE_URL = "";
476
- var PREDEV_API_BASE_URL = "";
477
- var PREDEV_SSE_BASE_URL = "";
478
- var DEVELOPMENT_API_BASE_URL = "https://d88f7h1ehc1xa.cloudfront.net";
479
- var DEVELOPMENT_SSE_BASE_URL = "https://d272va20q3venb.cloudfront.net";
480
- function requireBaseUrl(name, value) {
481
- if (typeof value !== "string" || value.trim().length === 0) {
482
- throw new Error(`@knot-technologies/seatmap: ${name} must be configured`);
483
- }
484
- return value.replace(/\/+$/, "");
485
- }
486
- function resolveSdkEndpoints(environment) {
487
- const profile = (0, import_seatmap_types2.resolveSeatmapEnvironment)(environment);
488
- switch (profile) {
489
- case "production":
490
- return {
491
- apiBaseUrl: requireBaseUrl(
492
- "production API base URL",
493
- DEFAULT_API_BASE_URL
494
- ),
495
- sseBaseUrl: requireBaseUrl(
496
- "production SSE base URL",
497
- DEFAULT_SSE_BASE_URL
498
- )
499
- };
500
- case "predev":
501
- return {
502
- apiBaseUrl: requireBaseUrl("predev API base URL", PREDEV_API_BASE_URL),
503
- sseBaseUrl: requireBaseUrl("predev SSE base URL", PREDEV_SSE_BASE_URL)
504
- };
505
- case "development":
506
- return {
507
- apiBaseUrl: requireBaseUrl(
508
- "development API base URL",
509
- DEVELOPMENT_API_BASE_URL
510
- ),
511
- sseBaseUrl: requireBaseUrl(
512
- "development SSE base URL",
513
- DEVELOPMENT_SSE_BASE_URL
514
- )
515
- };
516
- }
517
- }
518
-
519
- // src/engineUrl.ts
520
- var import_seatmap_types3 = require("@knot-technologies/seatmap-types");
521
- var DEFAULT_ENGINE_URL = "";
522
- var PREDEV_ENGINE_URL = "";
523
- var DEVELOPMENT_ENGINE_URL = "https://dev-seatmap.knottech.ai/seatmap/sdk/dev/0.3.1-dev.0/engine.html";
524
- var DEFAULT_CDN_BASE = "".length > 0 ? `${"".replace(/\/+$/, "")}/seatmap/sdk` : "";
525
- function requireEngineUrl(name, value) {
526
- if (typeof value !== "string" || value.trim().length === 0) {
527
- throw new Error(`@knot-technologies/seatmap: ${name} must be configured`);
528
- }
529
- return value;
237
+ // src/chartHandle.ts
238
+ function isRecord(value) {
239
+ return typeof value === "object" && value !== null && !Array.isArray(value);
530
240
  }
531
- function resolveEngineUrl(environment) {
532
- const profile = (0, import_seatmap_types3.resolveSeatmapEnvironment)(environment);
533
- switch (profile) {
534
- case "production":
535
- return requireEngineUrl("production engine URL", DEFAULT_ENGINE_URL);
536
- case "predev":
537
- return requireEngineUrl("predev engine URL", PREDEV_ENGINE_URL);
538
- case "development":
539
- return requireEngineUrl("development engine URL", DEVELOPMENT_ENGINE_URL);
241
+ function isObjectRef(value) {
242
+ if (!isRecord(value)) {
243
+ return false;
540
244
  }
541
- }
542
- function engineChannelUrl(channel) {
543
- const base = requireEngineUrl("production CDN base URL", DEFAULT_CDN_BASE);
544
- return `${base}/${channel}/engine.html`;
545
- }
546
- function originOf(url) {
547
- return new URL(url).origin;
548
- }
549
-
550
- // src/names.ts
551
- var import_seatmap_types4 = require("@knot-technologies/seatmap-types");
552
-
553
- // src/wireEvents.ts
554
- function fail(eventName, message) {
555
- throw new Error(
556
- `@knot-technologies/seatmap: invalid ${eventName} payload (${message})`
245
+ return (value.type === "seat" || value.type === "gaArea" || value.type === "table") && typeof value.id === "string" && value.id.length > 0;
246
+ }
247
+ function isObjectRefArray(value) {
248
+ return Array.isArray(value) && value.every(isObjectRef);
249
+ }
250
+ function isEventPayload(event, payload) {
251
+ switch (event) {
252
+ case "chartRendered":
253
+ return payload === void 0;
254
+ case "chartRenderingFailed":
255
+ return isRecord(payload) && typeof payload.message === "string";
256
+ case "selectionChanged":
257
+ return isRecord(payload) && isObjectRefArray(payload.selected);
258
+ case "objectClicked":
259
+ case "objectSelected":
260
+ case "objectDeselected":
261
+ case "objectMouseOver":
262
+ case "objectMouseOut":
263
+ return isObjectRef(payload);
264
+ }
265
+ }
266
+ function destroyedError(method) {
267
+ return new RpcError(
268
+ "CHART_DESTROYED",
269
+ "The chart has been destroyed",
270
+ method
557
271
  );
558
272
  }
559
- function isRecord2(value) {
560
- return typeof value === "object" && value !== null;
561
- }
562
- function record(value, eventName) {
563
- if (!isRecord2(value)) fail(eventName, "expected object");
564
- return value;
565
- }
566
- function stringField(source, key, eventName) {
567
- const value = source[key];
568
- if (typeof value !== "string") fail(eventName, `${key} must be string`);
569
- return value;
570
- }
571
- function numberField(source, key, eventName) {
572
- const value = source[key];
573
- if (typeof value !== "number") fail(eventName, `${key} must be number`);
574
- return value;
575
- }
576
- function booleanField(source, key, eventName) {
577
- const value = source[key];
578
- if (typeof value !== "boolean") fail(eventName, `${key} must be boolean`);
579
- return value;
580
- }
581
- function optionalString(target, source, key, eventName) {
582
- const value = source[key];
583
- if (value === void 0) return;
584
- if (typeof value !== "string") fail(eventName, `${key} must be string`);
585
- target[key] = value;
273
+ async function requestVoid(endpoint, method, params) {
274
+ await endpoint.request(method, params);
586
275
  }
587
- function optionalNumber(target, source, key, eventName) {
588
- const value = source[key];
589
- if (value === void 0) return;
590
- if (typeof value !== "number") fail(eventName, `${key} must be number`);
591
- target[key] = value;
592
- }
593
- function optionalBoolean(target, source, key, eventName) {
594
- const value = source[key];
595
- if (value === void 0) return;
596
- if (typeof value !== "boolean") fail(eventName, `${key} must be boolean`);
597
- target[key] = value;
598
- }
599
- function objectType(value, eventName) {
600
- if (value === "seat" || value === "table" || value === "booth" || value === "generalAdmission" || value === "section") {
601
- return value;
602
- }
603
- fail(eventName, "type must be a contract ObjectType");
604
- }
605
- function stringArray(source, key, eventName) {
606
- const value = source[key];
607
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
608
- fail(eventName, `${key} must be string[]`);
276
+ function createChartHandle(endpoint, removeIframe) {
277
+ let destroyed = false;
278
+ let chartRendered = false;
279
+ const subscriptions = [];
280
+ const unsubscribeChartRendered = endpoint.on("chartRendered", () => {
281
+ chartRendered = true;
282
+ });
283
+ function assertActive(method) {
284
+ if (destroyed) {
285
+ throw destroyedError(method);
286
+ }
609
287
  }
610
- return value;
611
- }
612
- function toSeatmapObject(value, eventName) {
613
- const source = record(value, eventName);
614
- const target = {
615
- id: stringField(source, "id", eventName),
616
- label: stringField(source, "label", eventName),
617
- type: objectType(source.type, eventName),
618
- status: source.status === "available" || source.status === "unavailable" ? source.status : fail(eventName, "status must be available|unavailable"),
619
- selectable: booleanField(source, "selectable", eventName)
620
- };
621
- optionalString(target, source, "categoryKey", eventName);
622
- optionalString(target, source, "sectionId", eventName);
623
- return target;
624
- }
625
- function toTicketType(value, eventName) {
626
- const source = record(value, eventName);
627
- const target = {
628
- ticketType: stringField(source, "ticketType", eventName),
629
- label: stringField(source, "label", eventName),
630
- price: numberField(source, "price", eventName)
631
- };
632
- optionalString(target, source, "description", eventName);
633
- optionalNumber(target, source, "originalPrice", eventName);
634
- optionalBoolean(target, source, "primary", eventName);
635
- optionalBoolean(target, source, "unavailable", eventName);
636
- optionalString(target, source, "unavailableReason", eventName);
637
- return target;
638
- }
639
- function toSelectedObject(value, eventName) {
640
- const source = record(value, eventName);
641
- const target = {
642
- id: stringField(source, "id", eventName),
643
- label: stringField(source, "label", eventName),
644
- type: objectType(source.type, eventName)
645
- };
646
- optionalString(target, source, "ticketType", eventName);
647
- optionalNumber(target, source, "price", eventName);
648
- optionalNumber(target, source, "quantity", eventName);
649
- return target;
650
- }
651
- function toSelectionChange(value, eventName) {
652
- const source = record(value, eventName);
653
- const objects = source.objects;
654
- if (!Array.isArray(objects)) fail(eventName, "objects must be array");
655
288
  return {
656
- objects: objects.map((item) => toSelectedObject(item, eventName))
657
- };
658
- }
659
- function toHoldState(value, eventName) {
660
- const source = record(value, eventName);
661
- return {
662
- holdToken: stringField(source, "holdToken", eventName),
663
- expiresAt: stringField(source, "expiresAt", eventName),
664
- expiresInSeconds: numberField(source, "expiresInSeconds", eventName),
665
- objects: stringArray(source, "objects", eventName)
666
- };
667
- }
668
- function toSdkError(value, eventName) {
669
- const source = record(value, eventName);
670
- return {
671
- code: stringField(source, "code", eventName),
672
- message: stringField(source, "message", eventName)
673
- };
674
- }
675
- function toObjectSelected(value, eventName) {
676
- const source = record(value, eventName);
677
- const result = {
678
- object: toSeatmapObject(source.object, eventName)
679
- };
680
- if (source.selectedTicketType !== void 0) {
681
- result.selectedTicketType = toTicketType(
682
- source.selectedTicketType,
683
- eventName
684
- );
685
- }
686
- return result;
687
- }
688
- function wireEvents(deps) {
689
- const { endpoint, config, getChart, setHoldState } = deps;
690
- const handlers = {
691
- chartRendered: () => config.onChartRendered?.(getChart()),
692
- chartRenderingFailed: (payload) => config.onChartRenderingFailed?.(
693
- toSdkError(payload, "chartRenderingFailed")
694
- ),
695
- objectClicked: (payload) => config.onObjectClicked?.(toSeatmapObject(payload, "objectClicked")),
696
- objectHovered: (payload) => config.onObjectHovered?.(toSeatmapObject(payload, "objectHovered")),
697
- objectMouseOut: (payload) => config.onObjectMouseOut?.(toSeatmapObject(payload, "objectMouseOut")),
698
- objectSelected: (payload) => {
699
- const selected = toObjectSelected(payload, "objectSelected");
700
- config.onObjectSelected?.(selected.object, selected.selectedTicketType);
289
+ get isDestroyed() {
290
+ return destroyed;
701
291
  },
702
- objectDeselected: (payload) => config.onObjectDeselected?.(toSeatmapObject(payload, "objectDeselected")),
703
- selectionChanged: (payload) => config.onSelectionChanged?.(
704
- toSelectionChange(payload, "selectionChanged")
705
- ),
706
- holdSucceeded: (payload) => {
707
- const state = toHoldState(payload, "holdSucceeded");
708
- setHoldState(state);
709
- config.onHoldSucceeded?.(state);
292
+ async selectObjects(objects) {
293
+ assertActive("selectObjects");
294
+ await requestVoid(endpoint, "selectObjects", { objects });
710
295
  },
711
- holdFailed: (payload) => config.onHoldFailed?.(toSdkError(payload, "holdFailed")),
712
- holdChanged: (payload) => {
713
- const state = toHoldState(payload, "holdChanged");
714
- setHoldState(state);
715
- config.onHoldChanged?.(state);
296
+ async deselectObjects(objects) {
297
+ assertActive("deselectObjects");
298
+ await requestVoid(endpoint, "deselectObjects", { objects });
716
299
  },
717
- holdExpired: () => {
718
- setHoldState(null);
719
- config.onHoldExpired?.();
300
+ async clearSelection() {
301
+ assertActive("clearSelection");
302
+ await requestVoid(endpoint, "clearSelection", {});
720
303
  },
721
- releaseHoldSucceeded: () => {
722
- setHoldState(null);
723
- config.onReleaseHoldSucceeded?.();
304
+ async listSelectedObjects() {
305
+ assertActive("listSelectedObjects");
306
+ const result = await endpoint.request("listSelectedObjects", {});
307
+ if (!isObjectRefArray(result)) {
308
+ throw new RpcError(
309
+ "ENGINE_INCOMPATIBLE",
310
+ "Engine returned an invalid selection",
311
+ "listSelectedObjects"
312
+ );
313
+ }
314
+ return result;
724
315
  },
725
- releaseHoldFailed: (payload) => config.onReleaseHoldFailed?.(toSdkError(payload, "releaseHoldFailed"))
726
- };
727
- const offs = import_seatmap_types4.EVENT_NAMES.map((name) => endpoint.on(name, handlers[name]));
728
- return () => {
729
- for (const off of offs.splice(0)) off();
730
- };
731
- }
732
-
733
- // src/mountSeatmap.ts
734
- var DEFAULT_SDK_TIMEOUT_MS = 1e4;
735
- function defaultLocalWindow() {
736
- if (typeof window === "undefined") {
737
- throw new Error("@knot-technologies/seatmap: window is not available");
738
- }
739
- return window;
740
- }
741
- function isRecord3(value) {
742
- return typeof value === "object" && value !== null;
743
- }
744
- function createFacadeAutoHeightController(endpoint, iframe, initialFitTo) {
745
- const fillHeight = iframe.style.height;
746
- let disposed = false;
747
- let autoHeightActive = false;
748
- let detach = () => {
749
- };
750
- const setFitTo = (fitTo) => {
751
- if (disposed) return;
752
- const nextAutoHeight = fitTo === "width";
753
- if (nextAutoHeight === autoHeightActive) return;
754
- const detachPrevious = detach;
755
- detach = () => {
756
- };
757
- autoHeightActive = nextAutoHeight;
758
- detachPrevious();
759
- if (!nextAutoHeight) {
760
- iframe.style.height = fillHeight;
761
- return;
762
- }
763
- detach = endpoint.on(ENGINE_RESIZED, (payload) => {
764
- if (disposed || !autoHeightActive || !isEngineResizedPayload(payload)) {
316
+ async setObjectQuantity(object, quantity) {
317
+ assertActive("setObjectQuantity");
318
+ await requestVoid(endpoint, "setObjectQuantity", { object, quantity });
319
+ },
320
+ async highlightObjects(objects, color) {
321
+ assertActive("highlightObjects");
322
+ await requestVoid(
323
+ endpoint,
324
+ "highlightObjects",
325
+ color === void 0 ? { objects } : { objects, color }
326
+ );
327
+ },
328
+ async clearHighlights() {
329
+ assertActive("clearHighlights");
330
+ await requestVoid(endpoint, "clearHighlights", {});
331
+ },
332
+ async setMetadata(metadata) {
333
+ assertActive("setMetadata");
334
+ await requestVoid(endpoint, "setMetadata", { metadata });
335
+ },
336
+ async setCategoryMetadata(metadata) {
337
+ assertActive("setCategoryMetadata");
338
+ await requestVoid(endpoint, "setCategoryMetadata", { metadata });
339
+ },
340
+ async holdBestAvailable() {
341
+ assertActive("holdBestAvailable");
342
+ await requestVoid(endpoint, "holdBestAvailable", {});
343
+ },
344
+ async pulse() {
345
+ assertActive("pulse");
346
+ await requestVoid(endpoint, "pulse", {});
347
+ },
348
+ async unpulse() {
349
+ assertActive("unpulse");
350
+ await requestVoid(endpoint, "unpulse", {});
351
+ },
352
+ async spotlight() {
353
+ assertActive("spotlight");
354
+ await requestVoid(endpoint, "spotlight", {});
355
+ },
356
+ async clearSpotlight() {
357
+ assertActive("clearSpotlight");
358
+ await requestVoid(endpoint, "clearSpotlight", {});
359
+ },
360
+ async disableObjects() {
361
+ assertActive("disableObjects");
362
+ await requestVoid(endpoint, "disableObjects", {});
363
+ },
364
+ async enableObjects() {
365
+ assertActive("enableObjects");
366
+ await requestVoid(endpoint, "enableObjects", {});
367
+ },
368
+ async selectCategories() {
369
+ assertActive("selectCategories");
370
+ await requestVoid(endpoint, "selectCategories", {});
371
+ },
372
+ async deselectCategories() {
373
+ assertActive("deselectCategories");
374
+ await requestVoid(endpoint, "deselectCategories", {});
375
+ },
376
+ async listCategories() {
377
+ assertActive("listCategories");
378
+ await requestVoid(endpoint, "listCategories", {});
379
+ },
380
+ async findObject() {
381
+ assertActive("findObject");
382
+ await requestVoid(endpoint, "findObject", {});
383
+ },
384
+ async zoomToObjects() {
385
+ assertActive("zoomToObjects");
386
+ await requestVoid(endpoint, "zoomToObjects", {});
387
+ },
388
+ async zoomToSection() {
389
+ assertActive("zoomToSection");
390
+ await requestVoid(endpoint, "zoomToSection", {});
391
+ },
392
+ async resetView() {
393
+ assertActive("resetView");
394
+ await requestVoid(endpoint, "resetView", {});
395
+ },
396
+ async changeConfig() {
397
+ assertActive("changeConfig");
398
+ await requestVoid(endpoint, "changeConfig", {});
399
+ },
400
+ async destroy() {
401
+ assertActive("destroy");
402
+ destroyed = true;
403
+ subscriptions.splice(0).forEach((subscription) => subscription.unsubscribe());
404
+ unsubscribeChartRendered();
405
+ endpoint.close();
406
+ removeIframe();
407
+ },
408
+ on(event, handler) {
409
+ assertActive("on");
410
+ if (subscriptions.some(
411
+ (subscription) => subscription.event === event && subscription.handler === handler
412
+ )) {
765
413
  return;
766
414
  }
767
- iframe.style.height = `${payload.height}px`;
768
- });
769
- };
770
- setFitTo(initialFitTo);
771
- return {
772
- setFitTo,
773
- dispose() {
774
- if (disposed) return;
775
- disposed = true;
776
- autoHeightActive = false;
777
- const detachCurrent = detach;
778
- detach = () => {
779
- };
780
- detachCurrent();
415
+ if (event === "chartRendered" && chartRendered) {
416
+ let active = true;
417
+ const subscription = {
418
+ event,
419
+ handler,
420
+ unsubscribe() {
421
+ active = false;
422
+ }
423
+ };
424
+ subscriptions.push(subscription);
425
+ const chartRenderedHandler = handler;
426
+ queueMicrotask(() => {
427
+ if (active) {
428
+ chartRenderedHandler();
429
+ }
430
+ });
431
+ return;
432
+ }
433
+ const unsubscribe = endpoint.on(event, (payload) => {
434
+ if (isEventPayload(event, payload)) {
435
+ handler(payload);
436
+ }
437
+ });
438
+ subscriptions.push({ event, handler, unsubscribe });
439
+ },
440
+ off(event, handler) {
441
+ assertActive("off");
442
+ const index = subscriptions.findIndex(
443
+ (subscription) => subscription.event === event && subscription.handler === handler
444
+ );
445
+ if (index < 0) {
446
+ return;
447
+ }
448
+ subscriptions.splice(index, 1)[0]?.unsubscribe();
781
449
  }
782
450
  };
783
451
  }
784
- function defaultFetch(input, init) {
785
- if (typeof fetch === "undefined") {
786
- throw new Error("@knot-technologies/seatmap: fetch is not available");
452
+
453
+ // src/engineUrl.ts
454
+ var ENGINE_ARTIFACT = "e452ecefc6c565f3";
455
+ var CDN_BASE = "https://dev-seatmap.knottech.ai";
456
+ function resolveEngineUrl({
457
+ artifact,
458
+ cdnBase
459
+ }) {
460
+ const base = cdnBase.replace(/\/+$/, "");
461
+ if (base.length === 0 || artifact.length === 0) {
462
+ throw new Error("Engine artifact and CDN base must be configured");
787
463
  }
788
- return fetch(input, init);
464
+ return `${base}/engine/${artifact}/engine.html`;
789
465
  }
790
- function redactSecrets(message, secrets) {
791
- let redacted = message;
792
- for (const secret of secrets) {
793
- if (secret.length > 0) redacted = redacted.replaceAll(secret, "[redacted]");
466
+ function engineOrigin(engineUrl) {
467
+ const url = new URL(engineUrl);
468
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
469
+ throw new Error("Engine URL must use HTTP or HTTPS");
794
470
  }
795
- return redacted;
471
+ return url.origin;
796
472
  }
797
- function toSdkError2(error, secrets = []) {
798
- if (isRecord3(error) && typeof error.code === "string" && typeof error.message === "string") {
799
- return { code: error.code, message: redactSecrets(error.message, secrets) };
800
- }
801
- if (error instanceof Error) {
802
- return {
803
- code: "SDK_ERROR",
804
- message: redactSecrets(error.message, secrets)
805
- };
806
- }
807
- return {
808
- code: "SDK_ERROR",
809
- message: redactSecrets(String(error), secrets)
810
- };
811
- }
812
- function toInitPayload(config, endpoints, environment) {
813
- return {
814
- environment,
815
- apiBaseUrl: endpoints.apiBaseUrl,
816
- sseBaseUrl: endpoints.sseBaseUrl,
817
- ...serializeConfigForWire(config, { skipUndefined: true })
818
- };
473
+
474
+ // src/mountSeatmap.ts
475
+ var HANDSHAKE_TIMEOUT_MS = 5e3;
476
+ function isRecord2(value) {
477
+ return typeof value === "object" && value !== null && !Array.isArray(value);
819
478
  }
820
- function engineSrc(deps, environment) {
821
- if (deps.channel !== void 0) {
822
- return engineChannelUrl(deps.channel);
479
+ function isHandshakeAcknowledgement(value) {
480
+ if (typeof value !== "object" || value === null) {
481
+ return false;
823
482
  }
824
- return resolveEngineUrl(environment);
483
+ const result = value;
484
+ return result.protocolVersion === PROTOCOL_VERSION;
825
485
  }
826
- function createChannelId(local) {
827
- const crypto = local.crypto;
828
- if (typeof crypto?.randomUUID === "function") {
829
- return crypto.randomUUID();
830
- }
831
- if (typeof crypto?.getRandomValues === "function") {
832
- const bytes = new Uint8Array(16);
833
- crypto.getRandomValues(bytes);
834
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
835
- ""
836
- );
837
- }
838
- throw new Error(
839
- "@knot-technologies/seatmap: crypto is required to create RPC channel"
486
+ function unreachableError(artifact) {
487
+ return new RpcError(
488
+ "ENGINE_UNREACHABLE",
489
+ `Unable to load engine artifact ${artifact}`
840
490
  );
841
491
  }
842
- function parentOriginOf(local) {
843
- const origin = local.location?.origin;
844
- if (typeof origin !== "string" || origin.length === 0 || origin === "null") {
845
- return void 0;
846
- }
847
- return origin;
848
- }
849
- function withRuntimeParams(src, channelId, parentOrigin) {
850
- const url = new URL(src);
851
- if (parentOrigin !== void 0) {
852
- url.searchParams.set("parentOrigin", parentOrigin);
853
- }
854
- const params = new URLSearchParams(url.hash.slice(1));
855
- params.set("channel", channelId);
856
- url.hash = params.toString();
857
- return url.toString();
858
- }
859
- function engineGateUrl(apiBaseUrl) {
860
- return `${apiBaseUrl.replace(/\/+$/, "")}/v1/engine-gate`;
861
- }
862
- function bestAvailableUrl(apiBaseUrl, session, opts) {
863
- const params = new URLSearchParams({
864
- count: String(opts.quantity),
865
- limit: "1"
866
- });
867
- if (opts.category !== void 0) params.set("categoryIds", opts.category);
868
- return `${apiBaseUrl.replace(/\/+$/, "")}/v4/sessions/${encodeURIComponent(
869
- session
870
- )}/best-available?${params.toString()}`;
871
- }
872
- async function preflightEngineGate(apiBaseUrl, token, fetchImpl) {
873
- let response;
874
- try {
875
- response = await fetchImpl(engineGateUrl(apiBaseUrl), {
876
- method: "GET",
877
- headers: { Authorization: `Bearer ${token}` }
878
- });
879
- } catch (error) {
880
- const message = error instanceof Error ? error.message : String(error);
881
- throw {
882
- code: "ENGINE_GATE_FAILED",
883
- message: `@knot-technologies/seatmap: engine gate request failed: ${message}`
884
- };
885
- }
886
- if (!response.ok) {
887
- throw {
888
- code: "ENGINE_GATE_REJECTED",
889
- message: `@knot-technologies/seatmap: engine gate rejected with ${response.status}`
890
- };
891
- }
892
- }
893
- function isStringArray(value) {
894
- return Array.isArray(value) && value.every((item) => typeof item === "string");
895
- }
896
- function firstBestAvailableSeatIds(value) {
897
- if (!isRecord3(value)) {
898
- throw new Error("best-available response must be an object");
899
- }
900
- const options = value.options;
901
- if (!Array.isArray(options)) {
902
- throw new Error("best-available response options must be an array");
903
- }
904
- if (options.length === 0) return [];
905
- const first = options[0];
906
- if (!isRecord3(first) || !isStringArray(first.seatIds)) {
907
- throw new Error("best-available option seatIds must be a string array");
908
- }
909
- return first.seatIds;
910
- }
911
- async function holdBestAvailable(config, token, apiBaseUrl, fetchImpl, getChart, opts) {
912
- if (!Number.isInteger(opts.quantity) || opts.quantity < 1) {
913
- throw {
914
- code: "BEST_AVAILABLE_INVALID_ARGS",
915
- message: "@knot-technologies/seatmap: quantity must be a positive integer"
916
- };
917
- }
918
- let response;
919
- try {
920
- response = await fetchImpl(
921
- bestAvailableUrl(apiBaseUrl, config.session, opts),
922
- {
923
- method: "GET",
924
- headers: { Authorization: `Bearer ${token}` }
492
+ function configureIframe(iframe, src) {
493
+ iframe.title = "KNOT Seatmap";
494
+ iframe.src = src;
495
+ iframe.style.display = "block";
496
+ iframe.style.width = "100%";
497
+ iframe.style.height = "100%";
498
+ iframe.style.border = "0";
499
+ }
500
+ function mountSeatmap(container, config, signal) {
501
+ return new Promise((resolve, reject) => {
502
+ const artifact = ENGINE_ARTIFACT;
503
+ const engineUrl = resolveEngineUrl({ artifact, cdnBase: CDN_BASE });
504
+ const targetOrigin = engineOrigin(engineUrl);
505
+ const channelId = crypto.randomUUID();
506
+ const iframe = document.createElement("iframe");
507
+ configureIframe(iframe, engineUrl);
508
+ let endpoint;
509
+ let transport;
510
+ let detachHandshake;
511
+ let channelStarted = false;
512
+ let settled = false;
513
+ const timer = window.setTimeout(() => {
514
+ fail(
515
+ new RpcError(
516
+ "HANDSHAKE_TIMEOUT",
517
+ `Engine artifact ${artifact} did not acknowledge the handshake`
518
+ )
519
+ );
520
+ }, HANDSHAKE_TIMEOUT_MS);
521
+ function removeMountListeners() {
522
+ iframe.removeEventListener("load", handleLoad);
523
+ iframe.removeEventListener("error", handleError);
524
+ signal?.removeEventListener("abort", handleAbort);
525
+ }
526
+ function removeHandshakeListener() {
527
+ detachHandshake?.();
528
+ detachHandshake = void 0;
529
+ }
530
+ function closeChannel() {
531
+ removeHandshakeListener();
532
+ if (endpoint) {
533
+ endpoint.close();
534
+ } else {
535
+ transport?.close();
925
536
  }
926
- );
927
- } catch (error) {
928
- const message = error instanceof Error ? error.message : String(error);
929
- throw {
930
- code: "BEST_AVAILABLE_FAILED",
931
- message: `@knot-technologies/seatmap: best-available request failed: ${message}`
932
- };
933
- }
934
- if (!response.ok) {
935
- throw {
936
- code: "BEST_AVAILABLE_FAILED",
937
- message: `@knot-technologies/seatmap: best-available rejected with ${response.status}`
938
- };
939
- }
940
- const seatIds = firstBestAvailableSeatIds(await response.json());
941
- if (seatIds.length === 0) return [];
942
- const chart = getChart();
943
- await chart.selectObjects(seatIds);
944
- return chart.listSelectedObjects();
945
- }
946
- function mountSeatmapInternal(container, config, deps = {}) {
947
- const sensitiveTokens = /* @__PURE__ */ new Set();
948
- sensitiveTokens.add(config.token);
949
- let failureNotified = false;
950
- const notifyFailure = (error) => {
951
- if (failureNotified) return;
952
- failureNotified = true;
953
- config.onChartRenderingFailed?.(toSdkError2(error, sensitiveTokens));
954
- };
955
- try {
956
- const domFactory = deps.domFactory ?? defaultDomFactory;
957
- const local = deps.localWindow ?? defaultLocalWindow();
958
- const fetchImpl = deps.fetchImpl ?? defaultFetch;
959
- const channelId = deps.channelId ?? createChannelId(local);
960
- const environment = (0, import_seatmap_types5.resolveSeatmapEnvironment)(config.environment);
961
- const src = withRuntimeParams(
962
- engineSrc(deps, environment),
963
- channelId,
964
- parentOriginOf(local)
965
- );
966
- const engineOrigin = originOf(src);
967
- const endpoints = resolveSdkEndpoints(environment);
968
- let holdState = null;
969
- let teardownDone = false;
970
- let unwire = () => {
971
- };
972
- let autoHeight = null;
973
- let removeFrameErrorListener = () => {
974
- };
975
- let frame = null;
976
- let endpoint = null;
977
- let renderTimer = null;
978
- const teardown = () => {
979
- if (teardownDone) return;
980
- teardownDone = true;
981
- if (renderTimer !== null) {
982
- clearTimeout(renderTimer);
983
- renderTimer = null;
537
+ }
538
+ function cleanFailedMount() {
539
+ window.clearTimeout(timer);
540
+ removeMountListeners();
541
+ closeChannel();
542
+ iframe.remove();
543
+ }
544
+ function fail(error) {
545
+ if (settled) {
546
+ return;
984
547
  }
985
- removeFrameErrorListener();
986
- autoHeight?.dispose();
987
- autoHeight = null;
988
- unwire();
989
- endpoint?.dispose();
990
- frame?.remove();
991
- sensitiveTokens.clear();
992
- };
993
- return new Promise((resolve, reject) => {
994
- let settled = false;
995
- const fail2 = (error) => {
996
- if (settled) return;
997
- settled = true;
998
- notifyFailure(error);
999
- teardown();
1000
- reject(error);
1001
- };
1002
- const succeed = (chart) => {
1003
- if (settled) return;
1004
- settled = true;
1005
- if (renderTimer !== null) {
1006
- clearTimeout(renderTimer);
1007
- renderTimer = null;
548
+ settled = true;
549
+ cleanFailedMount();
550
+ reject(error);
551
+ }
552
+ function handleError() {
553
+ fail(unreachableError(artifact));
554
+ }
555
+ function handleAbort() {
556
+ fail(new RpcError("CHART_DESTROYED", "Seatmap mount was cancelled"));
557
+ }
558
+ function handleLoad() {
559
+ if (settled || channelStarted) {
560
+ return;
561
+ }
562
+ channelStarted = true;
563
+ const target = iframe.contentWindow;
564
+ if (!target) {
565
+ fail(unreachableError(artifact));
566
+ return;
567
+ }
568
+ transport = createWindowTransport({ target, targetOrigin, channelId });
569
+ endpoint = createEndpoint({ transport, channelId });
570
+ const chart = createChartHandle(endpoint, () => {
571
+ iframe.remove();
572
+ });
573
+ const receiveHandshake = (event) => {
574
+ if (event.origin !== targetOrigin || event.source !== target || !isRecord2(event.data) || event.data.channelId !== channelId || event.data.type !== "hello" || typeof event.data.protocolVersion !== "number") {
575
+ return;
576
+ }
577
+ if (event.data.protocolVersion !== PROTOCOL_VERSION) {
578
+ fail(
579
+ new RpcError(
580
+ "ENGINE_INCOMPATIBLE",
581
+ `Engine uses unsupported protocol version ${event.data.protocolVersion}`
582
+ )
583
+ );
584
+ return;
585
+ }
586
+ if (isEnvelope(event.data) && event.data.error) {
587
+ fail(
588
+ new RpcError(
589
+ event.data.error.code,
590
+ event.data.error.message || "Engine rejected the handshake",
591
+ event.data.error.method
592
+ )
593
+ );
594
+ return;
1008
595
  }
1009
- config.onChartRendered?.(chart);
596
+ if (!isEnvelope(event.data) || !isHandshakeAcknowledgement(event.data.result)) {
597
+ fail(
598
+ new RpcError(
599
+ "ENGINE_INCOMPATIBLE",
600
+ "Engine acknowledged with an incompatible protocol version"
601
+ )
602
+ );
603
+ return;
604
+ }
605
+ settled = true;
606
+ window.clearTimeout(timer);
607
+ removeMountListeners();
608
+ removeHandshakeListener();
1010
609
  resolve(chart);
1011
610
  };
1012
- const timeoutMs = deps.renderTimeoutMs ?? DEFAULT_SDK_TIMEOUT_MS;
1013
- renderTimer = setTimeout(() => {
1014
- fail2({
1015
- code: "SDK_MOUNT_TIMEOUT",
1016
- message: `@knot-technologies/seatmap: chart did not render within ${timeoutMs}ms`
1017
- });
1018
- }, timeoutMs);
1019
- const start = async () => {
1020
- await preflightEngineGate(
1021
- endpoints.apiBaseUrl,
1022
- config.token,
1023
- fetchImpl
1024
- );
1025
- frame = domFactory.createFrame(container, src);
1026
- const transport = createWindowTransport({
1027
- local,
1028
- target: frame.contentWindow,
1029
- targetOrigin: engineOrigin,
1030
- acceptOrigin: (origin) => origin === engineOrigin
1031
- });
1032
- const activeEndpoint = new RpcEndpoint({
1033
- transport,
1034
- role: "facade",
1035
- build: deps.build ?? "facade",
1036
- channelId,
1037
- timeoutMs: deps.handshakeTimeoutMs ?? DEFAULT_SDK_TIMEOUT_MS
1038
- });
1039
- endpoint = activeEndpoint;
1040
- let chart = null;
1041
- const getChart = () => {
1042
- if (chart === null) {
1043
- throw new Error(
1044
- "@knot-technologies/seatmap: chart is not initialized"
1045
- );
1046
- }
1047
- return chart;
1048
- };
1049
- chart = createChart({
1050
- endpoint: activeEndpoint,
1051
- getHoldState: () => holdState,
1052
- teardown,
1053
- holdBestAvailable: (opts) => holdBestAvailable(
1054
- config,
1055
- config.token,
1056
- endpoints.apiBaseUrl,
1057
- fetchImpl,
1058
- getChart,
1059
- opts
1060
- ),
1061
- changeConfig: async (patch) => {
1062
- await activeEndpoint.request(
1063
- "changeConfig",
1064
- serializeConfigForWire(patch)
1065
- );
1066
- if ("fitTo" in patch) autoHeight?.setFitTo(patch.fitTo);
1067
- }
1068
- });
1069
- const onFrameError = () => {
1070
- fail2({
1071
- code: "IFRAME_LOAD_FAILED",
1072
- message: "@knot-technologies/seatmap: iframe failed to load"
1073
- });
1074
- };
1075
- frame.iframe.addEventListener("error", onFrameError);
1076
- removeFrameErrorListener = () => {
1077
- frame?.iframe.removeEventListener("error", onFrameError);
1078
- };
1079
- unwire = wireEvents({
1080
- endpoint: activeEndpoint,
1081
- config: {
1082
- ...config,
1083
- onChartRendered: () => succeed(chart),
1084
- onChartRenderingFailed: (error) => fail2(error)
1085
- },
1086
- getChart,
1087
- setHoldState: (state) => {
1088
- holdState = state;
1089
- }
1090
- });
1091
- autoHeight = createFacadeAutoHeightController(
1092
- activeEndpoint,
1093
- frame.iframe,
1094
- config.fitTo
1095
- );
1096
- await activeEndpoint.handshake();
1097
- await activeEndpoint.request(
1098
- "init",
1099
- toInitPayload(config, endpoints, environment)
1100
- );
611
+ window.addEventListener("message", receiveHandshake);
612
+ detachHandshake = () => {
613
+ window.removeEventListener("message", receiveHandshake);
1101
614
  };
1102
- void start().catch(fail2);
1103
- });
1104
- } catch (error) {
1105
- notifyFailure(error);
1106
- return Promise.reject(error);
1107
- }
1108
- }
1109
- function mountSeatmap(container, config, deps = {}) {
1110
- return mountSeatmapInternal(container, config, deps);
615
+ transport.send({
616
+ protocolVersion: PROTOCOL_VERSION,
617
+ channelId,
618
+ type: "hello",
619
+ params: config
620
+ });
621
+ }
622
+ iframe.addEventListener("load", handleLoad);
623
+ iframe.addEventListener("error", handleError);
624
+ signal?.addEventListener("abort", handleAbort, { once: true });
625
+ container.append(iframe);
626
+ if (signal?.aborted) {
627
+ handleAbort();
628
+ }
629
+ });
1111
630
  }
1112
-
1113
- // src/index.ts
1114
- var import_seatmap_types6 = require("@knot-technologies/seatmap-types");
1115
631
  // Annotate the CommonJS export names for ESM import in node:
1116
632
  0 && (module.exports = {
1117
- mountSeatmap,
1118
- resolveSeatmapEnvironment
633
+ mountSeatmap
1119
634
  });
1120
635
  //# sourceMappingURL=index.cjs.map