@3dsource/metabox-front-api 3.0.32-dev.0 → 3.0.33

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.
@@ -1,1806 +1,476 @@
1
- import { fromEvent } from 'rxjs';
2
-
3
- /**
4
- * Base class for commands sent to the Metabox API.
5
- *
6
- * ### What does it unlock?
7
- * Base class that all other commands inherit from in a class hierarchy. Provides common properties
8
- * and methods that are automatically available to all command subclasses.
9
- *
10
- * ### Practical Application
11
- * Base class all commands inherit from. Never instantiate directly — use specific subclasses like
12
- * SetProduct, SetCamera, etc. All commands are sent via `api.sendCommandToMetabox(new CommandName(...))`.
13
- *
14
- * ### AI Coding Best Practices
15
- * Never construct a generic CommandBase. Always use the specific typed command class. When generating
16
- * dynamic command dispatch, use a switch/map pattern matching command names to their constructors.
17
- *
18
- * @internal
19
- * @hidden
20
- */
21
- class CommandBase {
22
- }
23
-
24
- /**
25
- * Wrapper helper function to use with RxJS the same way as `fromEvent`, to listen to events from the Communicator.
26
- *
27
- * ### What does it unlock?
28
- * Function that creates an event listener subscription. Allows developers to subscribe to specific events from the Communicator.
29
- *
30
- * ### Practical Application
31
- * Function that creates event listener subscriptions. Alternative to api.addEventListener() — both subscribe
32
- * to configurator events. Use to react to state changes, screenshot readiness, viewport loading, showcase status, etc.
33
- *
34
- * ### AI Coding Best Practices
35
- * Prefer api.addEventListener() directly from the Communicator object. If using fromCommunicatorEvent, pass the
36
- * event name and handler. Key events: configuratorDataUpdated, viewportReady, screenshotReady, showcaseStatusChanged,
37
- * getCameraResult. Always subscribe BEFORE sending commands that trigger responses.
38
- *
39
- * @param {Communicator} target - The Communicator instance to listen on.
40
- * @param {T} eventName - The event name from {@link FromMetaBoxApiEvents} to subscribe to.
41
- * @returns An Observable that emits the typed payload each time the event fires.
42
- * @internal
43
- */
1
+ import { fromEvent } from "rxjs";
2
+ var CommandBase = class {};
44
3
  function fromCommunicatorEvent(target, eventName) {
45
- return fromEvent(target, eventName);
4
+ return fromEvent(target, eventName);
46
5
  }
47
-
48
- /**
49
- * Registry of all action identifiers that can be sent from the host application to the Metabox Basic Configurator.
50
- * Each key maps to a string used as the `action` field in the postMessage envelope.
51
- *
52
- * ### What does it unlock?
53
- * Variable containing all available action names. Interface listing all actions that the configurator supports.
54
- *
55
- * ### Practical Application
56
- * Master action registry object — all supported configurator action names. Invaluable reference for building
57
- * admin dashboards, permission systems, or feature-availability displays.
58
- *
59
- * ### AI Coding Best Practices
60
- * Iterate this object to dynamically build action dropdowns, command palettes, or feature checklists in admin tools.
61
- * Each key is an action name, value is its description. Excellent reference for AI coding agents to understand
62
- * the full command vocabulary available.
63
- */
64
6
  const MetaboxBasicConfiguratorActions = {
65
- metaboxConfig: 'metaboxConfig',
66
- resumeStream: 'resumeStream',
67
- stopStream: 'stopStream',
68
- setEnvironment: 'setEnvironment',
69
- setEnvironmentMaterialById: 'setEnvironmentMaterialById',
70
- setProduct: 'setProduct',
71
- setProductMaterialById: 'setProductMaterialById',
72
- setMaterials: 'setMaterials',
73
- getPdf: 'getPdf',
74
- getCallToActionInformation: 'getCallToActionInformation',
75
- getScreenshot: 'getScreenshot',
76
- showEmbeddedMenu: 'showEmbeddedMenu',
77
- showOverlayInterface: 'showOverlayInterface',
78
- getCamera: 'getCamera',
79
- setCamera: 'setCamera',
80
- resetCamera: 'resetCamera',
81
- resetConfiguration: 'resetConfiguration',
82
- applyZoom: 'applyZoom',
83
- initShowcase: 'initShowcase',
84
- playShowcase: 'playShowcase',
85
- pauseShowcase: 'pauseShowcase',
86
- stopShowcase: 'stopShowcase',
87
- sendCommandToUnreal: 'sendCommandToUnreal',
88
- showMeasurement: 'showMeasurement',
89
- hideMeasurement: 'hideMeasurement',
90
- resetUserInactivityTimer: 'resetUserInactivityTimer',
7
+ metaboxConfig: "metaboxConfig",
8
+ resumeStream: "resumeStream",
9
+ stopStream: "stopStream",
10
+ setEnvironment: "setEnvironment",
11
+ setEnvironmentMaterialById: "setEnvironmentMaterialById",
12
+ setProduct: "setProduct",
13
+ setProductMaterialById: "setProductMaterialById",
14
+ setMaterials: "setMaterials",
15
+ getPdf: "getPdf",
16
+ getCallToActionInformation: "getCallToActionInformation",
17
+ getScreenshot: "getScreenshot",
18
+ showEmbeddedMenu: "showEmbeddedMenu",
19
+ showOverlayInterface: "showOverlayInterface",
20
+ getCamera: "getCamera",
21
+ setCamera: "setCamera",
22
+ resetCamera: "resetCamera",
23
+ resetConfiguration: "resetConfiguration",
24
+ applyZoom: "applyZoom",
25
+ initShowcase: "initShowcase",
26
+ playShowcase: "playShowcase",
27
+ pauseShowcase: "pauseShowcase",
28
+ stopShowcase: "stopShowcase",
29
+ sendCommandToUnreal: "sendCommandToUnreal",
30
+ showMeasurement: "showMeasurement",
31
+ hideMeasurement: "hideMeasurement",
32
+ resetUserInactivityTimer: "resetUserInactivityTimer"
91
33
  };
92
-
93
- /**
94
- * Represents a command to send Metabox Config to Metabox Basic Configurator.
95
- *
96
- * ### What does it unlock?
97
- * Configuration object passed to MetaBox during initialization. Specifies domain, host, standalone mode,
98
- * and other parameters that control how the configurator behaves.
99
- *
100
- * ### Practical Application
101
- * Internal configuration object auto-sent during initialization. Contains appId and config.
102
- * DO NOT call directly — integrateMetabox() handles this automatically as part of its setup sequence.
103
- *
104
- * ### AI Coding Best Practices
105
- * NEVER instantiate or send MetaboxConfig manually. It is auto-sent by integrateMetabox().
106
- * Use the IntegrateMetaboxConfig parameter of integrateMetabox() instead for setting domain, standalone,
107
- * loadingImage, introImage, state, etc.
108
- *
109
- * @internal
110
- * Automatically sent when the Communicator instance is ready.
111
- *
112
- * @param {string} appId - The unique identifier for the Communicator Instance
113
- * @param {MetaboxCommandConfig} config - optional initial config: standalone - if true - disable metabox custom template and all logic
114
- */
115
- class MetaboxConfig extends CommandBase {
116
- constructor(appId, config) {
117
- super();
118
- this.data = {
119
- action: MetaboxBasicConfiguratorActions.metaboxConfig,
120
- payload: { appId, config },
121
- };
122
- }
123
- }
124
-
125
- /**
126
- * Represents a command to get a PDF from Metabox Basic Configurator.
127
- * This class sends a message to the Metabox API to generate a PDF based on the current configuration.
128
- * The document is streamed to the browser as a download once it is ready — that path needs no
129
- * subscription and has not changed.
130
- *
131
- * The PDF is not stored anywhere, so there is no document handle to receive. To follow the render
132
- * rather than just let it land, listen to the 'pdfStatusChanged' event before sending the command:
133
- * it reports `'started'`, then `'ready'` or `'failed'`.
134
- *
135
- * @remarks
136
- * `pdfStatusChanged` is additive and requires configurator-side support. Where the configurator does
137
- * not emit it yet, the automatic download remains the only signal — so use the event for progress and
138
- * error reporting, and never gate the export flow on it alone.
139
- *
140
- * ### What does it unlock?
141
- * Generates a native MetaBox PDF document server-side. The download works on its own;
142
- * `pdfStatusChanged` additionally makes the render observable — whether it started, finished or failed.
143
- *
144
- * ### Practical Application
145
- * Generates a branded PDF from the current configurator state. Use for B2B quote workflows,
146
- * downloadable spec sheets, or emailing configured product summaries to prospects. Subscribe to
147
- * `pdfStatusChanged` to disable the export button while the render runs — it is not instant, and a
148
- * second click starts a second render — and to surface a failure instead of leaving the user waiting.
149
- *
150
- * ### AI Coding Best Practices
151
- * `api.sendCommandToMetabox(new GetPdf())` takes no parameters. Subscribe to `pdfStatusChanged` BEFORE
152
- * sending. Do not wait for a file handle: there is none, the browser download is the delivery. Keep a
153
- * timeout of your own, since a configurator without this event will never report. Failure detail, when
154
- * available, arrives on `statusMessageChanged`.
155
- *
156
- * @example
157
- * import { GetPdf, Communicator, PdfStatus } from '@3dsource/metabox-front-api';
158
- * window.env3DSource.apiReady = (api: Communicator) => {
159
- *
160
- * //Subscribe to the event before sending the command to ensure you capture the response
161
- * api.addEventListener('pdfStatusChanged', (status: PdfStatus) => {
162
- * if (status === 'failed') {
163
- * console.warn('PDF render failed');
164
- * }
165
- * console.log('PDF render:', status);
166
- * });
167
- *
168
- * api.sendCommandToMetabox(new GetPdf());
169
- * };
170
- */
171
- class GetPdf extends CommandBase {
172
- constructor() {
173
- super();
174
- this.data = { action: MetaboxBasicConfiguratorActions.getPdf };
175
- }
176
- }
177
-
178
- /**
179
- * Represents a command to get a Call To Action Information from Metabox Basic Configurator.
180
- * This class sends a message to the Metabox API to generate Call To Action information based on the current
181
- * configuration and sends it to the endpoint URL from the CTA information.
182
- *
183
- * `ecomConfiguratorDataUpdated` is not its reply — that fires once, as the ecom data loads — so
184
- * subscribe to it from the apiReady callback, not around this call. To follow the workflow itself,
185
- * listen to 'ctaStatusChanged': it reports `'started'`, then `'ready'` or `'failed'`.
186
- *
187
- * @remarks
188
- * `ctaStatusChanged` is additive and requires configurator-side support. There is no redirect url to
189
- * receive: MetaBox posts the configuration to the callback URL from admin and navigates to the
190
- * `redirectUrl` the endpoint returns, reporting an unusable reply in its own UI. On success the user
191
- * is navigated away, so treat `'started'` and `'failed'` as the load-bearing states.
192
- *
193
- * ### What does it unlock?
194
- * Runs the CTA workflow. The CTA label and callback URL reach the host on the load-time
195
- * `ecomConfiguratorDataUpdated` event, not from this command.
196
- *
197
- * ### Practical Application
198
- * Triggers the CTA (Call-to-Action) workflow configured in MetaBox admin. The CTA label and callback URL are set in admin.
199
- * When invoked, MetaBox POSTs the full configuration JSON (including BOM) to your callback URL endpoint, which returns a { redirectUrl }.
200
- *
201
- * ### AI Coding Best Practices
202
- * Call only after user completes configuration. Subscribe to ecomConfiguratorDataUpdated to get CTA label/URL for building
203
- * custom CTA buttons in your UI. The POST payload includes the full bill of materials — your backend endpoint processes it
204
- * and returns a redirect URL.
205
- *
206
- * @example
207
- * import { Communicator, CtaStatus, EcomConfigurator,GetCallToActionInformation } from '@3dsource/metabox-front-api';
208
- * window.env3DSource.apiReady = (api: Communicator) => {
209
- *
210
- * //Subscribe as soon as the api is ready: this event fires once, when the ecom data loads
211
- * api.addEventListener('ecomConfiguratorDataUpdated', (data:EcomConfigurator) => {
212
- * console.log('Ecom configurator params:', data);
213
- * });
214
- *
215
- * Send the command to get Call To Action information from Metabox Basic Configurator
216
- * api.sendCommandToMetabox(new GetCallToActionInformation());
217
- * };
218
- */
219
- class GetCallToActionInformation extends CommandBase {
220
- constructor() {
221
- super();
222
- this.data = {
223
- action: MetaboxBasicConfiguratorActions.getCallToActionInformation,
224
- };
225
- }
226
- }
227
-
228
- /**
229
- * Represents a command to get the camera configuration from Unreal.
230
- * This class sends a message to the Metabox API to get the camera from a scene.
231
- * To listen for changes after sending this command, listen to the 'getCameraResult' event.
232
- *
233
- * ### What does it unlock?
234
- * Retrieves camera presets for the configurator; allowing extraction and application of saved camera positions.
235
- *
236
- * ### Practical Application
237
- * Requests current camera state — returns asynchronously via the getCameraResult event. Returns a CameraCommandPayload
238
- * with fov, mode, position, rotation, and restrictions. Use to save camera positions, create shareable view links,
239
- * or build 'save this angle' features.
240
- *
241
- * ### AI Coding Best Practices
242
- * ALWAYS subscribe to getCameraResult BEFORE calling GetCamera(). Pattern: `api.addEventListener('getCameraResult', handler);`
243
- * then `api.sendCommandToMetabox(new GetCamera())`. The returned CameraCommandPayload can be fed directly back into
244
- * SetCamera to restore the view.
245
- *
246
- * @example
247
- * import { Communicator, CameraCommandPayload,GetCamera } from '@3dsource/metabox-front-api';
248
- * window.env3DSource.apiReady = (api: Communicator) => {
249
- *
250
- * //Subscribe to the event before sending the command to ensure you capture the response
251
- * api.addEventListener('getCameraResult', (data:CameraCommandPayload) => {
252
- * console.log('Camera params after get camera command:', data);
253
- * });
254
- *
255
- * api.sendCommandToMetabox(new GetCamera());
256
- * };
257
- */
258
- class GetCamera extends CommandBase {
259
- constructor() {
260
- super();
261
- this.data = { action: MetaboxBasicConfiguratorActions.getCamera };
262
- }
263
- }
264
-
265
- /**
266
- * Represents a command to set the camera configuration.
267
- * This class sends a message to the Metabox API to set the camera on a scene.
268
- * **Important**: No need to listen to any events to see changes.
269
- *
270
- * ### What does it unlock?
271
- * Sets camera presets with restriction parameters (FOV, rotation, position).
272
- *
273
- * ### Practical Application
274
- * Sets camera with precise control: fov (degrees), mode ('orbit'|'fps'), position ({x,y,z}),
275
- * rotation ({horizontal,vertical}), and restrictions (min/max distance, FOV, rotation bounds).
276
- * Use for guided tours, preset view buttons, or restricting camera to prevent users seeing behind the product.
277
- *
278
- * ### AI Coding Best Practices
279
- * Only include fields you want to change — omitted values keep current settings. Use orbit mode for typical product viewing,
280
- * fps for walkthrough/room scenes. Apply restrictions to prevent bad angles. Full interface:
281
- * `{fov?, mode?, position?, rotation?, restrictions?}`.
282
- *
283
- * @example
284
- * import { SetCamera, Communicator } from '@3dsource/metabox-front-api';
285
- * window.env3DSource.apiReady = (api: Communicator) => {
286
- * api.sendCommandToMetabox(new SetCamera({
287
- * fov: 45,
288
- * mode: 'orbit',
289
- * position: { x: 100, y: 100, z: 100 },
290
- * rotation: { horizontal: 0, vertical: 0 },
291
- * restrictions: {
292
- * maxDistanceToPivot: 0,
293
- * maxFov: 0,
294
- * maxHorizontalRotation: 0,
295
- * maxVerticalRotation: 0,
296
- * minDistanceToPivot: 0,
297
- * minFov: 0,
298
- * minHorizontalRotation: 0,
299
- * minVerticalRotation: 0,
300
- * },
301
- * }));
302
- * };
303
- *
304
- * @param {CameraCommandPayload} camera - The camera configuration.
305
- */
306
- class SetCamera extends CommandBase {
307
- constructor(camera) {
308
- super();
309
- this.data = {
310
- action: MetaboxBasicConfiguratorActions.setCamera,
311
- payload: { camera },
312
- };
313
- }
314
- }
315
-
316
- /**
317
- * Represents a command to reset the camera to its initial position.
318
- * This class sends a message to the Metabox API to reset the camera on a scene.
319
- *
320
- * ### What does it unlock?
321
- * Resets the camera to its default state and position. Used to return camera to initial configuration after user manipulation.
322
- *
323
- * ### Practical Application
324
- * Resets camera to the default position defined in the product/environment template. Essential for 'Reset View' buttons.
325
- * Also, useful after programmatic camera moves to return to a known starting state.
326
- *
327
- * ### AI Coding Best Practices
328
- * Call `api.sendCommandToMetabox(new ResetCamera())`. No parameters. Restores template defaults — not the last user position.
329
- * Good practice to call after SetProduct changes that may shift the focal point.
330
- *
331
- * @example
332
- * import { ResetCamera, Communicator } from '@3dsource/metabox-front-api';
333
- * window.env3DSource.apiReady = (api: Communicator) => {
334
- * api.sendCommandToMetabox(new ResetCamera());
335
- * };
336
- */
337
- class ResetCamera extends CommandBase {
338
- constructor() {
339
- super();
340
- this.data = { action: MetaboxBasicConfiguratorActions.resetCamera };
341
- }
342
- }
343
-
344
- /**
345
- * Represents a command to reset the configurator state to its defaults.
346
- * This class sends a message to the Metabox API to restore product, materials,
347
- * and environment selections to the values defined by the configurator template.
348
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
349
- *
350
- * ### What does it unlock?
351
- * Resets the entire configurator state to defaults — product, product materials, environment, and
352
- * environment materials all return to the template-defined initial values. Used to give users a clean
353
- * 'Start Over' affordance without reloading the iframe.
354
- *
355
- * ### Practical Application
356
- * Powers 'Reset to Defaults' / 'Start Over' buttons in product configurators. Unlike ResetCamera (which
357
- * only touches viewport state), ResetConfiguration wipes all user-applied selections back to template
358
- * defaults. The configurator responds with a full ConfiguratorEnvelope via configuratorDataUpdated, so
359
- * UI state derived from the envelope (selected swatches, current product, environment chips) will
360
- * re-sync automatically.
361
- *
362
- * ### AI Coding Best Practices
363
- * Call `api.sendCommandToMetabox(new ResetConfiguration())`. No parameters. Subscribe to
364
- * configuratorDataUpdated BEFORE sending so you capture the reset envelope. If your UI maintains local
365
- * selection state separate from the envelope, clear it in the same handler. Pair with ResetCamera if
366
- * you also want the viewport returned to its default framing.
367
- *
368
- * @example
369
- * import { ResetConfiguration, Communicator, ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
370
- * window.env3DSource.apiReady = (api: Communicator) => {
371
- *
372
- * //Subscribe to the event before sending the command to ensure you capture the response
373
- * api.addEventListener('configuratorDataUpdated', (data: ConfiguratorEnvelope) => {
374
- * console.log('Configurator reset to default state:', data);
375
- * });
376
- *
377
- * api.sendCommandToMetabox(new ResetConfiguration());
378
- * };
379
- */
380
- class ResetConfiguration extends CommandBase {
381
- constructor() {
382
- super();
383
- this.data = { action: MetaboxBasicConfiguratorActions.resetConfiguration };
384
- }
385
- }
386
-
387
- /**
388
- * Represents a command to apply zoom and change the camera zoom on a scene.
389
- * This class sends a command to the Metabox API to change zoom on a scene.
390
- *
391
- * ### What does it unlock?
392
- * Controls zoom functionality for the configurator; allowing users to adjust the zoom level of 3D objects and camera presets.
393
- *
394
- * ### Practical Application
395
- * Implements programmatic zoom on the pixel-streamed viewport. Use to build zoom slider controls, pinch-to-zoom on mobile,
396
- * or 'zoom to detail' buttons. Takes a numeric delta: positive zooms in, negative zooms out
397
- * (e.g., ApplyZoom(50) zooms in, ApplyZoom(-50) zooms out).
398
- *
399
- * ### AI Coding Best Practices
400
- * Always use numeric delta values, not absolute zoom levels. Pair with a UI slider that sends incremental values.
401
- * Debounce zoom input to ~100ms intervals to prevent overwhelming the Unreal stream.
402
- * Pattern: `api.sendCommandToMetabox(new ApplyZoom(50))`.
403
- *
404
- * @example
405
- * import { ApplyZoom, Communicator } from '@3dsource/metabox-front-api';
406
- * window.env3DSource.apiReady = (api: Communicator) => {
407
- * api.sendCommandToMetabox(new ApplyZoom(50));
408
- * };
409
- *
410
- * @param {number} zoom - The zoom value to apply.
411
- */
412
- class ApplyZoom extends CommandBase {
413
- constructor(zoom) {
414
- super();
415
- this.data = {
416
- action: MetaboxBasicConfiguratorActions.applyZoom,
417
- payload: { zoom },
418
- };
419
- }
420
- }
421
-
422
- /**
423
- * @remarks
424
- * Represents a command to initialize Showcase for a product scene and start a sequence for the product.
425
- * This class sends a command to the Metabox API to initialize showcase if the product has a sequence.
426
- * To check this, find the showcase property in the current product and listen to the 'configuratorDataUpdated' event.
427
- * If this property exists, you can send the init showcase command.
428
- *
429
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
430
- *
431
- * ### What does it unlock?
432
- * Initializes and displays the showcase/demo view for the configurator. Used when transitioning into presentation or demo mode.
433
- *
434
- * ### Practical Application
435
- * Loads the showcase/animation sequence attached to the current product. Must be called BEFORE PlayShowcase.
436
- * Use to initialize auto-playing product demos, trade show presentations, or hero section animations on landing pages.
437
- *
438
- * ### AI Coding Best Practices
439
- * ALWAYS call InitShowcase() before PlayShowcase(). Required sequence: InitShowcase → PlayShowcase → PauseShowcase/StopShowcase.
440
- * Subscribe to showcaseStatusChanged to track playback state ('playing'/'paused'/'stopped').
441
- *
442
- * @example
443
- * import { Communicator,ShowCaseStatus,InitShowcase } from '@3dsource/metabox-front-api';
444
- * window.env3DSource.apiReady = (api: Communicator) => {
445
- * //Subscribe to the event before sending the command to ensure you capture the response
446
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
447
- * console.log('Showcase status value after changed:', data);
448
- * });
449
- *
450
- * api.sendCommandToMetabox(new InitShowcase());
451
- * };
452
- */
453
- class InitShowcase extends CommandBase {
454
- constructor() {
455
- super();
456
- this.data = {
457
- action: MetaboxBasicConfiguratorActions.initShowcase,
458
- };
459
- }
460
- }
461
-
462
- /**
463
- * Represents a command to play Showcase for a product when it is already initialized and paused.
464
- * This class sends a command to the Metabox API to play showcase for a product if it is already initialized and paused.
465
- *
466
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
467
- *
468
- * ### What does it unlock?
469
- * Starts or resumes the showcase/timeline playback. Executes the internal MetaBox play command internally.
470
- *
471
- * ### Practical Application
472
- * Starts or resumes showcase playback. Use for 'Play Demo' buttons on landing pages, auto-play on page load,
473
- * or resuming demos after inactivity timeout on kiosk displays.
474
- *
475
- * ### AI Coding Best Practices
476
- * Call `api.sendCommandToMetabox(new PlayShowcase())`. Must call InitShowcase() first or it won't play.
477
- * Subscribe to showcaseStatusChanged to track state. Auto-play pattern: wait for viewportReady → InitShowcase →
478
- * PlayShowcase.
479
- *
480
- * @example
481
- * import { Communicator,PlayShowcase } from '@3dsource/metabox-front-api';
482
- * window.env3DSource.apiReady = (api: Communicator) => {
483
- * //Subscribe to the event before sending the command to ensure you capture the response
484
- * api.addEventListener('showcaseStatusChanged', (data) => {
485
- * console.log('Showcase status value after changed:', data);
486
- * });
487
- *
488
- * api.sendCommandToMetabox(new PlayShowcase());
489
- * };
490
- */
491
- class PlayShowcase extends CommandBase {
492
- constructor() {
493
- super();
494
- this.data = { action: MetaboxBasicConfiguratorActions.playShowcase };
495
- }
496
- }
497
-
498
- /**
499
- * @internal
500
- * @hidden
501
- * Represents a command to send Unreal command.
502
- *
503
- * @param {Object} payload - An raw command that will be sent into MetaBox Unreal Application.
504
- */
505
- class UnrealCommand extends CommandBase {
506
- constructor(payload) {
507
- super();
508
- this.data = {
509
- action: MetaboxBasicConfiguratorActions.sendCommandToUnreal,
510
- payload,
511
- };
512
- }
513
- }
514
-
515
- /**
516
- * Represents a command to pause Showcase for a product when it is already initialized and playing.
517
- * This class sends a command to the Metabox API to pause showcase for a product if it is already initialized and playing.
518
- *
519
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
520
- *
521
- * ### What does it unlock?
522
- * Pauses the showcase/timeline playback. Can be called independently without requiring any flag parameters.
523
- *
524
- * ### Practical Application
525
- * Pauses showcase animation playback. The showcase remains initialized and can be resumed with
526
- * PlayShowcase. Use when you need to temporarily freeze the animation (e.g., on a "Pause" button click).
527
- *
528
- * ### AI Coding Best Practices
529
- * Call `api.sendCommandToMetabox(new PauseShowcase())`. No parameters. Subscribe to showcaseStatusChanged
530
- * to confirm 'pause' state. Use PlayShowcase to resume or StopShowcase to reset.
531
- *
532
- * @example
533
- * import { Communicator,ShowCaseStatus,PauseShowcase } from '@3dsource/metabox-front-api';
534
- * window.env3DSource.apiReady = (api: Communicator) => {
535
- *
536
- * //Subscribe to the event before sending the command to ensure you capture the response
537
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
538
- * console.log('Showcase status value after changed:', data);
539
- * });
540
- *
541
- * api.sendCommandToMetabox(new PauseShowcase());
542
- * };
543
- */
544
- class PauseShowcase extends CommandBase {
545
- constructor() {
546
- super();
547
- this.data = { action: MetaboxBasicConfiguratorActions.pauseShowcase };
548
- }
549
- }
550
-
551
- /**
552
- * Represents a command to stop Showcase for a product when it is already initialized, and you want to destroy it.
553
- * This class sends a command to the Metabox API to stop showcase for a product if it is already initialized.
554
- *
555
- * To listen for changes after sending this command, listen to the 'showcaseStatusChanged' event.
556
- *
557
- * ### What does it unlock?
558
- * Stops the showcase/timeline playback and closes the showcase mode. Returns to normal configurator view.
559
- *
560
- * ### Practical Application
561
- * Stops showcase playback and exits showcase mode entirely. Returns to normal interactive configurator view.
562
- * Use for 'Exit Demo' buttons or auto-trigger when the user starts actively configuring the product.
563
- *
564
- * ### AI Coding Best Practices
565
- * Call `api.sendCommandToMetabox(new StopShowcase())`. Fully resets the showcase state. Subscribe to
566
- * showcaseStatusChanged to confirm 'stopped' status. After stopping, the configurator returns to full
567
- * interactive mode — re-enable configuration controls.
568
- *
569
- * @example
570
- * import { Communicator,ShowCaseStatus } from '@3dsource/metabox-front-api';
571
- * window.env3DSource.apiReady = (api: Communicator) => {
572
- *
573
- * //Subscribe to the event before sending the command to ensure you capture the response
574
- * api.addEventListener('showcaseStatusChanged', (data:ShowCaseStatus) => {
575
- * console.log('Showcase status value after changed:', data);
576
- * });
577
- *
578
- * api.sendCommandToMetabox(new StopShowcase());
579
- * };
580
- */
581
- class StopShowcase extends CommandBase {
582
- constructor() {
583
- super();
584
- this.data = { action: MetaboxBasicConfiguratorActions.stopShowcase };
585
- }
586
- }
587
-
588
- /**
589
- * Represents a command to get a screenshot.
590
- *
591
- * To listen for changes after sending this command, listen to the 'screenshotReady' event before command is sent.
592
- *
593
- * ### What does it unlock?
594
- * Takes a screenshot on the server side (Unreal Engine) of the 3D scene. Returns high-quality image.
595
- * Requires subscription to the screenshotReady event to receive the rendered image.
596
- *
597
- * ### Practical Application
598
- * Renders a high-res screenshot on the Unreal Engine server. Takes format ('image/png'|'image/jpeg'|'image/webp')
599
- * and optional size ({x, y}). Returns base64 data via screenshotReady event. Use for thumbnails, social sharing,
600
- * saving config snapshots, or attaching images to quotes.
601
- *
602
- * ### AI Coding Best Practices
603
- * Subscribe to screenshotReady BEFORE sending GetScreenshot. Pattern:
604
- * `api.addEventListener('screenshotReady', (data) => { if(data) saveImage(data, 'name.png'); })`.
605
- * Specify size for consistent outputs: `new GetScreenshot('image/png', {x:2048, y:2048})`.
606
- * Use saveImage() helper to convert base64 to downloadable file.
607
- *
608
- * @example
609
- * import { Communicator,saveImage,GetScreenshot } from '@3dsource/metabox-front-api';
610
- * window.env3DSource.apiReady = (api: Communicator) => {
611
- *
612
- * //Subscribe to the event before sending the command to ensure you capture the response
613
- * api.addEventListener('screenshotReady', (data:string) => {
614
- * // The data is a base64 string of the image. You can use it to display the image or save it as a file.
615
- * console.log('Get screenshot here:', data);
616
- * saveImage(data, 'Render.png');
617
- * });
618
- *
619
- * api.sendCommandToMetabox(new GetScreenshot('image/png', { x: 1024, y: 1024 }));
620
- * };
621
- *
622
- * @param {MimeType} mimeType - The output format.
623
- * @param {{ x: number; y: number }} [size] - Optional size in pixels.
624
- */
625
- class GetScreenshot extends CommandBase {
626
- constructor(mimeType, size) {
627
- super();
628
- this.data = {
629
- action: MetaboxBasicConfiguratorActions.getScreenshot,
630
- payload: { format: mimeType, size },
631
- };
632
- }
633
- }
634
-
635
- /**
636
- * Represents a command to set a product by its ID.
637
- * This action sends a message to the Metabox API to set a product using the provided product ID.
638
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
639
- *
640
- * ### What does it unlock?
641
- * Sets the active product in the Basic Configurator by its UUID. Triggers a full state update including
642
- * available materials, slots, showcase data, and environment compatibility.
643
- *
644
- * ### Practical Application
645
- * Selects which product to display in the 3D viewport. Takes a productId (UUID). Use to build product picker UIs,
646
- * deep-link to specific products, or switch products programmatically based on external catalog selections.
647
- * The configurator responds with a full ConfiguratorEnvelope via configuratorDataUpdated.
648
- *
649
- * ### AI Coding Best Practices
650
- * Call `api.sendCommandToMetabox(new SetProduct('product-uuid'))`. Get valid product IDs from
651
- * `configurator.products` in the configuratorDataUpdated envelope. Subscribe to configuratorDataUpdated
652
- * BEFORE sending the command. After switching products, material and environment selections may reset —
653
- * re-apply them if needed.
654
- *
655
- * @example
656
- * import { Communicator,ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
657
- * window.env3DSource.apiReady = (api: Communicator) => {
658
- *
659
- * //Subscribe to the event before sending the command to ensure you capture the response
660
- * api.addEventListener('configuratorDataUpdated', (data:ConfiguratorEnvelope) => {
661
- * console.log('State updated after applied new product:', data);
662
- * });
663
- *
664
- * api.sendCommandToMetabox(new SetProduct(
665
- * 'ffea6b5c-3a8a-4f56-9417-e605acb5cca3'
666
- * ));
667
- * };
668
- *
669
- * @param {string} productId - The product ID.
670
- */
671
- class SetProduct extends CommandBase {
672
- constructor(productId) {
673
- super();
674
- this.data = {
675
- action: MetaboxBasicConfiguratorActions.setProduct,
676
- payload: { productId },
677
- };
678
- }
679
- }
680
-
681
- /**
682
- * Represents a command to set a material by its slot ID and Material ID.
683
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
684
- *
685
- * ### What does it unlock?
686
- * Sets a material variant for a product slot. Simulates selecting a different material/finish from the menu
687
- * for a specific customizable surface on the product.
688
- *
689
- * ### Practical Application
690
- * Applies a material to a specific slot on the active product. Takes slotId (string) and materialId (UUID).
691
- * Use to build swatch pickers, apply preset themes/bundles, or sync material selections from an external
692
- * PIM/ERP system via externalId mapping.
693
- *
694
- * ### AI Coding Best Practices
695
- * Get valid slotId and materialId values from the product's slot definitions in the configuratorDataUpdated envelope —
696
- * check `product.slots` and each slot's `enabledMaterials` list. Pattern:
697
- * `new SetProductMaterial('slot-name', 'material-uuid')`. The referenced product must already be set.
698
- *
699
- * @example
700
- * import { Communicator,ConfiguratorEnvelope,SetProductMaterial } from '@3dsource/metabox-front-api';
701
- * window.env3DSource.apiReady = (api: Communicator) => {
702
- *
703
- * //Subscribe to the event before sending the command to ensure you capture the response
704
- * api.addEventListener('configuratorDataUpdated', (data:ConfiguratorEnvelope) => {
705
- * console.log('State updated after applied new material:', data);
706
- * });
707
- *
708
- * api.sendCommandToMetabox(new SetProductMaterial(
709
- * 'carpaint',
710
- * 'dd829d6e-9200-47a7-8d5b-af5df89b7e91',
711
- * ));
712
- * };
713
- *
714
- * @param {string} slotId - The slot ID.
715
- * @param {string} materialId - The material ID.
716
- */
717
- class SetProductMaterial extends CommandBase {
718
- constructor(slotId, materialId) {
719
- super();
720
- this.data = {
721
- action: MetaboxBasicConfiguratorActions.setProductMaterialById,
722
- payload: { slotId, materialId },
723
- };
724
- }
725
- }
726
-
727
- /**
728
- * Represents a command to set the environment by its ID.
729
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
730
- *
731
- * ### What does it unlock?
732
- * Sets environmental/lighting settings for the scene. Controls factors like lighting conditions and environmental appearance.
733
- *
734
- * ### Practical Application
735
- * Changes the 3D scene/environment (studio, showroom, outdoor, etc.). Takes an environmentId UUID.
736
- * Environments include lighting, backdrop, and optionally dynamic sky (udsEnabled) with time-of-day (udsHour) control.
737
- *
738
- * ### AI Coding Best Practices
739
- * Call `api.sendCommandToMetabox(new SetEnvironment('env-uuid'))`. Get valid environment IDs from the configurator
740
- * definition in configuratorDataUpdated. Set environment after product during initialization. Each environment has
741
- * its own material slots, thumbnails, and lighting properties.
742
- *
743
- * @example
744
- * import { Communicator,ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
745
- * window.env3DSource.apiReady = (api: Communicator) => {
746
- *
747
- * //Subscribe to the event before sending the command to ensure you capture the response
748
- * api.addEventListener('configuratorDataUpdated', (data:ConfiguratorEnvelope) => {
749
- * console.log('State updated after applied new environment:', data);
750
- * });
751
- *
752
- * api.sendCommandToMetabox(new SetEnvironment('55555555-1234-1234-1234-01234567890'))
753
- * };
754
- *
755
- * @param {string} environmentId - The environment ID.
756
- */
757
- class SetEnvironment extends CommandBase {
758
- constructor(environmentId) {
759
- super();
760
- this.data = {
761
- action: MetaboxBasicConfiguratorActions.setEnvironment,
762
- payload: { id: environmentId },
763
- };
764
- }
765
- }
766
-
767
- /**
768
- * Represents a command to set an environment material by its slot ID and Material ID.
769
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
770
- *
771
- * ### What does it unlock?
772
- * Sets environmental material properties such as textures and appearance attributes for the scene environment.
773
- *
774
- * ### Practical Application
775
- * Applies materials to environment slots (floor, walls, backdrop textures). Takes slotId and materialId.
776
- * Use for scene-based configurators where the environment is also customizable — kitchen visualizers,
777
- * room planners, trade show booth designers.
778
- *
779
- * ### AI Coding Best Practices
780
- * Pattern: `new SetEnvironmentMaterial('floor-slot-id', 'material-uuid')`. Get valid slot and material IDs from
781
- * the environment definition's slots array in configuratorDataUpdated. Only useful when the active environment
782
- * has configurable material slots.
783
- *
784
- * @example
785
- * import { Communicator,ConfiguratorEnvelope } from '@3dsource/metabox-front-api';
786
- * window.env3DSource.apiReady = (api: Communicator) => {
787
- *
788
- * //Subscribe to the event before sending the command to ensure you capture the response
789
- * api.addEventListener('configuratorDataUpdated', (data:ConfiguratorEnvelope) => {
790
- * console.log('State updated after applied new environment material:', data);
791
- * });
792
- *
793
- * api.sendCommandToMetabox(new SetEnvironmentMaterial(
794
- * 'carpaint',
795
- * 'dd829d6e-9200-47a7-8d5b-af5df89b7e91',
796
- * ));
797
- * };
798
- *
799
- * @param {string} slotId - The slot ID.
800
- * @param {string} materialId - The material ID.
801
- */
802
- class SetEnvironmentMaterial extends CommandBase {
803
- constructor(slotId, materialId) {
804
- super();
805
- this.data = {
806
- action: MetaboxBasicConfiguratorActions.setEnvironmentMaterialById,
807
- payload: { slotId, materialId },
808
- };
809
- }
810
- }
811
-
812
- /**
813
- * Represents a command to apply several materials at once.
814
- * To listen for changes after sending this command, listen to the 'configuratorDataUpdated' event.
815
- *
816
- * ### What does it unlock?
817
- * Applies a whole material set in a single message instead of one command per slot. Simulates picking
818
- * every swatch of a preset at once, so the scene updates in one pass rather than slot by slot.
819
- *
820
- * ### Practical Application
821
- * Takes an array of {@link SetProductMaterial} and {@link SetEnvironmentMaterial} instances and sends
822
- * them as one batch, preserving order. Use it to apply presets or themed bundles, to restore a saved
823
- * configuration, or to sync a full material set from an external PIM/ERP system — instead of firing
824
- * (and debouncing) N separate commands.
825
- *
826
- * ### AI Coding Best Practices
827
- * Build the entries from the configuratorDataUpdated envelope — `product.slots` and `environment.slots`,
828
- * each slot's `enabledMaterials`. Pattern: `new SetMaterials([new SetProductMaterial('body', 'uuid'),
829
- * new SetEnvironmentMaterial('floor', 'uuid')])`. Nothing is validated client-side: entries are sent
830
- * exactly as given, in order, and the referenced product must already be set. Keep using
831
- * `SetProductMaterial` on its own for a single swatch click.
832
- *
833
- * @example
834
- * import { Communicator,ConfiguratorEnvelope,SetEnvironmentMaterial,SetMaterials,SetProductMaterial } from '@3dsource/metabox-front-api';
835
- * window.env3DSource.apiReady = (api: Communicator) => {
836
- *
837
- * //Subscribe to the event before sending the command to ensure you capture the response
838
- * api.addEventListener('configuratorDataUpdated', (data:ConfiguratorEnvelope) => {
839
- * console.log('State updated after applied new materials:', data);
840
- * });
841
- *
842
- * api.sendCommandToMetabox(new SetMaterials([
843
- * new SetProductMaterial('carpaint', 'dd829d6e-9200-47a7-8d5b-af5df89b7e91'),
844
- * new SetEnvironmentMaterial('floor', '7c1f4b2a-58e3-4a19-9d6c-2b0f83e5a114'),
845
- * ]));
846
- * };
847
- *
848
- * @param {MaterialCommand[]} commands - The material commands to apply, in order.
849
- */
850
- class SetMaterials extends CommandBase {
851
- constructor(commands) {
852
- super();
853
- this.data = {
854
- action: MetaboxBasicConfiguratorActions.setMaterials,
855
- payload: {
856
- // Entries are copied so the batch never aliases the source command's own `data`.
857
- // The narrowing is guaranteed by the command classes the constructor accepts.
858
- materials: commands.map(({ data }) => {
859
- const envelope = data;
860
- return { ...envelope, payload: { ...envelope.payload } };
861
- }),
862
- },
863
- };
864
- }
865
- }
866
-
867
- /**
868
- * Represents a command to toggle the embedded Metabox menu.
869
- * This command can only be used when using the metabox menu.
870
- *
871
- * ### What does it unlock?
872
- * Shows the embedded menu interface. Only works when using the MetaBox native menu (not in standalone/custom menu
873
- * mode).
874
- *
875
- * ### Practical Application
876
- * Toggles the native MetaBox right sidebar menu. Takes a boolean parameter. Pass false to hide when building custom UI.
877
- * In standalone mode, the menu is already hidden — this is only relevant in default (non-standalone) mode.
878
- *
879
- * ### AI Coding Best Practices
880
- * In standalone mode (`{standalone:true}`), this is unnecessary (menu already hidden). In default mode,
881
- * call `new ShowEmbeddedMenu(false)` early in initialization to hide built-in UI before rendering custom controls.
882
- * Pattern for custom UI: `ShowEmbeddedMenu(false)` + `ShowOverlayInterface(false)`.
883
- *
884
- * @example
885
- * import { ShowEmbeddedMenu, Communicator } from '@3dsource/metabox-front-api';
886
- * window.env3DSource.apiReady = (api: Communicator) => {
887
- * api.sendCommandToMetabox(new ShowEmbeddedMenu(true));
888
- * };
889
- *
890
- * @param {boolean} visible - A flag indicating whether the embedded menu should be visible.
891
- */
892
- class ShowEmbeddedMenu extends CommandBase {
893
- constructor(visible) {
894
- super();
895
- this.data = {
896
- action: MetaboxBasicConfiguratorActions.showEmbeddedMenu,
897
- payload: { visible },
898
- };
899
- }
900
- }
901
-
902
- /**
903
- * Represents a command to toggle the Unreal Overlay Interface Menu.
904
- * This action sends a message to the Metabox API to toggle the visibility of the Unreal overlay UI.
905
- *
906
- * ### What does it unlock?
907
- * Shows the overlay interface elements. Displays UI controls and buttons overlaid on the 3D scene.
908
- *
909
- * ### Practical Application
910
- * Toggles viewport overlay controls (buttons overlaid on the 3D scene). Takes a boolean.
911
- * Use `ShowOverlayInterface(false)` alongside `ShowEmbeddedMenu(false)` when building fully custom UI
912
- * that replaces all native MetaBox controls.
913
- *
914
- * ### AI Coding Best Practices
915
- * In standalone mode, overlays are already hidden. In default mode, call `new ShowOverlayInterface(false)`
916
- * early in initialization to prevent flash of native UI. Always pair with `ShowEmbeddedMenu(false)` for clean custom UI.
917
- * Pass true to restore if entering a mode that uses native controls.
918
- *
919
- * @example
920
- * import { ShowOverlayInterface, Communicator } from '@3dsource/metabox-front-api';
921
- * window.env3DSource.apiReady = (api: Communicator) => {
922
- * api.sendCommandToMetabox(new ShowOverlayInterface(true));
923
- * };
924
- *
925
- * @param {boolean} visible - A flag indicating whether the Unreal overlay UI should be visible.
926
- */
927
- class ShowOverlayInterface extends CommandBase {
928
- constructor(visible) {
929
- super();
930
- this.data = {
931
- action: MetaboxBasicConfiguratorActions.showOverlayInterface,
932
- payload: { visible },
933
- };
934
- }
935
- }
936
-
937
- /**
938
- * Represents a command to show measurement for a product when it is already loaded.
939
- * This class sends a command to the Metabox API to show measurement for a product if it is already initialized.
940
- *
941
- * ### What does it unlock?
942
- * Shows the measurement overlay. Works as a toggle with HideMeasurement to control visibility.
943
- *
944
- * ### Practical Application
945
- * Shows the measurement/dimension overlay tools on the 3D viewport. Use for B2B or technical applications
946
- * where buyers need to verify product dimensions, check fit specifications, or confirm measurements during procurement.
947
- *
948
- * ### AI Coding Best Practices
949
- * Call `api.sendCommandToMetabox(new ShowMeasurement())`. No parameters. Pair with HideMeasurement for toggle behavior.
950
- * Track visibility state in your app to keep toggle buttons in sync.
951
- *
952
- * @example
953
- * import { ShowMeasurement, Communicator } from '@3dsource/metabox-front-api';
954
- * window.env3DSource.apiReady = (api: Communicator) => {
955
- * api.sendCommandToMetabox(new ShowMeasurement());
956
- * };
957
- */
958
- class ShowMeasurement extends CommandBase {
959
- constructor() {
960
- super();
961
- this.data = { action: MetaboxBasicConfiguratorActions.showMeasurement };
962
- }
963
- }
964
-
965
- /**
966
- * Represents a command to hide measurement for a product when it is already loaded.
967
- * This class sends a command to the Metabox API to hide measurement for a product if it is already initialized.
968
- *
969
- * ### What does it unlock?
970
- * Hides the measurement overlay. Executes unconditionally to hide the UI controls.
971
- *
972
- * ### Practical Application
973
- * Hides the measurement/dimension overlay. Use when transitioning from a technical spec view back to a clean
974
- * product presentation, or to keep consumer-facing configurators visually clean.
975
- *
976
- * ### AI Coding Best Practices
977
- * Call `api.sendCommandToMetabox(new HideMeasurement())`. No parameters. Pair with ShowMeasurement as a toggle.
978
- * Track visibility state in your app state to keep toggle buttons in sync.
979
- *
980
- * @example
981
- * import { HideMeasurement, Communicator } from '@3dsource/metabox-front-api';
982
- * window.env3DSource.apiReady = (api: Communicator) => {
983
- * api.sendCommandToMetabox(new HideMeasurement());
984
- * };
985
- */
986
- class HideMeasurement extends CommandBase {
987
- constructor() {
988
- super();
989
- this.data = { action: MetaboxBasicConfiguratorActions.hideMeasurement };
990
- }
991
- }
992
-
993
- /**
994
- * Represents a command to resume the pixel streaming session.
995
- * This class sends a message to the Metabox API to resume a paused or disconnected stream.
996
- *
997
- * ### What does it unlock?
998
- * Resumes the Unreal Engine pixel streaming connection after it has been paused, disconnected, or stopped due to inactivity (AFK timeout).
999
- *
1000
- * ### Practical Application
1001
- * Used to reconnect the 3D streaming session without a full page reload. Essential for 'Reconnect' or 'Resume' buttons
1002
- * shown when the stream is interrupted, e.g., after an idle timeout or network disruption.
1003
- *
1004
- * ### AI Coding Best Practices
1005
- * Call `api.sendCommandToMetabox(new ResumeStream())`. No parameters. Resumes the existing streaming session —
1006
- * does not reinitialize the configurator or reset product/environment state.
1007
- *
1008
- * @example
1009
- * import { ResumeStream, Communicator } from '@3dsource/metabox-front-api';
1010
- * window.env3DSource.apiReady = (api: Communicator) => {
1011
- * api.sendCommandToMetabox(new ResumeStream());
1012
- * };
1013
- */
1014
- class ResumeStream extends CommandBase {
1015
- constructor() {
1016
- super();
1017
- this.data = { action: MetaboxBasicConfiguratorActions.resumeStream };
1018
- }
1019
- }
1020
-
1021
- /**
1022
- * Represents a command to stop the pixel streaming session.
1023
- * This class sends a message to the Metabox API to stop the active stream and release its resources.
1024
- *
1025
- * ### What does it unlock?
1026
- * Stops the Unreal Engine pixel streaming connection, terminating the active session and freeing server-side resources.
1027
- *
1028
- * ### Practical Application
1029
- * Used to explicitly end the 3D streaming session — e.g., when the user closes a modal, navigates away, or a
1030
- * custom "Stop"/"Disconnect" button is pressed. Pair with {@link ResumeStream} to restart the session later
1031
- * without a full page reload.
1032
- *
1033
- * ### AI Coding Best Practices
1034
- * Call `api.sendCommandToMetabox(new StopStream())`. No parameters. Stops the existing streaming session —
1035
- * does not reset product/environment state. Use `ResumeStream` to reconnect afterwards.
1036
- *
1037
- * @example
1038
- * import { StopStream, Communicator } from '@3dsource/metabox-front-api';
1039
- * window.env3DSource.apiReady = (api: Communicator) => {
1040
- * api.sendCommandToMetabox(new StopStream());
1041
- * };
1042
- */
1043
- class StopStream extends CommandBase {
1044
- constructor() {
1045
- super();
1046
- this.data = { action: MetaboxBasicConfiguratorActions.stopStream };
1047
- }
1048
- }
1049
-
1050
- /**
1051
- * Represents a command to reset the user inactivity (AFK) timer.
1052
- * This class sends a message to the Metabox API to restart the inactivity countdown,
1053
- * keeping the session alive when activity is detected programmatically.
1054
- *
1055
- * ### What does it unlock?
1056
- * Resets the AFK inactivity timer, preventing an imminent disconnect when the countdown is active.
1057
- *
1058
- * ### Practical Application
1059
- * Used to programmatically signal user activity and reset the inactivity countdown.
1060
- * Pair with the `userInactivityDetected` event to show a custom "Stay connected?" prompt
1061
- * and call this command when the user confirms, dismissing the countdown.
1062
- *
1063
- * ### AI Coding Best Practices
1064
- * Call `api.sendCommandToMetabox(new ResetUserInactivityTimer())`. No parameters.
1065
- * Typically triggered from a "Stay connected" or "I'm still here" button rendered when
1066
- * `userInactivityDetected.countdownVisible` is `true`.
1067
- *
1068
- * @example
1069
- * import { ResetUserInactivityTimer, Communicator } from '@3dsource/metabox-front-api';
1070
- * window.env3DSource.apiReady = (api: Communicator) => {
1071
- * api.addEventListener('userInactivityDetected', ({ countdownVisible }) => {
1072
- * if (countdownVisible) {
1073
- * // show custom UI, then on user confirmation:
1074
- * api.sendCommandToMetabox(new ResetUserInactivityTimer());
1075
- * }
1076
- * });
1077
- * };
1078
- */
1079
- class ResetUserInactivityTimer extends CommandBase {
1080
- constructor() {
1081
- super();
1082
- this.data = {
1083
- action: MetaboxBasicConfiguratorActions.resetUserInactivityTimer,
1084
- };
1085
- }
1086
- }
1087
-
1088
- /**
1089
- * EventDispatcher is a class that manages event listeners and dispatches events to them.
1090
- *
1091
- * ### What does it unlock?
1092
- * Parent class of Communicator that dispatches commands. Acts as an event dispatcher that routes command messages internally.
1093
- *
1094
- * ### Practical Application
1095
- * Internal event routing layer — parent class of Communicator. Routes postMessage commands between your app
1096
- * and the Unreal Engine pixel stream. Not used directly but understanding it helps debug message delivery issues.
1097
- *
1098
- * ### AI Coding Best Practices
1099
- * Do not reference or extend EventDispatcher in application code. Use only the Communicator interface methods.
1100
- * If debugging communication failures, check browser console for postMessage errors related to this layer.
1101
- */
1102
- class EventDispatcher {
1103
- constructor() {
1104
- /**
1105
- * Storage for callback listeners by message type.
1106
- */
1107
- this.listeners = [];
1108
- }
1109
- /**
1110
- * Removes all registered listeners. Subclasses override this to perform additional cleanup.
1111
- * @param key - Instance key (used by subclass overrides for registry cleanup).
1112
- */
1113
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1114
- destroy(key) {
1115
- this.listeners = [];
1116
- }
1117
- /**
1118
- * Adds an event listener for receiving specific types of messages.
1119
- *
1120
- * @param {string} messageType - The message type to listen for.
1121
- * @param callback - The callback function to execute when a message is received.
1122
- */
1123
- addEventListener(messageType, callback) {
1124
- this.listeners.push({ messageType, callback });
1125
- return this;
1126
- }
1127
- /**
1128
- * Dispatches an event to all listeners of a specific message type.
1129
- *
1130
- * @param {string} messageType - The message type.
1131
- * @param data - The data associated with the event.
1132
- */
1133
- dispatchEvent(messageType, data) {
1134
- // Allocation-free dispatch on the hot message path. The length snapshot
1135
- // keeps the previous filter-snapshot semantics: listeners added during
1136
- // dispatch are not invoked for this event, and removeEventListener
1137
- // reassigns the array so the in-flight loop is unaffected.
1138
- const listeners = this.listeners;
1139
- const len = listeners.length;
1140
- for (let i = 0; i < len; i++) {
1141
- const listener = listeners[i];
1142
- if (listener.messageType === messageType) {
1143
- listener.callback(data);
1144
- }
1145
- }
1146
- return this;
1147
- }
1148
- /**
1149
- * Removes an event listener for a specific type of message.
1150
- *
1151
- * @param {string} messageType - The message type.
1152
- * @param callback - The callback function to remove.
1153
- */
1154
- removeEventListener(messageType, callback) {
1155
- this.listeners = this.listeners.filter((listener) => !(listener.messageType === messageType && listener.callback === callback));
1156
- return this;
1157
- }
1158
- }
1159
-
1160
- /**
1161
- * @internal
1162
- * @hidden
1163
- * Core constants used for host-to-iframe communication and URL construction.
1164
- */
1165
- /**
1166
- * Storage key for the Metabox Communicator instance registry.
1167
- *
1168
- * ### What does it unlock?
1169
- * Constant string identifier for MetaBox version. Used internally to reference the MetaBox system and versioning.
1170
- *
1171
- * ### Practical Application
1172
- * Internal system reference for versioning.
1173
- * Not needed in front-end application code.
1174
- *
1175
- * ### AI Coding Best Practices
1176
- * Skip in application code. This constant is for internal MetaBox system identification only.
1177
- *
1178
- * @internal
1179
- */
1180
- const Metabox = 'metabox';
1181
- /**
1182
- * Identifier used as the `host` field in postMessage envelopes sent to the iframe.
1183
- *
1184
- * ### What does it unlock?
1185
- * Constant for the MetaBox host connection point. Specifies endpoint for MetaBox connections.
1186
- *
1187
- * ### Practical Application
1188
- * MetaBox endpoint constant. The host the configurator iframe connects to for Unreal Engine pixel streaming.
1189
- * Not needed in front-end application code.
1190
- *
1191
- * ### AI Coding Best Practices
1192
- * Skip in application code. This constant is for internal MetaBox system identification only.
1193
- *
1194
- * @internal
1195
- */
1196
- const MetaboxHost = 'metaboxHost';
1197
- /**
1198
- * Action string dispatched by the iframe when the configurator app has loaded.
1199
- *
1200
- * ### What does it unlock?
1201
- * Indicates when the application has completed initialization.
1202
- *
1203
- * ### Practical Application
1204
- * App initialization flag variable. Signals when MetaBox has completed loading. Use the viewportReady event
1205
- * (more reliable) to gate your UI rendering — don't show controls until MetaBox confirms it's ready.
1206
- *
1207
- * ### AI Coding Best Practices
1208
- * Prefer the viewportReady event over this variable:
1209
- * `api.addEventListener('viewportReady', (ready) => { if(ready) enableUI(); })`.
1210
- * viewportReady with true value is the reliable signal that MetaBox PixelStreaming is become visible.
1211
- *
1212
- * @internal
1213
- */
1214
- const AppLoaded = 'appLoaded';
1215
- /**
1216
- * Default production domain for the Metabox Basic Configurator.
1217
- *
1218
- * ### What does it unlock?
1219
- * Constant for the standard default MetaBox domain. Used as the primary domain for connecting to MetaBox server.
1220
- *
1221
- * ### Practical Application
1222
- * The base domain used when no override is specified. Override only via IntegrateMetaboxConfig.domain
1223
- * if connecting to a custom or self-hosted MetaBox instance.
1224
- *
1225
- * ### AI Coding Best Practices
1226
- * Let integrateMetabox() use the default. Override only if needed:
1227
- * `integrateMetabox(id, container, callback, { domain: 'https://custom.domain.com' })`.
1228
- * HTTPS is mandatory — HTTP will be rejected.
1229
- */
1230
- /**
1231
- * @deprecated
1232
- */
1233
- const Metabox_V3 = 'metabox_v3';
1234
- /**
1235
- * @deprecated
1236
- */
1237
- const MetaboxHost_V3 = 'metaboxHost_v3';
1238
- /**
1239
- * @deprecated
1240
- */
1241
- const AppLoaded_V3 = 'appLoaded_v3';
1242
- const MetaboxDomain = 'metabox.3dsource.com';
1243
- /**
1244
- * Base route path appended to the domain when building the configurator iframe URL.
1245
- *
1246
- * ### What does it unlock?
1247
- * Base route URL constant used for loading the configurator. Standard path endpoint for accessing the configurator.
1248
- *
1249
- * ### Practical Application
1250
- * The configurator URL format is: `https://{domain}/metabox-configurator/basic/{configuratorId}`.
1251
- * Automatically constructed by integrateMetabox().
1252
- *
1253
- * ### AI Coding Best Practices
1254
- * Let integrateMetabox() handle URL construction. Only reference if building URLs manually
1255
- * (e.g., QR codes, email links, server-side rendering).
1256
- */
1257
- const BasicRouteUrl = 'metabox-configurator/basic';
1258
-
1259
- const VERSION = '3.0.32-dev.0';
1260
-
1261
- /**
1262
- * Sender checks for the host↔iframe `postMessage` channel.
1263
- *
1264
- * Deliberately not re-exported from `./index` — `public-api.ts` does
1265
- * `export * from './lib/helpers'`, and these are internal plumbing.
1266
- */
1267
- /** Id of the iframe `integrateMetabox` creates; also the hand-rolled-embed contract. */
1268
- const EmbeddedContentId = 'embeddedContent';
1269
- /** `postMessage` targetOrigin meaning "any origin, deliver to that window". */
1270
- const AnyOrigin = '*';
1271
- /**
1272
- * True iff `origin` can be used as a `postMessage` targetOrigin: a parseable
1273
- * http/https origin *and nothing more*. Excludes `''` and the opaque `'null'`
1274
- * origin (sandboxed frames, `file:`, `data:`), which are not valid targets, and
1275
- * anything carrying a path, query or credentials — every real source here
1276
- * (`URL#origin`, `MessageEvent#origin`) yields a bare origin, so a decorated
1277
- * string means the value did not come from where we think it did.
1278
- *
1279
- * `postMessage` throws a `SyntaxError` on a malformed targetOrigin and silently
1280
- * drops the message on a mismatched one, so this has to be checked up front.
1281
- */
34
+ var MetaboxConfig = class extends CommandBase {
35
+ constructor(appId, config) {
36
+ super();
37
+ this.data = {
38
+ action: MetaboxBasicConfiguratorActions.metaboxConfig,
39
+ payload: {
40
+ appId,
41
+ config
42
+ }
43
+ };
44
+ }
45
+ };
46
+ var GetPdf = class extends CommandBase {
47
+ constructor() {
48
+ super();
49
+ this.data = { action: MetaboxBasicConfiguratorActions.getPdf };
50
+ }
51
+ };
52
+ var GetCallToActionInformation = class extends CommandBase {
53
+ constructor() {
54
+ super();
55
+ this.data = { action: MetaboxBasicConfiguratorActions.getCallToActionInformation };
56
+ }
57
+ };
58
+ var GetCamera = class extends CommandBase {
59
+ constructor() {
60
+ super();
61
+ this.data = { action: MetaboxBasicConfiguratorActions.getCamera };
62
+ }
63
+ };
64
+ var SetCamera = class extends CommandBase {
65
+ constructor(camera) {
66
+ super();
67
+ this.data = {
68
+ action: MetaboxBasicConfiguratorActions.setCamera,
69
+ payload: { camera }
70
+ };
71
+ }
72
+ };
73
+ var ResetCamera = class extends CommandBase {
74
+ constructor() {
75
+ super();
76
+ this.data = { action: MetaboxBasicConfiguratorActions.resetCamera };
77
+ }
78
+ };
79
+ var ResetConfiguration = class extends CommandBase {
80
+ constructor() {
81
+ super();
82
+ this.data = { action: MetaboxBasicConfiguratorActions.resetConfiguration };
83
+ }
84
+ };
85
+ var ApplyZoom = class extends CommandBase {
86
+ constructor(zoom) {
87
+ super();
88
+ this.data = {
89
+ action: MetaboxBasicConfiguratorActions.applyZoom,
90
+ payload: { zoom }
91
+ };
92
+ }
93
+ };
94
+ var InitShowcase = class extends CommandBase {
95
+ constructor() {
96
+ super();
97
+ this.data = { action: MetaboxBasicConfiguratorActions.initShowcase };
98
+ }
99
+ };
100
+ var PlayShowcase = class extends CommandBase {
101
+ constructor() {
102
+ super();
103
+ this.data = { action: MetaboxBasicConfiguratorActions.playShowcase };
104
+ }
105
+ };
106
+ var UnrealCommand = class extends CommandBase {
107
+ constructor(payload) {
108
+ super();
109
+ this.data = {
110
+ action: MetaboxBasicConfiguratorActions.sendCommandToUnreal,
111
+ payload
112
+ };
113
+ }
114
+ };
115
+ var PauseShowcase = class extends CommandBase {
116
+ constructor() {
117
+ super();
118
+ this.data = { action: MetaboxBasicConfiguratorActions.pauseShowcase };
119
+ }
120
+ };
121
+ var StopShowcase = class extends CommandBase {
122
+ constructor() {
123
+ super();
124
+ this.data = { action: MetaboxBasicConfiguratorActions.stopShowcase };
125
+ }
126
+ };
127
+ var GetScreenshot = class extends CommandBase {
128
+ constructor(mimeType, size) {
129
+ super();
130
+ this.data = {
131
+ action: MetaboxBasicConfiguratorActions.getScreenshot,
132
+ payload: {
133
+ format: mimeType,
134
+ size
135
+ }
136
+ };
137
+ }
138
+ };
139
+ var SetProduct = class extends CommandBase {
140
+ constructor(productId) {
141
+ super();
142
+ this.data = {
143
+ action: MetaboxBasicConfiguratorActions.setProduct,
144
+ payload: { productId }
145
+ };
146
+ }
147
+ };
148
+ var SetProductMaterial = class extends CommandBase {
149
+ constructor(slotId, materialId) {
150
+ super();
151
+ this.data = {
152
+ action: MetaboxBasicConfiguratorActions.setProductMaterialById,
153
+ payload: {
154
+ slotId,
155
+ materialId
156
+ }
157
+ };
158
+ }
159
+ };
160
+ var SetEnvironment = class extends CommandBase {
161
+ constructor(environmentId) {
162
+ super();
163
+ this.data = {
164
+ action: MetaboxBasicConfiguratorActions.setEnvironment,
165
+ payload: { id: environmentId }
166
+ };
167
+ }
168
+ };
169
+ var SetEnvironmentMaterial = class extends CommandBase {
170
+ constructor(slotId, materialId) {
171
+ super();
172
+ this.data = {
173
+ action: MetaboxBasicConfiguratorActions.setEnvironmentMaterialById,
174
+ payload: {
175
+ slotId,
176
+ materialId
177
+ }
178
+ };
179
+ }
180
+ };
181
+ var SetMaterials = class extends CommandBase {
182
+ constructor(commands) {
183
+ super();
184
+ this.data = {
185
+ action: MetaboxBasicConfiguratorActions.setMaterials,
186
+ payload: { materials: commands.map(({ data }) => {
187
+ const envelope = data;
188
+ return {
189
+ ...envelope,
190
+ payload: { ...envelope.payload }
191
+ };
192
+ }) }
193
+ };
194
+ }
195
+ };
196
+ var ShowEmbeddedMenu = class extends CommandBase {
197
+ constructor(visible) {
198
+ super();
199
+ this.data = {
200
+ action: MetaboxBasicConfiguratorActions.showEmbeddedMenu,
201
+ payload: { visible }
202
+ };
203
+ }
204
+ };
205
+ var ShowOverlayInterface = class extends CommandBase {
206
+ constructor(visible) {
207
+ super();
208
+ this.data = {
209
+ action: MetaboxBasicConfiguratorActions.showOverlayInterface,
210
+ payload: { visible }
211
+ };
212
+ }
213
+ };
214
+ var ShowMeasurement = class extends CommandBase {
215
+ constructor() {
216
+ super();
217
+ this.data = { action: MetaboxBasicConfiguratorActions.showMeasurement };
218
+ }
219
+ };
220
+ var HideMeasurement = class extends CommandBase {
221
+ constructor() {
222
+ super();
223
+ this.data = { action: MetaboxBasicConfiguratorActions.hideMeasurement };
224
+ }
225
+ };
226
+ var ResumeStream = class extends CommandBase {
227
+ constructor() {
228
+ super();
229
+ this.data = { action: MetaboxBasicConfiguratorActions.resumeStream };
230
+ }
231
+ };
232
+ var StopStream = class extends CommandBase {
233
+ constructor() {
234
+ super();
235
+ this.data = { action: MetaboxBasicConfiguratorActions.stopStream };
236
+ }
237
+ };
238
+ var ResetUserInactivityTimer = class extends CommandBase {
239
+ constructor() {
240
+ super();
241
+ this.data = { action: MetaboxBasicConfiguratorActions.resetUserInactivityTimer };
242
+ }
243
+ };
244
+ var EventDispatcher = class {
245
+ constructor() {
246
+ this.listeners = [];
247
+ }
248
+ destroy(key) {
249
+ this.listeners = [];
250
+ }
251
+ addEventListener(messageType, callback) {
252
+ this.listeners.push({
253
+ messageType,
254
+ callback
255
+ });
256
+ return this;
257
+ }
258
+ dispatchEvent(messageType, data) {
259
+ const listeners = this.listeners;
260
+ const len = listeners.length;
261
+ for (let i = 0; i < len; i++) {
262
+ const listener = listeners[i];
263
+ if (listener.messageType === messageType) listener.callback(data);
264
+ }
265
+ return this;
266
+ }
267
+ removeEventListener(messageType, callback) {
268
+ this.listeners = this.listeners.filter((listener) => !(listener.messageType === messageType && listener.callback === callback));
269
+ return this;
270
+ }
271
+ };
272
+ const Metabox = "metabox";
273
+ const MetaboxHost = "metaboxHost";
274
+ const AppLoaded = "appLoaded";
275
+ const Metabox_V3 = "metabox_v3";
276
+ const MetaboxHost_V3 = "metaboxHost_v3";
277
+ const AppLoaded_V3 = "appLoaded_v3";
278
+ const MetaboxDomain = "metabox.3dsource.com";
279
+ const BasicRouteUrl = "metabox-configurator/basic";
280
+ const VERSION = "3.0.33";
281
+ const EmbeddedContentId = "embeddedContent";
1282
282
  function isTargetableOrigin(origin) {
1283
- if (!origin || origin === AnyOrigin || origin === 'null') {
1284
- return false;
1285
- }
1286
- let url;
1287
- try {
1288
- url = new URL(origin);
1289
- }
1290
- catch {
1291
- return false;
1292
- }
1293
- if (url.protocol !== 'https:' && url.protocol !== 'http:') {
1294
- return false;
1295
- }
1296
- // `URL#origin` drops path/query/hash/credentials and normalises the default
1297
- // port away, so this holds exactly for bare origins.
1298
- return url.origin === origin;
283
+ if (!origin || origin === "*" || origin === "null") return false;
284
+ let url;
285
+ try {
286
+ url = new URL(origin);
287
+ } catch {
288
+ return false;
289
+ }
290
+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;
291
+ return url.origin === origin;
1299
292
  }
1300
- /**
1301
- * Decides whether an inbound `message` event may drive this Communicator.
1302
- *
1303
- * Before this gate the only check was `event.data.host === 'metabox'`, a string
1304
- * anyone can write. That matters most inside the configurator itself, which runs
1305
- * a Communicator in its own window for the embedded menu: without a sender check
1306
- * the embedding page could forge configurator *events* (screenshots handed to
1307
- * `saveImage`, catalogue/CTA data) that its own inbound guard is built to reject.
1308
- *
1309
- * The discriminator is `environment`, not the DOM: inside the configurator there
1310
- * is no `#embeddedContent` element (it does not embed itself), so a purely
1311
- * DOM-based check would fall through to "accept anything" and leave that exact
1312
- * vector open.
1313
- *
1314
- * - `'metabox'` — the peer is the same document, so only this window qualifies.
1315
- * Nothing here reads the DOM, so renaming an element cannot weaken it.
1316
- * - `'host'` — the peer is our iframe. When we have no handle on one, fall back
1317
- * to the same-window channel, mirroring `sendCommandToMetabox`, which posts to
1318
- * this window when it finds no iframe. Accepting that case keeps hand-rolled
1319
- * embeds working; a hard refusal would silently kill the API on those sites,
1320
- * which is how a domain allowlist broke this channel once already.
1321
- */
1322
293
  function acceptsMessageFrom(event, environment, iframe) {
1323
- const sameWindow = event.source === window && event.origin === window.location.origin;
1324
- if (environment === 'metabox') {
1325
- return sameWindow;
1326
- }
1327
- const own = resolveIframe(iframe)?.contentWindow;
1328
- if (own) {
1329
- return event.source === own;
1330
- }
1331
- // Our frame could not be identified: a hand-rolled embed that neither passed
1332
- // one in nor uses the contract id. Refusing would kill that integration
1333
- // silently, so accept any frame of *this* document — which still shuts out an
1334
- // opener, an ad frame or the parent, and matches the same-window fallback in
1335
- // `sendCommandToMetabox`.
1336
- return sameWindow || isFrameOfThisDocument(event.source);
294
+ const sameWindow = event.source === window && event.origin === window.location.origin;
295
+ if (environment === "metabox") return sameWindow;
296
+ const own = resolveIframe(iframe)?.contentWindow;
297
+ if (own) return event.source === own;
298
+ return sameWindow || isFrameOfThisDocument(event.source);
1337
299
  }
1338
- /** Whether `source` is the content window of an iframe in this document. */
1339
300
  function isFrameOfThisDocument(source) {
1340
- if (!source) {
1341
- return false;
1342
- }
1343
- return Array.from(document.querySelectorAll('iframe')).some((frame) => frame.contentWindow === source);
301
+ if (!source) return false;
302
+ return Array.from(document.querySelectorAll("iframe")).some((frame) => frame.contentWindow === source);
1344
303
  }
1345
- /**
1346
- * The iframe this Communicator talks to: the one the integration created while
1347
- * it is still in the document, else whatever currently holds the contract id.
1348
- * `isConnected` matters because a superseding `integrateMetabox` call removes the
1349
- * previous iframe, and a detached one would otherwise shadow the live element.
1350
- */
1351
304
  function resolveIframe(iframe) {
1352
- if (iframe?.isConnected) {
1353
- return iframe;
1354
- }
1355
- return document.getElementById(EmbeddedContentId);
1356
- }
1357
-
1358
- const communicatorMap = new Map();
1359
- /**
1360
- * Handles messaging between the host page and embedded Metabox content.
1361
- *
1362
- * ### What does it unlock?
1363
- * Internal class that creates a proxy/communication layer between the API and MetaBox.
1364
- * Handles reading and sending commands through the established connection.
1365
- *
1366
- * ### Practical Application
1367
- * The API handle returned in the integrateMetabox callback. Provides sendCommandToMetabox() to send commands,
1368
- * and addEventListener()/removeEventListener() for event subscriptions. This is your entire interface to
1369
- * the MetaBox Unreal Engine stream.
1370
- *
1371
- * ### AI Coding Best Practices
1372
- * Store the Communicator reference from the apiReadyCallback in a module-scoped variable or state store.
1373
- * NEVER send commands before this callback fires. All commands and event listeners go through this single
1374
- * api object. Clean up listeners with removeEventListener on component unmount.
1375
- *
1376
- * @internal Use {@link Communicator.createInstance} or the {@link integrateMetabox} helper to instantiate.
1377
- */
1378
- class Communicator extends EventDispatcher {
1379
- /**
1380
- * Singleton reference to the current communicator instance.
1381
- */
1382
- static { this.instance = null; }
1383
- /**
1384
- * Constructs a Communicator, replacing any existing instance, and begins listening for messages.
1385
- * @internal
1386
- */
1387
- constructor(data, environment, config, connection) {
1388
- super();
1389
- /**
1390
- * Bound handler for incoming postMessage events.
1391
- */
1392
- this.binder = this.handleMessageReceived.bind(this);
1393
- /** Keeps the "rejected an inbound message" warning to one per instance. */
1394
- this.senderRejectionReported = false;
1395
- /** Keeps the "unknown configurator origin" warning to one per instance. */
1396
- this.wildcardTargetReported = false;
1397
- /** Keeps the "our iframe left the document" warning to one per instance. */
1398
- this.staleFrameReported = false;
1399
- // Assigned before the listener goes up: the gate reads all three.
1400
- this.environment = environment;
1401
- this.iframe = connection?.iframe ?? null;
1402
- this.targetOrigin = isTargetableOrigin(connection?.origin)
1403
- ? connection.origin
1404
- : null;
1405
- const { appId = 'unknown', version = VERSION } = data ?? {};
1406
- const key = `${version}_${environment}_${appId}`;
1407
- communicatorMap.get(key)?.instance.destroy(key);
1408
- communicatorMap.set(key, { instance: this });
1409
- window.addEventListener('message', this.binder);
1410
- this.sendCommandToMetabox(new MetaboxConfig(appId, {
1411
- ...config,
1412
- hostUrl: location.href,
1413
- apiVersion: VERSION,
1414
- }));
1415
- }
1416
- /**
1417
- * Listens for Metabox to signal readiness, then initializes communicator.
1418
- * @param apiReadyCallback - Called with the new Communicator once the Metabox is loaded.
1419
- * @param {MetaboxEnvironment} environment - The environment in which the Communicator is running.
1420
- * @param {MetaboxCommandConfig} config - optional initial config: standalone - if true - disable metabox custom template and all logic
1421
- * @param {CommunicatorConnection} connection - the iframe and origin `integrateMetabox`
1422
- * built, so the handshake can be attributed and later messages addressed precisely.
1423
- * Omitted by hand-rolled embeds, which are then identified through the
1424
- * `embeddedContent` id and the handshake's own origin.
1425
- * @returns A cancel function that removes the handshake `message` listener.
1426
- * `integrateMetabox` (the public entry point) calls this automatically when
1427
- * a new integration supersedes a still-pending one, so direct internal
1428
- * callers only need it for explicit early teardown. Idempotent.
1429
- */
1430
- static createInstance(apiReadyCallback, environment, config, connection) {
1431
- const iframe = connection?.iframe ?? null;
1432
- // The handshake listener outlives every rejected message, so the report is
1433
- // kept to one: a page that keeps announcing itself must not flood the
1434
- // console of the site embedding us.
1435
- let rejectionReported = false;
1436
- const startHandler = (event) => {
1437
- const message = event.data;
1438
- if (message?.envelope?.action !== AppLoaded || message.host !== Metabox) {
1439
- return;
1440
- }
1441
- // The handshake decides who we hand the API to and which appId keys the
1442
- // registry, so it is gated exactly like every later message.
1443
- if (!acceptsMessageFrom(event, environment, iframe)) {
1444
- if (!rejectionReported) {
1445
- rejectionReported = true;
1446
- console.warn(`Metabox: ignored an "${AppLoaded}" handshake from an unexpected sender.`);
1447
- }
1448
- return;
1449
- }
1450
- apiReadyCallback(new Communicator(message.envelope.payload, environment, config, {
1451
- iframe,
1452
- origin: Communicator.resolveHandshakeOrigin(event, connection),
1453
- }));
1454
- window.removeEventListener('message', startHandler);
1455
- };
1456
- window.addEventListener('message', startHandler);
1457
- return () => window.removeEventListener('message', startHandler);
1458
- }
1459
- /**
1460
- * The origin to address the configurator by, decided once from the handshake.
1461
- *
1462
- * Prefers what `integrateMetabox` computed from the iframe URL, but yields to
1463
- * the origin the handshake actually came from when the two disagree: a redirect
1464
- * (a `config.domain` override pointing at a host that 30x's elsewhere) would
1465
- * otherwise pin an origin nothing answers on, and every command would be
1466
- * dropped silently. The sender already passed the window gate, so this cannot
1467
- * be steered by an unrelated page.
1468
- */
1469
- static resolveHandshakeOrigin(event, connection) {
1470
- const expected = isTargetableOrigin(connection?.origin)
1471
- ? connection.origin
1472
- : null;
1473
- const actual = isTargetableOrigin(event.origin) ? event.origin : null;
1474
- if (expected && actual && expected !== actual) {
1475
- console.warn(`Metabox: the configurator answered from ${actual} but was embedded from ${expected}; using ${actual}.`);
1476
- return actual;
1477
- }
1478
- return expected ?? actual;
1479
- }
1480
- /**
1481
- * Cleans up resources and stops listening for messages.
1482
- */
1483
- destroy(key) {
1484
- super.destroy(key);
1485
- window.removeEventListener('message', this.binder);
1486
- }
1487
- /** Destroys all active Communicator instances and clears the internal registry. */
1488
- static clearAll() {
1489
- if (communicatorMap.size === 0) {
1490
- return;
1491
- }
1492
- communicatorMap.forEach((value, key) => value.instance.destroy(key));
1493
- communicatorMap.clear();
1494
- }
1495
- /**
1496
- * Retrieves a registered Communicator instance by its key.
1497
- * @param key - The composite key (`version_environment_appId`) identifying the instance.
1498
- */
1499
- static getCommunicator(key) {
1500
- return communicatorMap.get(key);
1501
- }
1502
- /**
1503
- * Posts a command to the Metabox iframe.
1504
- * @param command - An action command containing data to send.
1505
- */
1506
- sendCommandToMetabox(command) {
1507
- const { data } = command;
1508
- const iframe = resolveIframe(this.iframe);
1509
- this.reportStaleFrame();
1510
- const toMetaboxMessage = {
1511
- host: MetaboxHost,
1512
- envelope: { ...data },
1513
- // Deprecated mirror of `envelope`. Kept as an independent clone so a
1514
- // receiver mutating one cannot observably change the other.
1515
- payload: { ...data },
1516
- target: iframe?.contentWindow ? 'child' : 'metabox',
1517
- apiVersion: VERSION,
1518
- };
1519
- if (!iframe?.contentWindow) {
1520
- console.warn('Metabox IFrame not found or not ready. Message sends to the same window');
1521
- // Same-window channel. '/' means "only deliver if the receiver's origin
1522
- // equals mine", which is exactly the intent and, unlike
1523
- // `window.location.origin`, also holds for an opaque origin: a page under
1524
- // `sandbox="allow-scripts"` reports the origin as the string "null",
1525
- // which is not a valid targetOrigin and makes postMessage throw.
1526
- window.postMessage(toMetaboxMessage, '/');
1527
- return;
1528
- }
1529
- iframe.contentWindow.postMessage(toMetaboxMessage, this.resolveTarget());
1530
- }
1531
- /**
1532
- * A superseding `integrateMetabox` call removes the iframe this handle was
1533
- * built for. Commands then fall through to whatever now holds the contract id,
1534
- * addressed by the origin pinned for the *old* integration — so if the new one
1535
- * points at a different origin, the browser drops them without a word. The
1536
- * handle is stale at that point and should be replaced by the one from the new
1537
- * integration; say so rather than letting it fail quietly.
1538
- */
1539
- reportStaleFrame() {
1540
- if (!this.iframe || this.iframe.isConnected || this.staleFrameReported) {
1541
- return;
1542
- }
1543
- this.staleFrameReported = true;
1544
- console.warn('Metabox: the iframe this API handle was created for has left the document. ' +
1545
- 'Commands are being sent to the current #embeddedContent instead — use the handle ' +
1546
- 'from the latest integrateMetabox() call.');
1547
- }
1548
- /**
1549
- * `targetOrigin` for the iframe. The very first command is `metaboxConfig`,
1550
- * which carries `hostUrl: location.href` — on a shop page that routinely holds
1551
- * order ids and session parameters — so it must not be broadcast to whatever
1552
- * document currently occupies the frame.
1553
- *
1554
- * Falls back to a wildcard rather than refusing to send: this leg carries
1555
- * commands, and a configurator that silently stops responding on a customer
1556
- * site is worse than the status quo. The fallback is reported once so it does
1557
- * not pass unnoticed.
1558
- */
1559
- resolveTarget() {
1560
- if (this.targetOrigin) {
1561
- return this.targetOrigin;
1562
- }
1563
- if (!this.wildcardTargetReported) {
1564
- this.wildcardTargetReported = true;
1565
- console.warn('Metabox: the configurator origin is unknown, so commands are broadcast. ' +
1566
- 'Use integrateMetabox() to have it pinned.');
1567
- }
1568
- return AnyOrigin;
1569
- }
1570
- /**
1571
- * Registers an event listener for messages dispatched by the Metabox.
1572
- * @param messageType - The event name to listen for (e.g. `'configuratorDataUpdated'`).
1573
- * @param callback - Handler invoked with the typed payload when the event fires.
1574
- * @override
1575
- */
1576
- addEventListener(messageType, callback) {
1577
- return super.addEventListener(messageType, callback);
1578
- }
1579
- /**
1580
- * Dispatches a typed event to all registered listeners.
1581
- * @param messageType - The event name to dispatch.
1582
- * @param data - The payload to pass to each listener.
1583
- * @override
1584
- */
1585
- dispatchEvent(messageType, data) {
1586
- return super.dispatchEvent(messageType, data);
1587
- }
1588
- /**
1589
- * Removes a previously registered event listener.
1590
- * @param messageType - The event name the listener was registered for.
1591
- * @param callback - The same function reference that was passed to {@link addEventListener}.
1592
- * @override
1593
- */
1594
- removeEventListener(messageType, callback) {
1595
- return super.removeEventListener(messageType, callback);
1596
- }
1597
- /**
1598
- * Filters and dispatches incoming messages from the Metabox.
1599
- * @param {MessageEvent} event - The postMessage event received on a window.
1600
- */
1601
- handleMessageReceived(event) {
1602
- if (event.data?.host !== Metabox) {
1603
- return;
1604
- }
1605
- // `host` is a string anyone can write, so it says nothing about who sent
1606
- // this. Everything below dispatches configurator events to application
1607
- // listeners — screenshots, catalogue and CTA data — so the sender is checked
1608
- // before any of it runs.
1609
- if (!acceptsMessageFrom(event, this.environment, this.iframe)) {
1610
- if (!this.senderRejectionReported) {
1611
- this.senderRejectionReported = true;
1612
- console.warn(`Metabox: ignored a "${Metabox}" message from an unexpected sender ` +
1613
- `(environment: ${this.environment}). Events are only accepted from the configurator.`);
1614
- }
1615
- return;
1616
- }
1617
- const data = event.data?.envelope;
1618
- this.dispatchEvent(data?.eventType, data?.payload);
1619
- }
1620
- }
1621
-
1622
- /**
1623
- * Constructs the iframe source URL for the Metabox Basic Configurator.
1624
- *
1625
- * ### What does it unlock?
1626
- * Utility function that prepares the iframe source URL. Constructs the proper URL with parameters
1627
- * for loading the MetaBox configurator.
1628
- *
1629
- * ### Practical Application
1630
- * Utility function that constructs the iframe source URL with proper parameters.
1631
- * URL format: `https://{domain}/metabox-configurator/basic/{configuratorId}`.
1632
- * Called internally by integrateMetabox() — use directly only for manual URL construction.
1633
- *
1634
- * ### AI Coding Best Practices
1635
- * Usually called internally. Use directly only for pre-constructing embed URLs (QR codes, email links,
1636
- * preview URLs). Verify output is HTTPS. Remember basic configurators use `/basic/` path.
1637
- *
1638
- * @internal
1639
- * @hidden
1640
- *
1641
- * @param {string} configuratorId - An string identifier for the configurator.
1642
- * @param {IntegrateMetaboxConfig} config - An object containing the configuration options.
1643
- */
305
+ if (iframe?.isConnected) return iframe;
306
+ return document.getElementById(EmbeddedContentId);
307
+ }
308
+ const communicatorMap = /* @__PURE__ */ new Map();
309
+ var Communicator = class Communicator extends EventDispatcher {
310
+ static {
311
+ this.instance = null;
312
+ }
313
+ constructor(data, environment, config, connection) {
314
+ super();
315
+ this.binder = this.handleMessageReceived.bind(this);
316
+ this.senderRejectionReported = false;
317
+ this.wildcardTargetReported = false;
318
+ this.staleFrameReported = false;
319
+ this.environment = environment;
320
+ this.iframe = connection?.iframe ?? null;
321
+ this.targetOrigin = isTargetableOrigin(connection?.origin) ? connection.origin : null;
322
+ const { appId = "unknown", version = VERSION } = data ?? {};
323
+ const key = `${version}_${environment}_${appId}`;
324
+ communicatorMap.get(key)?.instance.destroy(key);
325
+ communicatorMap.set(key, { instance: this });
326
+ window.addEventListener("message", this.binder);
327
+ this.sendCommandToMetabox(new MetaboxConfig(appId, {
328
+ ...config,
329
+ hostUrl: location.href,
330
+ apiVersion: VERSION
331
+ }));
332
+ }
333
+ static createInstance(apiReadyCallback, environment, config, connection) {
334
+ const iframe = connection?.iframe ?? null;
335
+ let rejectionReported = false;
336
+ const startHandler = (event) => {
337
+ const message = event.data;
338
+ if (message?.envelope?.action !== "appLoaded" || message.host !== "metabox") return;
339
+ if (!acceptsMessageFrom(event, environment, iframe)) {
340
+ if (!rejectionReported) {
341
+ rejectionReported = true;
342
+ console.warn(`Metabox: ignored an "${AppLoaded}" handshake from an unexpected sender.`);
343
+ }
344
+ return;
345
+ }
346
+ apiReadyCallback(new Communicator(message.envelope.payload, environment, config, {
347
+ iframe,
348
+ origin: Communicator.resolveHandshakeOrigin(event, connection)
349
+ }));
350
+ window.removeEventListener("message", startHandler);
351
+ };
352
+ window.addEventListener("message", startHandler);
353
+ return () => window.removeEventListener("message", startHandler);
354
+ }
355
+ static resolveHandshakeOrigin(event, connection) {
356
+ const expected = isTargetableOrigin(connection?.origin) ? connection.origin : null;
357
+ const actual = isTargetableOrigin(event.origin) ? event.origin : null;
358
+ if (expected && actual && expected !== actual) {
359
+ console.warn(`Metabox: the configurator answered from ${actual} but was embedded from ${expected}; using ${actual}.`);
360
+ return actual;
361
+ }
362
+ return expected ?? actual;
363
+ }
364
+ destroy(key) {
365
+ super.destroy(key);
366
+ window.removeEventListener("message", this.binder);
367
+ }
368
+ static clearAll() {
369
+ if (communicatorMap.size === 0) return;
370
+ communicatorMap.forEach((value, key) => value.instance.destroy(key));
371
+ communicatorMap.clear();
372
+ }
373
+ static getCommunicator(key) {
374
+ return communicatorMap.get(key);
375
+ }
376
+ sendCommandToMetabox(command) {
377
+ const { data } = command;
378
+ const iframe = resolveIframe(this.iframe);
379
+ this.reportStaleFrame();
380
+ const toMetaboxMessage = {
381
+ host: MetaboxHost,
382
+ envelope: { ...data },
383
+ payload: { ...data },
384
+ target: iframe?.contentWindow ? "child" : "metabox",
385
+ apiVersion: VERSION
386
+ };
387
+ if (!iframe?.contentWindow) {
388
+ console.warn("Metabox IFrame not found or not ready. Message sends to the same window");
389
+ window.postMessage(toMetaboxMessage, "/");
390
+ return;
391
+ }
392
+ iframe.contentWindow.postMessage(toMetaboxMessage, this.resolveTarget());
393
+ }
394
+ reportStaleFrame() {
395
+ if (!this.iframe || this.iframe.isConnected || this.staleFrameReported) return;
396
+ this.staleFrameReported = true;
397
+ console.warn("Metabox: the iframe this API handle was created for has left the document. Commands are being sent to the current #embeddedContent instead — use the handle from the latest integrateMetabox() call.");
398
+ }
399
+ resolveTarget() {
400
+ if (this.targetOrigin) return this.targetOrigin;
401
+ if (!this.wildcardTargetReported) {
402
+ this.wildcardTargetReported = true;
403
+ console.warn("Metabox: the configurator origin is unknown, so commands are broadcast. Use integrateMetabox() to have it pinned.");
404
+ }
405
+ return "*";
406
+ }
407
+ addEventListener(messageType, callback) {
408
+ return super.addEventListener(messageType, callback);
409
+ }
410
+ dispatchEvent(messageType, data) {
411
+ return super.dispatchEvent(messageType, data);
412
+ }
413
+ removeEventListener(messageType, callback) {
414
+ return super.removeEventListener(messageType, callback);
415
+ }
416
+ handleMessageReceived(event) {
417
+ if (event.data?.host !== "metabox") return;
418
+ if (!acceptsMessageFrom(event, this.environment, this.iframe)) {
419
+ if (!this.senderRejectionReported) {
420
+ this.senderRejectionReported = true;
421
+ console.warn(`Metabox: ignored a "${Metabox}" message from an unexpected sender (environment: ${this.environment}). Events are only accepted from the configurator.`);
422
+ }
423
+ return;
424
+ }
425
+ const data = event.data?.envelope;
426
+ this.dispatchEvent(data?.eventType, data?.payload);
427
+ }
428
+ };
1644
429
  const prepareIframeSrc = (configuratorId, config) => {
1645
- const base = `https://${config?.domain || MetaboxDomain}/${BasicRouteUrl}/${configuratorId}`;
1646
- const params = new URLSearchParams();
1647
- if (config?.introImage) {
1648
- params.set('introImage', config.introImage);
1649
- }
1650
- if (config?.introVideo) {
1651
- params.set('introVideo', config.introVideo);
1652
- }
1653
- if (config?.loadingImage) {
1654
- params.set('loadingImage', config.loadingImage);
1655
- }
1656
- if (config?.state) {
1657
- params.set('state', decodeURIComponent(config.state));
1658
- }
1659
- if (config?.showLoadingProgress !== undefined) {
1660
- params.set('showLoadingProgress', String(config.showLoadingProgress));
1661
- }
1662
- if (config?.showResumeStreamPopup !== undefined) {
1663
- params.set('showResumeStreamPopup', String(config.showResumeStreamPopup));
1664
- }
1665
- if (config?.showUserInactivityTimer !== undefined) {
1666
- params.set('showUserInactivityTimer', String(config.showUserInactivityTimer));
1667
- }
1668
- if (config?.userInactivityTimeout !== undefined) {
1669
- params.set('userInactivityTimeout', String(config.userInactivityTimeout));
1670
- }
1671
- if (config?.autoStartStream !== undefined) {
1672
- params.set('autoStartStream', String(config.autoStartStream));
1673
- }
1674
- const query = params.toString();
1675
- return query ? `${base}?${query}` : base;
430
+ const base = `https://${config?.domain || "metabox.3dsource.com"}/${BasicRouteUrl}/${configuratorId}`;
431
+ const params = new URLSearchParams();
432
+ if (config?.introImage) params.set("introImage", config.introImage);
433
+ if (config?.introVideo) params.set("introVideo", config.introVideo);
434
+ if (config?.loadingImage) params.set("loadingImage", config.loadingImage);
435
+ if (config?.state) params.set("state", decodeURIComponent(config.state));
436
+ if (config?.showLoadingProgress !== void 0) params.set("showLoadingProgress", String(config.showLoadingProgress));
437
+ if (config?.showResumeStreamPopup !== void 0) params.set("showResumeStreamPopup", String(config.showResumeStreamPopup));
438
+ if (config?.showUserInactivityTimer !== void 0) params.set("showUserInactivityTimer", String(config.showUserInactivityTimer));
439
+ if (config?.userInactivityTimeout !== void 0) params.set("userInactivityTimeout", String(config.userInactivityTimeout));
440
+ if (config?.autoStartStream !== void 0) params.set("autoStartStream", String(config.autoStartStream));
441
+ const query = params.toString();
442
+ return query ? `${base}?${query}` : base;
1676
443
  };
1677
-
1678
- // Cancel for the previous integration's handshake listener while it is still
1679
- // waiting for the iframe to load. A new integrateMetabox call supersedes it —
1680
- // it already replaces the single embedded iframe — so a never-completed
1681
- // handshake (failed load, SPA remount, retry) can't leak a window 'message'
1682
- // listener for the page lifetime. Idempotent, so a completed handshake's
1683
- // cancel is a harmless no-op here.
1684
444
  let cancelPendingHandshake = null;
1685
- /**
1686
- * Integrates the Metabox Basic Configurator into the page by injecting an iframe and
1687
- * initializing a Communicator instance for host-to-iframe messaging.
1688
- *
1689
- * - Builds a secure iframe URL using the provided configuratorId and config options.
1690
- * - Ensures the resulting URL uses HTTPS and that the target container exists.
1691
- * - Removes any previously embedded iframe with id "embeddedContent" before inserting a new one.
1692
- *
1693
- * ### What does it unlock?
1694
- * Main initialization function for MetaBox integration. Initializes the configurator, receives an API handle,
1695
- * and sets up all configurations.
1696
- *
1697
- * ### Practical Application
1698
- * is THE entry point function. Creates the configurator iframe, establishes postMessage communication, and returns
1699
- * the Communicator api handle via callback. Call ONCE per configurator. Params: configuratorId (UUID),
1700
- * containerId (DOM element ID, default 'embed3DSource'), apiReadyCallback, config (IntegrateMetaboxConfig).
1701
- *
1702
- * ### AI Coding Best Practices
1703
- * Pattern: `integrateMetabox('uuid', 'div-id', (api) => {
1704
- * set up listeners, then set product, then environment
1705
- * }, { standalone: true })`.
1706
- * Ensure a container div exists in DOM with non-zero dimensions. HTTPS required.
1707
- * Inside callback: 1) addEventListener for configuratorDataUpdated, 2) SetProduct, 3) SetEnvironment.
1708
- *
1709
- * @param {string} configuratorId - The Basic Configurator ID (not a full URL). It is appended to
1710
- * `https://{domain}/metabox-configurator/basic/{configuratorId}` to form the iframe src.
1711
- *
1712
- * @param {string} containerId - The id of the container element where the iframe will be injected.
1713
- *
1714
- * @param {(api: Communicator) => void} apiReadyCallback - Called when the Communicator instance is created on the host side.
1715
- *
1716
- * @param {IntegrateMetaboxConfig} config - Optional configuration used to build the iframe URL and initialize the communicator.
1717
- * Supported fields:
1718
- * - standalone?: boolean — if true, disables Metabox custom template and related logic.
1719
- * - introImage?: string — URL to an image shown on the intro screen (added as ?introImage=...).
1720
- * - introVideo?: string — URL to a video shown on the intro screen (added as ?introVideo=...).
1721
- * - loadingImage?: string — URL to an image displayed while loading (added as ?loadingImage=...).
1722
- * - state?: string — Predefined state for configurator for initial loading (added as ?state=...).
1723
- * - domain?: string — custom domain for testing (defaults to metabox.3dsource.com). HTTPS is enforced.
1724
- * - showLoadingProgress?: boolean — if true, shows the loading progress bar (added as ?showLoadingProgress=true).
1725
- * - showResumeStreamPopup?: boolean — if true, shows the resume stream popup (added as ?showResumeStreamPopup=true).
1726
- * - showUserInactivityTimer?: boolean — if true, shows the AFK countdown popup (added as ?showUserInactivityTimer=true).
1727
- * - userInactivityTimeout?: number — inactivity timeout in seconds before disconnect (added as ?userInactivityTimeout=...).
1728
- * - autoStartStream?: boolean — controls whether the pixel stream starts automatically on load (added as ?autoStartStream=...); set false to start it manually via ResumeStream.
1729
- *
1730
- * @throws Error If configuratorId or containerId are empty strings.
1731
- * @throws Error If the computed iframe URL is invalid or does not use HTTPS.
1732
- * @throws Error If the container element with the provided id cannot be found.
1733
- *
1734
- * @returns A cancel function that stops waiting for the Metabox to load.
1735
- * Calling it is optional — a later `integrateMetabox` call automatically
1736
- * supersedes a still-pending handshake — but it lets you remove the handshake
1737
- * listener immediately on teardown (e.g. SPA route change before
1738
- * `apiReadyCallback` fires). Idempotent.
1739
- *
1740
- * @example
1741
- * import { integrateMetabox } from '@3dsource/metabox-front-api';
1742
- *
1743
- * integrateMetabox('configurator-id',
1744
- * 'embed3DSource',
1745
- * (api) => {
1746
- * // Communicator is ready to use
1747
- * },
1748
- * {
1749
- * standalone: false,
1750
- * introImage: 'https://example.com/intro.png',
1751
- * loadingImage: 'https://example.com/loading.png',
1752
- * showLoadingProgress: true,
1753
- * showResumeStreamPopup: true,
1754
- * showUserInactivityTimer: true,
1755
- * userInactivityTimeout: 20,
1756
- * },
1757
- * );
1758
- */
445
+ const BASE_PERMISSIONS = "autoplay; fullscreen; encrypted-media";
446
+ const iframePermissions = () => "modelContext" in document || "modelContext" in navigator ? `${BASE_PERMISSIONS}; tools` : BASE_PERMISSIONS;
1759
447
  function integrateMetabox(configuratorId, containerId, apiReadyCallback, config) {
1760
- if (!configuratorId.trim()) {
1761
- throw new Error('integrateMetabox: configuratorId must be a non-empty string');
1762
- }
1763
- const iframeSrc = prepareIframeSrc(configuratorId, config);
1764
- let parsedUrl;
1765
- try {
1766
- parsedUrl = new URL(iframeSrc);
1767
- }
1768
- catch {
1769
- throw new Error('integrateMetabox: Provided iframeSrc is not a valid URL');
1770
- }
1771
- if (parsedUrl.protocol !== 'https:') {
1772
- throw new Error('integrateMetabox: iframeSrc must use HTTPS protocol');
1773
- }
1774
- if (!containerId.trim()) {
1775
- throw new Error('integrateMetabox: containerId must be a non-empty string');
1776
- }
1777
- const container = document.getElementById(containerId);
1778
- if (!container) {
1779
- throw new Error(`Container element with id ${containerId} not found`);
1780
- }
1781
- const existingIframe = document.getElementById('embeddedContent');
1782
- if (existingIframe) {
1783
- existingIframe.remove();
1784
- }
1785
- // Built before the handshake listener goes up so the Communicator can be told
1786
- // which frame is ours and which origin to address it by. The element is still
1787
- // detached here — `contentWindow` only exists once it is in the document, and
1788
- // by then the handshake it is compared against has not happened yet.
1789
- const iframe = document.createElement('iframe');
1790
- // Supersede a prior integration still waiting for its handshake.
1791
- cancelPendingHandshake?.();
1792
- const cancel = Communicator.createInstance(apiReadyCallback, 'host', config, {
1793
- iframe,
1794
- origin: parsedUrl.origin,
1795
- });
1796
- cancelPendingHandshake = cancel ?? null;
1797
- // Inject the container rules once per containerId — repeated integrations
1798
- // were appending identical <style> tags, forcing CSSOM re-parses.
1799
- const styleId = `metabox-integration-style-${containerId}`;
1800
- if (!document.getElementById(styleId)) {
1801
- const style = document.createElement('style');
1802
- style.id = styleId;
1803
- style.innerHTML = `
448
+ if (!configuratorId.trim()) throw new Error("integrateMetabox: configuratorId must be a non-empty string");
449
+ const iframeSrc = prepareIframeSrc(configuratorId, config);
450
+ let parsedUrl;
451
+ try {
452
+ parsedUrl = new URL(iframeSrc);
453
+ } catch {
454
+ throw new Error("integrateMetabox: Provided iframeSrc is not a valid URL");
455
+ }
456
+ if (parsedUrl.protocol !== "https:") throw new Error("integrateMetabox: iframeSrc must use HTTPS protocol");
457
+ if (!containerId.trim()) throw new Error("integrateMetabox: containerId must be a non-empty string");
458
+ const container = document.getElementById(containerId);
459
+ if (!container) throw new Error(`Container element with id ${containerId} not found`);
460
+ const existingIframe = document.getElementById("embeddedContent");
461
+ if (existingIframe) existingIframe.remove();
462
+ const iframe = document.createElement("iframe");
463
+ cancelPendingHandshake?.();
464
+ const cancel = Communicator.createInstance(apiReadyCallback, "host", config, {
465
+ iframe,
466
+ origin: parsedUrl.origin
467
+ });
468
+ cancelPendingHandshake = cancel ?? null;
469
+ const styleId = `metabox-integration-style-${containerId}`;
470
+ if (!document.getElementById(styleId)) {
471
+ const style = document.createElement("style");
472
+ style.id = styleId;
473
+ style.innerHTML = `
1804
474
  #${containerId} {
1805
475
  width: 100%;
1806
476
  height: 100%;
@@ -1808,111 +478,50 @@ function integrateMetabox(configuratorId, containerId, apiReadyCallback, config)
1808
478
  position: relative;
1809
479
  }
1810
480
  `;
1811
- document.head.appendChild(style);
1812
- }
1813
- iframe.setAttribute('allow', 'autoplay; fullscreen; encrypted-media');
1814
- iframe.setAttribute('referrerPolicy', 'no-referrer-when-downgrade');
1815
- iframe.setAttribute('id', 'embeddedContent');
1816
- iframe.style.border = '0';
1817
- iframe.style.width = '100%';
1818
- iframe.style.height = '100%';
1819
- iframe.style.overflow = 'hidden';
1820
- iframe.src = iframeSrc;
1821
- container.appendChild(iframe);
1822
- return cancel;
481
+ document.head.appendChild(style);
482
+ }
483
+ iframe.setAttribute("allow", iframePermissions());
484
+ iframe.setAttribute("referrerPolicy", "no-referrer-when-downgrade");
485
+ iframe.setAttribute("id", "embeddedContent");
486
+ iframe.style.border = "0";
487
+ iframe.style.width = "100%";
488
+ iframe.style.height = "100%";
489
+ iframe.style.overflow = "hidden";
490
+ iframe.src = iframeSrc;
491
+ container.appendChild(iframe);
492
+ return cancel;
1823
493
  }
1824
-
1825
- /**
1826
- * Saves an image by triggering a download.
1827
- *
1828
- * This function creates an anchor element, sets its `href` attribute to the provided image URL,
1829
- * and triggers a click event to initiate a download with the specified filename.
1830
- *
1831
- * ### What does it unlock?
1832
- * Main exported function to save images from the configurator. Converts base64 image data to actual image
1833
- * files and saves them to the local filesystem.
1834
- *
1835
- * ### Practical Application
1836
- * Exported utility function that converts base64 screenshot data (from screenshotReady event) to a downloadable
1837
- * image file. Handles the base64 → blob → browser download flow. Import directly from the API package.
1838
- *
1839
- * ### AI Coding Best Practices
1840
- * Pattern: `api.addEventListener('screenshotReady', (data) => { if(data) saveImage(data, 'config-screenshot.png'); })`.
1841
- * Filename extension should match the MimeType passed to GetScreenshot.
1842
- * Import: `import { saveImage } from '@3dsource/metabox-front-api'`.
1843
- *
1844
- * Only the three data-URL formats the configurator actually produces are
1845
- * accepted (`image/png`, `image/jpeg`, `image/webp`). The documented usage above
1846
- * feeds this an event payload straight off the wire, and the body below sets
1847
- * `href` on an anchor and clicks it — so without the check any `data:` URL that
1848
- * reached a `screenshotReady` listener would land in the user's downloads.
1849
- * Anything else is reported and ignored.
1850
- *
1851
- * @param {string} imageUrl - The URL of the image to save.
1852
- * @param {string} filename - The name of the file to save.
1853
- */
1854
494
  function saveImage(imageUrl, filename) {
1855
- if (!isScreenshotDataUrl(imageUrl)) {
1856
- console.warn('Metabox: saveImage ignored a value that is not a configurator screenshot ' +
1857
- '(expected a base64 data URL of type image/png, image/jpeg or image/webp).');
1858
- return;
1859
- }
1860
- const a = document.createElement('a');
1861
- a.href = imageUrl;
1862
- a.download = filename;
1863
- document.body.appendChild(a);
1864
- a.click();
1865
- document.body.removeChild(a);
495
+ if (!isScreenshotDataUrl(imageUrl)) {
496
+ console.warn("Metabox: saveImage ignored a value that is not a configurator screenshot (expected a base64 data URL of type image/png, image/jpeg or image/webp).");
497
+ return;
498
+ }
499
+ const a = document.createElement("a");
500
+ a.href = imageUrl;
501
+ a.download = filename;
502
+ document.body.appendChild(a);
503
+ a.click();
504
+ document.body.removeChild(a);
1866
505
  }
1867
- /**
1868
- * A base64 data URL in one of the formats `GetScreenshot` can ask for. Matched
1869
- * as a whole string rather than parsed: `new URL()` accepts a `data:` URL but
1870
- * exposes nothing useful about its media type, and a prefix check would let
1871
- * anything trail behind the payload.
1872
- */
1873
506
  function isScreenshotDataUrl(value) {
1874
- return /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/i.test(value);
507
+ return /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/i.test(value);
1875
508
  }
1876
-
1877
- /**
1878
- * Sets the URL parameters based on the provided state.
1879
- *
1880
- * @internal
1881
- * @hidden
1882
- * This function updates the current URL by replacing its search parameters with the key-value pairs from the provided state object.
1883
- *
1884
- * @param {Record<string, string>} state - An object containing key-value pairs to set as URL parameters.
1885
- */
1886
509
  function setUrlParams(state) {
1887
- const url = new URL(window.location.href);
1888
- url.search = '';
1889
- Object.entries(state).forEach(([key, value]) => {
1890
- url.searchParams.set(key, value);
1891
- });
1892
- history.replaceState(null, '', url.toString());
510
+ const url = new URL(window.location.href);
511
+ url.search = "";
512
+ Object.entries(state).forEach(([key, value]) => {
513
+ url.searchParams.set(key, value);
514
+ });
515
+ history.replaceState(null, "", url.toString());
1893
516
  }
1894
- /**
1895
- * Retrieves the URL parameters as an object.
1896
- *
1897
- * @remarks
1898
- * @internal
1899
- * @hidden
1900
- * This function parses the current URL's search parameters and returns them as a key-value object.
1901
- *
1902
- * @returns An object containing the URL parameters.
1903
- */
1904
517
  function getUrlParams() {
1905
- const urlParams = new URLSearchParams(window.location.search);
1906
- const selections = {};
1907
- urlParams.forEach((value, key) => {
1908
- selections[key] = value;
1909
- });
1910
- return selections;
518
+ const urlParams = new URLSearchParams(window.location.search);
519
+ const selections = {};
520
+ urlParams.forEach((value, key) => {
521
+ selections[key] = value;
522
+ });
523
+ return selections;
1911
524
  }
1912
-
1913
- /**
1914
- * Generated bundle index. Do not edit.
1915
- */
1916
-
1917
525
  export { AppLoaded, AppLoaded_V3, ApplyZoom, BasicRouteUrl, CommandBase, Communicator, EventDispatcher, GetCallToActionInformation, GetCamera, GetPdf, GetScreenshot, HideMeasurement, InitShowcase, Metabox, MetaboxBasicConfiguratorActions, MetaboxConfig, MetaboxDomain, MetaboxHost, MetaboxHost_V3, Metabox_V3, PauseShowcase, PlayShowcase, ResetCamera, ResetConfiguration, ResetUserInactivityTimer, ResumeStream, SetCamera, SetEnvironment, SetEnvironmentMaterial, SetMaterials, SetProduct, SetProductMaterial, ShowEmbeddedMenu, ShowMeasurement, ShowOverlayInterface, StopShowcase, StopStream, UnrealCommand, VERSION, fromCommunicatorEvent, getUrlParams, integrateMetabox, prepareIframeSrc, saveImage, setUrlParams };
1918
- //# sourceMappingURL=3dsource-metabox-front-api.mjs.map
526
+
527
+ //# sourceMappingURL=3dsource-metabox-front-api.mjs.map