@webspatial/core-sdk 1.6.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (320) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +10 -0
  3. package/dist/JSBCommand.d.ts +398 -0
  4. package/dist/JSBCommand.js +668 -0
  5. package/dist/JSBCommand.js.map +1 -0
  6. package/dist/Spatial.d.ts +63 -0
  7. package/dist/Spatial.js +60 -0
  8. package/dist/Spatial.js.map +1 -0
  9. package/dist/SpatialObject.d.ts +19 -0
  10. package/dist/SpatialObject.js +44 -0
  11. package/dist/SpatialObject.js.map +1 -0
  12. package/dist/SpatialScene.d.ts +51 -0
  13. package/dist/SpatialScene.js +74 -0
  14. package/dist/SpatialScene.js.map +1 -0
  15. package/dist/SpatialSession.d.ts +143 -0
  16. package/dist/SpatialSession.js +173 -0
  17. package/dist/SpatialSession.js.map +1 -0
  18. package/dist/SpatialWebEvent.d.ts +8 -0
  19. package/dist/SpatialWebEvent.js +18 -0
  20. package/dist/SpatialWebEvent.js.map +1 -0
  21. package/dist/SpatialWebEventCreator.d.ts +11 -0
  22. package/dist/SpatialWebEventCreator.js +11 -0
  23. package/dist/SpatialWebEventCreator.js.map +1 -0
  24. package/dist/Spatialized2DElement.d.ts +42 -0
  25. package/dist/Spatialized2DElement.js +47 -0
  26. package/dist/Spatialized2DElement.js.map +1 -0
  27. package/dist/SpatializedDynamic3DElement.d.ts +7 -0
  28. package/dist/SpatializedDynamic3DElement.js +43 -0
  29. package/dist/SpatializedDynamic3DElement.js.map +1 -0
  30. package/dist/SpatializedElement.d.ts +7 -0
  31. package/dist/SpatializedElement.js +206 -0
  32. package/dist/SpatializedElement.js.map +1 -0
  33. package/dist/SpatializedElementCreator.d.ts +15 -0
  34. package/dist/SpatializedElementCreator.js +47 -0
  35. package/dist/SpatializedElementCreator.js.map +1 -0
  36. package/dist/SpatializedStatic3DElement.d.ts +195 -0
  37. package/dist/SpatializedStatic3DElement.js +327 -0
  38. package/dist/SpatializedStatic3DElement.js.map +1 -0
  39. package/dist/WebMsgCommand.d.ts +7 -0
  40. package/dist/WebMsgCommand.js +23 -0
  41. package/dist/WebMsgCommand.js.map +1 -0
  42. package/dist/index.d.ts +35 -1101
  43. package/dist/index.js +21 -3393
  44. package/dist/index.js.map +1 -1
  45. package/dist/install-polyfills.d.ts +2 -0
  46. package/dist/install-polyfills.js +13 -0
  47. package/dist/install-polyfills.js.map +1 -0
  48. package/dist/isSSREnv.d.ts +3 -0
  49. package/dist/isSSREnv.js +6 -0
  50. package/dist/isSSREnv.js.map +1 -0
  51. package/dist/motion/AnimationObject.d.ts +7 -0
  52. package/dist/motion/AnimationObject.js +140 -0
  53. package/dist/motion/AnimationObject.js.map +1 -0
  54. package/dist/motion/compute/index.d.ts +10 -0
  55. package/dist/motion/compute/index.js +19 -0
  56. package/dist/motion/compute/index.js.map +1 -0
  57. package/dist/motion/compute/motionPropertyValues.d.ts +19 -0
  58. package/dist/motion/compute/motionPropertyValues.js +50 -0
  59. package/dist/motion/compute/motionPropertyValues.js.map +1 -0
  60. package/dist/motion/compute/normalize.d.ts +31 -0
  61. package/dist/motion/compute/normalize.js +201 -0
  62. package/dist/motion/compute/normalize.js.map +1 -0
  63. package/dist/motion/compute/validate.d.ts +22 -0
  64. package/dist/motion/compute/validate.js +103 -0
  65. package/dist/motion/compute/validate.js.map +1 -0
  66. package/dist/motion/index.d.ts +8 -0
  67. package/dist/motion/index.js +6 -0
  68. package/dist/motion/index.js.map +1 -0
  69. package/dist/motion/native/serializeMotionTimeline.d.ts +12 -0
  70. package/dist/motion/native/serializeMotionTimeline.js +21 -0
  71. package/dist/motion/native/serializeMotionTimeline.js.map +1 -0
  72. package/dist/physicalMetrics-W5uZ5xKb.d.ts +48 -0
  73. package/dist/physicalMetrics.d.ts +1 -0
  74. package/dist/physicalMetrics.js +58 -0
  75. package/dist/physicalMetrics.js.map +1 -0
  76. package/dist/platform-adapter/CommandResultUtils.d.ts +12 -0
  77. package/dist/platform-adapter/CommandResultUtils.js +21 -0
  78. package/dist/platform-adapter/CommandResultUtils.js.map +1 -0
  79. package/dist/platform-adapter/createPlatformSync.d.ts +16 -0
  80. package/dist/platform-adapter/createPlatformSync.js +30 -0
  81. package/dist/platform-adapter/createPlatformSync.js.map +1 -0
  82. package/dist/platform-adapter/index.d.ts +12 -0
  83. package/dist/platform-adapter/index.js +10 -0
  84. package/dist/platform-adapter/index.js.map +1 -0
  85. package/dist/platform-adapter/interface.d.ts +7 -0
  86. package/dist/platform-adapter/interface.js +1 -0
  87. package/dist/platform-adapter/interface.js.map +1 -0
  88. package/dist/platform-adapter/pico-os/PicoOSPlatform.d.ts +25 -0
  89. package/dist/platform-adapter/pico-os/PicoOSPlatform.js +168 -0
  90. package/dist/platform-adapter/pico-os/PicoOSPlatform.js.map +1 -0
  91. package/dist/platform-adapter/puppeteer/PuppeteerPlatform.d.ts +66 -0
  92. package/dist/platform-adapter/puppeteer/PuppeteerPlatform.js +372 -0
  93. package/dist/platform-adapter/puppeteer/PuppeteerPlatform.js.map +1 -0
  94. package/dist/platform-adapter/spatialRequestMetadata.d.ts +6 -0
  95. package/dist/platform-adapter/spatialRequestMetadata.js +39 -0
  96. package/dist/platform-adapter/spatialRequestMetadata.js.map +1 -0
  97. package/dist/platform-adapter/spatialSceneQuery.d.ts +12 -0
  98. package/dist/platform-adapter/spatialSceneQuery.js +12 -0
  99. package/dist/platform-adapter/spatialSceneQuery.js.map +1 -0
  100. package/dist/platform-adapter/vision-os/VisionOSPlatform.d.ts +19 -0
  101. package/dist/platform-adapter/vision-os/VisionOSPlatform.js +77 -0
  102. package/dist/platform-adapter/vision-os/VisionOSPlatform.js.map +1 -0
  103. package/dist/platform-runtime.d.ts +12 -0
  104. package/dist/platform-runtime.js +14 -0
  105. package/dist/platform-runtime.js.map +1 -0
  106. package/dist/reality/Attachment.d.ts +19 -0
  107. package/dist/reality/Attachment.js +39 -0
  108. package/dist/reality/Attachment.js.map +1 -0
  109. package/dist/reality/component/ModelComponent.d.ts +14 -0
  110. package/dist/reality/component/ModelComponent.js +11 -0
  111. package/dist/reality/component/ModelComponent.js.map +1 -0
  112. package/dist/reality/component/SpatialComponent.d.ts +8 -0
  113. package/dist/reality/component/SpatialComponent.js +19 -0
  114. package/dist/reality/component/SpatialComponent.js.map +1 -0
  115. package/dist/reality/component/index.d.ts +8 -0
  116. package/dist/reality/component/index.js +3 -0
  117. package/dist/reality/component/index.js.map +1 -0
  118. package/dist/reality/entity/SpatialEntity.d.ts +7 -0
  119. package/dist/reality/entity/SpatialEntity.js +291 -0
  120. package/dist/reality/entity/SpatialEntity.js.map +1 -0
  121. package/dist/reality/entity/SpatialModelEntity.d.ts +17 -0
  122. package/dist/reality/entity/SpatialModelEntity.js +17 -0
  123. package/dist/reality/entity/SpatialModelEntity.js.map +1 -0
  124. package/dist/reality/entity/index.d.ts +8 -0
  125. package/dist/reality/entity/index.js +3 -0
  126. package/dist/reality/entity/index.js.map +1 -0
  127. package/dist/reality/geometry/SpatialBoxGeometry.d.ts +16 -0
  128. package/dist/reality/geometry/SpatialBoxGeometry.js +13 -0
  129. package/dist/reality/geometry/SpatialBoxGeometry.js.map +1 -0
  130. package/dist/reality/geometry/SpatialConeGeometry.d.ts +16 -0
  131. package/dist/reality/geometry/SpatialConeGeometry.js +13 -0
  132. package/dist/reality/geometry/SpatialConeGeometry.js.map +1 -0
  133. package/dist/reality/geometry/SpatialCylinderGeometry.d.ts +16 -0
  134. package/dist/reality/geometry/SpatialCylinderGeometry.js +13 -0
  135. package/dist/reality/geometry/SpatialCylinderGeometry.js.map +1 -0
  136. package/dist/reality/geometry/SpatialGeometry.d.ts +7 -0
  137. package/dist/reality/geometry/SpatialGeometry.js +13 -0
  138. package/dist/reality/geometry/SpatialGeometry.js.map +1 -0
  139. package/dist/reality/geometry/SpatialPlaneGeometry.d.ts +16 -0
  140. package/dist/reality/geometry/SpatialPlaneGeometry.js +13 -0
  141. package/dist/reality/geometry/SpatialPlaneGeometry.js.map +1 -0
  142. package/dist/reality/geometry/SpatialSphereGeometry.d.ts +16 -0
  143. package/dist/reality/geometry/SpatialSphereGeometry.js +13 -0
  144. package/dist/reality/geometry/SpatialSphereGeometry.js.map +1 -0
  145. package/dist/reality/geometry/index.d.ts +12 -0
  146. package/dist/reality/geometry/index.js +7 -0
  147. package/dist/reality/geometry/index.js.map +1 -0
  148. package/dist/reality/index.d.ts +18 -0
  149. package/dist/reality/index.js +7 -0
  150. package/dist/reality/index.js.map +1 -0
  151. package/dist/reality/material/SpatialMaterial.d.ts +7 -0
  152. package/dist/reality/material/SpatialMaterial.js +13 -0
  153. package/dist/reality/material/SpatialMaterial.js.map +1 -0
  154. package/dist/reality/material/SpatialUnlitMaterial.d.ts +16 -0
  155. package/dist/reality/material/SpatialUnlitMaterial.js +16 -0
  156. package/dist/reality/material/SpatialUnlitMaterial.js.map +1 -0
  157. package/dist/reality/material/index.d.ts +8 -0
  158. package/dist/reality/material/index.js +3 -0
  159. package/dist/reality/material/index.js.map +1 -0
  160. package/dist/reality/realityCreator.d.ts +22 -0
  161. package/dist/reality/realityCreator.js +89 -0
  162. package/dist/reality/realityCreator.js.map +1 -0
  163. package/dist/reality/resource/SpatialModelAsset.d.ts +15 -0
  164. package/dist/reality/resource/SpatialModelAsset.js +12 -0
  165. package/dist/reality/resource/SpatialModelAsset.js.map +1 -0
  166. package/dist/reality/resource/SpatialTextureResource.d.ts +16 -0
  167. package/dist/reality/resource/SpatialTextureResource.js +16 -0
  168. package/dist/reality/resource/SpatialTextureResource.js.map +1 -0
  169. package/dist/reality/resource/index.d.ts +9 -0
  170. package/dist/reality/resource/index.js +3 -0
  171. package/dist/reality/resource/index.js.map +1 -0
  172. package/dist/runtime/WebSpatialRuntimeError.d.ts +10 -0
  173. package/dist/runtime/WebSpatialRuntimeError.js +14 -0
  174. package/dist/runtime/WebSpatialRuntimeError.js.map +1 -0
  175. package/dist/runtime/capability-data.d.ts +12 -0
  176. package/dist/runtime/capability-data.js +134 -0
  177. package/dist/runtime/capability-data.js.map +1 -0
  178. package/dist/runtime/index.d.ts +8 -0
  179. package/dist/runtime/index.js +27 -0
  180. package/dist/runtime/index.js.map +1 -0
  181. package/dist/runtime/jsbAdapterPlatform.d.ts +9 -0
  182. package/dist/runtime/jsbAdapterPlatform.js +38 -0
  183. package/dist/runtime/jsbAdapterPlatform.js.map +1 -0
  184. package/dist/runtime/keys.d.ts +34 -0
  185. package/dist/runtime/keys.js +122 -0
  186. package/dist/runtime/keys.js.map +1 -0
  187. package/dist/runtime/semver.d.ts +8 -0
  188. package/dist/runtime/semver.js +32 -0
  189. package/dist/runtime/semver.js.map +1 -0
  190. package/dist/runtime/supports.d.ts +22 -0
  191. package/dist/runtime/supports.js +78 -0
  192. package/dist/runtime/supports.js.map +1 -0
  193. package/dist/runtime/types.d.ts +12 -0
  194. package/dist/runtime/types.js +1 -0
  195. package/dist/runtime/types.js.map +1 -0
  196. package/dist/runtime/userAgent.d.ts +20 -0
  197. package/dist/runtime/userAgent.js +41 -0
  198. package/dist/runtime/userAgent.js.map +1 -0
  199. package/dist/scene-polyfill.d.ts +18 -0
  200. package/dist/scene-polyfill.js +480 -0
  201. package/dist/scene-polyfill.js.map +1 -0
  202. package/dist/spatial-host.d.ts +13 -0
  203. package/dist/spatial-host.js +18 -0
  204. package/dist/spatial-host.js.map +1 -0
  205. package/dist/spatial-window-polyfill.d.ts +3 -0
  206. package/dist/spatial-window-polyfill.js +155 -0
  207. package/dist/spatial-window-polyfill.js.map +1 -0
  208. package/dist/spatializedElementMotion-_0XWPQCE.d.ts +1009 -0
  209. package/dist/types/animation.d.ts +7 -0
  210. package/dist/types/animation.js +1 -0
  211. package/dist/types/animation.js.map +1 -0
  212. package/dist/types/global.d.ts +38 -0
  213. package/dist/types/global.js +1 -0
  214. package/dist/types/global.js.map +1 -0
  215. package/dist/types/internal.d.ts +7 -0
  216. package/dist/types/internal.js +12 -0
  217. package/dist/types/internal.js.map +1 -0
  218. package/dist/types/motion/index.d.ts +7 -0
  219. package/dist/types/motion/index.js +3 -0
  220. package/dist/types/motion/index.js.map +1 -0
  221. package/dist/types/motion/spatializedElementMotion.d.ts +7 -0
  222. package/dist/types/motion/spatializedElementMotion.js +1 -0
  223. package/dist/types/motion/spatializedElementMotion.js.map +1 -0
  224. package/dist/types/motion/spatializedMotion.d.ts +7 -0
  225. package/dist/types/motion/spatializedMotion.js +16 -0
  226. package/dist/types/motion/spatializedMotion.js.map +1 -0
  227. package/dist/types/motion/spatializedPlayback.d.ts +11 -0
  228. package/dist/types/motion/spatializedPlayback.js +1 -0
  229. package/dist/types/motion/spatializedPlayback.js.map +1 -0
  230. package/dist/types/motion/spatializedVisual.d.ts +35 -0
  231. package/dist/types/motion/spatializedVisual.js +1 -0
  232. package/dist/types/motion/spatializedVisual.js.map +1 -0
  233. package/dist/types/types.d.ts +7 -0
  234. package/dist/types/types.js +117 -0
  235. package/dist/types/types.js.map +1 -0
  236. package/dist/utils.d.ts +44 -0
  237. package/dist/utils.js +86 -0
  238. package/dist/utils.js.map +1 -0
  239. package/package.json +20 -4
  240. package/src/JSBCommand.ts +148 -91
  241. package/src/Spatial.ts +0 -21
  242. package/src/SpatialObject.ts +10 -0
  243. package/src/SpatialScene.ts +1 -5
  244. package/src/SpatialSession.ts +17 -3
  245. package/src/Spatialized2DElement.ts +5 -0
  246. package/src/SpatializedDynamic3DElement.ts +5 -1
  247. package/src/SpatializedElement.ts +29 -0
  248. package/src/SpatializedElementCreator.ts +6 -4
  249. package/src/SpatializedStatic3DElement.test.ts +99 -0
  250. package/src/SpatializedStatic3DElement.ts +141 -4
  251. package/src/WebMsgCommand.ts +50 -0
  252. package/src/coverage-boost.test.ts +258 -316
  253. package/src/index.ts +28 -12
  254. package/src/install-polyfills.ts +38 -0
  255. package/src/jsbcommand.coverage.test.ts +42 -48
  256. package/src/motion/AnimationObject.test.ts +421 -0
  257. package/src/motion/AnimationObject.ts +208 -0
  258. package/src/motion/compute/index.ts +10 -0
  259. package/src/motion/compute/motionPropertyValues.test.ts +55 -0
  260. package/src/motion/compute/motionPropertyValues.ts +70 -0
  261. package/src/motion/compute/normalize.test.ts +99 -0
  262. package/src/motion/compute/normalize.ts +289 -0
  263. package/src/motion/compute/validate.test.ts +229 -0
  264. package/src/motion/compute/validate.ts +156 -0
  265. package/src/motion/index.ts +2 -0
  266. package/src/motion/native/serializeMotionTimeline.test.ts +61 -0
  267. package/src/motion/native/serializeMotionTimeline.ts +27 -0
  268. package/src/platform-adapter/CommandResultUtils.ts +2 -2
  269. package/src/platform-adapter/createPlatformSync.ts +36 -0
  270. package/src/platform-adapter/index.ts +5 -51
  271. package/src/platform-adapter/interface.ts +35 -23
  272. package/src/platform-adapter/pico-os/PicoOSPlatform.ts +156 -59
  273. package/src/platform-adapter/puppeteer/PuppeteerPlatform.ts +37 -11
  274. package/src/platform-adapter/spatialRequestMetadata.test.ts +175 -0
  275. package/src/platform-adapter/spatialRequestMetadata.ts +48 -0
  276. package/src/platform-adapter/spatialSceneQuery.ts +17 -0
  277. package/src/platform-adapter/vision-os/VisionOSPlatform.ts +60 -24
  278. package/src/platform-runtime.ts +13 -0
  279. package/src/reality/Attachment.ts +2 -2
  280. package/src/reality/entity/SpatialEntity.ts +127 -2
  281. package/src/reality/realityCreator.ts +15 -1
  282. package/src/reality/resource/SpatialTextureResource.ts +16 -0
  283. package/src/reality/resource/index.ts +1 -0
  284. package/src/runtime/WebSpatialRuntimeError.ts +16 -0
  285. package/src/runtime/capability-data.ts +213 -0
  286. package/src/runtime/contract-review.test.ts +44 -0
  287. package/src/runtime/index.ts +17 -0
  288. package/src/runtime/jsbAdapterPlatform.test.ts +36 -0
  289. package/src/runtime/jsbAdapterPlatform.ts +51 -0
  290. package/src/runtime/keys.ts +140 -0
  291. package/src/runtime/semver.ts +33 -0
  292. package/src/runtime/supports.test.ts +346 -0
  293. package/src/runtime/supports.ts +112 -0
  294. package/src/runtime/types.ts +11 -0
  295. package/src/runtime/useAnimation.capability.test.ts +275 -0
  296. package/src/runtime/userAgent.ts +64 -0
  297. package/src/scene-polyfill.manifest.test.ts +312 -9
  298. package/src/scene-polyfill.request-metadata.test.ts +39 -0
  299. package/src/scene-polyfill.test.ts +33 -94
  300. package/src/scene-polyfill.ts +125 -92
  301. package/src/spatial-host.ts +25 -0
  302. package/src/spatial-window-polyfill.ts +18 -2
  303. package/src/transform-roundtrip.test.ts +90 -0
  304. package/src/types/animation.ts +224 -0
  305. package/src/types/{global.d.ts → global.ts} +10 -12
  306. package/src/types/motion/index.ts +10 -0
  307. package/src/types/motion/spatializedElementMotion.ts +49 -0
  308. package/src/types/motion/spatializedMotion.ts +147 -0
  309. package/src/types/motion/spatializedPlayback.ts +17 -0
  310. package/src/types/motion/spatializedVisual.ts +24 -0
  311. package/src/types/types.ts +12 -0
  312. package/src/utils.ts +54 -0
  313. package/tsup.config.ts +61 -36
  314. package/vitest.config.ts +5 -1
  315. package/dist/iife/index.d.ts +0 -1101
  316. package/dist/iife/index.global.js +0 -75
  317. package/dist/iife/index.global.js.map +0 -1
  318. package/src/platform-adapter/android/AndroidPlatform.ts +0 -133
  319. package/src/platform-adapter/ssr/SSRPlatform.ts +0 -43
  320. /package/src/{ssr-polyfill.ts → isSSREnv.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,3405 +1,33 @@
1
-
2
- (function(){
3
- if(typeof window === 'undefined') return;
4
- if(!window.__webspatialsdk__) window.__webspatialsdk__ = {}
5
- window.__webspatialsdk__['core-sdk-version'] = "1.6.1"
6
- })()
7
-
8
- var __defProp = Object.defineProperty;
9
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
- var __getOwnPropNames = Object.getOwnPropertyNames;
11
- var __hasOwnProp = Object.prototype.hasOwnProperty;
12
- var __esm = (fn, res) => function __init() {
13
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
- };
15
- var __export = (target, all) => {
16
- for (var name in all)
17
- __defProp(target, name, { get: all[name], enumerable: true });
18
- };
19
- var __copyProps = (to, from, except, desc) => {
20
- if (from && typeof from === "object" || typeof from === "function") {
21
- for (let key of __getOwnPropNames(from))
22
- if (!__hasOwnProp.call(to, key) && key !== except)
23
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
- }
25
- return to;
26
- };
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/ssr-polyfill.ts
30
- var isSSR, isSSREnv;
31
- var init_ssr_polyfill = __esm({
32
- "src/ssr-polyfill.ts"() {
33
- "use strict";
34
- isSSR = typeof window === "undefined";
35
- isSSREnv = () => isSSR;
36
- }
37
- });
38
-
39
- // src/platform-adapter/ssr/SSRPlatform.ts
40
- var SSRPlatform;
41
- var init_SSRPlatform = __esm({
42
- "src/platform-adapter/ssr/SSRPlatform.ts"() {
43
- "use strict";
44
- SSRPlatform = class {
45
- callJSB(cmd, msg) {
46
- return Promise.resolve({
47
- success: true,
48
- data: void 0,
49
- errorCode: void 0,
50
- errorMessage: void 0
51
- });
52
- }
53
- callWebSpatialProtocol(schema, query, target, features) {
54
- return Promise.resolve({
55
- success: true,
56
- data: void 0,
57
- errorCode: void 0,
58
- errorMessage: void 0
59
- });
60
- }
61
- callWebSpatialProtocolSync(schema, query, target, features, resultCallback) {
62
- return {
63
- success: true,
64
- data: void 0,
65
- errorCode: void 0,
66
- errorMessage: void 0
67
- };
68
- }
69
- };
70
- }
71
- });
72
-
73
- // src/platform-adapter/CommandResultUtils.ts
74
- function CommandResultSuccess(data) {
75
- return {
76
- success: true,
77
- data,
78
- errorCode: "",
79
- errorMessage: ""
80
- };
81
- }
82
- function CommandResultFailure(errorCode, errorMessage = "") {
83
- return {
84
- success: false,
85
- data: void 0,
86
- errorCode,
87
- errorMessage
88
- };
89
- }
90
- var init_CommandResultUtils = __esm({
91
- "src/platform-adapter/CommandResultUtils.ts"() {
92
- "use strict";
93
- }
94
- });
95
-
96
- // src/platform-adapter/puppeteer/PuppeteerPlatform.ts
97
- var PuppeteerPlatform_exports = {};
98
- __export(PuppeteerPlatform_exports, {
99
- PuppeteerPlatform: () => PuppeteerPlatform
100
- });
101
- var PuppeteerPlatform;
102
- var init_PuppeteerPlatform = __esm({
103
- "src/platform-adapter/puppeteer/PuppeteerPlatform.ts"() {
104
- "use strict";
105
- init_CommandResultUtils();
106
- console.log("PuppeteerPlatform");
107
- PuppeteerPlatform = class {
108
- // store iframe instance
109
- iframeRegistry = /* @__PURE__ */ new Map();
110
- constructor() {
111
- }
112
- callJSB(cmd, msg) {
113
- return new Promise((resolve) => {
114
- try {
115
- if (window.__handleJSBMessage) {
116
- try {
117
- console.log(` core-sdk Puppeteer Platform: callJSB: ${cmd}::${msg}`);
118
- const result = window.__handleJSBMessage(`${cmd}::${msg}`);
119
- console.log(
120
- ` core-sdk Puppeteer Platform callJSB result: ${result}`
121
- );
122
- resolve(CommandResultSuccess(result));
123
- } catch (err) {
124
- resolve(CommandResultFailure("500", "JSB execution error"));
125
- }
126
- } else {
127
- resolve(CommandResultSuccess("ok"));
128
- }
129
- } catch (error) {
130
- console.error(
131
- `PuppeteerPlatform cmd Error: ${cmd}, msg: ${msg} error: ${error}`
132
- );
133
- resolve(CommandResultFailure("500", "Internal error"));
134
- }
135
- });
136
- }
137
- /**
138
- * Synchronously create Spatialized2DElement to Puppeteer Runner
139
- */
140
- createSpatializedElementSync(spatialId, webspatialUrl) {
141
- try {
142
- console.log(
143
- `[Puppeteer Platform] Creating spatialized element sync with id: ${spatialId}, url: ${webspatialUrl}`
144
- );
145
- const win = window;
146
- if (win.__handleJSBMessage) {
147
- const createCommand = {
148
- id: spatialId,
149
- url: webspatialUrl
150
- };
151
- win.__handleJSBMessage(
152
- `CreateSpatialized2DElement::${JSON.stringify(createCommand)}`
153
- );
154
- }
155
- } catch (error) {
156
- console.error("Error creating spatialized element sync:", error);
157
- }
158
- }
159
- callWebSpatialProtocol(command, query, target, features) {
160
- console.log(
161
- `PuppeteerPlatform: Calling webspatial protocol: webspatial://${command}${query ? `?${query}` : ""}`
162
- );
163
- return new Promise((resolve) => {
164
- try {
165
- const webspatialUrl = `webspatial://${command}${query ? `?${query}` : ""}`;
166
- const { spatialId, iframe, windowProxy } = this.createIframeWindow(
167
- webspatialUrl,
168
- target,
169
- features
170
- );
171
- if (command === "createSpatialized2DElement") {
172
- this.createSpatializedElementSync(spatialId, webspatialUrl);
173
- }
174
- console.log(
175
- `[Puppeteer Platform] iframe created with spatialId: ${spatialId}`
176
- );
177
- this.iframeRegistry.set(spatialId, iframe);
178
- resolve(CommandResultSuccess({ windowProxy, id: spatialId }));
179
- } catch (error) {
180
- console.error("Error calling webspatial protocol:", error);
181
- resolve(
182
- CommandResultFailure("500", "Failed to call webspatial protocol")
183
- );
184
- }
185
- });
186
- }
187
- callWebSpatialProtocolSync(command, query, target, features) {
188
- try {
189
- const webspatialUrl = `webspatial://${command}${query ? `?${query}` : ""}`;
190
- console.log(`Calling webspatial protocol sync: ${webspatialUrl}`);
191
- const { spatialId, iframe, windowProxy } = this.createIframeWindow(
192
- webspatialUrl,
193
- target,
194
- features
195
- );
196
- if (command === "createSpatialized2DElement") {
197
- this.createSpatializedElementSync(spatialId, webspatialUrl);
198
- }
199
- this.iframeRegistry.set(spatialId, iframe);
200
- return CommandResultSuccess({ windowProxy, id: spatialId });
201
- } catch (error) {
202
- console.error("Error calling webspatial protocol sync:", error);
203
- return CommandResultFailure(
204
- "500",
205
- "Failed to call webspatial protocol sync"
206
- );
207
- }
208
- }
209
- /**
210
- * Synchronously create iframe-based window
211
- */
212
- createIframeWindow(url, target, features) {
213
- const iframe = document.createElement("iframe");
214
- iframe.style.border = "none";
215
- iframe.style.display = "none";
216
- iframe.style.width = "100%";
217
- iframe.style.height = "100%";
218
- const spatialId = this.generateUUID();
219
- iframe.spatialId = spatialId;
220
- iframe.id = `spatial-iframe-${spatialId}`;
221
- const featuresObj = this.parseFeatures(features || "");
222
- if (featuresObj.width) {
223
- iframe.style.width = featuresObj.width;
224
- }
225
- if (featuresObj.height) {
226
- iframe.style.height = featuresObj.height;
227
- }
228
- if (featuresObj.left) {
229
- iframe.style.left = featuresObj.left;
230
- iframe.style.position = "absolute";
231
- }
232
- if (featuresObj.top) {
233
- iframe.style.top = featuresObj.top;
234
- iframe.style.position = "absolute";
235
- }
236
- document.body.appendChild(iframe);
237
- const windowProxy = this.createEnhancedWindowProxy(iframe, url, spatialId);
238
- iframe.src = "about:blank";
239
- console.log(
240
- `PuppeteerPlatform created iframe window with spatialId: ${spatialId}, URL: ${url}`
241
- );
242
- this.initializeIframeContent(iframe, url, spatialId);
243
- return { spatialId, iframe, windowProxy };
244
- }
245
- /**
246
- * create enhanced windowProxy object
247
- */
248
- createEnhancedWindowProxy(iframe, url, spatialId) {
249
- return {
250
- // basic properties
251
- location: {
252
- href: url,
253
- toString: () => url,
254
- reload: () => {
255
- if (iframe.contentWindow) {
256
- iframe.contentWindow.location.reload();
257
- }
258
- }
259
- },
260
- navigator: {
261
- userAgent: `Mozilla/5.0 (WebKit) SpatialId/${spatialId}`
262
- },
263
- // methods
264
- close: () => {
265
- console.log(`Closing iframe with spatialId: ${spatialId}`);
266
- iframe.remove();
267
- this.iframeRegistry.delete(spatialId);
268
- },
269
- // document access
270
- document: iframe.contentDocument || {},
271
- contentWindow: iframe.contentWindow || {},
272
- // add message communication method
273
- postMessage: (message, targetOrigin) => {
274
- if (iframe.contentWindow) {
275
- iframe.contentWindow.postMessage(message, targetOrigin || "*");
276
- }
277
- },
278
- // add event listener method
279
- addEventListener: (type, listener) => {
280
- if (iframe.contentWindow) {
281
- iframe.contentWindow.addEventListener(type, listener);
282
- }
283
- },
284
- removeEventListener: (type, listener) => {
285
- if (iframe.contentWindow) {
286
- iframe.contentWindow.removeEventListener(type, listener);
287
- }
288
- },
289
- // execute JavaScript
290
- executeScript: (code) => {
291
- if (iframe.contentWindow) {
292
- try {
293
- const win = iframe.contentWindow;
294
- return win.eval(code);
295
- } catch (error) {
296
- console.error(
297
- `Error executing script in iframe ${spatialId}:`,
298
- error
299
- );
300
- return null;
301
- }
302
- }
303
- return null;
304
- },
305
- // get iframe reference
306
- getIframe: () => iframe,
307
- // get spatialId
308
- getSpatialId: () => spatialId
309
- };
310
- }
311
- /**
312
- * initialize iframe content
313
- */
314
- initializeIframeContent(iframe, url, spatialId) {
315
- try {
316
- iframe.onload = () => {
317
- try {
318
- const iframeContent = `
319
- // inject communication script
320
- window.webSpatialId = '${spatialId}';
321
- window.SpatialId = '${spatialId}';
322
-
323
- // override window.open to support webspatial protocol
324
- const originalOpen = window.open;
325
- window.open = function(url, target, features) {
326
- if (url && url.startsWith('webspatial://')) {
327
- // handle webspatial protocol through windowProxy
328
- const windowProxy = new Proxy({}, {
329
- get: function(target, prop) {
330
- if (prop === 'toString') {
331
- return function() { return url; };
332
- }
333
- return undefined;
334
- }
335
- });
336
- return windowProxy;
337
- }
338
- return originalOpen.call(window, url, target, features);
339
- };
340
-
341
- // set navigator.userAgent to identify webspatial environment
342
- Object.defineProperty(navigator, 'userAgent', {
343
- value: 'WebSpatial/1.0 ' + navigator.userAgent,
344
- configurable: true
345
- });
346
-
347
- // send loaded message
348
- window.parent.postMessage({
349
- type: 'iframe_loaded',
350
- spatialId: '${spatialId}',
351
- url: '${url}'
352
- }, '${window.location.origin}');
353
-
354
- // set message handler
355
- window.addEventListener('message', (event) => {
356
- if (event.origin !== window.parent.location.origin) return;
357
-
358
- const data = event.data;
359
- if (data && data.type === 'webspatial_command') {
360
- // handle command from parent window
361
- console.log('Received command in iframe from parent:', data.command);
362
- // add command handling logic here
363
- }
364
- });
365
- `;
366
- const doc = iframe.contentDocument;
367
- if (doc) {
368
- doc.open();
369
- doc.write(`
370
- <!DOCTYPE html>
371
- <html>
372
- <head>
373
- <title>Spatial Iframe - ${spatialId}</title>
374
- <meta charset="UTF-8">
375
- <style>
376
- body {
377
- margin: 0;
378
- padding: 0;
379
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
380
- }
381
- </style>
382
- </head>
383
- <body>
384
- <script>${iframeContent}</script>
385
- </body>
386
- </html>
387
- `);
388
- doc.close();
389
- }
390
- } catch (error) {
391
- console.error("Error initializing iframe content:", error);
392
- }
393
- };
394
- } catch (error) {
395
- console.error("Error setting up iframe:", error);
396
- }
397
- }
398
- /**
399
- * parse features string to object
400
- */
401
- parseFeatures(features) {
402
- const result = {};
403
- const pairs = features.split(",");
404
- pairs.forEach((pair) => {
405
- const [key, value] = pair.split("=").map((s) => s.trim());
406
- if (key && value) {
407
- result[key] = value;
408
- }
409
- });
410
- return result;
411
- }
412
- /**
413
- * send message to iframe with specified spatialId
414
- */
415
- sendMessageToIframe(spatialId, message) {
416
- const iframe = this.iframeRegistry.get(spatialId);
417
- if (iframe && iframe.contentWindow) {
418
- iframe.contentWindow.postMessage(message, window.location.origin);
419
- return true;
420
- }
421
- return false;
422
- }
423
- /**
424
- * get all active iframes
425
- */
426
- getAllActiveIframes() {
427
- const result = [];
428
- this.iframeRegistry.forEach((iframe, spatialId) => {
429
- result.push({ spatialId, iframe });
430
- });
431
- return result;
432
- }
433
- /**
434
- * dispose all active iframes
435
- */
436
- dispose() {
437
- this.iframeRegistry.forEach((iframe, spatialId) => {
438
- console.log(`Disposing iframe with spatialId: ${spatialId}`);
439
- iframe.remove();
440
- });
441
- this.iframeRegistry.clear();
442
- }
443
- // generate UUID function
444
- generateUUID() {
445
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
446
- /[xy]/g,
447
- function(c) {
448
- const r = Math.random() * 16 | 0;
449
- const v = c === "x" ? r : r & 3 | 8;
450
- return v.toString(16).toUpperCase();
451
- }
452
- );
453
- }
454
- };
455
- }
456
- });
457
-
458
- // src/SpatialWebEvent.ts
459
- var SpatialWebEvent;
460
- var init_SpatialWebEvent = __esm({
461
- "src/SpatialWebEvent.ts"() {
462
- "use strict";
463
- SpatialWebEvent = class _SpatialWebEvent {
464
- static eventReceiver = {};
465
- static init() {
466
- window.__SpatialWebEvent = ({ id, data }) => {
467
- _SpatialWebEvent.eventReceiver[id]?.(data);
468
- };
469
- }
470
- static addEventReceiver(id, callback) {
471
- _SpatialWebEvent.eventReceiver[id] = callback;
472
- }
473
- static removeEventReceiver(id) {
474
- delete _SpatialWebEvent.eventReceiver[id];
475
- }
476
- };
477
- }
478
- });
479
-
480
- // src/platform-adapter/pico-os/PicoOSPlatform.ts
481
- var PicoOSPlatform_exports = {};
482
- __export(PicoOSPlatform_exports, {
483
- PicoOSPlatform: () => PicoOSPlatform
484
- });
485
- function nextRequestId() {
486
- requestId = (requestId + 1) % MAX_ID;
487
- return `rId_${requestId}`;
488
- }
489
- var requestId, MAX_ID, PicoOSPlatform;
490
- var init_PicoOSPlatform = __esm({
491
- "src/platform-adapter/pico-os/PicoOSPlatform.ts"() {
492
- "use strict";
493
- init_CommandResultUtils();
494
- init_SpatialWebEvent();
495
- requestId = 0;
496
- MAX_ID = 1e5;
497
- PicoOSPlatform = class {
498
- async callJSB(cmd, msg) {
499
- return new Promise((resolve, reject) => {
500
- try {
501
- const rId = nextRequestId();
502
- SpatialWebEvent.addEventReceiver(rId, (result) => {
503
- SpatialWebEvent.removeEventReceiver(rId);
504
- if (result.success) {
505
- resolve(CommandResultSuccess(result.data));
506
- } else {
507
- const { code, message } = result.data;
508
- resolve(CommandResultFailure(code, message));
509
- }
510
- });
511
- const ans = window.webspatialBridge.postMessage(rId, cmd, msg);
512
- if (ans !== "") {
513
- SpatialWebEvent.removeEventReceiver(rId);
514
- const result = JSON.parse(ans);
515
- if (result.success) {
516
- resolve(CommandResultSuccess(result.data));
517
- } else {
518
- const { code, message } = result.data;
519
- resolve(CommandResultFailure(code, message));
520
- }
521
- }
522
- } catch (error) {
523
- console.error(`SwanPlatform cmd: ${cmd}, msg: ${msg} error: ${error}`);
524
- const { code, message } = error;
525
- resolve(CommandResultFailure(code, message));
526
- }
527
- });
528
- }
529
- async callWebSpatialProtocol(command, query, target, features) {
530
- return new Promise((resolve, reject) => {
531
- const createdId = nextRequestId();
532
- try {
533
- let windowProxy = null;
534
- SpatialWebEvent.addEventReceiver(
535
- createdId,
536
- (result) => {
537
- resolve(
538
- CommandResultSuccess({
539
- windowProxy,
540
- id: result.spatialId
541
- })
542
- );
543
- SpatialWebEvent.removeEventReceiver(createdId);
544
- }
545
- );
546
- windowProxy = this.openWindow(
547
- command,
548
- "rid=" + createdId,
549
- target,
550
- features
551
- ).windowProxy;
552
- } catch (error) {
553
- const { code, message } = error;
554
- SpatialWebEvent.removeEventReceiver(createdId);
555
- resolve(CommandResultFailure(code, message));
556
- }
557
- });
558
- }
559
- callWebSpatialProtocolSync(command, query, target, features) {
560
- const { spatialId: id = "", windowProxy } = this.openWindow(
561
- command,
562
- query,
563
- target,
564
- features
565
- );
566
- return CommandResultSuccess({ windowProxy, id });
567
- }
568
- openWindow(command, query, target, features) {
569
- const windowProxy = window.open(
570
- `webspatial://${command}?${query || ""}`,
571
- target,
572
- features
573
- );
574
- return { spatialId: "", windowProxy };
575
- }
576
- };
577
- }
578
- });
579
-
580
- // src/platform-adapter/android/AndroidPlatform.ts
581
- var AndroidPlatform_exports = {};
582
- __export(AndroidPlatform_exports, {
583
- AndroidPlatform: () => AndroidPlatform
584
- });
585
- function nextRequestId2() {
586
- requestId2 = (requestId2 + 1) % MAX_ID2;
587
- return `rId_${requestId2}`;
588
- }
589
- var creatingElementCount, requestId2, MAX_ID2, AndroidPlatform;
590
- var init_AndroidPlatform = __esm({
591
- "src/platform-adapter/android/AndroidPlatform.ts"() {
592
- "use strict";
593
- init_CommandResultUtils();
594
- init_JSBCommand();
595
- init_SpatialWebEvent();
596
- creatingElementCount = 0;
597
- requestId2 = 0;
598
- MAX_ID2 = 1e5;
599
- AndroidPlatform = class {
600
- async callJSB(cmd, msg) {
601
- return new Promise((resolve, reject) => {
602
- try {
603
- const rId = nextRequestId2();
604
- SpatialWebEvent.addEventReceiver(rId, (result) => {
605
- SpatialWebEvent.removeEventReceiver(rId);
606
- if (result.success) {
607
- resolve(CommandResultSuccess(result.data));
608
- } else {
609
- const { code, message } = result.data;
610
- resolve(CommandResultFailure(code, message));
611
- }
612
- });
613
- const ans = window.webspatialBridge.postMessage(rId, cmd, msg);
614
- if (ans !== "") {
615
- SpatialWebEvent.removeEventReceiver(rId);
616
- const result = JSON.parse(ans);
617
- if (result.success) {
618
- resolve(CommandResultSuccess(result.data));
619
- } else {
620
- const { code, message } = result.data;
621
- resolve(CommandResultFailure(code, message));
622
- }
623
- }
624
- } catch (error) {
625
- console.error(
626
- `AndroidPlatform cmd: ${cmd}, msg: ${msg} error: ${error}`
627
- );
628
- const { code, message } = error;
629
- resolve(CommandResultFailure(code, message));
630
- }
631
- });
632
- }
633
- async callWebSpatialProtocol(command, query, target, features) {
634
- await new Promise((resolve) => setTimeout(resolve, 16 * creatingElementCount));
635
- creatingElementCount++;
636
- let canCreate = await new CheckWebViewCanCreateCommand().execute();
637
- while (!canCreate.data.can) {
638
- await new Promise((resolve) => setTimeout(resolve, 16));
639
- canCreate = await new CheckWebViewCanCreateCommand().execute();
640
- }
641
- const { windowProxy } = this.openWindow(command, query, target, features);
642
- while (!windowProxy?.open) {
643
- await new Promise((resolve) => setTimeout(resolve, 16));
644
- }
645
- windowProxy?.open("about:blank", "_self");
646
- while (!windowProxy?.__SpatialId) {
647
- await new Promise((resolve) => setTimeout(resolve, 16));
648
- }
649
- let spatialId = windowProxy?.__SpatialId;
650
- creatingElementCount--;
651
- return Promise.resolve(
652
- CommandResultSuccess({ windowProxy, id: spatialId })
653
- );
654
- }
655
- callWebSpatialProtocolSync(command, query, target, features) {
656
- const { spatialId: id = "", windowProxy } = this.openWindow(
657
- command,
658
- query,
659
- target,
660
- features
661
- );
662
- return CommandResultSuccess({ windowProxy, id });
663
- }
664
- openWindow(command, query, target, features) {
665
- const windowProxy = window.open(
666
- `webspatial://${command}?${query || ""}`,
667
- target,
668
- features
669
- );
670
- return { spatialId: "", windowProxy };
671
- }
672
- };
673
- }
674
- });
675
-
676
- // src/platform-adapter/vision-os/VisionOSPlatform.ts
677
- var VisionOSPlatform_exports = {};
678
- __export(VisionOSPlatform_exports, {
679
- VisionOSPlatform: () => VisionOSPlatform
680
- });
681
- var VisionOSPlatform;
682
- var init_VisionOSPlatform = __esm({
683
- "src/platform-adapter/vision-os/VisionOSPlatform.ts"() {
684
- "use strict";
685
- init_CommandResultUtils();
686
- VisionOSPlatform = class {
687
- async callJSB(cmd, msg) {
688
- try {
689
- const result = await window.webkit.messageHandlers.bridge.postMessage(
690
- `${cmd}::${msg}`
691
- );
692
- return CommandResultSuccess(result);
693
- } catch (error) {
694
- const { code, message } = JSON.parse(error.message);
695
- return CommandResultFailure(code, message);
696
- }
697
- }
698
- callWebSpatialProtocol(command, query, target, features) {
699
- const { spatialId: id, windowProxy } = this.openWindow(
700
- command,
701
- query,
702
- target,
703
- features
704
- );
705
- return Promise.resolve(
706
- CommandResultSuccess({ windowProxy, id })
707
- );
708
- }
709
- callWebSpatialProtocolSync(command, query, target, features) {
710
- const { spatialId: id = "", windowProxy } = this.openWindow(
711
- command,
712
- query,
713
- target,
714
- features
715
- );
716
- return CommandResultSuccess({ windowProxy, id });
717
- }
718
- openWindow(command, query, target, features) {
719
- const windowProxy = window.open(
720
- `webspatial://${command}?${query || ""}`,
721
- target,
722
- features
723
- );
724
- const ua = windowProxy?.navigator.userAgent;
725
- const spatialId = ua?.match(
726
- /\b([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})\b/gi
727
- )?.[0];
728
- return { spatialId, windowProxy };
729
- }
730
- };
731
- }
732
- });
733
-
734
- // src/platform-adapter/index.ts
735
- function getWebSpatialVersion(ua) {
736
- const match = ua.match(/WebSpatial\/(\d+)\.(\d+)\.(\d+)/);
737
- if (!match) {
738
- return null;
739
- }
740
- return [Number(match[1]), Number(match[2]), Number(match[3])];
741
- }
742
- function isVersionGreater(a, b) {
743
- if (!a) {
744
- return false;
745
- }
746
- for (let index = 0; index < 3; index += 1) {
747
- const diff = a[index] - b[index];
748
- if (diff > 0) {
749
- return true;
750
- }
751
- if (diff < 0) {
752
- return false;
753
- }
754
- }
755
- return false;
756
- }
757
- function createPlatform() {
758
- if (isSSREnv()) {
759
- return new SSRPlatform();
760
- }
761
- const userAgent = window.navigator.userAgent;
762
- const webSpatialVersion = getWebSpatialVersion(userAgent);
763
- if (window.navigator.userAgent.includes("Puppeteer")) {
764
- const PuppeteerPlatform2 = (init_PuppeteerPlatform(), __toCommonJS(PuppeteerPlatform_exports)).PuppeteerPlatform;
765
- return new PuppeteerPlatform2();
766
- } else if (userAgent.includes("PicoWebApp") && isVersionGreater(webSpatialVersion, [0, 0, 1])) {
767
- const PicoOSPlatform2 = (init_PicoOSPlatform(), __toCommonJS(PicoOSPlatform_exports)).PicoOSPlatform;
768
- return new PicoOSPlatform2();
769
- } else if (userAgent.includes("Android") || userAgent.includes("Linux")) {
770
- const AndroidPlatform2 = (init_AndroidPlatform(), __toCommonJS(AndroidPlatform_exports)).AndroidPlatform;
771
- return new AndroidPlatform2();
772
- } else {
773
- const VisionOSPlatform2 = (init_VisionOSPlatform(), __toCommonJS(VisionOSPlatform_exports)).VisionOSPlatform;
774
- return new VisionOSPlatform2();
775
- }
776
- }
777
- var init_platform_adapter = __esm({
778
- "src/platform-adapter/index.ts"() {
779
- "use strict";
780
- init_ssr_polyfill();
781
- init_SSRPlatform();
782
- }
783
- });
784
-
785
- // src/utils.ts
786
- function parseBorderRadius(borderProperty, width) {
787
- if (borderProperty === "") {
788
- return 0;
789
- }
790
- if (borderProperty.endsWith("%")) {
791
- return width * parseFloat(borderProperty) / 100;
792
- }
793
- return parseFloat(borderProperty);
794
- }
795
- function parseCornerRadius(computedStyle) {
796
- const width = parseFloat(computedStyle.getPropertyValue("width"));
797
- const topLeftPropertyValue = computedStyle.getPropertyValue(
798
- "border-top-left-radius"
799
- );
800
- const topRightPropertyValue = computedStyle.getPropertyValue(
801
- "border-top-right-radius"
802
- );
803
- const bottomLeftPropertyValue = computedStyle.getPropertyValue(
804
- "border-bottom-left-radius"
805
- );
806
- const bottomRightPropertyValue = computedStyle.getPropertyValue(
807
- "border-bottom-right-radius"
808
- );
809
- const cornerRadius = {
810
- topLeading: parseBorderRadius(topLeftPropertyValue, width),
811
- bottomLeading: parseBorderRadius(bottomLeftPropertyValue, width),
812
- topTrailing: parseBorderRadius(topRightPropertyValue, width),
813
- bottomTrailing: parseBorderRadius(bottomRightPropertyValue, width)
814
- };
815
- return cornerRadius;
816
- }
817
- function composeSRT(position, rotation, scale) {
818
- const { x: px, y: py, z: pz } = position;
819
- const { x: rx, y: ry, z: rz } = rotation;
820
- const { x: sx, y: sy, z: sz } = scale;
821
- let m = new DOMMatrix();
822
- m = m.translate(px, py, pz);
823
- m = m.rotate(rx, ry, rz);
824
- m = m.scale(sx, sy, sz);
825
- return m;
826
- }
827
- function deepCloneJSON(value) {
828
- const sc = globalThis.structuredClone;
829
- if (typeof sc === "function") {
830
- try {
831
- return sc(value);
832
- } catch {
833
- }
834
- }
835
- return JSON.parse(JSON.stringify(value));
836
- }
837
- var init_utils = __esm({
838
- "src/utils.ts"() {
839
- "use strict";
840
- }
841
- });
842
-
843
- // src/JSBCommand.ts
844
- var platform, JSBCommand, UpdateEntityPropertiesCommand, UpdateEntityEventCommand, UpdateSpatialSceneProperties, UpdateSceneConfig, FocusScene, GetSpatialSceneState, SpatializedElementCommand, UpdateSpatialized2DElementProperties, UpdateSpatializedDynamic3DElementProperties, UpdateUnlitMaterialProperties, UpdateSpatializedElementTransform, UpdateSpatializedStatic3DElementProperties, AddSpatializedElementToSpatialized2DElement, AddSpatializedElementToSpatialScene, CreateSpatializedStatic3DElementCommand, CreateSpatializedDynamic3DElementCommand, CreateSpatialEntityCommand, CreateModelComponentCommand, CreateSpatialModelEntityCommand, CreateModelAssetCommand, CreateSpatialGeometryCommand, CreateSpatialUnlitMaterialCommand, AddComponentToEntityCommand, RemoveComponentFromEntityCommand, SetMaterialsOnEntityCommand, SetParentForEntityCommand, ConvertFromEntityToEntityCommand, ConvertFromEntityToSceneCommand, ConvertFromSceneToEntityCommand, ConvertCoordinateCommand, InspectCommand, DestroyCommand, CheckWebViewCanCreateCommand, WebSpatialProtocolCommand, createSpatialized2DElementCommand, createSpatialSceneCommand, CreateAttachmentEntityCommand, InitializeAttachmentCommand, UpdateAttachmentEntityCommand;
845
- var init_JSBCommand = __esm({
846
- "src/JSBCommand.ts"() {
847
- "use strict";
848
- init_platform_adapter();
849
- init_utils();
850
- platform = createPlatform();
851
- JSBCommand = class {
852
- commandType = "";
853
- async execute() {
854
- const param = this.getParams();
855
- const msg = param ? JSON.stringify(param) : "";
856
- return platform.callJSB(this.commandType, msg);
857
- }
858
- };
859
- UpdateEntityPropertiesCommand = class extends JSBCommand {
860
- constructor(entity, properties) {
861
- super();
862
- this.entity = entity;
863
- this.properties = properties;
864
- }
865
- commandType = "UpdateEntityProperties";
866
- getParams() {
867
- const transform = composeSRT(
868
- this.properties.position ?? this.entity.position,
869
- this.properties.rotation ?? this.entity.rotation,
870
- this.properties.scale ?? this.entity.scale
871
- ).toFloat64Array();
872
- return {
873
- entityId: this.entity.id,
874
- transform
875
- };
876
- }
877
- };
878
- UpdateEntityEventCommand = class extends JSBCommand {
879
- constructor(entity, type, isEnable) {
880
- super();
881
- this.entity = entity;
882
- this.type = type;
883
- this.isEnable = isEnable;
884
- }
885
- commandType = "UpdateEntityEvent";
886
- getParams() {
887
- return {
888
- type: this.type,
889
- entityId: this.entity.id,
890
- isEnable: this.isEnable
891
- };
892
- }
893
- };
894
- UpdateSpatialSceneProperties = class extends JSBCommand {
895
- properties;
896
- commandType = "UpdateSpatialSceneProperties";
897
- constructor(properties) {
898
- super();
899
- this.properties = properties;
900
- }
901
- getParams() {
902
- return this.properties;
903
- }
904
- };
905
- UpdateSceneConfig = class extends JSBCommand {
906
- config;
907
- commandType = "UpdateSceneConfig";
908
- constructor(config) {
909
- super();
910
- this.config = config;
911
- }
912
- getParams() {
913
- return { config: this.config };
914
- }
915
- };
916
- FocusScene = class extends JSBCommand {
917
- constructor(id) {
918
- super();
919
- this.id = id;
920
- }
921
- commandType = "FocusScene";
922
- getParams() {
923
- return { id: this.id };
924
- }
925
- };
926
- GetSpatialSceneState = class extends JSBCommand {
927
- commandType = "GetSpatialSceneState";
928
- constructor() {
929
- super();
930
- }
931
- getParams() {
932
- return {};
933
- }
934
- };
935
- SpatializedElementCommand = class extends JSBCommand {
936
- constructor(spatialObject) {
937
- super();
938
- this.spatialObject = spatialObject;
939
- }
940
- getParams() {
941
- const extraParams = this.getExtraParams();
942
- return { id: this.spatialObject.id, ...extraParams };
943
- }
944
- };
945
- UpdateSpatialized2DElementProperties = class extends SpatializedElementCommand {
946
- properties;
947
- commandType = "UpdateSpatialized2DElementProperties";
948
- constructor(spatialObject, properties) {
949
- super(spatialObject);
950
- this.properties = properties;
951
- }
952
- getExtraParams() {
953
- return this.properties;
954
- }
955
- };
956
- UpdateSpatializedDynamic3DElementProperties = class extends SpatializedElementCommand {
957
- properties;
958
- commandType = "UpdateSpatializedDynamic3DElementProperties";
959
- constructor(spatialObject, properties) {
960
- super(spatialObject);
961
- this.properties = properties;
962
- }
963
- getExtraParams() {
964
- return {
965
- id: this.spatialObject.id,
966
- ...this.properties
967
- };
968
- }
969
- };
970
- UpdateUnlitMaterialProperties = class extends SpatializedElementCommand {
971
- properties;
972
- commandType = "UpdateUnlitMaterialProperties";
973
- constructor(spatialObject, properties) {
974
- super(spatialObject);
975
- this.properties = properties;
976
- }
977
- getExtraParams() {
978
- return this.properties;
979
- }
980
- };
981
- UpdateSpatializedElementTransform = class extends SpatializedElementCommand {
982
- matrix;
983
- commandType = "UpdateSpatializedElementTransform";
984
- constructor(spatialObject, matrix) {
985
- super(spatialObject);
986
- this.matrix = matrix;
987
- }
988
- getExtraParams() {
989
- return { matrix: Array.from(this.matrix.toFloat64Array()) };
990
- }
991
- };
992
- UpdateSpatializedStatic3DElementProperties = class extends SpatializedElementCommand {
993
- properties;
994
- commandType = "UpdateSpatializedStatic3DElementProperties";
995
- constructor(spatialObject, properties) {
996
- super(spatialObject);
997
- this.properties = properties;
998
- }
999
- getExtraParams() {
1000
- return this.properties;
1001
- }
1002
- };
1003
- AddSpatializedElementToSpatialized2DElement = class extends SpatializedElementCommand {
1004
- commandType = "AddSpatializedElementToSpatialized2DElement";
1005
- spatializedElement;
1006
- constructor(spatialObject, spatializedElement) {
1007
- super(spatialObject);
1008
- this.spatializedElement = spatializedElement;
1009
- }
1010
- getExtraParams() {
1011
- return { spatializedElementId: this.spatializedElement.id };
1012
- }
1013
- };
1014
- AddSpatializedElementToSpatialScene = class extends JSBCommand {
1015
- commandType = "AddSpatializedElementToSpatialScene";
1016
- spatializedElement;
1017
- constructor(spatializedElement) {
1018
- super();
1019
- this.spatializedElement = spatializedElement;
1020
- }
1021
- getParams() {
1022
- return {
1023
- spatializedElementId: this.spatializedElement.id
1024
- };
1025
- }
1026
- };
1027
- CreateSpatializedStatic3DElementCommand = class extends JSBCommand {
1028
- constructor(modelURL, sources) {
1029
- super();
1030
- this.modelURL = modelURL;
1031
- this.sources = sources;
1032
- this.modelURL = modelURL;
1033
- this.sources = sources;
1034
- }
1035
- commandType = "CreateSpatializedStatic3DElement";
1036
- getParams() {
1037
- return { modelURL: this.modelURL, sources: this.sources };
1038
- }
1039
- };
1040
- CreateSpatializedDynamic3DElementCommand = class extends JSBCommand {
1041
- getParams() {
1042
- return { test: true };
1043
- }
1044
- commandType = "CreateSpatializedDynamic3DElement";
1045
- };
1046
- CreateSpatialEntityCommand = class extends JSBCommand {
1047
- constructor(name) {
1048
- super();
1049
- this.name = name;
1050
- }
1051
- getParams() {
1052
- return { name: this.name };
1053
- }
1054
- commandType = "CreateSpatialEntity";
1055
- };
1056
- CreateModelComponentCommand = class extends JSBCommand {
1057
- constructor(options) {
1058
- super();
1059
- this.options = options;
1060
- }
1061
- getParams() {
1062
- let geometryId = this.options.mesh.id;
1063
- let materialIds = this.options.materials.map((material) => material.id);
1064
- return { geometryId, materialIds };
1065
- }
1066
- commandType = "CreateModelComponent";
1067
- };
1068
- CreateSpatialModelEntityCommand = class extends JSBCommand {
1069
- constructor(options) {
1070
- super();
1071
- this.options = options;
1072
- }
1073
- getParams() {
1074
- return this.options;
1075
- }
1076
- commandType = "CreateSpatialModelEntity";
1077
- };
1078
- CreateModelAssetCommand = class extends JSBCommand {
1079
- constructor(options) {
1080
- super();
1081
- this.options = options;
1082
- }
1083
- getParams() {
1084
- return { url: this.options.url };
1085
- }
1086
- commandType = "CreateModelAsset";
1087
- };
1088
- CreateSpatialGeometryCommand = class extends JSBCommand {
1089
- constructor(type, options = {}) {
1090
- super();
1091
- this.type = type;
1092
- this.options = options;
1093
- }
1094
- getParams() {
1095
- return { type: this.type, ...this.options };
1096
- }
1097
- commandType = "CreateGeometry";
1098
- };
1099
- CreateSpatialUnlitMaterialCommand = class extends JSBCommand {
1100
- constructor(options) {
1101
- super();
1102
- this.options = options;
1103
- }
1104
- getParams() {
1105
- return this.options;
1106
- }
1107
- commandType = "CreateUnlitMaterial";
1108
- };
1109
- AddComponentToEntityCommand = class extends JSBCommand {
1110
- constructor(entity, comp) {
1111
- super();
1112
- this.entity = entity;
1113
- this.comp = comp;
1114
- }
1115
- getParams() {
1116
- return {
1117
- entityId: this.entity.id,
1118
- componentId: this.comp.id
1119
- };
1120
- }
1121
- commandType = "AddComponentToEntity";
1122
- };
1123
- RemoveComponentFromEntityCommand = class extends JSBCommand {
1124
- constructor(entity, comp) {
1125
- super();
1126
- this.entity = entity;
1127
- this.comp = comp;
1128
- }
1129
- getParams() {
1130
- return {
1131
- entityId: this.entity.id,
1132
- componentId: this.comp.id
1133
- };
1134
- }
1135
- commandType = "RemoveComponentFromEntity";
1136
- };
1137
- SetMaterialsOnEntityCommand = class extends JSBCommand {
1138
- constructor(entityId, materials) {
1139
- super();
1140
- this.entityId = entityId;
1141
- this.materials = materials;
1142
- }
1143
- getParams() {
1144
- return {
1145
- entityId: this.entityId,
1146
- materialIds: this.materials.map((m) => m.id)
1147
- };
1148
- }
1149
- commandType = "SetMaterialsOnEntity";
1150
- };
1151
- SetParentForEntityCommand = class extends JSBCommand {
1152
- // childId, parentId
1153
- constructor(childId, parentId) {
1154
- super();
1155
- this.childId = childId;
1156
- this.parentId = parentId;
1157
- }
1158
- getParams() {
1159
- return {
1160
- childId: this.childId,
1161
- parentId: this.parentId
1162
- };
1163
- }
1164
- commandType = "SetParentToEntity";
1165
- };
1166
- ConvertFromEntityToEntityCommand = class extends JSBCommand {
1167
- constructor(fromEntityId, toEntityId, fromPosition) {
1168
- super();
1169
- this.fromEntityId = fromEntityId;
1170
- this.toEntityId = toEntityId;
1171
- this.fromPosition = fromPosition;
1172
- }
1173
- getParams() {
1174
- return {
1175
- fromEntityId: this.fromEntityId,
1176
- toEntityId: this.toEntityId,
1177
- position: this.fromPosition
1178
- };
1179
- }
1180
- commandType = "ConvertFromEntityToEntity";
1181
- };
1182
- ConvertFromEntityToSceneCommand = class extends JSBCommand {
1183
- constructor(fromEntityId, position) {
1184
- super();
1185
- this.fromEntityId = fromEntityId;
1186
- this.position = position;
1187
- }
1188
- getParams() {
1189
- return {
1190
- fromEntityId: this.fromEntityId,
1191
- position: this.position
1192
- };
1193
- }
1194
- commandType = "ConvertFromEntityToScene";
1195
- };
1196
- ConvertFromSceneToEntityCommand = class extends JSBCommand {
1197
- // let entityId: String
1198
- // let position:Vec3
1199
- constructor(entityId, position) {
1200
- super();
1201
- this.entityId = entityId;
1202
- this.position = position;
1203
- }
1204
- getParams() {
1205
- return {
1206
- entityId: this.entityId,
1207
- position: this.position
1208
- };
1209
- }
1210
- commandType = "ConvertFromSceneToEntity";
1211
- };
1212
- ConvertCoordinateCommand = class extends JSBCommand {
1213
- constructor(position, fromId, toId) {
1214
- super();
1215
- this.position = position;
1216
- this.fromId = fromId;
1217
- this.toId = toId;
1218
- }
1219
- getParams() {
1220
- return {
1221
- position: this.position,
1222
- fromId: this.fromId,
1223
- toId: this.toId
1224
- };
1225
- }
1226
- commandType = "ConvertCoordinate";
1227
- };
1228
- InspectCommand = class extends JSBCommand {
1229
- constructor(id = "") {
1230
- super();
1231
- this.id = id;
1232
- }
1233
- commandType = "Inspect";
1234
- getParams() {
1235
- return this.id ? { id: this.id } : { id: "" };
1236
- }
1237
- };
1238
- DestroyCommand = class extends JSBCommand {
1239
- constructor(id) {
1240
- super();
1241
- this.id = id;
1242
- }
1243
- commandType = "Destroy";
1244
- getParams() {
1245
- return { id: this.id };
1246
- }
1247
- };
1248
- CheckWebViewCanCreateCommand = class extends JSBCommand {
1249
- constructor(id = "") {
1250
- super();
1251
- this.id = id;
1252
- }
1253
- commandType = "CheckWebViewCanCreate";
1254
- getParams() {
1255
- return { id: this.id };
1256
- }
1257
- };
1258
- WebSpatialProtocolCommand = class extends JSBCommand {
1259
- target;
1260
- features;
1261
- async execute() {
1262
- const query = this.getQuery();
1263
- return platform.callWebSpatialProtocol(
1264
- this.commandType,
1265
- query,
1266
- this.target,
1267
- this.features
1268
- );
1269
- }
1270
- executeSync() {
1271
- const query = this.getQuery();
1272
- return platform.callWebSpatialProtocolSync(
1273
- this.commandType,
1274
- query,
1275
- this.target,
1276
- this.features
1277
- );
1278
- }
1279
- getQuery() {
1280
- let query = void 0;
1281
- const params = this.getParams();
1282
- if (params) {
1283
- query = Object.keys(params).map((key) => {
1284
- const value = params[key];
1285
- const finalValue = typeof value === "object" ? JSON.stringify(value) : value;
1286
- return `${key}=${encodeURIComponent(finalValue)}`;
1287
- }).join("&");
1288
- }
1289
- return query;
1290
- }
1291
- };
1292
- createSpatialized2DElementCommand = class extends WebSpatialProtocolCommand {
1293
- commandType = "createSpatialized2DElement";
1294
- constructor() {
1295
- super();
1296
- }
1297
- getParams() {
1298
- return {};
1299
- }
1300
- };
1301
- createSpatialSceneCommand = class extends WebSpatialProtocolCommand {
1302
- constructor(url, config, target, features) {
1303
- super();
1304
- this.url = url;
1305
- this.config = config;
1306
- this.target = target;
1307
- this.features = features;
1308
- }
1309
- commandType = "createSpatialScene";
1310
- getParams() {
1311
- return {
1312
- url: this.url,
1313
- config: this.config
1314
- };
1315
- }
1316
- };
1317
- CreateAttachmentEntityCommand = class extends WebSpatialProtocolCommand {
1318
- constructor(options) {
1319
- super();
1320
- this.options = options;
1321
- }
1322
- commandType = "createAttachment";
1323
- getParams() {
1324
- return {};
1325
- }
1326
- };
1327
- InitializeAttachmentCommand = class extends JSBCommand {
1328
- constructor(attachmentId, options) {
1329
- super();
1330
- this.attachmentId = attachmentId;
1331
- this.options = options;
1332
- }
1333
- commandType = "InitializeAttachment";
1334
- getParams() {
1335
- return {
1336
- id: this.attachmentId,
1337
- parentEntityId: this.options.parentEntityId,
1338
- position: this.options.position ?? [0, 0, 0],
1339
- size: this.options.size,
1340
- ownerViewId: this.options.ownerViewId
1341
- };
1342
- }
1343
- };
1344
- UpdateAttachmentEntityCommand = class extends JSBCommand {
1345
- constructor(attachmentId, options) {
1346
- super();
1347
- this.attachmentId = attachmentId;
1348
- this.options = options;
1349
- }
1350
- commandType = "UpdateAttachmentEntity";
1351
- getParams() {
1352
- return {
1353
- id: this.attachmentId,
1354
- ...this.options
1355
- };
1356
- }
1357
- };
1358
- }
1359
- });
1360
-
1361
- // src/SpatialObject.ts
1362
- init_JSBCommand();
1363
- var SpatialObject = class {
1364
- /** @hidden */
1365
- constructor(id) {
1366
- this.id = id;
1367
- }
1368
- name;
1369
- isDestroyed = false;
1370
- async inspect() {
1371
- const ret = await new InspectCommand(this.id).execute();
1372
- if (ret.success) {
1373
- return ret.data;
1374
- }
1375
- throw new Error(ret.errorMessage);
1376
- }
1377
- async destroy() {
1378
- if (this.isDestroyed) {
1379
- return;
1380
- }
1381
- const ret = await new DestroyCommand(this.id).execute();
1382
- if (ret.success) {
1383
- this.onDestroy();
1384
- this.isDestroyed = true;
1385
- return ret.data;
1386
- } else if (this.isDestroyed) {
1387
- return;
1388
- }
1389
- throw new Error(ret.errorMessage);
1390
- }
1391
- // override this method to do some cleanup
1392
- onDestroy() {
1393
- }
1394
- };
1395
-
1396
- // src/scene-polyfill.ts
1397
- init_JSBCommand();
1398
-
1399
- // src/SpatialScene.ts
1400
- init_JSBCommand();
1401
- init_JSBCommand();
1402
- var instance;
1403
- var SpatialScene = class _SpatialScene extends SpatialObject {
1404
- /**
1405
- * Gets the singleton instance of the SpatialScene.
1406
- * Creates a new instance if one doesn't exist yet.
1407
- * @returns The singleton SpatialScene instance
1408
- */
1409
- static getInstance() {
1410
- if (!instance) {
1411
- instance = new _SpatialScene("");
1412
- }
1413
- return instance;
1414
- }
1415
- async convertCoordinate(position, fromId, toId) {
1416
- try {
1417
- const ret = await new ConvertCoordinateCommand(
1418
- position,
1419
- fromId,
1420
- toId
1421
- ).execute();
1422
- return ret?.data ?? position;
1423
- } catch (error) {
1424
- console.warn("SpatialScene.convertCoordinate error:", error);
1425
- throw error;
1426
- }
1427
- }
1428
- /**
1429
- * Updates the properties of the spatial scene.
1430
- * This can include background settings, lighting, and other scene-wide properties.
1431
- * @param properties Partial set of properties to update
1432
- * @returns Promise resolving when the update is complete
1433
- */
1434
- async updateSpatialProperties(properties) {
1435
- return new UpdateSpatialSceneProperties(properties).execute();
1436
- }
1437
- /**
1438
- * Adds a spatialized element to the scene.
1439
- * This makes the element visible and interactive in the spatial environment.
1440
- * @param element The SpatializedElement to add to the scene
1441
- * @returns Promise resolving when the element is added
1442
- */
1443
- async addSpatializedElement(element) {
1444
- return new AddSpatializedElementToSpatialScene(element).execute();
1445
- }
1446
- /**
1447
- * Updates the scene creation configuration.
1448
- * This allows changing scene parameters after initial creation.
1449
- * @param config The new scene creation configuration
1450
- * @returns Promise resolving when the update is complete
1451
- */
1452
- async updateSceneCreationConfig(config) {
1453
- return new UpdateSceneConfig(config).execute();
1454
- }
1455
- /**
1456
- * Gets the current state of the spatial scene.
1457
- * This includes information about active elements and scene configuration.
1458
- * @returns Promise resolving to the current SpatialSceneState
1459
- */
1460
- async getState() {
1461
- return (await new GetSpatialSceneState().execute()).data.name;
1462
- }
1463
- };
1464
-
1465
- // src/types/types.ts
1466
- var SpatializedElementType = /* @__PURE__ */ ((SpatializedElementType2) => {
1467
- SpatializedElementType2[SpatializedElementType2["Spatialized2DElement"] = 0] = "Spatialized2DElement";
1468
- SpatializedElementType2[SpatializedElementType2["SpatializedStatic3DElement"] = 1] = "SpatializedStatic3DElement";
1469
- SpatializedElementType2[SpatializedElementType2["SpatializedDynamic3DElement"] = 2] = "SpatializedDynamic3DElement";
1470
- return SpatializedElementType2;
1471
- })(SpatializedElementType || {});
1472
- var BaseplateVisibilityValues = [
1473
- "automatic",
1474
- "visible",
1475
- "hidden"
1476
- ];
1477
- function isValidBaseplateVisibilityType(type) {
1478
- return BaseplateVisibilityValues.includes(type);
1479
- }
1480
- var WorldScalingValues = ["automatic", "dynamic"];
1481
- function isValidWorldScalingType(type) {
1482
- return WorldScalingValues.includes(type);
1483
- }
1484
- var WorldAlignmentValues = [
1485
- "adaptive",
1486
- "automatic",
1487
- "gravityAligned"
1488
- ];
1489
- function isValidWorldAlignmentType(type) {
1490
- return WorldAlignmentValues.includes(type);
1491
- }
1492
- var SpatialSceneValues = ["window", "volume"];
1493
- function isValidSpatialSceneType(type) {
1494
- return SpatialSceneValues.includes(type);
1495
- }
1496
- function isValidSceneUnit(val) {
1497
- if (typeof val === "number") {
1498
- return val >= 0;
1499
- }
1500
- if (typeof val === "string") {
1501
- if (val.endsWith("px")) {
1502
- if (isNaN(Number(val.slice(0, -2)))) {
1503
- return false;
1504
- }
1505
- return Number(val.slice(0, -2)) >= 0;
1506
- }
1507
- if (val.endsWith("m")) {
1508
- if (isNaN(Number(val.slice(0, -1)))) {
1509
- return false;
1510
- }
1511
- return Number(val.slice(0, -1)) >= 0;
1512
- }
1513
- }
1514
- return false;
1515
- }
1516
- var SpatialSceneState = /* @__PURE__ */ ((SpatialSceneState2) => {
1517
- SpatialSceneState2["idle"] = "idle";
1518
- SpatialSceneState2["pending"] = "pending";
1519
- SpatialSceneState2["willVisible"] = "willVisible";
1520
- SpatialSceneState2["visible"] = "visible";
1521
- SpatialSceneState2["fail"] = "fail";
1522
- return SpatialSceneState2;
1523
- })(SpatialSceneState || {});
1524
- var CubeInfo = class {
1525
- constructor(size, origin) {
1526
- this.size = size;
1527
- this.origin = origin;
1528
- this.size = size;
1529
- this.origin = origin;
1530
- }
1531
- get x() {
1532
- return this.origin.x;
1533
- }
1534
- get y() {
1535
- return this.origin.y;
1536
- }
1537
- get z() {
1538
- return this.origin.z;
1539
- }
1540
- get width() {
1541
- return this.size.width;
1542
- }
1543
- get height() {
1544
- return this.size.height;
1545
- }
1546
- get depth() {
1547
- return this.size.depth;
1548
- }
1549
- get left() {
1550
- return this.x;
1551
- }
1552
- get top() {
1553
- return this.y;
1554
- }
1555
- get right() {
1556
- return this.x + this.width;
1557
- }
1558
- get bottom() {
1559
- return this.y + this.height;
1560
- }
1561
- get back() {
1562
- return this.z;
1563
- }
1564
- get front() {
1565
- return this.z + this.depth;
1566
- }
1567
- };
1568
-
1569
- // src/scene-polyfill.ts
1570
- init_utils();
1571
-
1572
- // src/physicalMetrics.ts
1573
- var physicalMetrics_exports = {};
1574
- __export(physicalMetrics_exports, {
1575
- getValue: () => getValue,
1576
- physicalToPoint: () => physicalToPoint,
1577
- pointToPhysical: () => pointToPhysical,
1578
- subscribe: () => subscribe
1579
- });
1580
- init_SpatialWebEvent();
1581
- var snapshot = {
1582
- meterToPtUnscaled: 1360,
1583
- meterToPtScaled: 1360
1584
- };
1585
- function getWorldScalingCompensation(options) {
1586
- return options?.worldScalingCompensation ?? "scaled";
1587
- }
1588
- function pointToPhysical(point, options) {
1589
- updateValue();
1590
- const compensation = getWorldScalingCompensation(options);
1591
- if (compensation === "unscaled") {
1592
- return point / snapshot.meterToPtUnscaled;
1593
- }
1594
- return point / snapshot.meterToPtScaled;
1595
- }
1596
- function physicalToPoint(physical, options) {
1597
- updateValue();
1598
- const compensation = getWorldScalingCompensation(options);
1599
- if (compensation === "unscaled") {
1600
- return physical * snapshot.meterToPtUnscaled;
1601
- }
1602
- return physical * snapshot.meterToPtScaled;
1603
- }
1604
- function updateValue() {
1605
- if (typeof window === "undefined") return;
1606
- const src = window.__webspatialsdk__?.physicalMetrics;
1607
- if (!src) return;
1608
- const next = {
1609
- meterToPtScaled: src.meterToPtScaled ?? snapshot.meterToPtScaled,
1610
- meterToPtUnscaled: src.meterToPtUnscaled ?? snapshot.meterToPtUnscaled
1611
- };
1612
- if (next.meterToPtScaled !== snapshot.meterToPtScaled || next.meterToPtUnscaled !== snapshot.meterToPtUnscaled) {
1613
- snapshot = next;
1614
- }
1615
- }
1616
- function getValue() {
1617
- updateValue();
1618
- return snapshot;
1619
- }
1620
- function subscribe(cb) {
1621
- if (typeof window === "undefined") return () => {
1622
- };
1623
- const handler = () => {
1624
- cb();
1625
- };
1626
- SpatialWebEvent.addEventReceiver("window", handler);
1627
- return () => {
1628
- SpatialWebEvent.removeEventReceiver("window");
1629
- };
1630
- }
1631
-
1632
- // src/scene-polyfill.ts
1633
- var defaultSceneConfig = {
1634
- defaultSize: {
1635
- width: 1280,
1636
- height: 720
1637
- }
1638
- };
1639
- var defaultSceneConfigVolume = {
1640
- defaultSize: {
1641
- width: "0.94m",
1642
- height: "0.94m",
1643
- depth: "0.94m"
1644
- }
1645
- };
1646
- var xr_window_defaults = {
1647
- ...defaultSceneConfig
1648
- };
1649
- var xr_volume_defaults = {
1650
- ...defaultSceneConfigVolume
1651
- };
1652
- var INTERNAL_SCHEMA_PREFIX = "webspatial://";
1653
- function deepMergePlain(base, over) {
1654
- if (!over) return { ...base || {} };
1655
- const out = { ...base || {} };
1656
- for (const k of Object.keys(over)) {
1657
- const bv = out[k];
1658
- const ov = over[k];
1659
- if (ov && typeof ov === "object" && !Array.isArray(ov) && bv && typeof bv === "object" && !Array.isArray(bv)) {
1660
- out[k] = deepMergePlain(bv, ov);
1661
- } else {
1662
- out[k] = ov;
1663
- }
1664
- }
1665
- return out;
1666
- }
1667
- function normalizeXRDefaultsToSceneOptions(src) {
1668
- const out = { ...src || {} };
1669
- const ds = src.defaultSize !== void 0 ? src.defaultSize : src.default_size;
1670
- if (ds !== void 0) {
1671
- out.defaultSize = ds;
1672
- }
1673
- if ("default_size" in out) {
1674
- delete out.default_size;
1675
- }
1676
- return out;
1677
- }
1678
- var SceneManager = class _SceneManager {
1679
- originalOpen;
1680
- static instance;
1681
- manifestReady = null;
1682
- static getInstance() {
1683
- if (!_SceneManager.instance) {
1684
- _SceneManager.instance = new _SceneManager();
1685
- }
1686
- return _SceneManager.instance;
1687
- }
1688
- init(window2) {
1689
- this.manifestReady = this.setupManifest();
1690
- this.originalOpen = window2.open.bind(window2);
1691
- window2.open = this.open;
1692
- }
1693
- // Stores the latest formatted config used by the platform (per scene name).
1694
- // This object contains normalized values and is safe for internal consumption.
1695
- configMap = {};
1696
- // Stores the raw callback return value (per scene name) to feed into the next initScene call as `pre`.
1697
- // We keep this unformatted so developers receive exactly what they last returned.
1698
- callbackReturnMap = {};
1699
- getConfig(name) {
1700
- if (name === void 0 || !this.configMap[name]) return void 0;
1701
- return this.configMap[name];
1702
- }
1703
- waitManifest() {
1704
- return this.manifestReady ?? Promise.resolve();
1705
- }
1706
- // Ensure URL is absolute; only convert when a relative path is provided
1707
- // - Keep external and special schemes untouched (http, https, data, blob, about, file, mailto, etc.)
1708
- // - Handle protocol-relative URLs (//example.com/path)
1709
- // - Resolve relative paths against document.baseURI (respects <base href>)
1710
- ensureAbsoluteUrl(raw) {
1711
- if (!raw) return raw;
1712
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
1713
- return raw;
1714
- }
1715
- if (raw.startsWith("//")) {
1716
- return `${window.location.protocol}${raw}`;
1717
- }
1718
- try {
1719
- return new URL(raw, document.baseURI).toString();
1720
- } catch {
1721
- return raw;
1722
- }
1723
- }
1724
- async setupManifest() {
1725
- const manifest = await this.getPWAManifest();
1726
- try {
1727
- const xr = manifest?.xr_spatial_scene;
1728
- if (!xr || typeof xr !== "object") return;
1729
- const { overrides, ...topLevel } = xr;
1730
- const windowRaw = deepMergePlain(topLevel, overrides?.window_scene);
1731
- const volumeRaw = deepMergePlain(topLevel, overrides?.volume_scene);
1732
- const windowNext = normalizeXRDefaultsToSceneOptions(windowRaw);
1733
- const volumeNext = normalizeXRDefaultsToSceneOptions(volumeRaw);
1734
- if (windowNext && Object.keys(windowNext).length > 0) {
1735
- xr_window_defaults = windowNext;
1736
- }
1737
- if (volumeNext && Object.keys(volumeNext).length > 0) {
1738
- xr_volume_defaults = volumeNext;
1739
- }
1740
- } catch (error) {
1741
- console.warn(
1742
- "SceneManager.setupManifest failed; using built-in defaults.",
1743
- error?.message || error
1744
- );
1745
- }
1746
- }
1747
- open = (url, target, features) => {
1748
- if (url?.startsWith(INTERNAL_SCHEMA_PREFIX)) {
1749
- if (url.includes("createSpatialized2DElement") || url.includes("createAttachment")) {
1750
- const token = (
1751
- //@ts-ignore
1752
- (window.webSpatial || window.__webspatialShell__)?.genToken?.()
1753
- );
1754
- if (token) {
1755
- const command = url.includes("createAttachment") ? "createAttachment" : "createSpatialized2DElement";
1756
- const host = window.location.host;
1757
- const protocol = window.location.protocol;
1758
- const finalURL = `${protocol}//${host}/${token}/?command=${command}`;
1759
- const rid = new URL(url).searchParams.get("rid");
1760
- const final = new URL(finalURL);
1761
- if (rid) final.searchParams.set("rid", rid);
1762
- return this.originalOpen(final.toString(), target, features);
1763
- }
1764
- }
1765
- return this.originalOpen(url, target, features);
1766
- }
1767
- url = this.ensureAbsoluteUrl(url);
1768
- if (target === "_self" || target === "_parent" || target === "_top") {
1769
- const newWindow = this.originalOpen(url, target, features);
1770
- return newWindow;
1771
- }
1772
- let cfg = target ? this.getConfig(target) : void 0;
1773
- if (cfg === void 0) {
1774
- const preFormatted = deepCloneJSON(getSceneDefaultConfig("window"));
1775
- const [ans] = formatSceneConfig(preFormatted, "window");
1776
- cfg = { ...ans, type: "window" };
1777
- }
1778
- const cmd = new createSpatialSceneCommand(url, cfg, target, features);
1779
- const result = cmd.executeSync();
1780
- const id = result.data?.id;
1781
- if (id) {
1782
- let focusCmd = new FocusScene(id);
1783
- focusCmd.execute();
1784
- }
1785
- return result.data?.windowProxy;
1786
- };
1787
- initScene(name, callback, options) {
1788
- const sceneType = options?.type ?? "window";
1789
- const defaultConfigRaw = getSceneDefaultConfig(sceneType);
1790
- const previousOrDefault = this.callbackReturnMap[name] ?? (() => {
1791
- const cloned = deepCloneJSON(defaultConfigRaw);
1792
- return cloned;
1793
- })();
1794
- const rawReturnVal = callback(previousOrDefault);
1795
- const sanitizedReturnVal = sanitizeSceneOptionsUnits(
1796
- deepCloneJSON(rawReturnVal)
1797
- );
1798
- const clonedForFormat = deepCloneJSON(sanitizedReturnVal);
1799
- const baseDefaults = deepCloneJSON(getSceneDefaultConfig(sceneType));
1800
- const mergedForFormat = deepMergePlain(baseDefaults, clonedForFormat);
1801
- const [formattedConfig, errors] = formatSceneConfig(
1802
- mergedForFormat,
1803
- sceneType
1804
- );
1805
- if (errors.length > 0) {
1806
- console.warn(`initScene ${name} with errors: ${errors.join(", ")}`);
1807
- }
1808
- this.callbackReturnMap[name] = sanitizedReturnVal;
1809
- this.configMap[name] = {
1810
- ...formattedConfig,
1811
- type: sceneType
1812
- };
1813
- }
1814
- /**
1815
- * Resolve and load a PWA manifest as JSON:
1816
- * 1) Determine href:
1817
- * - Prefer explicit manifestUrl if provided;
1818
- * - Fallback to <link rel="manifest">, preferring the raw attribute over computed href.
1819
- * 2) Normalize href to absolute using ensureAbsoluteUrl (respects <base href>).
1820
- * 3) Handle data URLs inline:
1821
- * - data:...;base64,... → atob then JSON.parse
1822
- * - data:...,... → decodeURIComponent then JSON.parse
1823
- * 4) Fetch with credentials same-origin first; if that fails (e.g., CORS), attempt unauthenticated fetch.
1824
- * 5) Parse as JSON; if response body is text, parse the text as JSON.
1825
- */
1826
- async getPWAManifest(manifestUrl) {
1827
- let href = manifestUrl;
1828
- if (!href) {
1829
- const el = document.querySelector(
1830
- 'link[rel="manifest"]'
1831
- );
1832
- href = el?.getAttribute("href") || el?.href;
1833
- }
1834
- if (!href) return;
1835
- href = this.ensureAbsoluteUrl(href);
1836
- if (!href) return;
1837
- if (href.startsWith("data:")) {
1838
- try {
1839
- const comma = href.indexOf(",");
1840
- if (comma < 0) return;
1841
- const meta = href.slice(5, comma);
1842
- const data = href.slice(comma + 1);
1843
- const isBase64 = /;base64/i.test(meta);
1844
- const decoded = isBase64 ? atob(data) : decodeURIComponent(data);
1845
- return JSON.parse(decoded);
1846
- } catch {
1847
- return;
1848
- }
1849
- }
1850
- try {
1851
- const res = await fetch(href, { credentials: "same-origin" });
1852
- if (!res.ok) throw new Error(String(res.status));
1853
- try {
1854
- return await res.json();
1855
- } catch {
1856
- const t = await res.text();
1857
- return JSON.parse(t);
1858
- }
1859
- } catch {
1860
- try {
1861
- const res = await fetch(href);
1862
- if (!res.ok) return;
1863
- try {
1864
- return await res.json();
1865
- } catch {
1866
- const t = await res.text();
1867
- return JSON.parse(t);
1868
- }
1869
- } catch {
1870
- return;
1871
- }
1872
- }
1873
- }
1874
- };
1875
- function sanitizeSceneOptionsUnits(val) {
1876
- if (val?.defaultSize) {
1877
- const keys = ["width", "height", "depth"];
1878
- for (const k of keys) {
1879
- if (k in val.defaultSize && !isValidSceneUnit(val.defaultSize[k])) {
1880
- delete val.defaultSize[k];
1881
- }
1882
- }
1883
- }
1884
- if (val?.resizability) {
1885
- const keys = ["minWidth", "minHeight", "maxWidth", "maxHeight"];
1886
- for (const k of keys) {
1887
- if (k in val.resizability && !isValidSceneUnit(val.resizability[k])) {
1888
- delete val.resizability[k];
1889
- }
1890
- }
1891
- }
1892
- return val;
1893
- }
1894
- function pxToMeter(px) {
1895
- return pointToPhysical(px);
1896
- }
1897
- function meterToPx(meter) {
1898
- return physicalToPoint(meter);
1899
- }
1900
- function formatToNumber(str, targetUnit, defaultUnit) {
1901
- if (typeof str === "number") {
1902
- if (defaultUnit === "px" && targetUnit === "px" || defaultUnit === "m" && targetUnit === "m") {
1903
- return str;
1904
- }
1905
- if (defaultUnit === "px" && targetUnit === "m") {
1906
- return pxToMeter(str);
1907
- } else if (defaultUnit === "m" && targetUnit === "px") {
1908
- return meterToPx(str);
1909
- }
1910
- return str;
1911
- }
1912
- if (targetUnit === "m") {
1913
- if (str.endsWith("m")) {
1914
- return Number(str.slice(0, -1));
1915
- } else if (str.endsWith("px")) {
1916
- return pxToMeter(Number(str.slice(0, -2)));
1917
- } else {
1918
- throw new Error("formatToNumber: invalid str");
1919
- }
1920
- } else if (targetUnit === "px") {
1921
- if (str.endsWith("px")) {
1922
- return Number(str.slice(0, -2));
1923
- } else if (str.endsWith("m")) {
1924
- return meterToPx(Number(str.slice(0, -1)));
1925
- } else {
1926
- throw new Error("formatToNumber: invalid str");
1927
- }
1928
- } else {
1929
- throw new Error("formatToNumber: invalid targetUnit");
1930
- }
1931
- }
1932
- function formatSceneConfig(config, sceneType) {
1933
- const defaultSceneConfig2 = getSceneDefaultConfig(sceneType);
1934
- const errors = [];
1935
- const isWindow = sceneType === "window";
1936
- if (!isValidSpatialSceneType(sceneType)) {
1937
- errors.push(`sceneType`);
1938
- }
1939
- if (config.defaultSize) {
1940
- const iterKeys = ["width", "height", "depth"];
1941
- for (let k of iterKeys) {
1942
- if (!(k in config.defaultSize)) continue;
1943
- if (isValidSceneUnit(config.defaultSize[k])) {
1944
- ;
1945
- config.defaultSize[k] = formatToNumber(
1946
- config.defaultSize[k],
1947
- isWindow ? "px" : "m",
1948
- "px"
1949
- );
1950
- } else {
1951
- delete config.defaultSize[k];
1952
- errors.push(`defaultSize.${k}`);
1953
- }
1954
- }
1955
- }
1956
- if (config.resizability) {
1957
- const iterKeys = ["minWidth", "minHeight", "maxWidth", "maxHeight"];
1958
- for (let k of iterKeys) {
1959
- if (!(k in config.resizability)) continue;
1960
- if (isValidSceneUnit(config.resizability[k])) {
1961
- ;
1962
- config.resizability[k] = formatToNumber(
1963
- config.resizability[k],
1964
- "px",
1965
- "px"
1966
- );
1967
- } else {
1968
- delete config.resizability[k];
1969
- errors.push(`resizability.${k}`);
1970
- }
1971
- }
1972
- }
1973
- if (config.worldScaling) {
1974
- if (!isValidWorldScalingType(config.worldScaling)) {
1975
- config.worldScaling = "automatic";
1976
- errors.push("worldScaling");
1977
- }
1978
- }
1979
- if (config.worldAlignment) {
1980
- if (!isValidWorldAlignmentType(config.worldAlignment)) {
1981
- config.worldAlignment = "automatic";
1982
- errors.push("worldAlignment");
1983
- }
1984
- }
1985
- if (config.baseplateVisibility) {
1986
- if (!isValidBaseplateVisibilityType(config.baseplateVisibility)) {
1987
- config.baseplateVisibility = "automatic";
1988
- errors.push("baseplateVisibility");
1989
- }
1990
- }
1991
- return [config, errors];
1992
- }
1993
- function initScene(name, callback, options) {
1994
- return SceneManager.getInstance().initScene(name, callback, options);
1995
- }
1996
- function hijackWindowOpen(window2) {
1997
- SceneManager.getInstance().init(window2);
1998
- }
1999
- function hijackWindowATag(openedWindow) {
2000
- openedWindow.document.onclick = function(e) {
2001
- let element = e.target;
2002
- while (element) {
2003
- if (element.tagName == "A") {
2004
- if (handleATag(e, element)) {
2005
- return false;
2006
- }
2007
- return true;
2008
- }
2009
- if (element.parentElement) {
2010
- element = element.parentElement;
2011
- } else {
2012
- break;
2013
- }
2014
- }
2015
- };
2016
- }
2017
- function handleATag(event, link) {
2018
- if (event.defaultPrevented) return false;
2019
- const target = link.target;
2020
- const url = link.href;
2021
- if (target && target !== "_self") {
2022
- event.preventDefault();
2023
- window.open(url, target);
2024
- return true;
2025
- }
2026
- }
2027
- function getSceneDefaultConfig(sceneType) {
2028
- return sceneType === "window" ? xr_window_defaults || defaultSceneConfig : xr_volume_defaults || defaultSceneConfigVolume;
2029
- }
2030
- async function injectScenePolyfill() {
2031
- if (!window.opener) return;
2032
- const state = await SpatialScene.getInstance().getState();
2033
- if (state !== "pending" /* pending */) return;
2034
- function onContentLoaded(callback) {
2035
- if (document.readyState === "interactive" || document.readyState === "complete") {
2036
- callback();
2037
- } else {
2038
- document.addEventListener("DOMContentLoaded", callback);
2039
- }
2040
- }
2041
- onContentLoaded(async () => {
2042
- await SceneManager.getInstance().waitManifest();
2043
- const sceneType = window.xrCurrentSceneType ?? "window";
2044
- const rawDefault = getSceneDefaultConfig(sceneType);
2045
- const pre = deepCloneJSON(rawDefault);
2046
- let cfg = pre;
2047
- if (typeof window.xrCurrentSceneDefaults === "function") {
2048
- try {
2049
- cfg = await window.xrCurrentSceneDefaults?.(pre);
2050
- } catch (error) {
2051
- console.error(error);
2052
- }
2053
- }
2054
- await new Promise((resolve, reject) => {
2055
- setTimeout(() => {
2056
- resolve(null);
2057
- }, 1e3);
2058
- });
2059
- const mergedCfg = deepMergePlain(deepCloneJSON(rawDefault), cfg);
2060
- const [formattedConfig, errors] = formatSceneConfig(mergedCfg, sceneType);
2061
- if (errors.length > 0) {
2062
- console.warn(
2063
- `window.xrCurrentSceneDefaults with errors: ${errors.join(", ")}`
2064
- );
2065
- }
2066
- const finalCfg = {
2067
- ...formattedConfig,
2068
- type: sceneType
2069
- };
2070
- await SpatialScene.getInstance().updateSceneCreationConfig(finalCfg);
2071
- });
2072
- }
2073
- function injectSceneHook() {
2074
- hijackWindowOpen(window);
2075
- hijackWindowATag(window);
2076
- injectScenePolyfill();
2077
- }
2078
-
2079
- // src/SpatializedElementCreator.ts
2080
- init_JSBCommand();
2081
-
2082
- // src/Spatialized2DElement.ts
2083
- init_JSBCommand();
2084
-
2085
- // src/SpatializedElement.ts
2086
- init_JSBCommand();
2087
- init_SpatialWebEvent();
2088
-
2089
- // src/SpatialWebEventCreator.ts
2090
- function createSpatialEvent(type, detail) {
2091
- return new CustomEvent(type, {
2092
- bubbles: true,
2093
- cancelable: false,
2094
- detail
2095
- });
2096
- }
2097
-
2098
- // src/SpatializedElement.ts
2099
- var SpatializedElement = class extends SpatialObject {
2100
- /**
2101
- * Creates a new spatialized element with the specified ID.
2102
- * Registers the element to receive spatial events.
2103
- * @param id Unique identifier for this element
2104
- */
2105
- constructor(id) {
2106
- super(id);
2107
- this.id = id;
2108
- SpatialWebEvent.addEventReceiver(id, this.onReceiveEvent.bind(this));
2109
- }
2110
- /**
2111
- * Updates the transformation matrix of this element in 3D space.
2112
- * This affects the position, rotation, and scale of the element.
2113
- * @param matrix The new transformation matrix
2114
- * @returns Promise resolving when the transform is updated
2115
- */
2116
- async updateTransform(matrix) {
2117
- return new UpdateSpatializedElementTransform(this, matrix).execute();
2118
- }
2119
- /**
2120
- * Information about the element's bounding cube.
2121
- * Used for spatial calculations and hit testing.
2122
- */
2123
- _cubeInfo;
2124
- /**
2125
- * Gets the current cube information for this element.
2126
- * @returns The current CubeInfo or undefined if not set
2127
- */
2128
- get cubeInfo() {
2129
- return this._cubeInfo;
2130
- }
2131
- /**
2132
- * The current transformation matrix of this element.
2133
- */
2134
- _transform;
2135
- /**
2136
- * The inverse of the current transformation matrix.
2137
- * Used for converting world coordinates to local coordinates.
2138
- */
2139
- _transformInv;
2140
- /**
2141
- * Gets the current transformation matrix.
2142
- * @returns The current transformation matrix or undefined if not set
2143
- */
2144
- get transform() {
2145
- return this._transform;
2146
- }
2147
- /**
2148
- * Gets the inverse of the current transformation matrix.
2149
- * @returns The inverse transformation matrix or undefined if not set
2150
- */
2151
- get transformInv() {
2152
- return this._transformInv;
2153
- }
2154
- /**
2155
- * Processes events received from the WebSpatial environment.
2156
- * Handles various spatial events like transforms, gestures, and interactions.
2157
- * @param data The event data received from the WebSpatial system
2158
- */
2159
- onReceiveEvent(data) {
2160
- const { type } = data;
2161
- if (type === "objectdestroy" /* objectdestroy */) {
2162
- this.isDestroyed = true;
2163
- } else if (type === "spatialtap" /* spatialtap */) {
2164
- const event = createSpatialEvent(
2165
- "spatialtap" /* spatialtap */,
2166
- data.detail
2167
- );
2168
- this._onSpatialTap?.(event);
2169
- } else if (type === "spatialdragstart" /* spatialdragstart */) {
2170
- const dragStartEvent = createSpatialEvent(
2171
- "spatialdragstart" /* spatialdragstart */,
2172
- data.detail
2173
- );
2174
- this._onSpatialDragStart?.(dragStartEvent);
2175
- } else if (type === "spatialdrag" /* spatialdrag */) {
2176
- const event = createSpatialEvent(
2177
- "spatialdrag" /* spatialdrag */,
2178
- data.detail
2179
- );
2180
- this._onSpatialDrag?.(event);
2181
- } else if (type === "spatialdragend" /* spatialdragend */) {
2182
- const event = createSpatialEvent(
2183
- "spatialdragend" /* spatialdragend */,
2184
- data.detail
2185
- );
2186
- this._onSpatialDragEnd?.(event);
2187
- } else if (type === "spatialrotate" /* spatialrotate */) {
2188
- const event = createSpatialEvent(
2189
- "spatialrotate" /* spatialrotate */,
2190
- data.detail
2191
- );
2192
- this._onSpatialRotate?.(event);
2193
- } else if (type === "spatialrotateend" /* spatialrotateend */) {
2194
- const event = createSpatialEvent(
2195
- "spatialrotateend" /* spatialrotateend */,
2196
- data.detail
2197
- );
2198
- this._onSpatialRotateEnd?.(event);
2199
- } else if (type === "spatialmagnify" /* spatialmagnify */) {
2200
- const event = createSpatialEvent(
2201
- "spatialmagnify" /* spatialmagnify */,
2202
- data.detail
2203
- );
2204
- this._onSpatialMagnify?.(event);
2205
- } else if (type === "spatialmagnifyend" /* spatialmagnifyend */) {
2206
- const event = createSpatialEvent(
2207
- "spatialmagnifyend" /* spatialmagnifyend */,
2208
- data.detail
2209
- );
2210
- this._onSpatialMagnifyEnd?.(event);
2211
- }
2212
- }
2213
- _onSpatialTap;
2214
- set onSpatialTap(value) {
2215
- this._onSpatialTap = value;
2216
- this.updateProperties({
2217
- enableTapGesture: value !== void 0
2218
- });
2219
- }
2220
- _onSpatialDragStart;
2221
- set onSpatialDragStart(value) {
2222
- this._onSpatialDragStart = value;
2223
- this.updateProperties({
2224
- enableDragStartGesture: this._onSpatialDragStart !== void 0
2225
- });
2226
- }
2227
- _onSpatialDrag;
2228
- set onSpatialDrag(value) {
2229
- this._onSpatialDrag = value;
2230
- this.updateProperties({
2231
- enableDragGesture: this._onSpatialDrag !== void 0
2232
- });
2233
- }
2234
- _onSpatialDragEnd;
2235
- set onSpatialDragEnd(value) {
2236
- this._onSpatialDragEnd = value;
2237
- this.updateProperties({
2238
- enableDragEndGesture: value !== void 0
2239
- });
2240
- }
2241
- _onSpatialRotate;
2242
- set onSpatialRotate(value) {
2243
- this._onSpatialRotate = value;
2244
- this.updateProperties({
2245
- enableRotateGesture: this._onSpatialRotate !== void 0
2246
- });
2247
- }
2248
- _onSpatialRotateEnd;
2249
- set onSpatialRotateEnd(value) {
2250
- this._onSpatialRotateEnd = value;
2251
- this.updateProperties({
2252
- enableRotateEndGesture: value !== void 0
2253
- });
2254
- }
2255
- _onSpatialMagnify;
2256
- set onSpatialMagnify(value) {
2257
- this._onSpatialMagnify = value;
2258
- this.updateProperties({
2259
- enableMagnifyGesture: value !== void 0
2260
- });
2261
- }
2262
- _onSpatialMagnifyEnd;
2263
- set onSpatialMagnifyEnd(value) {
2264
- this._onSpatialMagnifyEnd = value;
2265
- this.updateProperties({
2266
- enableMagnifyEndGesture: value !== void 0
2267
- });
2268
- }
2269
- /**
2270
- * Cleans up resources when this element is destroyed.
2271
- * Removes event receivers to prevent memory leaks.
2272
- */
2273
- onDestroy() {
2274
- SpatialWebEvent.removeEventReceiver(this.id);
2275
- }
2276
- };
2277
-
2278
- // src/Spatialized2DElement.ts
2279
- var Spatialized2DElement = class extends SpatializedElement {
2280
- /**
2281
- * Creates a new spatialized 2D element.
2282
- * @param id Unique identifier for this element
2283
- * @param windowProxy Reference to the window object containing the 2D content
2284
- */
2285
- constructor(id, windowProxy) {
2286
- super(id);
2287
- this.windowProxy = windowProxy;
2288
- hijackWindowATag(windowProxy);
2289
- }
2290
- /**
2291
- * Updates the properties of this 2D element.
2292
- * This can include size, position, background, and other visual properties.
2293
- * @param properties Partial set of properties to update
2294
- * @returns Promise resolving when the update is complete
2295
- */
2296
- async updateProperties(properties) {
2297
- return new UpdateSpatialized2DElementProperties(this, properties).execute();
2298
- }
2299
- /**
2300
- * Adds a child spatialized element to this 2D element.
2301
- * This allows for creating hierarchical structures of spatial elements.
2302
- * @param element The child element to add
2303
- * @returns Promise resolving when the element is added
2304
- */
2305
- async addSpatializedElement(element) {
2306
- return new AddSpatializedElementToSpatialized2DElement(
2307
- this,
2308
- element
2309
- ).execute();
2310
- }
2311
- };
2312
-
2313
- // src/SpatializedStatic3DElement.ts
2314
- init_JSBCommand();
2315
- var SpatializedStatic3DElement = class extends SpatializedElement {
2316
- /**
2317
- * Creates a new spatialized static 3D element with the specified ID and URL.
2318
- * Registers the element to receive spatial events.
2319
- * @param id Unique identifier for this element
2320
- * @param modelURL URL of the 3D model
2321
- * @param sources Optional fallback model sources
2322
- */
2323
- constructor(id, modelURL, sources) {
2324
- super(id);
2325
- this.modelURL = modelURL;
2326
- this.sources = sources;
2327
- }
2328
- /**
2329
- * Promise resolver for the ready state.
2330
- * Used to resolve the ready promise when the model is loaded.
2331
- */
2332
- _readyResolve;
2333
- /**
2334
- * Caches the last model URL to detect changes.
2335
- * Used to reset the ready promise when the model URL changes.
2336
- */
2337
- modelURL;
2338
- /**
2339
- * Caches the last sources array to detect changes.
2340
- */
2341
- sources;
2342
- /**
2343
- * The model URL that was successfully loaded by the native runtime.
2344
- */
2345
- _currentSrc = "";
2346
- get currentSrc() {
2347
- return this._currentSrc;
2348
- }
2349
- /**
2350
- * Creates a new promise for tracking the ready state of the model.
2351
- * @returns Promise that resolves when the model is loaded (true) or fails to load (false)
2352
- */
2353
- createReadyPromise() {
2354
- this._readyResolve?.(false);
2355
- return new Promise((resolve) => {
2356
- this._readyResolve = resolve;
2357
- });
2358
- }
2359
- /**
2360
- * Promise that resolves when the model is loaded.
2361
- * Resolves to true on successful load, false on failure.
2362
- */
2363
- ready = this.createReadyPromise();
2364
- /**
2365
- * Updates the properties of this static 3D element.
2366
- * Handles special case for modelURL changes by resetting the ready promise.
2367
- * @param properties Partial set of properties to update
2368
- * @returns Promise resolving when the update is complete
2369
- */
2370
- async updateProperties(properties) {
2371
- let needsReadyReset = false;
2372
- if (properties.modelURL !== void 0) {
2373
- if (this.modelURL !== properties.modelURL) {
2374
- this.modelURL = properties.modelURL;
2375
- needsReadyReset = true;
2376
- }
2377
- }
2378
- if (properties.sources !== void 0) {
2379
- const prevJson = JSON.stringify(this.sources);
2380
- const nextJson = JSON.stringify(properties.sources);
2381
- if (prevJson !== nextJson) {
2382
- this.sources = properties.sources;
2383
- needsReadyReset = true;
2384
- }
2385
- }
2386
- if (needsReadyReset) {
2387
- this.ready = this.createReadyPromise();
2388
- }
2389
- if (properties.autoplay !== void 0) {
2390
- this._autoplay = properties.autoplay;
2391
- }
2392
- if (properties.loop !== void 0) {
2393
- this._loop = properties.loop;
2394
- }
2395
- if (properties.playbackRate !== void 0) {
2396
- this._playbackRate = properties.playbackRate;
2397
- }
2398
- return new UpdateSpatializedStatic3DElementProperties(
2399
- this,
2400
- properties
2401
- ).execute();
2402
- }
2403
- /**
2404
- * Total animation duration in seconds, synced from native.
2405
- */
2406
- _duration = 0;
2407
- /**
2408
- * Returns the total animation duration in seconds.
2409
- */
2410
- get duration() {
2411
- return this._duration;
2412
- }
2413
- /**
2414
- * Playback speed multiplier.
2415
- */
2416
- _playbackRate = 1;
2417
- /**
2418
- * Returns the current playback rate.
2419
- */
2420
- get playbackRate() {
2421
- return this._playbackRate;
2422
- }
2423
- /**
2424
- * Sets the playback rate and sends it to native.
2425
- */
2426
- set playbackRate(value) {
2427
- this.updateProperties({ playbackRate: value });
2428
- }
2429
- /**
2430
- * Whether the animation is currently paused.
2431
- */
2432
- _paused = true;
2433
- /**
2434
- * Returns whether the animation is currently paused.
2435
- */
2436
- get paused() {
2437
- return this._paused;
2438
- }
2439
- /**
2440
- * Callback for animation state changes.
2441
- */
2442
- _onAnimationStateChangeCallback;
2443
- /**
2444
- * Sets the callback for animation state changes.
2445
- */
2446
- set onAnimationStateChangeCallback(callback) {
2447
- this._onAnimationStateChangeCallback = callback;
2448
- }
2449
- /**
2450
- * Starts or resumes animation playback.
2451
- * @returns Promise resolving when the command is sent
2452
- */
2453
- async play() {
2454
- this._paused = false;
2455
- await this.updateProperties({ animationPaused: false });
2456
- }
2457
- /**
2458
- * Pauses animation playback.
2459
- * @returns Promise resolving when the command is sent
2460
- */
2461
- async pause() {
2462
- this._paused = true;
2463
- await this.updateProperties({ animationPaused: true });
2464
- }
2465
- /**
2466
- * Processes events received from the WebSpatial environment.
2467
- * Handles model loading events in addition to base spatial events.
2468
- * @param data The event data received from the WebSpatial system
2469
- */
2470
- onReceiveEvent(data) {
2471
- if (data.type === "modelloaded" /* modelloaded */) {
2472
- this._currentSrc = data.detail?.src ?? this.modelURL ?? "";
2473
- this._onLoadCallback?.();
2474
- this._readyResolve?.(true);
2475
- } else if (data.type === "modelloadfailed" /* modelloadfailed */) {
2476
- this._onLoadFailureCallback?.();
2477
- this._readyResolve?.(false);
2478
- } else if (data.type === "animationstatechange" /* animationstatechange */) {
2479
- this._paused = data.detail.paused;
2480
- this._duration = data.detail.duration;
2481
- this._onAnimationStateChangeCallback?.(data.detail);
2482
- } else {
2483
- super.onReceiveEvent(data);
2484
- }
2485
- }
2486
- /**
2487
- * Whether the model should automatically play its first animation on load.
2488
- */
2489
- _autoplay = false;
2490
- /**
2491
- * Returns whether autoplay is enabled for this element.
2492
- */
2493
- get autoplay() {
2494
- return this._autoplay;
2495
- }
2496
- /**
2497
- * Whether the model animation should loop continuously.
2498
- */
2499
- _loop = false;
2500
- /**
2501
- * Returns whether loop is enabled for this element.
2502
- */
2503
- get loop() {
2504
- return this._loop;
2505
- }
2506
- /**
2507
- * Callback function for successful model loading.
2508
- */
2509
- _onLoadCallback;
2510
- /**
2511
- * Sets the callback function for successful model loading.
2512
- * @param callback Function to call when the model is loaded successfully
2513
- */
2514
- set onLoadCallback(callback) {
2515
- this._onLoadCallback = callback;
2516
- }
2517
- /**
2518
- * Callback function for model loading failure.
2519
- */
2520
- _onLoadFailureCallback;
2521
- /**
2522
- * Sets the callback function for model loading failure.
2523
- * @param callback Function to call when the model fails to load
2524
- */
2525
- set onLoadFailureCallback(callback) {
2526
- this._onLoadFailureCallback = callback;
2527
- }
2528
- updateModelTransform(transform) {
2529
- const modelTransform = Array.from(transform.toFloat64Array());
2530
- this.updateProperties({ modelTransform });
2531
- }
2532
- };
2533
-
2534
- // src/SpatializedDynamic3DElement.ts
2535
- init_JSBCommand();
2536
- var SpatializedDynamic3DElement = class extends SpatializedElement {
2537
- children = [];
2538
- events = {};
2539
- constructor(id) {
2540
- super(id);
2541
- }
2542
- async addEntity(entity) {
2543
- const ans = new SetParentForEntityCommand(entity.id, this.id).execute();
2544
- this.children.push(entity);
2545
- entity.parent = this;
2546
- return ans;
2547
- }
2548
- addEvent(type, callback) {
2549
- this.events[type] = callback;
2550
- }
2551
- removeEvent(eventName) {
2552
- if (this.events[eventName]) {
2553
- delete this.events[eventName];
2554
- }
2555
- }
2556
- dispatchEvent(evt) {
2557
- this.events[evt.type]?.(evt);
2558
- }
2559
- async updateProperties(properties) {
2560
- return new UpdateSpatializedDynamic3DElementProperties(
2561
- this,
2562
- properties
2563
- ).execute();
2564
- }
2565
- };
2566
-
2567
- // src/SpatializedElementCreator.ts
2568
- async function createSpatialized2DElement() {
2569
- const result = await new createSpatialized2DElementCommand().execute();
2570
- if (!result.success) {
2571
- throw new Error("createSpatialized2DElement failed");
2572
- } else {
2573
- const { id, windowProxy } = result.data;
2574
- windowProxy.document.head.innerHTML = `<meta name="viewport" content="width=device-width, initial-scale=1">
2575
- <base href="${document.baseURI}">`;
2576
- return new Spatialized2DElement(id, windowProxy);
2577
- }
2578
- }
2579
- async function createSpatializedStatic3DElement(modelURL, sources) {
2580
- const result = await new CreateSpatializedStatic3DElementCommand(
2581
- modelURL,
2582
- sources
2583
- ).execute();
2584
- if (!result.success) {
2585
- throw new Error("createSpatializedStatic3DElement failed");
2586
- } else {
2587
- const { id } = result.data;
2588
- return new SpatializedStatic3DElement(id, modelURL, sources);
2589
- }
2590
- }
2591
- async function createSpatializedDynamic3DElement() {
2592
- const result = await new CreateSpatializedDynamic3DElementCommand().execute();
2593
- if (!result.success) {
2594
- throw new Error("createSpatializedDynamic3DElement failed");
2595
- } else {
2596
- const { id } = result.data;
2597
- return new SpatializedDynamic3DElement(id);
2598
- }
2599
- }
2600
-
2601
- // src/reality/Attachment.ts
2602
- init_JSBCommand();
2603
- var Attachment = class extends SpatialObject {
2604
- constructor(id, windowProxy, options) {
2605
- super(id);
2606
- this.windowProxy = windowProxy;
2607
- this.options = options;
2608
- }
2609
- getContainer() {
2610
- return this.windowProxy.document.body;
2611
- }
2612
- getWindowProxy() {
2613
- return this.windowProxy;
2614
- }
2615
- async update(options) {
2616
- if (this.isDestroyed) return;
2617
- if (options.position) this.options.position = options.position;
2618
- if (options.size) this.options.size = options.size;
2619
- return new UpdateAttachmentEntityCommand(this.id, options).execute();
2620
- }
2621
- };
2622
- async function createAttachmentEntity(options) {
2623
- const result = await new CreateAttachmentEntityCommand(options).execute();
2624
- if (!result.success) {
2625
- throw new Error("createAttachmentEntity failed: " + result?.errorMessage);
2626
- }
2627
- const { id, windowProxy } = result.data;
2628
- await new InitializeAttachmentCommand(id, options).execute();
2629
- return new Attachment(id, windowProxy, options);
2630
- }
2631
-
2632
- // src/reality/realityCreator.ts
2633
- init_JSBCommand();
2634
-
2635
- // src/reality/entity/SpatialEntity.ts
2636
- init_JSBCommand();
2637
- init_JSBCommand();
2638
- init_SpatialWebEvent();
2639
- var SpatialEntity = class extends SpatialObject {
2640
- constructor(id, userData) {
2641
- super(id);
2642
- this.userData = userData;
2643
- SpatialWebEvent.addEventReceiver(id, this.onReceiveEvent);
2644
- }
2645
- position = { x: 0, y: 0, z: 0 };
2646
- rotation = { x: 0, y: 0, z: 0 };
2647
- scale = { x: 1, y: 1, z: 1 };
2648
- events = {};
2649
- children = [];
2650
- parent = null;
2651
- _enableInput = false;
2652
- get enableInput() {
2653
- return this._enableInput;
2654
- }
2655
- set enableInput(value) {
2656
- if (this._enableInput === value) return;
2657
- this._enableInput = value;
2658
- void this.updateEntityEvent("spatialtap", value).catch((err) => {
2659
- console.error("enableInput updateEntityEvent failed", "spatialtap", err);
2660
- if (this._enableInput === value) {
2661
- this._enableInput = !value;
2662
- }
2663
- });
2664
- }
2665
- async addComponent(component) {
2666
- return new AddComponentToEntityCommand(this, component).execute();
2667
- }
2668
- async removeComponent(component) {
2669
- return new RemoveComponentFromEntityCommand(this, component).execute();
2670
- }
2671
- async setPosition(position) {
2672
- return this.updateTransform({ position });
2673
- }
2674
- async setRotation(rotation) {
2675
- return this.updateTransform({ rotation });
2676
- }
2677
- async setScale(scale) {
2678
- return this.updateTransform({ scale });
2679
- }
2680
- async addEntity(ent) {
2681
- const ans = await new SetParentForEntityCommand(ent.id, this.id).execute();
2682
- this.children.push(ent);
2683
- ent.parent = this;
2684
- return ans;
2685
- }
2686
- async removeFromParent() {
2687
- const ans = await new SetParentForEntityCommand(
2688
- this.id,
2689
- void 0
2690
- ).execute();
2691
- if (this.parent) {
2692
- this.parent.children = this.parent.children.filter(
2693
- (child) => child.id !== this.id
2694
- );
2695
- this.parent = null;
2696
- }
2697
- return ans;
2698
- }
2699
- async updateTransform(properties) {
2700
- this.position = properties.position ?? this.position;
2701
- this.rotation = properties.rotation ?? this.rotation;
2702
- this.scale = properties.scale ?? this.scale;
2703
- return new UpdateEntityPropertiesCommand(this, properties).execute();
2704
- }
2705
- async addEvent(type, callback) {
2706
- if (this.events[type]) {
2707
- this.events[type] = callback;
2708
- } else {
2709
- try {
2710
- await this.updateEntityEvent(type, true);
2711
- this.events[type] = callback;
2712
- } catch (error) {
2713
- console.error("addEvent failed", type);
2714
- }
2715
- }
2716
- }
2717
- async removeEvent(eventName) {
2718
- if (this.events[eventName]) {
2719
- delete this.events[eventName];
2720
- try {
2721
- await this.updateEntityEvent(eventName, false);
2722
- } catch (error) {
2723
- console.error("removeEvent failed", eventName);
2724
- }
2725
- }
2726
- }
2727
- async updateEntityEvent(eventName, isEnable) {
2728
- return new UpdateEntityEventCommand(this, eventName, isEnable).execute();
2729
- }
2730
- onReceiveEvent = (data) => {
2731
- const { type } = data;
2732
- if (type === "objectdestroy" /* objectdestroy */) {
2733
- this.isDestroyed = true;
2734
- } else if (type === "spatialtap" /* spatialtap */) {
2735
- const evt = createSpatialEvent("spatialtap" /* spatialtap */, data.detail);
2736
- this.dispatchEvent(evt);
2737
- } else if (type === "spatialdragstart" /* spatialdragstart */) {
2738
- const evt = createSpatialEvent(
2739
- "spatialdragstart" /* spatialdragstart */,
2740
- data.detail
2741
- );
2742
- this.dispatchEvent(evt);
2743
- } else if (type === "spatialdrag" /* spatialdrag */) {
2744
- const evt = createSpatialEvent("spatialdrag" /* spatialdrag */, data.detail);
2745
- this.dispatchEvent(evt);
2746
- } else if (type === "spatialdragend" /* spatialdragend */) {
2747
- const evt = createSpatialEvent(
2748
- "spatialdragend" /* spatialdragend */,
2749
- data.detail
2750
- );
2751
- this.dispatchEvent(evt);
2752
- } else if (type === "spatialrotate" /* spatialrotate */) {
2753
- const evt = createSpatialEvent(
2754
- "spatialrotate" /* spatialrotate */,
2755
- data.detail
2756
- );
2757
- this.dispatchEvent(evt);
2758
- } else if (type === "spatialrotateend" /* spatialrotateend */) {
2759
- const evt = createSpatialEvent(
2760
- "spatialrotateend" /* spatialrotateend */,
2761
- data.detail
2762
- );
2763
- this.dispatchEvent(evt);
2764
- } else if (type === "spatialmagnify" /* spatialmagnify */) {
2765
- const evt = createSpatialEvent(
2766
- "spatialmagnify" /* spatialmagnify */,
2767
- data.detail
2768
- );
2769
- this.dispatchEvent(evt);
2770
- } else if (type === "spatialmagnifyend" /* spatialmagnifyend */) {
2771
- const evt = createSpatialEvent(
2772
- "spatialmagnifyend" /* spatialmagnifyend */,
2773
- data.detail
2774
- );
2775
- this.dispatchEvent(evt);
2776
- }
2777
- };
2778
- dispatchEvent(evt) {
2779
- if (!evt.__origin) {
2780
- Object.defineProperty(evt, "__origin", { value: this, enumerable: false });
2781
- }
2782
- this.events[evt.type]?.(evt);
2783
- if (evt.bubbles && !evt.cancelBubble) {
2784
- if (this.parent) {
2785
- this.parent.dispatchEvent(evt);
2786
- }
2787
- }
2788
- }
2789
- onDestroy() {
2790
- SpatialWebEvent.removeEventReceiver(this.id);
2791
- this.children.forEach((child) => {
2792
- child.parent = null;
2793
- });
2794
- this.children = [];
2795
- if (this.parent) {
2796
- this.parent.children = this.parent.children.filter(
2797
- (child) => child.id !== this.id
2798
- );
2799
- this.parent = null;
2800
- }
2801
- }
2802
- // onUpdate(properties: SpatialEntityProperties) {
2803
- // this.position = properties.position
2804
- // this.rotation = properties.rotation
2805
- // this.scale = properties.scale
2806
- // }
2807
- async convertFromEntityToEntity(fromEntityId, toEntityId, position) {
2808
- return new ConvertFromEntityToEntityCommand(
2809
- fromEntityId,
2810
- toEntityId,
2811
- position
2812
- ).execute();
2813
- }
2814
- async convertFromEntityToScene(fromEntityId, position) {
2815
- return new ConvertFromEntityToSceneCommand(fromEntityId, position).execute();
2816
- }
2817
- async convertFromSceneToEntity(entityId, position) {
2818
- return new ConvertFromSceneToEntityCommand(entityId, position).execute();
2819
- }
2820
- };
2821
-
2822
- // src/reality/entity/SpatialModelEntity.ts
2823
- init_JSBCommand();
2824
- var SpatialModelEntity = class extends SpatialEntity {
2825
- constructor(id, options, userData) {
2826
- super(id, userData);
2827
- this.id = id;
2828
- this.options = options;
2829
- this.userData = userData;
2830
- }
2831
- async setMaterials(materials) {
2832
- return new SetMaterialsOnEntityCommand(this.id, materials).execute();
2833
- }
2834
- };
2835
-
2836
- // src/reality/component/SpatialComponent.ts
2837
- init_SpatialWebEvent();
2838
- var SpatialComponent = class extends SpatialObject {
2839
- constructor(id) {
2840
- super(id);
2841
- SpatialWebEvent.addEventReceiver(id, this.onReceiveEvent);
2842
- }
2843
- onReceiveEvent = (data) => {
2844
- const { type } = data;
2845
- if (type === "objectdestroy" /* objectdestroy */) {
2846
- this.isDestroyed = true;
2847
- }
2848
- };
2849
- };
2850
-
2851
- // src/reality/component/ModelComponent.ts
2852
- var ModelComponent = class extends SpatialComponent {
2853
- constructor(id, options) {
2854
- super(id);
2855
- this.options = options;
2856
- }
2857
- };
2858
-
2859
- // src/reality/material/SpatialUnlitMaterial.ts
2860
- init_JSBCommand();
2861
-
2862
- // src/reality/material/SpatialMaterial.ts
2863
- var SpatialMaterial = class extends SpatialObject {
2864
- constructor(id, type) {
2865
- super(id);
2866
- this.id = id;
2867
- this.type = type;
2868
- this.type = type;
2869
- }
2870
- };
2871
-
2872
- // src/reality/material/SpatialUnlitMaterial.ts
2873
- var SpatialUnlitMaterial = class extends SpatialMaterial {
2874
- constructor(id, options) {
2875
- super(id, "unlit");
2876
- this.id = id;
2877
- this.options = options;
2878
- }
2879
- updateProperties(properties) {
2880
- return new UpdateUnlitMaterialProperties(this, properties).execute();
2881
- }
2882
- };
2883
-
2884
- // src/reality/resource/SpatialModelAsset.ts
2885
- var SpatialModelAsset = class extends SpatialObject {
2886
- constructor(id, options) {
2887
- super(id);
2888
- this.id = id;
2889
- this.options = options;
2890
- }
2891
- };
2892
-
2893
- // src/reality/realityCreator.ts
2894
- async function createSpatialEntity(userData) {
2895
- const result = await new CreateSpatialEntityCommand(userData?.name).execute();
2896
- if (!result.success) {
2897
- throw new Error("createSpatialEntity failed:" + result?.errorMessage);
2898
- } else {
2899
- const { id } = result.data;
2900
- return new SpatialEntity(id, userData);
2901
- }
2902
- }
2903
- async function createSpatialGeometry(ctor, options) {
2904
- const result = await new CreateSpatialGeometryCommand(
2905
- ctor.type,
2906
- options
2907
- ).execute();
2908
- if (!result.success) {
2909
- throw new Error("createSpatialGeometry failed:" + result?.errorMessage);
2910
- } else {
2911
- const { id } = result.data;
2912
- return new ctor(id, options);
2913
- }
2914
- }
2915
- async function createSpatialUnlitMaterial(options) {
2916
- const result = await new CreateSpatialUnlitMaterialCommand(options).execute();
2917
- if (!result.success) {
2918
- throw new Error("createSpatialUnlitMaterial failed:" + result?.errorMessage);
2919
- } else {
2920
- const { id } = result.data;
2921
- return new SpatialUnlitMaterial(id, options);
2922
- }
2923
- }
2924
- async function createModelComponent(options) {
2925
- const result = await new CreateModelComponentCommand(options).execute();
2926
- if (!result.success) {
2927
- throw new Error("createModelComponent failed:" + result?.errorMessage);
2928
- } else {
2929
- const { id } = result.data;
2930
- return new ModelComponent(id, options);
2931
- }
2932
- }
2933
- async function createSpatialModelEntity(options, userData) {
2934
- const result = await new CreateSpatialModelEntityCommand(options).execute();
2935
- if (!result.success) {
2936
- throw new Error("createSpatialModelEntity failed:" + result?.errorMessage);
2937
- } else {
2938
- const { id } = result.data;
2939
- return new SpatialModelEntity(id, options, userData);
2940
- }
2941
- }
2942
- async function createModelAsset(options) {
2943
- const result = await new CreateModelAssetCommand(options).execute();
2944
- if (!result.success) {
2945
- throw new Error("createModelAsset failed:" + result?.errorMessage);
2946
- } else {
2947
- const { id } = result.data;
2948
- return new SpatialModelAsset(id, options);
2949
- }
2950
- }
2951
-
2952
- // src/reality/geometry/SpatialGeometry.ts
2953
- var SpatialGeometry = class extends SpatialObject {
2954
- constructor(id, options) {
2955
- super(id);
2956
- this.id = id;
2957
- this.options = options;
2958
- }
2959
- static type;
2960
- };
2961
-
2962
- // src/reality/geometry/SpatialBoxGeometry.ts
2963
- var SpatialBoxGeometry = class extends SpatialGeometry {
2964
- constructor(id, options) {
2965
- super(id, options);
2966
- this.id = id;
2967
- this.options = options;
2968
- }
2969
- static type = "BoxGeometry";
2970
- };
2971
-
2972
- // src/reality/geometry/SpatialSphereGeometry.ts
2973
- var SpatialSphereGeometry = class extends SpatialGeometry {
2974
- constructor(id, options) {
2975
- super(id, options);
2976
- this.id = id;
2977
- this.options = options;
2978
- }
2979
- static type = "SphereGeometry";
2980
- };
2981
-
2982
- // src/reality/geometry/SpatialCylinderGeometry.ts
2983
- var SpatialCylinderGeometry = class extends SpatialGeometry {
2984
- constructor(id, options) {
2985
- super(id, options);
2986
- this.id = id;
2987
- this.options = options;
2988
- }
2989
- static type = "CylinderGeometry";
2990
- };
2991
-
2992
- // src/reality/geometry/SpatialPlaneGeometry.ts
2993
- var SpatialPlaneGeometry = class extends SpatialGeometry {
2994
- constructor(id, options) {
2995
- super(id, options);
2996
- this.id = id;
2997
- this.options = options;
2998
- }
2999
- static type = "PlaneGeometry";
3000
- };
3001
-
3002
- // src/reality/geometry/SpatialConeGeometry.ts
3003
- var SpatialConeGeometry = class extends SpatialGeometry {
3004
- constructor(id, options) {
3005
- super(id, options);
3006
- this.id = id;
3007
- this.options = options;
3008
- }
3009
- static type = "ConeGeometry";
3010
- };
3011
-
3012
- // src/SpatialSession.ts
3013
- var SpatialSession = class {
3014
- /**
3015
- * Gets the singleton instance of the spatial scene.
3016
- * The spatial scene is the root container for all spatial elements.
3017
- * @returns The SpatialScene singleton instance
3018
- */
3019
- getSpatialScene() {
3020
- return SpatialScene.getInstance();
3021
- }
3022
- /**
3023
- * Creates a new 2D element that can be spatialized in the 3D environment.
3024
- * 2D elements represent HTML content that can be positioned in 3D space.
3025
- * @returns Promise resolving to a new Spatialized2DElement instance
3026
- */
3027
- createSpatialized2DElement() {
3028
- return createSpatialized2DElement();
3029
- }
3030
- /**
3031
- * Creates a new static 3D element with an optional model URL.
3032
- * Static 3D elements represent pre-built 3D models that can be loaded from a URL.
3033
- * @param modelURL Optional URL to the 3D model to load
3034
- * @returns Promise resolving to a new SpatializedStatic3DElement instance
3035
- */
3036
- createSpatializedStatic3DElement(modelURL, sources) {
3037
- return createSpatializedStatic3DElement(modelURL, sources);
3038
- }
3039
- /**
3040
- * Initializes the spatial scene with custom configuration.
3041
- * This is a reference to the initScene function from scene-polyfill.
3042
- */
3043
- initScene = initScene;
3044
- /**
3045
- * Creates a new dynamic 3D element that can be manipulated at runtime.
3046
- * Dynamic 3D elements allow for programmatic creation and modification of 3D content.
3047
- * @returns Promise resolving to a new SpatializedDynamic3DElement instance
3048
- */
3049
- createSpatializedDynamic3DElement() {
3050
- return createSpatializedDynamic3DElement();
3051
- }
3052
- /**
3053
- * Creates a new spatial entity with an optional name.
3054
- * Entities are the basic building blocks for creating custom 3D content.
3055
- * @param name Optional name for the entity
3056
- * @returns Promise resolving to a new SpatialEntity instance
3057
- */
3058
- createEntity(userData) {
3059
- return createSpatialEntity(userData);
3060
- }
3061
- /**
3062
- * Creates a box geometry with optional configuration.
3063
- * @param options Configuration options for the box geometry
3064
- * @returns Promise resolving to a new SpatialBoxGeometry instance
3065
- */
3066
- createBoxGeometry(options = {}) {
3067
- return createSpatialGeometry(SpatialBoxGeometry, options);
3068
- }
3069
- /**
3070
- * Creates a plane geometry with optional configuration.
3071
- * @param options Configuration options for the plane geometry
3072
- * @returns Promise resolving to a new SpatialPlaneGeometry instance
3073
- */
3074
- createPlaneGeometry(options = {}) {
3075
- return createSpatialGeometry(SpatialPlaneGeometry, options);
3076
- }
3077
- /**
3078
- * Creates a sphere geometry with optional configuration.
3079
- * @param options Configuration options for the sphere geometry
3080
- * @returns Promise resolving to a new SpatialSphereGeometry instance
3081
- */
3082
- createSphereGeometry(options = {}) {
3083
- return createSpatialGeometry(SpatialSphereGeometry, options);
3084
- }
3085
- /**
3086
- * Creates a cone geometry with the specified configuration.
3087
- * @param options Configuration options for the cone geometry
3088
- * @returns Promise resolving to a new SpatialConeGeometry instance
3089
- */
3090
- createConeGeometry(options) {
3091
- return createSpatialGeometry(SpatialConeGeometry, options);
3092
- }
3093
- /**
3094
- * Creates a cylinder geometry with the specified configuration.
3095
- * @param options Configuration options for the cylinder geometry
3096
- * @returns Promise resolving to a new SpatialCylinderGeometry instance
3097
- */
3098
- createCylinderGeometry(options) {
3099
- return createSpatialGeometry(SpatialCylinderGeometry, options);
3100
- }
3101
- /**
3102
- * Creates a model component with the specified configuration.
3103
- * Model components are used to add 3D model rendering capabilities to entities.
3104
- * @param options Configuration options for the model component
3105
- * @returns Promise resolving to a new ModelComponent instance
3106
- */
3107
- createModelComponent(options) {
3108
- return createModelComponent(options);
3109
- }
3110
- /**
3111
- * Creates an unlit material with the specified configuration.
3112
- * Unlit materials don't respond to lighting in the scene.
3113
- * @param options Configuration options for the unlit material
3114
- * @returns Promise resolving to a new SpatialUnlitMaterial instance
3115
- */
3116
- createUnlitMaterial(options) {
3117
- return createSpatialUnlitMaterial(options);
3118
- }
3119
- /**
3120
- * Creates a model asset with the specified configuration.
3121
- * Model assets represent 3D model resources that can be used by entities.
3122
- * @param options Configuration options for the model asset
3123
- * @returns Promise resolving to a new SpatialModelAsset instance
3124
- */
3125
- createModelAsset(options) {
3126
- return createModelAsset(options);
3127
- }
3128
- /**
3129
- * Creates a spatial model entity with the specified configuration.
3130
- * This is a convenience method for creating an entity with a model component.
3131
- * @param options Configuration options for the spatial model entity
3132
- * @returns Promise resolving to a new SpatialModelEntity instance
3133
- */
3134
- createSpatialModelEntity(options, userData) {
3135
- return createSpatialModelEntity(options, userData);
3136
- }
3137
- /**
3138
- * Creates an attachment entity that renders 2D HTML content as a child
3139
- * of a 3D entity in the scene graph.
3140
- * @param options Configuration options including parent entity ID, position, and size
3141
- * @returns Promise resolving to a new Attachment instance
3142
- */
3143
- createAttachmentEntity(options) {
3144
- return createAttachmentEntity(options);
3145
- }
3146
- };
3147
-
3148
- // src/Spatial.ts
3149
- init_SpatialWebEvent();
3150
- var Spatial = class {
3151
- wsAppShellVersionFromUA;
3152
- /**
3153
- * Requests a spatial session object from the browser.
3154
- * This is the primary method to initialize spatial functionality.
3155
- * @returns The SpatialSession instance or null if not available in the current browser
3156
- * [TODO] discuss implications of this not being async
3157
- */
3158
- requestSession() {
3159
- if (this.runInSpatialWeb()) {
3160
- SpatialWebEvent.init();
3161
- return new SpatialSession();
3162
- } else {
3163
- return null;
3164
- }
3165
- }
3166
- /**
3167
- * Checks if the current page is running in a spatial web environment.
3168
- * This method detects if the application is running in a WebSpatial-compatible browser.
3169
- * @returns True if running in a spatial web environment, false otherwise
3170
- */
3171
- runInSpatialWeb() {
3172
- if (navigator.userAgent.indexOf("WebSpatial/") >= 0) {
3173
- return true;
3174
- }
3175
- return false;
3176
- }
3177
- getShellVersionFromUA() {
3178
- if (this.wsAppShellVersionFromUA !== void 0) {
3179
- return this.wsAppShellVersionFromUA;
3180
- }
3181
- if (typeof navigator === "undefined" || typeof navigator.userAgent !== "string") {
3182
- this.wsAppShellVersionFromUA = null;
3183
- return null;
3184
- }
3185
- const match = navigator.userAgent.match(
3186
- /WSAppShell\/(\d+(?:\.\d+){2}(?:[-+][0-9A-Za-z.-]+)*)/
3187
- );
3188
- this.wsAppShellVersionFromUA = match ? match[1] : "1.3.0";
3189
- return this.wsAppShellVersionFromUA;
3190
- }
3191
- /** @deprecated
3192
- * Checks if WebSpatial is supported in the current environment.
3193
- * Verifies compatibility between native and client versions.
3194
- * @returns True if web spatial is supported by this webpage
3195
- */
3196
- isSupported() {
3197
- return true;
3198
- }
3199
- /** @deprecated
3200
- * Gets the native WebSpatial version from the browser environment.
3201
- * The version format follows semantic versioning (x.x.x).
3202
- * @returns Native version string in format "x.x.x"
3203
- */
3204
- getNativeVersion() {
3205
- if (window.__WebSpatialData && window.__WebSpatialData.getNativeVersion) {
3206
- return window.__WebSpatialData.getNativeVersion();
3207
- }
3208
- return window.WebSpatailNativeVersion === "WS_SHELL_VERSION" ? this.getClientVersion() : window.WebSpatailNativeVersion;
3209
- }
3210
- /** @deprecated
3211
- * Gets the client SDK version.
3212
- * The version format follows semantic versioning (x.x.x).
3213
- * @returns Client SDK version string in format "x.x.x"
3214
- */
3215
- getClientVersion() {
3216
- return "1.6.1";
3217
- }
3218
- };
3219
-
3220
- // src/index.ts
3221
- init_ssr_polyfill();
3222
-
3223
- // src/spatial-window-polyfill.ts
3224
- init_utils();
3225
- var spatial = new Spatial();
3226
- var session = void 0;
3227
- var SpatialGlobalCustomVars = {
3228
- backgroundMaterial: "--xr-background-material"
3229
- };
3230
- var htmlBackgroundMaterial = "";
3231
- function setCurrentWindowStyle(backgroundMaterial) {
3232
- if (backgroundMaterial !== htmlBackgroundMaterial) {
3233
- session?.getSpatialScene()?.updateSpatialProperties({
3234
- material: backgroundMaterial
3235
- });
3236
- htmlBackgroundMaterial = backgroundMaterial;
3237
- }
3238
- }
3239
- function checkHtmlBackgroundMaterial() {
3240
- const computedStyle = getComputedStyle(document.documentElement);
3241
- const backgroundMaterial = computedStyle.getPropertyValue(
3242
- SpatialGlobalCustomVars.backgroundMaterial
3243
- );
3244
- setCurrentWindowStyle(backgroundMaterial || "none");
3245
- }
3246
- var htmlCornerRadius = {
3247
- topLeading: 0,
3248
- bottomLeading: 0,
3249
- topTrailing: 0,
3250
- bottomTrailing: 0
3251
- };
3252
- function checkCornerRadius() {
3253
- const computedStyle = getComputedStyle(document.documentElement);
3254
- const cornerRadius = parseCornerRadius(computedStyle);
3255
- setCornerRadius(cornerRadius);
3256
- }
3257
- function setCornerRadius(cornerRadius) {
3258
- if (htmlCornerRadius.topLeading !== cornerRadius.topLeading || htmlCornerRadius.bottomLeading !== cornerRadius.bottomLeading || htmlCornerRadius.topTrailing !== cornerRadius.topTrailing || htmlCornerRadius.bottomTrailing !== cornerRadius.bottomTrailing) {
3259
- session?.getSpatialScene()?.updateSpatialProperties({
3260
- cornerRadius
3261
- });
3262
- htmlCornerRadius.topLeading = cornerRadius.topLeading;
3263
- htmlCornerRadius.bottomLeading = cornerRadius.bottomLeading;
3264
- htmlCornerRadius.topTrailing = cornerRadius.topTrailing;
3265
- htmlCornerRadius.bottomTrailing = cornerRadius.bottomTrailing;
3266
- }
3267
- }
3268
- function setOpacity(opacity) {
3269
- session?.getSpatialScene().updateSpatialProperties({
3270
- opacity
3271
- });
3272
- }
3273
- function checkOpacity() {
3274
- const computedStyle = getComputedStyle(document.documentElement);
3275
- const opacity = parseFloat(computedStyle.getPropertyValue("opacity"));
3276
- setOpacity(opacity);
3277
- }
3278
- function hijackDocumentElementStyle() {
3279
- const rawDocumentStyle = document.documentElement.style;
3280
- const styleProxy = new Proxy(rawDocumentStyle, {
3281
- set: function(target, key, value) {
3282
- const ret = Reflect.set(target, key, value);
3283
- if (key === SpatialGlobalCustomVars.backgroundMaterial) {
3284
- setCurrentWindowStyle(value);
3285
- }
3286
- if (key === "border-radius" || key === "borderRadius" || key === "border-top-left-radius" || key === "borderTopLeftRadius" || key === "border-top-right-radius" || key === "borderTopRightRadius" || key === "border-bottom-left-radius" || key === "borderBottomLeftRadius" || key === "border-bottom-right-radius" || key === "borderBottomRightRadius") {
3287
- checkCornerRadius();
3288
- }
3289
- if (key === "opacity") {
3290
- checkOpacity();
3291
- }
3292
- return ret;
3293
- },
3294
- get: function(target, prop) {
3295
- if (typeof target[prop] === "function") {
3296
- return function(...args) {
3297
- if (prop === "setProperty") {
3298
- const [property, value] = args;
3299
- if (property === SpatialGlobalCustomVars.backgroundMaterial) {
3300
- setCurrentWindowStyle(value);
3301
- }
3302
- } else if (prop === "removeProperty") {
3303
- const [property] = args;
3304
- if (property === SpatialGlobalCustomVars.backgroundMaterial) {
3305
- setCurrentWindowStyle("none");
3306
- }
3307
- }
3308
- return target[prop](
3309
- ...args
3310
- );
3311
- };
3312
- }
3313
- return Reflect.get(target, prop);
3314
- }
3315
- });
3316
- Object.defineProperty(document.documentElement, "style", {
3317
- get: function() {
3318
- return styleProxy;
3319
- }
3320
- });
3321
- }
3322
- function monitorExternalStyleChange() {
3323
- const headObserver = new MutationObserver(checkCSSProperties);
3324
- headObserver.observe(document.head, { childList: true, subtree: true });
3325
- }
3326
- function checkCSSProperties() {
3327
- checkHtmlBackgroundMaterial();
3328
- checkCornerRadius();
3329
- checkOpacity();
3330
- }
3331
- function monitorHTMLAttributeChange() {
3332
- const observer = new MutationObserver((mutations) => {
3333
- mutations.forEach((mutation) => {
3334
- if (mutation.type === "attributes" && mutation.attributeName) {
3335
- checkCSSProperties();
3336
- }
3337
- });
3338
- });
3339
- observer.observe(document.documentElement, {
3340
- attributes: true,
3341
- attributeFilter: ["style", "class"]
3342
- });
3343
- }
3344
- async function spatialWindowPolyfill() {
3345
- if (!spatial.runInSpatialWeb()) {
3346
- return;
3347
- }
3348
- session = await spatial.requestSession();
3349
- if (document.readyState === "complete") {
3350
- checkCSSProperties();
3351
- } else {
3352
- window.addEventListener("load", () => {
3353
- checkCSSProperties();
3354
- });
3355
- }
3356
- hijackDocumentElementStyle();
3357
- monitorExternalStyleChange();
3358
- monitorHTMLAttributeChange();
3359
- }
3360
-
3361
- // src/index.ts
3362
- if (!isSSREnv() && navigator.userAgent.indexOf("WebSpatial/") > 0) {
3363
- injectSceneHook();
3364
- spatialWindowPolyfill();
3365
- }
1
+ import { SpatialObject } from "./SpatialObject";
2
+ import { Spatial } from "./Spatial";
3
+ import { SpatialSession } from "./SpatialSession";
4
+ import { SpatialScene } from "./SpatialScene";
5
+ import { SpatializedElement } from "./SpatializedElement";
6
+ import { Spatialized2DElement } from "./Spatialized2DElement";
7
+ import { SpatializedStatic3DElement } from "./SpatializedStatic3DElement";
8
+ import { SpatializedDynamic3DElement } from "./SpatializedDynamic3DElement";
9
+ import * as PhysicalMetrics from "./physicalMetrics";
10
+ export * from "./reality";
11
+ export * from "./types/types";
12
+ export * from "./types/animation";
13
+ export * from "./types/motion";
14
+ import { validateSpatializedMotionConfig } from "./motion";
15
+ export * from "./runtime";
16
+ import { composeSRT, decomposeSRT } from "./utils";
17
+ import { isSSREnv } from "./isSSREnv";
3366
18
  export {
3367
- Attachment,
3368
- BaseplateVisibilityValues,
3369
- CubeInfo,
3370
- ModelComponent,
3371
- physicalMetrics_exports as PhysicalMetrics,
19
+ PhysicalMetrics,
3372
20
  Spatial,
3373
- SpatialBoxGeometry,
3374
- SpatialComponent,
3375
- SpatialConeGeometry,
3376
- SpatialCylinderGeometry,
3377
- SpatialEntity,
3378
- SpatialGeometry,
3379
- SpatialMaterial,
3380
- SpatialModelAsset,
3381
- SpatialModelEntity,
3382
21
  SpatialObject,
3383
- SpatialPlaneGeometry,
3384
22
  SpatialScene,
3385
- SpatialSceneState,
3386
- SpatialSceneValues,
3387
23
  SpatialSession,
3388
- SpatialSphereGeometry,
3389
- SpatialUnlitMaterial,
3390
24
  Spatialized2DElement,
3391
25
  SpatializedDynamic3DElement,
3392
26
  SpatializedElement,
3393
- SpatializedElementType,
3394
27
  SpatializedStatic3DElement,
3395
- WorldAlignmentValues,
3396
- WorldScalingValues,
3397
- createAttachmentEntity,
28
+ composeSRT,
29
+ decomposeSRT,
3398
30
  isSSREnv,
3399
- isValidBaseplateVisibilityType,
3400
- isValidSceneUnit,
3401
- isValidSpatialSceneType,
3402
- isValidWorldAlignmentType,
3403
- isValidWorldScalingType
31
+ validateSpatializedMotionConfig
3404
32
  };
3405
33
  //# sourceMappingURL=index.js.map