@midscene/ios 0.30.6-beta-20251022093704.0 → 1.0.1-beta-20251022061922.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 (47) hide show
  1. package/README.md +11 -11
  2. package/package.json +5 -5
  3. package/static/index.html +1 -1
  4. package/static/static/js/63.b6f8c5e5.js +667 -0
  5. package/static/static/js/{657.5a5fe47b.js.map → 63.b6f8c5e5.js.map} +1 -1
  6. package/static/static/js/async/150.2d81d791.js +158 -0
  7. package/static/static/js/async/{212.e243c338.js.map → 150.2d81d791.js.map} +1 -1
  8. package/static/static/js/async/{624.45ee2b2c.js → 195.7911eb6e.js} +3 -3
  9. package/static/static/js/async/{624.45ee2b2c.js.map → 195.7911eb6e.js.map} +1 -1
  10. package/static/static/js/async/260.638dda74.js +2 -0
  11. package/static/static/js/async/{544.b73fa603.js.map → 260.638dda74.js.map} +1 -1
  12. package/static/static/js/async/271.9e1c79dc.js +3 -0
  13. package/static/static/js/async/{173.9cf6b074.js.map → 271.9e1c79dc.js.map} +1 -1
  14. package/static/static/js/async/355.f86b7375.js +1 -0
  15. package/static/static/js/async/{644.6bdc4065.js → 441.11908ede.js} +1 -1
  16. package/static/static/js/async/45.ebc9207b.js +21 -0
  17. package/static/static/js/async/45.ebc9207b.js.map +1 -0
  18. package/static/static/js/async/586.bf0d228e.js +26 -0
  19. package/static/static/js/async/{329.f888b505.js.map → 586.bf0d228e.js.map} +1 -1
  20. package/static/static/js/async/631.422c34d1.js +30 -0
  21. package/static/static/js/async/{364.1821e74b.js.map → 631.422c34d1.js.map} +1 -1
  22. package/static/static/js/async/{702.60261735.js → 779.d48d6dc9.js} +20 -20
  23. package/static/static/js/async/{702.60261735.js.map → 779.d48d6dc9.js.map} +1 -1
  24. package/static/static/js/index.fd41dad8.js +30 -0
  25. package/static/static/js/index.fd41dad8.js.map +1 -0
  26. package/static/static/js/lib-react.88bfef40.js +3 -0
  27. package/static/static/js/{lib-react.f566a9ed.js.map → lib-react.88bfef40.js.map} +1 -1
  28. package/static/static/js/657.5a5fe47b.js +0 -673
  29. package/static/static/js/async/173.9cf6b074.js +0 -3
  30. package/static/static/js/async/212.e243c338.js +0 -158
  31. package/static/static/js/async/290.dd04c2bc.js +0 -21
  32. package/static/static/js/async/290.dd04c2bc.js.map +0 -1
  33. package/static/static/js/async/329.f888b505.js +0 -26
  34. package/static/static/js/async/364.1821e74b.js +0 -30
  35. package/static/static/js/async/544.b73fa603.js +0 -2
  36. package/static/static/js/async/582.5dccae2d.js +0 -21
  37. package/static/static/js/async/582.5dccae2d.js.map +0 -1
  38. package/static/static/js/async/920.7d9a9aa8.js +0 -2
  39. package/static/static/js/async/920.7d9a9aa8.js.map +0 -1
  40. package/static/static/js/async/983.8b91303f.js +0 -1
  41. package/static/static/js/index.914766d3.js +0 -21
  42. package/static/static/js/index.914766d3.js.map +0 -1
  43. package/static/static/js/lib-react.f566a9ed.js +0 -3
  44. /package/static/static/js/{657.5a5fe47b.js.LICENSE.txt → 63.b6f8c5e5.js.LICENSE.txt} +0 -0
  45. /package/static/static/js/{index.914766d3.js.LICENSE.txt → index.fd41dad8.js.LICENSE.txt} +0 -0
  46. /package/static/static/js/{lib-react.f566a9ed.js.LICENSE.txt → lib-react.88bfef40.js.LICENSE.txt} +0 -0
  47. /package/static/static/wasm/{9e906fbf55e08f98.module.wasm → 9e906fbf.module.wasm} +0 -0
@@ -1,3 +0,0 @@
1
- (self.webpackChunkplayground=self.webpackChunkplayground||[]).push([["173"],{10742:function(t,e,r){let n,o={};o.__wbindgen_placeholder__=t.exports;let{TextEncoder:_,TextDecoder:i}=r(80911),a=Array(32).fill(void 0);a.push(void 0,null,!0,!1);let s=a.length;function p(t){let e=a[t];return t<36||(a[t]=s,s=t),e}function c(t){s===a.length&&a.push(a.length+1);let e=s;return s=a[e],a[e]=t,e}let u=0,l=null;function f(){return(null===l||l.buffer!==n.memory.buffer)&&(l=new Uint8Array(n.memory.buffer)),l}let g=new _("utf-8"),d="function"==typeof g.encodeInto?function(t,e){return g.encodeInto(t,e)}:function(t,e){let r=g.encode(t);return e.set(r),{read:t.length,written:r.length}};function b(t,e,r){if(void 0===r){let r=g.encode(t),n=e(r.length);return f().subarray(n,n+r.length).set(r),u=r.length,n}let n=t.length,o=e(n),_=f(),i=0;for(;i<n;i++){let e=t.charCodeAt(i);if(e>127)break;_[o+i]=e}if(i!==n){0!==i&&(t=t.slice(i)),o=r(o,n,n=i+3*t.length);let e=d(t,f().subarray(o+i,o+n));i+=e.written}return u=i,o}let h=null;function x(){return(null===h||h.buffer!==n.memory.buffer)&&(h=new Int32Array(n.memory.buffer)),h}let w=new i("utf-8",{ignoreBOM:!0,fatal:!0});function m(t,e){return w.decode(f().subarray(t,t+e))}function v(t,e){if(!(t instanceof e))throw Error(`expected instance of ${e.name}`);return t.ptr}function y(t,e){let r=e(+t.length);return f().set(t,r/1),u=t.length,r}function k(t,e){return f().subarray(t/1,t/1+e)}w.decode(),t.exports.crop=function(t,e,r,o,_){v(t,A);var i=n.crop(t.ptr,e,r,o,_);return A.__wrap(i)},t.exports.crop_img_browser=function(t,e,r,o,_){return p(n.crop_img_browser(c(t),e,r,o,_))},t.exports.fliph=function(t){v(t,A),n.fliph(t.ptr)},t.exports.flipv=function(t){v(t,A),n.flipv(t.ptr)},t.exports.resize_img_browser=function(t,e,r,o){return v(t,A),p(n.resize_img_browser(t.ptr,e,r,o))},t.exports.resize=function(t,e,r,o){v(t,A);var _=n.resize(t.ptr,e,r,o);return A.__wrap(_)},t.exports.seam_carve=function(t,e,r){v(t,A);var o=n.seam_carve(t.ptr,e,r);return A.__wrap(o)},t.exports.padding_uniform=function(t,e,r){v(t,A),v(r,O);var o=r.ptr;r.ptr=0;var _=n.padding_uniform(t.ptr,e,o);return A.__wrap(_)},t.exports.padding_left=function(t,e,r){v(t,A),v(r,O);var o=r.ptr;r.ptr=0;var _=n.padding_left(t.ptr,e,o);return A.__wrap(_)},t.exports.padding_right=function(t,e,r){v(t,A),v(r,O);var o=r.ptr;r.ptr=0;var _=n.padding_right(t.ptr,e,o);return A.__wrap(_)},t.exports.padding_top=function(t,e,r){v(t,A),v(r,O);var o=r.ptr;r.ptr=0;var _=n.padding_top(t.ptr,e,o);return A.__wrap(_)},t.exports.padding_bottom=function(t,e,r){v(t,A),v(r,O);var o=r.ptr;r.ptr=0;var _=n.padding_bottom(t.ptr,e,o);return A.__wrap(_)},t.exports.rotate=function(t,e){v(t,A);var r=n.rotate(t.ptr,e);return A.__wrap(r)},t.exports.resample=function(t,e,r){v(t,A);var o=n.resample(t.ptr,e,r);return A.__wrap(o)},t.exports.draw_text_with_border=function(t,e,r,o){v(t,A);var _=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u;n.draw_text_with_border(t.ptr,_,i,r,o)},t.exports.draw_text=function(t,e,r,o){v(t,A);var _=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),i=u;n.draw_text(t.ptr,_,i,r,o)},t.exports.run=function(){n.run()};let z=32;function C(t){if(1==z)throw Error("out of js stack");return a[--z]=t,z}function j(t,e){try{return t.apply(this,e)}catch(t){n.__wbindgen_exn_store(c(t))}}t.exports.get_image_data=function(t,e){try{var r=n.get_image_data(C(t),C(e));return p(r)}finally{a[z++]=void 0,a[z++]=void 0}},t.exports.putImageData=function(t,e,r){v(r,A);var o=r.ptr;r.ptr=0,n.putImageData(c(t),c(e),o)},t.exports.open_image=function(t,e){var r=n.open_image(c(t),c(e));return A.__wrap(r)},t.exports.to_raw_pixels=function(t){try{let _=n.__wbindgen_add_to_stack_pointer(-16);n.to_raw_pixels(_,c(t));var e=x()[_/4+0],r=x()[_/4+1],o=k(e,r).slice();return n.__wbindgen_free(e,+r),o}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.base64_to_image=function(t){var e=b(t,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,o=n.base64_to_image(e,r);return A.__wrap(o)},t.exports.base64_to_vec=function(t){try{let a=n.__wbindgen_add_to_stack_pointer(-16);var e=b(t,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u;n.base64_to_vec(a,e,r);var o=x()[a/4+0],_=x()[a/4+1],i=k(o,_).slice();return n.__wbindgen_free(o,+_),i}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.to_image_data=function(t){v(t,A);var e=t.ptr;return t.ptr=0,p(n.to_image_data(e))},t.exports.alter_channel=function(t,e,r){v(t,A),n.alter_channel(t.ptr,e,r)},t.exports.alter_red_channel=function(t,e){v(t,A),n.alter_red_channel(t.ptr,e)},t.exports.alter_green_channel=function(t,e){v(t,A),n.alter_green_channel(t.ptr,e)},t.exports.alter_blue_channel=function(t,e){v(t,A),n.alter_blue_channel(t.ptr,e)},t.exports.alter_two_channels=function(t,e,r,o,_){v(t,A),n.alter_two_channels(t.ptr,e,r,o,_)},t.exports.alter_channels=function(t,e,r,o){v(t,A),n.alter_channels(t.ptr,e,r,o)},t.exports.remove_channel=function(t,e,r){v(t,A),n.remove_channel(t.ptr,e,r)},t.exports.remove_red_channel=function(t,e){v(t,A),n.remove_red_channel(t.ptr,e)},t.exports.remove_green_channel=function(t,e){v(t,A),n.remove_green_channel(t.ptr,e)},t.exports.remove_blue_channel=function(t,e){v(t,A),n.remove_blue_channel(t.ptr,e)},t.exports.swap_channels=function(t,e,r){v(t,A),n.swap_channels(t.ptr,e,r)},t.exports.invert=function(t){v(t,A),n.invert(t.ptr)},t.exports.selective_hue_rotate=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,n.selective_hue_rotate(t.ptr,o,r)},t.exports.selective_color_convert=function(t,e,r,o){v(t,A),v(e,E);var _=e.ptr;e.ptr=0,v(r,E);var i=r.ptr;r.ptr=0,n.selective_color_convert(t.ptr,_,i,o)},t.exports.selective_lighten=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,n.selective_lighten(t.ptr,o,r)},t.exports.selective_desaturate=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,n.selective_desaturate(t.ptr,o,r)},t.exports.selective_saturate=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,n.selective_saturate(t.ptr,o,r)},t.exports.selective_greyscale=function(t,e){v(t,A);var r=t.ptr;t.ptr=0,v(e,E);var o=e.ptr;e.ptr=0,n.selective_greyscale(r,o)},t.exports.monochrome=function(t,e,r,o){v(t,A),n.monochrome(t.ptr,e,r,o)},t.exports.sepia=function(t){v(t,A),n.sepia(t.ptr)},t.exports.grayscale=function(t){v(t,A),n.grayscale(t.ptr)},t.exports.grayscale_human_corrected=function(t){v(t,A),n.grayscale_human_corrected(t.ptr)},t.exports.desaturate=function(t){v(t,A),n.desaturate(t.ptr)},t.exports.decompose_min=function(t){v(t,A),n.decompose_min(t.ptr)},t.exports.decompose_max=function(t){v(t,A),n.decompose_max(t.ptr)},t.exports.grayscale_shades=function(t,e){v(t,A),n.grayscale_shades(t.ptr,e)},t.exports.r_grayscale=function(t){v(t,A),n.r_grayscale(t.ptr)},t.exports.g_grayscale=function(t){v(t,A),n.g_grayscale(t.ptr)},t.exports.b_grayscale=function(t){v(t,A),n.b_grayscale(t.ptr)},t.exports.single_channel_grayscale=function(t,e){v(t,A),n.single_channel_grayscale(t.ptr,e)},t.exports.threshold=function(t,e){v(t,A),n.threshold(t.ptr,e)},t.exports.offset=function(t,e,r){v(t,A),n.offset(t.ptr,e,r)},t.exports.offset_red=function(t,e){v(t,A),n.offset_red(t.ptr,e)},t.exports.offset_green=function(t,e){v(t,A),n.offset_green(t.ptr,e)},t.exports.offset_blue=function(t,e){v(t,A),n.offset_blue(t.ptr,e)},t.exports.multiple_offsets=function(t,e,r,o){v(t,A),n.multiple_offsets(t.ptr,e,r,o)},t.exports.primary=function(t){v(t,A),n.primary(t.ptr)},t.exports.colorize=function(t){v(t,A),n.colorize(t.ptr)},t.exports.solarize=function(t){v(t,A),n.solarize(t.ptr)},t.exports.solarize_retimg=function(t){v(t,A);var e=n.solarize_retimg(t.ptr);return A.__wrap(e)},t.exports.inc_brightness=function(t,e){v(t,A),n.inc_brightness(t.ptr,e)},t.exports.adjust_contrast=function(t,e){v(t,A),n.adjust_contrast(t.ptr,e)},t.exports.tint=function(t,e,r,o){v(t,A),n.tint(t.ptr,e,r,o)},t.exports.horizontal_strips=function(t,e){v(t,A),n.horizontal_strips(t.ptr,e)},t.exports.color_horizontal_strips=function(t,e,r){v(t,A),v(r,E);var o=r.ptr;r.ptr=0,n.color_horizontal_strips(t.ptr,e,o)},t.exports.vertical_strips=function(t,e){v(t,A),n.vertical_strips(t.ptr,e)},t.exports.color_vertical_strips=function(t,e,r){v(t,A),v(r,E);var o=r.ptr;r.ptr=0,n.color_vertical_strips(t.ptr,e,o)},t.exports.oil=function(t,e,r){v(t,A),n.oil(t.ptr,e,r)},t.exports.frosted_glass=function(t){v(t,A),n.frosted_glass(t.ptr)},t.exports.pixelize=function(t,e){v(t,A),n.pixelize(t.ptr,e)},t.exports.normalize=function(t){v(t,A),n.normalize(t.ptr)},t.exports.dither=function(t,e){v(t,A),n.dither(t.ptr,e)},t.exports.duotone=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,v(r,E);var _=r.ptr;r.ptr=0,n.duotone(t.ptr,o,_)},t.exports.neue=function(t){v(t,A),n.neue(t.ptr)},t.exports.lix=function(t){v(t,A),n.lix(t.ptr)},t.exports.ryo=function(t){v(t,A),n.ryo(t.ptr)},t.exports.filter=function(t,e){v(t,A);var r=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u;n.filter(t.ptr,r,o)},t.exports.lofi=function(t){v(t,A),n.lofi(t.ptr)},t.exports.pastel_pink=function(t){v(t,A),n.pastel_pink(t.ptr)},t.exports.golden=function(t){v(t,A),n.golden(t.ptr)},t.exports.cali=function(t){v(t,A),n.cali(t.ptr)},t.exports.dramatic=function(t){v(t,A),n.dramatic(t.ptr)},t.exports.monochrome_tint=function(t,e){v(t,A),v(e,E);var r=e.ptr;e.ptr=0,n.monochrome_tint(t.ptr,r)},t.exports.duotone_violette=function(t){v(t,A),n.duotone_violette(t.ptr)},t.exports.duotone_horizon=function(t){v(t,A),n.duotone_horizon(t.ptr)},t.exports.duotone_tint=function(t,e){v(t,A),v(e,E);var r=e.ptr;e.ptr=0,n.duotone_tint(t.ptr,r)},t.exports.duotone_lilac=function(t){v(t,A),n.duotone_lilac(t.ptr)},t.exports.duotone_ochre=function(t){v(t,A),n.duotone_ochre(t.ptr)},t.exports.firenze=function(t){v(t,A),n.firenze(t.ptr)},t.exports.obsidian=function(t){v(t,A),n.obsidian(t.ptr)},t.exports.gamma_correction=function(t,e,r,o){v(t,A),n.gamma_correction(t.ptr,e,r,o)},t.exports.hsluv=function(t,e,r){v(t,A);var o=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;n.hsluv(t.ptr,o,_,r)},t.exports.lch=function(t,e,r){v(t,A);var o=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;n.lch(t.ptr,o,_,r)},t.exports.hsl=function(t,e,r){v(t,A);var o=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;n.hsl(t.ptr,o,_,r)},t.exports.hsv=function(t,e,r){v(t,A);var o=b(e,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;n.hsv(t.ptr,o,_,r)},t.exports.hue_rotate_hsl=function(t,e){v(t,A),n.hue_rotate_hsl(t.ptr,e)},t.exports.hue_rotate_hsv=function(t,e){v(t,A),n.hue_rotate_hsv(t.ptr,e)},t.exports.hue_rotate_lch=function(t,e){v(t,A),n.hue_rotate_lch(t.ptr,e)},t.exports.hue_rotate_hsluv=function(t,e){v(t,A),n.hue_rotate_hsluv(t.ptr,e)},t.exports.saturate_hsl=function(t,e){v(t,A),n.saturate_hsl(t.ptr,e)},t.exports.saturate_lch=function(t,e){v(t,A),n.saturate_lch(t.ptr,e)},t.exports.saturate_hsluv=function(t,e){v(t,A),n.saturate_hsluv(t.ptr,e)},t.exports.saturate_hsv=function(t,e){v(t,A),n.saturate_hsv(t.ptr,e)},t.exports.lighten_lch=function(t,e){v(t,A),n.lighten_lch(t.ptr,e)},t.exports.lighten_hsluv=function(t,e){v(t,A),n.lighten_hsluv(t.ptr,e)},t.exports.lighten_hsl=function(t,e){v(t,A),n.lighten_hsl(t.ptr,e)},t.exports.lighten_hsv=function(t,e){v(t,A),n.lighten_hsv(t.ptr,e)},t.exports.darken_lch=function(t,e){v(t,A),n.darken_lch(t.ptr,e)},t.exports.darken_hsluv=function(t,e){v(t,A),n.darken_hsluv(t.ptr,e)},t.exports.darken_hsl=function(t,e){v(t,A),n.darken_hsl(t.ptr,e)},t.exports.darken_hsv=function(t,e){v(t,A),n.darken_hsv(t.ptr,e)},t.exports.desaturate_hsv=function(t,e){v(t,A),n.desaturate_hsv(t.ptr,e)},t.exports.desaturate_hsl=function(t,e){v(t,A),n.desaturate_hsl(t.ptr,e)},t.exports.desaturate_lch=function(t,e){v(t,A),n.desaturate_lch(t.ptr,e)},t.exports.desaturate_hsluv=function(t,e){v(t,A),n.desaturate_hsluv(t.ptr,e)},t.exports.mix_with_colour=function(t,e,r){v(t,A),v(e,E);var o=e.ptr;e.ptr=0,n.mix_with_colour(t.ptr,o,r)},t.exports.watermark=function(t,e,r,o){v(t,A),v(e,A),n.watermark(t.ptr,e.ptr,r,o)},t.exports.blend=function(t,e,r){v(t,A),v(e,A);var o=b(r,n.__wbindgen_malloc,n.__wbindgen_realloc),_=u;n.blend(t.ptr,e.ptr,o,_)},t.exports.create_gradient=function(t,e){var r=n.create_gradient(t,e);return A.__wrap(r)},t.exports.apply_gradient=function(t){v(t,A),n.apply_gradient(t.ptr)},t.exports.noise_reduction=function(t){v(t,A),n.noise_reduction(t.ptr)},t.exports.sharpen=function(t){v(t,A),n.sharpen(t.ptr)},t.exports.edge_detection=function(t){v(t,A),n.edge_detection(t.ptr)},t.exports.identity=function(t){v(t,A),n.identity(t.ptr)},t.exports.box_blur=function(t){v(t,A),n.box_blur(t.ptr)},t.exports.gaussian_blur=function(t,e){v(t,A),n.gaussian_blur(t.ptr,e)},t.exports.detect_horizontal_lines=function(t){v(t,A),n.detect_horizontal_lines(t.ptr)},t.exports.detect_vertical_lines=function(t){v(t,A),n.detect_vertical_lines(t.ptr)},t.exports.detect_45_deg_lines=function(t){v(t,A),n.detect_45_deg_lines(t.ptr)},t.exports.detect_135_deg_lines=function(t){v(t,A),n.detect_135_deg_lines(t.ptr)},t.exports.laplace=function(t){v(t,A),n.laplace(t.ptr)},t.exports.edge_one=function(t){v(t,A),n.edge_one(t.ptr)},t.exports.emboss=function(t){v(t,A),n.emboss(t.ptr)},t.exports.sobel_horizontal=function(t){v(t,A),n.sobel_horizontal(t.ptr)},t.exports.prewitt_horizontal=function(t){v(t,A),n.prewitt_horizontal(t.ptr)},t.exports.sobel_vertical=function(t){v(t,A),n.sobel_vertical(t.ptr)};let I=null;t.exports.SamplingFilter=Object.freeze({Nearest:1,1:"Nearest",Triangle:2,2:"Triangle",CatmullRom:3,3:"CatmullRom",Gaussian:4,4:"Gaussian",Lanczos3:5,5:"Lanczos3"});class A{static __wrap(t){let e=Object.create(A.prototype);return e.ptr=t,e}__destroy_into_raw(){let t=this.ptr;return this.ptr=0,t}free(){let t=this.__destroy_into_raw();n.__wbg_photonimage_free(t)}constructor(t,e,r){var o=y(t,n.__wbindgen_malloc),_=u,i=n.photonimage_new(o,_,e,r);return A.__wrap(i)}static new_from_base64(t){var e=b(t,n.__wbindgen_malloc,n.__wbindgen_realloc),r=u,o=n.base64_to_image(e,r);return A.__wrap(o)}static new_from_byteslice(t){var e=y(t,n.__wbindgen_malloc),r=u,o=n.photonimage_new_from_byteslice(e,r);return A.__wrap(o)}get_width(){return n.photonimage_get_width(this.ptr)>>>0}get_raw_pixels(){try{let o=n.__wbindgen_add_to_stack_pointer(-16);n.photonimage_get_raw_pixels(o,this.ptr);var t=x()[o/4+0],e=x()[o/4+1],r=k(t,e).slice();return n.__wbindgen_free(t,+e),r}finally{n.__wbindgen_add_to_stack_pointer(16)}}get_height(){return n.photonimage_get_height(this.ptr)>>>0}get_base64(){try{let r=n.__wbindgen_add_to_stack_pointer(-16);n.photonimage_get_base64(r,this.ptr);var t=x()[r/4+0],e=x()[r/4+1];return m(t,e)}finally{n.__wbindgen_add_to_stack_pointer(16),n.__wbindgen_free(t,e)}}get_bytes(){try{let o=n.__wbindgen_add_to_stack_pointer(-16);n.photonimage_get_bytes(o,this.ptr);var t=x()[o/4+0],e=x()[o/4+1],r=k(t,e).slice();return n.__wbindgen_free(t,+e),r}finally{n.__wbindgen_add_to_stack_pointer(16)}}get_bytes_jpeg(t){try{let _=n.__wbindgen_add_to_stack_pointer(-16);n.photonimage_get_bytes_jpeg(_,this.ptr,t);var e=x()[_/4+0],r=x()[_/4+1],o=k(e,r).slice();return n.__wbindgen_free(e,+r),o}finally{n.__wbindgen_add_to_stack_pointer(16)}}get_image_data(){return p(n.photonimage_get_image_data(this.ptr))}set_imgdata(t){n.photonimage_set_imgdata(this.ptr,c(t))}}t.exports.PhotonImage=A;class E{static __wrap(t){let e=Object.create(E.prototype);return e.ptr=t,e}__destroy_into_raw(){let t=this.ptr;return this.ptr=0,t}free(){let t=this.__destroy_into_raw();n.__wbg_rgb_free(t)}constructor(t,e,r){var o=n.rgb_new(t,e,r);return E.__wrap(o)}set_red(t){n.rgb_set_red(this.ptr,t)}set_green(t){n.rgb_set_green(this.ptr,t)}set_blue(t){n.rgb_set_blue(this.ptr,t)}get_red(){return n.rgb_get_red(this.ptr)}get_green(){return n.rgb_get_green(this.ptr)}get_blue(){return n.rgb_get_blue(this.ptr)}}t.exports.Rgb=E;class O{static __wrap(t){let e=Object.create(O.prototype);return e.ptr=t,e}__destroy_into_raw(){let t=this.ptr;return this.ptr=0,t}free(){let t=this.__destroy_into_raw();n.__wbg_rgba_free(t)}constructor(t,e,r,o){var _=n.rgba_new(t,e,r,o);return O.__wrap(_)}set_red(t){n.rgb_set_red(this.ptr,t)}set_green(t){n.rgb_set_green(this.ptr,t)}set_blue(t){n.rgb_set_blue(this.ptr,t)}set_alpha(t){n.rgba_set_alpha(this.ptr,t)}get_red(){return n.rgb_get_red(this.ptr)}get_green(){return n.rgb_get_green(this.ptr)}get_blue(){return n.rgb_get_blue(this.ptr)}get_alpha(){return n.rgba_get_alpha(this.ptr)}}t.exports.Rgba=O,t.exports.__wbindgen_object_drop_ref=function(t){p(t)},t.exports.__wbg_new_693216e109162396=function(){return c(Error())},t.exports.__wbg_stack_0ddaca5d1abfb52f=function(t,e){var r=b(a[e].stack,n.__wbindgen_malloc,n.__wbindgen_realloc),o=u;x()[t/4+1]=o,x()[t/4+0]=r},t.exports.__wbg_error_09919627ac0992f5=function(t,e){try{console.error(m(t,e))}finally{n.__wbindgen_free(t,e)}},t.exports.__wbg_instanceof_Window_c4b70662a0d2c5ec=function(t){return a[t]instanceof Window},t.exports.__wbg_document_1c64944725c0d81d=function(t){var e=a[t].document;return null==e?0:c(e)},t.exports.__wbg_body_78ae4fd43b446013=function(t){var e=a[t].body;return null==e?0:c(e)},t.exports.__wbg_createElement_86c152812a141a62=function(){return j(function(t,e,r){return c(a[t].createElement(m(e,r)))},arguments)},t.exports.__wbg_width_16bd64d09cbf5661=function(t){return a[t].width},t.exports.__wbg_height_368bb86c37d51bc9=function(t){return a[t].height},t.exports.__wbg_data_1ae7496c58caf755=function(t,e){var r=y(a[e].data,n.__wbindgen_malloc),o=u;x()[t/4+1]=o,x()[t/4+0]=r},t.exports.__wbg_newwithu8clampedarrayandsh_1b8c6e1bede43657=function(){return j(function(t,e,r,o){return c(new ImageData(((null===I||I.buffer!==n.memory.buffer)&&(I=new Uint8ClampedArray(n.memory.buffer)),I).subarray(t/1,t/1+e),r>>>0,o>>>0))},arguments)},t.exports.__wbg_instanceof_CanvasRenderingContext2d_3abbe7ec7af32cae=function(t){return a[t]instanceof CanvasRenderingContext2D},t.exports.__wbg_drawImage_9e2d13329d92a0a3=function(){return j(function(t,e,r,n,o,_,i,s,p,c){a[t].drawImage(a[e],r,n,o,_,i,s,p,c)},arguments)},t.exports.__wbg_getImageData_9ffc3df78ca3dbc9=function(){return j(function(t,e,r,n,o){return c(a[t].getImageData(e,r,n,o))},arguments)},t.exports.__wbg_putImageData_b9544b271e569392=function(){return j(function(t,e,r,n){a[t].putImageData(a[e],r,n)},arguments)},t.exports.__wbg_settextContent_799ebbf96e16265d=function(t,e,r){a[t].textContent=0===e?void 0:m(e,r)},t.exports.__wbg_appendChild_d318db34c4559916=function(){return j(function(t,e){return c(a[t].appendChild(a[e]))},arguments)},t.exports.__wbg_instanceof_HtmlCanvasElement_25d964a0dde6717e=function(t){return a[t]instanceof HTMLCanvasElement},t.exports.__wbg_width_555f63ab09ba7d3f=function(t){return a[t].width},t.exports.__wbg_setwidth_c1a7061891b71f25=function(t,e){a[t].width=e>>>0},t.exports.__wbg_height_7153faec70fbaf7b=function(t){return a[t].height},t.exports.__wbg_setheight_88894b05710ff752=function(t,e){a[t].height=e>>>0},t.exports.__wbg_getContext_f701d0231ae22393=function(){return j(function(t,e,r){var n=a[t].getContext(m(e,r));return null==n?0:c(n)},arguments)},t.exports.__wbg_newnoargs_be86524d73f67598=function(t,e){return c(Function(m(t,e)))},t.exports.__wbg_call_888d259a5fefc347=function(){return j(function(t,e){return c(a[t].call(a[e]))},arguments)},t.exports.__wbindgen_object_clone_ref=function(t){return c(a[t])},t.exports.__wbg_self_c6fbdfc2918d5e58=function(){return j(function(){return c(self.self)},arguments)},t.exports.__wbg_window_baec038b5ab35c54=function(){return j(function(){return c(window.window)},arguments)},t.exports.__wbg_globalThis_3f735a5746d41fbd=function(){return j(function(){return c(globalThis.globalThis)},arguments)},t.exports.__wbg_global_1bc0b39582740e95=function(){return j(function(){return c(r.g.global)},arguments)},t.exports.__wbindgen_is_undefined=function(t){return void 0===a[t]},t.exports.__wbindgen_debug_string=function(t,e){var r=b(function t(e){let r,n=typeof e;if("number"==n||"boolean"==n||null==e)return`${e}`;if("string"==n)return`"${e}"`;if("symbol"==n){let t=e.description;return null==t?"Symbol":`Symbol(${t})`}if("function"==n){let t=e.name;return"string"==typeof t&&t.length>0?`Function(${t})`:"Function"}if(Array.isArray(e)){let r=e.length,n="[";r>0&&(n+=t(e[0]));for(let o=1;o<r;o++)n+=", "+t(e[o]);return n+"]"}let o=/\[object ([^\]]+)\]/.exec(toString.call(e));if(!(o.length>1))return toString.call(e);if("Object"==(r=o[1]))try{return"Object("+JSON.stringify(e)+")"}catch(t){return"Object"}return e instanceof Error?`${e.name}: ${e.message}
2
- ${e.stack}`:r}(a[e]),n.__wbindgen_malloc,n.__wbindgen_realloc),o=u;x()[t/4+1]=o,x()[t/4+0]=r},t.exports.__wbindgen_throw=function(t,e){throw Error(m(t,e))},t.exports.__wbindgen_rethrow=function(t){throw p(t)};let D=r(77410).join("/","photon_rs_bg.wasm"),$=r(34225).readFileSync(D),S=new WebAssembly.Module($);n=new WebAssembly.Instance(S,o).exports,t.exports.__wasm=n}}]);
3
- //# sourceMappingURL=173.9cf6b074.js.map
@@ -1,158 +0,0 @@
1
- "use strict";(self.webpackChunkplayground=self.webpackChunkplayground||[]).push([["212"],{52818:function(e,t,r){var i=r(91957);class s{static init(e){Object.defineProperty(this,"resizeTo",{set(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{let e,t;if(this._resizeTo){if(this._cancelResize(),this._resizeTo===globalThis.window)e=globalThis.innerWidth,t=globalThis.innerHeight;else{let{clientWidth:r,clientHeight:i}=this._resizeTo;e=r,t=i}this.renderer.resize(e,t),this.render()}},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}s.extension=i.nw.Application;var a=r(95909),n=r(96743);class l{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,a.u.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?n.v.shared:new n.v,e.autoStart&&this.start()}static destroy(){if(this._ticker){let e=this._ticker;this.ticker=null,e.destroy()}}}l.extension=i.nw.Application,i.Rw.add(s),i.Rw.add(l)},24508:function(e,t,r){var i=r(91957);class s{constructor(e){this._renderer=e}push(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){"pushFilter"===e.action?this._renderer.filter.push(e):"popFilter"===e.action&&this._renderer.filter.pop()}destroy(){this._renderer=null}}s.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"filter"};var a=r(30044),n=r(87246),l=r(49458),o=r(73531),h=r(73109),d=r(41277),u=r(50900),c=r(71423),p=r(39622),f=r(51141);let g=new a.y;var m=r(92245);let x=new o.Z({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),location:0,format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class _{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new h.o({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new l.v({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){let t=this.renderer,r=e.filterEffect.filters;this._filterStack[this._filterStackIndex]||(this._filterStack[this._filterStackIndex]=this._getFilterData());let i=this._filterStack[this._filterStackIndex];if(this._filterStackIndex++,0===r.length){i.skip=!0;return}let s=i.bounds;if(e.renderables)!function(e,t){t.clear();let r=t.matrix;for(let r=0;r<e.length;r++){let i=e[r];i.globalDisplayStatus<7||(t.matrix=i.worldTransform,i.addBounds(t))}t.matrix=r}(e.renderables,s);else if(e.filterEffect.filterArea)s.clear(),s.addRect(e.filterEffect.filterArea),s.applyMatrix(e.container.worldTransform);else{var a;a=e.container,s.clear(),function e(t,r){if(7!==t.localDisplayStatus||!t.measurable)return;let i=!!t.effects.length,s=r;if((t.isRenderGroupRoot||i)&&(s=f.W.get().clear()),t.boundsArea)r.addRect(t.boundsArea,t.worldTransform);else{if(t.renderPipeId){let e=t.bounds;s.addFrame(e.minX,e.minY,e.maxX,e.maxY,t.groupTransform)}let r=t.children;for(let t=0;t<r.length;t++)e(r[t],s)}if(i){let e=!1;for(let r=0;r<t.effects.length;r++)t.effects[r].addBounds&&(e||(e=!0,s.applyMatrix(t.renderGroup.worldTransform)),t.effects[r].addBounds(s,!0));e&&(s.applyMatrix(t.renderGroup.worldTransform.copyTo(g).invert()),r.addBounds(s,t.relativeGroupTransform)),r.addBounds(s),f.W.return(s)}else t.isRenderGroupRoot&&(r.addBounds(s,t.relativeGroupTransform),f.W.return(s))}(a,s),s.isValid||s.set(0,0,0,0),a.isRenderGroupRoot?s.applyMatrix(a.renderGroup.localTransform):s.applyMatrix(a.renderGroup.worldTransform)}let n=t.renderTarget.rootRenderTarget.colorTexture.source,l=n._resolution,o=0,h=n.antialias,d=!1,c=!1;for(let e=0;e<r.length;e++){let i=r[e];if(l=Math.min(l,i.resolution),o+=i.padding,"inherit"!==i.antialias&&(h="on"===i.antialias),!(i.compatibleRenderers&t.type)){c=!1;break}if(i.blendRequired&&!(t.backBuffer?.useBackBuffer??!0)){(0,m.Z)("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),c=!1;break}c=i.enabled||c,d=d||i.blendRequired}if(!c){i.skip=!0;return}let p=t.renderTarget.rootViewPort;if(s.scale(l).fitBounds(0,p.width,0,p.height).scale(1/l).pad(o).ceil(),!s.isPositive){i.skip=!0;return}i.skip=!1,i.bounds=s,i.blendRequired=d,i.container=e.container,i.filterEffect=e.filterEffect,i.previousRenderSurface=t.renderTarget.renderSurface,i.inputTexture=u.z.getOptimalTexture(s.width,s.height,l,h),t.renderTarget.bind(i.inputTexture,!0),t.globalUniforms.push({offset:s})}pop(){let e=this.renderer;this._filterStackIndex--;let t=this._filterStack[this._filterStackIndex];if(t.skip)return;this._activeFilterData=t;let r=t.inputTexture,i=t.bounds,s=d.x.EMPTY;if(e.renderTarget.finishRenderPass(),t.blendRequired){let r=this._filterStackIndex>0?this._filterStack[this._filterStackIndex-1].bounds:null,a=e.renderTarget.getRenderTarget(t.previousRenderSurface);s=this.getBackTexture(a,i,r)}t.backTexture=s;let a=t.filterEffect.filters;if(this._globalFilterBindGroup.setResource(r.source.style,2),this._globalFilterBindGroup.setResource(s.source,3),e.globalUniforms.pop(),1===a.length)a[0].apply(this,r,t.previousRenderSurface,!1),u.z.returnTexture(r);else{let e=t.inputTexture,r=u.z.getOptimalTexture(i.width,i.height,e.source._resolution,!1),s=0;for(s=0;s<a.length-1;++s){a[s].apply(this,e,r,!0);let t=e;e=r,r=t}a[s].apply(this,e,t.previousRenderSurface,!1),u.z.returnTexture(e),u.z.returnTexture(r)}t.blendRequired&&u.z.returnTexture(s)}getBackTexture(e,t,r){let i=e.colorTexture.source._resolution,s=u.z.getOptimalTexture(t.width,t.height,i,!1),a=t.minX,n=t.minY;r&&(a-=r.minX,n-=r.minY),a=Math.floor(a*i),n=Math.floor(n*i);let l=Math.ceil(t.width*i),o=Math.ceil(t.height*i);return this.renderer.renderTarget.copyToTexture(e,s,{x:a,y:n},{width:l,height:o},{x:0,y:0}),s}applyFilter(e,t,r,i){let s=this.renderer,a=this._filterStack[this._filterStackIndex],l=a.bounds,o=n.E.shared,h=a.previousRenderSurface===r,u=this.renderer.renderTarget.rootRenderTarget.colorTexture.source._resolution,p=this._filterStackIndex-1;for(;p>0&&this._filterStack[p].skip;)--p;p>0&&(u=this._filterStack[p].inputTexture.source._resolution);let f=this._filterGlobalUniforms,g=f.uniforms,m=g.uOutputFrame,_=g.uInputSize,b=g.uInputPixel,y=g.uInputClamp,w=g.uGlobalFrame,T=g.uOutputTexture;if(h){let e=this._filterStackIndex;for(;e>0;){e--;let t=this._filterStack[this._filterStackIndex-1];if(!t.skip){o.x=t.bounds.minX,o.y=t.bounds.minY;break}}m[0]=l.minX-o.x,m[1]=l.minY-o.y}else m[0]=0,m[1]=0;m[2]=t.frame.width,m[3]=t.frame.height,_[0]=t.source.width,_[1]=t.source.height,_[2]=1/_[0],_[3]=1/_[1],b[0]=t.source.pixelWidth,b[1]=t.source.pixelHeight,b[2]=1/b[0],b[3]=1/b[1],y[0]=.5*b[2],y[1]=.5*b[3],y[2]=t.frame.width*_[2]-.5*b[2],y[3]=t.frame.height*_[3]-.5*b[3];let v=this.renderer.renderTarget.rootRenderTarget.colorTexture;w[0]=o.x*u,w[1]=o.y*u,w[2]=v.source.width*u,w[3]=v.source.height*u;let S=this.renderer.renderTarget.getRenderTarget(r);if(s.renderTarget.bind(r,!!i),r instanceof d.x?(T[0]=r.frame.width,T[1]=r.frame.height):(T[0]=S.width,T[1]=S.height),T[2]=S.isRoot?-1:1,f.update(),s.renderPipes.uniformBatch){let e=s.renderPipes.uniformBatch.getUboResource(f);this._globalFilterBindGroup.setResource(e,0)}else this._globalFilterBindGroup.setResource(f,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,s.encoder.draw({geometry:x,shader:e,state:e._state,topology:"triangle-list"}),s.type===c.g.WEBGL&&s.renderTarget.finishRenderPass()}_getFilterData(){return{skip:!1,inputTexture:null,bounds:new p.Y,container:null,filterEffect:null,blendRequired:!1,previousRenderSurface:null}}calculateSpriteMatrix(e,t){let r=this._activeFilterData,i=e.set(r.inputTexture._source.width,0,0,r.inputTexture._source.height,r.bounds.minX,r.bounds.minY),s=t.worldTransform.copyTo(a.y.shared);return s.invert(),i.prepend(s),i.scale(1/t.texture.frame.width,1/t.texture.frame.height),i.translate(t.anchor.x,t.anchor.y),i}}_.extension={type:[i.nw.WebGLSystem,i.nw.WebGPUSystem],name:"filter"},i.Rw.add(_),i.Rw.add(s)},17094:function(e,t,r){r.d(t,{y:()=>n});var i=r(29465),s=r(73109);let a=new Int32Array(i.A);for(let e=0;e<i.A;e++)a[e]=e;let n=new s.o({uTextures:{value:a,type:"i32",size:i.A}},{isStatic:!0})},51982:function(e,t,r){r.d(t,{h:()=>a});var i=r(767),s=r(45854);let a=new class{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){let r=i.z.get().createCanvas();r.width=e,r.height=t;let s=r.getContext("2d");return{canvas:r,context:s}}getOptimalCanvasAndContext(e,t,r=1){e=Math.ceil(e*r-1e-6),t=Math.ceil(t*r-1e-6),e=(0,s.a9)(e),t=(0,s.a9)(t);let i=(e<<17)+(t<<1);this._canvasPool[i]||(this._canvasPool[i]=[]);let a=this._canvasPool[i].pop();return a||(a=this._createCanvasAndContext(e,t)),a}returnCanvasAndContext(e){let{width:t,height:r}=e.canvas;this._canvasPool[(t<<17)+(r<<1)].push(e)}clear(){this._canvasPool={}}}},42454:function(e,t,r){var i=r(91957),s=r(62014),a=r(29492),n=r(24951),l=r(23947),o=r(48876);class h{constructor(e,t){this.state=a.Z.for2d(),this._graphicsBatchesHash=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){let t=e.context,r=!!this._graphicsBatchesHash[e.uid],i=this.renderer.graphicsContext.updateGpuContext(t);return!!i.isBatchable||r!==i.isBatchable}addRenderable(e,t){let r=this.renderer.graphicsContext.updateGpuContext(e.context);e._didGraphicsUpdate&&(e._didGraphicsUpdate=!1,this._rebuild(e)),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){let t=this._graphicsBatchesHash[e.uid];if(t)for(let e=0;e<t.length;e++){let r=t[e];r.batcher.updateElement(r)}}destroyRenderable(e){this._graphicsBatchesHash[e.uid]&&this._removeBatchForRenderable(e.uid)}execute(e){if(!e.isRenderable)return;let t=this.renderer,r=e.context;if(!t.graphicsContext.getGpuContext(r).batches.length)return;let i=r.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;let s=i.resources.localUniforms.uniforms;s.uTransformMatrix=e.groupTransform,s.uRound=t._roundPixels|e._roundPixels,(0,l.V)(e.groupColorAlpha,s.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){let t=!!this._graphicsBatchesHash[e.uid],r=this.renderer.graphicsContext.updateGpuContext(e.context);t&&this._removeBatchForRenderable(e.uid),r.isBatchable&&this._initBatchesForRenderable(e),e.batched=r.isBatchable}_addToBatcher(e,t){let r=this.renderer.renderPipes.batch,i=this._getBatchesForRenderable(e);for(let e=0;e<i.length;e++){let s=i[e];r.addToBatch(s,t)}}_getBatchesForRenderable(e){return this._graphicsBatchesHash[e.uid]||this._initBatchesForRenderable(e)}_initBatchesForRenderable(e){let t=e.context,r=this.renderer.graphicsContext.getGpuContext(t),i=this.renderer._roundPixels|e._roundPixels,s=r.batches.map(t=>{let r=n.u.get(o.I);return t.copyTo(r),r.renderable=e,r.roundPixels=i,r});return this._graphicsBatchesHash[e.uid]=s,e.on("destroyed",()=>{this.destroyRenderable(e)}),s}_removeBatchForRenderable(e){this._graphicsBatchesHash[e].forEach(e=>{n.u.return(e)}),this._graphicsBatchesHash[e]=null}destroy(){for(let e in this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null,this._graphicsBatchesHash)this._removeBatchForRenderable(e);this._graphicsBatchesHash=null}}h.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"graphics"},i.Rw.add(h),i.Rw.add(s.hJ)},30773:function(e,t,r){var i=r(91957),s=r(30044),a=r(49458),n=r(73109),l=r(24951),o=r(23947),h=r(32594);class d{constructor(e,t){this.localUniforms=new n.o({uTransformMatrix:{value:new s.y,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new a.v({0:this.localUniforms}),this._meshDataHash=Object.create(null),this._gpuBatchableMeshHash=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){let t=this._getMeshData(e),r=t.batched,i=e.batched;if(t.batched=i,r!==i)return!0;if(i){let r=e._geometry;if(r.indices.length!==t.indexSize||r.positions.length!==t.vertexSize)return t.indexSize=r.indices.length,t.vertexSize=r.positions.length,!0;let i=this._getBatchableMesh(e),s=e.texture;if(i.texture._source!==s._source&&i.texture._source!==s._source)return!i.batcher.checkAndUpdateTexture(i,s)}return!1}addRenderable(e,t){let r=this.renderer.renderPipes.batch,{batched:i}=this._getMeshData(e);if(i){let t=this._getBatchableMesh(e);t.texture=e._texture,t.geometry=e._geometry,r.addToBatch(t)}else r.break(t),t.add({renderPipeId:"mesh",mesh:e})}updateRenderable(e){if(e.batched){let t=this._gpuBatchableMeshHash[e.uid];t.texture=e._texture,t.geometry=e._geometry,t.batcher.updateElement(t)}}destroyRenderable(e){this._meshDataHash[e.uid]=null;let t=this._gpuBatchableMeshHash[e.uid];t&&(l.u.return(t),this._gpuBatchableMeshHash[e.uid]=null)}execute({mesh:e}){if(!e.isRenderable)return;e.state.blendMode=e.groupBlendMode;let t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),(0,o.V)(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){return this._meshDataHash[e.uid]||this._initMeshData(e)}_initMeshData(e){return this._meshDataHash[e.uid]={batched:e.batched,indexSize:e._geometry.indices?.length,vertexSize:e._geometry.positions?.length},e.on("destroyed",()=>{this.destroyRenderable(e)}),this._meshDataHash[e.uid]}_getBatchableMesh(e){return this._gpuBatchableMeshHash[e.uid]||this._initBatchableMesh(e)}_initBatchableMesh(e){let t=l.u.get(h.X);return t.mesh=e,t.texture=e._texture,t.roundPixels=this.renderer._roundPixels|e._roundPixels,this._gpuBatchableMeshHash[e.uid]=t,t.mesh=e,t}destroy(){for(let e in this._gpuBatchableMeshHash)this._gpuBatchableMeshHash[e]&&l.u.return(this._gpuBatchableMeshHash[e]);this._gpuBatchableMeshHash=null,this._meshDataHash=null,this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}d.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"mesh"},i.Rw.add(d)},32594:function(e,t,r){r.d(t,{X:()=>i});class i{constructor(){this.batcher=null,this.batch=null,this.roundPixels=0,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}get blendMode(){return this.mesh.groupBlendMode}reset(){this.mesh=null,this.texture=null,this.batcher=null,this.batch=null}packIndex(e,t,r){let i=this.geometry.indices;for(let s=0;s<i.length;s++)e[t++]=i[s]+r}packAttributes(e,t,r,i){let s=this.mesh,a=this.geometry,n=s.groupTransform,l=i<<16|65535&this.roundPixels,o=n.a,h=n.b,d=n.c,u=n.d,c=n.tx,p=n.ty,f=a.positions,g=a.getBuffer("aUV"),m=g.data,x=m,_=this.texture.textureMatrix;_.isSimple||(x=this._transformedUvs,(this._textureMatrixUpdateId!==_._updateID||this._uvUpdateId!==g._updateID)&&((!x||x.length<m.length)&&(x=this._transformedUvs=new Float32Array(m.length)),this._textureMatrixUpdateId=_._updateID,this._uvUpdateId=g._updateID,_.multiplyUvs(m,x)));let b=s.groupColorAlpha;for(let i=0;i<f.length;i+=2){let s=f[i],a=f[i+1];e[r]=o*s+d*a+c,e[r+1]=h*s+u*a+p,e[r+2]=x[i],e[r+3]=x[i+1],t[r+4]=b,t[r+5]=l,r+=6}}get vertexSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}},14738:function(e,t,r){r.d(t,{x:()=>o});var i=r(36697),s=r(74821),a=r(73531),n=r(24584);let l=class e extends a.Z{constructor(...t){let r=t[0]??{};r instanceof Float32Array&&((0,n.a)(n.P,"use new MeshGeometry({ positions, uvs, indices }) instead"),r={positions:r,uvs:t[1],indices:t[2]});let a=(r={...e.defaultOptions,...r}).positions||new Float32Array([0,0,1,0,1,1,0,1]),l=r.uvs||new Float32Array([0,0,1,0,1,1,0,1]),o=r.indices||new Uint32Array([0,1,2,0,2,3]),h=r.shrinkBuffersToFit,d=new i.l({data:a,label:"attribute-mesh-positions",shrinkToFit:h,usage:s.F.VERTEX|s.F.COPY_DST});super({attributes:{aPosition:{buffer:d,format:"float32x2",stride:8,offset:0},aUV:{buffer:new i.l({data:l,label:"attribute-mesh-uvs",shrinkToFit:h,usage:s.F.VERTEX|s.F.COPY_DST}),format:"float32x2",stride:8,offset:0}},indexBuffer:new i.l({data:o,label:"index-mesh-buffer",shrinkToFit:h,usage:s.F.INDEX|s.F.COPY_DST}),topology:r.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};l.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let o=l},34354:function(e,t,r){var i=r(91957),s=r(24951),a=r(32594),n=r(24584),l=r(14738);let o=class e extends l.x{constructor(...e){super({});let t=e[0]??{};"number"==typeof t&&((0,n.a)(n.P,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(t){t={...e.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;let r=this.verticesX*this.verticesY,i=[],s=[],a=[],n=this.verticesX-1,l=this.verticesY-1,o=this.width/n,h=this.height/l;for(let e=0;e<r;e++){let t=e%this.verticesX,r=e/this.verticesX|0;i.push(t*o,r*h),s.push(t/n,r/l)}let d=n*l;for(let e=0;e<d;e++){let t=e%n,r=e/n|0,i=r*this.verticesX+t,s=r*this.verticesX+t+1,l=(r+1)*this.verticesX+t,o=(r+1)*this.verticesX+t+1;a.push(i,s,l,s,o,l)}this.buffers[0].data=new Float32Array(i),this.buffers[1].data=new Float32Array(s),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};o.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let h=o,d=class e extends h{constructor(t={}){t={...e.defaultOptions,...t},super({width:t.width,height:t.height,verticesX:4,verticesY:4}),this.update(t)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this.updateUvs(),this.updatePositions()}updatePositions(){let e=this.positions,t=this._leftWidth+this._rightWidth,r=this.width>t?1:this.width/t,i=this._topHeight+this._bottomHeight,s=Math.min(r,this.height>i?1:this.height/i);e[9]=e[11]=e[13]=e[15]=this._topHeight*s,e[17]=e[19]=e[21]=e[23]=this.height-this._bottomHeight*s,e[25]=e[27]=e[29]=e[31]=this.height,e[2]=e[10]=e[18]=e[26]=this._leftWidth*s,e[4]=e[12]=e[20]=e[28]=this.width-this._rightWidth*s,e[6]=e[14]=e[22]=e[30]=this.width,this.getBuffer("aPosition").update()}updateUvs(){let e=this.uvs;e[0]=e[8]=e[16]=e[24]=0,e[1]=e[3]=e[5]=e[7]=0,e[6]=e[14]=e[22]=e[30]=1,e[25]=e[27]=e[29]=e[31]=1;let t=1/this._originalWidth,r=1/this._originalHeight;e[2]=e[10]=e[18]=e[26]=t*this._leftWidth,e[9]=e[11]=e[13]=e[15]=r*this._topHeight,e[4]=e[12]=e[20]=e[28]=1-t*this._rightWidth,e[17]=e[19]=e[21]=e[23]=1-r*this._bottomHeight,this.getBuffer("aUV").update()}};d.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};class u{constructor(e){this._gpuSpriteHash=Object.create(null),this._renderer=e}addRenderable(e,t){let r=this._getGpuSprite(e);e._didSpriteUpdate&&this._updateBatchableSprite(e,r),this._renderer.renderPipes.batch.addToBatch(r)}updateRenderable(e){let t=this._gpuSpriteHash[e.uid];e._didSpriteUpdate&&this._updateBatchableSprite(e,t),t.batcher.updateElement(t)}validateRenderable(e){let t=e._texture,r=this._getGpuSprite(e);return r.texture._source!==t._source&&!r.batcher.checkAndUpdateTexture(r,t)}destroyRenderable(e){let t=this._gpuSpriteHash[e.uid];s.u.return(t),this._gpuSpriteHash[e.uid]=null}_updateBatchableSprite(e,t){e._didSpriteUpdate=!1,t.geometry.update(e),t.texture=e._texture}_getGpuSprite(e){return this._gpuSpriteHash[e.uid]||this._initGPUSprite(e)}_initGPUSprite(e){let t=new a.X;return t.geometry=new d,t.mesh=e,t.texture=e._texture,t.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuSpriteHash[e.uid]=t,e.on("destroyed",()=>{this.destroyRenderable(e)}),t}destroy(){for(let e in this._gpuSpriteHash)this._gpuSpriteHash[e].geometry.destroy();this._gpuSpriteHash=null,this._renderer=null}}u.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"nineSliceSprite"},i.Rw.add(u)},28803:function(e,t,r){let i,s;var a=r(91957),n=r(29492),l=r(71423),o=r(23947),h=r(32594),d=r(14738),u=r(30044),c=r(43200),p=r(78300),f=r(71067),g=r(8482),m=r(73109),x=r(41277);let _={name:"tiling-bit",vertex:{header:`
2
- struct TilingUniforms {
3
- uMapCoord:mat3x3<f32>,
4
- uClampFrame:vec4<f32>,
5
- uClampOffset:vec2<f32>,
6
- uTextureTransform:mat3x3<f32>,
7
- uSizeAnchor:vec4<f32>
8
- };
9
-
10
- @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
11
- @group(2) @binding(1) var uTexture: texture_2d<f32>;
12
- @group(2) @binding(2) var uSampler: sampler;
13
- `,main:`
14
- uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
15
-
16
- position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
17
- `},fragment:{header:`
18
- struct TilingUniforms {
19
- uMapCoord:mat3x3<f32>,
20
- uClampFrame:vec4<f32>,
21
- uClampOffset:vec2<f32>,
22
- uTextureTransform:mat3x3<f32>,
23
- uSizeAnchor:vec4<f32>
24
- };
25
-
26
- @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
27
- @group(2) @binding(1) var uTexture: texture_2d<f32>;
28
- @group(2) @binding(2) var uSampler: sampler;
29
- `,main:`
30
-
31
- var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
32
- coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
33
- var unclamped = coord;
34
- coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
35
-
36
- var bias = 0.;
37
-
38
- if(unclamped.x == coord.x && unclamped.y == coord.y)
39
- {
40
- bias = -32.;
41
- }
42
-
43
- outColor = textureSampleBias(uTexture, uSampler, coord, bias);
44
- `}},b={name:"tiling-bit",vertex:{header:`
45
- uniform mat3 uTextureTransform;
46
- uniform vec4 uSizeAnchor;
47
-
48
- `,main:`
49
- uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
50
-
51
- position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
52
- `},fragment:{header:`
53
- uniform sampler2D uTexture;
54
- uniform mat3 uMapCoord;
55
- uniform vec4 uClampFrame;
56
- uniform vec2 uClampOffset;
57
- `,main:`
58
-
59
- vec2 coord = vUV + ceil(uClampOffset - vUV);
60
- coord = (uMapCoord * vec3(coord, 1.0)).xy;
61
- vec2 unclamped = coord;
62
- coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
63
-
64
- outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
65
-
66
- `}};class y extends g.e{constructor(){i??(i=(0,c.d)({name:"tiling-sprite-shader",bits:[p.XH,_,f.j]})),s??(s=(0,c.o)({name:"tiling-sprite-shader",bits:[p.$g,b,f.X]})),super({glProgram:s,gpuProgram:i,resources:{localUniforms:new m.o({uTransformMatrix:{value:new u.y,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:new m.o({uMapCoord:{value:new u.y,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new u.y,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}}),uTexture:x.x.EMPTY.source,uSampler:x.x.EMPTY.source.style}})}updateUniforms(e,t,r,i,s,a){let n=this.resources.tilingUniforms,l=a.width,o=a.height,h=a.textureMatrix,d=n.uniforms.uTextureTransform;d.set(r.a*l/e,r.b*l/t,r.c*o/e,r.d*o/t,r.tx/e,r.ty/t),d.invert(),n.uniforms.uMapCoord=h.mapCoord,n.uniforms.uClampFrame=h.uClampFrame,n.uniforms.uClampOffset=h.uClampOffset,n.uniforms.uTextureTransform=d,n.uniforms.uSizeAnchor[0]=e,n.uniforms.uSizeAnchor[1]=t,n.uniforms.uSizeAnchor[2]=i,n.uniforms.uSizeAnchor[3]=s,a&&(this.resources.uTexture=a.source,this.resources.uSampler=a.source.style)}}class w extends d.x{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}let T=new w;class v{constructor(e){this._tilingSpriteDataHash=Object.create(null),this._renderer=e}validateRenderable(e){let t=this._getTilingSpriteData(e),r=t.canBatch;this._updateCanBatch(e);let i=t.canBatch;if(i&&i===r){let{batchableMesh:r}=t;if(r.texture._source!==e.texture._source)return!r.batcher.checkAndUpdateTexture(r,e.texture)}return r!==i}addRenderable(e,t){let r=this._renderer.renderPipes.batch;this._updateCanBatch(e);let i=this._getTilingSpriteData(e),{geometry:s,canBatch:a}=i;if(a){i.batchableMesh||(i.batchableMesh=new h.X);let t=i.batchableMesh;e._didTilingSpriteUpdate&&(e._didTilingSpriteUpdate=!1,this._updateBatchableMesh(e),t.geometry=s,t.mesh=e,t.texture=e._texture),t.roundPixels=this._renderer._roundPixels|e._roundPixels,r.addToBatch(t)}else r.break(t),i.shader||(i.shader=new y),this.updateRenderable(e),t.add(e)}execute(e){let{shader:t}=this._tilingSpriteDataHash[e.uid];t.groups[0]=this._renderer.globalUniforms.bindGroup;let r=t.resources.localUniforms.uniforms;r.uTransformMatrix=e.groupTransform,r.uRound=this._renderer._roundPixels|e._roundPixels,(0,o.V)(e.groupColorAlpha,r.uColor,0),this._renderer.encoder.draw({geometry:T,shader:t,state:n.Z.default2d})}updateRenderable(e){let t=this._getTilingSpriteData(e),{canBatch:r}=t;if(r){let{batchableMesh:r}=t;e._didTilingSpriteUpdate&&this._updateBatchableMesh(e),r.batcher.updateElement(r)}else if(e._didTilingSpriteUpdate){let{shader:r}=t;r.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}e._didTilingSpriteUpdate=!1}destroyRenderable(e){let t=this._getTilingSpriteData(e);t.batchableMesh=null,t.shader?.destroy(),this._tilingSpriteDataHash[e.uid]=null}_getTilingSpriteData(e){return this._tilingSpriteDataHash[e.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){let t=new d.x({indices:T.indices,positions:T.positions.slice(),uvs:T.uvs.slice()});return this._tilingSpriteDataHash[e.uid]={canBatch:!0,renderable:e,geometry:t},e.on("destroyed",()=>{this.destroyRenderable(e)}),this._tilingSpriteDataHash[e.uid]}_updateBatchableMesh(e){let{geometry:t}=this._getTilingSpriteData(e),r=e.texture.source.style;"repeat"!==r.addressMode&&(r.addressMode="repeat",r.update()),function(e,t){let r=e.texture,i=r.frame.width,s=r.frame.height,a=0,n=0;e._applyAnchorToTexture&&(a=e.anchor.x,n=e.anchor.y),t[0]=t[6]=-a,t[2]=t[4]=1-a,t[1]=t[3]=-n,t[5]=t[7]=1-n;let l=u.y.shared;l.copyFrom(e._tileTransform.matrix),l.tx/=e.width,l.ty/=e.height,l.invert(),l.scale(e.width/i,e.height/s),function(e,t,r,i){let s=0,a=e.length/2,n=i.a,l=i.b,o=i.c,h=i.d,d=i.tx,u=i.ty;for(r*=2;s<a;){let i=e[r],a=e[r+1];e[r]=n*i+o*a+d,e[r+1]=l*i+h*a+u,r+=t,s++}}(t,2,0,l)}(e,t.uvs);var i=t.positions;let s=e.anchor.x,a=e.anchor.y;i[0]=-s*e.width,i[1]=-a*e.height,i[2]=(1-s)*e.width,i[3]=-a*e.height,i[4]=(1-s)*e.width,i[5]=(1-a)*e.height,i[6]=-s*e.width,i[7]=(1-a)*e.height}destroy(){for(let e in this._tilingSpriteDataHash)this.destroyRenderable(this._tilingSpriteDataHash[e].renderable);this._tilingSpriteDataHash=null,this._renderer=null}_updateCanBatch(e){let t=this._getTilingSpriteData(e),r=e.texture,i=!0;return this._renderer.type===l.g.WEBGL&&(i=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=r.textureMatrix.isSimple&&(i||r.source.isPowerOfTwo),t.canBatch}}v.extension={type:[a.nw.WebGLPipes,a.nw.WebGPUPipes,a.nw.CanvasPipes],name:"tilingSprite"},a.Rw.add(v)},53828:function(e,t,r){var i=r(91957),s=r(79886),a=r(86160),n=r(767),l=r(15792),o=r(45266),h=r(41277),d=r(72193),u=r(24584);class c extends d.Z{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return(0,u.a)(u.P,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return(0,u.a)(u.P,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return(0,u.a)(u.P,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return(0,u.a)(u.P,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return(0,u.a)(u.P,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(e=!1){for(let e in this.emit("destroy",this),this.removeAllListeners(),this.chars)this.chars[e].texture.destroy();this.chars=null,e&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}var p=r(45158),f=r(82175),g=r(32036),m=r(51982),x=r(31315),_=r(24332),b=r(92007),y=r(29331);function w(e){if(""===e)return[];"string"==typeof e&&(e=[e]);let t=[];for(let r=0,i=e.length;r<i;r++){let i=e[r];if(Array.isArray(i)){if(2!==i.length)throw Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${i.length}.`);if(0===i[0].length||0===i[1].length)throw Error("[BitmapFont]: Invalid character delimiter.");let e=i[0].charCodeAt(0),r=i[1].charCodeAt(0);if(r<e)throw Error("[BitmapFont]: Invalid character range.");for(let i=e;i<=r;i++)t.push(String.fromCharCode(i))}else t.push(...Array.from(i))}if(0===t.length)throw Error("[BitmapFont]: Empty set when resolving characters.");return t}class T extends c{constructor(e){super(),this.resolution=1,this.pages=[],this._padding=4,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentPageIndex=-1,this._skipKerning=!1;let t=e.style.clone();e.overrideFill&&(t._fill.color=0xffffff,t._fill.alpha=1,t._fill.texture=h.x.WHITE,t._fill.fill=null);let r=t.fontSize;t.fontSize=this.baseMeasurementFontSize;let i=(0,b.M)(t);e.overrideSize?t._stroke&&(t._stroke.width*=this.baseRenderedFontSize/r):t.fontSize=this.baseRenderedFontSize=r,this._style=t,this._skipKerning=e.skipKerning??!1,this.resolution=e.resolution??1,this._padding=e.padding??4,this.fontMetrics=_.c.measureFont(i),this.lineHeight=t.lineHeight||this.fontMetrics.fontSize||t.fontSize}ensureCharacters(e){let t,r=w(e).filter(e=>!this._currentChars.includes(e)).filter((e,t,r)=>r.indexOf(e)===t);if(!r.length)return;this._currentChars=[...this._currentChars,...r];let{canvas:i,context:s}=(t=-1===this._currentPageIndex?this._nextPage():this.pages[this._currentPageIndex]).canvasAndContext,a=t.texture.source,n=this._style,l=this._currentX,d=this._currentY,u=this.baseRenderedFontSize/this.baseMeasurementFontSize,c=this._padding*u,p="italic"===n.fontStyle?2:1,f=0,g=!1;for(let e=0;e<r.length;e++){let t=r[e],m=_.c.measureText(t,n,i,!1);m.lineHeight=m.height;let x=p*m.width*u,b=m.height*u,y=x+2*c,w=b+2*c;if(g=!1,"\n"!==t&&"\r"!==t&&" "!==t&&" "!==t&&(g=!0,f=Math.ceil(Math.max(w,f))),l+y>512&&(l=0,(d+=f)+(f=w)>512)){a.update();let e=this._nextPage();i=e.canvasAndContext.canvas,s=e.canvasAndContext.context,a=e.texture.source,d=0}let T=x/u-(n.dropShadow?.distance??0)-(n._stroke?.width??0);if(this.chars[t]={id:t.codePointAt(0),xOffset:-this._padding,yOffset:-this._padding,xAdvance:T,kerning:{}},g){this._drawGlyph(s,m,l+c,d+c,u,n);let e=a.width*u,r=a.height*u,i=new o.A(l/e*a.width,d/r*a.height,y/e*a.width,w/r*a.height);this.chars[t].texture=new h.x({source:a,frame:i}),l+=Math.ceil(y)}}a.update(),this._currentX=l,this._currentY=d,this._skipKerning&&this._applyKerning(r,s)}get pageTextures(){return(0,u.a)(u.P,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}_applyKerning(e,t){let r=this._measureCache;for(let i=0;i<e.length;i++){let s=e[i];for(let e=0;e<this._currentChars.length;e++){let i=this._currentChars[e],a=r[s];a||(a=r[s]=t.measureText(s).width);let n=r[i];n||(n=r[i]=t.measureText(i).width);let l=t.measureText(s+i).width,o=l-(a+n);o&&(this.chars[s].kerning[i]=o),(o=(l=t.measureText(s+i).width)-(a+n))&&(this.chars[i].kerning[s]=o)}}}_nextPage(){this._currentPageIndex++;let e=this.resolution,t=m.h.getOptimalCanvasAndContext(512,512,e);this._setupContext(t.context,this._style,e);let r=e*(this.baseRenderedFontSize/this.baseMeasurementFontSize),i=new h.x({source:new x.c({resource:t.canvas,resolution:r,alphaMode:"premultiply-alpha-on-upload"})}),s={canvasAndContext:t,texture:i};return this.pages[this._currentPageIndex]=s,s}_setupContext(e,t,r){t.fontSize=this.baseRenderedFontSize,e.scale(r,r),e.font=(0,b.M)(t),t.fontSize=this.baseMeasurementFontSize,e.textBaseline=t.textBaseline;let i=t._stroke,s=i?.width??0;if(i&&(e.lineWidth=s,e.lineJoin=i.join,e.miterLimit=i.miterLimit,e.strokeStyle=(0,y.m)(i,e)),t._fill&&(e.fillStyle=(0,y.m)(t._fill,e)),t.dropShadow){let i=t.dropShadow,s=g.I.shared.setValue(i.color).toArray(),a=i.blur*r,n=i.distance*r;e.shadowColor=`rgba(${255*s[0]},${255*s[1]},${255*s[2]},${i.alpha})`,e.shadowBlur=a,e.shadowOffsetX=Math.cos(i.angle)*n,e.shadowOffsetY=Math.sin(i.angle)*n}else e.shadowColor="black",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0}_drawGlyph(e,t,r,i,s,a){let n=t.text,l=t.fontProperties,o=a._stroke,h=(o?.width??0)*s,d=r+h/2,u=i-h/2,c=l.descent*s,p=t.lineHeight*s;a.stroke&&h&&e.strokeText(n,d,u+p-c),a._fill&&e.fillText(n,d,u+p-c)}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){let{canvasAndContext:t,texture:r}=this.pages[e];m.h.returnCanvasAndContext(t),r.destroy(!0)}this.pages=null}}function v(e,t,r){let i={width:0,height:0,offsetY:0,scale:t.fontSize/r.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};i.offsetY=r.baseLineOffset;let s=i.lines[0],a=null,n=!0,l={spaceWord:!1,width:0,start:0,index:0,positions:[],chars:[]},o=e=>{let t=s.width;for(let r=0;r<l.index;r++){let i=e.positions[r];s.chars.push(e.chars[r]),s.charPositions.push(i+t)}s.width+=e.width,n=!1,l.width=0,l.index=0,l.chars.length=0},h=()=>{let e=s.chars.length-1,t=s.chars[e];for(;" "===t;)s.width-=r.chars[t].xAdvance,t=s.chars[--e];i.width=Math.max(i.width,s.width),s={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},n=!0,i.lines.push(s),i.height+=r.lineHeight},d=r.baseMeasurementFontSize/t.fontSize,u=t.letterSpacing*d,c=t.wordWrapWidth*d;for(let i=0;i<e.length+1;i++){let d,p=i===e.length;p||(d=e[i]);let f=r.chars[d]||r.chars[" "];if(/(?:\s)/.test(d)||"\r"===d||"\n"===d||p){if(!n&&t.wordWrap&&s.width+l.width-u>c?h():l.start=s.width,o(l),p||s.charPositions.push(0),"\r"===d||"\n"===d)0!==s.width&&h();else if(!p){let e=f.xAdvance+(f.kerning[a]||0)+u;s.width+=e,s.spaceWidth=e,s.spacesIndex.push(s.charPositions.length),s.chars.push(d)}}else{let e=f.kerning[a]||0,t=f.xAdvance+e+u;l.positions[l.index++]=l.width+e,l.chars.push(d),l.width+=t}a=d}return h(),"center"===t.align?function(e){for(let t=0;t<e.lines.length;t++){let r=e.lines[t],i=e.width/2-r.width/2;for(let e=0;e<r.charPositions.length;e++)r.charPositions[e]+=i}}(i):"right"===t.align?function(e){for(let t=0;t<e.lines.length;t++){let r=e.lines[t],i=e.width-r.width;for(let e=0;e<r.charPositions.length;e++)r.charPositions[e]+=i}}(i):"justify"===t.align&&function(e){let t=e.width;for(let r=0;r<e.lines.length;r++){let i=e.lines[r],s=0,a=i.spacesIndex[s++],n=0,l=i.spacesIndex.length,o=(t-i.width)/l;for(let e=0;e<i.charPositions.length;e++)e===a&&(a=i.spacesIndex[s++],n+=o),i.charPositions[e]+=n}}(i),i}let S=new class{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1}}getFont(e,t){let r=`${t.fontFamily}-bitmap`,i=!0;if(t._fill.fill&&(r+=t._fill.fill.uid,i=!1),!p.C.has(r)){let e=new T({style:t,overrideFill:i,overrideSize:!0,...this.defaultOptions});e.once("destroy",()=>p.C.remove(r)),p.C.set(r,e)}let s=p.C.get(r);return s.ensureCharacters?.(e),s}getLayout(e,t){let r=this.getFont(e,t);return v(e.split(""),t,r)}measureText(e,t){return this.getLayout(e,t)}install(...e){let t=e[0];"string"==typeof t&&(t={name:t,style:e[1],chars:e[2]?.chars,resolution:e[2]?.resolution,padding:e[2]?.padding,skipKerning:e[2]?.skipKerning},(0,u.a)(u.P,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));let r=t?.name;if(!r)throw Error("[BitmapFontManager] Property `name` is required.");let i=(t={...this.defaultOptions,...t}).style,s=i instanceof f.p?i:new f.p(i),a=null!==s._fill.fill&&void 0!==s._fill.fill,n=new T({style:s,overrideFill:a,skipKerning:t.skipKerning,padding:t.padding,resolution:t.resolution,overrideSize:!1}),l=w(t.chars);return n.ensureCharacters(l.join("")),p.C.set(`${r}-bitmap`,n),n.once("destroy",()=>p.C.remove(`${r}-bitmap`)),n}uninstall(e){let t=`${e}-bitmap`,r=p.C.get(t);r&&(p.C.remove(t),r.destroy())}};class C extends c{constructor(e,t){super();let{textures:r,data:i}=e;Object.keys(i.pages).forEach(e=>{let t=r[i.pages[parseInt(e,10)].id];this.pages.push({texture:t})}),Object.keys(i.chars).forEach(e=>{let t=i.chars[e],{frame:s,source:a}=r[t.page],n=new o.A(t.x+s.x,t.y+s.y,t.width,t.height),l=new h.x({source:a,frame:n});this.chars[e]={id:e.codePointAt(0),xOffset:t.xOffset,yOffset:t.yOffset,xAdvance:t.xAdvance,kerning:t.kerning??{},texture:l}}),this.baseRenderedFontSize=i.fontSize,this.baseMeasurementFontSize=i.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:i.fontSize},this.baseLineOffset=i.baseLineOffset,this.lineHeight=i.lineHeight,this.fontFamily=i.fontFamily,this.distanceField=i.distanceField??{type:"none",range:0},this.url=t}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){let{texture:t}=this.pages[e];t.destroy(!0)}this.pages=null}static install(e){S.install(e)}static uninstall(e){S.uninstall(e)}}let P={test:e=>"string"==typeof e&&e.startsWith("info face="),parse(e){let t=e.match(/^[a-z]+\s+.+$/gm),r={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(let e in t){let i=t[e].match(/^[a-z]+/gm)[0],s=t[e].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(let e in s){let t=s[e].split("="),r=t[0],i=t[1].replace(/"/gm,""),n=parseFloat(i),l=isNaN(n)?i:n;a[r]=l}r[i].push(a)}let i={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[s]=r.info,[a]=r.common,[n]=r.distanceField??[];n&&(i.distanceField={range:parseInt(n.distanceRange,10),type:n.fieldType}),i.fontSize=parseInt(s.size,10),i.fontFamily=s.face,i.lineHeight=parseInt(a.lineHeight,10);let l=r.page;for(let e=0;e<l.length;e++)i.pages.push({id:parseInt(l[e].id,10)||0,file:l[e].file});let o={};i.baseLineOffset=i.lineHeight-parseInt(a.base,10);let h=r.char;for(let e=0;e<h.length;e++){let t=h[e],r=parseInt(t.id,10),s=t.letter??t.char??String.fromCharCode(r);"space"===s&&(s=" "),o[r]=s,i.chars[s]={id:r,page:parseInt(t.page,10)||0,x:parseInt(t.x,10),y:parseInt(t.y,10),width:parseInt(t.width,10),height:parseInt(t.height,10),xOffset:parseInt(t.xoffset,10),yOffset:parseInt(t.yoffset,10),xAdvance:parseInt(t.xadvance,10),kerning:{}}}let d=r.kerning||[];for(let e=0;e<d.length;e++){let t=parseInt(d[e].first,10),r=parseInt(d[e].second,10),s=parseInt(d[e].amount,10);i.chars[o[r]].kerning[o[t]]=s}return i}},M={test:e=>"string"!=typeof e&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&null!==e.getElementsByTagName("info")[0].getAttribute("face"),parse(e){let t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},r=e.getElementsByTagName("info")[0],i=e.getElementsByTagName("common")[0],s=e.getElementsByTagName("distanceField")[0];s&&(t.distanceField={type:s.getAttribute("fieldType"),range:parseInt(s.getAttribute("distanceRange"),10)});let a=e.getElementsByTagName("page"),n=e.getElementsByTagName("char"),l=e.getElementsByTagName("kerning");t.fontSize=parseInt(r.getAttribute("size"),10),t.fontFamily=r.getAttribute("face"),t.lineHeight=parseInt(i.getAttribute("lineHeight"),10);for(let e=0;e<a.length;e++)t.pages.push({id:parseInt(a[e].getAttribute("id"),10)||0,file:a[e].getAttribute("file")});let o={};t.baseLineOffset=t.lineHeight-parseInt(i.getAttribute("base"),10);for(let e=0;e<n.length;e++){let r=n[e],i=parseInt(r.getAttribute("id"),10),s=r.getAttribute("letter")??r.getAttribute("char")??String.fromCharCode(i);"space"===s&&(s=" "),o[i]=s,t.chars[s]={id:i,page:parseInt(r.getAttribute("page"),10)||0,x:parseInt(r.getAttribute("x"),10),y:parseInt(r.getAttribute("y"),10),width:parseInt(r.getAttribute("width"),10),height:parseInt(r.getAttribute("height"),10),xOffset:parseInt(r.getAttribute("xoffset"),10),yOffset:parseInt(r.getAttribute("yoffset"),10),xAdvance:parseInt(r.getAttribute("xadvance"),10),kerning:{}}}for(let e=0;e<l.length;e++){let r=parseInt(l[e].getAttribute("first"),10),i=parseInt(l[e].getAttribute("second"),10),s=parseInt(l[e].getAttribute("amount"),10);t.chars[o[i]].kerning[o[r]]=s}return t}},F=e=>!!("string"==typeof e&&e.includes("<font>"))&&M.test(n.z.get().parseXML(e)),R=e=>M.parse(n.z.get().parseXML(e)),B=[".xml",".fnt"],A={extension:i.nw.CacheParser,test:e=>e instanceof C,getCacheableAssets(e,t){let r={};return e.forEach(e=>{r[e]=t}),r[`${t.fontFamily}-bitmap`]=t,r}},k={extension:{type:i.nw.LoadParser,priority:s.Q.Normal},test:e=>B.includes(l.E.extname(e).toLowerCase()),testParse:async e=>P.test(e)||F(e),async parse(e,t,r){let i=P.test(e)?P.parse(e):R(e),{src:s}=t,{pages:n}=i,o=[];for(let e=0;e<n.length;++e){let t=n[e].file,r=l.E.join(l.E.dirname(s),t);r=(0,a.u)(r,s),o.push(r)}let h=await r.load(o);return new C({data:i,textures:o.map(e=>h[e])},s)},async load(e,t){let r=await n.z.get().fetch(e);return await r.text()},async unload(e,t,r){await Promise.all(e.pages.map(e=>r.unload(e.texture.source._sourceOrigin))),e.destroy()}};var z=r(24951),U=r(40318),I=r(30044),H=r(29465),O=r(43200),G=r(23149),W=r(39193),E=r(71067),L=r(17094),D=r(8482),$=r(73109);let X={name:"local-uniform-msdf-bit",vertex:{header:`
67
- struct LocalUniforms {
68
- uColor:vec4<f32>,
69
- uTransformMatrix:mat3x3<f32>,
70
- uDistance: f32,
71
- uRound:f32,
72
- }
73
-
74
- @group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
75
- `,main:`
76
- vColor *= localUniforms.uColor;
77
- modelMatrix *= localUniforms.uTransformMatrix;
78
- `,end:`
79
- if(localUniforms.uRound == 1)
80
- {
81
- vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
82
- }
83
- `},fragment:{header:`
84
- struct LocalUniforms {
85
- uColor:vec4<f32>,
86
- uTransformMatrix:mat3x3<f32>,
87
- uDistance: f32
88
- }
89
-
90
- @group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
91
- `,main:`
92
- outColor = vColor * calculateMSDFAlpha(outColor, localUniforms.uDistance);
93
- `}},V={name:"local-uniform-msdf-bit",vertex:{header:`
94
- uniform mat3 uTransformMatrix;
95
- uniform vec4 uColor;
96
- uniform float uRound;
97
- `,main:`
98
- vColor *= uColor;
99
- modelMatrix *= uTransformMatrix;
100
- `,end:`
101
- if(uRound == 1.)
102
- {
103
- gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
104
- }
105
- `},fragment:{header:`
106
- uniform float uDistance;
107
- `,main:`
108
- outColor = vColor * calculateMSDFAlpha(outColor, uDistance);
109
- `}},Y={name:"msdf-bit",fragment:{header:`
110
- fn calculateMSDFAlpha(msdfColor:vec4<f32>, distance:f32) -> f32 {
111
-
112
- // MSDF
113
- var median = msdfColor.r + msdfColor.g + msdfColor.b -
114
- min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
115
- max(msdfColor.r, max(msdfColor.g, msdfColor.b));
116
-
117
- // SDF
118
- median = min(median, msdfColor.a);
119
-
120
- var screenPxDistance = distance * (median - 0.5);
121
- var alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
122
- if (median < 0.01) {
123
- alpha = 0.0;
124
- } else if (median > 0.99) {
125
- alpha = 1.0;
126
- }
127
-
128
- return alpha;
129
- }
130
- `}},K={name:"msdf-bit",fragment:{header:`
131
- float calculateMSDFAlpha(vec4 msdfColor, float distance) {
132
-
133
- // MSDF
134
- float median = msdfColor.r + msdfColor.g + msdfColor.b -
135
- min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
136
- max(msdfColor.r, max(msdfColor.g, msdfColor.b));
137
-
138
- // SDF
139
- median = min(median, msdfColor.a);
140
-
141
- float screenPxDistance = distance * (median - 0.5);
142
- float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
143
-
144
- if (median < 0.01) {
145
- alpha = 0.0;
146
- } else if (median > 0.99) {
147
- alpha = 1.0;
148
- }
149
-
150
- return alpha;
151
- }
152
- `}};class j extends D.e{constructor(){let e=new $.o({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new I.y,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}});super({glProgram:(0,O.o)({name:"sdf-shader",bits:[G.T,(0,W.h)(H.A),V,K,E.X]}),gpuProgram:(0,O.d)({name:"sdf-shader",bits:[G.M,(0,W.m)(H.A),X,Y,E.j]}),resources:{localUniforms:e,batchSamplers:L.y}})}}class N{constructor(e){this._gpuBitmapText={},this._renderer=e}validateRenderable(e){let t=this._getGpuBitmapText(e);return e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,t)),this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){let r=this._getGpuBitmapText(e);q(e,r),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,r)),this._renderer.renderPipes.graphics.addRenderable(r,t),r.context.customShader&&this._updateDistanceField(e)}destroyRenderable(e){this._destroyRenderableByUid(e.uid)}_destroyRenderableByUid(e){z.u.return(this._gpuBitmapText[e]),this._gpuBitmapText[e]=null}updateRenderable(e){let t=this._getGpuBitmapText(e);q(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){let{context:r}=t,i=S.getFont(e.text,e._style);r.clear(),"none"===i.distanceField.type||r.customShader||(this._sdfShader||(this._sdfShader=new j),r.customShader=this._sdfShader);let s=Array.from(e.text),a=e._style,n=(a._stroke?.width||0)/2;n+=i.baseLineOffset;let l=v(s,a,i),o=0,h=a.padding,d=l.scale;r.translate(-e._anchor._x*l.width-h,-e._anchor._y*(l.height+l.offsetY)-h).scale(d,d);let u=a._fill.color;for(let e=0;e<l.lines.length;e++){let t=l.lines[e];for(let e=0;e<t.charPositions.length;e++){let a=s[o++],l=i.chars[a];l?.texture&&r.texture(l.texture,u||"black",Math.round(t.charPositions[e]+l.xOffset),Math.round(n+l.yOffset))}n+=i.lineHeight}}_getGpuBitmapText(e){return this._gpuBitmapText[e.uid]||this.initGpuText(e)}initGpuText(e){let t=z.u.get(U.T);return this._gpuBitmapText[e.uid]=t,this._updateContext(e,t),e.on("destroyed",()=>{this.destroyRenderable(e)}),this._gpuBitmapText[e.uid]}_updateDistanceField(e){let t=this._getGpuBitmapText(e).context,r=e._style.fontFamily,i=p.C.get(`${r}-bitmap`),{a:s,b:a,c:n,d:l}=e.groupTransform,o=(Math.abs(Math.sqrt(s*s+a*a))+Math.abs(Math.sqrt(n*n+l*l)))/2,h=i.baseRenderedFontSize/e._style.fontSize,d=e.resolution??this._renderer.resolution,u=o*i.distanceField.range*(1/h)*d;t.customShader.resources.localUniforms.uniforms.uDistance=u}destroy(){for(let e in this._gpuBitmapText)this._destroyRenderableByUid(e);this._gpuBitmapText=null,this._sdfShader?.destroy(!0),this._sdfShader=null,this._renderer=null}}function q(e,t){t.groupTransform=e.groupTransform,t.groupColorAlpha=e.groupColorAlpha,t.groupColor=e.groupColor,t.groupBlendMode=e.groupBlendMode,t.globalDisplayStatus=e.globalDisplayStatus,t.groupTransform=e.groupTransform,t.localDisplayStatus=e.localDisplayStatus,t.groupAlpha=e.groupAlpha,t._roundPixels=e._roundPixels}N.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"bitmapText"},i.Rw.add(N,k,A)},19921:function(e,t,r){let i;var s=r(91957),a=r(41277),n=r(88515),l=r(24951),o=r(88556);class h{constructor(e){this._gpuText=Object.create(null),this._renderer=e}validateRenderable(e){let t=this._getGpuText(e),r=e._getKey();return t.textureNeedsUploading?(t.textureNeedsUploading=!1,!0):t.currentKey!==r}addRenderable(e){let t=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(t)}updateRenderable(e){let t=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),t.batcher.updateElement(t)}destroyRenderable(e){this._destroyRenderableById(e.uid)}_destroyRenderableById(e){let t=this._gpuText[e];this._renderer.htmlText.decreaseReferenceCount(t.currentKey),l.u.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){let t=e._getKey(),r=this._getGpuText(e),i=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e).catch(e=>{console.error(e)}),e._didTextUpdate=!1;let s=e._style.padding;(0,n.w)(i.bounds,e._anchor,i.texture,s)}async _updateGpuText(e){e._didTextUpdate=!1;let t=this._getGpuText(e);if(t.generatingTexture)return;let r=e._getKey();this._renderer.htmlText.decreaseReferenceCount(t.currentKey),t.generatingTexture=!0,t.currentKey=r;let i=e.resolution??this._renderer.resolution,s=await this._renderer.htmlText.getManagedTexture(e.text,i,e._style,e._getKey()),a=t.batchableSprite;a.texture=t.texture=s,t.generatingTexture=!1,t.textureNeedsUploading=!0,e.onViewUpdate();let l=e._style.padding;(0,n.w)(a.bounds,e._anchor,a.texture,l)}_getGpuText(e){return this._gpuText[e.uid]||this.initGpuText(e)}initGpuText(e){let t={texture:a.x.EMPTY,currentKey:"--",batchableSprite:l.u.get(o.c),textureNeedsUploading:!1,generatingTexture:!1},r=t.batchableSprite;return r.renderable=e,r.texture=a.x.EMPTY,r.bounds={minX:0,maxX:1,minY:0,maxY:0},r.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuText[e.uid]=t,e.on("destroyed",()=>{this.destroyRenderable(e)}),t}destroy(){for(let e in this._gpuText)this._destroyRenderableById(e);this._gpuText=null,this._renderer=null}}h.extension={type:[s.nw.WebGLPipes,s.nw.WebGPUPipes,s.nw.CanvasPipes],name:"htmlText"};var d=r(50900),u=r(71423),c=r(767),p=r(92245),f=r(13263);let g="http://www.w3.org/2000/svg",m="http://www.w3.org/1999/xhtml";class x{constructor(){this.svgRoot=document.createElementNS(g,"svg"),this.foreignObject=document.createElementNS(g,"foreignObject"),this.domElement=document.createElementNS(m,"div"),this.styleElement=document.createElementNS(m,"style"),this.image=new Image;let{foreignObject:e,svgRoot:t,styleElement:r,domElement:i}=this;e.setAttribute("width","10000"),e.setAttribute("height","10000"),e.style.overflow="hidden",t.appendChild(e),e.appendChild(r),e.appendChild(i)}}var _=r(82175),b=r(71722),y=r(32036);function w(e){let t=y.I.shared.setValue(e.color).setAlpha(e.alpha).toHexa(),r=Math.round(Math.cos(e.angle)*e.distance),i=Math.round(Math.sin(e.angle)*e.distance),s=`${r}px ${i}px`;return e.blur>0?`text-shadow: ${s} ${e.blur}px ${t}`:`text-shadow: ${s} ${t}`}function T(e){return`-webkit-text-stroke-width: ${e.width}px;-webkit-text-stroke-color: ${y.I.shared.setValue(e.color).toHex()};text-stroke-width: ${e.width}px;text-stroke-color: ${y.I.shared.setValue(e.color).toHex()};paint-order: stroke`}let v={fontSize:"font-size: {{VALUE}}px",fontFamily:"font-family: {{VALUE}}",fontWeight:"font-weight: {{VALUE}}",fontStyle:"font-style: {{VALUE}}",fontVariant:"font-variant: {{VALUE}}",letterSpacing:"letter-spacing: {{VALUE}}px",align:"text-align: {{VALUE}}",padding:"padding: {{VALUE}}px",whiteSpace:"white-space: {{VALUE}}",lineHeight:"line-height: {{VALUE}}px",wordWrapWidth:"max-width: {{VALUE}}px"},S={fill:e=>`color: ${y.I.shared.setValue(e).toHex()}`,breakWords:e=>`word-wrap: ${e?"break-all":"break-word"}`,stroke:T,dropShadow:w};class C extends _.p{constructor(e={}){super(e),this._cssOverrides=[],this.cssOverrides??(this.cssOverrides=e.cssOverrides),this.tagStyles=e.tagStyles??{}}set cssOverrides(e){this._cssOverrides=e instanceof Array?e:[e],this.update()}get cssOverrides(){return this._cssOverrides}_generateKey(){return this._styleKey=(0,b.L)(this)+this._cssOverrides.join("-"),this._styleKey}update(){this._cssStyle=null,super.update()}clone(){return new C({align:this.align,breakWords:this.breakWords,dropShadow:this.dropShadow,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,cssOverrides:this.cssOverrides})}get cssStyle(){return this._cssStyle||(this._cssStyle=function(e){let t=e._stroke,r=e._fill,i=[`color: ${y.I.shared.setValue(r.color).toHex()}`,`font-size: ${e.fontSize}px`,`font-family: ${e.fontFamily}`,`font-weight: ${e.fontWeight}`,`font-style: ${e.fontStyle}`,`font-variant: ${e.fontVariant}`,`letter-spacing: ${e.letterSpacing}px`,`text-align: ${e.align}`,`padding: ${e.padding}px`,`white-space: ${"pre"===e.whiteSpace&&e.wordWrap?"pre-wrap":e.whiteSpace}`,...e.lineHeight?[`line-height: ${e.lineHeight}px`]:[],...e.wordWrap?[`word-wrap: ${e.breakWords?"break-all":"break-word"}`,`max-width: ${e.wordWrapWidth}px`]:[],...t?[T(t)]:[],...e.dropShadow?[w(e.dropShadow)]:[],...e.cssOverrides].join(";"),s=[`div { ${i} }`];return function(e,t){for(let r in e){let i=e[r],s=[];for(let e in i)S[e]?s.push(S[e](i[e])):v[e]&&s.push(v[e].replace("{{VALUE}}",i[e]));t.push(`${r} { ${s.join(";")} }`)}}(e.tagStyles,s),s.join(" ")}(this)),this._cssStyle}addOverride(...e){let t=e.filter(e=>!this.cssOverrides.includes(e));t.length>0&&(this.cssOverrides.push(...t),this.update())}removeOverride(...e){let t=e.filter(e=>this.cssOverrides.includes(e));t.length>0&&(this.cssOverrides=this.cssOverrides.filter(e=>!t.includes(e)),this.update())}set fill(e){"string"!=typeof e&&"number"!=typeof e&&(0,p.Z)("[HTMLTextStyle] only color fill is not supported by HTMLText"),super.fill=e}set stroke(e){e&&"string"!=typeof e&&"number"!=typeof e&&(0,p.Z)("[HTMLTextStyle] only color stroke is not supported by HTMLText"),super.stroke=e}}var P=r(45158);async function M(e){let t=await c.z.get().fetch(e),r=await t.blob(),i=new FileReader;return await new Promise((e,t)=>{i.onloadend=()=>e(i.result),i.onerror=t,i.readAsDataURL(r)})}async function F(e,t){let r=await M(t);return`@font-face {
153
- font-family: "${e.fontFamily}";
154
- src: url('${r}');
155
- font-weight: ${e.fontWeight};
156
- font-style: ${e.fontStyle};
157
- }`}let R=new Map;async function B(e,t,r){let i=e.filter(e=>P.C.has(`${e}-and-url`)).map((e,i)=>{if(!R.has(e)){let{url:s}=P.C.get(`${e}-and-url`);0===i?R.set(e,F(t,s)):R.set(e,F({fontWeight:r.fontWeight,fontStyle:r.fontStyle,fontFamily:e},s))}return R.get(e)});return(await Promise.all(i)).join("\n")}var A=r(51982),k=r(24332);class z{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===u.g.WEBGPU}getTexture(e){return this._buildTexturePromise(e.text,e.resolution,e.style)}getManagedTexture(e,t,r,i){if(this._activeTextures[i])return this._increaseReferenceCount(i),this._activeTextures[i].promise;let s=this._buildTexturePromise(e,t,r).then(e=>(this._activeTextures[i].texture=e,e));return this._activeTextures[i]={texture:null,promise:s,usageCount:1},s}async _buildTexturePromise(e,t,r){var s;let a=l.u.get(x),n=function(e,t){let r=t.fontFamily,i=[],s={},a=e.match(/font-family:([^;"\s]+)/g);function n(e){s[e]||(i.push(e),s[e]=!0)}if(Array.isArray(r))for(let e=0;e<r.length;e++)n(r[e]);else n(r);for(let e in a&&a.forEach(e=>{n(e.split(":")[1].trim())}),t.tagStyles)n(t.tagStyles[e].fontFamily);return i}(e,r),o=await B(n,r,C.defaultTextStyle),h=function(e,t,r,s){let{domElement:a,styleElement:n,svgRoot:l}=s=s||i||(i=new x);a.innerHTML=`<style>${t.cssStyle}</style><div>${e}</div>`,a.setAttribute("style","transform-origin: top left; display: inline-block"),r&&(n.textContent=r),document.body.appendChild(l);let o=a.getBoundingClientRect();l.remove();let h=k.c.measureFont(t.fontStyle).descent;return{width:o.width,height:o.height+h}}(e,r,o,a),d=Math.ceil(Math.ceil(Math.max(1,h.width)+2*r.padding)*t),u=Math.ceil(Math.ceil(Math.max(1,h.height)+2*r.padding)*t),p=a.image;p.width=0|d,p.height=0|u;let g=function(e,t,r,i,s){let{domElement:a,styleElement:n,svgRoot:l}=s;a.innerHTML=`<style>${t.cssStyle}</style><div>${e}</div>`,a.setAttribute("style",`transform: scale(${r});transform-origin: top left; display: inline-block`),n.textContent=i;let{width:o,height:h}=s.image;return l.setAttribute("width",o.toString()),l.setAttribute("height",h.toString()),new XMLSerializer().serializeToString(l)}(e,r,t,o,a);await (s=function(){let{userAgent:e}=c.z.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(e)}()&&n.length>0,new Promise(async e=>{s&&await new Promise(e=>setTimeout(e,100)),p.onload=()=>{e()},p.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(g)}`,p.crossOrigin="anonymous"}));let m=p;this._createCanvas&&(m=function(e,t){let r=A.h.getOptimalCanvasAndContext(e.width,e.height,t),{context:i}=r;return i.clearRect(0,0,e.width,e.height),i.drawImage(e,0,0),A.h.returnCanvasAndContext(r),r.canvas}(p,t));let _=(0,f.H)(m,p.width,p.height,t);return this._createCanvas&&this._renderer.texture.initSource(_.source),l.u.return(a),_}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,0===t.usageCount&&(t.texture?this._cleanUp(t):t.promise.then(e=>{t.texture=e,this._cleanUp(t)}).catch(()=>{(0,p.Z)("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}_cleanUp(e){d.z.returnTexture(e.texture),e.texture.source.resource=null,e.texture.source.uploadMethodId="unknown"}getReferenceCount(e){return this._activeTextures[e].usageCount}destroy(){this._activeTextures=null}}z.extension={type:[s.nw.WebGLSystem,s.nw.WebGPUSystem,s.nw.CanvasSystem],name:"htmlText"},z.defaultFontOptions={fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal"},s.Rw.add(z),s.Rw.add(h)},29331:function(e,t,r){r.d(t,{m:()=>h});var i=r(32036),s=r(30044),a=r(41277),n=r(92245),l=r(46456),o=r(23901);function h(e,t){if(e.texture===a.x.WHITE&&!e.fill)return i.I.shared.setValue(e.color).toHex();if(e.fill){if(e.fill instanceof o.h){let r=e.fill,i=t.createPattern(r.texture.source.resource,"repeat"),a=r.transform.copyTo(s.y.shared);return a.scale(r.texture.frame.width,r.texture.frame.height),i.setTransform(a),i}else if(e.fill instanceof l.f){let r=e.fill;if("linear"===r.type){let e=t.createLinearGradient(r.x0,r.y0,r.x1,r.y1);return r.gradientStops.forEach(t=>{e.addColorStop(t.offset,i.I.shared.setValue(t.color).toHex())}),e}}}else{let r=t.createPattern(e.texture.source.resource,"repeat"),i=e.matrix.copyTo(s.y.shared);return i.scale(e.texture.frame.width,e.texture.frame.height),r.setTransform(i),r}return(0,n.Z)("FillStyle not recognised",e),"red"}},66241:function(e,t,r){var i=r(91957),s=r(88515),a=r(24951),n=r(88556);class l{constructor(e){this._gpuText=Object.create(null),this._renderer=e}validateRenderable(e){let t=this._getGpuText(e),r=e._getKey();if(t.currentKey!==r){let r=e.resolution??this._renderer.resolution,{width:i,height:s}=this._renderer.canvasText.getTextureSize(e.text,r,e._style);return 1!==this._renderer.canvasText.getReferenceCount(t.currentKey)||i!==t.texture._source.width||s!==t.texture._source.height}return!1}addRenderable(e,t){let r=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(r)}updateRenderable(e){let t=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),t.batcher.updateElement(t)}destroyRenderable(e){this._destroyRenderableById(e.uid)}_destroyRenderableById(e){let t=this._gpuText[e];this._renderer.canvasText.decreaseReferenceCount(t.currentKey),a.u.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){let t=e._getKey(),r=this._getGpuText(e),i=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e),e._didTextUpdate=!1;let a=e._style.padding;(0,s.w)(i.bounds,e._anchor,i.texture,a)}_updateGpuText(e){let t=this._getGpuText(e),r=t.batchableSprite;t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),t.texture=r.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e._getKey(),r.texture=t.texture}_getGpuText(e){return this._gpuText[e.uid]||this.initGpuText(e)}initGpuText(e){let t={texture:null,currentKey:"--",batchableSprite:a.u.get(n.c)};return t.batchableSprite.renderable=e,t.batchableSprite.bounds={minX:0,maxX:1,minY:0,maxY:0},t.batchableSprite.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuText[e.uid]=t,this._updateText(e),e.on("destroyed",()=>{this.destroyRenderable(e)}),t}destroy(){for(let e in this._gpuText)this._destroyRenderableById(e);this._gpuText=null,this._renderer=null}}l.extension={type:[i.nw.WebGLPipes,i.nw.WebGPUPipes,i.nw.CanvasPipes],name:"text"};var o=r(32036),h=r(45854),d=r(51982),u=r(50900),c=r(45266);function p(e,t,r){for(let i=0,s=4*r*t;i<t;++i,s+=4)if(0!==e[s+3])return!1;return!0}function f(e,t,r,i,s){let a=4*t;for(let t=i,n=i*a+4*r;t<=s;++t,n+=a)if(0!==e[n+3])return!1;return!0}var g=r(24584),m=r(82175),x=r(13263),_=r(24332),b=r(92007),y=r(29331);class w{constructor(e){this._activeTextures={},this._renderer=e}getTextureSize(e,t,r){let i=_.c.measureText(e||" ",r),s=Math.ceil(Math.ceil(Math.max(1,i.width)+2*r.padding)*t),a=Math.ceil(Math.ceil(Math.max(1,i.height)+2*r.padding)*t);return s=Math.ceil(s-1e-6),a=Math.ceil(a-1e-6),{width:s=(0,h.a9)(s),height:a=(0,h.a9)(a)}}getTexture(e,t,r,i){"string"==typeof e&&((0,g.a)("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:r,resolution:t}),e.style instanceof m.p||(e.style=new m.p(e.style));let{texture:s,canvasAndContext:a}=this.createTextureAndCanvas(e);return this._renderer.texture.initSource(s._source),d.h.returnCanvasAndContext(a),s}createTextureAndCanvas(e){let{text:t,style:r}=e,i=e.resolution??this._renderer.resolution,s=_.c.measureText(t||" ",r),a=Math.ceil(Math.ceil(Math.max(1,s.width)+2*r.padding)*i),n=Math.ceil(Math.ceil(Math.max(1,s.height)+2*r.padding)*i),l=d.h.getOptimalCanvasAndContext(a,n),{canvas:o}=l;this.renderTextToCanvas(t,r,i,l);let h=(0,x.H)(o,a,n,i);if(r.trim){let e=function(e,t=1){let{width:r,height:i}=e,s=e.getContext("2d",{willReadFrequently:!0});if(null===s)throw TypeError("Failed to get canvas 2D context");let a=s.getImageData(0,0,r,i).data,n=0,l=0,o=r-1,h=i-1;for(;l<i&&p(a,r,l);)++l;if(l===i)return c.A.EMPTY;for(;p(a,r,h);)--h;for(;f(a,r,n,l,h);)++n;for(;f(a,r,o,l,h);)--o;return++o,++h,new c.A(n/t,l/t,(o-n)/t,(h-l)/t)}(o,i);h.frame.copyFrom(e),h.updateUvs()}return{texture:h,canvasAndContext:l}}getManagedTexture(e){let t=e._getKey();if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;let{texture:r,canvasAndContext:i}=this.createTextureAndCanvas(e);return this._activeTextures[t]={canvasAndContext:i,texture:r,usageCount:1},r}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){let t=this._activeTextures[e];if(t.usageCount--,0===t.usageCount){d.h.returnCanvasAndContext(t.canvasAndContext),u.z.returnTexture(t.texture);let r=t.texture.source;r.resource=null,r.uploadMethodId="unknown",r.alphaMode="no-premultiply-alpha",this._activeTextures[e]=null}}getReferenceCount(e){return this._activeTextures[e].usageCount}renderTextToCanvas(e,t,r,i){let s,a,{canvas:n,context:l}=i,h=(0,b.M)(t),d=_.c.measureText(e||" ",t),u=d.lines,c=d.lineHeight,p=d.lineWidths,f=d.maxLineWidth,g=d.fontProperties,m=n.height;l.resetTransform(),l.scale(r,r);let x=2*t.padding;if(l.clearRect(0,0,d.width+4+x,d.height+4+x),t._stroke?.width){let e=t._stroke;l.lineWidth=e.width,l.miterLimit=e.miterLimit,l.lineJoin=e.join,l.lineCap=e.cap}l.font=h;let w=t.dropShadow?2:1;for(let e=0;e<w;++e){let n=t.dropShadow&&0===e,h=n?Math.ceil(Math.max(1,m)+2*t.padding):0,d=h*r;if(n){l.fillStyle="black",l.strokeStyle="black";let e=t.dropShadow,i=e.color,s=e.alpha;l.shadowColor=o.I.shared.setValue(i).setAlpha(s).toRgbaString();let a=e.blur*r,n=e.distance*r;l.shadowBlur=a,l.shadowOffsetX=Math.cos(e.angle)*n,l.shadowOffsetY=Math.sin(e.angle)*n+d}else l.globalAlpha=t._fill?.alpha??1,l.fillStyle=t._fill?(0,y.m)(t._fill,l):null,t._stroke?.width&&(l.strokeStyle=(0,y.m)(t._stroke,l)),l.shadowColor="black";let x=(c-g.fontSize)/2;c-g.fontSize<0&&(x=0);let _=t._stroke?.width??0;for(let e=0;e<u.length;e++)s=_/2,a=_/2+e*c+g.ascent+x,"right"===t.align?s+=f-p[e]:"center"===t.align&&(s+=(f-p[e])/2),t._stroke?.width&&this._drawLetterSpacing(u[e],t,i,s+t.padding,a+t.padding-h,!0),void 0!==t._fill&&this._drawLetterSpacing(u[e],t,i,s+t.padding,a+t.padding-h)}}_drawLetterSpacing(e,t,r,i,s,a=!1){let{context:n}=r,l=t.letterSpacing,o=!1;if(_.c.experimentalLetterSpacingSupported&&(_.c.experimentalLetterSpacing?(n.letterSpacing=`${l}px`,n.textLetterSpacing=`${l}px`,o=!0):(n.letterSpacing="0px",n.textLetterSpacing="0px")),0===l||o)return void(a?n.strokeText(e,i,s):n.fillText(e,i,s));let h=i,d=_.c.graphemeSegmenter(e),u=n.measureText(e).width,c=0;for(let e=0;e<d.length;++e){let t=d[e];a?n.strokeText(t,h,s):n.fillText(t,h,s);let r="";for(let t=e+1;t<d.length;++t)r+=d[t];h+=u-(c=n.measureText(r).width)+l,u=c}}destroy(){this._activeTextures=null}}w.extension={type:[i.nw.WebGLSystem,i.nw.WebGPUSystem,i.nw.CanvasSystem],name:"canvasText"},i.Rw.add(w),i.Rw.add(l)},13263:function(e,t,r){r.d(t,{H:()=>a});var i=r(50900);let s=new(r(39622)).Y;function a(e,t,r,a){s.minX=0,s.minY=0,s.maxX=e.width/a|0,s.maxY=e.height/a|0;let n=i.z.getOptimalTexture(s.width,s.height,a,!1);return n.source.uploadMethodId="image",n.source.resource=e,n.source.alphaMode="premultiply-alpha-on-upload",n.frame.width=t/a,n.frame.height=r/a,n.source.emit("update",n.source),n.updateUvs(),n}}}]);
158
- //# sourceMappingURL=212.e243c338.js.map
@@ -1,21 +0,0 @@
1
- "use strict";(self.webpackChunkplayground=self.webpackChunkplayground||[]).push([["290"],{19042:function(t,e,a){let i,r,n;a.d(e,{wrapOpenAI:()=>tf});var s=a(96945),o=a(67774),l=a(32656),d=a(88464);let u=(...t)=>fetch(...t),h=Symbol.for("ls:fetch_implementation"),c=()=>globalThis[h]??u,p=[400,401,403,404,405,406,407,408],m=[409];class f{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in d?this.queue=new d.default({concurrency:this.maxConcurrency}):this.queue=new d({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...e){let a=this.onFailedResponseHook;return this.queue.add(()=>l(()=>t(...e).catch(t=>{if(t instanceof Error)throw t;throw Error(t)}),{async onFailedAttempt(t){if(t.message.startsWith("Cancel")||t.message.startsWith("TimeoutError")||t.message.startsWith("AbortError")||t?.code==="ECONNABORTED")throw t;let e=t?.response,i=e?.status;if(i){if(p.includes(+i))throw t;if(m.includes(+i))return;a&&await a(e)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...a){return t.signal?Promise.race([this.call(e,...a),new Promise((e,a)=>{t.signal?.addEventListener("abort",()=>{a(Error("AbortError"))})})]):this.call(e,...a)}fetch(...t){return this.call(()=>c()(...t).then(t=>t.ok?t:Promise.reject(t)))}}function g(t){return"function"==typeof t?._getType}function _(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var b=a(46633);function y(t,e){if(!b.Z(t))throw Error(void 0!==e?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`);return t}let w={};function v(t){w[t]||(console.warn(t),w[t]=!0)}function O(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw Error(`Invalid identifier format: ${t}`);let[e,a]=t.split(":"),i=a||"latest";if(e.includes("/")){let[a,r]=e.split("/",2);if(!a||!r)throw Error(`Invalid identifier format: ${t}`);return[a,r,i]}if(!e)throw Error(`Invalid identifier format: ${t}`);return["-",e,i]}a(78970);class S extends Error{constructor(t){super(t),this.name="LangSmithConflictError"}}async function j(t,e,a){let i;if(t.ok){a&&(i=await t.text());return}i=await t.text();let r=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Server response: ${i}`;if(409===t.status)throw new S(r);throw Error(r)}var $={result:"[Circular]"},I=[],P=[];let E=new TextEncoder;function A(t){return E.encode(t)}function T(t,e,a,i){try{let i=JSON.stringify(t,e,a);return A(i)}catch(s){let n;if(!s.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),A("[Unserializable]");console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),void 0===i&&(i={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),function t(e,a,i,r,n,s,o){if(s+=1,"object"==typeof e&&null!==e){for(l=0;l<r.length;l++)if(r[l]===e)return void C($,e,a,n);if(void 0!==o.depthLimit&&s>o.depthLimit||void 0!==o.edgesLimit&&i+1>o.edgesLimit)return void C("[...]",e,a,n);if(r.push(e),Array.isArray(e))for(l=0;l<e.length;l++)t(e[l],l,l,r,e,s,o);else{var l,d=Object.keys(e);for(l=0;l<d.length;l++){var u=d[l];t(e[u],u,l,r,e,s,o)}}r.pop()}}(t,"",0,[],void 0,0,i);try{var r;n=0===P.length?JSON.stringify(t,e,a):JSON.stringify(t,(r=e,r=void 0!==r?r:function(t,e){return e},function(t,e){if(P.length>0)for(var a=0;a<P.length;a++){var i=P[a];if(i[1]===t&&i[0]===e){e=i[2],P.splice(a,1);break}}return r.call(this,t,e)}),a)}catch(t){return A("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==I.length;){let t=I.pop();4===t.length?Object.defineProperty(t[0],t[1],t[3]):t[0][t[1]]=t[2]}}return A(n)}}function C(t,e,a,i){var r=Object.getOwnPropertyDescriptor(i,a);void 0!==r.get?r.configurable?(Object.defineProperty(i,a,{value:t}),I.push([i,a,e,r])):P.push([e,a,t]):(i[a]=t,I.push([i,a,e]))}function U(t){let e=B(),a=function(){let t=function(){try{if(void 0!==D&&D.env)return Object.entries(D.env).reduce((t,[e,a])=>(t[e]=String(a),t),{});return}catch(t){return}}()||{},e={},a=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[i,r]of Object.entries(t))(i.startsWith("LANGCHAIN_")||i.startsWith("LANGSMITH_"))&&"string"==typeof r&&!a.includes(i)&&!i.toLowerCase().includes("key")&&!i.toLowerCase().includes("secret")&&!i.toLowerCase().includes("token")&&("LANGCHAIN_REVISION_ID"===i?e.revision_id=r:e[i]=r);return e}(),i=t.extra??{},r=i.metadata;return t.extra={...i,runtime:{...e,...i?.runtime},metadata:{...a,...a.revision_id||t.revision_id?{revision_id:t.revision_id??a.revision_id}:{},...r}},t}async function x(t){let e=[];for await(let a of t)e.push(a);return e}function R(t){if(void 0!==t)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let k=async t=>{if(t?.status===429){let e=1e3*parseInt(t.headers.get("retry-after")??"30",10);if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};class N{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let e,a=new Promise(t=>{e=t}),i=T(t.item).length;return this.items.push({action:t.action,payload:t.item,itemPromiseResolve:e,itemPromise:a,size:i}),this.sizeBytes+=i,a}pop(t){if(t<1)throw Error("Number of bytes to pop off may not be less than 1.");let e=[],a=0;for(;a+(this.peek()?.size??0)<t&&this.items.length>0;){let t=this.items.shift();t&&(e.push(t),a+=t.size,this.sizeBytes-=t.size)}if(0===e.length&&this.items.length>0){let t=this.items.shift();e.push(t),a+=t.size,this.sizeBytes-=t.size}return[e.map(t=>({action:t.action,item:t.payload})),()=>e.forEach(t=>t.itemPromiseResolve())]}}class L{constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new N}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===H("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});let e=L.getDefaultClientConfig();if(this.tracingSampleRate=(()=>{let t=G("TRACING_SAMPLING_RATE");if(void 0===t)return;let e=parseFloat(t);if(e<0||e>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${e}`);return e})(),this.apiUrl=R(t.apiUrl??e.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=R(t.apiKey??e.apiKey),this.webUrl=R(t.webUrl??e.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=t.timeout_ms??9e4,this.caller=new f(t.callerOptions??{}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new f({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:k}),this.hideInputs=t.hideInputs??t.anonymizer??e.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??e.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let t=G("API_KEY"),e=G("ENDPOINT")??"https://api.smith.langchain.com";return{apiUrl:e,apiKey:t,webUrl:void 0,hideInputs:"true"===G("HIDE_INPUTS"),hideOutputs:"true"===G("HIDE_OUTPUTS")}}getHostUrl(){if(this.webUrl)return this.webUrl;if((t=>{let e=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e})(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get headers(){let t={"User-Agent":`langsmith-js/${M}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),t}processInputs(t){return!1===this.hideInputs?t:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(t):t}processOutputs(t){return!1===this.hideOutputs?t:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(t):t}prepareRunCreateOrUpdateInputs(t){let e={...t};return void 0!==e.inputs&&(e.inputs=this.processInputs(e.inputs)),void 0!==e.outputs&&(e.outputs=this.processOutputs(e.outputs)),e}async _getResponse(t,e){let a=e?.toString()??"",i=`${this.apiUrl}${t}?${a}`,r=await this.caller.call(c(),i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(r,`Failed to fetch ${t}`),r}async _get(t,e){return(await this._getResponse(t,e)).json()}async *_getPaginated(t,e=new URLSearchParams,a){let i=Number(e.get("offset"))||0,r=Number(e.get("limit"))||100;for(;;){e.set("offset",String(i)),e.set("limit",String(r));let n=`${this.apiUrl}${t}?${e}`,s=await this.caller.call(c(),n,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,`Failed to fetch ${t}`);let o=a?a(await s.json()):await s.json();if(0===o.length||(yield o,o.length<r))break;i+=o.length}}async *_getCursorPaginatedList(t,e=null,a="POST",i="runs"){let r=e?{...e}:{};for(;;){let e=await this.caller.call(c(),`${this.apiUrl}${t}`,{method:a,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)}),n=await e.json();if(!n||!n[i])break;yield n[i];let s=n.cursors;if(!s||!s.next)break;r.cursor=s.next}}_filterForSampling(t,e=!1){if(void 0===this.tracingSampleRate)return t;if(e){let e=[];for(let a of t)this.filteredPostUuids.has(a.id)?this.filteredPostUuids.delete(a.id):e.push(a);return e}{let e=[];for(let a of t)a.id!==a.trace_id&&!this.filteredPostUuids.has(a.trace_id)||Math.random()<this.tracingSampleRate?e.push(a):this.filteredPostUuids.add(a.id);return e}}async _getBatchSizeLimitBytes(){let t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??0x1400000}async _getMultiPartSupport(){let t=await this._ensureServerInfo();return t.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue(t){let e=[];for(;this.autoBatchQueue.items.length>0;){let[a,i]=this.autoBatchQueue.pop(t);if(!a.length){i();break}let r=this._processBatch(a,i).catch(console.error);e.push(r)}return Promise.all(e)}async _processBatch(t,e){if(!t.length)return void e();try{let e={runCreates:t.filter(t=>"create"===t.action).map(t=>t.item),runUpdates:t.filter(t=>"update"===t.action).map(t=>t.item)},a=await this._ensureServerInfo();a?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(e):await this.batchIngestRuns(e)}finally{e()}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,"create"===t.action&&(t.item=U(t.item));let e=this.autoBatchQueue.push(t);if(this.manualFlushMode)return e;let a=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>a&&this.drainAutoBatchQueue(a),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(a)},this.autoBatchAggregationDelayMs)),e}async _getServerInfo(){let t=await c()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(2500),...this.fetchOptions});return await j(t,"get server info"),t.json()}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(t)}async createRun(t){if(!this._filterForSampling([t]).length)return;let e={...this.headers,"Content-Type":"application/json"},a=t.project_name;delete t.project_name;let i=this.prepareRunCreateOrUpdateInputs({session_name:a,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==i.trace_id&&void 0!==i.dotted_order)return void this.processRunOperation({action:"create",item:i}).catch(console.error);let r=U(i),n=await this.caller.call(c(),`${this.apiUrl}/runs`,{method:"POST",headers:e,body:T(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"create run",!0)}async batchIngestRuns({runCreates:t,runUpdates:e}){if(void 0===t&&void 0===e)return;let a=t?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[],i=e?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[];if(a.length>0&&i.length>0){let t=a.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let a of i)void 0!==a.id&&t[a.id]?t[a.id]={...t[a.id],...a}:e.push(a);a=Object.values(t),i=e}let r={post:this._filterForSampling(a),patch:this._filterForSampling(i,!0)};if(!r.post.length&&!r.patch.length)return;let n={post:[],patch:[]};for(let t of["post","patch"]){let e=r[t].reverse(),a=e.pop();for(;void 0!==a;)n[t].push(a),a=e.pop()}(n.post.length>0||n.patch.length>0)&&await this._postBatchIngestRuns(T(n))}async _postBatchIngestRuns(t){let e={...this.headers,"Content-Type":"application/json",Accept:"application/json"},a=await this.batchIngestCaller.call(c(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:e,body:t,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"batch create run",!0)}async multipartIngestRuns({runCreates:t,runUpdates:e}){if(void 0===t&&void 0===e)return;let a={},i=[];for(let e of t??[]){let t=this.prepareRunCreateOrUpdateInputs(e);void 0!==t.id&&void 0!==t.attachments&&(a[t.id]=t.attachments),delete t.attachments,i.push(t)}let r=[];for(let t of e??[])r.push(this.prepareRunCreateOrUpdateInputs(t));if(void 0!==i.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==r.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&r.length>0){let t=i.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let a of r)void 0!==a.id&&t[a.id]?t[a.id]={...t[a.id],...a}:e.push(a);i=Object.values(t),r=e}if(0===i.length&&0===r.length)return;let n=[],s=[];for(let[t,e]of[["post",i],["patch",r]])for(let i of e){let{inputs:e,outputs:r,events:o,attachments:l,...d}=i,u={inputs:e,outputs:r,events:o},h=T(d);for(let[e,a]of(s.push({name:`${t}.${d.id}`,payload:new Blob([h],{type:`application/json; length=${h.length}`})}),Object.entries(u))){if(void 0===a)continue;let i=T(a);s.push({name:`${t}.${d.id}.${e}`,payload:new Blob([i],{type:`application/json; length=${i.length}`})})}if(void 0!==d.id){let t=a[d.id];if(t)for(let[e,i]of(delete a[d.id],Object.entries(t))){let t,a;if(Array.isArray(i)?[t,a]=i:(t=i.mimeType,a=i.data),e.includes(".")){console.warn(`Skipping attachment '${e}' for run ${d.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${d.id}.${e}`,payload:new Blob([a],{type:`${t}; length=${a.byteLength}`})})}}n.push(`trace=${d.trace_id},id=${d.id}`)}await this._sendMultipartRequest(s,n.join("; "))}async _sendMultipartRequest(t,e){try{let e="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=[];for(let i of t)a.push(new Blob([`--${e}\r
2
- `])),a.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
3
- `,`Content-Type: ${i.payload.type}\r
4
- \r
5
- `])),a.push(i.payload),a.push(new Blob(["\r\n"]));a.push(new Blob([`--${e}--\r
6
- `]));let i=new Blob(a),r=await i.arrayBuffer(),n=await this.batchIngestCaller.call(c(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${e}`},body:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"ingest multipart runs",!0)}catch(t){console.warn(`${t.message.trim()}
7
-
8
- Context: ${e}`)}}async updateRun(t,e){y(t),e.inputs&&(e.inputs=this.processInputs(e.inputs)),e.outputs&&(e.outputs=this.processOutputs(e.outputs));let a={...e,id:t};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order)return void 0!==e.end_time&&void 0===a.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:a}).catch(console.error):void this.processRunOperation({action:"update",item:a}).catch(console.error);let i={...this.headers,"Content-Type":"application/json"},r=await this.caller.call(c(),`${this.apiUrl}/runs/${t}`,{method:"PATCH",headers:i,body:T(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"update run",!0)}async readRun(t,{loadChildRuns:e}={loadChildRuns:!1}){y(t);let a=await this._get(`/runs/${t}`);return e&&a.child_run_ids&&(a=await this._loadChildRuns(a)),a}async getRunUrl({runId:t,run:e,projectOpts:a}){if(void 0!==e){let t;t=e.session_id?e.session_id:a?.projectName?(await this.readProject({projectName:a?.projectName})).id:a?.projectId?a?.projectId:(await this.readProject({projectName:G("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${t}/r/${e.id}?poll=true`}if(void 0!==t){let e=await this.readRun(t);if(!e.app_path)throw Error(`Run ${t} has no app_path`);let a=this.getHostUrl();return`${a}${e.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(t){let e=await x(this.listRuns({id:t.child_run_ids})),a={},i={};for(let t of(e.sort((t,e)=>(t?.dotted_order??"").localeCompare(e?.dotted_order??"")),e)){if(null===t.parent_run_id||void 0===t.parent_run_id)throw Error(`Child run ${t.id} has no parent`);t.parent_run_id in a||(a[t.parent_run_id]=[]),a[t.parent_run_id].push(t),i[t.id]=t}for(let e in t.child_runs=a[t.id]||[],a)e!==t.id&&(i[e].child_runs=a[e]);return t}async *listRuns(t){let{projectId:e,projectName:a,parentRunId:i,traceId:r,referenceExampleId:n,startTime:s,executionOrder:o,isRoot:l,runType:d,error:u,id:h,query:c,filter:p,traceFilter:m,treeFilter:f,limit:g,select:_}=t,b=[];if(e&&(b=Array.isArray(e)?e:[e]),a){let t=Array.isArray(a)?a:[a],e=await Promise.all(t.map(t=>this.readProject({projectName:t}).then(t=>t.id)));b.push(...e)}let y={session:b.length?b:null,run_type:d,reference_example:n,query:c,filter:p,trace_filter:m,tree_filter:f,execution_order:o,parent_run:i,start_time:s?s.toISOString():null,error:u,id:h,limit:g,trace:r,select:_||["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],is_root:l},w=0;for await(let t of this._getCursorPaginatedList("/runs/query",y))if(g){if(w>=g)break;if(t.length+w>g){let e=t.slice(0,g-w);yield*e;break}w+=t.length,yield*t}else yield*t}async getRunStats({id:t,trace:e,parentRun:a,runType:i,projectNames:r,projectIds:n,referenceExampleIds:s,startTime:o,endTime:l,error:d,query:u,filter:h,traceFilter:p,treeFilter:m,isRoot:f,dataSourceType:g}){let _=n||[];r&&(_=[...n||[],...await Promise.all(r.map(t=>this.readProject({projectName:t}).then(t=>t.id)))]);let b=Object.fromEntries(Object.entries({id:t,trace:e,parent_run:a,run_type:i,session:_,reference_example:s,start_time:o,end_time:l,error:d,query:u,filter:h,trace_filter:p,tree_filter:m,is_root:f,data_source_type:g}).filter(([t,e])=>void 0!==e)),y=await this.caller.call(c(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await y.json()}async shareRun(t,{shareId:e}={}){let a={run_id:t,share_token:e||o.Z()};y(t);let i=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await i.json();if(null===r||!("share_token"in r))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${r.share_token}/r`}async unshareRun(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"unshare run",!0)}async readRunSharedLink(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await e.json();if(null!==a&&"share_token"in a)return`${this.getHostUrl()}/public/${a.share_token}/r`}async listSharedRuns(t,{runIds:e}={}){let a=new URLSearchParams({share_token:t});if(void 0!==e)for(let t of e)a.append("id",t);y(t);let i=await this.caller.call(c(),`${this.apiUrl}/public/${t}/runs${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await i.json()}async readDatasetSharedSchema(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id),y(t);let a=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id);let a={dataset_id:t};y(t);let i=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),r=await i.json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async unshareDataset(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"unshare dataset",!0)}async readSharedDataset(t){y(t);let e=await this.caller.call(c(),`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await e.json()}async listSharedExamples(t,e){let a={};e?.exampleIds&&(a.id=e.exampleIds);let i=new URLSearchParams;Object.entries(a).forEach(([t,e])=>{Array.isArray(e)?e.forEach(e=>i.append(t,e)):i.append(t,e)});let r=await this.caller.call(c(),`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){if("detail"in n)throw Error(`Failed to list shared examples.
9
- Status: ${r.status}
10
- Message: ${n.detail.join("\n")}`);throw Error(`Failed to list shared examples: ${r.status} ${r.statusText}`)}return n.map(t=>({...t,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:e=null,metadata:a=null,upsert:i=!1,projectExtra:r=null,referenceDatasetId:n=null}){let s=`${this.apiUrl}/sessions${i?"?upsert=true":""}`,o=r||{};a&&(o.metadata=a);let l={name:t,extra:o,description:e};null!==n&&(l.reference_dataset_id=n);let d=await this.caller.call(c(),s,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"create project"),await d.json()}async updateProject(t,{name:e=null,description:a=null,metadata:i=null,projectExtra:r=null,endTime:n=null}){let s=`${this.apiUrl}/sessions/${t}`,o=r;i&&(o={...o||{},metadata:i});let l={name:e,extra:o,description:a,end_time:n?new Date(n).toISOString():null},d=await this.caller.call(c(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"update project"),await d.json()}async hasProject({projectId:t,projectName:e}){let a="/sessions",i=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)y(t),a+=`/${t}`;else if(void 0!==e)i.append("name",e);else throw Error("Must provide projectName or projectId");let r=await this.caller.call(c(),`${this.apiUrl}${a}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let t=await r.json();if(!r.ok)return!1;if(Array.isArray(t))return t.length>0;return!0}catch(t){return!1}}async readProject({projectId:t,projectName:e,includeStats:a}){let i,r="/sessions",n=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)y(t),r+=`/${t}`;else if(void 0!==e)n.append("name",e);else throw Error("Must provide projectName or projectId");void 0!==a&&n.append("include_stats",a.toString());let s=await this._get(r,n);if(Array.isArray(s)){if(0===s.length)throw Error(`Project[id=${t}, name=${e}] not found`);i=s[0]}else i=s;return i}async getProjectUrl({projectId:t,projectName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either projectName or projectId");let a=await this.readProject({projectId:t,projectName:e}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${a.id}`}async getDatasetUrl({datasetId:t,datasetName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either datasetName or datasetId");let a=await this.readDataset({datasetId:t,datasetName:e}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${a.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let e of this._getPaginated("/sessions",t))return this._tenantId=e[0].tenant_id,e[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:t,name:e,nameContains:a,referenceDatasetId:i,referenceDatasetName:r,referenceFree:n,metadata:s}={}){let o=new URLSearchParams;if(void 0!==t)for(let e of t)o.append("id",e);if(void 0!==e&&o.append("name",e),void 0!==a&&o.append("name_contains",a),void 0!==i)o.append("reference_dataset",i);else if(void 0!==r){let t=await this.readDataset({datasetName:r});o.append("reference_dataset",t.id)}for await(let t of(void 0!==n&&o.append("reference_free",n.toString()),void 0!==s&&o.append("metadata",JSON.stringify(s)),this._getPaginated("/sessions",o)))yield*t}async deleteProject({projectId:t,projectName:e}){let a;if(void 0===t&&void 0===e)throw Error("Must provide projectName or projectId");if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");y(a=void 0===t?(await this.readProject({projectName:e})).id:t);let i=await this.caller.call(c(),`${this.apiUrl}/sessions/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(i,`delete session ${a} (${e})`,!0)}async uploadCsv({csvFile:t,fileName:e,inputKeys:a,outputKeys:i,description:r,dataType:n,name:s}){let o=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",t,e),a.forEach(t=>{l.append("input_keys",t)}),i.forEach(t=>{l.append("output_keys",t)}),r&&l.append("description",r),n&&l.append("data_type",n),s&&l.append("name",s);let d=await this.caller.call(c(),o,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(d,"upload CSV"),await d.json()}async createDataset(t,{description:e,dataType:a,inputsSchema:i,outputsSchema:r,metadata:n}={}){let s={name:t,description:e,extra:n?{metadata:n}:void 0};a&&(s.data_type=a),i&&(s.inputs_schema_definition=i),r&&(s.outputs_schema_definition=r);let o=await this.caller.call(c(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(o,"create dataset"),await o.json()}async readDataset({datasetId:t,datasetName:e}){let a,i="/datasets",r=new URLSearchParams({limit:"1"});if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t)y(t),i+=`/${t}`;else if(void 0!==e)r.append("name",e);else throw Error("Must provide datasetName or datasetId");let n=await this._get(i,r);if(Array.isArray(n)){if(0===n.length)throw Error(`Dataset[id=${t}, name=${e}] not found`);a=n[0]}else a=n;return a}async hasDataset({datasetId:t,datasetName:e}){try{return await this.readDataset({datasetId:t,datasetName:e}),!0}catch(t){if(t instanceof Error&&t.message.toLocaleLowerCase().includes("not found"))return!1;throw t}}async diffDatasetVersions({datasetId:t,datasetName:e,fromVersion:a,toVersion:i}){let r=t;if(void 0===r&&void 0===e)throw Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");void 0===r&&(r=(await this.readDataset({datasetName:e})).id);let n=new URLSearchParams({from_version:"string"==typeof a?a:a.toISOString(),to_version:"string"==typeof i?i:i.toISOString()});return await this._get(`/datasets/${r}/versions/diff`,n)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:e}){if(void 0!==t);else if(void 0!==e)t=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide datasetName or datasetId");let a=await this._getResponse(`/datasets/${t}/openai_ft`);return(await a.text()).trim().split("\n").map(t=>JSON.parse(t))}async *listDatasets({limit:t=100,offset:e=0,datasetIds:a,datasetName:i,datasetNameContains:r,metadata:n}={}){let s=new URLSearchParams({limit:t.toString(),offset:e.toString()});if(void 0!==a)for(let t of a)s.append("id",t);for await(let t of(void 0!==i&&s.append("name",i),void 0!==r&&s.append("name_contains",r),void 0!==n&&s.append("metadata",JSON.stringify(n)),this._getPaginated("/datasets",s)))yield*t}async updateDataset(t){let{datasetId:e,datasetName:a,...i}=t;if(!e&&!a)throw Error("Must provide either datasetName or datasetId");let r=e??(await this.readDataset({datasetName:a})).id;y(r);let n=await this.caller.call(c(),`${this.apiUrl}/datasets/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"update dataset"),await n.json()}async updateDatasetTag(t){let{datasetId:e,datasetName:a,asOf:i,tag:r}=t;if(!e&&!a)throw Error("Must provide either datasetName or datasetId");let n=e??(await this.readDataset({datasetName:a})).id;y(n);let s=await this.caller.call(c(),`${this.apiUrl}/datasets/${n}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:"string"==typeof i?i:i.toISOString(),tag:r}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,"update dataset tags")}async deleteDataset({datasetId:t,datasetName:e}){let a="/datasets",i=t;if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e&&(i=(await this.readDataset({datasetName:e})).id),void 0!==i)y(i),a+=`/${i}`;else throw Error("Must provide datasetName or datasetId");let r=await this.caller.call(c(),this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,`delete ${a}`),await r.json()}async indexDataset({datasetId:t,datasetName:e,tag:a}){let i=t;if(i||e)if(i&&e)throw Error("Must provide either datasetName or datasetId, not both");else i||(i=(await this.readDataset({datasetName:e})).id);else throw Error("Must provide either datasetName or datasetId");y(i);let r=await this.caller.call(c(),`${this.apiUrl}/datasets/${i}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({tag:a}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"index dataset"),await r.json()}async similarExamples(t,e,a,{filter:i}={}){let r={limit:a,inputs:t};void 0!==i&&(r.filter=i),y(e);let n=await this.caller.call(c(),`${this.apiUrl}/datasets/${e}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"fetch similar examples"),(await n.json()).examples}async createExample(t,e,{datasetId:a,datasetName:i,createdAt:r,exampleId:n,metadata:s,split:o,sourceRunId:l}){let d=a;if(void 0===d&&void 0===i)throw Error("Must provide either datasetName or datasetId");if(void 0!==d&&void 0!==i)throw Error("Must provide either datasetName or datasetId, not both");void 0===d&&(d=(await this.readDataset({datasetName:i})).id);let u=r||new Date,h={dataset_id:d,inputs:t,outputs:e,created_at:u?.toISOString(),id:n,metadata:s,split:o,source_run_id:l},p=await this.caller.call(c(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(h),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(p,"create example"),await p.json()}async createExamples(t){let{inputs:e,outputs:a,metadata:i,sourceRunIds:r,exampleIds:n,datasetId:s,datasetName:o}=t,l=s;if(void 0===l&&void 0===o)throw Error("Must provide either datasetName or datasetId");if(void 0!==l&&void 0!==o)throw Error("Must provide either datasetName or datasetId, not both");void 0===l&&(l=(await this.readDataset({datasetName:o})).id);let d=e.map((e,s)=>({dataset_id:l,inputs:e,outputs:a?a[s]:void 0,metadata:i?i[s]:void 0,split:t.splits?t.splits[s]:void 0,id:n?n[s]:void 0,source_run_id:r?r[s]:void 0})),u=await this.caller.call(c(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(u,"create examples"),await u.json()}async createLLMExample(t,e,a){return this.createExample({input:t},{output:e},a)}async createChatExample(t,e,a){let i=t.map(t=>g(t)?_(t):t),r=g(e)?_(e):e;return this.createExample({input:i},{output:r},a)}async readExample(t){y(t);let e=`/examples/${t}`,{attachment_urls:a,...i}=await this._get(e);return a&&(i.attachments=Object.entries(a).reduce((t,[e,a])=>(t[e.slice(11)]={presigned_url:a.presigned_url,mime_type:a.mime_type},t),{})),i}async *listExamples({datasetId:t,datasetName:e,exampleIds:a,asOf:i,splits:r,inlineS3Urls:n,metadata:s,limit:o,offset:l,filter:d,includeAttachments:u}={}){let h;if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t)h=t;else if(void 0!==e)h=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide a datasetName or datasetId");let c=new URLSearchParams({dataset:h}),p=i?"string"==typeof i?i:i?.toISOString():void 0;if(p&&c.append("as_of",p),c.append("inline_s3_urls",(n??!0).toString()),void 0!==a)for(let t of a)c.append("id",t);if(void 0!==r)for(let t of r)c.append("splits",t);if(void 0!==s){let t=JSON.stringify(s);c.append("metadata",t)}void 0!==o&&c.append("limit",o.toString()),void 0!==l&&c.append("offset",l.toString()),void 0!==d&&c.append("filter",d),!0===u&&["attachment_urls","outputs","metadata"].forEach(t=>c.append("select",t));let m=0;for await(let t of this._getPaginated("/examples",c)){for(let e of t){let{attachment_urls:t,...a}=e;t&&(a.attachments=Object.entries(t).reduce((t,[e,a])=>(t[e.slice(11)]={presigned_url:a.presigned_url,mime_type:a.mime_type||void 0},t),{})),yield a,m++}if(void 0!==o&&m>=o)break}}async deleteExample(t){y(t);let e=`/examples/${t}`,a=await this.caller.call(c(),this.apiUrl+e,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,`delete ${e}`),await a.json()}async updateExample(t,e){y(t);let a=await this.caller.call(c(),`${this.apiUrl}/examples/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(a,"update example"),await a.json()}async updateExamples(t){let e=await this.caller.call(c(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(e,"update examples"),await e.json()}async readDatasetVersion({datasetId:t,datasetName:e,asOf:a,tag:i}){let r;if(y(r=t||(await this.readDataset({datasetName:e})).id),a&&i||!a&&!i)throw Error("Exactly one of asOf and tag must be specified.");let n=new URLSearchParams;void 0!==a&&n.append("as_of","string"==typeof a?a:a.toISOString()),void 0!==i&&n.append("tag",i);let s=await this.caller.call(c(),`${this.apiUrl}/datasets/${r}/version?${n.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(s,"read dataset version"),await s.json()}async listDatasetSplits({datasetId:t,datasetName:e,asOf:a}){let i;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");y(i=void 0===t?(await this.readDataset({datasetName:e})).id:t);let r=new URLSearchParams,n=a?"string"==typeof a?a:a?.toISOString():void 0;return n&&r.append("as_of",n),await this._get(`/datasets/${i}/splits`,r)}async updateDatasetSplits({datasetId:t,datasetName:e,splitName:a,exampleIds:i,remove:r=!1}){let n;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");y(n=void 0===t?(await this.readDataset({datasetName:e})).id:t);let s={split_name:a,examples:i.map(t=>(y(t),t)),remove:r},o=await this.caller.call(c(),`${this.apiUrl}/datasets/${n}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(o,"update dataset splits",!0)}async evaluateRun(t,e,{sourceInfo:a,loadChildRuns:i,referenceExample:r}={loadChildRuns:!1}){let n;if(v("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."),"string"==typeof t)n=await this.readRun(t,{loadChildRuns:i});else if("object"==typeof t&&"id"in t)n=t;else throw Error(`Invalid run type: ${typeof t}`);null!==n.reference_example_id&&void 0!==n.reference_example_id&&(r=await this.readExample(n.reference_example_id));let s=await e.evaluateRun(n,r),[o,l]=await this._logEvaluationFeedback(s,n,a);return l[0]}async createFeedback(t,e,{score:a,value:i,correction:r,comment:n,sourceInfo:s,feedbackSourceType:l="api",sourceRunId:d,feedbackId:u,feedbackConfig:h,projectId:p,comparativeExperimentId:m}){if(!t&&!p)throw Error("One of runId or projectId must be provided");if(t&&p)throw Error("Only one of runId or projectId can be provided");let f={type:l??"api",metadata:s??{}};void 0===d||f?.metadata===void 0||f.metadata.__run||(f.metadata.__run={run_id:d}),f?.metadata!==void 0&&f.metadata.__run?.run_id!==void 0&&y(f.metadata.__run.run_id);let g={id:u??o.Z(),run_id:t,key:e,score:a,value:i,correction:r,comment:n,feedback_source:f,comparative_experiment_id:m,feedbackConfig:h,session_id:p},_=`${this.apiUrl}/feedback`,b=await this.caller.call(c(),_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(b,"create feedback",!0),g}async updateFeedback(t,{score:e,value:a,correction:i,comment:r}){let n={};null!=e&&(n.score=e),null!=a&&(n.value=a),null!=i&&(n.correction=i),null!=r&&(n.comment=r),y(t);let s=await this.caller.call(c(),`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(s,"update feedback",!0)}async readFeedback(t){y(t);let e=`/feedback/${t}`;return await this._get(e)}async deleteFeedback(t){y(t);let e=`/feedback/${t}`,a=await this.caller.call(c(),this.apiUrl+e,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,`delete ${e}`),await a.json()}async *listFeedback({runIds:t,feedbackKeys:e,feedbackSourceTypes:a}={}){let i=new URLSearchParams;if(t&&i.append("run",t.join(",")),e)for(let t of e)i.append("key",t);if(a)for(let t of a)i.append("source",t);for await(let t of this._getPaginated("/feedback",i))yield*t}async createPresignedFeedbackToken(t,e,{expiration:a,feedbackConfig:i}={}){let r={run_id:t,feedback_key:e,feedback_config:i};a?"string"==typeof a?r.expires_at=a:(a?.hours||a?.minutes||a?.days)&&(r.expires_in=a):r.expires_in={hours:3};let n=await this.caller.call(c(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await n.json()}async createComparativeExperiment({name:t,experimentIds:e,referenceDatasetId:a,createdAt:i,description:r,metadata:n,id:s}){if(0===e.length)throw Error("At least one experiment is required");if(a||(a=(await this.readProject({projectId:e[0]})).reference_dataset_id),null==!a)throw Error("A reference dataset is required");let o={id:s,name:t,experiment_ids:e,reference_dataset_id:a,description:r,created_at:(i??new Date)?.toISOString(),extra:{}};n&&(o.extra.metadata=n);let l=await this.caller.call(c(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await l.json()}async *listPresignedFeedbackTokens(t){y(t);let e=new URLSearchParams({run_id:t});for await(let t of this._getPaginated("/feedback/tokens",e))yield*t}_selectEvalResults(t){return"results"in t?t.results:[t]}async _logEvaluationFeedback(t,e,a){let i=this._selectEvalResults(t),r=[];for(let t of i){let i=a||{};t.evaluatorInfo&&(i={...t.evaluatorInfo,...i});let n=null;t.targetRunId?n=t.targetRunId:e&&(n=e.id),r.push(await this.createFeedback(n,t.key,{score:t.score,value:t.value,comment:t.comment,correction:t.correction,sourceInfo:i,sourceRunId:t.sourceRunId,feedbackConfig:t.feedbackConfig,feedbackSourceType:"model"}))}return[i,r]}async logEvaluationFeedback(t,e,a){let[i]=await this._logEvaluationFeedback(t,e,a);return i}async *listAnnotationQueues(t={}){let{queueIds:e,name:a,nameContains:i,limit:r}=t,n=new URLSearchParams;e&&e.forEach((t,e)=>{y(t,`queueIds[${e}]`),n.append("ids",t)}),a&&n.append("name",a),i&&n.append("name_contains",i),n.append("limit",(void 0!==r?Math.min(r,100):100).toString());let s=0;for await(let t of this._getPaginated("/annotation-queues",n))if(yield*t,s++,void 0!==r&&s>=r)break}async createAnnotationQueue(t){let{name:e,description:a,queueId:i}=t,r={name:e,description:a,id:i||o.Z()},n=await this.caller.call(c(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(r).filter(([t,e])=>void 0!==e))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"create annotation queue"),await n.json()}async readAnnotationQueue(t){let e=await this.listAnnotationQueues({queueIds:[t]}).next();if(e.done)throw Error(`Annotation queue with ID ${t} not found`);return e.value}async updateAnnotationQueue(t,e){let{name:a,description:i}=e,r=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:a,description:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(r,"update annotation queue")}async deleteAnnotationQueue(t){let e=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(e,"delete annotation queue")}async addRunsToAnnotationQueue(t,e){let a=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(e.map((t,e)=>y(t,`runIds[${e}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"add runs to annotation queue")}async getRunFromAnnotationQueue(t,e){let a=`/annotation-queues/${y(t,"queueId")}/run`,i=await this.caller.call(c(),`${this.apiUrl}${a}/${e}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(i,"get run from annotation queue"),await i.json()}async deleteRunFromAnnotationQueue(t,e){let a=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/runs/${y(e,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(a,"delete run from annotation queue")}async getSizeFromAnnotationQueue(t){let e=await this.caller.call(c(),`${this.apiUrl}/annotation-queues/${y(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(e,"get size from annotation queue"),await e.json()}async _currentTenantIsOwner(t){let e=await this._getSettings();return"-"==t||e.tenant_handle===t}async _ownerConflictError(t,e){let a=await this._getSettings();return Error(`Cannot ${t} for another tenant.
11
-
12
- Current tenant: ${a.tenant_handle}
13
-
14
- Requested tenant: ${e}`)}async _getLatestCommitHash(t){let e=await this.caller.call(c(),`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await e.json();if(!e.ok){let t="string"==typeof a.detail?a.detail:JSON.stringify(a.detail),i=Error(`Error ${e.status}: ${e.statusText}
15
- ${t}`);throw i.statusCode=e.status,i}if(0!==a.commits.length)return a.commits[0].commit_hash}async _likeOrUnlikePrompt(t,e){let[a,i,r]=O(t),n=await this.caller.call(c(),`${this.apiUrl}/likes/${a}/${i}`,{method:"POST",body:JSON.stringify({like:e}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,`${e?"like":"unlike"} prompt`),await n.json()}async _getPromptUrl(t){let[e,a,i]=O(t);if(await this._currentTenantIsOwner(e)){let t=await this._getSettings();return"latest"!==i?`${this.getHostUrl()}/prompts/${a}/${i.substring(0,8)}?organizationId=${t.id}`:`${this.getHostUrl()}/prompts/${a}?organizationId=${t.id}`}return"latest"!==i?`${this.getHostUrl()}/hub/${e}/${a}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${e}/${a}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async *listCommits(t){for await(let e of this._getPaginated(`/commits/${t}/`,new URLSearchParams,t=>t.commits))yield*e}async *listPrompts(t){let e=new URLSearchParams;for await(let a of(e.append("sort_field",t?.sortField??"updated_at"),e.append("sort_direction","desc"),e.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&e.append("is_public",t.isPublic.toString()),t?.query&&e.append("query",t.query),this._getPaginated("/repos",e,t=>t.repos)))yield*a}async getPrompt(t){let[e,a,i]=O(t),r=await this.caller.call(c(),`${this.apiUrl}/repos/${e}/${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(404===r.status)return null;await j(r,"get prompt");let n=await r.json();return n.repo?n.repo:null}async createPrompt(t,e){let a=await this._getSettings();if(e?.isPublic&&!a.tenant_handle)throw Error(`Cannot create a public prompt without first
16
-
17
- creating a LangChain Hub handle.
18
- You can add a handle by creating a public prompt at:
19
-
20
- https://smith.langchain.com/prompts`);let[i,r,n]=O(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let s={repo_handle:r,...e?.description&&{description:e.description},...e?.readme&&{readme:e.readme},...e?.tags&&{tags:e.tags},is_public:!!e?.isPublic},o=await this.caller.call(c(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(o,"create prompt");let{repo:l}=await o.json();return l}async createCommit(t,e,a){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[i,r,n]=O(t),s=a?.parentCommitHash!=="latest"&&a?.parentCommitHash?a?.parentCommitHash:await this._getLatestCommitHash(`${i}/${r}`),o={manifest:JSON.parse(JSON.stringify(e)),parent_commit:s},l=await this.caller.call(c(),`${this.apiUrl}/commits/${i}/${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(l,"create commit");let d=await l.json();return this._getPromptUrl(`${i}/${r}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,e=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let a=new FormData;for(let t of e){let e=t.id,i=new Blob([T({...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split}})],{type:"application/json"});if(a.append(e,i),t.inputs){let i=new Blob([T(t.inputs)],{type:"application/json"});a.append(`${e}.inputs`,i)}if(t.outputs){let i=new Blob([T(t.outputs)],{type:"application/json"});a.append(`${e}.outputs`,i)}if(t.attachments)for(let[i,r]of Object.entries(t.attachments)){let t,n;Array.isArray(r)?[t,n]=r:(t=r.mimeType,n=r.data);let s=new Blob([n],{type:`${t}; length=${n.byteLength}`});a.append(`${e}.attachment.${i}`,s)}if(t.attachments_operations){let i=new Blob([T(t.attachments_operations)],{type:"application/json"});a.append(`${e}.attachments_operations`,i)}}let i=await this.caller.call(c(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"PATCH",headers:this.headers,body:a});return await i.json()}async uploadExamplesMultipart(t,e=[]){if(!await this._getMultiPartSupport())throw Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let a=new FormData;for(let t of e){let e=(t.id??o.Z()).toString(),i=new Blob([T({created_at:t.created_at,...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split}})],{type:"application/json"});a.append(e,i);let r=new Blob([T(t.inputs)],{type:"application/json"});if(a.append(`${e}.inputs`,r),t.outputs){let i=new Blob([T(t.outputs)],{type:"application/json"});a.append(`${e}.outputs`,i)}if(t.attachments)for(let[i,r]of Object.entries(t.attachments)){let t,n;Array.isArray(r)?[t,n]=r:(t=r.mimeType,n=r.data);let s=new Blob([n],{type:`${t}; length=${n.byteLength}`});a.append(`${e}.attachment.${i}`,s)}}let i=await this.caller.call(c(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"POST",headers:this.headers,body:a});return await i.json()}async updatePrompt(t,e){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[a,i]=O(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("update a prompt",a);let r={};if(e?.description!==void 0&&(r.description=e.description),e?.readme!==void 0&&(r.readme=e.readme),e?.tags!==void 0&&(r.tags=e.tags),e?.isPublic!==void 0&&(r.is_public=e.isPublic),e?.isArchived!==void 0&&(r.is_archived=e.isArchived),0===Object.keys(r).length)throw Error("No valid update options provided");let n=await this.caller.call(c(),`${this.apiUrl}/repos/${a}/${i}`,{method:"PATCH",body:JSON.stringify(r),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await j(n,"update prompt"),n.json()}async deletePrompt(t){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[e,a,i]=O(t);if(!await this._currentTenantIsOwner(e))throw await this._ownerConflictError("delete a prompt",e);let r=await this.caller.call(c(),`${this.apiUrl}/repos/${e}/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await r.json()}async pullPromptCommit(t,e){let[a,i,r]=O(t),n=await this.caller.call(c(),`${this.apiUrl}/commits/${a}/${i}/${r}${e?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await j(n,"pull prompt commit");let s=await n.json();return{owner:a,repo:i,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async _pullPrompt(t,e){return JSON.stringify((await this.pullPromptCommit(t,{includeModel:e?.includeModel})).manifest)}async pushPrompt(t,e){return(await this.promptExists(t)?e&&Object.keys(e).some(t=>"object"!==t)&&await this.updatePrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}):await this.createPrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}),e?.object)?await this.createCommit(t,e?.object,{parentCommitHash:e?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,e={}){let{sourceApiUrl:a=this.apiUrl,datasetName:i}=e,[r,n]=this.parseTokenOrUrl(t,a),s=new L({apiUrl:r,apiKey:"placeholder"}),o=await s.readSharedDataset(n),l=i||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(t){}let d=await s.listSharedExamples(n),u=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(t=>t.inputs),outputs:d.flatMap(t=>t.outputs?[t.outputs]:[]),datasetId:u.id})}catch(t){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),t}}parseTokenOrUrl(t,e,a=2,i="dataset"){try{return y(t),[e,t]}catch(t){}try{let r=new URL(t).pathname.split("/").filter(t=>""!==t);if(r.length>=a){let t=r[r.length-a];return[e,t]}throw Error(`Invalid public ${i} URL: ${t}`)}catch(e){throw Error(`Invalid public ${i} URL or token: ${t}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()])}}let M="0.3.7";var D=a(73656);function B(){return void 0===r&&(r={library:"langsmith",runtime:i||(i="undefined"!=typeof window&&void 0!==window.document?"browser":void 0===D||void 0===D.versions||void 0===D.versions.node||"undefined"!=typeof Deno?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))?"jsdom":"undefined"!=typeof Deno?"deno":"other":"node"),sdk:"langsmith-js",sdk_version:M,...function(){if(void 0!==n)return n;let t={};for(let e of["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"]){let a=H(e);void 0!==a&&(t[e]=a)}return n=t,t}()}),r}function H(t){try{return void 0!==D?D.env?.[t]:void 0}catch(t){return}}function G(t){return H(`LANGSMITH_${t}`)||H(`LANGCHAIN_${t}`)}let F=t=>void 0!==t?t:!!["TRACING_V2","TRACING"].find(t=>"true"===G(t)),J=Symbol.for("lc:context_variables");class q{constructor(t,e){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=e}static fromHeader(t){let e=t.split(","),a={},i=[];for(let t of e){let[e,r]=t.split("="),n=decodeURIComponent(r);"langsmith-metadata"===e?a=JSON.parse(n):"langsmith-tags"===e&&(i=n.split(","))}return new q(a,i)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),t.join(",")}}class z{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Q(t))return void Object.assign(this,{...t});let e=z.getDefaultConfig(),{metadata:a,...i}=t,r=i.client??z.getSharedClient(),n={...a,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:n},Object.assign(this,{...e,...i,client:r}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let t=function(t,e,a=1){let i=a.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${i}Z`.replace(/[-:.]/g,"")+e}(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+t:this.dotted_order=t}}static getDefaultConfig(){return{id:o.Z(),run_type:"chain",project_name:G("PROJECT")??H("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:H("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:H("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return z.sharedClient||(z.sharedClient=new L),z.sharedClient}createChild(t){let e=this.child_execution_order+1,a=new z({...t,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:e,child_execution_order:e});J in this&&(a[J]=this[J]);let i=Symbol.for("lc:child_config"),r=t.extra?.[i]??this.extra[i];if(V(r)){var n;let t={...r},e="object"==typeof(n=t.callbacks)&&null!=n&&Array.isArray(n.handlers)?t.callbacks.copy?.():void 0;e&&(Object.assign(e,{_parentRunId:a.id}),e.handlers?.find(W)?.updateFromRunTree?.(a),t.callbacks=e),a.extra[i]=t}let s=new Set,o=this;for(;null!=o&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,e),o=o.parent_run;return this.child_runs.push(a),a}async end(t,e,a=Date.now(),i){this.outputs=this.outputs??t,this.error=this.error??e,this.end_time=this.end_time??a,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(t,e,a=!0){let i,r,n=t.extra??{};if(n.runtime||(n.runtime={}),e)for(let[t,a]of Object.entries(e))n.runtime[t]||(n.runtime[t]=a);return a?(r=t.parent_run?.id,i=[]):(i=t.child_runs.map(t=>this._convertToCreate(t,e,a)),r=void 0),{id:t.id,name:t.name,start_time:t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:n,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:i,parent_run_id:r,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments}}async postRun(t=!0){try{let e=B(),a=await this._convertToCreate(this,e,!0);if(await this.client.createRun(a),!t)for(let t of(v("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await t.postRun(!1)}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(){try{let t={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(t,e){let a,i,r,n=t?.callbacks,s=F();if(n){let t=n?.getParentRunId?.()??"",e=n?.handlers?.find(t=>t?.name=="langchain_tracer");a=e?.getRun?.(t),i=e?.projectName,r=e?.client,s=s||!!e}return a?new z({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:r,tracingEnabled:s,project_name:i,tags:[...new Set((a?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...t?.metadata}}}).createChild(e):new z({...e,client:r,tracingEnabled:s,project_name:i})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,e){let a="get"in t&&"function"==typeof t.get?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=a["langsmith-trace"];if(!i||"string"!=typeof i)return;let r=i.trim(),n=r.split(".").map(t=>{let[e,a]=t.split("Z");return{strTime:e,time:Date.parse(e+"Z"),uuid:a}}),s=n[0].uuid,o={...e,name:e?.name??"parent",run_type:e?.run_type??"chain",start_time:e?.start_time??Date.now(),id:n.at(-1)?.uuid,trace_id:s,dotted_order:r};if(a.baggage&&"string"==typeof a.baggage){let t=q.fromHeader(a.baggage);o.metadata=t.metadata,o.tags=t.tags}return new z(o)}toHeaders(t){let e={"langsmith-trace":this.dotted_order,baggage:new q(this.extra?.metadata,this.tags).toHeader()};if(t)for(let[a,i]of Object.entries(e))t.set(a,i);return e}}function Q(t){return void 0!==t&&"function"==typeof t.createChild&&"function"==typeof t.postRun}function W(t){return"object"==typeof t&&null!=t&&"string"==typeof t.name&&"langchain_tracer"===t.name}function K(t){return Array.isArray(t)&&t.some(t=>W(t))}function V(t){return void 0!==t&&"object"==typeof t.callbacks&&(K(t.callbacks?.handlers)||K(t.callbacks))}Object.defineProperty(z,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});let Z=Symbol.for("ls:tracing_async_local_storage"),Y=new class{getStore(){}run(t,e){return e()}},X=new class{getInstance(){return globalThis[Z]??Y}initializeGlobalInstance(t){void 0===globalThis[Z]&&(globalThis[Z]=t)}},tt=Symbol.for("langsmith:traceable:root");function te(t){return"function"==typeof t&&"langsmith:traceable"in t}function ta(t){if("object"!=typeof t||null==t)return!1;let e=Object.getPrototypeOf(t);return(null===e||e===Object.prototype||null===Object.getPrototypeOf(e))&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}let ti=t=>null!=t&&"object"==typeof t&&"function"==typeof t[Symbol.asyncIterator],tr=t=>null!=t&&"object"==typeof t&&"next"in t&&"function"==typeof t.next,tn=(function*(){}).constructor,ts=t=>null!=t&&"object"==typeof t&&"getReader"in t&&"function"==typeof t.getReader;X.initializeGlobalInstance(new s.A);let to=(t,e)=>{let a;a=ta(t)?t:{outputs:t};try{return e(a)}catch(t){return console.error("Error occurred during processOutputs. Sending raw outputs:",t),a}},tl=(t,e,a,i,r)=>{if(!F(t.tracingEnabled))return;let[n,s]=((t,e)=>{if(!e)return[void 0,t];try{let[a,i]=e(...t);return[a,i]}catch(e){return console.error("Error occurred during extractAttachments:",e),[void 0,t]}})(e,r);t.attachments=n,t.inputs=((t,e)=>{try{return e(t)}catch(e){return console.error("Error occurred during processInputs. Sending raw inputs:",e),t}})(s,i);let o=a?.(...e);return null!=o&&(t.extra??={},t.extra.metadata={...o,...t.extra.metadata}),t},td=t=>{let e={current:void 0};return new Proxy(t,{get(a,i,r){if("then"===i){let a=t[i].bind(t);return(t,i=t=>{throw t})=>a(a=>(e.current=["resolve",a],t(a)),t=>(e.current=["reject",t],i(t)))}if("catch"===i){let a=t[i].bind(t);return t=>a(a=>(e.current=["reject",a],t(a)))}return"toJSON"===i?()=>{if(!e.current)return;let[t,a]=e.current??[];return"resolve"===t?a:{error:a}}:Reflect.get(a,i,r)}})},tu=t=>{if(ts(t)){let e=[],a=new TransformStream({start:()=>void 0,transform:(t,a)=>{e.push(t),a.enqueue(t)},flush:()=>void 0}),i=t.pipeThrough(a);return Object.assign(i,{toJSON:()=>e}),i}if(ti(t)){let e=[];return new Proxy(t,{get:(a,i,r)=>i===Symbol.asyncIterator?()=>{let a=t[Symbol.asyncIterator].bind(t)();return new Proxy(a,{get(t,i,r){if("next"===i||"return"===i||"throw"===i){let t=a.next.bind(a);return(...a)=>{let i=td(t(...a));return e.push(i),i}}return"return"===i||"throw"===i?a.next.bind(a):Reflect.get(t,i,r)}})}:"toJSON"===i?()=>e.map(t=>t.toJSON()).reduce((t,e)=>(e?.value&&t.push(e.value),t),[]):Reflect.get(a,i,r)})}if(!Array.isArray(t)&&tr(t)){let e=[];return new Proxy(t,{get(a,i,r){if("next"===i||"return"===i||"throw"===i){let a=t[i]?.bind(t);return(...t)=>{let i=a?.(...t);return null!=i&&e.push(i),i}}return"toJSON"===i?()=>e.reduce((t,e)=>(e.value&&t.push(e.value),t),[]):Reflect.get(a,i,r)}})}return null!=t&&"object"==typeof t&&"then"in t&&"function"==typeof t.then?td(t):t};function th(t,e){let{aggregator:a,argsConfigPath:i,__finalTracedIteratorKey:r,processInputs:n,processOutputs:o,extractAttachments:l,...d}=e??{},u=n??(t=>t),h=o??(t=>t),c=l??((...t)=>[void 0,(t=>{let e=t[0];return null==e?{}:t.length>1?{args:t}:ta(e)?e:{input:e}})(t)]),p=(...n)=>{let o;try{let e;if(i){let[t,a]=i;if(t!==n.length-1||a){if(t<=n.length&&"object"==typeof n[t]&&null!==n[t])if(a){let{[a]:i,...r}=n[t];e=i,n[t]=r}else e=n[t],n.splice(t,1)}else e=n.pop()}o={name:t.name||"<lambda>",...d,...e,tags:[...new Set([...d?.tags??[],...e?.tags??[]])],metadata:{...d?.metadata,...e?.metadata}}}catch(e){console.warn(`Failed to extract runtime config from args for ${d?.name??t.name}`,e),o={name:t.name||"<lambda>",...d}}let l=X.getInstance();for(let t=0;t<n.length;t++)n[t]=tu(n[t]);let[p,m]=(()=>{let[t,...a]=n;if(V(t))return[tl(z.fromRunnableConfig(t,o),a,e?.getInvocationParams,u,c),a];if(Q(t)&&"callbackManager"in t&&null!=t.callbackManager)return[t,a];if(t===tt||Q(t)){let i=tl(t===tt?new z(o):t.createChild(o),a,e?.getInvocationParams,u,c);return[i,[i,...a]]}let i=l.getStore();if(Q(i))return[tl(i.createChild(o),n,e?.getInvocationParams,u,c),n];let r=tl(new z(o),n,e?.getInvocationParams,u,c);return void 0!==i&&J in i&&(r[J]=i[J]),[r,n]})();return l.run(p,()=>{let i,n=p?.postRun();async function o(t){if(void 0!==a)try{return await a(t)}catch(t){console.error("[ERROR]: LangSmith aggregation failed: ",t)}return t}async function*l(t,e){let a=!1,i=[];try{for(;;){let{value:r,done:n}=await (e?e(()=>t.next()):t.next());if(n){a=!0;break}i.push(r),yield r}}catch(t){throw await p?.end(void 0,String(t)),t}finally{a||await p?.end(void 0,"Cancelled"),await p?.end(to(await o(i),h)),await u()}}function d(t,e){if(ts(t)){let a=t.getReader(),i=!1,r=[];return new ReadableStream({async start(t){for(;;){let n=await (e?e(()=>a.read()):a.read());if(n.done){i=!0,await p?.end(to(await o(r),h)),await u(),t.close();break}r.push(n.value),t.enqueue(n.value)}},cancel:async t=>(i||await p?.end(void 0,"Cancelled"),await p?.end(to(await o(r),h)),await u(),a.cancel(t))})}let a=l(t[Symbol.asyncIterator](),e);return t[Symbol.asyncIterator]=()=>a,t}async function u(){let t=e?.on_end;t&&(p?t(p):console.warn("Can not call 'on_end' if currentRunTree is undefined")),await n,await p?.patchRun()}try{i=t(...m)}catch(t){i=Promise.reject(t)}if(ti(i)){let t=s.A.snapshot();return d(i,t)}if(!Array.isArray(i)&&"object"==typeof i&&null!=i&&void 0!==r&&ti(i[r])){let t=s.A.snapshot();return{...i,[r]:d(i[r],t)}}let c=new Promise((e,a)=>{Promise.resolve(i).then(async a=>{if(ti(a))return e(d(a,s.A.snapshot()));if(!Array.isArray(a)&&"object"==typeof a&&null!=a&&void 0!==r&&ti(a[r])){let t=s.A.snapshot();return{...a,[r]:d(a[r],t)}}if(null!=t&&"function"==typeof t&&t instanceof tn&&tr(a)){let t=function(t){let e=[];for(;;){let a=t.next();if(e.push(a),a.done)break}return e}(a);try{await p?.end(to(await o(t.reduce((t,{value:e,done:a})=>(a&&void 0===e||t.push(e),t),[])),h)),await u()}catch(t){console.error("Error occurred during handleEnd:",t)}return function*(){for(let e of t){if(e.done)return e.value;yield e.value}}()}try{await p?.end(to(a,h)),await u()}finally{return a}},async t=>{throw await p?.end(void 0,String(t)),await u(),t}).then(e,a)});return"object"!=typeof i||null===i?c:new Proxy(i,{get:(t,e,a)=>"then"===e||"catch"===e||"finally"===e?c[e].bind(c):Reflect.get(t,e,a)})})};return Object.defineProperty(p,"langsmith:traceable",{value:d}),p}let tc=t=>{if(!t||0===t.length)return{choices:[{message:{role:"assistant",content:""}}]};let e={};for(let a of t)for(let t of a.choices)void 0===e[t.index]&&(e[t.index]=[]),e[t.index].push(t);let a=t[t.length-1];return a.choices=Object.values(e).map(t=>(function(t){let e=t.slice().reverse(),a={role:"assistant",content:""};for(let t of e)if(t.delta.role){a.role=t.delta.role;break}let i={};for(let e of t)if(e.delta.content&&(a.content=a.content.concat(e.delta.content)),e.delta.function_call&&(a.function_call||(a.function_call={name:"",arguments:""}),e.delta.function_call.name&&(a.function_call.name+=e.delta.function_call.name),e.delta.function_call.arguments&&(a.function_call.arguments+=e.delta.function_call.arguments)),e.delta.tool_calls)for(let t of e.delta.tool_calls)i[e.index]||(i[e.index]=[]),i[e.index].push(t);if(Object.keys(i).length>0)for(let[t,e]of(a.tool_calls=[...Array(Object.keys(i).length)],Object.entries(i))){let i=parseInt(t);for(let t of(a.tool_calls[i]={index:i,id:e.find(t=>t.id)?.id||null,type:e.find(t=>t.type)?.type||null},e))t.function&&(a.tool_calls[i].function||(a.tool_calls[i].function={name:"",arguments:""}),t.function.name&&(a.tool_calls[i].function.name+=t.function.name),t.function.arguments&&(a.tool_calls[i].function.arguments+=t.function.arguments))}return{index:t[0].index,finish_reason:e.find(t=>t.finish_reason)||null,message:a}})(t)),a},tp=t=>{if(0===t.length)return{choices:[{text:""}]};let e=[];for(let a of t){let t=a.choices[0].text;null!=t&&e.push(t)}let a=e.join(""),i=t[t.length-1];return i.choices=[{...i.choices[0],text:a}],i};function tm(t){let e={...t},a=t.usage;if(a){let t={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},i={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}};e.usage_metadata={input_tokens:a.prompt_tokens??0,output_tokens:a.completion_tokens??0,total_tokens:a.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(i).length>0&&{output_token_details:i}}}return delete e.usage,e}let tf=(t,e)=>{if(te(t.chat.completions.create)||te(t.completions.create))throw Error("This instance of OpenAI client has been already wrapped once.");let a={...t};return t.beta&&t.beta.chat&&t.beta.chat.completions&&"function"==typeof t.beta.chat.completions.parse&&(a.beta={...t.beta,chat:{...t.beta.chat,completions:{...t.beta.chat.completions,parse:th(t.beta.chat.completions.parse.bind(t.beta.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:tc,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"chat",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},...e})}}}),a.chat={...t.chat,completions:{...t.chat.completions,create:th(t.chat.completions.create.bind(t.chat.completions),{name:"ChatOpenAI",run_type:"llm",aggregator:tc,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"chat",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},processOutputs:tm,...e})}},a.completions={...t.completions,create:th(t.completions.create.bind(t.completions),{name:"OpenAI",run_type:"llm",aggregator:tp,argsConfigPath:[1,"langsmithExtra"],getInvocationParams:t=>{if("object"!=typeof t||null==t)return;let e=("string"==typeof t.stop?[t.stop]:t.stop)??void 0;return{ls_provider:"openai",ls_model_type:"llm",ls_model_name:t.model,ls_max_tokens:t.max_tokens??void 0,ls_temperature:t.temperature??void 0,ls_stop:e}},...e})},a}}}]);
21
- //# sourceMappingURL=290.dd04c2bc.js.map