@iwsdk/vite-plugin-dev 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,17 +7,25 @@ import { inflateSync } from 'zlib';
7
7
  import { assertValidIwsdkProjectManifest, normalizeProjectSourcePath, normalizeProjectDevOptions } from '@iwsdk/core/project';
8
8
  import { m as findNode, n as getNodeWorldBounds, o as getScenePatternRequestedCount, p as resolveScenePrefabRoot, q as getSceneNodeCollisionRadius, t as MAX_SCENE_PATTERN_INSTANCES, u as getScenePatternInstanceCount, s as sha256, c as canonicalizeJson, w as deepClone, a as assertValidSceneDocument, x as isPlainObject, y as SCENE_IMPORT_ID_PATTERN, z as validateSceneReview, v as validateSceneDocument, h as hashSceneDocument, b as hashRuntimeSceneDocument, A as getSceneCompositionSourceHashes, i as applyScenePatch, B as parseSceneDocument, j as serializeSceneDocument, D as serializeSceneReview, E as resolveSceneAuthoringTransforms, F as parseSceneReview } from './patch-BVc5fBs4.js';
9
9
  import { getCertificate } from '@vitejs/plugin-basic-ssl';
10
+ import process$1 from 'node:process';
11
+ import { Buffer as Buffer$1 } from 'node:buffer';
12
+ import path$1 from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { promisify } from 'node:util';
15
+ import childProcess, { execFile as execFile$1 } from 'node:child_process';
16
+ import fs$2, { constants, readFile as readFile$1, readdir } from 'node:fs/promises';
17
+ import os$1 from 'node:os';
18
+ import fs$1, { existsSync as existsSync$1, readFileSync, realpathSync, lstatSync } from 'node:fs';
10
19
  import { WebSocketServer, WebSocket } from 'ws';
11
- import { fileURLToPath } from 'url';
20
+ import { fileURLToPath as fileURLToPath$1 } from 'url';
12
21
  import { spawn } from 'child_process';
13
22
  import * as os from 'os';
14
23
  import { chromium } from 'playwright';
15
24
  import sharp from 'sharp';
16
- import { createRequire } from 'module';
17
25
  import { readFile, access, rm, mkdir, writeFile, rename } from 'fs/promises';
18
- import { existsSync as existsSync$1, readFileSync, realpathSync, lstatSync } from 'node:fs';
19
- import path$1 from 'node:path';
26
+ import { createRequire } from 'module';
20
27
  import { d } from './signals-core-BRx7ThPn.js';
28
+ import { parse, resolveKitComponentSets } from '@drawcall/uikitml';
21
29
 
22
30
  /**
23
31
  * Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -3529,6 +3537,617 @@ RUNTIME_MCP_TOOLS.map((tool) => {
3529
3537
  };
3530
3538
  });
3531
3539
 
3540
+ let isDockerCached;
3541
+
3542
+ function hasDockerEnv() {
3543
+ try {
3544
+ fs$1.statSync('/.dockerenv');
3545
+ return true;
3546
+ } catch {
3547
+ return false;
3548
+ }
3549
+ }
3550
+
3551
+ function hasDockerCGroup() {
3552
+ try {
3553
+ return fs$1.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
3554
+ } catch {
3555
+ return false;
3556
+ }
3557
+ }
3558
+
3559
+ function isDocker() {
3560
+ // TODO: Use `??=` when targeting Node.js 16.
3561
+ if (isDockerCached === undefined) {
3562
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
3563
+ }
3564
+
3565
+ return isDockerCached;
3566
+ }
3567
+
3568
+ let cachedResult;
3569
+
3570
+ // Podman detection
3571
+ const hasContainerEnv = () => {
3572
+ try {
3573
+ fs$1.statSync('/run/.containerenv');
3574
+ return true;
3575
+ } catch {
3576
+ return false;
3577
+ }
3578
+ };
3579
+
3580
+ function isInsideContainer() {
3581
+ // TODO: Use `??=` when targeting Node.js 16.
3582
+ if (cachedResult === undefined) {
3583
+ cachedResult = hasContainerEnv() || isDocker();
3584
+ }
3585
+
3586
+ return cachedResult;
3587
+ }
3588
+
3589
+ const isWsl = () => {
3590
+ if (process$1.platform !== 'linux') {
3591
+ return false;
3592
+ }
3593
+
3594
+ if (os$1.release().toLowerCase().includes('microsoft')) {
3595
+ if (isInsideContainer()) {
3596
+ return false;
3597
+ }
3598
+
3599
+ return true;
3600
+ }
3601
+
3602
+ try {
3603
+ if (fs$1.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')) {
3604
+ return !isInsideContainer();
3605
+ }
3606
+ } catch {}
3607
+
3608
+ // Fallback for custom kernels: check WSL-specific paths.
3609
+ if (
3610
+ fs$1.existsSync('/proc/sys/fs/binfmt_misc/WSLInterop')
3611
+ || fs$1.existsSync('/run/WSL')
3612
+ ) {
3613
+ return !isInsideContainer();
3614
+ }
3615
+
3616
+ return false;
3617
+ };
3618
+
3619
+ var isWsl$1 = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
3620
+
3621
+ const wslDrivesMountPoint = (() => {
3622
+ // Default value for "root" param
3623
+ // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
3624
+ const defaultMountPoint = '/mnt/';
3625
+
3626
+ let mountPoint;
3627
+
3628
+ return async function () {
3629
+ if (mountPoint) {
3630
+ // Return memoized mount point value
3631
+ return mountPoint;
3632
+ }
3633
+
3634
+ const configFilePath = '/etc/wsl.conf';
3635
+
3636
+ let isConfigFileExists = false;
3637
+ try {
3638
+ await fs$2.access(configFilePath, constants.F_OK);
3639
+ isConfigFileExists = true;
3640
+ } catch {}
3641
+
3642
+ if (!isConfigFileExists) {
3643
+ return defaultMountPoint;
3644
+ }
3645
+
3646
+ const configContent = await fs$2.readFile(configFilePath, {encoding: 'utf8'});
3647
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
3648
+
3649
+ if (!configMountPoint) {
3650
+ return defaultMountPoint;
3651
+ }
3652
+
3653
+ mountPoint = configMountPoint.groups.mountPoint.trim();
3654
+ mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
3655
+
3656
+ return mountPoint;
3657
+ };
3658
+ })();
3659
+
3660
+ const powerShellPathFromWsl = async () => {
3661
+ const mountPoint = await wslDrivesMountPoint();
3662
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
3663
+ };
3664
+
3665
+ const powerShellPath = async () => {
3666
+ if (isWsl$1) {
3667
+ return powerShellPathFromWsl();
3668
+ }
3669
+
3670
+ return `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
3671
+ };
3672
+
3673
+ function defineLazyProperty(object, propertyName, valueGetter) {
3674
+ const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
3675
+
3676
+ Object.defineProperty(object, propertyName, {
3677
+ configurable: true,
3678
+ enumerable: true,
3679
+ get() {
3680
+ const result = valueGetter();
3681
+ define(result);
3682
+ return result;
3683
+ },
3684
+ set(value) {
3685
+ define(value);
3686
+ }
3687
+ });
3688
+
3689
+ return object;
3690
+ }
3691
+
3692
+ const execFileAsync$3 = promisify(execFile$1);
3693
+
3694
+ async function defaultBrowserId() {
3695
+ if (process$1.platform !== 'darwin') {
3696
+ throw new Error('macOS only');
3697
+ }
3698
+
3699
+ const {stdout} = await execFileAsync$3('defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure', 'LSHandlers']);
3700
+
3701
+ // `(?!-)` is to prevent matching `LSHandlerRoleAll = "-";`.
3702
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
3703
+
3704
+ const browserId = match?.groups.id ?? 'com.apple.Safari';
3705
+
3706
+ // Correct the case for Safari's bundle identifier
3707
+ if (browserId === 'com.apple.safari') {
3708
+ return 'com.apple.Safari';
3709
+ }
3710
+
3711
+ return browserId;
3712
+ }
3713
+
3714
+ const execFileAsync$2 = promisify(execFile$1);
3715
+
3716
+ async function runAppleScript(script, {humanReadableOutput = true, signal} = {}) {
3717
+ if (process$1.platform !== 'darwin') {
3718
+ throw new Error('macOS only');
3719
+ }
3720
+
3721
+ const outputArguments = humanReadableOutput ? [] : ['-ss'];
3722
+
3723
+ const execOptions = {};
3724
+ if (signal) {
3725
+ execOptions.signal = signal;
3726
+ }
3727
+
3728
+ const {stdout} = await execFileAsync$2('osascript', ['-e', script, outputArguments], execOptions);
3729
+ return stdout.trim();
3730
+ }
3731
+
3732
+ async function bundleName(bundleId) {
3733
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
3734
+ }
3735
+
3736
+ const execFileAsync$1 = promisify(execFile$1);
3737
+
3738
+ // TODO: Fix the casing of bundle identifiers in the next major version.
3739
+
3740
+ // Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake
3741
+ // ones that look real and match the macOS/Linux versions for cross-platform apps.
3742
+ const windowsBrowserProgIds = {
3743
+ MSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // The missing `L` is correct.
3744
+ MSEdgeBHTML: {name: 'Edge Beta', id: 'com.microsoft.edge.beta'},
3745
+ MSEdgeDHTML: {name: 'Edge Dev', id: 'com.microsoft.edge.dev'},
3746
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'},
3747
+ ChromeHTML: {name: 'Chrome', id: 'com.google.chrome'},
3748
+ ChromeBHTML: {name: 'Chrome Beta', id: 'com.google.chrome.beta'},
3749
+ ChromeDHTML: {name: 'Chrome Dev', id: 'com.google.chrome.dev'},
3750
+ ChromiumHTM: {name: 'Chromium', id: 'org.chromium.Chromium'},
3751
+ BraveHTML: {name: 'Brave', id: 'com.brave.Browser'},
3752
+ BraveBHTML: {name: 'Brave Beta', id: 'com.brave.Browser.beta'},
3753
+ BraveDHTML: {name: 'Brave Dev', id: 'com.brave.Browser.dev'},
3754
+ BraveSSHTM: {name: 'Brave Nightly', id: 'com.brave.Browser.nightly'},
3755
+ FirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'},
3756
+ OperaStable: {name: 'Opera', id: 'com.operasoftware.Opera'},
3757
+ VivaldiHTM: {name: 'Vivaldi', id: 'com.vivaldi.Vivaldi'},
3758
+ 'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'},
3759
+ };
3760
+
3761
+ new Map(Object.entries(windowsBrowserProgIds));
3762
+
3763
+ class UnknownBrowserError extends Error {}
3764
+
3765
+ async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
3766
+ const {stdout} = await _execFileAsync('reg', [
3767
+ 'QUERY',
3768
+ ' HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice',
3769
+ '/v',
3770
+ 'ProgId',
3771
+ ]);
3772
+
3773
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
3774
+ if (!match) {
3775
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
3776
+ }
3777
+
3778
+ const {id} = match.groups;
3779
+
3780
+ // Windows can append a hash suffix to ProgIds using a dot or hyphen
3781
+ // (e.g., `ChromeHTML.ABC123`, `FirefoxURL-6F193CCC56814779`).
3782
+ // Try exact match first, then try without the suffix.
3783
+ const dotIndex = id.lastIndexOf('.');
3784
+ const hyphenIndex = id.lastIndexOf('-');
3785
+ const baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);
3786
+ const baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);
3787
+
3788
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {name: id, id};
3789
+ }
3790
+
3791
+ const execFileAsync = promisify(execFile$1);
3792
+
3793
+ // Inlined: https://github.com/sindresorhus/titleize/blob/main/index.js
3794
+ const titleize = string => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, x => x.toUpperCase());
3795
+
3796
+ async function defaultBrowser() {
3797
+ if (process$1.platform === 'darwin') {
3798
+ const id = await defaultBrowserId();
3799
+ const name = await bundleName(id);
3800
+ return {name, id};
3801
+ }
3802
+
3803
+ if (process$1.platform === 'linux') {
3804
+ const {stdout} = await execFileAsync('xdg-mime', ['query', 'default', 'x-scheme-handler/http']);
3805
+ const id = stdout.trim();
3806
+ const name = titleize(id.replace(/.desktop$/, '').replace('-', ' '));
3807
+ return {name, id};
3808
+ }
3809
+
3810
+ if (process$1.platform === 'win32') {
3811
+ return defaultBrowser$1();
3812
+ }
3813
+
3814
+ throw new Error('Only macOS, Linux, and Windows are supported');
3815
+ }
3816
+
3817
+ const execFile = promisify(childProcess.execFile);
3818
+
3819
+ // Path to included `xdg-open`.
3820
+ const __dirname$2 = path$1.dirname(fileURLToPath(import.meta.url));
3821
+ const localXdgOpenPath = path$1.join(__dirname$2, 'xdg-open');
3822
+
3823
+ const {platform, arch} = process$1;
3824
+
3825
+ /**
3826
+ Get the default browser name in Windows from WSL.
3827
+
3828
+ @returns {Promise<string>} Browser name.
3829
+ */
3830
+ async function getWindowsDefaultBrowserFromWsl() {
3831
+ const powershellPath = await powerShellPath();
3832
+ const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
3833
+ const encodedCommand = Buffer$1.from(rawCommand, 'utf16le').toString('base64');
3834
+
3835
+ const {stdout} = await execFile(
3836
+ powershellPath,
3837
+ [
3838
+ '-NoProfile',
3839
+ '-NonInteractive',
3840
+ '-ExecutionPolicy',
3841
+ 'Bypass',
3842
+ '-EncodedCommand',
3843
+ encodedCommand,
3844
+ ],
3845
+ {encoding: 'utf8'},
3846
+ );
3847
+
3848
+ const progId = stdout.trim();
3849
+
3850
+ // Map ProgId to browser IDs
3851
+ const browserMap = {
3852
+ ChromeHTML: 'com.google.chrome',
3853
+ BraveHTML: 'com.brave.Browser',
3854
+ MSEdgeHTM: 'com.microsoft.edge',
3855
+ FirefoxURL: 'org.mozilla.firefox',
3856
+ };
3857
+
3858
+ return browserMap[progId] ? {id: browserMap[progId]} : {};
3859
+ }
3860
+
3861
+ const pTryEach = async (array, mapper) => {
3862
+ let latestError;
3863
+
3864
+ for (const item of array) {
3865
+ try {
3866
+ return await mapper(item); // eslint-disable-line no-await-in-loop
3867
+ } catch (error) {
3868
+ latestError = error;
3869
+ }
3870
+ }
3871
+
3872
+ throw latestError;
3873
+ };
3874
+
3875
+ // eslint-disable-next-line complexity
3876
+ const baseOpen = async options => {
3877
+ options = {
3878
+ wait: false,
3879
+ background: false,
3880
+ newInstance: false,
3881
+ allowNonzeroExitCode: false,
3882
+ ...options,
3883
+ };
3884
+
3885
+ if (Array.isArray(options.app)) {
3886
+ return pTryEach(options.app, singleApp => baseOpen({
3887
+ ...options,
3888
+ app: singleApp,
3889
+ }));
3890
+ }
3891
+
3892
+ let {name: app, arguments: appArguments = []} = options.app ?? {};
3893
+ appArguments = [...appArguments];
3894
+
3895
+ if (Array.isArray(app)) {
3896
+ return pTryEach(app, appName => baseOpen({
3897
+ ...options,
3898
+ app: {
3899
+ name: appName,
3900
+ arguments: appArguments,
3901
+ },
3902
+ }));
3903
+ }
3904
+
3905
+ if (app === 'browser' || app === 'browserPrivate') {
3906
+ // IDs from default-browser for macOS and windows are the same
3907
+ const ids = {
3908
+ 'com.google.chrome': 'chrome',
3909
+ 'google-chrome.desktop': 'chrome',
3910
+ 'com.brave.Browser': 'brave',
3911
+ 'org.mozilla.firefox': 'firefox',
3912
+ 'firefox.desktop': 'firefox',
3913
+ 'com.microsoft.msedge': 'edge',
3914
+ 'com.microsoft.edge': 'edge',
3915
+ 'com.microsoft.edgemac': 'edge',
3916
+ 'microsoft-edge.desktop': 'edge',
3917
+ };
3918
+
3919
+ // Incognito flags for each browser in `apps`.
3920
+ const flags = {
3921
+ chrome: '--incognito',
3922
+ brave: '--incognito',
3923
+ firefox: '--private-window',
3924
+ edge: '--inPrivate',
3925
+ };
3926
+
3927
+ const browser = isWsl$1 ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
3928
+ if (browser.id in ids) {
3929
+ const browserName = ids[browser.id];
3930
+
3931
+ if (app === 'browserPrivate') {
3932
+ appArguments.push(flags[browserName]);
3933
+ }
3934
+
3935
+ return baseOpen({
3936
+ ...options,
3937
+ app: {
3938
+ name: apps[browserName],
3939
+ arguments: appArguments,
3940
+ },
3941
+ });
3942
+ }
3943
+
3944
+ throw new Error(`${browser.name} is not supported as a default browser`);
3945
+ }
3946
+
3947
+ let command;
3948
+ const cliArguments = [];
3949
+ const childProcessOptions = {};
3950
+
3951
+ if (platform === 'darwin') {
3952
+ command = 'open';
3953
+
3954
+ if (options.wait) {
3955
+ cliArguments.push('--wait-apps');
3956
+ }
3957
+
3958
+ if (options.background) {
3959
+ cliArguments.push('--background');
3960
+ }
3961
+
3962
+ if (options.newInstance) {
3963
+ cliArguments.push('--new');
3964
+ }
3965
+
3966
+ if (app) {
3967
+ cliArguments.push('-a', app);
3968
+ }
3969
+ } else if (platform === 'win32' || (isWsl$1 && !isInsideContainer() && !app)) {
3970
+ command = await powerShellPath();
3971
+
3972
+ cliArguments.push(
3973
+ '-NoProfile',
3974
+ '-NonInteractive',
3975
+ '-ExecutionPolicy',
3976
+ 'Bypass',
3977
+ '-EncodedCommand',
3978
+ );
3979
+
3980
+ if (!isWsl$1) {
3981
+ childProcessOptions.windowsVerbatimArguments = true;
3982
+ }
3983
+
3984
+ const encodedArguments = ['Start'];
3985
+
3986
+ if (options.wait) {
3987
+ encodedArguments.push('-Wait');
3988
+ }
3989
+
3990
+ if (app) {
3991
+ // Double quote with double quotes to ensure the inner quotes are passed through.
3992
+ // Inner quotes are delimited for PowerShell interpretation with backticks.
3993
+ encodedArguments.push(`"\`"${app}\`""`);
3994
+ if (options.target) {
3995
+ appArguments.push(options.target);
3996
+ }
3997
+ } else if (options.target) {
3998
+ encodedArguments.push(`"${options.target}"`);
3999
+ }
4000
+
4001
+ if (appArguments.length > 0) {
4002
+ appArguments = appArguments.map(argument => `"\`"${argument}\`""`);
4003
+ encodedArguments.push('-ArgumentList', appArguments.join(','));
4004
+ }
4005
+
4006
+ // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
4007
+ options.target = Buffer$1.from(encodedArguments.join(' '), 'utf16le').toString('base64');
4008
+ } else {
4009
+ if (app) {
4010
+ command = app;
4011
+ } else {
4012
+ // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
4013
+ const isBundled = !__dirname$2 || __dirname$2 === '/';
4014
+
4015
+ // Check if local `xdg-open` exists and is executable.
4016
+ let exeLocalXdgOpen = false;
4017
+ try {
4018
+ await fs$2.access(localXdgOpenPath, constants.X_OK);
4019
+ exeLocalXdgOpen = true;
4020
+ } catch {}
4021
+
4022
+ const useSystemXdgOpen = process$1.versions.electron
4023
+ ?? (platform === 'android' || isBundled || !exeLocalXdgOpen);
4024
+ command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
4025
+ }
4026
+
4027
+ if (appArguments.length > 0) {
4028
+ cliArguments.push(...appArguments);
4029
+ }
4030
+
4031
+ if (!options.wait) {
4032
+ // `xdg-open` will block the process unless stdio is ignored
4033
+ // and it's detached from the parent even if it's unref'd.
4034
+ childProcessOptions.stdio = 'ignore';
4035
+ childProcessOptions.detached = true;
4036
+ }
4037
+ }
4038
+
4039
+ if (platform === 'darwin' && appArguments.length > 0) {
4040
+ cliArguments.push('--args', ...appArguments);
4041
+ }
4042
+
4043
+ // This has to come after `--args`.
4044
+ if (options.target) {
4045
+ cliArguments.push(options.target);
4046
+ }
4047
+
4048
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
4049
+
4050
+ if (options.wait) {
4051
+ return new Promise((resolve, reject) => {
4052
+ subprocess.once('error', reject);
4053
+
4054
+ subprocess.once('close', exitCode => {
4055
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
4056
+ reject(new Error(`Exited with code ${exitCode}`));
4057
+ return;
4058
+ }
4059
+
4060
+ resolve(subprocess);
4061
+ });
4062
+ });
4063
+ }
4064
+
4065
+ subprocess.unref();
4066
+
4067
+ return subprocess;
4068
+ };
4069
+
4070
+ const open = (target, options) => {
4071
+ if (typeof target !== 'string') {
4072
+ throw new TypeError('Expected a `target`');
4073
+ }
4074
+
4075
+ return baseOpen({
4076
+ ...options,
4077
+ target,
4078
+ });
4079
+ };
4080
+
4081
+ function detectArchBinary(binary) {
4082
+ if (typeof binary === 'string' || Array.isArray(binary)) {
4083
+ return binary;
4084
+ }
4085
+
4086
+ const {[arch]: archBinary} = binary;
4087
+
4088
+ if (!archBinary) {
4089
+ throw new Error(`${arch} is not supported`);
4090
+ }
4091
+
4092
+ return archBinary;
4093
+ }
4094
+
4095
+ function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
4096
+ if (wsl && isWsl$1) {
4097
+ return detectArchBinary(wsl);
4098
+ }
4099
+
4100
+ if (!platformBinary) {
4101
+ throw new Error(`${platform} is not supported`);
4102
+ }
4103
+
4104
+ return detectArchBinary(platformBinary);
4105
+ }
4106
+
4107
+ const apps = {};
4108
+
4109
+ defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
4110
+ darwin: 'google chrome',
4111
+ win32: 'chrome',
4112
+ linux: ['google-chrome', 'google-chrome-stable', 'chromium'],
4113
+ }, {
4114
+ wsl: {
4115
+ ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
4116
+ x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'],
4117
+ },
4118
+ }));
4119
+
4120
+ defineLazyProperty(apps, 'brave', () => detectPlatformBinary({
4121
+ darwin: 'brave browser',
4122
+ win32: 'brave',
4123
+ linux: ['brave-browser', 'brave'],
4124
+ }, {
4125
+ wsl: {
4126
+ ia32: '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe',
4127
+ x64: ['/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe', '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe'],
4128
+ },
4129
+ }));
4130
+
4131
+ defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
4132
+ darwin: 'firefox',
4133
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
4134
+ linux: 'firefox',
4135
+ }, {
4136
+ wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe',
4137
+ }));
4138
+
4139
+ defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
4140
+ darwin: 'microsoft edge',
4141
+ win32: 'msedge',
4142
+ linux: ['microsoft-edge', 'microsoft-edge-dev'],
4143
+ }, {
4144
+ wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
4145
+ }));
4146
+
4147
+ defineLazyProperty(apps, 'browser', () => 'browser');
4148
+
4149
+ defineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate');
4150
+
3532
4151
  /**
3533
4152
  * Copyright (c) Meta Platforms, Inc. and affiliates.
3534
4153
  *
@@ -3589,12 +4208,12 @@ function getEditorSessionModuleImport() {
3589
4208
  './editor/scene-editor-session.ts',
3590
4209
  ];
3591
4210
  for (const candidate of candidates) {
3592
- const modulePath = fileURLToPath(new URL(candidate, import.meta.url));
4211
+ const modulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3593
4212
  if (existsSync(modulePath)) {
3594
4213
  return `/@fs/${modulePath}`;
3595
4214
  }
3596
4215
  }
3597
- return `/@fs/${fileURLToPath(new URL('./scene-editor-session.ts', import.meta.url))}`;
4216
+ return `/@fs/${fileURLToPath$1(new URL('./scene-editor-session.ts', import.meta.url))}`;
3598
4217
  }
3599
4218
  function getEditorWorkspaceModuleImport() {
3600
4219
  const candidates = [
@@ -3604,7 +4223,7 @@ function getEditorWorkspaceModuleImport() {
3604
4223
  './editor/editor-workspace.tsx',
3605
4224
  ];
3606
4225
  for (const candidate of candidates) {
3607
- const modulePath = fileURLToPath(new URL(candidate, import.meta.url));
4226
+ const modulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3608
4227
  if (existsSync(modulePath)) {
3609
4228
  return `/@fs/${modulePath}`;
3610
4229
  }
@@ -3614,7 +4233,7 @@ function getEditorWorkspaceModuleImport() {
3614
4233
  function getCoreModuleImport() {
3615
4234
  const candidates = ['../../../core/src/index.ts', '../../core/src/index.ts'];
3616
4235
  for (const candidate of candidates) {
3617
- const sourceModulePath = fileURLToPath(new URL(candidate, import.meta.url));
4236
+ const sourceModulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3618
4237
  if (existsSync(sourceModulePath)) {
3619
4238
  return `/@fs/${sourceModulePath}`;
3620
4239
  }
@@ -3627,7 +4246,7 @@ function getSceneCompositionModuleImport() {
3627
4246
  '../../scene-composition/src/index.ts',
3628
4247
  ];
3629
4248
  for (const candidate of candidates) {
3630
- const sourceModulePath = fileURLToPath(new URL(candidate, import.meta.url));
4249
+ const sourceModulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3631
4250
  if (existsSync(sourceModulePath)) {
3632
4251
  return `/@fs/${sourceModulePath}`;
3633
4252
  }
@@ -3640,7 +4259,7 @@ function getOrbitControlsModuleImport() {
3640
4259
  '../../core/node_modules/three/examples/jsm/controls/OrbitControls.js',
3641
4260
  ];
3642
4261
  for (const candidate of candidates) {
3643
- const sourceModulePath = fileURLToPath(new URL(candidate, import.meta.url));
4262
+ const sourceModulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3644
4263
  if (existsSync(sourceModulePath)) {
3645
4264
  return `/@fs/${sourceModulePath}`;
3646
4265
  }
@@ -3653,7 +4272,7 @@ function getTransformControlsModuleImport() {
3653
4272
  '../../core/node_modules/three/examples/jsm/controls/TransformControls.js',
3654
4273
  ];
3655
4274
  for (const candidate of candidates) {
3656
- const sourceModulePath = fileURLToPath(new URL(candidate, import.meta.url));
4275
+ const sourceModulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3657
4276
  if (existsSync(sourceModulePath)) {
3658
4277
  return `/@fs/${sourceModulePath}`;
3659
4278
  }
@@ -3666,7 +4285,7 @@ function getViewportGizmoModuleImport() {
3666
4285
  '../../node_modules/three-viewport-gizmo/dist/three-viewport-gizmo.js',
3667
4286
  ];
3668
4287
  for (const candidate of candidates) {
3669
- const sourceModulePath = fileURLToPath(new URL(candidate, import.meta.url));
4288
+ const sourceModulePath = fileURLToPath$1(new URL(candidate, import.meta.url));
3670
4289
  if (existsSync(sourceModulePath)) {
3671
4290
  return `/@fs/${sourceModulePath}`;
3672
4291
  }
@@ -3972,6 +4591,7 @@ let applyScenePatch;
3972
4591
  let Box3;
3973
4592
  let Box3Helper;
3974
4593
  let BoxGeometry;
4594
+ let BufferGeometry;
3975
4595
  let CanvasTexture;
3976
4596
  let Color;
3977
4597
  let ComponentRegistry;
@@ -3981,13 +4601,15 @@ let disposeLoweredSceneNodes;
3981
4601
  let ConeGeometry;
3982
4602
  let CylinderGeometry;
3983
4603
  let DirectionalLight;
4604
+ let Float32BufferAttribute;
3984
4605
  let Frustum;
3985
4606
  let finalizeSceneReviewDraft;
3986
- let GridHelper;
3987
4607
  let Group;
3988
4608
  let hashSceneDocument;
3989
4609
  let hashRuntimeSceneDocument;
3990
4610
  let LevelComponentApplier;
4611
+ let LineBasicMaterial;
4612
+ let LineSegments;
3991
4613
  let LightBinding;
3992
4614
  let lightSpecFromComponentValue;
3993
4615
  let lowerSceneDocumentObjects;
@@ -3999,9 +4621,11 @@ let MeshStandardMaterial;
3999
4621
  let OrthographicCamera;
4000
4622
  let PerspectiveCamera;
4001
4623
  let PlaneGeometry;
4624
+ let Quaternion;
4002
4625
  let Raycaster;
4003
4626
  let restoreSceneEnvironment;
4004
4627
  let Scene;
4628
+ let ShaderMaterial;
4005
4629
  let SphereGeometry;
4006
4630
  let SRGBColorSpace;
4007
4631
  let Types;
@@ -4021,6 +4645,22 @@ let editorPanelPreviewRendererState = null;
4021
4645
  let editorPanelPreviewRendererCreatedCount = 0;
4022
4646
  let editorPanelPreviewRenderQueue = Promise.resolve();
4023
4647
  const editorPanelFrameSchedulers = new WeakMap();
4648
+ const DEFAULT_EDITOR_DRAW_DISTANCE = 5000;
4649
+ const MIN_EDITOR_DRAW_DISTANCE = 50;
4650
+ const MAX_EDITOR_DRAW_DISTANCE = 100000;
4651
+ const MIN_EDITOR_GRID_SPACING = 0.5;
4652
+ const EDITOR_DRAW_DISTANCE_STORAGE_KEY = 'iwsdk-editor-view-distance';
4653
+ const DEFAULT_EDITOR_TRANSFORM_SNAP = Object.freeze({
4654
+ rotationDeg: 15,
4655
+ scale: 0.1,
4656
+ translation: 0.25,
4657
+ });
4658
+ const EDITOR_TRANSFORM_SNAP_LIMITS = Object.freeze({
4659
+ rotationDeg: { max: 180, min: 0.1 },
4660
+ scale: { max: 10, min: 0.001 },
4661
+ translation: { max: 10000, min: 0.001 },
4662
+ });
4663
+ const EDITOR_TRANSFORM_SNAP_STORAGE_KEY = 'iwsdk-editor-transform-snap';
4024
4664
 
4025
4665
  async function loadEditorRuntimeDependencies() {
4026
4666
  const [
@@ -4063,6 +4703,7 @@ async function loadEditorRuntimeDependencies() {
4063
4703
  Box3,
4064
4704
  Box3Helper,
4065
4705
  BoxGeometry,
4706
+ BufferGeometry,
4066
4707
  CanvasTexture,
4067
4708
  Color,
4068
4709
  ComponentRegistry,
@@ -4072,10 +4713,12 @@ async function loadEditorRuntimeDependencies() {
4072
4713
  ConeGeometry,
4073
4714
  CylinderGeometry,
4074
4715
  DirectionalLight,
4716
+ Float32BufferAttribute,
4075
4717
  Frustum,
4076
- GridHelper,
4077
4718
  Group,
4078
4719
  LevelComponentApplier,
4720
+ LineBasicMaterial,
4721
+ LineSegments,
4079
4722
  LightBinding,
4080
4723
  lightSpecFromComponentValue,
4081
4724
  lowerSceneDocumentObjects,
@@ -4087,9 +4730,11 @@ async function loadEditorRuntimeDependencies() {
4087
4730
  OrthographicCamera,
4088
4731
  PerspectiveCamera,
4089
4732
  PlaneGeometry,
4733
+ Quaternion,
4090
4734
  Raycaster,
4091
4735
  restoreSceneEnvironment,
4092
4736
  Scene,
4737
+ ShaderMaterial,
4093
4738
  SphereGeometry,
4094
4739
  SRGBColorSpace,
4095
4740
  Types,
@@ -6351,6 +6996,25 @@ function editorWorkspaceController() {
6351
6996
  reloadPage() {
6352
6997
  window.location.reload();
6353
6998
  },
6999
+ openRuntimeInBrowser() {
7000
+ void fetch('/__iwsdk/workspace/open-runtime', {
7001
+ method: 'POST',
7002
+ })
7003
+ .then((response) => {
7004
+ if (!response.ok) {
7005
+ console.error(
7006
+ '[IWSDK] Failed to open runtime in default browser:',
7007
+ response.status,
7008
+ );
7009
+ }
7010
+ })
7011
+ .catch((error) => {
7012
+ console.error(
7013
+ '[IWSDK] Failed to open runtime in default browser:',
7014
+ error,
7015
+ );
7016
+ });
7017
+ },
6354
7018
  selectNode(nodeId, modifiers) {
6355
7019
  const session = activeEditorSession();
6356
7020
  if (!session) {
@@ -6385,7 +7049,14 @@ function editorWorkspaceController() {
6385
7049
  .then(refreshActiveEditor);
6386
7050
  },
6387
7051
  setTransformMode,
7052
+ setTransformSnap(mode, value) {
7053
+ setTransformSnapValue(mode, value);
7054
+ refreshActiveEditor();
7055
+ },
6388
7056
  setTransformSpace,
7057
+ setViewportDrawDistance(distance) {
7058
+ setEditorDrawDistance(distance);
7059
+ },
6389
7060
  setView(view) {
6390
7061
  void setWorkspaceView(view);
6391
7062
  },
@@ -7341,6 +8012,13 @@ function snapVector(values, increment) {
7341
8012
  return values.map((value) => snapNumber(value, increment));
7342
8013
  }
7343
8014
 
8015
+ function snapScaleVector(values, increment) {
8016
+ return values.map((value) => {
8017
+ const snapped = snapNumber(value, increment);
8018
+ return snapped === 0 ? (Math.sign(value) || 1) * increment : snapped;
8019
+ });
8020
+ }
8021
+
7344
8022
  function scaleVectorFromTransform(transform = {}) {
7345
8023
  return typeof transform.scale === 'number'
7346
8024
  ? [transform.scale, transform.scale, transform.scale]
@@ -7380,7 +8058,9 @@ function snapTransformForCurrentMode(transform) {
7380
8058
  if (mode === 'scale') {
7381
8059
  return {
7382
8060
  ...transform,
7383
- scale: compactScaleValue(snapVector(scaleVectorFromTransform(transform), snap.scale)),
8061
+ scale: compactScaleValue(
8062
+ snapScaleVector(scaleVectorFromTransform(transform), snap.scale),
8063
+ ),
7384
8064
  };
7385
8065
  }
7386
8066
  return transform;
@@ -7693,23 +8373,302 @@ function markOwnedEditorHelper(mesh, nodeId, helperType) {
7693
8373
  return mesh;
7694
8374
  }
7695
8375
 
8376
+ function markLightEditorHelper(mesh, nodeId, helperType, role) {
8377
+ markOwnedEditorHelper(mesh, nodeId, helperType);
8378
+ mesh.userData.iwsdkEditorLightRole = role;
8379
+ mesh.userData.iwsdkEditorPickable = role === 'handle';
8380
+ return mesh;
8381
+ }
8382
+
8383
+ function createLightPickHandle(nodeId, helperType, color) {
8384
+ return markLightEditorHelper(
8385
+ new Mesh(
8386
+ new SphereGeometry(0.09, 16, 10),
8387
+ new MeshBasicMaterial({
8388
+ color,
8389
+ colorWrite: false,
8390
+ depthWrite: false,
8391
+ }),
8392
+ ),
8393
+ nodeId,
8394
+ helperType,
8395
+ 'handle',
8396
+ );
8397
+ }
8398
+
8399
+ function createLightCenterDot(nodeId, helperType, color) {
8400
+ return markLightEditorHelper(
8401
+ new Mesh(
8402
+ new SphereGeometry(0.025, 12, 8),
8403
+ new MeshBasicMaterial({ color, depthTest: false, depthWrite: false }),
8404
+ ),
8405
+ nodeId,
8406
+ helperType,
8407
+ 'visual',
8408
+ );
8409
+ }
8410
+
8411
+ function appendLightOutlineSegment(points, start, end) {
8412
+ points.push(new Vector3(...start), new Vector3(...end));
8413
+ }
8414
+
8415
+ function appendLightOutlineCircle(
8416
+ points,
8417
+ radius,
8418
+ plane = 'xy',
8419
+ center = [0, 0, 0],
8420
+ segments = 24,
8421
+ ) {
8422
+ const pointAt = (angle) => {
8423
+ const cosine = Math.cos(angle) * radius;
8424
+ const sine = Math.sin(angle) * radius;
8425
+ if (plane === 'yz') {
8426
+ return [center[0], center[1] + cosine, center[2] + sine];
8427
+ }
8428
+ if (plane === 'xz') {
8429
+ return [center[0] + cosine, center[1], center[2] + sine];
8430
+ }
8431
+ return [center[0] + cosine, center[1] + sine, center[2]];
8432
+ };
8433
+ for (let index = 0; index < segments; index += 1) {
8434
+ appendLightOutlineSegment(
8435
+ points,
8436
+ pointAt((index / segments) * Math.PI * 2),
8437
+ pointAt(((index + 1) / segments) * Math.PI * 2),
8438
+ );
8439
+ }
8440
+ }
8441
+
8442
+ function appendDashedLightOutlineCircle(points, radius, segments) {
8443
+ const ring = Array.from({ length: segments }, (_, index) => {
8444
+ const angle = (index / segments) * Math.PI * 2;
8445
+ return [Math.cos(angle) * radius, Math.sin(angle) * radius, 0];
8446
+ });
8447
+ for (let index = 0; index < segments; index += 2) {
8448
+ appendLightOutlineSegment(points, ring[index], ring[index + 1]);
8449
+ }
8450
+ }
8451
+
8452
+ function appendLightOutlineDiamond(points, radius) {
8453
+ const diamond = [
8454
+ [radius, 0, 0],
8455
+ [0, radius, 0],
8456
+ [-radius, 0, 0],
8457
+ [0, -radius, 0],
8458
+ ];
8459
+ for (let index = 0; index < diamond.length; index += 1) {
8460
+ appendLightOutlineSegment(
8461
+ points,
8462
+ diamond[index],
8463
+ diamond[(index + 1) % diamond.length],
8464
+ );
8465
+ }
8466
+ }
8467
+
8468
+ function createLightOutline(
8469
+ nodeId,
8470
+ helperType,
8471
+ color,
8472
+ points,
8473
+ alignment = 'object',
8474
+ ) {
8475
+ let material;
8476
+ if (alignment === 'object') {
8477
+ material = new LineBasicMaterial({
8478
+ color,
8479
+ depthTest: false,
8480
+ depthWrite: false,
8481
+ opacity: 0.9,
8482
+ transparent: true,
8483
+ });
8484
+ } else {
8485
+ const screenSpace = alignment === 'screen-space';
8486
+ material = new ShaderMaterial({
8487
+ depthTest: false,
8488
+ depthWrite: false,
8489
+ fragmentShader: \`uniform vec3 outlineColor;
8490
+ void main() { gl_FragColor = vec4(outlineColor, 0.9); }\`,
8491
+ transparent: true,
8492
+ uniforms: {
8493
+ outlineColor: { value: color },
8494
+ viewportSize: { value: new Vector2(1, 1) },
8495
+ },
8496
+ vertexShader: screenSpace
8497
+ ? \`uniform vec2 viewportSize;
8498
+ void main() {
8499
+ vec4 center = projectionMatrix * viewMatrix * modelMatrix * vec4(0.0, 0.0, 0.0, 1.0);
8500
+ center.xy += position.xy * 200.0 / viewportSize * center.w;
8501
+ gl_Position = center;
8502
+ }\`
8503
+ : \`void main() {
8504
+ vec3 center = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
8505
+ vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
8506
+ vec3 up = vec3(viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1]);
8507
+ vec3 worldPosition = center + right * position.x + up * position.y;
8508
+ gl_Position = projectionMatrix * viewMatrix * vec4(worldPosition, 1.0);
8509
+ }\`,
8510
+ });
8511
+ }
8512
+ const outline = new LineSegments(
8513
+ new BufferGeometry().setFromPoints(points),
8514
+ material,
8515
+ );
8516
+ if (alignment === 'screen-space') {
8517
+ const viewportSize = material.uniforms.viewportSize.value;
8518
+ outline.onBeforeRender = (renderer) => {
8519
+ renderer.getDrawingBufferSize(viewportSize);
8520
+ };
8521
+ }
8522
+ return markLightEditorHelper(
8523
+ outline,
8524
+ nodeId,
8525
+ helperType,
8526
+ 'visual',
8527
+ );
8528
+ }
8529
+
8530
+ function createBlenderLightIcon(nodeId, helperType, color, sunRays = false) {
8531
+ const points = [];
8532
+ appendLightOutlineDiamond(points, 0.027);
8533
+ appendDashedLightOutlineCircle(points, 0.09, 16);
8534
+ appendDashedLightOutlineCircle(points, 0.1197, 20);
8535
+ if (sunRays) {
8536
+ for (let index = 0; index < 8; index += 1) {
8537
+ const angle = (index / 8) * Math.PI * 2;
8538
+ const direction = [Math.cos(angle), Math.sin(angle)];
8539
+ for (const [startScale, endScale] of [
8540
+ [0.144, 0.171],
8541
+ [0.198, 0.225],
8542
+ ]) {
8543
+ appendLightOutlineSegment(
8544
+ points,
8545
+ [direction[0] * startScale, direction[1] * startScale, 0],
8546
+ [direction[0] * endScale, direction[1] * endScale, 0],
8547
+ );
8548
+ }
8549
+ }
8550
+ }
8551
+ return createLightOutline(
8552
+ nodeId,
8553
+ helperType,
8554
+ color,
8555
+ points,
8556
+ 'screen-space',
8557
+ );
8558
+ }
8559
+
8560
+ function createSpotSilhouette(
8561
+ nodeId,
8562
+ helperType,
8563
+ color,
8564
+ radius,
8565
+ length,
8566
+ segments = 32,
8567
+ ) {
8568
+ const positions = [];
8569
+ const adjacentNormalsA = [];
8570
+ const adjacentNormalsB = [];
8571
+ const edgeCenters = [];
8572
+ const angularStep = (Math.PI * 2) / segments;
8573
+ const appendVectorTwice = (target, value) => {
8574
+ target.push(...value, ...value);
8575
+ };
8576
+ const faceNormal = (angle) =>
8577
+ new Vector3(
8578
+ length * Math.cos(angle),
8579
+ length * Math.sin(angle),
8580
+ radius,
8581
+ )
8582
+ .normalize()
8583
+ .toArray();
8584
+ for (let index = 0; index < segments; index += 1) {
8585
+ const angle = index * angularStep;
8586
+ const base = [
8587
+ radius * Math.cos(angle),
8588
+ radius * Math.sin(angle),
8589
+ -length,
8590
+ ];
8591
+ positions.push(0, 0, 0, ...base);
8592
+ appendVectorTwice(
8593
+ adjacentNormalsA,
8594
+ faceNormal(angle - angularStep / 2),
8595
+ );
8596
+ appendVectorTwice(
8597
+ adjacentNormalsB,
8598
+ faceNormal(angle + angularStep / 2),
8599
+ );
8600
+ appendVectorTwice(edgeCenters, [base[0] / 2, base[1] / 2, -length / 2]);
8601
+ }
8602
+ const geometry = new BufferGeometry();
8603
+ geometry.setAttribute(
8604
+ 'position',
8605
+ new Float32BufferAttribute(positions, 3),
8606
+ );
8607
+ geometry.setAttribute(
8608
+ 'adjacentNormalA',
8609
+ new Float32BufferAttribute(adjacentNormalsA, 3),
8610
+ );
8611
+ geometry.setAttribute(
8612
+ 'adjacentNormalB',
8613
+ new Float32BufferAttribute(adjacentNormalsB, 3),
8614
+ );
8615
+ geometry.setAttribute(
8616
+ 'edgeCenter',
8617
+ new Float32BufferAttribute(edgeCenters, 3),
8618
+ );
8619
+ return markLightEditorHelper(
8620
+ new LineSegments(
8621
+ geometry,
8622
+ new ShaderMaterial({
8623
+ depthTest: false,
8624
+ depthWrite: false,
8625
+ fragmentShader: \`uniform vec3 outlineColor;
8626
+ void main() {
8627
+ gl_FragColor = vec4(outlineColor, 0.9);
8628
+ }\`,
8629
+ transparent: true,
8630
+ uniforms: { outlineColor: { value: color } },
8631
+ vertexShader: \`attribute vec3 adjacentNormalA;
8632
+ attribute vec3 adjacentNormalB;
8633
+ attribute vec3 edgeCenter;
8634
+ void main() {
8635
+ vec3 centerInView = (modelViewMatrix * vec4(edgeCenter, 1.0)).xyz;
8636
+ bool perspective = projectionMatrix[2][3] == -1.0;
8637
+ vec3 viewDirection = perspective ? normalize(-centerInView) : vec3(0.0, 0.0, 1.0);
8638
+ float facingA = dot(normalize(normalMatrix * adjacentNormalA), viewDirection);
8639
+ float facingB = dot(normalize(normalMatrix * adjacentNormalB), viewDirection);
8640
+ vec3 visiblePosition = facingA * facingB <= 0.0 ? position : vec3(0.0);
8641
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(visiblePosition, 1.0);
8642
+ }\`,
8643
+ }),
8644
+ ),
8645
+ nodeId,
8646
+ helperType,
8647
+ 'visual',
8648
+ );
8649
+ }
8650
+
7696
8651
  function createComponentHelperDecoration(node, helperType) {
7697
8652
  const group = new Group();
7698
8653
  group.name = node.id + '-' + helperType + '-helper';
7699
8654
  group.userData.iwsdkEditorHelper = true;
7700
8655
  group.userData.iwsdkEditorHelperType = helperType;
7701
8656
  group.userData.iwsdkSceneNodeId = node.id;
8657
+ if (isLightEditorHelperType(helperType)) {
8658
+ group.matrixAutoUpdate = false;
8659
+ group.matrixWorldAutoUpdate = false;
8660
+ group.userData.iwsdkEditorScaleInvariant = true;
8661
+ group.userData.iwsdkEditorWorldPosition = new Vector3();
8662
+ group.userData.iwsdkEditorWorldQuaternion = new Quaternion();
8663
+ group.userData.iwsdkEditorWorldScale = new Vector3(1, 1, 1);
8664
+ }
7702
8665
 
7703
8666
  const lightSpec = Object.entries(node.components || {})
7704
8667
  .map(([componentName, value]) =>
7705
8668
  lightSpecFromComponentValue(componentName, value),
7706
8669
  )
7707
8670
  .find(Boolean);
7708
- const lightColor = new Color(0xffd86b);
7709
- const authoredColor = lightSpec?.color || lightSpec?.skyColor;
7710
- if (authoredColor) {
7711
- lightColor.setRGB(authoredColor[0], authoredColor[1], authoredColor[2]);
7712
- }
8671
+ const lightColor = new Color(0xffa62b);
7713
8672
 
7714
8673
  if (helperType === 'audio-source') {
7715
8674
  const body = markOwnedEditorHelper(
@@ -7737,140 +8696,238 @@ function createComponentHelperDecoration(node, helperType) {
7737
8696
  wave.position.x = 0.18;
7738
8697
  group.add(body, wave);
7739
8698
  } else if (helperType === 'camera-source') {
7740
- const body = markOwnedEditorHelper(
7741
- new Mesh(
7742
- new BoxGeometry(0.22, 0.14, 0.12),
7743
- new MeshBasicMaterial({ color: 0xffd166, opacity: 0.9, transparent: true }),
7744
- ),
8699
+ const cameraColor = new Color(0xffa62b);
8700
+ const handle = createLightPickHandle(node.id, helperType, cameraColor);
8701
+ const center = createLightCenterDot(node.id, helperType, cameraColor);
8702
+ const points = [];
8703
+ const planeZ = -0.44;
8704
+ const corners = [
8705
+ [-0.22, -0.14, planeZ],
8706
+ [0.22, -0.14, planeZ],
8707
+ [0.22, 0.14, planeZ],
8708
+ [-0.22, 0.14, planeZ],
8709
+ ];
8710
+ for (const corner of corners) {
8711
+ appendLightOutlineSegment(points, [0, 0, 0], corner);
8712
+ }
8713
+ for (let index = 0; index < corners.length; index += 1) {
8714
+ appendLightOutlineSegment(
8715
+ points,
8716
+ corners[index],
8717
+ corners[(index + 1) % corners.length],
8718
+ );
8719
+ }
8720
+ const frustum = createLightOutline(
7745
8721
  node.id,
7746
8722
  helperType,
8723
+ cameraColor,
8724
+ points,
7747
8725
  );
7748
- const frustum = markOwnedEditorHelper(
8726
+ const upMarker = markLightEditorHelper(
7749
8727
  new Mesh(
7750
- new ConeGeometry(0.2, 0.34, 4, 1, true),
8728
+ new BufferGeometry().setFromPoints([
8729
+ new Vector3(-0.08, 0.16, planeZ),
8730
+ new Vector3(0.08, 0.16, planeZ),
8731
+ new Vector3(0, 0.29, planeZ),
8732
+ new Vector3(0, 0.29, planeZ),
8733
+ new Vector3(0.08, 0.16, planeZ),
8734
+ new Vector3(-0.08, 0.16, planeZ),
8735
+ ]),
7751
8736
  new MeshBasicMaterial({
7752
- color: 0xfff0a8,
7753
- opacity: 0.5,
7754
- transparent: true,
7755
- wireframe: true,
8737
+ color: cameraColor,
8738
+ depthTest: false,
8739
+ depthWrite: false,
7756
8740
  }),
7757
8741
  ),
7758
8742
  node.id,
7759
8743
  helperType,
8744
+ 'visual',
7760
8745
  );
7761
- frustum.rotation.x = Math.PI / 2;
7762
- frustum.position.z = -0.24;
7763
- group.add(body, frustum);
8746
+ group.add(handle, center, frustum, upMarker);
7764
8747
  } else if (helperType === 'point-light') {
7765
- const distance = lightSpec?.kind === 'point' ? lightSpec.distance : 0;
7766
- const radius = distance > 0 ? distance : 0.18;
7767
- const range = markOwnedEditorHelper(
7768
- new Mesh(
7769
- new SphereGeometry(radius, 20, 14),
7770
- new MeshBasicMaterial({
7771
- color: lightColor,
7772
- opacity: distance > 0 ? 0.22 : 0.68,
7773
- transparent: true,
7774
- wireframe: true,
7775
- }),
7776
- ),
8748
+ const handle = createLightPickHandle(node.id, helperType, lightColor);
8749
+ const center = createLightCenterDot(node.id, helperType, lightColor);
8750
+ const icon = createBlenderLightIcon(node.id, helperType, lightColor);
8751
+ const points = [];
8752
+ appendLightOutlineCircle(points, 0.13, 'xy', [0, 0, 0], 32);
8753
+ const symbol = createLightOutline(
7777
8754
  node.id,
7778
8755
  helperType,
8756
+ lightColor,
8757
+ points,
8758
+ 'screen-aligned',
7779
8759
  );
7780
- group.add(range);
8760
+ group.add(handle, center, icon, symbol);
7781
8761
  } else if (helperType === 'spot-light') {
7782
- const distance =
7783
- lightSpec?.kind === 'spot' && lightSpec.distance > 0
7784
- ? lightSpec.distance
7785
- : 0.5;
8762
+ const handle = createLightPickHandle(node.id, helperType, lightColor);
8763
+ const center = createLightCenterDot(node.id, helperType, lightColor);
8764
+ const icon = createBlenderLightIcon(node.id, helperType, lightColor);
8765
+ const emitterPoints = [];
8766
+ appendLightOutlineCircle(emitterPoints, 0.07, 'xy', [0, 0, 0], 32);
8767
+ const emitter = createLightOutline(
8768
+ node.id,
8769
+ helperType,
8770
+ lightColor,
8771
+ emitterPoints,
8772
+ 'screen-aligned',
8773
+ );
8774
+ const length = 0.5;
7786
8775
  const angleDeg = lightSpec?.kind === 'spot' ? lightSpec.angleDeg : 60;
7787
- const radius = Math.max(
7788
- 0.02,
7789
- Math.tan(MathUtils.degToRad(angleDeg)) * distance,
8776
+ const radius = MathUtils.clamp(
8777
+ Math.tan(MathUtils.degToRad(MathUtils.clamp(angleDeg, 5, 70))) * length,
8778
+ 0.08,
8779
+ 0.26,
7790
8780
  );
7791
- const cone = markOwnedEditorHelper(
7792
- new Mesh(
7793
- new ConeGeometry(radius, distance, 24, 1, true),
7794
- new MeshBasicMaterial({
7795
- color: lightColor,
7796
- opacity: 0.62,
7797
- transparent: true,
7798
- wireframe: true,
7799
- }),
7800
- ),
8781
+ const points = [];
8782
+ appendLightOutlineCircle(points, radius, 'xy', [0, 0, -length], 24);
8783
+ appendLightOutlineCircle(
8784
+ points,
8785
+ radius * 0.86,
8786
+ 'xy',
8787
+ [0, 0, -length],
8788
+ 24,
8789
+ );
8790
+ appendLightOutlineSegment(points, [0, 0, 0], [0, 0, -length]);
8791
+ const coneOutline = createLightOutline(
8792
+ node.id,
8793
+ helperType,
8794
+ lightColor,
8795
+ points,
8796
+ );
8797
+ const coneSilhouette = createSpotSilhouette(
7801
8798
  node.id,
7802
8799
  helperType,
8800
+ lightColor,
8801
+ radius,
8802
+ length,
7803
8803
  );
7804
- cone.rotation.x = Math.PI / 2;
7805
- cone.position.z = -distance / 2;
7806
- group.add(cone);
8804
+ group.add(handle, center, icon, emitter, coneOutline, coneSilhouette);
7807
8805
  } else if (helperType === 'directional-light') {
7808
- const shaft = markOwnedEditorHelper(
7809
- new Mesh(
7810
- new CylinderGeometry(0.035, 0.035, 0.36, 12),
7811
- new MeshBasicMaterial({ color: lightColor }),
7812
- ),
8806
+ const handle = createLightPickHandle(node.id, helperType, lightColor);
8807
+ const center = createLightCenterDot(node.id, helperType, lightColor);
8808
+ const icon = createBlenderLightIcon(node.id, helperType, lightColor, true);
8809
+ const points = [];
8810
+ appendLightOutlineSegment(points, [0, 0, 0], [0, 0, -0.46]);
8811
+ const direction = createLightOutline(
7813
8812
  node.id,
7814
8813
  helperType,
8814
+ lightColor,
8815
+ points,
7815
8816
  );
7816
- shaft.rotation.x = -Math.PI / 2;
7817
- shaft.position.z = -0.18;
7818
- const head = markOwnedEditorHelper(
7819
- new Mesh(
7820
- new ConeGeometry(0.1, 0.2, 16),
7821
- new MeshBasicMaterial({ color: lightColor }),
7822
- ),
8817
+ const endpointPoints = [];
8818
+ appendLightOutlineDiamond(endpointPoints, 0.022);
8819
+ const endpoint = createLightOutline(
7823
8820
  node.id,
7824
8821
  helperType,
8822
+ lightColor,
8823
+ endpointPoints,
8824
+ 'screen-space',
7825
8825
  );
7826
- head.rotation.x = -Math.PI / 2;
7827
- head.position.z = -0.44;
7828
- group.add(shaft, head);
8826
+ endpoint.position.z = -0.46;
8827
+ group.add(handle, center, icon, direction, endpoint);
7829
8828
  } else if (helperType === 'rect-area-light') {
7830
- const width = lightSpec?.kind === 'rect-area' ? lightSpec.width : 0.48;
7831
- const height = lightSpec?.kind === 'rect-area' ? lightSpec.height : 0.32;
7832
- const panel = markOwnedEditorHelper(
7833
- new Mesh(
7834
- new BoxGeometry(width, height, 0.025),
7835
- new MeshBasicMaterial({
7836
- color: lightColor,
7837
- opacity: 0.55,
7838
- transparent: true,
7839
- wireframe: true,
7840
- }),
7841
- ),
8829
+ const authoredWidth = lightSpec?.kind === 'rect-area' ? lightSpec.width : 0.48;
8830
+ const authoredHeight = lightSpec?.kind === 'rect-area' ? lightSpec.height : 0.32;
8831
+ const fitScale = Math.min(
8832
+ 1,
8833
+ 0.42 / Math.max(Math.abs(authoredWidth), Math.abs(authoredHeight), 0.01),
8834
+ );
8835
+ const width = Math.max(0.12, Math.abs(authoredWidth) * fitScale);
8836
+ const height = Math.max(0.08, Math.abs(authoredHeight) * fitScale);
8837
+ const handle = createLightPickHandle(node.id, helperType, lightColor);
8838
+ const center = createLightCenterDot(node.id, helperType, lightColor);
8839
+ const icon = createBlenderLightIcon(node.id, helperType, lightColor);
8840
+ const points = [];
8841
+ const corners = [
8842
+ [-width / 2, -height / 2, 0],
8843
+ [width / 2, -height / 2, 0],
8844
+ [width / 2, height / 2, 0],
8845
+ [-width / 2, height / 2, 0],
8846
+ ];
8847
+ for (let index = 0; index < corners.length; index += 1) {
8848
+ appendLightOutlineSegment(
8849
+ points,
8850
+ corners[index],
8851
+ corners[(index + 1) % corners.length],
8852
+ );
8853
+ }
8854
+ appendLightOutlineSegment(points, [0, 0, 0], [0, 0, -0.44]);
8855
+ const panel = createLightOutline(
7842
8856
  node.id,
7843
8857
  helperType,
8858
+ lightColor,
8859
+ points,
7844
8860
  );
7845
- group.add(panel);
7846
- } else {
7847
- const core = markOwnedEditorHelper(
7848
- new Mesh(
7849
- new CylinderGeometry(0.14, 0.14, 0.06, 24),
7850
- new MeshBasicMaterial({ color: 0xa8ff78, opacity: 0.85, transparent: true }),
7851
- ),
8861
+ const endpointPoints = [];
8862
+ appendLightOutlineDiamond(endpointPoints, 0.022);
8863
+ const endpoint = createLightOutline(
7852
8864
  node.id,
7853
8865
  helperType,
8866
+ lightColor,
8867
+ endpointPoints,
8868
+ 'screen-space',
7854
8869
  );
7855
- const halo = markOwnedEditorHelper(
7856
- new Mesh(
7857
- new ConeGeometry(0.28, 0.12, 24, 1, true),
7858
- new MeshBasicMaterial({
7859
- color: 0xf7ff9e,
7860
- opacity: 0.45,
7861
- transparent: true,
7862
- wireframe: true,
7863
- }),
7864
- ),
8870
+ endpoint.position.z = -0.44;
8871
+ group.add(handle, center, icon, panel, endpoint);
8872
+ } else {
8873
+ const handle = createLightPickHandle(node.id, helperType, lightColor);
8874
+ const center = createLightCenterDot(node.id, helperType, lightColor);
8875
+ const points = [];
8876
+ appendLightOutlineCircle(points, 0.17, 'xy', [0, 0, 0], 24);
8877
+ appendLightOutlineCircle(points, 0.17, 'xz', [0, 0, 0], 24);
8878
+ const halo = createLightOutline(
7865
8879
  node.id,
7866
8880
  helperType,
8881
+ lightColor,
8882
+ points,
7867
8883
  );
7868
- halo.position.y = 0.04;
7869
- group.add(core, halo);
8884
+ group.add(handle, center, halo);
7870
8885
  }
7871
8886
  return group;
7872
8887
  }
7873
8888
 
8889
+ function componentHelperProof(nodeId) {
8890
+ syncEditorLightHelperTransforms();
8891
+ const object = editorWorldState?.objectMap.get(nodeId);
8892
+ const helper = object?.children.find(
8893
+ (child) =>
8894
+ child.userData?.iwsdkEditorHelper === true &&
8895
+ typeof child.userData?.iwsdkEditorHelperType === 'string',
8896
+ );
8897
+ if (!helper) {
8898
+ return null;
8899
+ }
8900
+ helper.updateMatrixWorld(true);
8901
+ const bounds = new Box3().setFromObject(helper);
8902
+ const size = new Vector3();
8903
+ if (!bounds.isEmpty()) {
8904
+ bounds.getSize(size);
8905
+ }
8906
+ const meshes = [];
8907
+ helper.traverse((entry) => {
8908
+ if (!entry.isMesh && !entry.isLine) {
8909
+ return;
8910
+ }
8911
+ meshes.push({
8912
+ color:
8913
+ entry.material?.color?.getHexString?.() ||
8914
+ entry.material?.uniforms?.outlineColor?.value?.getHexString?.() ||
8915
+ null,
8916
+ geometry: entry.geometry?.type || null,
8917
+ kind: entry.isLine ? 'line' : 'mesh',
8918
+ material: entry.material?.type || null,
8919
+ pickable: entry.userData?.iwsdkEditorPickable !== false,
8920
+ role: entry.userData?.iwsdkEditorLightRole || null,
8921
+ vertexCount: entry.geometry?.attributes?.position?.count || 0,
8922
+ });
8923
+ });
8924
+ return {
8925
+ helperType: helper.userData.iwsdkEditorHelperType,
8926
+ meshes,
8927
+ size: roundVec3(size.toArray()),
8928
+ };
8929
+ }
8930
+
7874
8931
  async function waitForAssetLoads() {
7875
8932
  if (!editorWorldState) {
7876
8933
  return;
@@ -8180,6 +9237,25 @@ function syncEditorLightBindings() {
8180
9237
  }
8181
9238
  }
8182
9239
 
9240
+ function syncEditorLightHelperTransforms() {
9241
+ if (!editorWorldState?.objectMap) return;
9242
+ for (const object of editorWorldState.objectMap.values()) {
9243
+ const helper = object.children.find(
9244
+ (child) => child.userData?.iwsdkEditorScaleInvariant === true,
9245
+ );
9246
+ if (!helper) continue;
9247
+ object.updateWorldMatrix(true, false);
9248
+ const position = helper.userData.iwsdkEditorWorldPosition;
9249
+ const quaternion = helper.userData.iwsdkEditorWorldQuaternion;
9250
+ const scale = helper.userData.iwsdkEditorWorldScale;
9251
+ object.getWorldPosition(position);
9252
+ object.getWorldQuaternion(quaternion);
9253
+ helper.matrixWorld.compose(position, quaternion, scale);
9254
+ helper.matrixWorldNeedsUpdate = false;
9255
+ helper.updateWorldMatrix(false, true);
9256
+ }
9257
+ }
9258
+
8183
9259
  function runtimeComponentForSceneName(componentName) {
8184
9260
  const componentId = stripComponentPrefix(componentName);
8185
9261
  const targetId = componentId === 'Interactable' ? 'RayInteractable' : componentId;
@@ -8721,7 +9797,20 @@ function boundsForObjectWithoutEditorHelpers(object) {
8721
9797
  return fallbackBounds.isEmpty() ? null : fallbackBounds;
8722
9798
  }
8723
9799
 
9800
+ function isLightEditorHelperType(helperType) {
9801
+ return (
9802
+ helperType === 'directional-light' ||
9803
+ helperType === 'environment-light' ||
9804
+ helperType === 'point-light' ||
9805
+ helperType === 'rect-area-light' ||
9806
+ helperType === 'spot-light'
9807
+ );
9808
+ }
9809
+
8724
9810
  function createEditorBoundsHelper(object, color) {
9811
+ if (isLightEditorHelperType(object.userData?.iwsdkEditorHelperType)) {
9812
+ return null;
9813
+ }
8725
9814
  const bounds = boundsForObjectWithoutEditorHelpers(object);
8726
9815
  if (!bounds) {
8727
9816
  return null;
@@ -8971,6 +10060,8 @@ function renderEditorWorld() {
8971
10060
  }
8972
10061
  hideCurrentEditorHelpersForRenderOnlyCapture();
8973
10062
  syncEditorLightBindings();
10063
+ syncEditorLightHelperTransforms();
10064
+ syncInfiniteEditorGrid();
8974
10065
  const startedAt = performance.now();
8975
10066
  editorWorldState.world.renderer.render(
8976
10067
  editorWorldState.world.scene,
@@ -9649,6 +10740,42 @@ function selectedBuiltinTarget() {
9649
10740
  return target === 'player' ? target : null;
9650
10741
  }
9651
10742
 
10743
+ function lightScaleTarget(node) {
10744
+ if (!node || node.content != null) {
10745
+ return null;
10746
+ }
10747
+ for (const [component, value] of Object.entries(node.components || {})) {
10748
+ const spec = lightSpecFromComponentValue(component, value);
10749
+ if (spec) {
10750
+ return { component, spec, value };
10751
+ }
10752
+ }
10753
+ return null;
10754
+ }
10755
+
10756
+ function lightScaleAxisPolicy(node) {
10757
+ const target = lightScaleTarget(node);
10758
+ if (!target) return null;
10759
+ switch (target.spec.kind) {
10760
+ case 'point':
10761
+ return {
10762
+ x: target.spec.distance > 0,
10763
+ y: target.spec.distance > 0,
10764
+ z: target.spec.distance > 0,
10765
+ };
10766
+ case 'spot':
10767
+ return {
10768
+ x: true,
10769
+ y: true,
10770
+ z: target.spec.distance > 0,
10771
+ };
10772
+ case 'rect-area':
10773
+ return { x: true, y: true, z: false };
10774
+ default:
10775
+ return { x: false, y: false, z: false };
10776
+ }
10777
+ }
10778
+
9652
10779
  function selectionForNodeClick(nodeId, event) {
9653
10780
  const currentSelection = Array.isArray(window.__IWSDK_EDITOR_SELECTION)
9654
10781
  ? window.__IWSDK_EDITOR_SELECTION
@@ -9671,6 +10798,14 @@ function applyTransformControlSettings() {
9671
10798
  const transformControls = editorWorldState.transformControls;
9672
10799
  transformControls.setMode(mode);
9673
10800
  transformControls.setSpace(space);
10801
+ const nodeId = selectedNodeId();
10802
+ const node = nodeId
10803
+ ? findNodeById(editorWorldState.currentSession?.document, nodeId)
10804
+ : null;
10805
+ const lightPolicy = mode === 'scale' ? lightScaleAxisPolicy(node) : null;
10806
+ transformControls.showX = lightPolicy?.x ?? true;
10807
+ transformControls.showY = lightPolicy?.y ?? true;
10808
+ transformControls.showZ = lightPolicy?.z ?? true;
9674
10809
  const snap = editorWorldState.transformSnapEnabled
9675
10810
  ? editorWorldState.transformSnap
9676
10811
  : null;
@@ -9713,6 +10848,119 @@ function setTransformControlSnap(transformControls, method, property, value) {
9713
10848
  }
9714
10849
  }
9715
10850
 
10851
+ function scaleRatio(startTransform, nextTransform) {
10852
+ const start = scaleVectorFromTransform(startTransform);
10853
+ const next = scaleVectorFromTransform(nextTransform);
10854
+ return start.map((value, index) =>
10855
+ Math.max(
10856
+ 0.001,
10857
+ Math.abs(value) > 1e-6 ? Math.abs(next[index] / value) : 1,
10858
+ ),
10859
+ );
10860
+ }
10861
+
10862
+ function inferredScaleAxis(ratio) {
10863
+ const changed = ['X', 'Y', 'Z'].filter(
10864
+ (_axis, index) => Math.abs(ratio[index] - 1) > 1e-4,
10865
+ );
10866
+ if (
10867
+ changed.length === 3 &&
10868
+ Math.abs(ratio[0] - ratio[1]) < 1e-4 &&
10869
+ Math.abs(ratio[1] - ratio[2]) < 1e-4
10870
+ ) {
10871
+ return 'XYZ';
10872
+ }
10873
+ return changed.join('');
10874
+ }
10875
+
10876
+ function combinedScaleFactor(ratio, axis) {
10877
+ const indices = ['X', 'Y', 'Z']
10878
+ .map((name, index) => (axis.includes(name) ? index : -1))
10879
+ .filter((index) => index >= 0);
10880
+ if (indices.length === 0) return 1;
10881
+ return Math.pow(
10882
+ indices.reduce((product, index) => product * ratio[index], 1),
10883
+ 1 / indices.length,
10884
+ );
10885
+ }
10886
+
10887
+ function roundedLightProperty(value) {
10888
+ return Number(value.toFixed(4));
10889
+ }
10890
+
10891
+ function lightPropertyScaleEdit(node, startTransform, nextTransform, scaleAxis) {
10892
+ const target = lightScaleTarget(node);
10893
+ if (!target) return null;
10894
+ const ratio = scaleRatio(startTransform, nextTransform);
10895
+ const axis = scaleAxis || inferredScaleAxis(ratio);
10896
+ const value = { ...target.value };
10897
+ let changed = false;
10898
+ switch (target.spec.kind) {
10899
+ case 'point': {
10900
+ if (target.spec.distance <= 0) break;
10901
+ const factor = combinedScaleFactor(ratio, axis || 'XYZ');
10902
+ value.distance = roundedLightProperty(
10903
+ Math.max(0.001, target.spec.distance * factor),
10904
+ );
10905
+ changed = value.distance !== target.spec.distance;
10906
+ break;
10907
+ }
10908
+ case 'spot': {
10909
+ if (axis !== 'XYZ' && (axis.includes('X') || axis.includes('Y'))) {
10910
+ const radialAxis = ['X', 'Y'].filter((name) => axis.includes(name)).join('');
10911
+ const radialFactor = combinedScaleFactor(ratio, radialAxis);
10912
+ value.angleDeg = roundedLightProperty(
10913
+ MathUtils.clamp(
10914
+ MathUtils.radToDeg(
10915
+ Math.atan(
10916
+ Math.tan(MathUtils.degToRad(target.spec.angleDeg)) *
10917
+ radialFactor,
10918
+ ),
10919
+ ),
10920
+ 0.1,
10921
+ 90,
10922
+ ),
10923
+ );
10924
+ changed = value.angleDeg !== target.spec.angleDeg;
10925
+ }
10926
+ if (axis.includes('Z') && target.spec.distance > 0) {
10927
+ value.distance = roundedLightProperty(
10928
+ Math.max(0.001, target.spec.distance * ratio[2]),
10929
+ );
10930
+ changed = changed || value.distance !== target.spec.distance;
10931
+ }
10932
+ break;
10933
+ }
10934
+ case 'rect-area': {
10935
+ if (axis.includes('X')) {
10936
+ value.width = roundedLightProperty(
10937
+ Math.max(0.001, target.spec.width * ratio[0]),
10938
+ );
10939
+ changed = value.width !== target.spec.width;
10940
+ }
10941
+ if (axis.includes('Y')) {
10942
+ value.height = roundedLightProperty(
10943
+ Math.max(0.001, target.spec.height * ratio[1]),
10944
+ );
10945
+ changed = changed || value.height !== target.spec.height;
10946
+ }
10947
+ break;
10948
+ }
10949
+ }
10950
+ return {
10951
+ changed,
10952
+ patch: changed
10953
+ ? {
10954
+ component: target.component,
10955
+ nodeId: node.id,
10956
+ op: 'updateComponent',
10957
+ value,
10958
+ }
10959
+ : null,
10960
+ policy: target.spec.kind,
10961
+ };
10962
+ }
10963
+
9716
10964
  function renderTransformToolbar() {
9717
10965
  const mode = editorWorldState?.transformMode || 'translate';
9718
10966
  const space = editorWorldState?.transformSpace || 'local';
@@ -9741,6 +10989,7 @@ function setTransformMode(mode) {
9741
10989
  if (editorWorldState) {
9742
10990
  editorWorldState.transformMode = mode;
9743
10991
  applyTransformControlSettings();
10992
+ workspaceUi?.update({ transformMode: mode });
9744
10993
  renderEditorWorld();
9745
10994
  }
9746
10995
  renderTransformToolbar();
@@ -9758,6 +11007,46 @@ function setTransformSpace(space) {
9758
11007
  renderTransformToolbar();
9759
11008
  }
9760
11009
 
11010
+ function transformSnapPropertyForMode(mode) {
11011
+ if (mode === 'rotate') {
11012
+ return 'rotationDeg';
11013
+ }
11014
+ if (mode === 'scale') {
11015
+ return 'scale';
11016
+ }
11017
+ return 'translation';
11018
+ }
11019
+
11020
+ function setTransformSnapValue(mode, value, persist = true) {
11021
+ if (!editorWorldState) {
11022
+ return null;
11023
+ }
11024
+ const property = transformSnapPropertyForMode(mode);
11025
+ const nextValue = normalizeEditorTransformSnapValue(property, value);
11026
+ editorWorldState.transformSnap = {
11027
+ ...editorWorldState.transformSnap,
11028
+ [property]: nextValue,
11029
+ };
11030
+ applyTransformControlSettings();
11031
+ if (persist && typeof localStorage !== 'undefined') {
11032
+ try {
11033
+ localStorage.setItem(
11034
+ EDITOR_TRANSFORM_SNAP_STORAGE_KEY,
11035
+ JSON.stringify(editorWorldState.transformSnap),
11036
+ );
11037
+ } catch {
11038
+ // The snap settings still apply when browser storage is unavailable.
11039
+ }
11040
+ }
11041
+ workspaceUi?.update({
11042
+ transformSnapRotationDeg: editorWorldState.transformSnap.rotationDeg,
11043
+ transformSnapScale: editorWorldState.transformSnap.scale,
11044
+ transformSnapTranslation: editorWorldState.transformSnap.translation,
11045
+ });
11046
+ renderEditorWorld();
11047
+ return nextValue;
11048
+ }
11049
+
9761
11050
  function setTransformSnapEnabled(enabled) {
9762
11051
  if (editorWorldState) {
9763
11052
  editorWorldState.transformSnapEnabled = Boolean(enabled);
@@ -9845,6 +11134,28 @@ async function commitTransformControlDrag(session, rerender) {
9845
11134
  const nextTransform = snapTransformForCurrentMode(
9846
11135
  transformFromObject(object, node.transform || {}),
9847
11136
  );
11137
+ const lightScaleEdit =
11138
+ dragState.mode === 'scale'
11139
+ ? lightPropertyScaleEdit(
11140
+ node,
11141
+ dragState.startTransform,
11142
+ nextTransform,
11143
+ dragState.scaleAxis,
11144
+ )
11145
+ : null;
11146
+ if (lightScaleEdit) {
11147
+ applyNodeTransform(object, dragState.startTransform);
11148
+ updateSelectionHelpers();
11149
+ renderEditorWorld();
11150
+ if (lightScaleEdit.patch) {
11151
+ await session.dispatch('scene_apply_patch', {
11152
+ patch: lightScaleEdit.patch,
11153
+ });
11154
+ clearValidationResult();
11155
+ }
11156
+ rerender();
11157
+ return;
11158
+ }
9848
11159
  applyNodeTransform(object, nextTransform);
9849
11160
  updateSelectionHelpers();
9850
11161
  renderEditorWorld();
@@ -9988,6 +11299,193 @@ function syncEditorWorld(session, camera, size = {}) {
9988
11299
  updateProjectedHitTargets(session);
9989
11300
  }
9990
11301
 
11302
+ function normalizeEditorDrawDistance(value) {
11303
+ if (value == null || value === '') {
11304
+ return DEFAULT_EDITOR_DRAW_DISTANCE;
11305
+ }
11306
+ const numeric = Number(value);
11307
+ if (!Number.isFinite(numeric)) {
11308
+ return DEFAULT_EDITOR_DRAW_DISTANCE;
11309
+ }
11310
+ return Math.round(
11311
+ MathUtils.clamp(
11312
+ numeric,
11313
+ MIN_EDITOR_DRAW_DISTANCE,
11314
+ MAX_EDITOR_DRAW_DISTANCE,
11315
+ ),
11316
+ );
11317
+ }
11318
+
11319
+ function loadEditorDrawDistance() {
11320
+ if (typeof localStorage === 'undefined') {
11321
+ return DEFAULT_EDITOR_DRAW_DISTANCE;
11322
+ }
11323
+ try {
11324
+ return normalizeEditorDrawDistance(
11325
+ localStorage.getItem(EDITOR_DRAW_DISTANCE_STORAGE_KEY),
11326
+ );
11327
+ } catch {
11328
+ return DEFAULT_EDITOR_DRAW_DISTANCE;
11329
+ }
11330
+ }
11331
+
11332
+ function normalizeEditorTransformSnapValue(property, value) {
11333
+ const fallback = DEFAULT_EDITOR_TRANSFORM_SNAP[property];
11334
+ const limits = EDITOR_TRANSFORM_SNAP_LIMITS[property];
11335
+ const numeric = Number(value);
11336
+ if (!limits || !Number.isFinite(numeric)) {
11337
+ return fallback;
11338
+ }
11339
+ return Number(
11340
+ MathUtils.clamp(numeric, limits.min, limits.max).toFixed(6),
11341
+ );
11342
+ }
11343
+
11344
+ function normalizeEditorTransformSnap(value) {
11345
+ const candidate = value && typeof value === 'object' ? value : {};
11346
+ return {
11347
+ rotationDeg: normalizeEditorTransformSnapValue(
11348
+ 'rotationDeg',
11349
+ candidate.rotationDeg,
11350
+ ),
11351
+ scale: normalizeEditorTransformSnapValue('scale', candidate.scale),
11352
+ translation: normalizeEditorTransformSnapValue(
11353
+ 'translation',
11354
+ candidate.translation,
11355
+ ),
11356
+ };
11357
+ }
11358
+
11359
+ function loadEditorTransformSnap() {
11360
+ if (typeof localStorage === 'undefined') {
11361
+ return { ...DEFAULT_EDITOR_TRANSFORM_SNAP };
11362
+ }
11363
+ try {
11364
+ const stored = localStorage.getItem(EDITOR_TRANSFORM_SNAP_STORAGE_KEY);
11365
+ return normalizeEditorTransformSnap(stored ? JSON.parse(stored) : null);
11366
+ } catch {
11367
+ return { ...DEFAULT_EDITOR_TRANSFORM_SNAP };
11368
+ }
11369
+ }
11370
+
11371
+ function createInfiniteEditorGrid(drawDistance) {
11372
+ const material = new ShaderMaterial({
11373
+ depthTest: true,
11374
+ depthWrite: false,
11375
+ extensions: { derivatives: true },
11376
+ fragmentShader:
11377
+ 'varying vec3 gridWorldPosition; ' +
11378
+ 'uniform float drawDistance; ' +
11379
+ 'uniform float minimumGridSpacing; ' +
11380
+ 'uniform bool perspectiveView; ' +
11381
+ 'float gridLine(vec2 position, float scale) { ' +
11382
+ ' vec2 coordinate = position / scale; ' +
11383
+ ' vec2 width = max(fwidth(coordinate), vec2(0.0001)); ' +
11384
+ ' vec2 lineDistance = abs(fract(coordinate - 0.5) - 0.5) / width; ' +
11385
+ ' return 1.0 - min(min(lineDistance.x, lineDistance.y), 1.0); ' +
11386
+ '} ' +
11387
+ 'void main() { ' +
11388
+ ' vec2 gridPosition = gridWorldPosition.xz; ' +
11389
+ ' float pixelWorldSize = max(length(fwidth(gridPosition)), 0.0001); ' +
11390
+ ' float level = log(max((pixelWorldSize * 10.0) / minimumGridSpacing, 1.0)) / log(10.0); ' +
11391
+ ' float gridScale = minimumGridSpacing * pow(10.0, floor(level)); ' +
11392
+ ' float levelBlend = fract(level); ' +
11393
+ ' float fineLine = gridLine(gridPosition, gridScale); ' +
11394
+ ' float middleLine = gridLine(gridPosition, gridScale * 10.0); ' +
11395
+ ' float coarseLine = gridLine(gridPosition, gridScale * 100.0); ' +
11396
+ ' float fineAlpha = fineLine * (1.0 - levelBlend) * 0.22; ' +
11397
+ ' float middleAlpha = middleLine * mix(0.48, 0.22, levelBlend); ' +
11398
+ ' float coarseAlpha = coarseLine * levelBlend * 0.48; ' +
11399
+ ' float gridAlpha = max(fineAlpha, max(middleAlpha, coarseAlpha)); ' +
11400
+ ' float xAxis = 1.0 - smoothstep(0.0, max(fwidth(gridWorldPosition.z) * 1.5, 0.0001), abs(gridWorldPosition.z)); ' +
11401
+ ' float zAxis = 1.0 - smoothstep(0.0, max(fwidth(gridWorldPosition.x) * 1.5, 0.0001), abs(gridWorldPosition.x)); ' +
11402
+ ' vec3 color = vec3(0.24, 0.29, 0.32); ' +
11403
+ ' color = mix(color, vec3(0.63, 0.20, 0.19), xAxis); ' +
11404
+ ' color = mix(color, vec3(0.28, 0.53, 0.16), zAxis); ' +
11405
+ ' float alpha = max(gridAlpha, max(xAxis, zAxis) * 0.78); ' +
11406
+ ' float cameraDistance = length(cameraPosition - gridWorldPosition); ' +
11407
+ ' float distanceFade = 1.0 - smoothstep(drawDistance * 0.5, drawDistance, cameraDistance); ' +
11408
+ ' if (perspectiveView) { ' +
11409
+ ' vec3 viewDirection = normalize(cameraPosition - gridWorldPosition); ' +
11410
+ ' float angleFade = 1.0 - pow(1.0 - abs(viewDirection.y), 3.0); ' +
11411
+ ' distanceFade *= angleFade; ' +
11412
+ ' } ' +
11413
+ ' alpha *= distanceFade; ' +
11414
+ ' if (alpha < 0.003) discard; ' +
11415
+ ' gl_FragColor = vec4(color, alpha); ' +
11416
+ '}',
11417
+ polygonOffset: true,
11418
+ polygonOffsetFactor: -1,
11419
+ polygonOffsetUnits: -1,
11420
+ transparent: true,
11421
+ uniforms: {
11422
+ drawDistance: { value: drawDistance },
11423
+ minimumGridSpacing: { value: MIN_EDITOR_GRID_SPACING },
11424
+ perspectiveView: { value: true },
11425
+ },
11426
+ vertexShader:
11427
+ 'varying vec3 gridWorldPosition; ' +
11428
+ 'void main() { ' +
11429
+ ' vec4 worldPosition = modelMatrix * vec4(position, 1.0); ' +
11430
+ ' gridWorldPosition = worldPosition.xyz; ' +
11431
+ ' gl_Position = projectionMatrix * viewMatrix * worldPosition; ' +
11432
+ '}',
11433
+ });
11434
+ const grid = new Mesh(new PlaneGeometry(2, 2), material);
11435
+ grid.name = 'IWSDKSceneEditorGrid';
11436
+ grid.rotation.x = -Math.PI / 2;
11437
+ grid.scale.set(drawDistance, drawDistance, 1);
11438
+ grid.frustumCulled = false;
11439
+ grid.renderOrder = -1;
11440
+ grid.userData.iwsdkEditorHelper = true;
11441
+ grid.userData.iwsdkEditorInfiniteGrid = true;
11442
+ return grid;
11443
+ }
11444
+
11445
+ function syncInfiniteEditorGrid() {
11446
+ if (!editorWorldState?.editorGrid) {
11447
+ return;
11448
+ }
11449
+ const camera = editorWorldState.world.camera;
11450
+ const grid = editorWorldState.editorGrid;
11451
+ const drawDistance = editorWorldState.drawDistance;
11452
+ grid.position.set(camera.position.x, 0, camera.position.z);
11453
+ grid.scale.set(drawDistance, drawDistance, 1);
11454
+ grid.material.uniforms.drawDistance.value = drawDistance;
11455
+ grid.material.uniforms.perspectiveView.value =
11456
+ camera.isPerspectiveCamera === true;
11457
+ grid.updateMatrixWorld(true);
11458
+ }
11459
+
11460
+ function setEditorDrawDistance(value, persist = true) {
11461
+ const drawDistance = normalizeEditorDrawDistance(value);
11462
+ if (!editorWorldState) {
11463
+ return drawDistance;
11464
+ }
11465
+ editorWorldState.drawDistance = drawDistance;
11466
+ for (const camera of [
11467
+ editorWorldState.perspectiveCamera,
11468
+ editorWorldState.orthographicCamera,
11469
+ ]) {
11470
+ camera.far = drawDistance;
11471
+ camera.updateProjectionMatrix();
11472
+ }
11473
+ if (persist && typeof localStorage !== 'undefined') {
11474
+ try {
11475
+ localStorage.setItem(
11476
+ EDITOR_DRAW_DISTANCE_STORAGE_KEY,
11477
+ String(drawDistance),
11478
+ );
11479
+ } catch {
11480
+ // The viewport setting still applies when browser storage is unavailable.
11481
+ }
11482
+ }
11483
+ syncInfiniteEditorGrid();
11484
+ workspaceUi?.update({ viewportDrawDistance: drawDistance });
11485
+ renderEditorWorld();
11486
+ return drawDistance;
11487
+ }
11488
+
9991
11489
  async function createEditorWorld(session, camera) {
9992
11490
  const host = getViewportHost();
9993
11491
  const editorRuntime = window.FRAMEWORK_MCP_RUNTIME;
@@ -10025,7 +11523,11 @@ async function createEditorWorld(session, camera) {
10025
11523
  canvas.setAttribute('aria-label', 'IWSDK 3D scene viewport');
10026
11524
  world.renderer.setClearColor(0x101418, 1);
10027
11525
 
11526
+ const drawDistance = loadEditorDrawDistance();
11527
+ const transformSnap = loadEditorTransformSnap();
10028
11528
  const perspectiveCamera = world.camera;
11529
+ perspectiveCamera.far = drawDistance;
11530
+ perspectiveCamera.updateProjectionMatrix();
10029
11531
  const orthographicCamera = new OrthographicCamera(
10030
11532
  -1,
10031
11533
  1,
@@ -10065,9 +11567,7 @@ async function createEditorWorld(session, camera) {
10065
11567
  const { builtInObjectMap, levelRootProxy } =
10066
11568
  createEditorBuiltinRig(proxyRoot);
10067
11569
 
10068
- const grid = new GridHelper(12, 24, 0x40515f, 0x26343d);
10069
- grid.name = 'IWSDKSceneEditorGrid';
10070
- grid.userData.iwsdkEditorHelper = true;
11570
+ const grid = createInfiniteEditorGrid(drawDistance);
10071
11571
  world.scene.add(grid);
10072
11572
  const ambient = new AmbientLight(0xffffff, 0.65);
10073
11573
  ambient.name = 'IWSDKSceneEditorAmbientLight';
@@ -10086,6 +11586,7 @@ async function createEditorWorld(session, camera) {
10086
11586
  currentCamera: camera,
10087
11587
  currentDocumentValue: null,
10088
11588
  currentSession: session,
11589
+ drawDistance,
10089
11590
  editorAmbient: ambient,
10090
11591
  editorDirectional: directional,
10091
11592
  editorGrid: grid,
@@ -10135,11 +11636,7 @@ async function createEditorWorld(session, camera) {
10135
11636
  transformDragState: null,
10136
11637
  transformHelper,
10137
11638
  transformMode: 'translate',
10138
- transformSnap: {
10139
- rotationDeg: 15,
10140
- scale: 0.1,
10141
- translation: 0.25,
10142
- },
11639
+ transformSnap,
10143
11640
  transformSnapApplied: {
10144
11641
  rotationSnapDeg: null,
10145
11642
  scaleSnap: null,
@@ -10165,6 +11662,8 @@ async function createEditorWorld(session, camera) {
10165
11662
  : nodeId && node
10166
11663
  ? {
10167
11664
  nodeId,
11665
+ mode: editorWorldState.transformMode,
11666
+ scaleAxis: transformControls.axis,
10168
11667
  startTransform: cloneTransform(node.transform || {}),
10169
11668
  }
10170
11669
  : null;
@@ -10430,6 +11929,34 @@ function createViewportProof() {
10430
11929
  layout: createLayoutProof(),
10431
11930
  materialCount,
10432
11931
  meshCount,
11932
+ editorGrid: {
11933
+ cameraAnchored:
11934
+ editorWorldState.editorGrid.position.x ===
11935
+ editorWorldState.world.camera.position.x &&
11936
+ editorWorldState.editorGrid.position.z ===
11937
+ editorWorldState.world.camera.position.z,
11938
+ drawDistance: editorWorldState.drawDistance,
11939
+ fadeEnd: editorWorldState.drawDistance,
11940
+ fadeStart: editorWorldState.drawDistance * 0.5,
11941
+ followsCamera: true,
11942
+ geometry: editorWorldState.editorGrid.geometry.type,
11943
+ material: editorWorldState.editorGrid.material.type,
11944
+ minimumSpacing:
11945
+ editorWorldState.editorGrid.material.uniforms.minimumGridSpacing.value,
11946
+ planeSize: editorWorldState.drawDistance * 2,
11947
+ position: roundCameraVec3(editorWorldState.editorGrid.position),
11948
+ seamlessLod:
11949
+ editorWorldState.editorGrid.material.fragmentShader.includes(
11950
+ 'middleLine * mix(0.48, 0.22, levelBlend)',
11951
+ ) &&
11952
+ editorWorldState.editorGrid.material.fragmentShader.includes(
11953
+ 'coarseLine * levelBlend * 0.48',
11954
+ ),
11955
+ shaderFade:
11956
+ editorWorldState.editorGrid.material.fragmentShader.includes(
11957
+ 'smoothstep(drawDistance * 0.5, drawDistance, cameraDistance)',
11958
+ ),
11959
+ },
10433
11960
  nodeObjectCount: editorWorldState.objectMap.size,
10434
11961
  objectHierarchy: objectHierarchyProof(),
10435
11962
  orbitControls: Boolean(editorWorldState.orbitControls),
@@ -10450,10 +11977,12 @@ function createViewportProof() {
10450
11977
  : null,
10451
11978
  renderer: canvas.dataset.renderer || 'unknown',
10452
11979
  rendererCamera: {
11980
+ far: editorWorldState.world.camera.far,
10453
11981
  isOrthographicCamera:
10454
11982
  editorWorldState.world.camera.isOrthographicCamera === true,
10455
11983
  isPerspectiveCamera:
10456
11984
  editorWorldState.world.camera.isPerspectiveCamera === true,
11985
+ near: editorWorldState.world.camera.near,
10457
11986
  type: editorWorldState.world.camera.type,
10458
11987
  },
10459
11988
  renderStats: currentEditorRenderStats(),
@@ -13804,6 +15333,9 @@ function pickCanvasNode(session, camera, canvas, event) {
13804
15333
  true,
13805
15334
  );
13806
15335
  for (const intersection of intersections) {
15336
+ if (intersection.object.userData?.iwsdkEditorPickable === false) {
15337
+ continue;
15338
+ }
13807
15339
  let current = intersection.object;
13808
15340
  while (current) {
13809
15341
  const nodeId = current.userData?.iwsdkSceneNodeId;
@@ -13833,6 +15365,36 @@ function pickCanvasNode(session, camera, canvas, event) {
13833
15365
  return null;
13834
15366
  }
13835
15367
 
15368
+ function pickNodeAtObjectCenter(session, nodeId) {
15369
+ if (!editorWorldState) {
15370
+ return null;
15371
+ }
15372
+ const object = editorWorldState.objectMap.get(nodeId);
15373
+ if (!object) {
15374
+ return { builtinTarget: null, nodeId: null };
15375
+ }
15376
+ const bounds = boundsForObjectWithoutEditorHelpers(object);
15377
+ if (!bounds) {
15378
+ return { builtinTarget: null, nodeId: null };
15379
+ }
15380
+ const projected = new Vector3();
15381
+ bounds.getCenter(projected);
15382
+ projected.project(editorWorldState.world.camera);
15383
+ if (!Number.isFinite(projected.z) || projected.z < -1 || projected.z > 1) {
15384
+ return { builtinTarget: null, nodeId: null };
15385
+ }
15386
+ const canvas = getCanvas();
15387
+ const rect = canvas.getBoundingClientRect();
15388
+ const hit = pickCanvasNode(session, editorWorldState.currentCamera, canvas, {
15389
+ clientX: rect.left + ((projected.x + 1) / 2) * rect.width,
15390
+ clientY: rect.top + ((1 - projected.y) / 2) * rect.height,
15391
+ });
15392
+ return {
15393
+ builtinTarget: hit?.builtinTarget || null,
15394
+ nodeId: hit?.node?.id || null,
15395
+ };
15396
+ }
15397
+
13836
15398
  function renderCanvas(session, camera, size = {}) {
13837
15399
  if (!editorWorldState) {
13838
15400
  return;
@@ -13905,9 +15467,20 @@ function renderUi(session, camera) {
13905
15467
  soloNodeId: soloOutlinerNodeId,
13906
15468
  statusStrip: editorStatusStripText(session, nodes.length),
13907
15469
  transformMode: editorWorldState?.transformMode || 'translate',
15470
+ transformSnapRotationDeg:
15471
+ editorWorldState?.transformSnap?.rotationDeg ??
15472
+ DEFAULT_EDITOR_TRANSFORM_SNAP.rotationDeg,
15473
+ transformSnapScale:
15474
+ editorWorldState?.transformSnap?.scale ??
15475
+ DEFAULT_EDITOR_TRANSFORM_SNAP.scale,
15476
+ transformSnapTranslation:
15477
+ editorWorldState?.transformSnap?.translation ??
15478
+ DEFAULT_EDITOR_TRANSFORM_SNAP.translation,
13908
15479
  transformSnapEnabled:
13909
15480
  editorWorldState?.transformSnapEnabled === true,
13910
15481
  transformSpace: editorWorldState?.transformSpace || 'local',
15482
+ viewportDrawDistance:
15483
+ editorWorldState?.drawDistance ?? DEFAULT_EDITOR_DRAW_DISTANCE,
13911
15484
  view: window.__IWSDK_WORKSPACE_VIEW || 'runtime',
13912
15485
  });
13913
15486
 
@@ -14477,10 +16050,13 @@ async function init() {
14477
16050
  };
14478
16051
  },
14479
16052
  getCamera: () => activeCamera,
16053
+ getComponentHelperState: (nodeId) => componentHelperProof(nodeId),
14480
16054
  getObjectSummary: () => ({
14481
16055
  ids: editorWorldState ? [...editorWorldState.objectMap.keys()] : [],
14482
16056
  objectCount: editorWorldState?.objectMap.size ?? 0,
14483
16057
  }),
16058
+ pickNodeAtObjectCenter: (nodeId) =>
16059
+ pickNodeAtObjectCenter(session, nodeId),
14484
16060
  getPanelPreviewState: (nodeId) => {
14485
16061
  const object = editorWorldState?.objectMap.get(nodeId);
14486
16062
  const preview = object?.children.find(
@@ -14624,6 +16200,11 @@ async function init() {
14624
16200
  getRendererGlobals: () => rendererGlobalsProof(),
14625
16201
  getTransformControlObjectTransform: () =>
14626
16202
  objectTransformProof(editorWorldState?.transformControls?.object),
16203
+ getTransformControlAxisVisibility: () => ({
16204
+ x: editorWorldState?.transformControls?.showX ?? null,
16205
+ y: editorWorldState?.transformControls?.showY ?? null,
16206
+ z: editorWorldState?.transformControls?.showZ ?? null,
16207
+ }),
14627
16208
  findTransformControlPointerTarget: (axis = 'X') =>
14628
16209
  findTransformControlPointerTarget(axis),
14629
16210
  beginTransformControlDrag: (transform) => {
@@ -14672,6 +16253,7 @@ async function init() {
14672
16253
  return activeCamera;
14673
16254
  },
14674
16255
  setTransformMode: (mode) => setTransformMode(mode),
16256
+ setTransformSnap: (mode, value) => setTransformSnapValue(mode, value),
14675
16257
  setSurfacePlacementEnabled: (enabled) =>
14676
16258
  setSurfacePlacementEnabled(enabled),
14677
16259
  setTransformSnapEnabled: (enabled) => setTransformSnapEnabled(enabled),
@@ -14686,7 +16268,7 @@ async function init() {
14686
16268
  };
14687
16269
  },
14688
16270
  hasSharedAsset: (key) => editorWorldState?.world.assets.has(String(key)) === true,
14689
- simulateTransformControlCommit: async (transform) => {
16271
+ simulateTransformControlCommit: async (transform, scaleAxis = null) => {
14690
16272
  const nodeId = selectedNodeId();
14691
16273
  if (!nodeId || !editorWorldState?.transformControls?.object) {
14692
16274
  throw new Error('A selected node with attached transform controls is required');
@@ -14697,6 +16279,8 @@ async function init() {
14697
16279
  }
14698
16280
  editorWorldState.transformDragState = {
14699
16281
  nodeId,
16282
+ mode: editorWorldState.transformMode,
16283
+ scaleAxis,
14700
16284
  startTransform: cloneTransform(node.transform || {}),
14701
16285
  };
14702
16286
  applyNodeTransform(editorWorldState.transformControls.object, transform);
@@ -15021,16 +16605,19 @@ const EDITOR_SHELL_CSS = String.raw ` html,
15021
16605
  color: #ffffff;
15022
16606
  }
15023
16607
 
15024
- .workspace-view-switcher .workspace-reload-button {
16608
+ .workspace-view-switcher .workspace-icon-button {
15025
16609
  align-items: center;
15026
16610
  display: flex;
15027
16611
  justify-content: center;
15028
- margin-left: 2px;
15029
16612
  padding: 0;
15030
16613
  width: 24px;
15031
16614
  }
15032
16615
 
15033
- .workspace-view-switcher .workspace-reload-button .lucide-icon {
16616
+ .workspace-view-switcher .workspace-reload-button {
16617
+ margin-left: 2px;
16618
+ }
16619
+
16620
+ .workspace-view-switcher .workspace-icon-button .lucide-icon {
15034
16621
  height: 13px;
15035
16622
  stroke-width: 1.8;
15036
16623
  width: 13px;
@@ -15315,6 +16902,35 @@ const EDITOR_SHELL_CSS = String.raw ` html,
15315
16902
  padding-left: 0;
15316
16903
  }
15317
16904
 
16905
+ .transform-snap-control,
16906
+ .viewport-distance-control {
16907
+ align-items: center;
16908
+ display: flex;
16909
+ gap: 4px;
16910
+ white-space: nowrap;
16911
+ }
16912
+
16913
+ .transform-snap-control > span,
16914
+ .viewport-distance-control > span {
16915
+ color: #8d8d94;
16916
+ font-size: 10px;
16917
+ }
16918
+
16919
+ .transform-snap-control input,
16920
+ .viewport-distance-control input {
16921
+ height: 24px;
16922
+ min-height: 24px;
16923
+ text-align: right;
16924
+ }
16925
+
16926
+ .transform-snap-control input {
16927
+ width: 54px;
16928
+ }
16929
+
16930
+ .viewport-distance-control input {
16931
+ width: 68px;
16932
+ }
16933
+
15318
16934
  .editor-slot:empty {
15319
16935
  display: none !important;
15320
16936
  }
@@ -17786,6 +19402,9 @@ async function launchManagedBrowser(url, headless, verbose, viewport = null, scr
17786
19402
  : `🖥️ IWSDK: Using hardware GPU (${backend.useAngle})`);
17787
19403
  const browserArgs = [
17788
19404
  '--enable-webgl',
19405
+ // This dedicated browser only visits the local managed workspace. Keep
19406
+ // HTTPS enabled while accepting IWSDK's intentionally untrusted dev cert.
19407
+ '--ignore-certificate-errors',
17789
19408
  `--use-gl=${backend.useGl}`,
17790
19409
  `--use-angle=${backend.useAngle}`,
17791
19410
  '--disable-background-timer-throttling',
@@ -17971,72 +19590,6 @@ async function launchManagedBrowser(url, headless, verbose, viewport = null, scr
17971
19590
  };
17972
19591
  }
17973
19592
 
17974
- /**
17975
- * Copyright (c) Meta Platforms, Inc. and affiliates.
17976
- *
17977
- * This source code is licensed under the MIT license found in the
17978
- * LICENSE file in the root directory of this source tree.
17979
- */
17980
- /**
17981
- * MetaVR telemetry integration for IWSDK.
17982
- *
17983
- * Reports MCP tool calls, session lifecycle, and errors through MetaVR's
17984
- * DeveloperTelemetry pipeline via the `metavr xxiwsdk` subcommand.
17985
- * All calls are fire-and-forget — telemetry never blocks or breaks the tool.
17986
- *
17987
- * Executes MetaVR's JavaScript entrypoint with the current Node executable.
17988
- * This avoids platform shell shims and works the same way on Windows and Unix.
17989
- * If MetaVR is not installed in the workspace, telemetry is silently skipped.
17990
- */
17991
- function resolveMetaVrEntrypoint() {
17992
- try {
17993
- const requireFromWorkspace = createRequire(path__default.join(process.cwd(), 'package.json'));
17994
- return requireFromWorkspace.resolve('@meta-quest/metavr/bin.js');
17995
- }
17996
- catch {
17997
- return null;
17998
- }
17999
- }
18000
- function metaVrTelemetry(args, clientVersion) {
18001
- const entrypoint = resolveMetaVrEntrypoint();
18002
- if (entrypoint == null) {
18003
- return;
18004
- }
18005
- const globalArgs = ['xxiwsdk'];
18006
- if (clientVersion) {
18007
- globalArgs.push('--client-version', clientVersion);
18008
- }
18009
- const child = spawn(process.execPath, [entrypoint, ...globalArgs, ...args], {
18010
- stdio: 'ignore',
18011
- windowsHide: true,
18012
- });
18013
- child.on('error', () => { });
18014
- child.unref();
18015
- }
18016
- function reportSessionStart(sessionId, opts) {
18017
- const args = ['session-start', '--session-id', sessionId];
18018
- if (opts?.iwsdkVersion) {
18019
- args.push('--iwsdk-version', opts.iwsdkVersion);
18020
- }
18021
- if (opts?.device) {
18022
- args.push('--device', opts.device);
18023
- }
18024
- if (opts?.port) {
18025
- args.push('--port', String(opts.port));
18026
- }
18027
- metaVrTelemetry(args, opts?.clientVersion);
18028
- }
18029
- function reportSessionEnd(sessionId, opts) {
18030
- const args = ['session-end', '--session-id', sessionId];
18031
- if (opts?.durationMs != null) {
18032
- args.push('--duration-ms', String(Math.round(opts.durationMs)));
18033
- }
18034
- if (opts?.reason) {
18035
- args.push('--reason', opts.reason);
18036
- }
18037
- metaVrTelemetry(args, opts?.clientVersion);
18038
- }
18039
-
18040
19593
  /**
18041
19594
  * Copyright (c) Meta Platforms, Inc. and affiliates.
18042
19595
  *
@@ -18044,7 +19597,7 @@ function reportSessionEnd(sessionId, opts) {
18044
19597
  * LICENSE file in the root directory of this source tree.
18045
19598
  */
18046
19599
  // Get __dirname equivalent for ES modules
18047
- const __filename$1 = fileURLToPath(import.meta.url);
19600
+ const __filename$1 = fileURLToPath$1(import.meta.url);
18048
19601
  const __dirname$1 = path.dirname(__filename$1);
18049
19602
  /**
18050
19603
  * Load and customize the pre-built injection bundle
@@ -18406,6 +19959,72 @@ function isRelayPageTarget(value) {
18406
19959
  typeof target.sceneSessionId === 'string');
18407
19960
  }
18408
19961
 
19962
+ /**
19963
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
19964
+ *
19965
+ * This source code is licensed under the MIT license found in the
19966
+ * LICENSE file in the root directory of this source tree.
19967
+ */
19968
+ /**
19969
+ * MetaVR telemetry integration for IWSDK.
19970
+ *
19971
+ * Reports MCP tool calls, session lifecycle, and errors through MetaVR's
19972
+ * DeveloperTelemetry pipeline via the `metavr xxiwsdk` subcommand.
19973
+ * All calls are fire-and-forget — telemetry never blocks or breaks the tool.
19974
+ *
19975
+ * Executes MetaVR's JavaScript entrypoint with the current Node executable.
19976
+ * This avoids platform shell shims and works the same way on Windows and Unix.
19977
+ * If MetaVR is not installed in the workspace, telemetry is silently skipped.
19978
+ */
19979
+ function resolveMetaVrEntrypoint() {
19980
+ try {
19981
+ const requireFromWorkspace = createRequire(path__default.join(process.cwd(), 'package.json'));
19982
+ return requireFromWorkspace.resolve('@meta-quest/metavr/bin.js');
19983
+ }
19984
+ catch {
19985
+ return null;
19986
+ }
19987
+ }
19988
+ function metaVrTelemetry(args, clientVersion) {
19989
+ const entrypoint = resolveMetaVrEntrypoint();
19990
+ if (entrypoint == null) {
19991
+ return;
19992
+ }
19993
+ const globalArgs = ['xxiwsdk'];
19994
+ if (clientVersion) {
19995
+ globalArgs.push('--client-version', clientVersion);
19996
+ }
19997
+ const child = spawn(process.execPath, [entrypoint, ...globalArgs, ...args], {
19998
+ stdio: 'ignore',
19999
+ windowsHide: true,
20000
+ });
20001
+ child.on('error', () => { });
20002
+ child.unref();
20003
+ }
20004
+ function reportSessionStart(sessionId, opts) {
20005
+ const args = ['session-start', '--session-id', sessionId];
20006
+ if (opts?.iwsdkVersion) {
20007
+ args.push('--iwsdk-version', opts.iwsdkVersion);
20008
+ }
20009
+ if (opts?.device) {
20010
+ args.push('--device', opts.device);
20011
+ }
20012
+ if (opts?.port) {
20013
+ args.push('--port', String(opts.port));
20014
+ }
20015
+ metaVrTelemetry(args, opts?.clientVersion);
20016
+ }
20017
+ function reportSessionEnd(sessionId, opts) {
20018
+ const args = ['session-end', '--session-id', sessionId];
20019
+ if (opts?.durationMs != null) {
20020
+ args.push('--duration-ms', String(Math.round(opts.durationMs)));
20021
+ }
20022
+ if (opts?.reason) {
20023
+ args.push('--reason', opts.reason);
20024
+ }
20025
+ metaVrTelemetry(args, opts?.clientVersion);
20026
+ }
20027
+
18409
20028
  /**
18410
20029
  * Copyright (c) Meta Platforms, Inc. and affiliates.
18411
20030
  *
@@ -49025,6 +50644,16 @@ const RectAreaLightComponent = createComponent('RectAreaLight', {
49025
50644
  */
49026
50645
  function createSystem(queries = {}, schema = {}) {
49027
50646
  var _a;
50647
+ if (typeof queries === 'function') {
50648
+ throw new TypeError('createSystem() received a lifecycle function as its query map. ' +
50649
+ 'Pass only named query descriptors in createSystem({...}); define init(), update(), and destroy() in the subclass body.');
50650
+ }
50651
+ for (const [name, query] of Object.entries(queries)) {
50652
+ if (typeof query === 'function') {
50653
+ throw new TypeError(`createSystem() received lifecycle method "${name}" inside its query map. ` +
50654
+ `Move ${name}() into the subclass body; each createSystem() entry must be a query descriptor such as { required: [Component] }.`);
50655
+ }
50656
+ }
49028
50657
  return _a = class {
49029
50658
  constructor(world, queryManager, priority) {
49030
50659
  this.world = world;
@@ -49902,6 +51531,119 @@ async function unregisterRuntimeSession(workspaceRoot) {
49902
51531
  });
49903
51532
  }
49904
51533
 
51534
+ /**
51535
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
51536
+ *
51537
+ * This source code is licensed under the MIT license found in the
51538
+ * LICENSE file in the root directory of this source tree.
51539
+ */
51540
+ const BUNDLED_FONT_CHARACTERS = new Set(`${Array.from({ length: 95 }, (_, index) => String.fromCodePoint(0x20 + index)).join('')}°ÄÖÜäöüß§`);
51541
+ function formatParseError(error) {
51542
+ const position = error.range?.start;
51543
+ return `${error.message}${position ? ` at ${position.line}:${position.column}` : ''}`;
51544
+ }
51545
+ function describeElement(element) {
51546
+ if (!element) {
51547
+ return '<text>';
51548
+ }
51549
+ const id = typeof element.props.id === 'string' ? `#${element.props.id}` : '';
51550
+ return `<${element.tagName}${id}>`;
51551
+ }
51552
+ function collectUnsupportedGlyphs(node, glyphs, parent) {
51553
+ if (node.kind === 'text') {
51554
+ for (const character of node.value) {
51555
+ if (/\s/u.test(character) || BUNDLED_FONT_CHARACTERS.has(character)) {
51556
+ continue;
51557
+ }
51558
+ if (!glyphs.has(character)) {
51559
+ const position = node.meta.text?.start ?? node.meta.element.start;
51560
+ glyphs.set(character, `${describeElement(parent)} ${position.line + 1}:${position.column + 1}`);
51561
+ }
51562
+ }
51563
+ return;
51564
+ }
51565
+ if (node.kind === 'element') {
51566
+ for (const child of node.children) {
51567
+ collectUnsupportedGlyphs(child, glyphs, node);
51568
+ }
51569
+ }
51570
+ }
51571
+ function fontCoverageWarning(ast, filePath) {
51572
+ const glyphs = new Map();
51573
+ collectUnsupportedGlyphs(ast.root, glyphs);
51574
+ if (glyphs.size === 0) {
51575
+ return undefined;
51576
+ }
51577
+ const details = [...glyphs].map(([character, location]) => {
51578
+ const codePoint = character.codePointAt(0);
51579
+ return `${JSON.stringify(character)} (U+${codePoint
51580
+ .toString(16)
51581
+ .toUpperCase()
51582
+ .padStart(4, '0')}) at ${location}`;
51583
+ });
51584
+ const customFontNote = ast.fontFaces?.length
51585
+ ? ' A custom @font-face is declared; confirm that it is applied to these elements and contains these glyphs.'
51586
+ : ' Define and apply a custom @font-face containing these glyphs; UIKitML does not automatically fall back to a system font.';
51587
+ return `[IWSDK] UIKitML font coverage warning in ${filePath}: the bundled font atlas does not contain ${details.join(', ')}.${customFontNote}`;
51588
+ }
51589
+ function parseUIKitMLSource(source, filePath) {
51590
+ if (/^\s*(?:<!doctype\s+html\b|<html(?:\s|>))/i.test(source)) {
51591
+ throw new Error(`[IWSDK] Invalid UIKitML ${filePath}: file contains an HTML document instead of UIKitML.`);
51592
+ }
51593
+ const result = parse(source, {
51594
+ componentSets: resolveKitComponentSets('horizon'),
51595
+ });
51596
+ if (!result.success) {
51597
+ throw new Error(`[IWSDK] Invalid UIKitML ${filePath}:\n${result.errors
51598
+ .map(formatParseError)
51599
+ .join('\n')}`);
51600
+ }
51601
+ return result.ast;
51602
+ }
51603
+ async function collectUIKitMLFiles(directory) {
51604
+ let entries;
51605
+ try {
51606
+ entries = await readdir(directory, { withFileTypes: true });
51607
+ }
51608
+ catch (error) {
51609
+ if (error.code === 'ENOENT') {
51610
+ return [];
51611
+ }
51612
+ throw error;
51613
+ }
51614
+ const files = await Promise.all(entries.map(async (entry) => {
51615
+ const entryPath = path$1.join(directory, entry.name);
51616
+ if (entry.isDirectory()) {
51617
+ return collectUIKitMLFiles(entryPath);
51618
+ }
51619
+ return entry.isFile() && entry.name.endsWith('.uikitml')
51620
+ ? [entryPath]
51621
+ : [];
51622
+ }));
51623
+ return files.flat().sort();
51624
+ }
51625
+ async function validateUIKitMLDirectory(publicDirectory) {
51626
+ const files = await collectUIKitMLFiles(publicDirectory);
51627
+ const failures = [];
51628
+ const warnings = [];
51629
+ for (const file of files) {
51630
+ try {
51631
+ const ast = parseUIKitMLSource(await readFile$1(file, 'utf8'), file);
51632
+ const warning = fontCoverageWarning(ast, file);
51633
+ if (warning) {
51634
+ warnings.push(warning);
51635
+ }
51636
+ }
51637
+ catch (error) {
51638
+ failures.push(error instanceof Error ? error.message : String(error));
51639
+ }
51640
+ }
51641
+ if (failures.length > 0) {
51642
+ throw new Error(failures.join('\n\n'));
51643
+ }
51644
+ return { files, warnings };
51645
+ }
51646
+
49905
51647
  /**
49906
51648
  * Copyright (c) Meta Platforms, Inc. and affiliates.
49907
51649
  *
@@ -49935,6 +51677,7 @@ const WORKSPACE_REVIEWS_ROUTE = `${WORKSPACE_ROUTE}/reviews`;
49935
51677
  const WORKSPACE_REVIEW_CAPTURES_ROUTE = `${WORKSPACE_REVIEWS_ROUTE}/captures`;
49936
51678
  const WORKSPACE_REVIEW_TRANSITIONS_ROUTE = `${WORKSPACE_REVIEWS_ROUTE}/transitions`;
49937
51679
  const WORKSPACE_PUBLISH_ROUTE = `${WORKSPACE_ROUTE}/publish`;
51680
+ const WORKSPACE_OPEN_RUNTIME_ROUTE = `${WORKSPACE_ROUTE}/open-runtime`;
49938
51681
  const WORKSPACE_RUNTIME_PREFLIGHT_ROUTE = `${WORKSPACE_ROUTE}/runtime-preflight`;
49939
51682
  const OPTIMIZER_EXCLUSIONS = [
49940
51683
  '@zappar/msdf-generator',
@@ -49968,6 +51711,11 @@ const MAX_ISSUED_REVIEW_TRANSITIONS = 64;
49968
51711
  * Process and normalize plugin options with defaults
49969
51712
  */
49970
51713
  function processOptions(options = {}) {
51714
+ const bridgeReadyTimeoutMs = options.bridgeReadyTimeoutMs ?? 5000;
51715
+ if (!Number.isSafeInteger(bridgeReadyTimeoutMs) ||
51716
+ bridgeReadyTimeoutMs <= 0) {
51717
+ throw new Error('iwsdkDev().bridgeReadyTimeoutMs must be a positive integer');
51718
+ }
49971
51719
  const emulator = options.emulator ?? {};
49972
51720
  const processed = {
49973
51721
  ...(options.assetManifest == null
@@ -49982,6 +51730,7 @@ function processOptions(options = {}) {
49982
51730
  verbose: options.verbose || false,
49983
51731
  userAgentException: emulator.userAgentException || new RegExp('OculusBrowser'),
49984
51732
  iwer: emulator.iwer ?? true,
51733
+ bridgeReadyTimeoutMs,
49985
51734
  };
49986
51735
  // Process SEM options from emulator.environment
49987
51736
  if (emulator.environment) {
@@ -50127,6 +51876,9 @@ function projectManifestPluginOptions(options, manifest, projectRoot, command) {
50127
51876
  ...(workspace == null ? {} : { workspace }),
50128
51877
  ...(options.https == null ? {} : { https: options.https }),
50129
51878
  ...(options.verbose == null ? {} : { verbose: options.verbose }),
51879
+ ...(options.bridgeReadyTimeoutMs == null
51880
+ ? {}
51881
+ : { bridgeReadyTimeoutMs: options.bridgeReadyTimeoutMs }),
50130
51882
  };
50131
51883
  }
50132
51884
  function optionalAiMode(value) {
@@ -50237,12 +51989,18 @@ function iwsdkDev(options = {}) {
50237
51989
  options.https !== false &&
50238
51990
  userConfig.server?.https === undefined) {
50239
51991
  const httpsOptions = typeof options.https === 'object' ? options.https : {};
50240
- const configuredCacheDir = httpsOptions.certDir ??
50241
- path.join(userConfig.cacheDir ?? 'node_modules/.vite', 'iwsdk-https');
51992
+ const configuredCacheDir = httpsOptions.certDir ?? path.join('.iwsdk', 'https');
50242
51993
  const certDir = path.isAbsolute(configuredCacheDir)
50243
51994
  ? configuredCacheDir
50244
51995
  : path.resolve(projectRoot, configuredCacheDir);
50245
51996
  const certificate = await getCertificate(certDir, httpsOptions.name ?? 'IWSDK Development', httpsOptions.domains, httpsOptions.ttlDays ?? 365);
51997
+ // @vitejs/plugin-basic-ssl writes its cache asynchronously after
51998
+ // returning. Complete the write before Vite starts so a rapid restart
51999
+ // cannot generate a second certificate for the same project.
52000
+ mkdirSync(certDir, { recursive: true });
52001
+ writeFileSync(path.join(certDir, '_cert.pem'), certificate, {
52002
+ mode: 0o600,
52003
+ });
50246
52004
  userConfig.server ?? (userConfig.server = {});
50247
52005
  userConfig.server.https = {
50248
52006
  cert: certificate,
@@ -50400,6 +52158,14 @@ function iwsdkDev(options = {}) {
50400
52158
  handleScenePublishRequest(request, response, config.root, managedBrowser);
50401
52159
  return;
50402
52160
  }
52161
+ if (pathname === WORKSPACE_OPEN_RUNTIME_ROUTE) {
52162
+ if (!isManagedWorkspaceRequest) {
52163
+ sendJsonError(response, 403, 'Opening the runtime in the default browser is only available from the managed workspace browser.');
52164
+ return;
52165
+ }
52166
+ handleOpenRuntimeRequest(request, response, server);
52167
+ return;
52168
+ }
50403
52169
  if (pathname === WORKSPACE_RUNTIME_PREFLIGHT_ROUTE) {
50404
52170
  if (!isManagedWorkspaceRequest) {
50405
52171
  sendJsonError(response, 403, 'IWSDK runtime preflight is only available in the managed workspace browser.');
@@ -50440,7 +52206,7 @@ function iwsdkDev(options = {}) {
50440
52206
  let consecutiveFailures = 0;
50441
52207
  let currentBrowserState = null;
50442
52208
  const MAX_LAUNCH_FAILURES = 3;
50443
- const BRIDGE_READY_TIMEOUT_MS = 5000;
52209
+ const BRIDGE_READY_TIMEOUT_MS = pluginOptions.bridgeReadyTimeoutMs;
50444
52210
  const traceEnabled = process.env.IWSDK_RUNTIME_TRACE === '1';
50445
52211
  const wsConnectionIds = new WeakMap();
50446
52212
  const wsConnectionKinds = new WeakMap();
@@ -51309,6 +53075,15 @@ function iwsdkDev(options = {}) {
51309
53075
  if (loadedProject != null) {
51310
53076
  this.addWatchFile(loadedProject.configPath);
51311
53077
  }
53078
+ if (config.command === 'build') {
53079
+ const validation = await validateUIKitMLDirectory(config.publicDir || path.resolve(config.root, 'public'));
53080
+ for (const file of validation.files) {
53081
+ this.addWatchFile(file);
53082
+ }
53083
+ for (const warning of validation.warnings) {
53084
+ this.warn(warning);
53085
+ }
53086
+ }
51312
53087
  // Development always builds the managed-workspace bridge, even when
51313
53088
  // IWER is disabled. Production builds include only explicitly enabled
51314
53089
  // IWER emulation; the editor bridge is never a production side effect.
@@ -51499,6 +53274,28 @@ function sendJsonError(response, statusCode, message, extra = {}) {
51499
53274
  response.setHeader('Content-Type', 'application/json; charset=utf-8');
51500
53275
  response.end(JSON.stringify({ error: message, ...extra }));
51501
53276
  }
53277
+ async function handleOpenRuntimeRequest(request, response, server) {
53278
+ if (request.method !== 'POST') {
53279
+ response.statusCode = 405;
53280
+ response.setHeader('Allow', 'POST');
53281
+ response.end('Method not allowed');
53282
+ return;
53283
+ }
53284
+ const localUrl = server.resolvedUrls?.local?.[0];
53285
+ if (localUrl == null) {
53286
+ sendJsonError(response, 503, 'The local runtime URL is not available yet.');
53287
+ return;
53288
+ }
53289
+ try {
53290
+ await open(new URL('/', localUrl).toString(), { wait: false });
53291
+ response.statusCode = 204;
53292
+ response.end();
53293
+ }
53294
+ catch (error) {
53295
+ console.error('[IWSDK] Failed to open the default browser:', error);
53296
+ sendJsonError(response, 500, 'Failed to open the default browser.');
53297
+ }
53298
+ }
51502
53299
  function normalizePageRole(role) {
51503
53300
  return role === 'editor' || role === 'preview' ? role : 'app';
51504
53301
  }