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16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
"use client";

// src/next/index.tsx
import { useRef as useRef2, useState as useState3, useEffect as useEffect3 } from "react";
import Script from "next/script";
import Image from "next/image";

// src/next/hooks.ts
import { useState as useState2, useCallback as useCallback2, useEffect as useEffect2 } from "react";

// src/shared/hooks.ts
import { useEffect, useRef, useState, useCallback, useMemo } from "react";

// src/shared/constants.ts
var UNICORN_STUDIO_VERSION = "2.1.4";
var UNICORN_STUDIO_CDN_URL = `https://cdn.jsdelivr.net/gh/hiunicornstudio/unicornstudio.js@v${UNICORN_STUDIO_VERSION}/dist/unicornStudio.umd.js`;
var DEFAULT_VALUES = {
  /** Default container width */
  width: "100%",
  /** Default container height */
  height: "100%",
  /** Default rendering scale (0.25 to 1.0) */
  scale: 1,
  /** Default production mode setting */
  production: true,
  /** Default device pixel ratio */
  dpi: 1.5,
  /** Default frames per second */
  fps: 60,
  /** Default alt text for accessibility */
  altText: "Scene",
  /** Default CSS class name */
  className: "",
  /** Default paused state */
  paused: false,
  /** Default lazy loading setting */
  lazyLoad: true,
  /** Default setting for showing placeholder on error */
  showPlaceholderOnError: true,
  /** Default setting for showing placeholder while loading */
  showPlaceholderWhileLoading: true
};
var VALID_FPS = [15, 24, 30, 60, 120];

// src/shared/utils.ts
function isWebGLSupported() {
  if (typeof window === "undefined") return true;
  try {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    return !!gl;
  } catch (e) {
    return false;
  }
}
function validateFPS(fps) {
  return VALID_FPS.includes(fps);
}
function validateScale(scale) {
  return scale >= 0.25 && scale <= 1;
}
function validateParameters(scale, fps) {
  if (!validateScale(scale)) {
    return `Invalid scale: ${scale}. Scale must be between 0.25 and 1.0`;
  }
  if (!validateFPS(fps)) {
    return `Invalid fps: ${fps}. FPS must be one of: 15, 24, 30, 60, 120`;
  }
  return null;
}

// src/shared/hooks.ts
function sanitizeErrorMessage(message) {
  if (message.includes("404") || message.includes("Failed to fetch")) {
    return "Resource not found";
  }
  if (message.includes("Network") || message.includes("network")) {
    return "Network error occurred";
  }
  if (message.includes("timeout")) {
    return "Loading timeout";
  }
  const urlPattern = /\bhttps?:\/\/[^\s)]+/gi;
  const filePathPattern = /\b(?:[A-Za-z]:\\|\/)[^\s)]+/g;
  let sanitized = message.replaceAll(urlPattern, "[redacted]");
  sanitized = sanitized.replaceAll(filePathPattern, "[redacted]");
  return sanitized;
}
function buildSceneConfig(element, params) {
  const elementId = element.id || `unicorn-${Math.random().toString(36).slice(2, 11)}`;
  if (!element.id) {
    element.id = elementId;
  }
  const config = {
    elementId,
    scale: params.scale,
    dpi: params.dpi,
    fps: params.fps,
    lazyLoad: params.lazyLoad,
    altText: params.altText,
    ariaLabel: params.ariaLabel,
    production: params.production
  };
  if (params.jsonFilePath) {
    config.filePath = params.jsonFilePath;
  } else if (params.projectId) {
    config.projectId = params.projectId;
  } else {
    throw new Error("No project ID or JSON file path provided");
  }
  return config;
}
var INIT_TIMEOUT_MS = 15e3;
async function withTimeout(promise, ms = INIT_TIMEOUT_MS) {
  let timeoutId;
  const timeoutPromise = new Promise((_, reject) => {
    timeoutId = setTimeout(
      () => reject(new Error("Scene initialization timeout")),
      ms
    );
  });
  try {
    return await Promise.race([promise, timeoutPromise]);
  } finally {
    if (timeoutId) clearTimeout(timeoutId);
  }
}
function assignSceneRef(ref, value) {
  if (!ref) return;
  if (typeof ref === "function") {
    ref(value);
    return;
  }
  ref.current = value;
}
function useUnicornScene({
  elementRef,
  projectId,
  jsonFilePath,
  production,
  scale,
  dpi,
  fps,
  lazyLoad,
  altText,
  ariaLabel,
  isScriptLoaded,
  paused,
  onLoad,
  onError,
  sceneRef
}) {
  const internalSceneRef = useRef(null);
  const [initError, setInitError] = useState(null);
  const initializationKeyRef = useRef("");
  const isInitializingRef = useRef(false);
  const onLoadRef = useRef(onLoad);
  onLoadRef.current = onLoad;
  const onErrorRef = useRef(onError);
  onErrorRef.current = onError;
  const sceneRefRef = useRef(sceneRef);
  const prevSceneRef = useRef(sceneRef);
  if (sceneRef !== prevSceneRef.current) {
    assignSceneRef(prevSceneRef.current, null);
    sceneRefRef.current = sceneRef;
    prevSceneRef.current = sceneRef;
    assignSceneRef(sceneRef, internalSceneRef.current);
  }
  const validationError = useMemo(() => {
    return validateParameters(scale, fps);
  }, [scale, fps]);
  const prevValidationError = useRef(null);
  useEffect(() => {
    var _a;
    if (validationError !== prevValidationError.current) {
      prevValidationError.current = validationError;
      if (validationError) {
        const error = new Error(validationError);
        setInitError(error);
        (_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, error);
      } else {
        setInitError(null);
      }
    }
  }, [validationError]);
  const destroyScene = useCallback(() => {
    var _a;
    if ((_a = internalSceneRef.current) == null ? void 0 : _a.destroy) {
      internalSceneRef.current.destroy();
      internalSceneRef.current = null;
      assignSceneRef(sceneRefRef.current, null);
    }
    isInitializingRef.current = false;
  }, []);
  useEffect(() => {
    let ignore = false;
    async function initializeScene() {
      var _a, _b, _c;
      if (!elementRef.current || !isScriptLoaded || validationError) return;
      if (isInitializingRef.current) return;
      const currentKey = `${projectId || ""}-${jsonFilePath || ""}-${scale}-${dpi}-${fps}-${production ? "prod" : "dev"}`;
      if (initializationKeyRef.current === currentKey && internalSceneRef.current) {
        return;
      }
      initializationKeyRef.current = currentKey;
      try {
        destroyScene();
        isInitializingRef.current = true;
        if (!((_a = window.UnicornStudio) == null ? void 0 : _a.addScene)) {
          throw new Error("UnicornStudio.addScene not found");
        }
        const sceneConfig = buildSceneConfig(elementRef.current, {
          jsonFilePath,
          projectId,
          scale,
          dpi,
          fps,
          lazyLoad,
          altText,
          ariaLabel,
          production
        });
        const scene = await withTimeout(
          window.UnicornStudio.addScene(sceneConfig)
        );
        if (ignore) {
          scene == null ? void 0 : scene.destroy();
          return;
        }
        if (scene) {
          internalSceneRef.current = scene;
          assignSceneRef(sceneRefRef.current, scene);
          setInitError(null);
          isInitializingRef.current = false;
          (_b = onLoadRef.current) == null ? void 0 : _b.call(onLoadRef);
        } else {
          isInitializingRef.current = false;
          throw new Error("Failed to initialize scene");
        }
      } catch (error) {
        if (ignore) return;
        const err = error instanceof Error ? error : new Error("Unknown error");
        const sanitizedError = new Error(sanitizeErrorMessage(err.message));
        setInitError(sanitizedError);
        isInitializingRef.current = false;
        (_c = onErrorRef.current) == null ? void 0 : _c.call(onErrorRef, sanitizedError);
      }
    }
    if (isScriptLoaded) {
      void initializeScene();
    }
    return () => {
      ignore = true;
      destroyScene();
    };
  }, [
    isScriptLoaded,
    elementRef,
    jsonFilePath,
    projectId,
    production,
    scale,
    dpi,
    fps,
    lazyLoad,
    altText,
    ariaLabel,
    destroyScene,
    validationError
  ]);
  useEffect(() => {
    if (internalSceneRef.current && paused !== void 0) {
      internalSceneRef.current.paused = paused;
    }
  }, [paused]);
  useEffect(() => {
    const el = elementRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver(() => {
      var _a, _b;
      (_b = (_a = internalSceneRef.current) == null ? void 0 : _a.resize) == null ? void 0 : _b.call(_a);
    });
    observer.observe(el);
    return () => {
      observer.disconnect();
    };
  }, [elementRef]);
  return { error: initError };
}

// src/next/hooks.ts
function useUnicornStudioScript() {
  const [isLoaded, setIsLoaded] = useState2(false);
  const [error, setError] = useState2(null);
  const handleScriptLoad = useCallback2(() => {
    setIsLoaded((prev) => {
      if (!prev && typeof window !== "undefined" && window.UnicornStudio) {
        setError(null);
        return true;
      }
      return prev;
    });
  }, []);
  const handleScriptError = useCallback2(() => {
    setError(new Error("Failed to load UnicornStudio script"));
    setIsLoaded(false);
  }, []);
  useEffect2(() => {
    if (typeof window !== "undefined" && window.UnicornStudio && !isLoaded) {
      setIsLoaded(true);
      setError(null);
    }
  }, [isLoaded]);
  return { isLoaded, error, handleScriptLoad, handleScriptError };
}

// src/shared/styles.ts
var unicornStyles = {
  /**
   * Styles for the main scene container element.
   *
   * @remarks
   * Uses CSS custom properties for width and height to allow dynamic sizing.
   */
  container: {
    position: "relative",
    width: "var(--unicorn-width)",
    height: "var(--unicorn-height)"
  },
  /**
   * Styles for the error message wrapper.
   */
  errorWrapper: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    height: "100%"
  },
  /**
   * Styles for the error message box.
   */
  errorBox: {
    textAlign: "center",
    padding: "1rem",
    borderRadius: "0.5rem",
    backgroundColor: "rgb(254 242 242)",
    color: "rgb(239 68 68)"
  },
  /**
   * Styles for the error title text.
   */
  errorTitle: {
    fontWeight: "600",
    marginBottom: "0.25rem"
  },
  /**
   * Styles for the error message text.
   */
  errorMessage: {
    fontSize: "0.875rem",
    marginTop: "0.25rem"
  }
};

// src/next/index.tsx
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function UnicornScene({
  projectId,
  jsonFilePath,
  sdkUrl = UNICORN_STUDIO_CDN_URL,
  width = DEFAULT_VALUES.width,
  height = DEFAULT_VALUES.height,
  scale = DEFAULT_VALUES.scale,
  dpi = DEFAULT_VALUES.dpi,
  fps = DEFAULT_VALUES.fps,
  altText = DEFAULT_VALUES.altText,
  ariaLabel,
  className = DEFAULT_VALUES.className,
  lazyLoad = DEFAULT_VALUES.lazyLoad,
  production = DEFAULT_VALUES.production,
  paused = DEFAULT_VALUES.paused,
  placeholder,
  placeholderClassName,
  showPlaceholderOnError = DEFAULT_VALUES.showPlaceholderOnError,
  showPlaceholderWhileLoading = DEFAULT_VALUES.showPlaceholderWhileLoading,
  onLoad,
  onError,
  sceneRef
}) {
  const elementRef = useRef2(null);
  const [isSceneLoaded, setIsSceneLoaded] = useState3(false);
  const [webGLSupported, setWebGLSupported] = useState3(true);
  const {
    isLoaded,
    error: scriptError,
    handleScriptLoad,
    handleScriptError
  } = useUnicornStudioScript();
  const { error: sceneError } = useUnicornScene({
    elementRef,
    projectId,
    jsonFilePath,
    production,
    scale,
    dpi,
    fps,
    lazyLoad,
    altText,
    ariaLabel: ariaLabel || altText,
    isScriptLoaded: isLoaded,
    paused,
    sceneRef,
    onLoad: () => {
      setIsSceneLoaded(true);
      onLoad == null ? void 0 : onLoad();
    },
    onError
  });
  const error = scriptError || sceneError;
  useEffect3(() => {
    setWebGLSupported(isWebGLSupported());
  }, []);
  const showPlaceholder = (placeholder || placeholderClassName) && (!webGLSupported || showPlaceholderWhileLoading && !isSceneLoaded || showPlaceholderOnError && error);
  const numericWidth = typeof width === "number" ? width : 0;
  const numericHeight = typeof height === "number" ? height : 0;
  const useNumericDimensions = typeof width === "number" && typeof height === "number";
  const customProperties = {
    "--unicorn-width": typeof width === "number" ? `${width}px` : width,
    "--unicorn-height": typeof height === "number" ? `${height}px` : height
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Script,
      {
        src: sdkUrl,
        strategy: lazyLoad ? "lazyOnload" : "afterInteractive",
        onLoad: handleScriptLoad,
        onError: handleScriptError
      }
    ),
    /* @__PURE__ */ jsxs(
      "div",
      {
        ref: elementRef,
        style: { ...unicornStyles.container, ...customProperties },
        className,
        children: [
          showPlaceholder && (placeholder || placeholderClassName) && /* @__PURE__ */ jsx("div", { style: { position: "absolute", inset: 0 }, children: typeof placeholder === "string" ? useNumericDimensions ? /* @__PURE__ */ jsx(
            Image,
            {
              src: placeholder,
              alt: altText,
              width: numericWidth,
              height: numericHeight,
              style: { objectFit: "cover" },
              priority: true
            }
          ) : /* @__PURE__ */ jsx(
            Image,
            {
              src: placeholder,
              alt: altText,
              fill: true,
              style: { objectFit: "cover" },
              priority: true
            }
          ) : placeholder ? placeholder : placeholderClassName ? /* @__PURE__ */ jsx(
            "div",
            {
              className: placeholderClassName,
              style: { width: "100%", height: "100%" },
              "aria-label": altText
            }
          ) : null }),
          error && !showPlaceholder && /* @__PURE__ */ jsx("div", { style: unicornStyles.errorWrapper, children: /* @__PURE__ */ jsxs("div", { style: unicornStyles.errorBox, children: [
            /* @__PURE__ */ jsx("p", { style: unicornStyles.errorTitle, children: "Error loading scene" }),
            /* @__PURE__ */ jsx("p", { style: unicornStyles.errorMessage, children: error.message })
          ] }) })
        ]
      }
    )
  ] });
}
var next_default = UnicornScene;
export {
  UnicornScene,
  next_default as default
};
//# sourceMappingURL=next.mjs.map