From 5187885c3b0889fbd5b9c6642132614a1817d3df Mon Sep 17 00:00:00 2001 From: Ross Date: Mon, 14 Jul 2025 13:26:11 +0100 Subject: [PATCH] lots of improvements --- atlas/admin.py | 4 +- atlas/forms.py | 31 +++- ...itions_casedisplayset_findings_and_more.py | 34 ++++ atlas/models.py | 11 +- atlas/templates/atlas/case_display_block.html | 100 +++++++++++- atlas/templates/atlas/case_displaysets.html | 72 ++++++++ .../atlas/collection_case_display_setup.html | 4 +- atlas/templates/atlas/collection_detail.html | 2 +- .../atlas/partials/displayset_form.html | 19 +++ .../atlas/partials/displayset_row.html | 84 ++++++++++ .../templates/atlas/question_link_header.html | 1 + atlas/urls.py | 9 +- atlas/views.py | 154 +++++++++++++++--- rad/static/dv3d/index.js | 82 +++++----- 14 files changed, 536 insertions(+), 71 deletions(-) create mode 100644 atlas/migrations/0073_casedisplayset_conditions_casedisplayset_findings_and_more.py create mode 100755 atlas/templates/atlas/case_displaysets.html create mode 100644 atlas/templates/atlas/partials/displayset_form.html create mode 100644 atlas/templates/atlas/partials/displayset_row.html diff --git a/atlas/admin.py b/atlas/admin.py index 9e83ba5f..d7edf087 100755 --- a/atlas/admin.py +++ b/atlas/admin.py @@ -16,7 +16,8 @@ from .models import ( Presentation, UncategorisedDicom, SeriesDetail, - Resource + Resource, + CaseDisplaySet, ) from django.forms import ModelForm @@ -46,6 +47,7 @@ admin.site.register(CaseDetail) admin.site.register(UncategorisedDicom) admin.site.register(SeriesDetail) admin.site.register(Resource) +admin.site.register(CaseDisplaySet) class DifferentialInline(admin.TabularInline): diff --git a/atlas/forms.py b/atlas/forms.py index aa480d90..0d4eef0a 100755 --- a/atlas/forms.py +++ b/atlas/forms.py @@ -40,6 +40,7 @@ from atlas.models import ( Subspecialty, UncategorisedDicom, UserReportAnswer, + CaseDisplaySet, ) from anatomy.models import Modality @@ -963,4 +964,32 @@ SeriesFormSet = inlineformset_factory( formset=BaseSeriesFormSet, extra=1, can_delete=True, -) \ No newline at end of file +) + +class CaseDisplaySetForm(forms.ModelForm): + class Meta: + model = CaseDisplaySet + fields = [ + "name", + "description", + "findings", + "structures", + "conditions", + ] + widgets = { + "name": forms.TextInput(attrs={"class": "form-control", "placeholder": "Display Set Name"}), + "description": forms.Textarea(attrs={"class": "form-control", "rows": 3, "placeholder": "Description"}), + "findings": autocomplete.ModelSelect2Multiple( + url="atlas:finding-autocomplete" + ), + "structures": autocomplete.ModelSelect2Multiple( + url="atlas:structure-autocomplete" + ), + "conditions": autocomplete.ModelSelect2Multiple( + url="atlas:condition-autocomplete" + ), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Optionally, you can filter queryset for findings/structures/conditions here if needed \ No newline at end of file diff --git a/atlas/migrations/0073_casedisplayset_conditions_casedisplayset_findings_and_more.py b/atlas/migrations/0073_casedisplayset_conditions_casedisplayset_findings_and_more.py new file mode 100644 index 00000000..ab57decc --- /dev/null +++ b/atlas/migrations/0073_casedisplayset_conditions_casedisplayset_findings_and_more.py @@ -0,0 +1,34 @@ +# Generated by Django 5.1.4 on 2025-07-14 09:41 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('atlas', '0072_casedisplayset'), + ] + + operations = [ + migrations.AddField( + model_name='casedisplayset', + name='conditions', + field=models.ManyToManyField(blank=True, to='atlas.condition'), + ), + migrations.AddField( + model_name='casedisplayset', + name='findings', + field=models.ManyToManyField(blank=True, to='atlas.finding'), + ), + migrations.AddField( + model_name='casedisplayset', + name='structures', + field=models.ManyToManyField(blank=True, to='atlas.structure'), + ), + migrations.AlterField( + model_name='casedisplayset', + name='case', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='display_sets', to='atlas.case'), + ), + ] diff --git a/atlas/models.py b/atlas/models.py index 4d51e49d..2980104c 100644 --- a/atlas/models.py +++ b/atlas/models.py @@ -1119,7 +1119,12 @@ class SeriesDetail(models.Model): ordering = ("sort_order",) class CaseDisplaySet(models.Model, AuthorMixin): - case = models.ForeignKey(Case, on_delete=models.CASCADE) + """ + This is analogous to a SeriesFinding but for a Case (it has + access to all the series stacks). + + """ + case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name="display_sets") name = models.CharField( max_length=255, @@ -1142,6 +1147,10 @@ class CaseDisplaySet(models.Model, AuthorMixin): blank=True, help_text="Annotations for the display set", ) + + findings = models.ManyToManyField(Finding, blank=True) + structures = models.ManyToManyField(Structure, blank=True) + conditions = models.ManyToManyField(Condition, blank=True) diff --git a/atlas/templates/atlas/case_display_block.html b/atlas/templates/atlas/case_display_block.html index 1f4e8cf9..e6799162 100755 --- a/atlas/templates/atlas/case_display_block.html +++ b/atlas/templates/atlas/case_display_block.html @@ -118,6 +118,16 @@ ID: {{ case.id }} +
+ Viewer + +
+
+

Description: {{ case.description }}

@@ -227,8 +237,10 @@ {% endif %} + +

Series Findings
{% if case.series.all %} - {% for detail in case.get_ordered_series %} + {% for series in case.get_ordered_series %} {% for finding in series.findings.all %}
- + + + @@ -274,6 +288,75 @@ {% else %} No series associated with case. {% endif %} + + +
Case Display Sets
+ {% if case.display_sets %} +
    + {% for ds in case.display_sets.all %} +
  • + Name: {{ ds.name }} + {% if ds.description %} + ({{ ds.description }}) + {% endif %} + + View Display Set + +
    + Findings: + {% if ds.findings.all %} +
      + {% for finding in ds.findings.all %} +
    • {{ finding }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    + Structures: + {% if ds.structures.all %} +
      + {% for structure in ds.structures.all %} +
    • {{ structure }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    + Conditions: + {% if ds.conditions.all %} +
      + {% for condition in ds.conditions.all %} +
    • {{ condition }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    +
    + Show advanced (viewer state & annotations) +
    + Viewer State: +
    {{ ds.viewerstate|default:"{}" }}
    +
    +
    + Annotations: +
    {{ ds.annotations|default:"{}" }}
    +
    +
    +
    +
  • + {% endfor %} +
+ {% else %} + No display sets for this case. + {% endif %}
@@ -439,7 +522,18 @@ } document.addEventListener("DOMContentLoaded", function () { - // Move up/down logic + + const dicomDetails = document.getElementById("dicom-viewer-details"); + let dicomViewerLoaded = false; + dicomDetails.addEventListener("toggle", function() { + if (!dicomViewerLoaded && dicomDetails.open) { + window.mountDicomViewers(); + dicomViewerLoaded = true; + } + }); + + + // Move up/down logic document.querySelectorAll("#series-reorder-list .move-up, #series-reorder-list .move-down").forEach(function(btn) { btn.addEventListener("click", function(e) { e.preventDefault(); diff --git a/atlas/templates/atlas/case_displaysets.html b/atlas/templates/atlas/case_displaysets.html new file mode 100755 index 00000000..62befea0 --- /dev/null +++ b/atlas/templates/atlas/case_displaysets.html @@ -0,0 +1,72 @@ +{% extends 'atlas/base.html' %} + +{% block content %} + + + {% include 'atlas/question_link_header.html' %} + +

Display Sets: {{ case.title }}

+ +
+ Help +

This page shows the display sets associated with the case.

+

If you have access you can add and edit display sets.

+
+ + +
+ +
+ +
+
+ + + +{% endblock %} + +{% block js %} + + +{% endblock %} diff --git a/atlas/templates/atlas/collection_case_display_setup.html b/atlas/templates/atlas/collection_case_display_setup.html index 43133f99..9112f87c 100644 --- a/atlas/templates/atlas/collection_case_display_setup.html +++ b/atlas/templates/atlas/collection_case_display_setup.html @@ -29,7 +29,7 @@ document.getElementById('save-viewerstate').addEventListener('click', function() document.getElementById('viewerstate-save-response').innerHTML = "Viewer state could not be retrieved."; return; } - fetch("{% url 'atlas:collection_case_display_setup' case_detail.collection.pk case_detail.case.pk %}", { + fetch("{% url 'atlas:collection_case_displaysetup' case_detail.collection.pk case_detail.case.pk %}", { method: "POST", headers: { "Content-Type": "application/json", @@ -46,7 +46,7 @@ document.getElementById('save-viewerstate').addEventListener('click', function() }); }); document.getElementById('reset-viewerstate').addEventListener('click', function() { - fetch("{% url 'atlas:collection_case_display_setup' case_detail.collection.pk case_detail.case.pk %}", { + fetch("{% url 'atlas:collection_case_displaysetup' case_detail.collection.pk case_detail.case.pk %}", { method: "POST", headers: { "Content-Type": "application/json", diff --git a/atlas/templates/atlas/collection_detail.html b/atlas/templates/atlas/collection_detail.html index dc9726d8..7045dd81 100644 --- a/atlas/templates/atlas/collection_detail.html +++ b/atlas/templates/atlas/collection_detail.html @@ -18,7 +18,7 @@
  • Case {{forloop.counter}} : {{casedetail.case.title}} - (setup default display + (setup default display {% if casedetail.default_viewerstate %} {% endif %} diff --git a/atlas/templates/atlas/partials/displayset_form.html b/atlas/templates/atlas/partials/displayset_form.html new file mode 100644 index 00000000..ca75d538 --- /dev/null +++ b/atlas/templates/atlas/partials/displayset_form.html @@ -0,0 +1,19 @@ +
    + {% csrf_token %} + {{ form.as_p }} + {{ form.media }} + + + +
    \ No newline at end of file diff --git a/atlas/templates/atlas/partials/displayset_row.html b/atlas/templates/atlas/partials/displayset_row.html new file mode 100644 index 00000000..7833e18f --- /dev/null +++ b/atlas/templates/atlas/partials/displayset_row.html @@ -0,0 +1,84 @@ +
  • +
    + {% if ds.viewerstate and ds.annotations %} + + {% endif %} +
    +
    + {{ ds.name }} + {% if ds.description %} + ({{ ds.description }}) + {% endif %} + +
    + Findings: + {% if ds.findings.all %} +
      + {% for finding in ds.findings.all %} +
    • {{ finding }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    + Structures: + {% if ds.structures.all %} +
      + {% for structure in ds.structures.all %} +
    • {{ structure }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    + Conditions: + {% if ds.conditions.all %} +
      + {% for condition in ds.conditions.all %} +
    • {{ condition }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    +
    + Show advanced (viewer state & annotations) +
    + Viewer State: +
    {{ ds.viewerstate|default:"{}" }}
    +
    +
    + Annotations: +
    {{ ds.annotations|default:"{}" }}
    +
    +
    +
    +
    + + +
    +
    +
    +
  • \ No newline at end of file diff --git a/atlas/templates/atlas/question_link_header.html b/atlas/templates/atlas/question_link_header.html index 58dd9782..7c84b961 100644 --- a/atlas/templates/atlas/question_link_header.html +++ b/atlas/templates/atlas/question_link_header.html @@ -2,6 +2,7 @@ View Edit Series + Display Sets Clone Delete diff --git a/atlas/urls.py b/atlas/urls.py index 76519ddd..ae7cfd70 100755 --- a/atlas/urls.py +++ b/atlas/urls.py @@ -221,8 +221,8 @@ urlpatterns = [ ), path( "collection///display_setup", - views.collection_case_display_setup, - name="collection_case_display_setup", + views.collection_case_displaysetup, + name="collection_case_displaysetup", ), path( "collection///take//", @@ -250,6 +250,11 @@ urlpatterns = [ name="collection_dicom_json", ), path("case//authors", views.CaseAuthorUpdate.as_view(), name="case_authors"), + path("case//display_sets", views.case_displaysets, name="case_displaysets"), + path("case//display_sets/add", views.case_displaysets_add, name="case_displaysets_add"), + path("/display_sets/edit", views.case_displaysets_edit, name="case_displaysets_edit"), + path("/display_sets/detail", views.case_displaysets_detail, name="case_displaysets_detail"), + path("/display_sets/delete", views.case_displaysets_delete, name="case_displaysets_delete"), path( "case//dicom_json", views.case_dicom_json, diff --git a/atlas/views.py b/atlas/views.py index 5f10e0fd..a85fba12 100755 --- a/atlas/views.py +++ b/atlas/views.py @@ -9,6 +9,8 @@ from django.shortcuts import render, get_object_or_404, redirect from django import forms from django.utils import timezone from django.views.decorators.http import require_POST +from django.views.decorators.http import require_http_methods +from django.template.loader import render_to_string # from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required, user_passes_test @@ -47,6 +49,7 @@ from .forms import ( CaseCollectionCaseFormSet, CaseCollectionForm, CaseDetailForm, + CaseDisplaySetForm, CaseForm, CaseResourceFormSet, CaseUpdateSeriesForm, @@ -77,7 +80,9 @@ from .models import ( Case, CaseCollection, CaseDetail, + CaseDisplaySet, CasePrior, + CaseResource, CidReportAnswer, Condition, Differential, @@ -196,6 +201,102 @@ class AtlasEditorRequiredMixin(object): return obj raise PermissionDenied("You must be an atlas editor to do this.") # or Http404 +@login_required +@user_has_case_view_access +def case_displaysets(request, pk): + case = get_object_or_404(Case, pk=pk) + + can_edit = case.check_user_can_edit(request.user) + + # Get displayset id from GET parameter + displayset_id = request.GET.get("displayset") + selected_displayset = None + if displayset_id: + try: + selected_displayset = case.display_sets.get(pk=displayset_id) + except CaseDisplaySet.DoesNotExist: + selected_displayset = None + + return render( + request, + "atlas/case_displaysets.html", + { + "case": case, + "can_edit": can_edit, + "selected_displayset": selected_displayset, + }, + ) + +@login_required +@user_has_case_view_access +@require_http_methods(["GET", "POST"]) +def case_displaysets_add(request, pk): + case = get_object_or_404(Case, pk=pk) + form = CaseDisplaySetForm(request.POST or None) + if request.method == "POST": + if form.is_valid(): + ds = form.save(commit=False) + ds.case = case + ds.author = request.user + ds.viewerstate = request.POST.get("viewerstate") or None + ds.annotations = request.POST.get("annotations") or None + ds.save() + form.save_m2m() + # HTMX: return the new display set row HTML fragment + html = render_to_string("atlas/partials/displayset_row.html", {"ds": ds, "can_edit": True}) + return HttpResponse(html) + else: + # HTMX: return the form HTML fragment with errors + html = render_to_string("atlas/partials/displayset_form.html", {"form": form, "case": case}, request=request) + return HttpResponse(html, status=400) + else: + # HTMX: return the blank form HTML fragment + html = render_to_string("atlas/partials/displayset_form.html", {"form": form, "case": case}, request=request) + return HttpResponse(html) + +@login_required +@require_http_methods(["GET", "POST"]) +def case_displaysets_edit(request, pk): + ds = get_object_or_404(CaseDisplaySet, pk=pk) + + case = ds.case + if not case.check_user_can_edit(request.user): + return HttpResponse("You do not have permission to delete this display set.") + form = CaseDisplaySetForm(request.POST or None, instance=ds) + if request.method == "POST": + if form.is_valid(): + ds = form.save(commit=False) + ds.viewerstate = request.POST.get("viewerstate") or ds.viewerstate + ds.annotations = request.POST.get("annotations") or ds.annotations + ds.save() + form.save_m2m() + # Return updated row HTML + html = render_to_string("atlas/partials/displayset_row.html", {"ds": ds, "can_edit": True}, request=request) + return HttpResponse(html) + else: + html = render_to_string("atlas/partials/displayset_form.html", {"form": form, "case": case}, request=request) + return HttpResponse(html, status=400) + else: + html = render_to_string("atlas/partials/displayset_form.html", {"form": form, "case": case}, request=request) + return HttpResponse(html) + +@require_http_methods(["GET", "POST"]) +def case_displaysets_detail(request, pk): + displayset = get_object_or_404(CaseDisplaySet, pk=pk) + case = displayset.case + # Redirect to the case_displaysets page with ?displayset= + return redirect(f"{reverse('atlas:case_displaysets', args=[case.pk])}?displayset={pk}") + +def case_displaysets_delete(request, pk): + try: + displayset = CaseDisplaySet.objects.get(pk=pk) + except CaseDisplaySet.DoesNotExist: + raise Http404("Display set not found.") + + if not displayset.case.check_user_can_edit(request.user): + raise PermissionDenied("You do not have permission to delete this display set.") + displayset.delete() + return HttpResponse("
  • Display set deleted successfully.") @login_required @user_has_case_view_access @@ -205,25 +306,40 @@ def case_detail(request, pk): Case.objects .select_related() # Add any FK fields if needed .prefetch_related( - "series__examination", - "series__plane", - "series__contrast", - "series__images", - "series__findings__findings", - "series__findings__conditions", - "series__findings__structures", - "subspecialty", - "condition", - "presentation", - "pathological_process", - #"differential", - "caseresource_set", - "author", - "casecollection_set", + Prefetch( + "seriesdetail_set", + queryset=SeriesDetail.objects.select_related("series").order_by("sort_order").prefetch_related( + Prefetch( + "series", + queryset=Series.objects.select_related("modality", "examination", "plane", "contrast") + .prefetch_related( + Prefetch("images", queryset=SeriesImage.objects.filter(removed=False).order_by("position")), + Prefetch( + "findings", + queryset=SeriesFinding.objects.prefetch_related( + Prefetch("findings", queryset=Finding.objects.all()), + Prefetch("conditions", queryset=Condition.objects.all()), + Prefetch("structures", queryset=Structure.objects.all()), + ) + ), + ) + ), + ), + ), + Prefetch("subspecialty", queryset=Subspecialty.objects.all()), + Prefetch("condition", queryset=Condition.objects.all()), + Prefetch("presentation", queryset=Presentation.objects.all()), + Prefetch("pathological_process", queryset=PathologicalProcess.objects.all()), + Prefetch("caseresource_set", queryset=CaseResource.objects.all()), + Prefetch("casecollection_set", queryset=CaseCollection.objects.all()), + Prefetch("display_sets", queryset=CaseDisplaySet.objects.prefetch_related( + Prefetch("findings", queryset=Finding.objects.all()), + Prefetch("structures", queryset=Structure.objects.all()), + Prefetch("conditions", queryset=Condition.objects.all()), + )), ) .get(pk=pk) ) - can_edit = case.check_user_can_edit(request.user) return render( @@ -3349,7 +3465,7 @@ def series_bulk_delete(request): @user_is_collection_author_or_atlas_editor @csrf_exempt # Only if you have CSRF issues; otherwise, keep CSRF protection -def collection_case_display_setup(request, collection_id, case_id): +def collection_case_displaysetup(request, collection_id, case_id): """ View to set up the display options for a specific case in a collection. This can include setting which series to display, annotations, etc. @@ -3370,6 +3486,6 @@ def collection_case_display_setup(request, collection_id, case_id): else: return HttpResponse("No viewer state provided.", status=400) - return render(request, "atlas/collection_case_display_setup.html", { + return render(request, "atlas/collection_case_displaysetup.html", { "case_detail": case_detail - }) \ No newline at end of file + }) diff --git a/rad/static/dv3d/index.js b/rad/static/dv3d/index.js index 4e848e46..0461143b 100644 --- a/rad/static/dv3d/index.js +++ b/rad/static/dv3d/index.js @@ -56,7 +56,7 @@ Error generating stack: `+o.message+` vec4 intColor = texture(u_image, gl_PointCoord.xy); color = vec4(vec3(intColor.rrr), 1); } - `,f=a.createShader(a.VERTEX_SHADER);if(a.shaderSource(f,c),a.compileShader(f),!a.getShaderParameter(f,a.COMPILE_STATUS))return!1;const u=a.createShader(a.FRAGMENT_SHADER);if(a.shaderSource(u,l),a.compileShader(u),!a.getShaderParameter(u,a.COMPILE_STATUS))return!1;const d=a.createProgram();if(a.attachShader(d,f),a.attachShader(d,u),a.linkProgram(d),!a.getProgramParameter(d,a.LINK_STATUS))return!1;const h=a.createTexture();a.bindTexture(a.TEXTURE_2D,h),a.texImage2D(a.TEXTURE_2D,0,s.R16_SNORM_EXT,2,1,0,a.RED,a.SHORT,n),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.useProgram(d),a.drawArrays(a.POINTS,0,1);const g=new Uint8Array(4);a.readPixels(i[0],i[1],1,1,a.RGBA,a.UNSIGNED_BYTE,g);const[p,v,y]=g,m=a.getExtension("WEBGL_lose_context");return m&&m.loseContext(),p===v&&v===y&&p!==0}catch{return!1}}let Dw;function IH(){return Dw===void 0&&(Dw=bH()),Dw}const{Wrap:Ic,Filter:bi}=UO,{VtkDataTypes:Hn}=Yt,{vtkDebugMacro:bw,vtkErrorMacro:md,vtkWarningMacro:s6}=So,{toHalf:OH}=Od;function MH(t,e){e.classHierarchy.push("vtkOpenGLTexture");function r(){return{internalFormat:e.internalFormat,format:e.format,openGLDataType:e.openGLDataType,width:e.width,height:e.height}}t.render=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;if(g?e._openGLRenderWindow=g:(e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow")),e.context=e._openGLRenderWindow.getContext(),e.renderable.getInterpolate()?(e.generateMipmap?t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR):t.setMinificationFilter(bi.LINEAR),t.setMagnificationFilter(bi.LINEAR)):(t.setMinificationFilter(bi.NEAREST),t.setMagnificationFilter(bi.NEAREST)),e.renderable.getRepeat()&&(t.setWrapR(Ic.REPEAT),t.setWrapS(Ic.REPEAT),t.setWrapT(Ic.REPEAT)),e.renderable.getInputData()&&e.renderable.setImage(null),!e.handle||e.renderable.getMTime()>e.textureBuildTime.getMTime()){if(e.renderable.getImage()!==null&&(e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR)),e.renderable.getImage()&&e.renderable.getImageLoaded()&&(t.create2DFromImage(e.renderable.getImage()),t.activate(),t.sendParameters(),e.textureBuildTime.modified())),e.renderable.getCanvas()!==null){e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR));const v=e.renderable.getCanvas();t.create2DFromRaw(v.width,v.height,4,Hn.UNSIGNED_CHAR,v,!0),t.activate(),t.sendParameters(),e.textureBuildTime.modified()}if(e.renderable.getJsImageData()!==null){const v=e.renderable.getJsImageData();e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR)),t.create2DFromRaw(v.width,v.height,4,Hn.UNSIGNED_CHAR,v.data,!0),t.activate(),t.sendParameters(),e.textureBuildTime.modified()}const p=e.renderable.getInputData(0);if(p&&p.getPointData().getScalars()){const v=p.getExtent(),y=p.getPointData().getScalars(),m=[];for(let w=0;w{if(!((e.minificationFilter===bi.LINEAR||e.magnificationFilter===bi.LINEAR)&&!IH()))return e.oglNorm16Ext};t.destroyTexture=()=>{t.deactivate(),e.context&&e.handle&&e.context.deleteTexture(e.handle),e._prevTexParams=null,e.handle=0,e.numberOfDimensions=0,e.target=0,e.components=0,e.width=0,e.height=0,e.depth=0,t.resetFormatAndType()},t.createTexture=()=>{e.handle||(e.handle=e.context.createTexture(),e.target&&(e.context.bindTexture(e.target,e.handle),e.context.texParameteri(e.target,e.context.TEXTURE_MIN_FILTER,t.getOpenGLFilterMode(e.minificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_MAG_FILTER,t.getOpenGLFilterMode(e.magnificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_S,t.getOpenGLWrapMode(e.wrapS)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_T,t.getOpenGLWrapMode(e.wrapT)),e._openGLRenderWindow.getWebgl2()&&e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_R,t.getOpenGLWrapMode(e.wrapR)),e.context.bindTexture(e.target,null)))},t.getTextureUnit=()=>e._openGLRenderWindow?e._openGLRenderWindow.getTextureUnitForTexture(t):-1,t.activate=()=>{e._openGLRenderWindow.activateTexture(t),t.bind()},t.deactivate=()=>{e._openGLRenderWindow&&e._openGLRenderWindow.deactivateTexture(t)},t.releaseGraphicsResources=g=>{g&&e.handle&&(g.activateTexture(t),g.deactivateTexture(t),e.context.deleteTexture(e.handle),e._prevTexParams=null,e.handle=0,e.numberOfDimensions=0,e.target=0,e.internalFormat=0,e.format=0,e.openGLDataType=0,e.components=0,e.width=0,e.height=0,e.depth=0,e.allocatedGPUMemoryInBytes=0),e.shaderProgram&&(e.shaderProgram.releaseGraphicsResources(g),e.shaderProgram=null)},t.bind=()=>{e.context.bindTexture(e.target,e.handle),e.autoParameters&&t.getMTime()>e.sendParametersTime.getMTime()&&t.sendParameters()},t.isBound=()=>{let g=!1;if(e.context&&e.handle){let p=0;switch(e.target){case e.context.TEXTURE_2D:p=e.context.TEXTURE_BINDING_2D;break;default:s6("impossible case");break}g=e.context.getIntegerv(p)===e.handle}return g},t.sendParameters=()=>{e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_S,t.getOpenGLWrapMode(e.wrapS)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_T,t.getOpenGLWrapMode(e.wrapT)),e._openGLRenderWindow.getWebgl2()&&e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_R,t.getOpenGLWrapMode(e.wrapR)),e.context.texParameteri(e.target,e.context.TEXTURE_MIN_FILTER,t.getOpenGLFilterMode(e.minificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_MAG_FILTER,t.getOpenGLFilterMode(e.magnificationFilter)),e._openGLRenderWindow.getWebgl2()&&(e.context.texParameteri(e.target,e.context.TEXTURE_BASE_LEVEL,e.baseLevel),e.context.texParameteri(e.target,e.context.TEXTURE_MAX_LEVEL,e.maxLevel)),e.sendParametersTime.modified()},t.getInternalFormat=(g,p)=>(e._forceInternalFormat||(e.internalFormat=t.getDefaultInternalFormat(g,p)),e.internalFormat||bw(`Unable to find suitable internal format for T=${g} NC= ${p}`),[e.context.R32F,e.context.RG32F,e.context.RGB32F,e.context.RGBA32F].includes(e.internalFormat)&&!e.context.getExtension("OES_texture_float_linear")&&s6("Failed to load OES_texture_float_linear. Texture filtering is not available for *32F internal formats."),e.internalFormat),t.getDefaultInternalFormat=(g,p)=>{let v=0;return v=e._openGLRenderWindow.getDefaultTextureInternalFormat(g,p,n(),t.useHalfFloat()),v||(v||(bw("Unsupported internal texture type!"),bw(`Unable to find suitable internal format for T=${g} NC= ${p}`)),v)},t.useHalfFloat=()=>e.enableUseHalfFloat&&e.canUseHalfFloat,t.setInternalFormat=g=>{e._forceInternalFormat=!0,g!==e.internalFormat&&(e.internalFormat=g,t.modified())},t.getFormat=(g,p)=>(e.format=t.getDefaultFormat(g,p),e.format),t.getDefaultFormat=(g,p)=>{if(e._openGLRenderWindow.getWebgl2())switch(p){case 1:return e.context.RED;case 2:return e.context.RG;case 3:return e.context.RGB;case 4:return e.context.RGBA;default:return e.context.RGB}else switch(p){case 1:return e.context.LUMINANCE;case 2:return e.context.LUMINANCE_ALPHA;case 3:return e.context.RGB;case 4:return e.context.RGBA;default:return e.context.RGB}},t.resetFormatAndType=()=>{e._prevTexParams=null,e.format=0,e.internalFormat=0,e._forceInternalFormat=!1,e.openGLDataType=0},t.getDefaultDataType=g=>{const p=t.useHalfFloat();if(e._openGLRenderWindow.getWebgl2())switch(g){case Hn.UNSIGNED_CHAR:return e.context.UNSIGNED_BYTE;case(n()&&!p&&Hn.SHORT):return e.context.SHORT;case(n()&&!p&&Hn.UNSIGNED_SHORT):return e.context.UNSIGNED_SHORT;case(p&&Hn.SHORT):return e.context.HALF_FLOAT;case(p&&Hn.UNSIGNED_SHORT):return e.context.HALF_FLOAT;case Hn.FLOAT:case Hn.VOID:default:return e.context.FLOAT}switch(g){case Hn.UNSIGNED_CHAR:return e.context.UNSIGNED_BYTE;case Hn.FLOAT:case Hn.VOID:default:if(e.context.getExtension("OES_texture_float")&&e.context.getExtension("OES_texture_float_linear"))return e.context.FLOAT;{const v=e.context.getExtension("OES_texture_half_float");if(v&&e.context.getExtension("OES_texture_half_float_linear"))return v.HALF_FLOAT_OES}return e.context.UNSIGNED_BYTE}},t.getOpenGLDataType=function(g){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(!e.openGLDataType||p)&&(e.openGLDataType=t.getDefaultDataType(g)),e.openGLDataType},t.getShiftAndScale=()=>{let g=0,p=1;switch(e.openGLDataType){case e.context.BYTE:p=127.5,g=p-128;break;case e.context.UNSIGNED_BYTE:p=255,g=0;break;case e.context.SHORT:p=32767.5,g=p-32768;break;case e.context.UNSIGNED_SHORT:p=65536,g=0;break;case e.context.INT:p=21474836475e-1,g=p-2147483648;break;case e.context.UNSIGNED_INT:p=4294967295,g=0;break;case e.context.FLOAT:}return{shift:g,scale:p}},t.getOpenGLFilterMode=g=>{switch(g){case bi.NEAREST:return e.context.NEAREST;case bi.LINEAR:return e.context.LINEAR;case bi.NEAREST_MIPMAP_NEAREST:return e.context.NEAREST_MIPMAP_NEAREST;case bi.NEAREST_MIPMAP_LINEAR:return e.context.NEAREST_MIPMAP_LINEAR;case bi.LINEAR_MIPMAP_NEAREST:return e.context.LINEAR_MIPMAP_NEAREST;case bi.LINEAR_MIPMAP_LINEAR:return e.context.LINEAR_MIPMAP_LINEAR;default:return e.context.NEAREST}},t.getOpenGLWrapMode=g=>{switch(g){case Ic.CLAMP_TO_EDGE:return e.context.CLAMP_TO_EDGE;case Ic.REPEAT:return e.context.REPEAT;case Ic.MIRRORED_REPEAT:return e.context.MIRRORED_REPEAT;default:return e.context.CLAMP_TO_EDGE}};function i(g){const[p,v,y,m,w,x]=g;return[v-p+1,m-y+1,x-w+1]}function o(g){const[p,v,y]=i(g);return p*v*y}function a(g,p,v,y,m){const[w,x,C,S,_,T]=v,[E,D]=p,b=E*D;let I=m;for(let P=_;P<=T;P++){const M=P*b;for(let L=C;L<=S;L++){const V=M+L*E;for(let G=V+w,A=V+x;G<=A;G++,I++)y[I]=g[G]}}}function s(g,p){const y=(arguments.length>2&&arguments[2]!==void 0?arguments[2]:null)||g.constructor,m=p.reduce((S,_)=>S+o(_),0),w=new y(m),x=[e.width,e.height,e.depth];let C=0;return p.forEach(S=>{a(g,x,S,w,C),C+=o(S)}),w}t.updateArrayDataTypeForGL=function(g,p){let v=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:[];const m=[];let w=e.width*e.height*e.components;v&&(w*=e.depth);const x=!!y.length;if(g!==Hn.FLOAT&&e.openGLDataType===e.context.FLOAT)for(let S=0;Sw?p[S].subarray(0,w):p[S];m.push(new Float32Array(_))}else m.push(null);if(g!==Hn.UNSIGNED_CHAR&&e.openGLDataType===e.context.UNSIGNED_BYTE)for(let S=0;Sw?p[S].subarray(0,w):p[S];m.push(new Uint8Array(_))}else m.push(null);let C=!1;if(e._openGLRenderWindow.getWebgl2())C=e.openGLDataType===e.context.HALF_FLOAT;else{const S=e.context.getExtension("OES_texture_half_float");C=S&&e.openGLDataType===S.HALF_FLOAT_OES}if(C)for(let S=0;S=y&&(V=y-1);const G=M-L,A=1-G;L=L*v*m,V=V*v*m;for(let k=0;k=v&&(re=v-1);const ue=j-Y;Y*=m,re*=m;for(let ce=0;ce5&&arguments[5]!==void 0?arguments[5]:!1;if(t.getOpenGLDataType(y,!0),t.getInternalFormat(y,v),t.getFormat(y,v),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=v,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind();const x=[m],C=t.updateArrayDataTypeForGL(y,x),S=c(C);return e.context.pixelStorei(e.context.UNPACK_FLIP_Y_WEBGL,w),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),l(y)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),S[0]!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,S[0])):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,S[0]),e.generateMipmap&&e.context.generateMipmap(e.target),w&&e.context.pixelStorei(e.context.UNPACK_FLIP_Y_WEBGL,!1),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*v*e._openGLRenderWindow.getDefaultTextureByteSize(y,n(),t.useHalfFloat()),t.deactivate(),!0},t.createCubeFromRaw=(g,p,v,y,m)=>{if(t.getOpenGLDataType(y),t.getInternalFormat(y,v),t.getFormat(y,v),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_CUBE_MAP,e.components=v,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),e.maxLevel=m.length/6-1,t.createTexture(),t.bind();const w=t.updateArrayDataTypeForGL(y,m),x=c(w),C=[];let S=e.width,_=e.height;for(let T=0;T=1&&b>=1;){let I=null;E<=e.maxLevel&&(I=C[6*E+T]),l(y)?I!=null&&e.context.texSubImage2D(e.context.TEXTURE_CUBE_MAP_POSITIVE_X+T,E,0,0,D,b,e.format,e.openGLDataType,I):e.context.texImage2D(e.context.TEXTURE_CUBE_MAP_POSITIVE_X+T,E,e.internalFormat,D,b,0,e.format,e.openGLDataType,I),E++,D/=2,b/=2}}return e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*v*e._openGLRenderWindow.getDefaultTextureByteSize(y,n(),t.useHalfFloat()),t.deactivate(),!0},t.createDepthFromRaw=(g,p,v,y)=>(t.getOpenGLDataType(v),e.format=e.context.DEPTH_COMPONENT,e._openGLRenderWindow.getWebgl2()?v===Hn.FLOAT?e.internalFormat=e.context.DEPTH_COMPONENT32F:e.internalFormat=e.context.DEPTH_COMPONENT16:e.internalFormat=e.context.DEPTH_COMPONENT,!e.internalFormat||!e.format||!e.openGLDataType?(md("Failed to determine texture parameters."),!1):(e.target=e.context.TEXTURE_2D,e.components=1,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),l(v)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),y!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,y)):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,y),e.generateMipmap&&e.context.generateMipmap(e.target),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*e.components*e._openGLRenderWindow.getDefaultTextureByteSize(v,n(),t.useHalfFloat()),t.deactivate(),!0)),t.create2DFromImage=g=>{if(t.getOpenGLDataType(Hn.UNSIGNED_CHAR),t.getInternalFormat(Hn.UNSIGNED_CHAR,4),t.getFormat(Hn.UNSIGNED_CHAR,4),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=4,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1);const p=!e._openGLRenderWindow.getWebgl2()&&(!cg(g.width)||!cg(g.height)),v=document.createElement("canvas");v.width=p?Ul(g.width):g.width,v.height=p?Ul(g.height):g.height,e.width=v.width,e.height=v.height;const y=v.getContext("2d");y.translate(0,v.height),y.scale(1,-1),y.drawImage(g,0,0,g.width,g.height,0,0,v.width,v.height);const m=v;return l(Hn.UNSIGNED_CHAR)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),m!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,m)):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,m),e.generateMipmap&&e.context.generateMipmap(e.target),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*e.components*e._openGLRenderWindow.getDefaultTextureByteSize(Hn.UNSIGNED_CHAR,n(),t.useHalfFloat()),t.deactivate(),!0};function f(g,p,v){const y=new Array(v),m=new Array(v);for(let w=0;w2048||m<-2048||m>2048)return!1}return!0}function d(g,p,v,y){t.getOpenGLDataType(g);const m=u(p,v)||y;let w=!1;if(e._openGLRenderWindow.getWebgl2())w=e.openGLDataType===e.context.FLOAT&&e.context.getExtension("OES_texture_float_linear")===null&&m||e.openGLDataType===e.context.HALF_FLOAT;else{const x=e.context.getExtension("OES_texture_half_float");w=x&&e.openGLDataType===x.HALF_FLOAT_OES}e.canUseHalfFloat=w&&m}function h(g,p){const v=g.getNumberOfComponents(),y=g.getDataType(),m=g.getData(),w=new Array(v),x=new Array(v);for(let S=0;S5&&arguments[5]!==void 0?arguments[5]:!1,x=arguments.length>6&&arguments[6]!==void 0?arguments[6]:void 0;return t.create2DFilterableFromDataArray(g,p,Yt.newInstance({numberOfComponents:v,dataType:y,values:m,ranges:x}),w)},t.create2DFilterableFromDataArray=function(g,p,v){let y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const{numComps:m,dataType:w,data:x}=h(v,y);t.create2DFromRaw(g,p,m,w,x)},t.updateVolumeInfoForGL=(g,p)=>{var m,w;let v=!1;const y=t.useHalfFloat();(!((m=e.volumeInfo)!=null&&m.scale)||!((w=e.volumeInfo)!=null&&w.offset))&&(e.volumeInfo={scale:new Array(p),offset:new Array(p)});for(let x=0;x6&&arguments[6]!==void 0?arguments[6]:[],C=m,S=w;if(!t.updateVolumeInfoForGL(C,y)&&S){const P=g*p*v,M=structuredClone(e.volumeInfo),L=new Float32Array(P*y);e.volumeInfo.offset=M.offset,e.volumeInfo.scale=M.scale;let V=0;const G=M.scale.map(A=>1/A);for(let A=0;A0,T=!_||!n_(e._prevTexParams,r()),E=[S],b=t.updateArrayDataTypeForGL(C,E,!0,T?[]:x),I=c(b);if(e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),T)l(C)?(e.context.texStorage3D(e.target,1,e.internalFormat,e.width,e.height,e.depth),I[0]!=null&&e.context.texSubImage3D(e.target,0,0,0,0,e.width,e.height,e.depth,e.format,e.openGLDataType,I[0])):e.context.texImage3D(e.target,0,e.internalFormat,e.width,e.height,e.depth,0,e.format,e.openGLDataType,I[0]),e._prevTexParams=r();else if(_){const P=I[0];let M=0;for(let L=0;L6&&arguments[6]!==void 0?arguments[6]:!1,C=arguments.length>7&&arguments[7]!==void 0?arguments[7]:void 0,S=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[];return t.create3DFilterableFromDataArray(g,p,v,Yt.newInstance({numberOfComponents:y,dataType:m,values:w,ranges:C}),x,S)},t.create3DFilterableFromDataArray=function(g,p,v,y){let m=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,w=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];const{numComps:x,dataType:C,data:S,scaleOffsets:_}=h(y,m),T=[],E=[];for(let pe=0;pe{pe[Ee]=Oe},P=Hn.UNSIGNED_CHAR;if(C===Hn.UNSIGNED_CHAR)for(let pe=0;pe{pe[Ee]=(Oe-Se)/B}):(P=Hn.UNSIGNED_CHAR,I=(pe,Ee,Oe,Se,B)=>{pe[Ee]=255*(Oe-Se)/B});if(t.getOpenGLDataType(P),t.getInternalFormat(P,x),t.getFormat(P,x),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=x,e.depth=1,e.numberOfDimensions=2;let M=e.context.getParameter(e.context.MAX_TEXTURE_SIZE);M>4096&&(P===Hn.FLOAT||x>=3)&&(M=4096);let L=1,V=1;D>M*M&&(L=Math.ceil(Math.sqrt(D/(M*M))),V=L);let G=Math.sqrt(D)/L;G=Ul(G);const A=Math.floor(G*L/g),k=Math.ceil(v/A),F=Ul(p*k/V);e.width=G,e.height=F,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.volumeInfo.xreps=A,e.volumeInfo.yreps=k,e.volumeInfo.xstride=L,e.volumeInfo.ystride=V,e.volumeInfo.offset=b.offset,e.volumeInfo.scale=b.scale;let j;const Y=G*F*x;P===Hn.FLOAT?j=new Float32Array(Y):j=new Uint8Array(Y);let re=0;const ue=Math.floor(g/L),ce=Math.floor(p/V);for(let pe=0;pe{e._openGLRenderWindow!==g&&(t.releaseGraphicsResources(),e._openGLRenderWindow=g,e.context=null,g&&(e.context=e._openGLRenderWindow.getContext()))},t.getMaximumTextureSize=g=>g&&g.isCurrent()?g.getIntegerv(g.MAX_TEXTURE_SIZE):-1,t.enableUseHalfFloat=g=>{e.enableUseHalfFloat=g}}const PH={_openGLRenderWindow:null,_forceInternalFormat:!1,_prevTexParams:null,context:null,handle:0,sendParametersTime:null,textureBuildTime:null,numberOfDimensions:0,target:0,format:0,openGLDataType:0,components:0,width:0,height:0,depth:0,autoParameters:!0,wrapS:Ic.CLAMP_TO_EDGE,wrapT:Ic.CLAMP_TO_EDGE,wrapR:Ic.CLAMP_TO_EDGE,minificationFilter:bi.NEAREST,magnificationFilter:bi.NEAREST,minLOD:-1e3,maxLOD:1e3,baseLevel:0,maxLevel:1e3,generateMipmap:!1,oglNorm16Ext:null,allocatedGPUMemoryInBytes:0,enableUseHalfFloat:!0,canUseHalfFloat:!1};function mM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,PH,r),gi.extend(t,e,r),e.sendParametersTime={},br(e.sendParametersTime,{mtime:0}),e.textureBuildTime={},br(e.textureBuildTime,{mtime:0}),i1(t,e,["format","openGLDataType"]),Di(t,e,["keyMatrixTime","minificationFilter","magnificationFilter","wrapS","wrapT","wrapR","generateMipmap","oglNorm16Ext"]),Fo(t,e,["width","height","volumeInfo","components","handle","target","allocatedGPUMemoryInBytes"]),o1(t,e,["openGLRenderWindow"]),MH(t,e)}const vM=hr(mM,"vtkOpenGLTexture");var Dr={newInstance:vM,extend:mM,...UO};Ki("vtkTexture",vM);function RH(t,e){e.classHierarchy.push("vtkFramebuffer"),t.getBothMode=()=>e.context.FRAMEBUFFER,t.saveCurrentBindingsAndBuffers=r=>{const n=typeof r<"u"?r:t.getBothMode();t.saveCurrentBindings(n),t.saveCurrentBuffers(n)},t.saveCurrentBindings=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling saveCurrentBindings");return}const n=e.context;e.previousDrawBinding=n.getParameter(e.context.FRAMEBUFFER_BINDING),e.previousActiveFramebuffer=e._openGLRenderWindow.getActiveFramebuffer()},t.saveCurrentBuffers=r=>{},t.restorePreviousBindingsAndBuffers=r=>{const n=typeof r<"u"?r:t.getBothMode();t.restorePreviousBindings(n),t.restorePreviousBuffers(n)},t.restorePreviousBindings=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling restorePreviousBindings");return}const n=e.context;n.bindFramebuffer(n.FRAMEBUFFER,e.previousDrawBinding),e._openGLRenderWindow.setActiveFramebuffer(e.previousActiveFramebuffer)},t.restorePreviousBuffers=r=>{},t.bind=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;n===null&&(n=e.context.FRAMEBUFFER),e.context.bindFramebuffer(n,e.glFramebuffer);for(let i=0;i{if(!e.context){In("you must set the OpenGLRenderWindow before calling create");return}e.glFramebuffer=e.context.createFramebuffer(),e.glFramebuffer.width=r,e.glFramebuffer.height=n},t.setColorBuffer=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;const i=e.context;if(!i){In("you must set the OpenGLRenderWindow before calling setColorBuffer");return}let o=i.COLOR_ATTACHMENT0;if(n>0)if(e._openGLRenderWindow.getWebgl2())o+=n;else{In("Using multiple framebuffer attachments requires WebGL 2");return}e.colorBuffers[n]=r,i.framebufferTexture2D(i.FRAMEBUFFER,o,i.TEXTURE_2D,r.getHandle(),0)},t.removeColorBuffer=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;const n=e.context;if(!n){In("you must set the OpenGLRenderWindow before calling removeColorBuffer");return}let i=n.COLOR_ATTACHMENT0;if(r>0)if(e._openGLRenderWindow.getWebgl2())i+=r;else{In("Using multiple framebuffer attachments requires WebGL 2");return}n.framebufferTexture2D(n.FRAMEBUFFER,i,n.TEXTURE_2D,null,0),e.colorBuffers=e.colorBuffers.splice(r,1)},t.setDepthBuffer=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling setDepthBuffer");return}if(e._openGLRenderWindow.getWebgl2()){const n=e.context;n.framebufferTexture2D(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.TEXTURE_2D,r.getHandle(),0)}else In("Attaching depth buffer textures to fbo requires WebGL 2")},t.removeDepthBuffer=()=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling removeDepthBuffer");return}if(e._openGLRenderWindow.getWebgl2()){const r=e.context;r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,null,0)}else In("Attaching depth buffer textures to framebuffers requires WebGL 2")},t.getGLFramebuffer=()=>e.glFramebuffer,t.setOpenGLRenderWindow=r=>{e._openGLRenderWindow!==r&&(t.releaseGraphicsResources(),e._openGLRenderWindow=r,e.context=null,r&&(e.context=e._openGLRenderWindow.getContext()))},t.releaseGraphicsResources=()=>{e.glFramebuffer&&e.context.deleteFramebuffer(e.glFramebuffer)},t.getSize=()=>e.glFramebuffer==null?null:[e.glFramebuffer.width,e.glFramebuffer.height],t.populateFramebuffer=()=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling populateFrameBuffer");return}t.bind();const r=e.context,n=Dr.newInstance();n.setOpenGLRenderWindow(e._openGLRenderWindow),n.setMinificationFilter(Bt.LINEAR),n.setMagnificationFilter(Bt.LINEAR),n.create2DFromRaw(e.glFramebuffer.width,e.glFramebuffer.height,4,pn.UNSIGNED_CHAR,null),t.setColorBuffer(n),e.depthTexture=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,e.depthTexture),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,e.glFramebuffer.width,e.glFramebuffer.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e.depthTexture)},t.getColorTexture=()=>e.colorBuffers[0]}const LH={glFramebuffer:null,colorBuffers:null,depthTexture:null,previousDrawBinding:0,previousReadBinding:0,previousDrawBuffer:0,previousReadBuffer:0,previousActiveFramebuffer:null};function yM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,LH,r),br(t,e),e.colorBuffers&&In("you cannot initialize colorBuffers through the constructor. You should call setColorBuffer() instead."),e.colorBuffers=[],rh(t,e,["colorBuffers"]),RH(t,e)}const AH=hr(yM,"vtkFramebuffer");var zy={newInstance:AH,extend:yM};function NH(t,e){e.classHierarchy.push("vtkRenderPass"),t.getOperation=()=>e.currentOperation,t.setCurrentOperation=r=>{e.currentOperation=r,e.currentTraverseOperation=`traverse${ne.capitalize(e.currentOperation)}`},t.getTraverseOperation=()=>e.currentTraverseOperation,t.traverse=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;e.deleted||(e._currentParent=n,e.preDelegateOperations.forEach(i=>{t.setCurrentOperation(i),r.traverse(t)}),e.delegates.forEach(i=>{i.traverse(r,t)}),e.postDelegateOperations.forEach(i=>{t.setCurrentOperation(i),r.traverse(t)}))}}const kH={delegates:[],currentOperation:null,preDelegateOperations:[],postDelegateOperations:[],currentParent:null};function wM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,kH,r),ne.obj(t,e),ne.get(t,e,["currentOperation"]),ne.setGet(t,e,["delegates","_currentParent","preDelegateOperations","postDelegateOperations"]),ne.moveToProtected(t,e,["currentParent"]),NH(t,e)}const VH=ne.newInstance(wM,"vtkRenderPass");var T_={newInstance:VH,extend:wM},Wn=1e-6,Yr=typeof Float32Array<"u"?Float32Array:Array,FH=Math.PI/180;function UH(t){return t*FH}function vu(t,e){return Math.abs(t-e)<=Wn*Math.max(1,Math.abs(t),Math.abs(e))}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});function E_(){var t=new Yr(9);return Yr!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function $y(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t}function BH(t){var e=new Yr(9);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function GH(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function ug(t,e,r,n,i,o,a,s,c){var l=new Yr(9);return l[0]=t,l[1]=e,l[2]=r,l[3]=n,l[4]=i,l[5]=o,l[6]=a,l[7]=s,l[8]=c,l}function xM(t,e,r,n,i,o,a,s,c,l){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=o,t[5]=a,t[6]=s,t[7]=c,t[8]=l,t}function xs(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function D_(t,e){if(t===e){var r=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=r,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t}function u1(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=f*a-s*l,d=-f*o+s*c,h=l*o-a*c,g=r*u+n*d+i*h;return g?(g=1/g,t[0]=u*g,t[1]=(-f*n+i*l)*g,t[2]=(s*n-i*a)*g,t[3]=d*g,t[4]=(f*r-i*c)*g,t[5]=(-s*r+i*o)*g,t[6]=h*g,t[7]=(-l*r+n*c)*g,t[8]=(a*r-n*o)*g,t):null}function WH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8];return t[0]=a*f-s*l,t[1]=i*l-n*f,t[2]=n*s-i*a,t[3]=s*c-o*f,t[4]=r*f-i*c,t[5]=i*o-r*s,t[6]=o*l-a*c,t[7]=n*c-r*l,t[8]=r*a-n*o,t}function yf(t){var e=t[0],r=t[1],n=t[2],i=t[3],o=t[4],a=t[5],s=t[6],c=t[7],l=t[8];return e*(l*o-a*c)+r*(-l*i+a*s)+n*(c*i-o*s)}function A0(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=r[0],h=r[1],g=r[2],p=r[3],v=r[4],y=r[5],m=r[6],w=r[7],x=r[8];return t[0]=d*n+h*a+g*l,t[1]=d*i+h*s+g*f,t[2]=d*o+h*c+g*u,t[3]=p*n+v*a+y*l,t[4]=p*i+v*s+y*f,t[5]=p*o+v*c+y*u,t[6]=m*n+w*a+x*l,t[7]=m*i+w*s+x*f,t[8]=m*o+w*c+x*u,t}function zH(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=r[0],h=r[1];return t[0]=n,t[1]=i,t[2]=o,t[3]=a,t[4]=s,t[5]=c,t[6]=d*n+h*a+l,t[7]=d*i+h*s+f,t[8]=d*o+h*c+u,t}function $H(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=Math.sin(r),h=Math.cos(r);return t[0]=h*n+d*a,t[1]=h*i+d*s,t[2]=h*o+d*c,t[3]=h*a-d*n,t[4]=h*s-d*i,t[5]=h*c-d*o,t[6]=l,t[7]=f,t[8]=u,t}function jH(t,e,r){var n=r[0],i=r[1];return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=i*e[3],t[4]=i*e[4],t[5]=i*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function HH(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=e[0],t[7]=e[1],t[8]=1,t}function KH(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function qH(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=e[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function XH(t,e){return t[0]=e[0],t[1]=e[1],t[2]=0,t[3]=e[2],t[4]=e[3],t[5]=0,t[6]=e[4],t[7]=e[5],t[8]=1,t}function YH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=r+r,s=n+n,c=i+i,l=r*a,f=n*a,u=n*s,d=i*a,h=i*s,g=i*c,p=o*a,v=o*s,y=o*c;return t[0]=1-u-g,t[3]=f-y,t[6]=d+v,t[1]=f+y,t[4]=1-l-g,t[7]=h-p,t[2]=d-v,t[5]=h+p,t[8]=1-l-u,t}function JH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15],m=r*s-n*a,w=r*c-i*a,x=r*l-o*a,C=n*c-i*s,S=n*l-o*s,_=i*l-o*c,T=f*p-u*g,E=f*v-d*g,D=f*y-h*g,b=u*v-d*p,I=u*y-h*p,P=d*y-h*v,M=m*P-w*I+x*b+C*D-S*E+_*T;return M?(M=1/M,t[0]=(s*P-c*I+l*b)*M,t[1]=(c*D-a*P-l*E)*M,t[2]=(a*I-s*D+l*T)*M,t[3]=(i*I-n*P-o*b)*M,t[4]=(r*P-i*D+o*E)*M,t[5]=(n*D-r*I-o*T)*M,t[6]=(p*_-v*S+y*C)*M,t[7]=(v*x-g*_-y*w)*M,t[8]=(g*S-p*x+y*m)*M,t):null}function ZH(t,e,r){return t[0]=2/e,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function QH(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function eK(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])}function tK(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t}function CM(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t}function nK(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t}function rK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t}function iK(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]}function oK(t,e){var r=t[0],n=t[1],i=t[2],o=t[3],a=t[4],s=t[5],c=t[6],l=t[7],f=t[8],u=e[0],d=e[1],h=e[2],g=e[3],p=e[4],v=e[5],y=e[6],m=e[7],w=e[8];return Math.abs(r-u)<=Wn*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-d)<=Wn*Math.max(1,Math.abs(n),Math.abs(d))&&Math.abs(i-h)<=Wn*Math.max(1,Math.abs(i),Math.abs(h))&&Math.abs(o-g)<=Wn*Math.max(1,Math.abs(o),Math.abs(g))&&Math.abs(a-p)<=Wn*Math.max(1,Math.abs(a),Math.abs(p))&&Math.abs(s-v)<=Wn*Math.max(1,Math.abs(s),Math.abs(v))&&Math.abs(c-y)<=Wn*Math.max(1,Math.abs(c),Math.abs(y))&&Math.abs(l-m)<=Wn*Math.max(1,Math.abs(l),Math.abs(m))&&Math.abs(f-w)<=Wn*Math.max(1,Math.abs(f),Math.abs(w))}var aK=A0,sK=CM;const cK=Object.freeze(Object.defineProperty({__proto__:null,add:tK,adjoint:WH,clone:BH,copy:GH,create:E_,determinant:yf,equals:oK,exactEquals:iK,frob:eK,fromMat2d:XH,fromMat4:$y,fromQuat:YH,fromRotation:KH,fromScaling:qH,fromTranslation:HH,fromValues:ug,identity:xs,invert:u1,mul:aK,multiply:A0,multiplyScalar:nK,multiplyScalarAndAdd:rK,normalFromMat4:JH,projection:ZH,rotate:$H,scale:jH,set:xM,str:QH,sub:sK,subtract:CM,translate:zH,transpose:D_},Symbol.toStringTag,{value:"Module"}));function Zo(){var t=new Yr(16);return Yr!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function lK(t){var e=new Yr(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function ri(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function b_(t,e,r,n,i,o,a,s,c,l,f,u,d,h,g,p){var v=new Yr(16);return v[0]=t,v[1]=e,v[2]=r,v[3]=n,v[4]=i,v[5]=o,v[6]=a,v[7]=s,v[8]=c,v[9]=l,v[10]=f,v[11]=u,v[12]=d,v[13]=h,v[14]=g,v[15]=p,v}function uK(t,e,r,n,i,o,a,s,c,l,f,u,d,h,g,p,v){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=o,t[5]=a,t[6]=s,t[7]=c,t[8]=l,t[9]=f,t[10]=u,t[11]=d,t[12]=h,t[13]=g,t[14]=p,t[15]=v,t}function Vt(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Fn(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],o=e[6],a=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=o,t[11]=e[14],t[12]=i,t[13]=a,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function oi(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15],m=r*s-n*a,w=r*c-i*a,x=r*l-o*a,C=n*c-i*s,S=n*l-o*s,_=i*l-o*c,T=f*p-u*g,E=f*v-d*g,D=f*y-h*g,b=u*v-d*p,I=u*y-h*p,P=d*y-h*v,M=m*P-w*I+x*b+C*D-S*E+_*T;return M?(M=1/M,t[0]=(s*P-c*I+l*b)*M,t[1]=(i*I-n*P-o*b)*M,t[2]=(p*_-v*S+y*C)*M,t[3]=(d*S-u*_-h*C)*M,t[4]=(c*D-a*P-l*E)*M,t[5]=(r*P-i*D+o*E)*M,t[6]=(v*x-g*_-y*w)*M,t[7]=(f*_-d*x+h*w)*M,t[8]=(a*I-s*D+l*T)*M,t[9]=(n*D-r*I-o*T)*M,t[10]=(g*S-p*x+y*m)*M,t[11]=(u*x-f*S-h*m)*M,t[12]=(s*E-a*b-c*T)*M,t[13]=(r*b-n*E+i*T)*M,t[14]=(p*w-g*C-v*m)*M,t[15]=(f*C-u*w+d*m)*M,t):null}function fK(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15];return t[0]=s*(d*y-h*v)-u*(c*y-l*v)+p*(c*h-l*d),t[1]=-(n*(d*y-h*v)-u*(i*y-o*v)+p*(i*h-o*d)),t[2]=n*(c*y-l*v)-s*(i*y-o*v)+p*(i*l-o*c),t[3]=-(n*(c*h-l*d)-s*(i*h-o*d)+u*(i*l-o*c)),t[4]=-(a*(d*y-h*v)-f*(c*y-l*v)+g*(c*h-l*d)),t[5]=r*(d*y-h*v)-f*(i*y-o*v)+g*(i*h-o*d),t[6]=-(r*(c*y-l*v)-a*(i*y-o*v)+g*(i*l-o*c)),t[7]=r*(c*h-l*d)-a*(i*h-o*d)+f*(i*l-o*c),t[8]=a*(u*y-h*p)-f*(s*y-l*p)+g*(s*h-l*u),t[9]=-(r*(u*y-h*p)-f*(n*y-o*p)+g*(n*h-o*u)),t[10]=r*(s*y-l*p)-a*(n*y-o*p)+g*(n*l-o*s),t[11]=-(r*(s*h-l*u)-a*(n*h-o*u)+f*(n*l-o*s)),t[12]=-(a*(u*v-d*p)-f*(s*v-c*p)+g*(s*d-c*u)),t[13]=r*(u*v-d*p)-f*(n*v-i*p)+g*(n*d-i*u),t[14]=-(r*(s*v-c*p)-a*(n*v-i*p)+g*(n*c-i*s)),t[15]=r*(s*d-c*u)-a*(n*d-i*u)+f*(n*c-i*s),t}function dK(t){var e=t[0],r=t[1],n=t[2],i=t[3],o=t[4],a=t[5],s=t[6],c=t[7],l=t[8],f=t[9],u=t[10],d=t[11],h=t[12],g=t[13],p=t[14],v=t[15],y=e*a-r*o,m=e*s-n*o,w=e*c-i*o,x=r*s-n*a,C=r*c-i*a,S=n*c-i*s,_=l*g-f*h,T=l*p-u*h,E=l*v-d*h,D=f*p-u*g,b=f*v-d*g,I=u*v-d*p;return y*I-m*b+w*D+x*E-C*T+S*_}function On(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=e[9],h=e[10],g=e[11],p=e[12],v=e[13],y=e[14],m=e[15],w=r[0],x=r[1],C=r[2],S=r[3];return t[0]=w*n+x*s+C*u+S*p,t[1]=w*i+x*c+C*d+S*v,t[2]=w*o+x*l+C*h+S*y,t[3]=w*a+x*f+C*g+S*m,w=r[4],x=r[5],C=r[6],S=r[7],t[4]=w*n+x*s+C*u+S*p,t[5]=w*i+x*c+C*d+S*v,t[6]=w*o+x*l+C*h+S*y,t[7]=w*a+x*f+C*g+S*m,w=r[8],x=r[9],C=r[10],S=r[11],t[8]=w*n+x*s+C*u+S*p,t[9]=w*i+x*c+C*d+S*v,t[10]=w*o+x*l+C*h+S*y,t[11]=w*a+x*f+C*g+S*m,w=r[12],x=r[13],C=r[14],S=r[15],t[12]=w*n+x*s+C*u+S*p,t[13]=w*i+x*c+C*d+S*v,t[14]=w*o+x*l+C*h+S*y,t[15]=w*a+x*f+C*g+S*m,t}function Lr(t,e,r){var n=r[0],i=r[1],o=r[2],a,s,c,l,f,u,d,h,g,p,v,y;return e===t?(t[12]=e[0]*n+e[4]*i+e[8]*o+e[12],t[13]=e[1]*n+e[5]*i+e[9]*o+e[13],t[14]=e[2]*n+e[6]*i+e[10]*o+e[14],t[15]=e[3]*n+e[7]*i+e[11]*o+e[15]):(a=e[0],s=e[1],c=e[2],l=e[3],f=e[4],u=e[5],d=e[6],h=e[7],g=e[8],p=e[9],v=e[10],y=e[11],t[0]=a,t[1]=s,t[2]=c,t[3]=l,t[4]=f,t[5]=u,t[6]=d,t[7]=h,t[8]=g,t[9]=p,t[10]=v,t[11]=y,t[12]=a*n+f*i+g*o+e[12],t[13]=s*n+u*i+p*o+e[13],t[14]=c*n+d*i+v*o+e[14],t[15]=l*n+h*i+y*o+e[15]),t}function Qs(t,e,r){var n=r[0],i=r[1],o=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function go(t,e,r,n){var i=n[0],o=n[1],a=n[2],s=Math.hypot(i,o,a),c,l,f,u,d,h,g,p,v,y,m,w,x,C,S,_,T,E,D,b,I,P,M,L;return s0?(r[0]=(s*a+f*n+c*o-l*i)*2/u,r[1]=(c*a+f*i+l*n-s*o)*2/u,r[2]=(l*a+f*o+s*i-c*n)*2/u):(r[0]=(s*a+f*n+c*o-l*i)*2,r[1]=(c*a+f*i+l*n-s*o)*2,r[2]=(l*a+f*o+s*i-c*n)*2),SM(t,e,r),t}function vK(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function _M(t,e){var r=e[0],n=e[1],i=e[2],o=e[4],a=e[5],s=e[6],c=e[8],l=e[9],f=e[10];return t[0]=Math.hypot(r,n,i),t[1]=Math.hypot(o,a,s),t[2]=Math.hypot(c,l,f),t}function Ux(t,e){var r=new Yr(3);_M(r,e);var n=1/r[0],i=1/r[1],o=1/r[2],a=e[0]*n,s=e[1]*i,c=e[2]*o,l=e[4]*n,f=e[5]*i,u=e[6]*o,d=e[8]*n,h=e[9]*i,g=e[10]*o,p=a+f+g,v=0;return p>0?(v=Math.sqrt(p+1)*2,t[3]=.25*v,t[0]=(u-h)/v,t[1]=(d-c)/v,t[2]=(s-l)/v):a>f&&a>g?(v=Math.sqrt(1+a-f-g)*2,t[3]=(u-h)/v,t[0]=.25*v,t[1]=(s+l)/v,t[2]=(d+c)/v):f>g?(v=Math.sqrt(1+f-a-g)*2,t[3]=(d-c)/v,t[0]=(s+l)/v,t[1]=.25*v,t[2]=(u+h)/v):(v=Math.sqrt(1+g-a-f)*2,t[3]=(s-l)/v,t[0]=(d+c)/v,t[1]=(u+h)/v,t[2]=.25*v),t}function TM(t,e,r,n){var i=e[0],o=e[1],a=e[2],s=e[3],c=i+i,l=o+o,f=a+a,u=i*c,d=i*l,h=i*f,g=o*l,p=o*f,v=a*f,y=s*c,m=s*l,w=s*f,x=n[0],C=n[1],S=n[2];return t[0]=(1-(g+v))*x,t[1]=(d+w)*x,t[2]=(h-m)*x,t[3]=0,t[4]=(d-w)*C,t[5]=(1-(u+v))*C,t[6]=(p+y)*C,t[7]=0,t[8]=(h+m)*S,t[9]=(p-y)*S,t[10]=(1-(u+g))*S,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function yK(t,e,r,n,i){var o=e[0],a=e[1],s=e[2],c=e[3],l=o+o,f=a+a,u=s+s,d=o*l,h=o*f,g=o*u,p=a*f,v=a*u,y=s*u,m=c*l,w=c*f,x=c*u,C=n[0],S=n[1],_=n[2],T=i[0],E=i[1],D=i[2],b=(1-(p+y))*C,I=(h+x)*C,P=(g-w)*C,M=(h-x)*S,L=(1-(d+y))*S,V=(v+m)*S,G=(g+w)*_,A=(v-m)*_,k=(1-(d+p))*_;return t[0]=b,t[1]=I,t[2]=P,t[3]=0,t[4]=M,t[5]=L,t[6]=V,t[7]=0,t[8]=G,t[9]=A,t[10]=k,t[11]=0,t[12]=r[0]+T-(b*T+M*E+G*D),t[13]=r[1]+E-(I*T+L*E+A*D),t[14]=r[2]+D-(P*T+V*E+k*D),t[15]=1,t}function vv(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=r+r,s=n+n,c=i+i,l=r*a,f=n*a,u=n*s,d=i*a,h=i*s,g=i*c,p=o*a,v=o*s,y=o*c;return t[0]=1-u-g,t[1]=f+y,t[2]=d-v,t[3]=0,t[4]=f-y,t[5]=1-l-g,t[6]=h+p,t[7]=0,t[8]=d+v,t[9]=h-p,t[10]=1-l-u,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wK(t,e,r,n,i,o,a){var s=1/(r-e),c=1/(i-n),l=1/(o-a);return t[0]=o*2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*s,t[9]=(i+n)*c,t[10]=(a+o)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=a*o*2*l,t[15]=0,t}function EM(t,e,r,n,i){var o=1/Math.tan(e/2),a;return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0?(a=1/(n-i),t[10]=(i+n)*a,t[14]=2*i*n*a):(t[10]=-1,t[14]=-2*n),t}var xK=EM;function CK(t,e,r,n,i){var o=1/Math.tan(e/2),a;return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0?(a=1/(n-i),t[10]=i*a,t[14]=i*n*a):(t[10]=-1,t[14]=-n),t}function SK(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),o=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),s=Math.tan(e.rightDegrees*Math.PI/180),c=2/(a+s),l=2/(i+o);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((a-s)*c*.5),t[9]=(i-o)*l*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function DM(t,e,r,n,i,o,a){var s=1/(e-r),c=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=(a+o)*l,t[15]=1,t}var L_=DM;function _K(t,e,r,n,i,o,a){var s=1/(e-r),c=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=o*l,t[15]=1,t}function A_(t,e,r,n){var i,o,a,s,c,l,f,u,d,h,g=e[0],p=e[1],v=e[2],y=n[0],m=n[1],w=n[2],x=r[0],C=r[1],S=r[2];return Math.abs(g-x)0&&(h=1/Math.sqrt(h),f*=h,u*=h,d*=h);var g=c*d-l*u,p=l*f-s*d,v=s*u-c*f;return h=g*g+p*p+v*v,h>0&&(h=1/Math.sqrt(h),g*=h,p*=h,v*=h),t[0]=g,t[1]=p,t[2]=v,t[3]=0,t[4]=u*v-d*p,t[5]=d*g-f*v,t[6]=f*p-u*g,t[7]=0,t[8]=f,t[9]=u,t[10]=d,t[11]=0,t[12]=i,t[13]=o,t[14]=a,t[15]=1,t}function EK(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function DK(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function bK(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function bM(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function IM(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function IK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t}function OK(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function MK(t,e){var r=t[0],n=t[1],i=t[2],o=t[3],a=t[4],s=t[5],c=t[6],l=t[7],f=t[8],u=t[9],d=t[10],h=t[11],g=t[12],p=t[13],v=t[14],y=t[15],m=e[0],w=e[1],x=e[2],C=e[3],S=e[4],_=e[5],T=e[6],E=e[7],D=e[8],b=e[9],I=e[10],P=e[11],M=e[12],L=e[13],V=e[14],G=e[15];return Math.abs(r-m)<=Wn*Math.max(1,Math.abs(r),Math.abs(m))&&Math.abs(n-w)<=Wn*Math.max(1,Math.abs(n),Math.abs(w))&&Math.abs(i-x)<=Wn*Math.max(1,Math.abs(i),Math.abs(x))&&Math.abs(o-C)<=Wn*Math.max(1,Math.abs(o),Math.abs(C))&&Math.abs(a-S)<=Wn*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(s-_)<=Wn*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(c-T)<=Wn*Math.max(1,Math.abs(c),Math.abs(T))&&Math.abs(l-E)<=Wn*Math.max(1,Math.abs(l),Math.abs(E))&&Math.abs(f-D)<=Wn*Math.max(1,Math.abs(f),Math.abs(D))&&Math.abs(u-b)<=Wn*Math.max(1,Math.abs(u),Math.abs(b))&&Math.abs(d-I)<=Wn*Math.max(1,Math.abs(d),Math.abs(I))&&Math.abs(h-P)<=Wn*Math.max(1,Math.abs(h),Math.abs(P))&&Math.abs(g-M)<=Wn*Math.max(1,Math.abs(g),Math.abs(M))&&Math.abs(p-L)<=Wn*Math.max(1,Math.abs(p),Math.abs(L))&&Math.abs(v-V)<=Wn*Math.max(1,Math.abs(v),Math.abs(V))&&Math.abs(y-G)<=Wn*Math.max(1,Math.abs(y),Math.abs(G))}var yv=On,PK=bM;const wv=Object.freeze(Object.defineProperty({__proto__:null,add:bK,adjoint:fK,clone:lK,copy:ri,create:Zo,determinant:dK,equals:MK,exactEquals:OK,frob:DK,fromQuat:vv,fromQuat2:mK,fromRotation:R_,fromRotationTranslation:SM,fromRotationTranslationScale:TM,fromRotationTranslationScaleOrigin:yK,fromScaling:P_,fromTranslation:f1,fromValues:b_,fromXRotation:hK,fromYRotation:gK,fromZRotation:pK,frustum:wK,getRotation:Ux,getScaling:_M,getTranslation:vK,identity:Vt,invert:oi,lookAt:A_,mul:yv,multiply:On,multiplyScalar:IM,multiplyScalarAndAdd:IK,ortho:L_,orthoNO:DM,orthoZO:_K,perspective:xK,perspectiveFromFieldOfView:SK,perspectiveNO:EM,perspectiveZO:CK,rotate:go,rotateX:I_,rotateY:O_,rotateZ:M_,scale:Qs,set:uK,str:EK,sub:PK,subtract:bM,targetTo:TK,translate:Lr,transpose:Fn},Symbol.toStringTag,{value:"Module"}));function Ve(){var t=new Yr(3);return Yr!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function OM(t){var e=new Yr(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function Po(t){var e=t[0],r=t[1],n=t[2];return Math.hypot(e,r,n)}function bt(t,e,r){var n=new Yr(3);return n[0]=t,n[1]=e,n[2]=r,n}function RK(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function Yn(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t}function Ai(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function rr(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function LK(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function AK(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function NK(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function kK(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function VK(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t[2]=Math.round(e[2]),t}function Ni(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function Tn(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t}function ki(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.hypot(r,n,i)}function MM(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function Hs(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function PM(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function tr(t,e){var r=e[0],n=e[1],i=e[2],o=r*r+n*n+i*i;return o>0&&(o=1/Math.sqrt(o)),t[0]=e[0]*o,t[1]=e[1]*o,t[2]=e[2]*o,t}function Et(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Rn(t,e,r){var n=e[0],i=e[1],o=e[2],a=r[0],s=r[1],c=r[2];return t[0]=i*c-o*s,t[1]=o*a-n*c,t[2]=n*s-i*a,t}function Jt(t,e,r){var n=e[0],i=e[1],o=e[2],a=r[3]*n+r[7]*i+r[11]*o+r[15];return a=a||1,t[0]=(r[0]*n+r[4]*i+r[8]*o+r[12])/a,t[1]=(r[1]*n+r[5]*i+r[9]*o+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*o+r[14])/a,t}function m2(t,e,r){var n=e[0],i=e[1],o=e[2];return t[0]=n*r[0]+i*r[3]+o*r[6],t[1]=n*r[1]+i*r[4]+o*r[7],t[2]=n*r[2]+i*r[5]+o*r[8],t}function FK(t,e,r){var n=r[0],i=r[1],o=r[2],a=r[3],s=e[0],c=e[1],l=e[2],f=i*l-o*c,u=o*s-n*l,d=n*c-i*s,h=i*d-o*u,g=o*f-n*d,p=n*u-i*f,v=a*2;return f*=v,u*=v,d*=v,h*=2,g*=2,p*=2,t[0]=s+f+h,t[1]=c+u+g,t[2]=l+d+p,t}function N_(t,e){var r=t[0],n=t[1],i=t[2],o=e[0],a=e[1],s=e[2],c=Math.sqrt(r*r+n*n+i*i),l=Math.sqrt(o*o+a*a+s*s),f=c*l,u=f&&Et(t,e)/f;return Math.acos(Math.min(Math.max(u,-1),1))}function UK(t){return t[0]=0,t[1]=0,t[2]=0,t}function c6(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function Bx(t,e){var r=t[0],n=t[1],i=t[2],o=e[0],a=e[1],s=e[2];return Math.abs(r-o)<=Wn*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-a)<=Wn*Math.max(1,Math.abs(n),Math.abs(a))&&Math.abs(i-s)<=Wn*Math.max(1,Math.abs(i),Math.abs(s))}var En=rr,BK=LK,Gx=MM,N0=Po;(function(){var t=Ve();return function(e,r,n,i,o,a){var s,c;for(r||(r=3),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s0&&(a=1/Math.sqrt(a)),t[0]=r*a,t[1]=n*a,t[2]=i*a,t[3]=o*a,t}function u6(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Jl(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*o+r[12]*a,t[1]=r[1]*n+r[5]*i+r[9]*o+r[13]*a,t[2]=r[2]*n+r[6]*i+r[10]*o+r[14]*a,t[3]=r[3]*n+r[7]*i+r[11]*o+r[15]*a,t}(function(){var t=RM();return function(e,r,n,i,o,a){var s,c;for(r||(r=4),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;sWn?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function f6(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=r[0],c=r[1],l=r[2],f=r[3];return t[0]=n*f+a*s+i*l-o*c,t[1]=i*f+a*c+o*s-n*l,t[2]=o*f+a*l+n*c-i*s,t[3]=a*f-n*s-i*c-o*l,t}function y2(t,e,r,n){var i=e[0],o=e[1],a=e[2],s=e[3],c=r[0],l=r[1],f=r[2],u=r[3],d,h,g,p,v;return h=i*c+o*l+a*f+s*u,h<0&&(h=-h,c=-c,l=-l,f=-f,u=-u),1-h>Wn?(d=Math.acos(h),g=Math.sin(d),p=Math.sin((1-n)*d)/g,v=Math.sin(n*d)/g):(p=1-n,v=n),t[0]=p*i+v*c,t[1]=p*o+v*l,t[2]=p*a+v*f,t[3]=p*s+v*u,t}function zK(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t}function $K(t,e){var r=e[0]+e[4]+e[8],n;if(r>0)n=Math.sqrt(r+1),t[3]=.5*n,n=.5/n,t[0]=(e[5]-e[7])*n,t[1]=(e[6]-e[2])*n,t[2]=(e[1]-e[3])*n;else{var i=0;e[4]>e[0]&&(i=1),e[8]>e[i*3+i]&&(i=2);var o=(i+1)%3,a=(i+2)%3;n=Math.sqrt(e[i*3+i]-e[o*3+o]-e[a*3+a]+1),t[i]=.5*n,n=.5/n,t[3]=(e[o*3+a]-e[a*3+o])*n,t[o]=(e[o*3+i]+e[i*3+o])*n,t[a]=(e[a*3+i]+e[i*3+a])*n}return t}var d6=v2,LM=GK;(function(){var t=Ve(),e=bt(1,0,0),r=bt(0,1,0);return function(n,i,o){var a=Et(i,o);return a<-.999999?(Rn(t,e,i),N0(t)<1e-6&&Rn(t,r,i),tr(t,t),jy(n,t,Math.PI),n):a>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(Rn(t,i,o),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+a,LM(n,n))}})();(function(){var t=yu(),e=yu();return function(r,n,i,o,a,s){return y2(t,n,a,s),y2(e,i,o,s),y2(r,t,e,2*s*(1-s)),r}})();(function(){var t=E_();return function(e,r,n,i){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=i[0],t[4]=i[1],t[7]=i[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],LM(e,$K(e,t))}})();function qt(){var t=new Yr(2);return Yr!=Float32Array&&(t[0]=0,t[1]=0),t}function om(t){var e=new Yr(2);return e[0]=t[0],e[1]=t[1],e}function h6(t,e){var r=new Yr(2);return r[0]=t,r[1]=e,r}function Va(t,e,r){return t[0]=e,t[1]=r,t}function Qi(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t}function Wr(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function Oc(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t}function jK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t}function yr(t,e){var r=e[0]-t[0],n=e[1]-t[1];return Math.hypot(r,n)}function xv(t){var e=t[0],r=t[1];return Math.hypot(e,r)}function Nc(t,e){var r=e[0],n=e[1],i=r*r+n*n;return i>0&&(i=1/Math.sqrt(i)),t[0]=e[0]*i,t[1]=e[1]*i,t}function k_(t,e){return t[0]*e[0]+t[1]*e[1]}function HK(t,e,r,n){var i=e[0]-r[0],o=e[1]-r[1],a=Math.sin(n),s=Math.cos(n);return t[0]=i*s-o*a+r[0],t[1]=i*a+o*s+r[1],t}function KK(t,e){var r=t[0],n=t[1],i=e[0],o=e[1],a=Math.sqrt(r*r+n*n)*Math.sqrt(i*i+o*o),s=a&&(r*i+n*o)/a;return Math.acos(Math.min(Math.max(s,-1),1))}var qK=xv,Ga=Wr,V_=yr;(function(){var t=qt();return function(e,r,n,i,o,a){var s,c;for(r||(r=2),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;sn,t.setType=s=>{n=s},t.getHandle=()=>i,t.isReady=()=>o===!1,t.generateBuffer=s=>{const c=r(s);return i===null&&(i=e.context.createBuffer(),n=s),r(n)===c},t.upload=(s,c)=>t.generateBuffer(c)?(e.context.bindBuffer(r(n),i),e.context.bufferData(r(n),s,e.context.STATIC_DRAW),e.allocatedGPUMemoryInBytes=s.length*s.BYTES_PER_ELEMENT,o=!1,!0):(a="Trying to upload array buffer to incompatible buffer.",!1),t.bind=()=>i?(e.context.bindBuffer(r(n),i),!0):!1,t.release=()=>i?(e.context.bindBuffer(r(n),null),!0):!1,t.releaseGraphicsResources=()=>{i!==null&&(e.context.bindBuffer(r(n),null),e.context.deleteBuffer(i),i=null,e.allocatedGPUMemoryInBytes=0)},t.setOpenGLRenderWindow=s=>{e._openGLRenderWindow!==s&&(t.releaseGraphicsResources(),e._openGLRenderWindow=s,e.context=null,s&&(e.context=e._openGLRenderWindow.getContext()))},t.getError=()=>a}const JK={objectType:w2.ARRAY_BUFFER,context:null,allocatedGPUMemoryInBytes:0};function NM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,JK,r),ne.obj(t,e),ne.get(t,e,["_openGLRenderWindow","allocatedGPUMemoryInBytes"]),ne.moveToProtected(t,e,["openGLRenderWindow"]),YK(t,e)}const ZK=ne.newInstance(NM);var kc={newInstance:ZK,extend:NM,...XK,...AM};const kM={FLAT:0,GOURAUD:1,PHONG:2},Wa={POINTS:0,WIREFRAME:1,SURFACE:2},QK=kM;var VM={Shading:kM,Representation:Wa,Interpolation:QK};const{vtkErrorMacro:g6}=ne;function eq(t,e){const r=new Float64Array(3);PM(r,e);const n=new Float64Array(16);return TM(n,yu(),t,r),n}function tq(t,e){return t===null||e===null?!1:!(c6(t,[0,0,0])&&c6(e,[1,1,1]))}function nq(t,e){e.classHierarchy.push("vtkOpenGLCellArrayBufferObject"),t.setType(Bc.ARRAY_BUFFER),t.createVBO=function(r,n,i,o){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;if(!r.getData()||!r.getData().length)return e.elementCount=0,0;e.blockSize=3,e.vertexOffset=0,e.normalOffset=0,e.tCoordOffset=0,e.tCoordComponents=0,e.colorComponents=0,e.colorOffset=0,e.customData=[];const s=o.points.getData();let c=null,l=null,f=null;const u=o.colors?o.colors.getNumberOfComponents():0,d=o.tcoords?o.tcoords.getNumberOfComponents():0;o.normals&&(e.normalOffset=4*e.blockSize,e.blockSize+=3,c=o.normals.getData()),o.customAttributes&&o.customAttributes.forEach(k=>{k&&(e.customData.push({data:k.getData(),offset:4*e.blockSize,components:k.getNumberOfComponents(),name:k.getName()}),e.blockSize+=k.getNumberOfComponents())}),o.tcoords&&(e.tCoordOffset=4*e.blockSize,e.tCoordComponents=d,e.blockSize+=d,l=o.tcoords.getData()),o.colors?(e.colorComponents=o.colors.getNumberOfComponents(),e.colorOffset=0,f=o.colors.getData(),e.colorBO||(e.colorBO=kc.newInstance()),e.colorBO.setOpenGLRenderWindow(e._openGLRenderWindow)):e.colorBO=null,e.stride=4*e.blockSize;let h=0,g=0,p=0,v=0,y=0,m=0,w;const x={anythingToPoints(k,F,j,Y){for(let re=0;re2)for(let re=0;re2){for(let re=0;re1?(k-1)*2:0},polysToWireframe(k,F){return k>2?k*2:0},stripsToWireframe(k,F){return k>2?k*4-6:0},polysToSurface(k,F){return k>2?(k-2)*3:0},stripsToSurface(k,F,j){return k>2?(k-2)*3:0}};let S=null,_=null;i===Wa.POINTS||n==="verts"?(S=x.anythingToPoints,_=C.anythingToPoints):i===Wa.WIREFRAME||n==="lines"?(S=x[`${n}ToWireframe`],_=C[`${n}ToWireframe`]):(S=x[`${n}ToSurface`],_=C[`${n}ToSurface`]);const T=r.getData(),E=T.length;let D=0;for(let k=0;k0&&(Math.abs(V)/L>1e6||Math.abs(Math.log10(L))>3||L===0&&V>1e6)){const k=new Float64Array(3),F=new Float64Array(3);for(let j=0;j<3;++j){const Y=o.points.getRange(j),re=Y[1]-Y[0];k[j]=.5*(Y[1]+Y[0]),F[j]=re>0?1/re:1}t.setCoordShiftAndScale(k,F)}else e.coordShiftAndScaleEnabled===!0&&t.setCoordShiftAndScale(null,null);if(a)if(!a.points&&!a.cells)a.points=new Int32Array(D),a.cells=new Int32Array(D);else{const k=new Int32Array(D+a.points.length);k.set(a.points),a.points=k;const F=new Int32Array(D+a.cells.length);F.set(a.cells),a.cells=F}let A=o.vertexOffset;w=function(F,j){if(a&&(a.points[A]=F,a.cells[A]=m+o.cellOffset),++A,h=F*3,e.coordShiftAndScaleEnabled?(I[P++]=(s[h++]-e.coordShift[0])*e.coordScale[0],I[P++]=(s[h++]-e.coordShift[1])*e.coordScale[1],I[P++]=(s[h++]-e.coordShift[2])*e.coordScale[2]):(I[P++]=s[h++],I[P++]=s[h++],I[P++]=s[h++]),c!==null&&(o.haveCellNormals?g=(m+o.cellOffset)*3:g=F*3,I[P++]=c[g++],I[P++]=c[g++],I[P++]=c[g++]),e.customData.forEach(Y=>{y=F*Y.components;for(let re=0;re{if(r!==null&&(r.constructor!==Float64Array||r.length!==3)){g6("Wrong type for coordShift, expected vec3 or null");return}if(n!==null&&(n.constructor!==Float64Array||n.length!==3)){g6("Wrong type for coordScale, expected vec3 or null");return}(e.coordShift===null||r===null||!Bx(r,e.coordShift))&&(e.coordShift=r),(e.coordScale===null||n===null||!Bx(n,e.coordScale))&&(e.coordScale=n),e.coordShiftAndScaleEnabled=tq(e.coordShift,e.coordScale),e.coordShiftAndScaleEnabled?e.inverseShiftAndScaleMatrix=eq(e.coordShift,e.coordScale):e.inverseShiftAndScaleMatrix=null}}const rq={elementCount:0,stride:0,colorBOStride:0,vertexOffset:0,normalOffset:0,tCoordOffset:0,tCoordComponents:0,colorOffset:0,colorComponents:0,tcoordBO:null,customData:[],coordShift:null,coordScale:null,coordShiftAndScaleEnabled:!1,inverseShiftAndScaleMatrix:null};function FM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,rq,r),kc.extend(t,e,r),ne.setGet(t,e,["colorBO","elementCount","stride","colorBOStride","vertexOffset","normalOffset","tCoordOffset","tCoordComponents","colorOffset","colorComponents","customData"]),ne.get(t,e,["coordShift","coordScale","coordShiftAndScaleEnabled","inverseShiftAndScaleMatrix"]),nq(t,e)}const iq=ne.newInstance(FM);var oq={newInstance:iq,extend:FM};const{vtkErrorMacro:aq}=ne;function sq(t,e){e.classHierarchy.push("vtkShader"),t.compile=()=>{let r=e.context.VERTEX_SHADER;if(!e.source||!e.source.length||e.shaderType==="Unknown")return!1;switch(e.handle!==0&&(e.context.deleteShader(e.handle),e.handle=0),e.shaderType){case"Fragment":r=e.context.FRAGMENT_SHADER;break;case"Vertex":default:r=e.context.VERTEX_SHADER;break}if(e.handle=e.context.createShader(r),e.context.shaderSource(e.handle,e.source),e.context.compileShader(e.handle),!e.context.getShaderParameter(e.handle,e.context.COMPILE_STATUS)){const i=e.context.getShaderInfoLog(e.handle);return aq(`Error compiling shader '${e.source}': ${i}`),e.context.deleteShader(e.handle),e.handle=0,!1}return!0},t.cleanup=()=>{e.shaderType==="Unknown"||e.handle===0||(e.context.deleteShader(e.handle),e.handle=0,e.dirty=!0)}}const cq={shaderType:"Unknown",source:"",error:"",handle:0,dirty:!1,context:null};function UM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,cq,r),ne.obj(t,e),ne.setGet(t,e,["shaderType","source","error","handle","context"]),sq(t,e)}const lq=ne.newInstance(UM,"vtkShader");var Iw={newInstance:lq,extend:UM};const{vtkErrorMacro:Ms}=ne;function uq(t,e,r,n){const i=typeof r=="string"?r:r.join(` + `,f=a.createShader(a.VERTEX_SHADER);if(a.shaderSource(f,c),a.compileShader(f),!a.getShaderParameter(f,a.COMPILE_STATUS))return!1;const u=a.createShader(a.FRAGMENT_SHADER);if(a.shaderSource(u,l),a.compileShader(u),!a.getShaderParameter(u,a.COMPILE_STATUS))return!1;const d=a.createProgram();if(a.attachShader(d,f),a.attachShader(d,u),a.linkProgram(d),!a.getProgramParameter(d,a.LINK_STATUS))return!1;const h=a.createTexture();a.bindTexture(a.TEXTURE_2D,h),a.texImage2D(a.TEXTURE_2D,0,s.R16_SNORM_EXT,2,1,0,a.RED,a.SHORT,n),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.useProgram(d),a.drawArrays(a.POINTS,0,1);const g=new Uint8Array(4);a.readPixels(i[0],i[1],1,1,a.RGBA,a.UNSIGNED_BYTE,g);const[p,v,y]=g,m=a.getExtension("WEBGL_lose_context");return m&&m.loseContext(),p===v&&v===y&&p!==0}catch{return!1}}let Dw;function IH(){return Dw===void 0&&(Dw=bH()),Dw}const{Wrap:Ic,Filter:bi}=UO,{VtkDataTypes:Hn}=Yt,{vtkDebugMacro:bw,vtkErrorMacro:md,vtkWarningMacro:s6}=So,{toHalf:OH}=Od;function MH(t,e){e.classHierarchy.push("vtkOpenGLTexture");function r(){return{internalFormat:e.internalFormat,format:e.format,openGLDataType:e.openGLDataType,width:e.width,height:e.height}}t.render=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;if(g?e._openGLRenderWindow=g:(e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow")),e.context=e._openGLRenderWindow.getContext(),e.renderable.getInterpolate()?(e.generateMipmap?t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR):t.setMinificationFilter(bi.LINEAR),t.setMagnificationFilter(bi.LINEAR)):(t.setMinificationFilter(bi.NEAREST),t.setMagnificationFilter(bi.NEAREST)),e.renderable.getRepeat()&&(t.setWrapR(Ic.REPEAT),t.setWrapS(Ic.REPEAT),t.setWrapT(Ic.REPEAT)),e.renderable.getInputData()&&e.renderable.setImage(null),!e.handle||e.renderable.getMTime()>e.textureBuildTime.getMTime()){if(e.renderable.getImage()!==null&&(e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR)),e.renderable.getImage()&&e.renderable.getImageLoaded()&&(t.create2DFromImage(e.renderable.getImage()),t.activate(),t.sendParameters(),e.textureBuildTime.modified())),e.renderable.getCanvas()!==null){e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR));const v=e.renderable.getCanvas();t.create2DFromRaw(v.width,v.height,4,Hn.UNSIGNED_CHAR,v,!0),t.activate(),t.sendParameters(),e.textureBuildTime.modified()}if(e.renderable.getJsImageData()!==null){const v=e.renderable.getJsImageData();e.renderable.getInterpolate()&&(e.generateMipmap=!0,t.setMinificationFilter(bi.LINEAR_MIPMAP_LINEAR)),t.create2DFromRaw(v.width,v.height,4,Hn.UNSIGNED_CHAR,v.data,!0),t.activate(),t.sendParameters(),e.textureBuildTime.modified()}const p=e.renderable.getInputData(0);if(p&&p.getPointData().getScalars()){const v=p.getExtent(),y=p.getPointData().getScalars(),m=[];for(let w=0;w{if(!((e.minificationFilter===bi.LINEAR||e.magnificationFilter===bi.LINEAR)&&!IH()))return e.oglNorm16Ext};t.destroyTexture=()=>{t.deactivate(),e.context&&e.handle&&e.context.deleteTexture(e.handle),e._prevTexParams=null,e.handle=0,e.numberOfDimensions=0,e.target=0,e.components=0,e.width=0,e.height=0,e.depth=0,t.resetFormatAndType()},t.createTexture=()=>{e.handle||(e.handle=e.context.createTexture(),e.target&&(e.context.bindTexture(e.target,e.handle),e.context.texParameteri(e.target,e.context.TEXTURE_MIN_FILTER,t.getOpenGLFilterMode(e.minificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_MAG_FILTER,t.getOpenGLFilterMode(e.magnificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_S,t.getOpenGLWrapMode(e.wrapS)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_T,t.getOpenGLWrapMode(e.wrapT)),e._openGLRenderWindow.getWebgl2()&&e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_R,t.getOpenGLWrapMode(e.wrapR)),e.context.bindTexture(e.target,null)))},t.getTextureUnit=()=>e._openGLRenderWindow?e._openGLRenderWindow.getTextureUnitForTexture(t):-1,t.activate=()=>{e._openGLRenderWindow.activateTexture(t),t.bind()},t.deactivate=()=>{e._openGLRenderWindow&&e._openGLRenderWindow.deactivateTexture(t)},t.releaseGraphicsResources=g=>{g&&e.handle&&(g.activateTexture(t),g.deactivateTexture(t),e.context.deleteTexture(e.handle),e._prevTexParams=null,e.handle=0,e.numberOfDimensions=0,e.target=0,e.internalFormat=0,e.format=0,e.openGLDataType=0,e.components=0,e.width=0,e.height=0,e.depth=0,e.allocatedGPUMemoryInBytes=0),e.shaderProgram&&(e.shaderProgram.releaseGraphicsResources(g),e.shaderProgram=null)},t.bind=()=>{e.context.bindTexture(e.target,e.handle),e.autoParameters&&t.getMTime()>e.sendParametersTime.getMTime()&&t.sendParameters()},t.isBound=()=>{let g=!1;if(e.context&&e.handle){let p=0;switch(e.target){case e.context.TEXTURE_2D:p=e.context.TEXTURE_BINDING_2D;break;default:s6("impossible case");break}g=e.context.getIntegerv(p)===e.handle}return g},t.sendParameters=()=>{e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_S,t.getOpenGLWrapMode(e.wrapS)),e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_T,t.getOpenGLWrapMode(e.wrapT)),e._openGLRenderWindow.getWebgl2()&&e.context.texParameteri(e.target,e.context.TEXTURE_WRAP_R,t.getOpenGLWrapMode(e.wrapR)),e.context.texParameteri(e.target,e.context.TEXTURE_MIN_FILTER,t.getOpenGLFilterMode(e.minificationFilter)),e.context.texParameteri(e.target,e.context.TEXTURE_MAG_FILTER,t.getOpenGLFilterMode(e.magnificationFilter)),e._openGLRenderWindow.getWebgl2()&&(e.context.texParameteri(e.target,e.context.TEXTURE_BASE_LEVEL,e.baseLevel),e.context.texParameteri(e.target,e.context.TEXTURE_MAX_LEVEL,e.maxLevel)),e.sendParametersTime.modified()},t.getInternalFormat=(g,p)=>(e._forceInternalFormat||(e.internalFormat=t.getDefaultInternalFormat(g,p)),e.internalFormat||bw(`Unable to find suitable internal format for T=${g} NC= ${p}`),[e.context.R32F,e.context.RG32F,e.context.RGB32F,e.context.RGBA32F].includes(e.internalFormat)&&!e.context.getExtension("OES_texture_float_linear")&&s6("Failed to load OES_texture_float_linear. Texture filtering is not available for *32F internal formats."),e.internalFormat),t.getDefaultInternalFormat=(g,p)=>{let v=0;return v=e._openGLRenderWindow.getDefaultTextureInternalFormat(g,p,n(),t.useHalfFloat()),v||(v||(bw("Unsupported internal texture type!"),bw(`Unable to find suitable internal format for T=${g} NC= ${p}`)),v)},t.useHalfFloat=()=>e.enableUseHalfFloat&&e.canUseHalfFloat,t.setInternalFormat=g=>{e._forceInternalFormat=!0,g!==e.internalFormat&&(e.internalFormat=g,t.modified())},t.getFormat=(g,p)=>(e.format=t.getDefaultFormat(g,p),e.format),t.getDefaultFormat=(g,p)=>{if(e._openGLRenderWindow.getWebgl2())switch(p){case 1:return e.context.RED;case 2:return e.context.RG;case 3:return e.context.RGB;case 4:return e.context.RGBA;default:return e.context.RGB}else switch(p){case 1:return e.context.LUMINANCE;case 2:return e.context.LUMINANCE_ALPHA;case 3:return e.context.RGB;case 4:return e.context.RGBA;default:return e.context.RGB}},t.resetFormatAndType=()=>{e._prevTexParams=null,e.format=0,e.internalFormat=0,e._forceInternalFormat=!1,e.openGLDataType=0},t.getDefaultDataType=g=>{const p=t.useHalfFloat();if(e._openGLRenderWindow.getWebgl2())switch(g){case Hn.UNSIGNED_CHAR:return e.context.UNSIGNED_BYTE;case(n()&&!p&&Hn.SHORT):return e.context.SHORT;case(n()&&!p&&Hn.UNSIGNED_SHORT):return e.context.UNSIGNED_SHORT;case(p&&Hn.SHORT):return e.context.HALF_FLOAT;case(p&&Hn.UNSIGNED_SHORT):return e.context.HALF_FLOAT;case Hn.FLOAT:case Hn.VOID:default:return e.context.FLOAT}switch(g){case Hn.UNSIGNED_CHAR:return e.context.UNSIGNED_BYTE;case Hn.FLOAT:case Hn.VOID:default:if(e.context.getExtension("OES_texture_float")&&e.context.getExtension("OES_texture_float_linear"))return e.context.FLOAT;{const v=e.context.getExtension("OES_texture_half_float");if(v&&e.context.getExtension("OES_texture_half_float_linear"))return v.HALF_FLOAT_OES}return e.context.UNSIGNED_BYTE}},t.getOpenGLDataType=function(g){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(!e.openGLDataType||p)&&(e.openGLDataType=t.getDefaultDataType(g)),e.openGLDataType},t.getShiftAndScale=()=>{let g=0,p=1;switch(e.openGLDataType){case e.context.BYTE:p=127.5,g=p-128;break;case e.context.UNSIGNED_BYTE:p=255,g=0;break;case e.context.SHORT:p=32767.5,g=p-32768;break;case e.context.UNSIGNED_SHORT:p=65536,g=0;break;case e.context.INT:p=21474836475e-1,g=p-2147483648;break;case e.context.UNSIGNED_INT:p=4294967295,g=0;break;case e.context.FLOAT:}return{shift:g,scale:p}},t.getOpenGLFilterMode=g=>{switch(g){case bi.NEAREST:return e.context.NEAREST;case bi.LINEAR:return e.context.LINEAR;case bi.NEAREST_MIPMAP_NEAREST:return e.context.NEAREST_MIPMAP_NEAREST;case bi.NEAREST_MIPMAP_LINEAR:return e.context.NEAREST_MIPMAP_LINEAR;case bi.LINEAR_MIPMAP_NEAREST:return e.context.LINEAR_MIPMAP_NEAREST;case bi.LINEAR_MIPMAP_LINEAR:return e.context.LINEAR_MIPMAP_LINEAR;default:return e.context.NEAREST}},t.getOpenGLWrapMode=g=>{switch(g){case Ic.CLAMP_TO_EDGE:return e.context.CLAMP_TO_EDGE;case Ic.REPEAT:return e.context.REPEAT;case Ic.MIRRORED_REPEAT:return e.context.MIRRORED_REPEAT;default:return e.context.CLAMP_TO_EDGE}};function i(g){const[p,v,y,m,w,x]=g;return[v-p+1,m-y+1,x-w+1]}function o(g){const[p,v,y]=i(g);return p*v*y}function a(g,p,v,y,m){const[w,x,C,S,_,T]=v,[E,D]=p,b=E*D;let I=m;for(let P=_;P<=T;P++){const M=P*b;for(let L=C;L<=S;L++){const V=M+L*E;for(let G=V+w,A=V+x;G<=A;G++,I++)y[I]=g[G]}}}function s(g,p){const y=(arguments.length>2&&arguments[2]!==void 0?arguments[2]:null)||g.constructor,m=p.reduce((S,_)=>S+o(_),0),w=new y(m),x=[e.width,e.height,e.depth];let C=0;return p.forEach(S=>{a(g,x,S,w,C),C+=o(S)}),w}t.updateArrayDataTypeForGL=function(g,p){let v=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:[];const m=[];let w=e.width*e.height*e.components;v&&(w*=e.depth);const x=!!y.length;if(g!==Hn.FLOAT&&e.openGLDataType===e.context.FLOAT)for(let S=0;Sw?p[S].subarray(0,w):p[S];m.push(new Float32Array(_))}else m.push(null);if(g!==Hn.UNSIGNED_CHAR&&e.openGLDataType===e.context.UNSIGNED_BYTE)for(let S=0;Sw?p[S].subarray(0,w):p[S];m.push(new Uint8Array(_))}else m.push(null);let C=!1;if(e._openGLRenderWindow.getWebgl2())C=e.openGLDataType===e.context.HALF_FLOAT;else{const S=e.context.getExtension("OES_texture_half_float");C=S&&e.openGLDataType===S.HALF_FLOAT_OES}if(C)for(let S=0;S=y&&(V=y-1);const G=M-L,A=1-G;L=L*v*m,V=V*v*m;for(let k=0;k=v&&(re=v-1);const ue=j-Y;Y*=m,re*=m;for(let ce=0;ce5&&arguments[5]!==void 0?arguments[5]:!1;if(t.getOpenGLDataType(y,!0),t.getInternalFormat(y,v),t.getFormat(y,v),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=v,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind();const x=[m],C=t.updateArrayDataTypeForGL(y,x),S=c(C);return e.context.pixelStorei(e.context.UNPACK_FLIP_Y_WEBGL,w),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),l(y)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),S[0]!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,S[0])):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,S[0]),e.generateMipmap&&e.context.generateMipmap(e.target),w&&e.context.pixelStorei(e.context.UNPACK_FLIP_Y_WEBGL,!1),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*v*e._openGLRenderWindow.getDefaultTextureByteSize(y,n(),t.useHalfFloat()),t.deactivate(),!0},t.createCubeFromRaw=(g,p,v,y,m)=>{if(t.getOpenGLDataType(y),t.getInternalFormat(y,v),t.getFormat(y,v),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_CUBE_MAP,e.components=v,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),e.maxLevel=m.length/6-1,t.createTexture(),t.bind();const w=t.updateArrayDataTypeForGL(y,m),x=c(w),C=[];let S=e.width,_=e.height;for(let T=0;T=1&&b>=1;){let I=null;E<=e.maxLevel&&(I=C[6*E+T]),l(y)?I!=null&&e.context.texSubImage2D(e.context.TEXTURE_CUBE_MAP_POSITIVE_X+T,E,0,0,D,b,e.format,e.openGLDataType,I):e.context.texImage2D(e.context.TEXTURE_CUBE_MAP_POSITIVE_X+T,E,e.internalFormat,D,b,0,e.format,e.openGLDataType,I),E++,D/=2,b/=2}}return e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*v*e._openGLRenderWindow.getDefaultTextureByteSize(y,n(),t.useHalfFloat()),t.deactivate(),!0},t.createDepthFromRaw=(g,p,v,y)=>(t.getOpenGLDataType(v),e.format=e.context.DEPTH_COMPONENT,e._openGLRenderWindow.getWebgl2()?v===Hn.FLOAT?e.internalFormat=e.context.DEPTH_COMPONENT32F:e.internalFormat=e.context.DEPTH_COMPONENT16:e.internalFormat=e.context.DEPTH_COMPONENT,!e.internalFormat||!e.format||!e.openGLDataType?(md("Failed to determine texture parameters."),!1):(e.target=e.context.TEXTURE_2D,e.components=1,e.width=g,e.height=p,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),l(v)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),y!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,y)):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,y),e.generateMipmap&&e.context.generateMipmap(e.target),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*e.components*e._openGLRenderWindow.getDefaultTextureByteSize(v,n(),t.useHalfFloat()),t.deactivate(),!0)),t.create2DFromImage=g=>{if(t.getOpenGLDataType(Hn.UNSIGNED_CHAR),t.getInternalFormat(Hn.UNSIGNED_CHAR,4),t.getFormat(Hn.UNSIGNED_CHAR,4),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=4,e.depth=1,e.numberOfDimensions=2,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1);const p=!e._openGLRenderWindow.getWebgl2()&&(!cg(g.width)||!cg(g.height)),v=document.createElement("canvas");v.width=p?Ul(g.width):g.width,v.height=p?Ul(g.height):g.height,e.width=v.width,e.height=v.height;const y=v.getContext("2d");y.translate(0,v.height),y.scale(1,-1),y.drawImage(g,0,0,g.width,g.height,0,0,v.width,v.height);const m=v;return l(Hn.UNSIGNED_CHAR)?(e.context.texStorage2D(e.target,1,e.internalFormat,e.width,e.height),m!=null&&e.context.texSubImage2D(e.target,0,0,0,e.width,e.height,e.format,e.openGLDataType,m)):e.context.texImage2D(e.target,0,e.internalFormat,e.width,e.height,0,e.format,e.openGLDataType,m),e.generateMipmap&&e.context.generateMipmap(e.target),e.allocatedGPUMemoryInBytes=e.width*e.height*e.depth*e.components*e._openGLRenderWindow.getDefaultTextureByteSize(Hn.UNSIGNED_CHAR,n(),t.useHalfFloat()),t.deactivate(),!0};function f(g,p,v){const y=new Array(v),m=new Array(v);for(let w=0;w2048||m<-2048||m>2048)return!1}return!0}function d(g,p,v,y){t.getOpenGLDataType(g);const m=u(p,v)||y;let w=!1;if(e._openGLRenderWindow.getWebgl2())w=e.openGLDataType===e.context.FLOAT&&e.context.getExtension("OES_texture_float_linear")===null&&m||e.openGLDataType===e.context.HALF_FLOAT;else{const x=e.context.getExtension("OES_texture_half_float");w=x&&e.openGLDataType===x.HALF_FLOAT_OES}e.canUseHalfFloat=w&&m}function h(g,p){const v=g.getNumberOfComponents(),y=g.getDataType(),m=g.getData(),w=new Array(v),x=new Array(v);for(let S=0;S5&&arguments[5]!==void 0?arguments[5]:!1,x=arguments.length>6&&arguments[6]!==void 0?arguments[6]:void 0;return t.create2DFilterableFromDataArray(g,p,Yt.newInstance({numberOfComponents:v,dataType:y,values:m,ranges:x}),w)},t.create2DFilterableFromDataArray=function(g,p,v){let y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const{numComps:m,dataType:w,data:x}=h(v,y);t.create2DFromRaw(g,p,m,w,x)},t.updateVolumeInfoForGL=(g,p)=>{var m,w;let v=!1;const y=t.useHalfFloat();(!((m=e.volumeInfo)!=null&&m.scale)||!((w=e.volumeInfo)!=null&&w.offset))&&(e.volumeInfo={scale:new Array(p),offset:new Array(p)});for(let x=0;x6&&arguments[6]!==void 0?arguments[6]:[],C=m,S=w;if(!t.updateVolumeInfoForGL(C,y)&&S){const P=g*p*v,M=structuredClone(e.volumeInfo),L=new Float32Array(P*y);e.volumeInfo.offset=M.offset,e.volumeInfo.scale=M.scale;let V=0;const G=M.scale.map(A=>1/A);for(let A=0;A0,T=!_||!n_(e._prevTexParams,r()),E=[S],b=t.updateArrayDataTypeForGL(C,E,!0,T?[]:x),I=c(b);if(e.context.pixelStorei(e.context.UNPACK_ALIGNMENT,1),T)l(C)?(e.context.texStorage3D(e.target,1,e.internalFormat,e.width,e.height,e.depth),I[0]!=null&&e.context.texSubImage3D(e.target,0,0,0,0,e.width,e.height,e.depth,e.format,e.openGLDataType,I[0])):e.context.texImage3D(e.target,0,e.internalFormat,e.width,e.height,e.depth,0,e.format,e.openGLDataType,I[0]),e._prevTexParams=r();else if(_){const P=I[0];let M=0;for(let L=0;L6&&arguments[6]!==void 0?arguments[6]:!1,C=arguments.length>7&&arguments[7]!==void 0?arguments[7]:void 0,S=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[];return t.create3DFilterableFromDataArray(g,p,v,Yt.newInstance({numberOfComponents:y,dataType:m,values:w,ranges:C}),x,S)},t.create3DFilterableFromDataArray=function(g,p,v,y){let m=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,w=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[];const{numComps:x,dataType:C,data:S,scaleOffsets:_}=h(y,m),T=[],E=[];for(let pe=0;pe{pe[Ee]=Oe},P=Hn.UNSIGNED_CHAR;if(C===Hn.UNSIGNED_CHAR)for(let pe=0;pe{pe[Ee]=(Oe-_e)/B}):(P=Hn.UNSIGNED_CHAR,I=(pe,Ee,Oe,_e,B)=>{pe[Ee]=255*(Oe-_e)/B});if(t.getOpenGLDataType(P),t.getInternalFormat(P,x),t.getFormat(P,x),!e.internalFormat||!e.format||!e.openGLDataType)return md("Failed to determine texture parameters."),!1;e.target=e.context.TEXTURE_2D,e.components=x,e.depth=1,e.numberOfDimensions=2;let M=e.context.getParameter(e.context.MAX_TEXTURE_SIZE);M>4096&&(P===Hn.FLOAT||x>=3)&&(M=4096);let L=1,V=1;D>M*M&&(L=Math.ceil(Math.sqrt(D/(M*M))),V=L);let G=Math.sqrt(D)/L;G=Ul(G);const A=Math.floor(G*L/g),k=Math.ceil(v/A),F=Ul(p*k/V);e.width=G,e.height=F,e._openGLRenderWindow.activateTexture(t),t.createTexture(),t.bind(),e.volumeInfo.xreps=A,e.volumeInfo.yreps=k,e.volumeInfo.xstride=L,e.volumeInfo.ystride=V,e.volumeInfo.offset=b.offset,e.volumeInfo.scale=b.scale;let j;const Y=G*F*x;P===Hn.FLOAT?j=new Float32Array(Y):j=new Uint8Array(Y);let re=0;const ue=Math.floor(g/L),ce=Math.floor(p/V);for(let pe=0;pe{e._openGLRenderWindow!==g&&(t.releaseGraphicsResources(),e._openGLRenderWindow=g,e.context=null,g&&(e.context=e._openGLRenderWindow.getContext()))},t.getMaximumTextureSize=g=>g&&g.isCurrent()?g.getIntegerv(g.MAX_TEXTURE_SIZE):-1,t.enableUseHalfFloat=g=>{e.enableUseHalfFloat=g}}const PH={_openGLRenderWindow:null,_forceInternalFormat:!1,_prevTexParams:null,context:null,handle:0,sendParametersTime:null,textureBuildTime:null,numberOfDimensions:0,target:0,format:0,openGLDataType:0,components:0,width:0,height:0,depth:0,autoParameters:!0,wrapS:Ic.CLAMP_TO_EDGE,wrapT:Ic.CLAMP_TO_EDGE,wrapR:Ic.CLAMP_TO_EDGE,minificationFilter:bi.NEAREST,magnificationFilter:bi.NEAREST,minLOD:-1e3,maxLOD:1e3,baseLevel:0,maxLevel:1e3,generateMipmap:!1,oglNorm16Ext:null,allocatedGPUMemoryInBytes:0,enableUseHalfFloat:!0,canUseHalfFloat:!1};function mM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,PH,r),gi.extend(t,e,r),e.sendParametersTime={},br(e.sendParametersTime,{mtime:0}),e.textureBuildTime={},br(e.textureBuildTime,{mtime:0}),i1(t,e,["format","openGLDataType"]),Di(t,e,["keyMatrixTime","minificationFilter","magnificationFilter","wrapS","wrapT","wrapR","generateMipmap","oglNorm16Ext"]),Fo(t,e,["width","height","volumeInfo","components","handle","target","allocatedGPUMemoryInBytes"]),o1(t,e,["openGLRenderWindow"]),MH(t,e)}const vM=hr(mM,"vtkOpenGLTexture");var Dr={newInstance:vM,extend:mM,...UO};Ki("vtkTexture",vM);function RH(t,e){e.classHierarchy.push("vtkFramebuffer"),t.getBothMode=()=>e.context.FRAMEBUFFER,t.saveCurrentBindingsAndBuffers=r=>{const n=typeof r<"u"?r:t.getBothMode();t.saveCurrentBindings(n),t.saveCurrentBuffers(n)},t.saveCurrentBindings=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling saveCurrentBindings");return}const n=e.context;e.previousDrawBinding=n.getParameter(e.context.FRAMEBUFFER_BINDING),e.previousActiveFramebuffer=e._openGLRenderWindow.getActiveFramebuffer()},t.saveCurrentBuffers=r=>{},t.restorePreviousBindingsAndBuffers=r=>{const n=typeof r<"u"?r:t.getBothMode();t.restorePreviousBindings(n),t.restorePreviousBuffers(n)},t.restorePreviousBindings=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling restorePreviousBindings");return}const n=e.context;n.bindFramebuffer(n.FRAMEBUFFER,e.previousDrawBinding),e._openGLRenderWindow.setActiveFramebuffer(e.previousActiveFramebuffer)},t.restorePreviousBuffers=r=>{},t.bind=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;n===null&&(n=e.context.FRAMEBUFFER),e.context.bindFramebuffer(n,e.glFramebuffer);for(let i=0;i{if(!e.context){In("you must set the OpenGLRenderWindow before calling create");return}e.glFramebuffer=e.context.createFramebuffer(),e.glFramebuffer.width=r,e.glFramebuffer.height=n},t.setColorBuffer=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;const i=e.context;if(!i){In("you must set the OpenGLRenderWindow before calling setColorBuffer");return}let o=i.COLOR_ATTACHMENT0;if(n>0)if(e._openGLRenderWindow.getWebgl2())o+=n;else{In("Using multiple framebuffer attachments requires WebGL 2");return}e.colorBuffers[n]=r,i.framebufferTexture2D(i.FRAMEBUFFER,o,i.TEXTURE_2D,r.getHandle(),0)},t.removeColorBuffer=function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;const n=e.context;if(!n){In("you must set the OpenGLRenderWindow before calling removeColorBuffer");return}let i=n.COLOR_ATTACHMENT0;if(r>0)if(e._openGLRenderWindow.getWebgl2())i+=r;else{In("Using multiple framebuffer attachments requires WebGL 2");return}n.framebufferTexture2D(n.FRAMEBUFFER,i,n.TEXTURE_2D,null,0),e.colorBuffers=e.colorBuffers.splice(r,1)},t.setDepthBuffer=r=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling setDepthBuffer");return}if(e._openGLRenderWindow.getWebgl2()){const n=e.context;n.framebufferTexture2D(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.TEXTURE_2D,r.getHandle(),0)}else In("Attaching depth buffer textures to fbo requires WebGL 2")},t.removeDepthBuffer=()=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling removeDepthBuffer");return}if(e._openGLRenderWindow.getWebgl2()){const r=e.context;r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,null,0)}else In("Attaching depth buffer textures to framebuffers requires WebGL 2")},t.getGLFramebuffer=()=>e.glFramebuffer,t.setOpenGLRenderWindow=r=>{e._openGLRenderWindow!==r&&(t.releaseGraphicsResources(),e._openGLRenderWindow=r,e.context=null,r&&(e.context=e._openGLRenderWindow.getContext()))},t.releaseGraphicsResources=()=>{e.glFramebuffer&&e.context.deleteFramebuffer(e.glFramebuffer)},t.getSize=()=>e.glFramebuffer==null?null:[e.glFramebuffer.width,e.glFramebuffer.height],t.populateFramebuffer=()=>{if(!e.context){In("you must set the OpenGLRenderWindow before calling populateFrameBuffer");return}t.bind();const r=e.context,n=Dr.newInstance();n.setOpenGLRenderWindow(e._openGLRenderWindow),n.setMinificationFilter(Bt.LINEAR),n.setMagnificationFilter(Bt.LINEAR),n.create2DFromRaw(e.glFramebuffer.width,e.glFramebuffer.height,4,pn.UNSIGNED_CHAR,null),t.setColorBuffer(n),e.depthTexture=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,e.depthTexture),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,e.glFramebuffer.width,e.glFramebuffer.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e.depthTexture)},t.getColorTexture=()=>e.colorBuffers[0]}const LH={glFramebuffer:null,colorBuffers:null,depthTexture:null,previousDrawBinding:0,previousReadBinding:0,previousDrawBuffer:0,previousReadBuffer:0,previousActiveFramebuffer:null};function yM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,LH,r),br(t,e),e.colorBuffers&&In("you cannot initialize colorBuffers through the constructor. You should call setColorBuffer() instead."),e.colorBuffers=[],rh(t,e,["colorBuffers"]),RH(t,e)}const AH=hr(yM,"vtkFramebuffer");var zy={newInstance:AH,extend:yM};function NH(t,e){e.classHierarchy.push("vtkRenderPass"),t.getOperation=()=>e.currentOperation,t.setCurrentOperation=r=>{e.currentOperation=r,e.currentTraverseOperation=`traverse${ne.capitalize(e.currentOperation)}`},t.getTraverseOperation=()=>e.currentTraverseOperation,t.traverse=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;e.deleted||(e._currentParent=n,e.preDelegateOperations.forEach(i=>{t.setCurrentOperation(i),r.traverse(t)}),e.delegates.forEach(i=>{i.traverse(r,t)}),e.postDelegateOperations.forEach(i=>{t.setCurrentOperation(i),r.traverse(t)}))}}const kH={delegates:[],currentOperation:null,preDelegateOperations:[],postDelegateOperations:[],currentParent:null};function wM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,kH,r),ne.obj(t,e),ne.get(t,e,["currentOperation"]),ne.setGet(t,e,["delegates","_currentParent","preDelegateOperations","postDelegateOperations"]),ne.moveToProtected(t,e,["currentParent"]),NH(t,e)}const VH=ne.newInstance(wM,"vtkRenderPass");var T_={newInstance:VH,extend:wM},Wn=1e-6,Yr=typeof Float32Array<"u"?Float32Array:Array,FH=Math.PI/180;function UH(t){return t*FH}function vu(t,e){return Math.abs(t-e)<=Wn*Math.max(1,Math.abs(t),Math.abs(e))}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});function E_(){var t=new Yr(9);return Yr!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function $y(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t}function BH(t){var e=new Yr(9);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function GH(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function ug(t,e,r,n,i,o,a,s,c){var l=new Yr(9);return l[0]=t,l[1]=e,l[2]=r,l[3]=n,l[4]=i,l[5]=o,l[6]=a,l[7]=s,l[8]=c,l}function xM(t,e,r,n,i,o,a,s,c,l){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=o,t[5]=a,t[6]=s,t[7]=c,t[8]=l,t}function xs(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function D_(t,e){if(t===e){var r=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=r,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t}function u1(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=f*a-s*l,d=-f*o+s*c,h=l*o-a*c,g=r*u+n*d+i*h;return g?(g=1/g,t[0]=u*g,t[1]=(-f*n+i*l)*g,t[2]=(s*n-i*a)*g,t[3]=d*g,t[4]=(f*r-i*c)*g,t[5]=(-s*r+i*o)*g,t[6]=h*g,t[7]=(-l*r+n*c)*g,t[8]=(a*r-n*o)*g,t):null}function WH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8];return t[0]=a*f-s*l,t[1]=i*l-n*f,t[2]=n*s-i*a,t[3]=s*c-o*f,t[4]=r*f-i*c,t[5]=i*o-r*s,t[6]=o*l-a*c,t[7]=n*c-r*l,t[8]=r*a-n*o,t}function yf(t){var e=t[0],r=t[1],n=t[2],i=t[3],o=t[4],a=t[5],s=t[6],c=t[7],l=t[8];return e*(l*o-a*c)+r*(-l*i+a*s)+n*(c*i-o*s)}function A0(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=r[0],h=r[1],g=r[2],p=r[3],v=r[4],y=r[5],m=r[6],w=r[7],x=r[8];return t[0]=d*n+h*a+g*l,t[1]=d*i+h*s+g*f,t[2]=d*o+h*c+g*u,t[3]=p*n+v*a+y*l,t[4]=p*i+v*s+y*f,t[5]=p*o+v*c+y*u,t[6]=m*n+w*a+x*l,t[7]=m*i+w*s+x*f,t[8]=m*o+w*c+x*u,t}function zH(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=r[0],h=r[1];return t[0]=n,t[1]=i,t[2]=o,t[3]=a,t[4]=s,t[5]=c,t[6]=d*n+h*a+l,t[7]=d*i+h*s+f,t[8]=d*o+h*c+u,t}function $H(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=Math.sin(r),h=Math.cos(r);return t[0]=h*n+d*a,t[1]=h*i+d*s,t[2]=h*o+d*c,t[3]=h*a-d*n,t[4]=h*s-d*i,t[5]=h*c-d*o,t[6]=l,t[7]=f,t[8]=u,t}function jH(t,e,r){var n=r[0],i=r[1];return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=i*e[3],t[4]=i*e[4],t[5]=i*e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function HH(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=e[0],t[7]=e[1],t[8]=1,t}function KH(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function qH(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=e[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function XH(t,e){return t[0]=e[0],t[1]=e[1],t[2]=0,t[3]=e[2],t[4]=e[3],t[5]=0,t[6]=e[4],t[7]=e[5],t[8]=1,t}function YH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=r+r,s=n+n,c=i+i,l=r*a,f=n*a,u=n*s,d=i*a,h=i*s,g=i*c,p=o*a,v=o*s,y=o*c;return t[0]=1-u-g,t[3]=f-y,t[6]=d+v,t[1]=f+y,t[4]=1-l-g,t[7]=h-p,t[2]=d-v,t[5]=h+p,t[8]=1-l-u,t}function JH(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15],m=r*s-n*a,w=r*c-i*a,x=r*l-o*a,C=n*c-i*s,S=n*l-o*s,_=i*l-o*c,T=f*p-u*g,E=f*v-d*g,D=f*y-h*g,b=u*v-d*p,I=u*y-h*p,P=d*y-h*v,M=m*P-w*I+x*b+C*D-S*E+_*T;return M?(M=1/M,t[0]=(s*P-c*I+l*b)*M,t[1]=(c*D-a*P-l*E)*M,t[2]=(a*I-s*D+l*T)*M,t[3]=(i*I-n*P-o*b)*M,t[4]=(r*P-i*D+o*E)*M,t[5]=(n*D-r*I-o*T)*M,t[6]=(p*_-v*S+y*C)*M,t[7]=(v*x-g*_-y*w)*M,t[8]=(g*S-p*x+y*m)*M,t):null}function ZH(t,e,r){return t[0]=2/e,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function QH(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function eK(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])}function tK(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t}function CM(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t}function nK(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t}function rK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t}function iK(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]}function oK(t,e){var r=t[0],n=t[1],i=t[2],o=t[3],a=t[4],s=t[5],c=t[6],l=t[7],f=t[8],u=e[0],d=e[1],h=e[2],g=e[3],p=e[4],v=e[5],y=e[6],m=e[7],w=e[8];return Math.abs(r-u)<=Wn*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-d)<=Wn*Math.max(1,Math.abs(n),Math.abs(d))&&Math.abs(i-h)<=Wn*Math.max(1,Math.abs(i),Math.abs(h))&&Math.abs(o-g)<=Wn*Math.max(1,Math.abs(o),Math.abs(g))&&Math.abs(a-p)<=Wn*Math.max(1,Math.abs(a),Math.abs(p))&&Math.abs(s-v)<=Wn*Math.max(1,Math.abs(s),Math.abs(v))&&Math.abs(c-y)<=Wn*Math.max(1,Math.abs(c),Math.abs(y))&&Math.abs(l-m)<=Wn*Math.max(1,Math.abs(l),Math.abs(m))&&Math.abs(f-w)<=Wn*Math.max(1,Math.abs(f),Math.abs(w))}var aK=A0,sK=CM;const cK=Object.freeze(Object.defineProperty({__proto__:null,add:tK,adjoint:WH,clone:BH,copy:GH,create:E_,determinant:yf,equals:oK,exactEquals:iK,frob:eK,fromMat2d:XH,fromMat4:$y,fromQuat:YH,fromRotation:KH,fromScaling:qH,fromTranslation:HH,fromValues:ug,identity:xs,invert:u1,mul:aK,multiply:A0,multiplyScalar:nK,multiplyScalarAndAdd:rK,normalFromMat4:JH,projection:ZH,rotate:$H,scale:jH,set:xM,str:QH,sub:sK,subtract:CM,translate:zH,transpose:D_},Symbol.toStringTag,{value:"Module"}));function Zo(){var t=new Yr(16);return Yr!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function lK(t){var e=new Yr(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function ri(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function b_(t,e,r,n,i,o,a,s,c,l,f,u,d,h,g,p){var v=new Yr(16);return v[0]=t,v[1]=e,v[2]=r,v[3]=n,v[4]=i,v[5]=o,v[6]=a,v[7]=s,v[8]=c,v[9]=l,v[10]=f,v[11]=u,v[12]=d,v[13]=h,v[14]=g,v[15]=p,v}function uK(t,e,r,n,i,o,a,s,c,l,f,u,d,h,g,p,v){return t[0]=e,t[1]=r,t[2]=n,t[3]=i,t[4]=o,t[5]=a,t[6]=s,t[7]=c,t[8]=l,t[9]=f,t[10]=u,t[11]=d,t[12]=h,t[13]=g,t[14]=p,t[15]=v,t}function Vt(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Fn(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],o=e[6],a=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=o,t[11]=e[14],t[12]=i,t[13]=a,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function oi(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15],m=r*s-n*a,w=r*c-i*a,x=r*l-o*a,C=n*c-i*s,S=n*l-o*s,_=i*l-o*c,T=f*p-u*g,E=f*v-d*g,D=f*y-h*g,b=u*v-d*p,I=u*y-h*p,P=d*y-h*v,M=m*P-w*I+x*b+C*D-S*E+_*T;return M?(M=1/M,t[0]=(s*P-c*I+l*b)*M,t[1]=(i*I-n*P-o*b)*M,t[2]=(p*_-v*S+y*C)*M,t[3]=(d*S-u*_-h*C)*M,t[4]=(c*D-a*P-l*E)*M,t[5]=(r*P-i*D+o*E)*M,t[6]=(v*x-g*_-y*w)*M,t[7]=(f*_-d*x+h*w)*M,t[8]=(a*I-s*D+l*T)*M,t[9]=(n*D-r*I-o*T)*M,t[10]=(g*S-p*x+y*m)*M,t[11]=(u*x-f*S-h*m)*M,t[12]=(s*E-a*b-c*T)*M,t[13]=(r*b-n*E+i*T)*M,t[14]=(p*w-g*C-v*m)*M,t[15]=(f*C-u*w+d*m)*M,t):null}function fK(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],s=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],g=e[12],p=e[13],v=e[14],y=e[15];return t[0]=s*(d*y-h*v)-u*(c*y-l*v)+p*(c*h-l*d),t[1]=-(n*(d*y-h*v)-u*(i*y-o*v)+p*(i*h-o*d)),t[2]=n*(c*y-l*v)-s*(i*y-o*v)+p*(i*l-o*c),t[3]=-(n*(c*h-l*d)-s*(i*h-o*d)+u*(i*l-o*c)),t[4]=-(a*(d*y-h*v)-f*(c*y-l*v)+g*(c*h-l*d)),t[5]=r*(d*y-h*v)-f*(i*y-o*v)+g*(i*h-o*d),t[6]=-(r*(c*y-l*v)-a*(i*y-o*v)+g*(i*l-o*c)),t[7]=r*(c*h-l*d)-a*(i*h-o*d)+f*(i*l-o*c),t[8]=a*(u*y-h*p)-f*(s*y-l*p)+g*(s*h-l*u),t[9]=-(r*(u*y-h*p)-f*(n*y-o*p)+g*(n*h-o*u)),t[10]=r*(s*y-l*p)-a*(n*y-o*p)+g*(n*l-o*s),t[11]=-(r*(s*h-l*u)-a*(n*h-o*u)+f*(n*l-o*s)),t[12]=-(a*(u*v-d*p)-f*(s*v-c*p)+g*(s*d-c*u)),t[13]=r*(u*v-d*p)-f*(n*v-i*p)+g*(n*d-i*u),t[14]=-(r*(s*v-c*p)-a*(n*v-i*p)+g*(n*c-i*s)),t[15]=r*(s*d-c*u)-a*(n*d-i*u)+f*(n*c-i*s),t}function dK(t){var e=t[0],r=t[1],n=t[2],i=t[3],o=t[4],a=t[5],s=t[6],c=t[7],l=t[8],f=t[9],u=t[10],d=t[11],h=t[12],g=t[13],p=t[14],v=t[15],y=e*a-r*o,m=e*s-n*o,w=e*c-i*o,x=r*s-n*a,C=r*c-i*a,S=n*c-i*s,_=l*g-f*h,T=l*p-u*h,E=l*v-d*h,D=f*p-u*g,b=f*v-d*g,I=u*v-d*p;return y*I-m*b+w*D+x*E-C*T+S*_}function On(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=e[9],h=e[10],g=e[11],p=e[12],v=e[13],y=e[14],m=e[15],w=r[0],x=r[1],C=r[2],S=r[3];return t[0]=w*n+x*s+C*u+S*p,t[1]=w*i+x*c+C*d+S*v,t[2]=w*o+x*l+C*h+S*y,t[3]=w*a+x*f+C*g+S*m,w=r[4],x=r[5],C=r[6],S=r[7],t[4]=w*n+x*s+C*u+S*p,t[5]=w*i+x*c+C*d+S*v,t[6]=w*o+x*l+C*h+S*y,t[7]=w*a+x*f+C*g+S*m,w=r[8],x=r[9],C=r[10],S=r[11],t[8]=w*n+x*s+C*u+S*p,t[9]=w*i+x*c+C*d+S*v,t[10]=w*o+x*l+C*h+S*y,t[11]=w*a+x*f+C*g+S*m,w=r[12],x=r[13],C=r[14],S=r[15],t[12]=w*n+x*s+C*u+S*p,t[13]=w*i+x*c+C*d+S*v,t[14]=w*o+x*l+C*h+S*y,t[15]=w*a+x*f+C*g+S*m,t}function Lr(t,e,r){var n=r[0],i=r[1],o=r[2],a,s,c,l,f,u,d,h,g,p,v,y;return e===t?(t[12]=e[0]*n+e[4]*i+e[8]*o+e[12],t[13]=e[1]*n+e[5]*i+e[9]*o+e[13],t[14]=e[2]*n+e[6]*i+e[10]*o+e[14],t[15]=e[3]*n+e[7]*i+e[11]*o+e[15]):(a=e[0],s=e[1],c=e[2],l=e[3],f=e[4],u=e[5],d=e[6],h=e[7],g=e[8],p=e[9],v=e[10],y=e[11],t[0]=a,t[1]=s,t[2]=c,t[3]=l,t[4]=f,t[5]=u,t[6]=d,t[7]=h,t[8]=g,t[9]=p,t[10]=v,t[11]=y,t[12]=a*n+f*i+g*o+e[12],t[13]=s*n+u*i+p*o+e[13],t[14]=c*n+d*i+v*o+e[14],t[15]=l*n+h*i+y*o+e[15]),t}function Qs(t,e,r){var n=r[0],i=r[1],o=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function go(t,e,r,n){var i=n[0],o=n[1],a=n[2],s=Math.hypot(i,o,a),c,l,f,u,d,h,g,p,v,y,m,w,x,C,S,_,T,E,D,b,I,P,M,L;return s0?(r[0]=(s*a+f*n+c*o-l*i)*2/u,r[1]=(c*a+f*i+l*n-s*o)*2/u,r[2]=(l*a+f*o+s*i-c*n)*2/u):(r[0]=(s*a+f*n+c*o-l*i)*2,r[1]=(c*a+f*i+l*n-s*o)*2,r[2]=(l*a+f*o+s*i-c*n)*2),SM(t,e,r),t}function vK(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function _M(t,e){var r=e[0],n=e[1],i=e[2],o=e[4],a=e[5],s=e[6],c=e[8],l=e[9],f=e[10];return t[0]=Math.hypot(r,n,i),t[1]=Math.hypot(o,a,s),t[2]=Math.hypot(c,l,f),t}function Ux(t,e){var r=new Yr(3);_M(r,e);var n=1/r[0],i=1/r[1],o=1/r[2],a=e[0]*n,s=e[1]*i,c=e[2]*o,l=e[4]*n,f=e[5]*i,u=e[6]*o,d=e[8]*n,h=e[9]*i,g=e[10]*o,p=a+f+g,v=0;return p>0?(v=Math.sqrt(p+1)*2,t[3]=.25*v,t[0]=(u-h)/v,t[1]=(d-c)/v,t[2]=(s-l)/v):a>f&&a>g?(v=Math.sqrt(1+a-f-g)*2,t[3]=(u-h)/v,t[0]=.25*v,t[1]=(s+l)/v,t[2]=(d+c)/v):f>g?(v=Math.sqrt(1+f-a-g)*2,t[3]=(d-c)/v,t[0]=(s+l)/v,t[1]=.25*v,t[2]=(u+h)/v):(v=Math.sqrt(1+g-a-f)*2,t[3]=(s-l)/v,t[0]=(d+c)/v,t[1]=(u+h)/v,t[2]=.25*v),t}function TM(t,e,r,n){var i=e[0],o=e[1],a=e[2],s=e[3],c=i+i,l=o+o,f=a+a,u=i*c,d=i*l,h=i*f,g=o*l,p=o*f,v=a*f,y=s*c,m=s*l,w=s*f,x=n[0],C=n[1],S=n[2];return t[0]=(1-(g+v))*x,t[1]=(d+w)*x,t[2]=(h-m)*x,t[3]=0,t[4]=(d-w)*C,t[5]=(1-(u+v))*C,t[6]=(p+y)*C,t[7]=0,t[8]=(h+m)*S,t[9]=(p-y)*S,t[10]=(1-(u+g))*S,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function yK(t,e,r,n,i){var o=e[0],a=e[1],s=e[2],c=e[3],l=o+o,f=a+a,u=s+s,d=o*l,h=o*f,g=o*u,p=a*f,v=a*u,y=s*u,m=c*l,w=c*f,x=c*u,C=n[0],S=n[1],_=n[2],T=i[0],E=i[1],D=i[2],b=(1-(p+y))*C,I=(h+x)*C,P=(g-w)*C,M=(h-x)*S,L=(1-(d+y))*S,V=(v+m)*S,G=(g+w)*_,A=(v-m)*_,k=(1-(d+p))*_;return t[0]=b,t[1]=I,t[2]=P,t[3]=0,t[4]=M,t[5]=L,t[6]=V,t[7]=0,t[8]=G,t[9]=A,t[10]=k,t[11]=0,t[12]=r[0]+T-(b*T+M*E+G*D),t[13]=r[1]+E-(I*T+L*E+A*D),t[14]=r[2]+D-(P*T+V*E+k*D),t[15]=1,t}function vv(t,e){var r=e[0],n=e[1],i=e[2],o=e[3],a=r+r,s=n+n,c=i+i,l=r*a,f=n*a,u=n*s,d=i*a,h=i*s,g=i*c,p=o*a,v=o*s,y=o*c;return t[0]=1-u-g,t[1]=f+y,t[2]=d-v,t[3]=0,t[4]=f-y,t[5]=1-l-g,t[6]=h+p,t[7]=0,t[8]=d+v,t[9]=h-p,t[10]=1-l-u,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wK(t,e,r,n,i,o,a){var s=1/(r-e),c=1/(i-n),l=1/(o-a);return t[0]=o*2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*s,t[9]=(i+n)*c,t[10]=(a+o)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=a*o*2*l,t[15]=0,t}function EM(t,e,r,n,i){var o=1/Math.tan(e/2),a;return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0?(a=1/(n-i),t[10]=(i+n)*a,t[14]=2*i*n*a):(t[10]=-1,t[14]=-2*n),t}var xK=EM;function CK(t,e,r,n,i){var o=1/Math.tan(e/2),a;return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,i!=null&&i!==1/0?(a=1/(n-i),t[10]=i*a,t[14]=i*n*a):(t[10]=-1,t[14]=-n),t}function SK(t,e,r,n){var i=Math.tan(e.upDegrees*Math.PI/180),o=Math.tan(e.downDegrees*Math.PI/180),a=Math.tan(e.leftDegrees*Math.PI/180),s=Math.tan(e.rightDegrees*Math.PI/180),c=2/(a+s),l=2/(i+o);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((a-s)*c*.5),t[9]=(i-o)*l*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function DM(t,e,r,n,i,o,a){var s=1/(e-r),c=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=(a+o)*l,t[15]=1,t}var L_=DM;function _K(t,e,r,n,i,o,a){var s=1/(e-r),c=1/(n-i),l=1/(o-a);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*c,t[14]=o*l,t[15]=1,t}function A_(t,e,r,n){var i,o,a,s,c,l,f,u,d,h,g=e[0],p=e[1],v=e[2],y=n[0],m=n[1],w=n[2],x=r[0],C=r[1],S=r[2];return Math.abs(g-x)0&&(h=1/Math.sqrt(h),f*=h,u*=h,d*=h);var g=c*d-l*u,p=l*f-s*d,v=s*u-c*f;return h=g*g+p*p+v*v,h>0&&(h=1/Math.sqrt(h),g*=h,p*=h,v*=h),t[0]=g,t[1]=p,t[2]=v,t[3]=0,t[4]=u*v-d*p,t[5]=d*g-f*v,t[6]=f*p-u*g,t[7]=0,t[8]=f,t[9]=u,t[10]=d,t[11]=0,t[12]=i,t[13]=o,t[14]=a,t[15]=1,t}function EK(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function DK(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function bK(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function bM(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function IM(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function IK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t[3]=e[3]+r[3]*n,t[4]=e[4]+r[4]*n,t[5]=e[5]+r[5]*n,t[6]=e[6]+r[6]*n,t[7]=e[7]+r[7]*n,t[8]=e[8]+r[8]*n,t[9]=e[9]+r[9]*n,t[10]=e[10]+r[10]*n,t[11]=e[11]+r[11]*n,t[12]=e[12]+r[12]*n,t[13]=e[13]+r[13]*n,t[14]=e[14]+r[14]*n,t[15]=e[15]+r[15]*n,t}function OK(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function MK(t,e){var r=t[0],n=t[1],i=t[2],o=t[3],a=t[4],s=t[5],c=t[6],l=t[7],f=t[8],u=t[9],d=t[10],h=t[11],g=t[12],p=t[13],v=t[14],y=t[15],m=e[0],w=e[1],x=e[2],C=e[3],S=e[4],_=e[5],T=e[6],E=e[7],D=e[8],b=e[9],I=e[10],P=e[11],M=e[12],L=e[13],V=e[14],G=e[15];return Math.abs(r-m)<=Wn*Math.max(1,Math.abs(r),Math.abs(m))&&Math.abs(n-w)<=Wn*Math.max(1,Math.abs(n),Math.abs(w))&&Math.abs(i-x)<=Wn*Math.max(1,Math.abs(i),Math.abs(x))&&Math.abs(o-C)<=Wn*Math.max(1,Math.abs(o),Math.abs(C))&&Math.abs(a-S)<=Wn*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(s-_)<=Wn*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(c-T)<=Wn*Math.max(1,Math.abs(c),Math.abs(T))&&Math.abs(l-E)<=Wn*Math.max(1,Math.abs(l),Math.abs(E))&&Math.abs(f-D)<=Wn*Math.max(1,Math.abs(f),Math.abs(D))&&Math.abs(u-b)<=Wn*Math.max(1,Math.abs(u),Math.abs(b))&&Math.abs(d-I)<=Wn*Math.max(1,Math.abs(d),Math.abs(I))&&Math.abs(h-P)<=Wn*Math.max(1,Math.abs(h),Math.abs(P))&&Math.abs(g-M)<=Wn*Math.max(1,Math.abs(g),Math.abs(M))&&Math.abs(p-L)<=Wn*Math.max(1,Math.abs(p),Math.abs(L))&&Math.abs(v-V)<=Wn*Math.max(1,Math.abs(v),Math.abs(V))&&Math.abs(y-G)<=Wn*Math.max(1,Math.abs(y),Math.abs(G))}var yv=On,PK=bM;const wv=Object.freeze(Object.defineProperty({__proto__:null,add:bK,adjoint:fK,clone:lK,copy:ri,create:Zo,determinant:dK,equals:MK,exactEquals:OK,frob:DK,fromQuat:vv,fromQuat2:mK,fromRotation:R_,fromRotationTranslation:SM,fromRotationTranslationScale:TM,fromRotationTranslationScaleOrigin:yK,fromScaling:P_,fromTranslation:f1,fromValues:b_,fromXRotation:hK,fromYRotation:gK,fromZRotation:pK,frustum:wK,getRotation:Ux,getScaling:_M,getTranslation:vK,identity:Vt,invert:oi,lookAt:A_,mul:yv,multiply:On,multiplyScalar:IM,multiplyScalarAndAdd:IK,ortho:L_,orthoNO:DM,orthoZO:_K,perspective:xK,perspectiveFromFieldOfView:SK,perspectiveNO:EM,perspectiveZO:CK,rotate:go,rotateX:I_,rotateY:O_,rotateZ:M_,scale:Qs,set:uK,str:EK,sub:PK,subtract:bM,targetTo:TK,translate:Lr,transpose:Fn},Symbol.toStringTag,{value:"Module"}));function Ve(){var t=new Yr(3);return Yr!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function OM(t){var e=new Yr(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function Po(t){var e=t[0],r=t[1],n=t[2];return Math.hypot(e,r,n)}function bt(t,e,r){var n=new Yr(3);return n[0]=t,n[1]=e,n[2]=r,n}function RK(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function Yn(t,e,r,n){return t[0]=e,t[1]=r,t[2]=n,t}function Ai(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function rr(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function LK(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function AK(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function NK(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function kK(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function VK(t,e){return t[0]=Math.round(e[0]),t[1]=Math.round(e[1]),t[2]=Math.round(e[2]),t}function Ni(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function Tn(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t[2]=e[2]+r[2]*n,t}function ki(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return Math.hypot(r,n,i)}function MM(t,e){var r=e[0]-t[0],n=e[1]-t[1],i=e[2]-t[2];return r*r+n*n+i*i}function Hs(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function PM(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function tr(t,e){var r=e[0],n=e[1],i=e[2],o=r*r+n*n+i*i;return o>0&&(o=1/Math.sqrt(o)),t[0]=e[0]*o,t[1]=e[1]*o,t[2]=e[2]*o,t}function Et(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Rn(t,e,r){var n=e[0],i=e[1],o=e[2],a=r[0],s=r[1],c=r[2];return t[0]=i*c-o*s,t[1]=o*a-n*c,t[2]=n*s-i*a,t}function Jt(t,e,r){var n=e[0],i=e[1],o=e[2],a=r[3]*n+r[7]*i+r[11]*o+r[15];return a=a||1,t[0]=(r[0]*n+r[4]*i+r[8]*o+r[12])/a,t[1]=(r[1]*n+r[5]*i+r[9]*o+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*o+r[14])/a,t}function m2(t,e,r){var n=e[0],i=e[1],o=e[2];return t[0]=n*r[0]+i*r[3]+o*r[6],t[1]=n*r[1]+i*r[4]+o*r[7],t[2]=n*r[2]+i*r[5]+o*r[8],t}function FK(t,e,r){var n=r[0],i=r[1],o=r[2],a=r[3],s=e[0],c=e[1],l=e[2],f=i*l-o*c,u=o*s-n*l,d=n*c-i*s,h=i*d-o*u,g=o*f-n*d,p=n*u-i*f,v=a*2;return f*=v,u*=v,d*=v,h*=2,g*=2,p*=2,t[0]=s+f+h,t[1]=c+u+g,t[2]=l+d+p,t}function N_(t,e){var r=t[0],n=t[1],i=t[2],o=e[0],a=e[1],s=e[2],c=Math.sqrt(r*r+n*n+i*i),l=Math.sqrt(o*o+a*a+s*s),f=c*l,u=f&&Et(t,e)/f;return Math.acos(Math.min(Math.max(u,-1),1))}function UK(t){return t[0]=0,t[1]=0,t[2]=0,t}function c6(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function Bx(t,e){var r=t[0],n=t[1],i=t[2],o=e[0],a=e[1],s=e[2];return Math.abs(r-o)<=Wn*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-a)<=Wn*Math.max(1,Math.abs(n),Math.abs(a))&&Math.abs(i-s)<=Wn*Math.max(1,Math.abs(i),Math.abs(s))}var En=rr,BK=LK,Gx=MM,N0=Po;(function(){var t=Ve();return function(e,r,n,i,o,a){var s,c;for(r||(r=3),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;s0&&(a=1/Math.sqrt(a)),t[0]=r*a,t[1]=n*a,t[2]=i*a,t[3]=o*a,t}function u6(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Jl(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*o+r[12]*a,t[1]=r[1]*n+r[5]*i+r[9]*o+r[13]*a,t[2]=r[2]*n+r[6]*i+r[10]*o+r[14]*a,t[3]=r[3]*n+r[7]*i+r[11]*o+r[15]*a,t}(function(){var t=RM();return function(e,r,n,i,o,a){var s,c;for(r||(r=4),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;sWn?(t[0]=e[0]/n,t[1]=e[1]/n,t[2]=e[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function f6(t,e,r){var n=e[0],i=e[1],o=e[2],a=e[3],s=r[0],c=r[1],l=r[2],f=r[3];return t[0]=n*f+a*s+i*l-o*c,t[1]=i*f+a*c+o*s-n*l,t[2]=o*f+a*l+n*c-i*s,t[3]=a*f-n*s-i*c-o*l,t}function y2(t,e,r,n){var i=e[0],o=e[1],a=e[2],s=e[3],c=r[0],l=r[1],f=r[2],u=r[3],d,h,g,p,v;return h=i*c+o*l+a*f+s*u,h<0&&(h=-h,c=-c,l=-l,f=-f,u=-u),1-h>Wn?(d=Math.acos(h),g=Math.sin(d),p=Math.sin((1-n)*d)/g,v=Math.sin(n*d)/g):(p=1-n,v=n),t[0]=p*i+v*c,t[1]=p*o+v*l,t[2]=p*a+v*f,t[3]=p*s+v*u,t}function zK(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t}function $K(t,e){var r=e[0]+e[4]+e[8],n;if(r>0)n=Math.sqrt(r+1),t[3]=.5*n,n=.5/n,t[0]=(e[5]-e[7])*n,t[1]=(e[6]-e[2])*n,t[2]=(e[1]-e[3])*n;else{var i=0;e[4]>e[0]&&(i=1),e[8]>e[i*3+i]&&(i=2);var o=(i+1)%3,a=(i+2)%3;n=Math.sqrt(e[i*3+i]-e[o*3+o]-e[a*3+a]+1),t[i]=.5*n,n=.5/n,t[3]=(e[o*3+a]-e[a*3+o])*n,t[o]=(e[o*3+i]+e[i*3+o])*n,t[a]=(e[a*3+i]+e[i*3+a])*n}return t}var d6=v2,LM=GK;(function(){var t=Ve(),e=bt(1,0,0),r=bt(0,1,0);return function(n,i,o){var a=Et(i,o);return a<-.999999?(Rn(t,e,i),N0(t)<1e-6&&Rn(t,r,i),tr(t,t),jy(n,t,Math.PI),n):a>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(Rn(t,i,o),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+a,LM(n,n))}})();(function(){var t=yu(),e=yu();return function(r,n,i,o,a,s){return y2(t,n,a,s),y2(e,i,o,s),y2(r,t,e,2*s*(1-s)),r}})();(function(){var t=E_();return function(e,r,n,i){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=i[0],t[4]=i[1],t[7]=i[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],LM(e,$K(e,t))}})();function qt(){var t=new Yr(2);return Yr!=Float32Array&&(t[0]=0,t[1]=0),t}function om(t){var e=new Yr(2);return e[0]=t[0],e[1]=t[1],e}function h6(t,e){var r=new Yr(2);return r[0]=t,r[1]=e,r}function Va(t,e,r){return t[0]=e,t[1]=r,t}function Qi(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t}function Wr(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function Oc(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t}function jK(t,e,r,n){return t[0]=e[0]+r[0]*n,t[1]=e[1]+r[1]*n,t}function yr(t,e){var r=e[0]-t[0],n=e[1]-t[1];return Math.hypot(r,n)}function xv(t){var e=t[0],r=t[1];return Math.hypot(e,r)}function Nc(t,e){var r=e[0],n=e[1],i=r*r+n*n;return i>0&&(i=1/Math.sqrt(i)),t[0]=e[0]*i,t[1]=e[1]*i,t}function k_(t,e){return t[0]*e[0]+t[1]*e[1]}function HK(t,e,r,n){var i=e[0]-r[0],o=e[1]-r[1],a=Math.sin(n),s=Math.cos(n);return t[0]=i*s-o*a+r[0],t[1]=i*a+o*s+r[1],t}function KK(t,e){var r=t[0],n=t[1],i=e[0],o=e[1],a=Math.sqrt(r*r+n*n)*Math.sqrt(i*i+o*o),s=a&&(r*i+n*o)/a;return Math.acos(Math.min(Math.max(s,-1),1))}var qK=xv,Ga=Wr,V_=yr;(function(){var t=qt();return function(e,r,n,i,o,a){var s,c;for(r||(r=2),n||(n=0),i?c=Math.min(i*r+n,e.length):c=e.length,s=n;sn,t.setType=s=>{n=s},t.getHandle=()=>i,t.isReady=()=>o===!1,t.generateBuffer=s=>{const c=r(s);return i===null&&(i=e.context.createBuffer(),n=s),r(n)===c},t.upload=(s,c)=>t.generateBuffer(c)?(e.context.bindBuffer(r(n),i),e.context.bufferData(r(n),s,e.context.STATIC_DRAW),e.allocatedGPUMemoryInBytes=s.length*s.BYTES_PER_ELEMENT,o=!1,!0):(a="Trying to upload array buffer to incompatible buffer.",!1),t.bind=()=>i?(e.context.bindBuffer(r(n),i),!0):!1,t.release=()=>i?(e.context.bindBuffer(r(n),null),!0):!1,t.releaseGraphicsResources=()=>{i!==null&&(e.context.bindBuffer(r(n),null),e.context.deleteBuffer(i),i=null,e.allocatedGPUMemoryInBytes=0)},t.setOpenGLRenderWindow=s=>{e._openGLRenderWindow!==s&&(t.releaseGraphicsResources(),e._openGLRenderWindow=s,e.context=null,s&&(e.context=e._openGLRenderWindow.getContext()))},t.getError=()=>a}const JK={objectType:w2.ARRAY_BUFFER,context:null,allocatedGPUMemoryInBytes:0};function NM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,JK,r),ne.obj(t,e),ne.get(t,e,["_openGLRenderWindow","allocatedGPUMemoryInBytes"]),ne.moveToProtected(t,e,["openGLRenderWindow"]),YK(t,e)}const ZK=ne.newInstance(NM);var kc={newInstance:ZK,extend:NM,...XK,...AM};const kM={FLAT:0,GOURAUD:1,PHONG:2},Wa={POINTS:0,WIREFRAME:1,SURFACE:2},QK=kM;var VM={Shading:kM,Representation:Wa,Interpolation:QK};const{vtkErrorMacro:g6}=ne;function eq(t,e){const r=new Float64Array(3);PM(r,e);const n=new Float64Array(16);return TM(n,yu(),t,r),n}function tq(t,e){return t===null||e===null?!1:!(c6(t,[0,0,0])&&c6(e,[1,1,1]))}function nq(t,e){e.classHierarchy.push("vtkOpenGLCellArrayBufferObject"),t.setType(Bc.ARRAY_BUFFER),t.createVBO=function(r,n,i,o){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;if(!r.getData()||!r.getData().length)return e.elementCount=0,0;e.blockSize=3,e.vertexOffset=0,e.normalOffset=0,e.tCoordOffset=0,e.tCoordComponents=0,e.colorComponents=0,e.colorOffset=0,e.customData=[];const s=o.points.getData();let c=null,l=null,f=null;const u=o.colors?o.colors.getNumberOfComponents():0,d=o.tcoords?o.tcoords.getNumberOfComponents():0;o.normals&&(e.normalOffset=4*e.blockSize,e.blockSize+=3,c=o.normals.getData()),o.customAttributes&&o.customAttributes.forEach(k=>{k&&(e.customData.push({data:k.getData(),offset:4*e.blockSize,components:k.getNumberOfComponents(),name:k.getName()}),e.blockSize+=k.getNumberOfComponents())}),o.tcoords&&(e.tCoordOffset=4*e.blockSize,e.tCoordComponents=d,e.blockSize+=d,l=o.tcoords.getData()),o.colors?(e.colorComponents=o.colors.getNumberOfComponents(),e.colorOffset=0,f=o.colors.getData(),e.colorBO||(e.colorBO=kc.newInstance()),e.colorBO.setOpenGLRenderWindow(e._openGLRenderWindow)):e.colorBO=null,e.stride=4*e.blockSize;let h=0,g=0,p=0,v=0,y=0,m=0,w;const x={anythingToPoints(k,F,j,Y){for(let re=0;re2)for(let re=0;re2){for(let re=0;re1?(k-1)*2:0},polysToWireframe(k,F){return k>2?k*2:0},stripsToWireframe(k,F){return k>2?k*4-6:0},polysToSurface(k,F){return k>2?(k-2)*3:0},stripsToSurface(k,F,j){return k>2?(k-2)*3:0}};let S=null,_=null;i===Wa.POINTS||n==="verts"?(S=x.anythingToPoints,_=C.anythingToPoints):i===Wa.WIREFRAME||n==="lines"?(S=x[`${n}ToWireframe`],_=C[`${n}ToWireframe`]):(S=x[`${n}ToSurface`],_=C[`${n}ToSurface`]);const T=r.getData(),E=T.length;let D=0;for(let k=0;k0&&(Math.abs(V)/L>1e6||Math.abs(Math.log10(L))>3||L===0&&V>1e6)){const k=new Float64Array(3),F=new Float64Array(3);for(let j=0;j<3;++j){const Y=o.points.getRange(j),re=Y[1]-Y[0];k[j]=.5*(Y[1]+Y[0]),F[j]=re>0?1/re:1}t.setCoordShiftAndScale(k,F)}else e.coordShiftAndScaleEnabled===!0&&t.setCoordShiftAndScale(null,null);if(a)if(!a.points&&!a.cells)a.points=new Int32Array(D),a.cells=new Int32Array(D);else{const k=new Int32Array(D+a.points.length);k.set(a.points),a.points=k;const F=new Int32Array(D+a.cells.length);F.set(a.cells),a.cells=F}let A=o.vertexOffset;w=function(F,j){if(a&&(a.points[A]=F,a.cells[A]=m+o.cellOffset),++A,h=F*3,e.coordShiftAndScaleEnabled?(I[P++]=(s[h++]-e.coordShift[0])*e.coordScale[0],I[P++]=(s[h++]-e.coordShift[1])*e.coordScale[1],I[P++]=(s[h++]-e.coordShift[2])*e.coordScale[2]):(I[P++]=s[h++],I[P++]=s[h++],I[P++]=s[h++]),c!==null&&(o.haveCellNormals?g=(m+o.cellOffset)*3:g=F*3,I[P++]=c[g++],I[P++]=c[g++],I[P++]=c[g++]),e.customData.forEach(Y=>{y=F*Y.components;for(let re=0;re{if(r!==null&&(r.constructor!==Float64Array||r.length!==3)){g6("Wrong type for coordShift, expected vec3 or null");return}if(n!==null&&(n.constructor!==Float64Array||n.length!==3)){g6("Wrong type for coordScale, expected vec3 or null");return}(e.coordShift===null||r===null||!Bx(r,e.coordShift))&&(e.coordShift=r),(e.coordScale===null||n===null||!Bx(n,e.coordScale))&&(e.coordScale=n),e.coordShiftAndScaleEnabled=tq(e.coordShift,e.coordScale),e.coordShiftAndScaleEnabled?e.inverseShiftAndScaleMatrix=eq(e.coordShift,e.coordScale):e.inverseShiftAndScaleMatrix=null}}const rq={elementCount:0,stride:0,colorBOStride:0,vertexOffset:0,normalOffset:0,tCoordOffset:0,tCoordComponents:0,colorOffset:0,colorComponents:0,tcoordBO:null,customData:[],coordShift:null,coordScale:null,coordShiftAndScaleEnabled:!1,inverseShiftAndScaleMatrix:null};function FM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,rq,r),kc.extend(t,e,r),ne.setGet(t,e,["colorBO","elementCount","stride","colorBOStride","vertexOffset","normalOffset","tCoordOffset","tCoordComponents","colorOffset","colorComponents","customData"]),ne.get(t,e,["coordShift","coordScale","coordShiftAndScaleEnabled","inverseShiftAndScaleMatrix"]),nq(t,e)}const iq=ne.newInstance(FM);var oq={newInstance:iq,extend:FM};const{vtkErrorMacro:aq}=ne;function sq(t,e){e.classHierarchy.push("vtkShader"),t.compile=()=>{let r=e.context.VERTEX_SHADER;if(!e.source||!e.source.length||e.shaderType==="Unknown")return!1;switch(e.handle!==0&&(e.context.deleteShader(e.handle),e.handle=0),e.shaderType){case"Fragment":r=e.context.FRAGMENT_SHADER;break;case"Vertex":default:r=e.context.VERTEX_SHADER;break}if(e.handle=e.context.createShader(r),e.context.shaderSource(e.handle,e.source),e.context.compileShader(e.handle),!e.context.getShaderParameter(e.handle,e.context.COMPILE_STATUS)){const i=e.context.getShaderInfoLog(e.handle);return aq(`Error compiling shader '${e.source}': ${i}`),e.context.deleteShader(e.handle),e.handle=0,!1}return!0},t.cleanup=()=>{e.shaderType==="Unknown"||e.handle===0||(e.context.deleteShader(e.handle),e.handle=0,e.dirty=!0)}}const cq={shaderType:"Unknown",source:"",error:"",handle:0,dirty:!1,context:null};function UM(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,cq,r),ne.obj(t,e),ne.setGet(t,e,["shaderType","source","error","handle","context"]),sq(t,e)}const lq=ne.newInstance(UM,"vtkShader");var Iw={newInstance:lq,extend:UM};const{vtkErrorMacro:Ms}=ne;function uq(t,e,r,n){const i=typeof r=="string"?r:r.join(` `),o=n===!1?e:new RegExp(e,"g"),a=t.replace(o,i);return{replace:a!==i,result:a}}function fq(t,e){e.classHierarchy.push("vtkShaderProgram"),t.compileShader=()=>e.vertexShader.compile()?e.fragmentShader.compile()?!t.attachShader(e.vertexShader)||!t.attachShader(e.fragmentShader)?(Ms(e.error),0):t.link()?(t.setCompiled(!0),1):(Ms(`Links failed: ${e.error}`),0):(Ms(e.fragmentShader.getSource().split(` `).map((r,n)=>`${n}: ${r}`).join(` `)),Ms(e.fragmentShader.getError()),0):(Ms(e.vertexShader.getSource().split(` @@ -329,7 +329,7 @@ void main() float scalarOpacity = texture2D(pwfTexture1, vec2(intensity * pwfscale0 + pwfshift0, 0.5)).r; gl_FragData[0] = vec4(tcolor, scalarOpacity * opacity); #endif - `)]).result;break;case 2:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);","float intensity = tcolor.r*cscale0 + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(intensity, 0.5)).rgb, pwfscale0*tcolor.g + pwfshift0);"]).result;break;case 3:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = cscale0*texture2D(texture1, tcoordVCVSOutput.st) + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, opacity);"]).result;break;default:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = cscale0*texture2D(texture1, tcoordVCVSOutput.st) + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, tcolor.a);"]).result}e.haveSeenDepthRequest&&(s=Re.substitute(s,"//VTK::ZBuffer::Dec","uniform int depthRequest;").result,s=Re.substitute(s,"//VTK::ZBuffer::Impl",["if (depthRequest == 1) {","float iz = floor(gl_FragCoord.z*65535.0 + 0.1);","float rf = floor(iz/256.0)/255.0;","float gf = mod(iz,256.0)/255.0;","gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }"]).result),n.Vertex=a,n.Fragment=s,t.replaceShaderClip(n,i,o),t.replaceShaderCoincidentOffset(n,i,o)},t.replaceShaderClip=(n,i,o)=>{let a=n.Vertex,s=n.Fragment;if(e.renderable.getNumberOfClippingPlanes()){let c=e.renderable.getNumberOfClippingPlanes();c>6&&(In("OpenGL has a limit of 6 clipping planes"),c=6),a=Re.substitute(a,"//VTK::Clip::Dec",["uniform int numClipPlanes;","uniform vec4 clipPlanes[6];","varying float clipDistancesVSOutput[6];"]).result,a=Re.substitute(a,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);"," }"]).result,s=Re.substitute(s,"//VTK::Clip::Dec",["uniform int numClipPlanes;","varying float clipDistancesVSOutput[6];"]).result,s=Re.substitute(s,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," if (clipDistancesVSOutput[planeNum] < 0.0) discard;"," }"]).result}n.Vertex=a,n.Fragment=s},t.getNeedToRebuildShaders=(n,i,o)=>{var l;const a=e.openGLTexture.getComponents(),s=o.getProperty().getIndependentComponents();let c=!1;return(!e.currentRenderPass&&e.lastRenderPassShaderReplacement||e.currentRenderPass&&e.currentRenderPass.getShaderReplacement()!==e.lastRenderPassShaderReplacement)&&(c=!0),c||e.lastHaveSeenDepthRequest!==e.haveSeenDepthRequest||((l=n.getProgram())==null?void 0:l.getHandle())===0||e.lastTextureComponents!==a||e.lastIndependentComponents!==s?(e.lastHaveSeenDepthRequest=e.haveSeenDepthRequest,e.lastTextureComponents=a,e.lastIndependentComponents=s,!0):!1},t.updateShaders=(n,i,o)=>{if(e.lastBoundBO=n,t.getNeedToRebuildShaders(n,i,o)){const a={Vertex:null,Fragment:null,Geometry:null};t.buildShaders(a,i,o);const s=e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(a.Vertex,a.Fragment,a.Geometry);s!==n.getProgram()&&(n.setProgram(s),n.getVAO().releaseGraphicsResources()),n.getShaderSourceTime().modified()}else e._openGLRenderWindow.getShaderCache().readyShaderProgram(n.getProgram());n.getVAO().bind(),t.setMapperShaderParameters(n,i,o),t.setCameraShaderParameters(n,i,o),t.setPropertyShaderParameters(n,i,o)},t.setMapperShaderParameters=(n,i,o)=>{n.getCABO().getElementCount()&&(e.VBOBuildTime>n.getAttributeUpdateTime().getMTime()||n.getShaderSourceTime().getMTime()>n.getAttributeUpdateTime().getMTime())&&(n.getProgram().isAttributeUsed("vertexMC")&&(n.getVAO().addAttributeArray(n.getProgram(),n.getCABO(),"vertexMC",n.getCABO().getVertexOffset(),n.getCABO().getStride(),e.context.FLOAT,3,e.context.FALSE)||yd("Error setting vertexMC in shader VAO.")),n.getProgram().isAttributeUsed("tcoordMC")&&n.getCABO().getTCoordOffset()&&(n.getVAO().addAttributeArray(n.getProgram(),n.getCABO(),"tcoordMC",n.getCABO().getTCoordOffset(),n.getCABO().getStride(),e.context.FLOAT,n.getCABO().getTCoordComponents(),e.context.FALSE)||yd("Error setting tcoordMC in shader VAO.")),n.getAttributeUpdateTime().modified());const a=e.openGLTexture.getTextureUnit();n.getProgram().setUniformi("texture1",a);const s=e.openGLTexture.getComponents(),c=o.getProperty().getIndependentComponents();if(c)for(let g=0;g6&&(In("OpenGL has a limit of 6 clipping planes"),g=6);const v=n.getCABO().getCoordShiftAndScaleEnabled()?n.getCABO().getInverseShiftAndScaleMatrix():null,y=v?ri(e.imagematinv,o.getMatrix()):o.getMatrix();v&&(Fn(y,y),On(y,y,v),Fn(y,y)),Fn(e.imagemat,e.currentInput.getIndexToWorld()),On(e.imagematinv,y,e.imagemat);const m=[];for(let w=0;w{const a=n.getProgram(),s=e.openGLImageSlice.getKeyMatrices(),c=e.currentInput,l=c.getIndexToWorld();On(e.imagemat,s.mcwc,l);const f=e.openGLCamera.getKeyMatrices(i);if(On(e.imagemat,f.wcpc,e.imagemat),n.getCABO().getCoordShiftAndScaleEnabled()){const d=n.getCABO().getInverseShiftAndScaleMatrix();On(e.imagemat,e.imagemat,d)}if(a.setUniformMatrix("MCPCMatrix",e.imagemat),o.getProperty().getUseLabelOutline()===!0){const d=c.getWorldToIndex(),h=c.getDimensions();let g=e.renderable.getClosestIJKAxis().ijkMode;g===aa.NONE&&(g=aa.K),a.setUniform3i("imageDimensions",h[0],h[1],h[2]),a.setUniformi("sliceAxis",g),a.setUniformMatrix("vWCtoIDX",d);const p=e.openGLCamera.getKeyMatrices(i);oi(e.projectionToWorld,p.wcpc),e.openGLCamera.getKeyMatrices(i),a.setUniformMatrix("PCWCMatrix",e.projectionToWorld);const v=t.getRenderTargetSize();a.setUniformf("vpWidth",v[0]),a.setUniformf("vpHeight",v[1]);const y=t.getRenderTargetOffset();a.setUniformf("vpOffsetX",y[0]/v[0]),a.setUniformf("vpOffsetY",y[1]/v[1])}},t.setPropertyShaderParameters=(n,i,o)=>{const a=n.getProgram(),c=o.getProperty().getOpacity();a.setUniformf("opacity",c)},t.renderPieceStart=(n,i)=>{t.updateBufferObjects(n,i),e.lastBoundBO=null},t.renderPieceDraw=(n,i)=>{const o=e.context;e.openGLTexture.activate(),e.colorTexture.activate(),e.labelOutlineThicknessTexture.activate(),e.pwfTexture.activate(),e.tris.getCABO().getElementCount()&&(t.updateShaders(e.tris,n,i),o.drawArrays(o.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release()),e.openGLTexture.deactivate(),e.colorTexture.deactivate(),e.labelOutlineThicknessTexture.deactivate(),e.pwfTexture.deactivate()},t.renderPieceFinish=(n,i)=>{},t.renderPiece=(n,i)=>{if(t.invokeEvent({type:"StartEvent"}),e.renderable.update(),e.currentInput=e.renderable.getCurrentImage(),t.invokeEvent({type:"EndEvent"}),!e.currentInput){yd("No input!");return}t.renderPieceStart(n,i),t.renderPieceDraw(n,i),t.renderPieceFinish(n,i)},t.computeBounds=(n,i)=>{if(!t.getInput()){ih(e.bounds);return}e.bounds=t.getInput().getBounds()},t.updateBufferObjects=(n,i)=>{t.getNeedToRebuildBufferObjects(n,i)&&t.buildBufferObjects(n,i)},t.getNeedToRebuildBufferObjects=(n,i)=>{var o,a,s,c;return e.VBOBuildTime.getMTime(){var I,P,M,L;const o=e.currentInput;if(!o)return;const a=o.getPointData()&&o.getPointData().getScalars();if(!a)return;const s=a.getDataType(),c=a.getNumberOfComponents(),l=i.getProperty(),f=l.getInterpolationType(),u=l.getIndependentComponents(),d=u?c:1,h=u?2*d:1,g=l.getRGBTransferFunction(),p=ec(g,u,d),v=e._openGLRenderWindow.getGraphicsResourceForObject(g);if(!((I=v==null?void 0:v.oglObject)!=null&&I.getHandle())||(v==null?void 0:v.hash)!==p){e.colorTexture=Dr.newInstance({resizable:!0}),e.colorTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const V=1024,G=V*h*3,A=new Uint8ClampedArray(G);if(f===kf.NEAREST?(e.colorTexture.setMinificationFilter(Bt.NEAREST),e.colorTexture.setMagnificationFilter(Bt.NEAREST)):(e.colorTexture.setMinificationFilter(Bt.LINEAR),e.colorTexture.setMagnificationFilter(Bt.LINEAR)),g){const k=new Float32Array(V*3);for(let F=0;F1?1:0;const F=[aa.X,aa.Y,aa.Z].includes(e.renderable.getSlicingMode())?_:T,j=o.getSpatialExtent(),Y=a.getData();let re=null;if(S===aa.I){re=new Y.constructor(V[2]*V[1]*c);let Se=0;for(let B=0;B{var c;const i=n.getProperty().getLabelOutlineThicknessByReference(),o=e._openGLRenderWindow.getGraphicsResourceForObject(i),a=`${i.join("-")}`;if(!((c=o==null?void 0:o.oglObject)!=null&&c.getHandle())||(o==null?void 0:o.hash)!==a){const d=new Uint8Array(1024);for(let h=0;h<1024;++h){const g=typeof i[h]<"u"?i[h]:i[0];d[h]=g}e.labelOutlineThicknessTexture=Dr.newInstance({resizable:!1}),e.labelOutlineThicknessTexture.setOpenGLRenderWindow(e._openGLRenderWindow),e.labelOutlineThicknessTexture.resetFormatAndType(),e.labelOutlineThicknessTexture.setMinificationFilter(Bt.NEAREST),e.labelOutlineThicknessTexture.setMagnificationFilter(Bt.NEAREST),e.labelOutlineThicknessTexture.create2DFromRaw(1024,1,1,pn.UNSIGNED_CHAR,d),i&&(e._openGLRenderWindow.setGraphicsResourceForObject(i,e.labelOutlineThicknessTexture,a),i!==e._labelOutlineThicknessArray&&(e._openGLRenderWindow.registerGraphicsResourceUser(i,t),e._openGLRenderWindow.unregisterGraphicsResourceUser(e._labelOutlineThicknessArray,t)),e._labelOutlineThicknessArray=i)}else e.labelOutlineThicknessTexture=o.oglObject},t.getRenderTargetSize=()=>{if(e._useSmallViewport)return[e._smallViewportWidth,e._smallViewportHeight];const{usize:n,vsize:i}=e._openGLRenderer.getTiledSizeAndOrigin();return[n,i]},t.getRenderTargetOffset=()=>{const{lowerLeftU:n,lowerLeftV:i}=e._openGLRenderer.getTiledSizeAndOrigin();return[n,i]},t.delete=a1(()=>{e._openGLRenderWindow&&r(e._openGLRenderWindow)},t.delete)}const PJ={VBOBuildTime:0,VBOBuildString:null,openGLTexture:null,tris:null,imagemat:null,imagematinv:null,colorTexture:null,pwfTexture:null,labelOutlineThicknessTexture:null,labelOutlineThicknessTextureString:null,lastHaveSeenDepthRequest:!1,haveSeenDepthRequest:!1,lastTextureComponents:0};function RJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,PJ,r),gi.extend(t,e,r),wu.implementReplaceShaderCoincidentOffset(t,e,r),wu.implementBuildShadersWithReplacements(t,e,r),e.tris=Lu.newInstance(),e.imagemat=Vt(new Float64Array(16)),e.imagematinv=Vt(new Float64Array(16)),e.projectionToWorld=Vt(new Float64Array(16)),e.idxToView=Vt(new Float64Array(16)),e.idxNormalMatrix=xs(new Float64Array(9)),e.modelToView=Vt(new Float64Array(16)),e.projectionToView=Vt(new Float64Array(16)),Di(t,e,[]),e.VBOBuildTime={},br(e.VBOBuildTime),MJ(t,e)}const QP=hr(RJ,"vtkOpenGLImageMapper");var LJ={newInstance:QP};Ki("vtkAbstractImageMapper",QP);const lf={MAX:0,MIN:1,AVERAGE:2},{vtkErrorMacro:dm}=ne;function AJ(t,e){e.classHierarchy.push("vtkOpenGLImageCPRMapper");function r(n){[e._scalars,e._colorTransferFunc,e._pwFunc].forEach(i=>n.unregisterGraphicsResourceUser(i,t))}t.buildPass=n=>{if(n){e.currentRenderPass=null,e.openGLImageSlice=t.getFirstAncestorOfType("vtkOpenGLImageSlice"),e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer");const i=e._openGLRenderWindow;e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow"),i&&!i.isDeleted()&&i!==e._openGLRenderWindow&&r(i),e.context=e._openGLRenderWindow.getContext(),e.openGLCamera=e._openGLRenderer.getViewNodeFor(e._openGLRenderer.getRenderable().getActiveCamera()),e.tris.setOpenGLRenderWindow(e._openGLRenderWindow)}},t.opaquePass=(n,i)=>{n&&(e.currentRenderPass=i,t.render())},t.opaqueZBufferPass=n=>{n&&(e.haveSeenDepthRequest=!0,e.renderDepth=!0,t.render(),e.renderDepth=!1)},t.getCoincidentParameters=(n,i)=>e.renderable.getResolveCoincidentTopology()===Ts.PolygonOffset?e.renderable.getCoincidentTopologyPolygonOffsetParameters():null,t.render=()=>{const n=e.openGLImageSlice.getRenderable(),i=e._openGLRenderer.getRenderable();t.renderPiece(i,n)},t.renderPiece=(n,i)=>{t.invokeEvent({type:"StartEvent"}),e.renderable.update(),t.invokeEvent({type:"EndEvent"}),e.renderable.preRenderCheck()&&(e.currentImageDataInput=e.renderable.getInputData(0),e.currentCenterlineInput=e.renderable.getOrientedCenterline(),t.renderPieceStart(n,i),t.renderPieceDraw(n,i),t.renderPieceFinish(n,i))},t.renderPieceStart=(n,i)=>{t.updateBufferObjects(n,i)},t.renderPieceDraw=(n,i)=>{const o=e.context;e.volumeTexture.activate(),e.colorTexture.activate(),e.pwfTexture.activate(),e.tris.getCABO().getElementCount()&&(t.updateShaders(e.tris,n,i),o.drawArrays(o.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release()),e.volumeTexture.deactivate(),e.colorTexture.deactivate(),e.pwfTexture.deactivate()},t.renderPieceFinish=(n,i)=>{},t.updateBufferObjects=(n,i)=>{t.getNeedToRebuildBufferObjects(n,i)&&t.buildBufferObjects(n,i),i.getProperty().getInterpolationType()===kf.NEAREST?(e.volumeTexture.setMinificationFilter(Bt.NEAREST),e.volumeTexture.setMagnificationFilter(Bt.NEAREST),e.colorTexture.setMinificationFilter(Bt.NEAREST),e.colorTexture.setMagnificationFilter(Bt.NEAREST),e.pwfTexture.setMinificationFilter(Bt.NEAREST),e.pwfTexture.setMagnificationFilter(Bt.NEAREST)):(e.volumeTexture.setMinificationFilter(Bt.LINEAR),e.volumeTexture.setMagnificationFilter(Bt.LINEAR),e.colorTexture.setMinificationFilter(Bt.LINEAR),e.colorTexture.setMagnificationFilter(Bt.LINEAR),e.pwfTexture.setMinificationFilter(Bt.LINEAR),e.pwfTexture.setMagnificationFilter(Bt.LINEAR))},t.getNeedToRebuildBufferObjects=(n,i)=>{var a;const o=e.VBOBuildTime.getMTime();return o{var D,b,I,P;const o=e.currentImageDataInput,a=e.currentCenterlineInput,s=(D=o==null?void 0:o.getPointData())==null?void 0:D.getScalars();if(!s)return;const c=e._openGLRenderWindow.getGraphicsResourceForObject(s),l=tT(o,s),f=!((b=c==null?void 0:c.oglObject)!=null&&b.getHandle())||(c==null?void 0:c.hash)!==l,u=e.renderable.getUpdatedExtents(),d=!!u.length;if(f){e.volumeTexture=Dr.newInstance(),e.volumeTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const M=o.getDimensions();e.volumeTexture.setOglNorm16Ext(e.context.getExtension("EXT_texture_norm16")),e.volumeTexture.resetFormatAndType(),e.volumeTexture.create3DFilterableFromDataArray(M[0],M[1],M[2],s,e.renderable.getPreferSizeOverAccuracy()),e._openGLRenderWindow.setGraphicsResourceForObject(s,e.volumeTexture,l),s!==e._scalars&&(e._openGLRenderWindow.registerGraphicsResourceUser(s,t),e._openGLRenderWindow.unregisterGraphicsResourceUser(e._scalars,t)),e._scalars=s}else e.volumeTexture=c.oglObject;if(d){e.renderable.setUpdatedExtents([]);const M=o.getDimensions();e.volumeTexture.create3DFilterableFromDataArray(M[0],M[1],M[2],s,!1,u)}const h=s.getNumberOfComponents(),g=i.getProperty(),p=g.getIndependentComponents(),v=p?h:1,y=p?2*v:1,m=g.getRGBTransferFunction(),w=ec(m,p,v),x=e._openGLRenderWindow.getGraphicsResourceForObject(m);if(!((I=x==null?void 0:x.oglObject)!=null&&I.getHandle())||(x==null?void 0:x.hash)!==w){const L=1024*y*3,V=new Uint8ClampedArray(L);if(e.colorTexture=Dr.newInstance(),e.colorTexture.setOpenGLRenderWindow(e._openGLRenderWindow),m){const G=new Float32Array(3072);for(let A=0;A{const a=e.volumeTexture.getComponents(),s=o.getProperty().getIndependentComponents(),c=!!e.renderable.getCenterPoint(),l=e.renderable.getUseUniformOrientation(),f=e.renderable.isProjectionEnabled()&&e.renderable.getProjectionMode();return n.getProgram()===0||e.lastUseCenterPoint!==c||e.lastUseUniformOrientation!==l||e.lastProjectionMode!==f||e.lastHaveSeenDepthRequest!==e.haveSeenDepthRequest||e.lastTextureComponents!==a||e.lastIndependentComponents!==s?(e.lastUseCenterPoint=c,e.lastUseUniformOrientation=l,e.lastProjectionMode=f,e.lastHaveSeenDepthRequest=e.haveSeenDepthRequest,e.lastTextureComponents=a,e.lastIndependentComponents=s,!0):!1},t.buildShaders=(n,i,o)=>{t.getShaderTemplate(n,i,o),t.replaceShaderValues(n,i,o)},t.replaceShaderValues=(n,i,o)=>{let a=n.Vertex,s=n.Fragment;const c=["vec3 applyQuaternionToVec(vec4 q, vec3 v) {"," float uvx = q.y * v.z - q.z * v.y;"," float uvy = q.z * v.x - q.x * v.z;"," float uvz = q.x * v.y - q.y * v.x;"," float uuvx = q.y * uvz - q.z * uvy;"," float uuvy = q.z * uvx - q.x * uvz;"," float uuvz = q.x * uvy - q.y * uvx;"," float w2 = q.w * 2.0;"," uvx *= w2;"," uvy *= w2;"," uvz *= w2;"," uuvx *= 2.0;"," uuvy *= 2.0;"," uuvz *= 2.0;"," return vec3(v.x + uvx + uuvx, v.y + uvy + uuvy, v.z + uvz + uuvz);","}"];a=Re.substitute(a,"//VTK::Camera::Dec",["uniform mat4 MCPCMatrix;"]).result,a=Re.substitute(a,"//VTK::PositionVC::Impl",[" gl_Position = MCPCMatrix * vertexMC;"]).result;const l=["attribute vec3 centerlinePosition;","attribute float quadIndex;","uniform float width;","out vec2 quadOffsetVSOutput;","out vec3 centerlinePosVSOutput;"],f=e.renderable.isProjectionEnabled(),u=e.renderable.getUseUniformOrientation();u?(l.push("out vec3 samplingDirVSOutput;","uniform vec4 centerlineOrientation;","uniform vec3 tangentDirection;",...c),f&&l.push("out vec3 projectionDirVSOutput;","uniform vec3 bitangentDirection;")):l.push("out vec4 centerlineTopOrientationVSOutput;","out vec4 centerlineBotOrientationVSOutput;","attribute vec4 centerlineTopOrientation;","attribute vec4 centerlineBotOrientation;"),a=Re.substitute(a,"//VTK::Color::Dec",l).result;const d=["quadOffsetVSOutput = vec2(width * (mod(quadIndex, 2.0) == 0.0 ? -0.5 : 0.5), quadIndex > 1.0 ? 0.0 : 1.0);","centerlinePosVSOutput = centerlinePosition;"];u?(d.push("samplingDirVSOutput = applyQuaternionToVec(centerlineOrientation, tangentDirection);"),f&&d.push("projectionDirVSOutput = applyQuaternionToVec(centerlineOrientation, bitangentDirection);")):d.push("centerlineTopOrientationVSOutput = centerlineTopOrientation;","centerlineBotOrientationVSOutput = centerlineBotOrientation;"),a=Re.substitute(a,"//VTK::Color::Impl",d).result;const h=e.volumeTexture.getComponents(),g=o.getProperty().getIndependentComponents();let p=["uniform mat4 MCTCMatrix; // Model coordinates to texture coordinates","in vec2 quadOffsetVSOutput;","in vec3 centerlinePosVSOutput;","uniform highp sampler3D volumeTexture;","uniform sampler2D colorTexture1;","uniform sampler2D pwfTexture1;","uniform float opacity;","uniform vec4 backgroundColor;","uniform float cshift0;","uniform float cscale0;","uniform float pwfshift0;","uniform float pwfscale0;"];f&&p.push("uniform vec3 volumeSizeMC;","uniform int projectionSlabNumberOfSamples;","uniform float projectionConstantOffset;","uniform float projectionStepLength;"),u?(p.push("in vec3 samplingDirVSOutput;"),f&&p.push("in vec3 projectionDirVSOutput;")):(p.push("uniform vec3 tangentDirection;","in vec4 centerlineTopOrientationVSOutput;","in vec4 centerlineBotOrientationVSOutput;",...c),f&&p.push("uniform vec3 bitangentDirection;"));const v=e.renderable.getCenterPoint();if(v&&p.push("uniform vec3 globalCenterPoint;"),g){for(let m=1;m 0.999 || qCosAngle < -0.999) {"," // Use LERP instead of SLERP when the two quaternions are close or opposite"," interpolatedOrientation = normalize(mix(q0, q1, quadOffsetVSOutput.y));","} else {"," float omega = acos(qCosAngle);"," interpolatedOrientation = normalize(sin((1.0 - quadOffsetVSOutput.y) * omega) * q0 + sin(quadOffsetVSOutput.y * omega) * q1);","}","vec3 samplingDirection = applyQuaternionToVec(interpolatedOrientation, tangentDirection);"),f&&y.push("vec3 projectionDirection = applyQuaternionToVec(interpolatedOrientation, bitangentDirection);")),v?y.push("float baseOffset = dot(samplingDirection, globalCenterPoint - centerlinePosVSOutput);","float horizontalOffset = quadOffsetVSOutput.x + baseOffset;"):y.push("float horizontalOffset = quadOffsetVSOutput.x;"),y.push("vec3 volumePosMC = centerlinePosVSOutput + horizontalOffset * samplingDirection;","vec3 volumePosTC = (MCTCMatrix * vec4(volumePosMC, 1.0)).xyz;","if (any(lessThan(volumePosTC, vec3(0.0))) || any(greaterThan(volumePosTC, vec3(1.0))))","{"," // set the background color and exit"," gl_FragData[0] = backgroundColor;"," return;","}"),f){const m=e.renderable.getProjectionMode();switch(m){case lf.MIN:y.push("const vec4 initialProjectionTextureValue = vec4(1.0);");break;case lf.MAX:case lf.AVERAGE:default:y.push("const vec4 initialProjectionTextureValue = vec4(0.0);");break}switch(y.push("vec3 projectionScaledDirection = projectionDirection / volumeSizeMC;","vec3 projectionStep = projectionStepLength * projectionScaledDirection;","vec3 projectionStartPosition = volumePosTC + projectionConstantOffset * projectionScaledDirection;","vec4 tvalue = initialProjectionTextureValue;","for (int projectionSampleIdx = 0; projectionSampleIdx < projectionSlabNumberOfSamples; ++projectionSampleIdx) {"," vec3 projectionSamplePosition = projectionStartPosition + float(projectionSampleIdx) * projectionStep;"," vec4 sampledTextureValue = texture(volumeTexture, projectionSamplePosition);"),m){case lf.MAX:y.push(" tvalue = max(tvalue, sampledTextureValue);");break;case lf.MIN:y.push(" tvalue = min(tvalue, sampledTextureValue);");break;case lf.AVERAGE:default:y.push(" tvalue = tvalue + sampledTextureValue;");break}y.push("}"),m===lf.AVERAGE&&y.push("tvalue = tvalue / float(projectionSlabNumberOfSamples);")}else y.push("vec4 tvalue = texture(volumeTexture, volumePosTC);");if(g){const m=["r","g","b","a"];for(let w=0;w{let a=n.Vertex,s=n.Fragment;if(e.renderable.getNumberOfClippingPlanes()){let c=e.renderable.getNumberOfClippingPlanes();c>6&&(ne.vtkErrorMacro("OpenGL has a limit of 6 clipping planes"),c=6),a=Re.substitute(a,"//VTK::Clip::Dec",["uniform int numClipPlanes;","uniform vec4 clipPlanes[6];","varying float clipDistancesVSOutput[6];"]).result,a=Re.substitute(a,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);"," }"]).result,s=Re.substitute(s,"//VTK::Clip::Dec",["uniform int numClipPlanes;","varying float clipDistancesVSOutput[6];"]).result,s=Re.substitute(s,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," if (clipDistancesVSOutput[planeNum] < 0.0) discard;"," }"]).result}n.Vertex=a,n.Fragment=s},t.getShaderTemplate=(n,i,o)=>{n.Vertex=eT,n.Fragment=p1,n.Geometry=""},t.setMapperShaderParameters=(n,i,o)=>{const a=n.getProgram(),s=n.getCABO();s.getElementCount()&&(e.VBOBuildTime.getMTime()>n.getAttributeUpdateTime().getMTime()||n.getShaderSourceTime().getMTime()>n.getAttributeUpdateTime().getMTime())&&(a.isAttributeUsed("vertexMC")&&(n.getVAO().addAttributeArray(a,s,"vertexMC",s.getVertexOffset(),s.getStride(),e.context.FLOAT,3,e.context.FALSE)||dm("Error setting vertexMC in shader VAO.")),n.getCABO().getCustomData().forEach(h=>{h&&a.isAttributeUsed(h.name)&&!n.getVAO().addAttributeArray(a,s,h.name,h.offset,s.getStride(),e.context.FLOAT,h.components,e.context.FALSE)&&dm(`Error setting ${h.name} in shader VAO.`)}),n.getAttributeUpdateTime().modified());const c=e.volumeTexture.getTextureUnit();if(a.setUniformi("volumeTexture",c),a.setUniformf("width",e.renderable.getWidth()),n.getProgram().setUniform4fv("backgroundColor",e.renderable.getBackgroundColor()),a.isUniformUsed("tangentDirection")){const h=e.renderable.getTangentDirection();n.getProgram().setUniform3fArray("tangentDirection",h)}if(a.isUniformUsed("bitangentDirection")){const h=e.renderable.getBitangentDirection();n.getProgram().setUniform3fArray("bitangentDirection",h)}if(a.isUniformUsed("centerlineOrientation")){const h=e.renderable.getUniformOrientation();n.getProgram().setUniform4fv("centerlineOrientation",h)}if(a.isUniformUsed("globalCenterPoint")){const h=e.renderable.getCenterPoint();a.setUniform3fArray("globalCenterPoint",h)}if(e.renderable.isProjectionEnabled()){const h=e.currentImageDataInput,g=h.getSpacing(),p=h.getDimensions(),v=e.renderable.getProjectionSlabThickness(),y=e.renderable.getProjectionSlabNumberOfSamples(),m=BK([],g,p);a.setUniform3fArray("volumeSizeMC",m),a.setUniformi("projectionSlabNumberOfSamples",y);const w=-.5*v;a.setUniformf("projectionConstantOffset",w);const x=v/(y-1);a.setUniformf("projectionStepLength",x)}const l=e.currentImageDataInput,f=l.getWorldToIndex(),u=P_(new Float32Array(16),PM([],l.getDimensions())),d=yv(u,u,f);if(a.setUniformMatrix("MCTCMatrix",d),e.haveSeenDepthRequest&&n.getProgram().setUniformi("depthRequest",e.renderDepth?1:0),e.renderable.getNumberOfClippingPlanes()){let h=e.renderable.getNumberOfClippingPlanes();h>6&&(ne.vtkErrorMacro("OpenGL has a limit of 6 clipping planes"),h=6);const p=s.getCoordShiftAndScaleEnabled()?s.getInverseShiftAndScaleMatrix():null,v=p?ri(e.imagematinv,o.getMatrix()):o.getMatrix();p&&(Fn(v,v),On(v,v,p),Fn(v,v)),Fn(e.imagemat,e.currentImageDataInput.getIndexToWorld()),On(e.imagematinv,v,e.imagemat);const y=[];for(let m=0;m{const a=e.openGLImageSlice.getKeyMatrices().mcwc,s=e.openGLCamera.getKeyMatrices(i).wcpc;if(On(e.imagemat,s,a),n.getCABO().getCoordShiftAndScaleEnabled()){const c=n.getCABO().getInverseShiftAndScaleMatrix();On(e.imagemat,e.imagemat,c)}n.getProgram().setUniformMatrix("MCPCMatrix",e.imagemat)},t.setPropertyShaderParameters=(n,i,o)=>{const a=n.getProgram(),s=o.getProperty(),c=s.getOpacity();a.setUniformf("opacity",c);const l=e.volumeTexture.getComponents(),f=s.getIndependentComponents();if(f)for(let g=0;g{if(t.getNeedToRebuildShaders(n,i,o)){const a={Vertex:null,Fragment:null,Geometry:null};t.buildShaders(a,i,o);const s=e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(a.Vertex,a.Fragment,a.Geometry);s!==n.getProgram()&&(n.setProgram(s),n.getVAO().releaseGraphicsResources()),n.getShaderSourceTime().modified()}else e._openGLRenderWindow.getShaderCache().readyShaderProgram(n.getProgram());n.getVAO().bind(),t.setMapperShaderParameters(n,i,o),t.setCameraShaderParameters(n,i,o),t.setPropertyShaderParameters(n,i,o)},t.delete=ne.chain(()=>{e._openGLRenderWindow&&r(e._openGLRenderWindow)},t.delete)}const NJ={currentRenderPass:null,volumeTexture:null,colorTexture:null,pwfTexture:null,tris:null,lastHaveSeenDepthRequest:!1,haveSeenDepthRequest:!1,lastTextureComponents:0,lastIndependentComponents:0,imagemat:null,imagematinv:null};function kJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,NJ,r),gi.extend(t,e,r),wu.implementReplaceShaderCoincidentOffset(t,e,r),ne.algo(t,e,2,0),e.tris=Lu.newInstance(),e.volumeTexture=null,e.colorTexture=null,e.pwfTexture=null,e.imagemat=Vt(new Float64Array(16)),e.imagematinv=Vt(new Float64Array(16)),e.VBOBuildTime={},ne.obj(e.VBOBuildTime,{mtime:0}),AJ(t,e)}const eR=ne.newInstance(kJ,"vtkOpenGLImageCPRMapper"),VJ={};var FJ={newInstance:eR,...VJ};Ki("vtkImageCPRMapper",eR);function UJ(t,e){e.classHierarchy.push("vtkOpenGLImageSlice"),t.buildPass=r=>{if(!(!e.renderable||!e.renderable.getVisibility())&&r){if(!e.renderable)return;e._openGLRenderWindow=t.getLastAncestorOfType("vtkOpenGLRenderWindow"),e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e.context=e._openGLRenderWindow.getContext(),t.prepareNodes(),t.addMissingNode(e.renderable.getMapper()),t.removeUnusedNodes()}},t.traverseZBufferPass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.traverseOpaqueZBufferPass=r=>t.traverseOpaquePass(r),t.traverseOpaquePass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||!e.renderable.getIsOpaque()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.traverseTranslucentPass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||e.renderable.getIsOpaque()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.queryPass=(r,n)=>{if(r){if(!e.renderable||!e.renderable.getVisibility())return;e.renderable.getIsOpaque()?n.incrementOpaqueActorCount():n.incrementTranslucentActorCount()}},t.zBufferPass=(r,n)=>t.opaquePass(r,n),t.opaqueZBufferPass=(r,n)=>t.opaquePass(r,n),t.opaquePass=(r,n)=>{r&&e.context.depthMask(!0)},t.translucentPass=(r,n)=>{e.context.depthMask(!r)},t.getKeyMatrices=()=>(e.renderable.getMTime()>e.keyMatrixTime.getMTime()&&(ri(e.keyMatrices.mcwc,e.renderable.getMatrix()),Fn(e.keyMatrices.mcwc,e.keyMatrices.mcwc),e.keyMatrixTime.modified()),e.keyMatrices)}const BJ={context:null,keyMatrixTime:null,keyMatrices:null};function GJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,BJ,r),gi.extend(t,e,r),e.keyMatrixTime={},br(e.keyMatrixTime,{mtime:0}),e.keyMatrices={mcwc:Vt(new Float64Array(16))},Di(t,e,["context"]),UJ(t,e)}const tR=hr(GJ,"vtkOpenGLImageSlice");var WJ={newInstance:tR};Ki("vtkImageSlice",tR);const{vtkDebugMacro:zJ}=So;function $J(t,e){e.classHierarchy.push("vtkOpenGLPixelSpaceCallbackMapper"),t.opaquePass=(r,n)=>{e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow");const i=e._openGLRenderer.getAspectRatio(),o=e._openGLRenderer?e._openGLRenderer.getRenderable().getActiveCamera():null,a=e._openGLRenderer.getTiledSizeAndOrigin();let s=null;if(e.renderable.getUseZValues()){const c=n.getZBufferTexture(),l=Math.floor(c.getWidth()),f=Math.floor(c.getHeight()),u=e._openGLRenderWindow.getContext();c.bind();const d=n.getFramebuffer();d?d.saveCurrentBindingsAndBuffers():zJ("No framebuffer to save/restore");const h=u.createFramebuffer();u.bindFramebuffer(u.FRAMEBUFFER,h),u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,c.getHandle(),0),u.checkFramebufferStatus(u.FRAMEBUFFER)===u.FRAMEBUFFER_COMPLETE&&(s=new Uint8Array(l*f*4),u.viewport(0,0,l,f),u.readPixels(0,0,l,f,u.RGBA,u.UNSIGNED_BYTE,s)),d&&d.restorePreviousBindingsAndBuffers(),u.deleteFramebuffer(h)}e.renderable.invokeCallback(e.renderable.getInputData(),o,i,a,s)},t.queryPass=(r,n)=>{r&&e.renderable.getUseZValues()&&n.requestDepth()}}const jJ={};function HJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,jJ,r),gi.extend(t,e,r),$J(t,e)}const nR=hr(HJ,"vtkOpenGLPixelSpaceCallbackMapper");var KJ={newInstance:nR};Ki("vtkPixelSpaceCallbackMapper",nR);const{vtkDebugMacro:qJ}=So;function XJ(t,e){e.classHierarchy.push("vtkOpenGLRenderer"),t.buildPass=r=>{if(r){if(!e.renderable)return;t.updateLights(),t.prepareNodes(),t.addMissingNode(e.renderable.getActiveCamera()),t.addMissingNodes(e.renderable.getViewPropsWithNestedProps()),t.removeUnusedNodes()}},t.updateLights=()=>{let r=0;const n=e.renderable.getLightsByReference();for(let i=0;i0&&r++;return r||(qJ("No lights are on, creating one."),e.renderable.createLight()),r},t.zBufferPass=r=>{if(r){let n=0;const i=e.context;e.renderable.getTransparent()||(e.context.clearColor(1,0,0,1),n|=i.COLOR_BUFFER_BIT),e.renderable.getPreserveDepthBuffer()||(i.clearDepth(1),n|=i.DEPTH_BUFFER_BIT,e.context.depthMask(!0));const o=t.getTiledSizeAndOrigin();i.enable(i.SCISSOR_TEST),i.scissor(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),i.viewport(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),i.colorMask(!0,!0,!0,!0),n&&i.clear(n),i.enable(i.DEPTH_TEST)}},t.opaqueZBufferPass=r=>t.zBufferPass(r),t.cameraPass=r=>{r&&t.clear()},t.getAspectRatio=()=>{const r=e._parent.getSizeByReference(),n=e.renderable.getViewportByReference();return r[0]*(n[2]-n[0])/((n[3]-n[1])*r[1])},t.getTiledSizeAndOrigin=()=>{const r=e.renderable.getViewportByReference(),n=[0,0,1,1],i=r[0]-n[0],o=r[1]-n[1],a=e._parent.normalizedDisplayToDisplay(i,o),s=Math.round(a[0]),c=Math.round(a[1]),l=r[2]-n[0],f=r[3]-n[1],u=e._parent.normalizedDisplayToDisplay(l,f);let d=Math.round(u[0])-s,h=Math.round(u[1])-c;return d<0&&(d=0),h<0&&(h=0),{usize:d,vsize:h,lowerLeftU:s,lowerLeftV:c}},t.clear=()=>{let r=0;const n=e.context;if(!e.renderable.getTransparent()){const o=e.renderable.getBackgroundByReference();n.clearColor(o[0],o[1],o[2],o[3]),r|=n.COLOR_BUFFER_BIT}e.renderable.getPreserveDepthBuffer()||(n.clearDepth(1),r|=n.DEPTH_BUFFER_BIT,n.depthMask(!0)),n.colorMask(!0,!0,!0,!0);const i=t.getTiledSizeAndOrigin();n.enable(n.SCISSOR_TEST),n.scissor(i.lowerLeftU,i.lowerLeftV,i.usize,i.vsize),n.viewport(i.lowerLeftU,i.lowerLeftV,i.usize,i.vsize),r&&n.clear(r),n.enable(n.DEPTH_TEST)},t.releaseGraphicsResources=()=>{e.selector!==null&&e.selector.releaseGraphicsResources(),e.renderable&&e.renderable.getViewProps().forEach(r=>{r.modified()})},t.setOpenGLRenderWindow=r=>{e._openGLRenderWindow!==r&&(t.releaseGraphicsResources(),e._openGLRenderWindow=r,e.context=null,r&&(e.context=e._openGLRenderWindow.getContext()))}}const YJ={context:null,_openGLRenderWindow:null,selector:null};function JJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,YJ,r),gi.extend(t,e,r),Fo(t,e,["shaderCache"]),Di(t,e,["selector"]),o1(t,e,["openGLRenderWindow"]),XJ(t,e)}const rR=hr(JJ,"vtkOpenGLRenderer");var ZJ={newInstance:rR};Ki("vtkRenderer",rR);const{vtkErrorMacro:k6}=So;function QJ(t,e){e.classHierarchy.push("vtkOpenGLSkybox"),t.buildPass=r=>{if(r){e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getParent(),e.context=e._openGLRenderWindow.getContext(),e.tris.setOpenGLRenderWindow(e._openGLRenderWindow),e.openGLTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const n=e._openGLRenderer.getRenderable();e.openGLCamera=e._openGLRenderer.getViewNodeFor(n.getActiveCamera())}},t.queryPass=(r,n)=>{if(r){if(!e.renderable||!e.renderable.getVisibility())return;n.incrementOpaqueActorCount()}},t.opaquePass=(r,n)=>{if(r&&!e._openGLRenderer.getSelector()){t.updateBufferObjects(),e.context.depthMask(!0),e._openGLRenderWindow.getShaderCache().readyShaderProgram(e.tris.getProgram()),e.openGLTexture.render(e._openGLRenderWindow);const i=e.openGLTexture.getTextureUnit();e.tris.getProgram().setUniformi("sbtexture",i);const o=e._openGLRenderer.getRenderable(),a=e.openGLCamera.getKeyMatrices(o),s=new Float64Array(16);if(oi(s,a.wcpc),e.tris.getProgram().setUniformMatrix("IMCPCMatrix",s),e.lastFormat==="box"){const c=o.getActiveCamera().getPosition();e.tris.getProgram().setUniform3f("camPos",c[0],c[1],c[2])}e.tris.getVAO().bind(),e.context.drawArrays(e.context.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release(),e.openGLTexture.deactivate()}},t.updateBufferObjects=()=>{if(!e.tris.getCABO().getElementCount()){const n=new Float32Array(12);for(let s=0;s<4;s++)n[s*3]=s%2*2-1,n[s*3+1]=s>1?1:-1,n[s*3+2]=1;const i=Yt.newInstance({numberOfComponents:3,values:n});i.setName("points");const o=new Uint16Array(8);o[0]=3,o[1]=0,o[2]=1,o[3]=3,o[4]=3,o[5]=0,o[6]=3,o[7]=2;const a=Yt.newInstance({numberOfComponents:1,values:o});e.tris.getCABO().createVBO(a,"polys",Wa.SURFACE,{points:i,cellOffset:0})}e.renderable.getFormat()!==e.lastFormat&&(e.lastFormat=e.renderable.getFormat(),e.lastFormat==="box"&&e.tris.setProgram(e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(`//VTK::System::Dec + `)]).result;break;case 2:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);","float intensity = tcolor.r*cscale0 + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(intensity, 0.5)).rgb, pwfscale0*tcolor.g + pwfshift0);"]).result;break;case 3:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = cscale0*texture2D(texture1, tcoordVCVSOutput.st) + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, opacity);"]).result;break;default:s=Re.substitute(s,"//VTK::TCoord::Impl",["vec4 tcolor = cscale0*texture2D(texture1, tcoordVCVSOutput.st) + cshift0;","gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,"," texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, tcolor.a);"]).result}e.haveSeenDepthRequest&&(s=Re.substitute(s,"//VTK::ZBuffer::Dec","uniform int depthRequest;").result,s=Re.substitute(s,"//VTK::ZBuffer::Impl",["if (depthRequest == 1) {","float iz = floor(gl_FragCoord.z*65535.0 + 0.1);","float rf = floor(iz/256.0)/255.0;","float gf = mod(iz,256.0)/255.0;","gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }"]).result),n.Vertex=a,n.Fragment=s,t.replaceShaderClip(n,i,o),t.replaceShaderCoincidentOffset(n,i,o)},t.replaceShaderClip=(n,i,o)=>{let a=n.Vertex,s=n.Fragment;if(e.renderable.getNumberOfClippingPlanes()){let c=e.renderable.getNumberOfClippingPlanes();c>6&&(In("OpenGL has a limit of 6 clipping planes"),c=6),a=Re.substitute(a,"//VTK::Clip::Dec",["uniform int numClipPlanes;","uniform vec4 clipPlanes[6];","varying float clipDistancesVSOutput[6];"]).result,a=Re.substitute(a,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);"," }"]).result,s=Re.substitute(s,"//VTK::Clip::Dec",["uniform int numClipPlanes;","varying float clipDistancesVSOutput[6];"]).result,s=Re.substitute(s,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," if (clipDistancesVSOutput[planeNum] < 0.0) discard;"," }"]).result}n.Vertex=a,n.Fragment=s},t.getNeedToRebuildShaders=(n,i,o)=>{var l;const a=e.openGLTexture.getComponents(),s=o.getProperty().getIndependentComponents();let c=!1;return(!e.currentRenderPass&&e.lastRenderPassShaderReplacement||e.currentRenderPass&&e.currentRenderPass.getShaderReplacement()!==e.lastRenderPassShaderReplacement)&&(c=!0),c||e.lastHaveSeenDepthRequest!==e.haveSeenDepthRequest||((l=n.getProgram())==null?void 0:l.getHandle())===0||e.lastTextureComponents!==a||e.lastIndependentComponents!==s?(e.lastHaveSeenDepthRequest=e.haveSeenDepthRequest,e.lastTextureComponents=a,e.lastIndependentComponents=s,!0):!1},t.updateShaders=(n,i,o)=>{if(e.lastBoundBO=n,t.getNeedToRebuildShaders(n,i,o)){const a={Vertex:null,Fragment:null,Geometry:null};t.buildShaders(a,i,o);const s=e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(a.Vertex,a.Fragment,a.Geometry);s!==n.getProgram()&&(n.setProgram(s),n.getVAO().releaseGraphicsResources()),n.getShaderSourceTime().modified()}else e._openGLRenderWindow.getShaderCache().readyShaderProgram(n.getProgram());n.getVAO().bind(),t.setMapperShaderParameters(n,i,o),t.setCameraShaderParameters(n,i,o),t.setPropertyShaderParameters(n,i,o)},t.setMapperShaderParameters=(n,i,o)=>{n.getCABO().getElementCount()&&(e.VBOBuildTime>n.getAttributeUpdateTime().getMTime()||n.getShaderSourceTime().getMTime()>n.getAttributeUpdateTime().getMTime())&&(n.getProgram().isAttributeUsed("vertexMC")&&(n.getVAO().addAttributeArray(n.getProgram(),n.getCABO(),"vertexMC",n.getCABO().getVertexOffset(),n.getCABO().getStride(),e.context.FLOAT,3,e.context.FALSE)||yd("Error setting vertexMC in shader VAO.")),n.getProgram().isAttributeUsed("tcoordMC")&&n.getCABO().getTCoordOffset()&&(n.getVAO().addAttributeArray(n.getProgram(),n.getCABO(),"tcoordMC",n.getCABO().getTCoordOffset(),n.getCABO().getStride(),e.context.FLOAT,n.getCABO().getTCoordComponents(),e.context.FALSE)||yd("Error setting tcoordMC in shader VAO.")),n.getAttributeUpdateTime().modified());const a=e.openGLTexture.getTextureUnit();n.getProgram().setUniformi("texture1",a);const s=e.openGLTexture.getComponents(),c=o.getProperty().getIndependentComponents();if(c)for(let g=0;g6&&(In("OpenGL has a limit of 6 clipping planes"),g=6);const v=n.getCABO().getCoordShiftAndScaleEnabled()?n.getCABO().getInverseShiftAndScaleMatrix():null,y=v?ri(e.imagematinv,o.getMatrix()):o.getMatrix();v&&(Fn(y,y),On(y,y,v),Fn(y,y)),Fn(e.imagemat,e.currentInput.getIndexToWorld()),On(e.imagematinv,y,e.imagemat);const m=[];for(let w=0;w{const a=n.getProgram(),s=e.openGLImageSlice.getKeyMatrices(),c=e.currentInput,l=c.getIndexToWorld();On(e.imagemat,s.mcwc,l);const f=e.openGLCamera.getKeyMatrices(i);if(On(e.imagemat,f.wcpc,e.imagemat),n.getCABO().getCoordShiftAndScaleEnabled()){const d=n.getCABO().getInverseShiftAndScaleMatrix();On(e.imagemat,e.imagemat,d)}if(a.setUniformMatrix("MCPCMatrix",e.imagemat),o.getProperty().getUseLabelOutline()===!0){const d=c.getWorldToIndex(),h=c.getDimensions();let g=e.renderable.getClosestIJKAxis().ijkMode;g===aa.NONE&&(g=aa.K),a.setUniform3i("imageDimensions",h[0],h[1],h[2]),a.setUniformi("sliceAxis",g),a.setUniformMatrix("vWCtoIDX",d);const p=e.openGLCamera.getKeyMatrices(i);oi(e.projectionToWorld,p.wcpc),e.openGLCamera.getKeyMatrices(i),a.setUniformMatrix("PCWCMatrix",e.projectionToWorld);const v=t.getRenderTargetSize();a.setUniformf("vpWidth",v[0]),a.setUniformf("vpHeight",v[1]);const y=t.getRenderTargetOffset();a.setUniformf("vpOffsetX",y[0]/v[0]),a.setUniformf("vpOffsetY",y[1]/v[1])}},t.setPropertyShaderParameters=(n,i,o)=>{const a=n.getProgram(),c=o.getProperty().getOpacity();a.setUniformf("opacity",c)},t.renderPieceStart=(n,i)=>{t.updateBufferObjects(n,i),e.lastBoundBO=null},t.renderPieceDraw=(n,i)=>{const o=e.context;e.openGLTexture.activate(),e.colorTexture.activate(),e.labelOutlineThicknessTexture.activate(),e.pwfTexture.activate(),e.tris.getCABO().getElementCount()&&(t.updateShaders(e.tris,n,i),o.drawArrays(o.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release()),e.openGLTexture.deactivate(),e.colorTexture.deactivate(),e.labelOutlineThicknessTexture.deactivate(),e.pwfTexture.deactivate()},t.renderPieceFinish=(n,i)=>{},t.renderPiece=(n,i)=>{if(t.invokeEvent({type:"StartEvent"}),e.renderable.update(),e.currentInput=e.renderable.getCurrentImage(),t.invokeEvent({type:"EndEvent"}),!e.currentInput){yd("No input!");return}t.renderPieceStart(n,i),t.renderPieceDraw(n,i),t.renderPieceFinish(n,i)},t.computeBounds=(n,i)=>{if(!t.getInput()){ih(e.bounds);return}e.bounds=t.getInput().getBounds()},t.updateBufferObjects=(n,i)=>{t.getNeedToRebuildBufferObjects(n,i)&&t.buildBufferObjects(n,i)},t.getNeedToRebuildBufferObjects=(n,i)=>{var o,a,s,c;return e.VBOBuildTime.getMTime(){var I,P,M,L;const o=e.currentInput;if(!o)return;const a=o.getPointData()&&o.getPointData().getScalars();if(!a)return;const s=a.getDataType(),c=a.getNumberOfComponents(),l=i.getProperty(),f=l.getInterpolationType(),u=l.getIndependentComponents(),d=u?c:1,h=u?2*d:1,g=l.getRGBTransferFunction(),p=ec(g,u,d),v=e._openGLRenderWindow.getGraphicsResourceForObject(g);if(!((I=v==null?void 0:v.oglObject)!=null&&I.getHandle())||(v==null?void 0:v.hash)!==p){e.colorTexture=Dr.newInstance({resizable:!0}),e.colorTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const V=1024,G=V*h*3,A=new Uint8ClampedArray(G);if(f===kf.NEAREST?(e.colorTexture.setMinificationFilter(Bt.NEAREST),e.colorTexture.setMagnificationFilter(Bt.NEAREST)):(e.colorTexture.setMinificationFilter(Bt.LINEAR),e.colorTexture.setMagnificationFilter(Bt.LINEAR)),g){const k=new Float32Array(V*3);for(let F=0;F1?1:0;const F=[aa.X,aa.Y,aa.Z].includes(e.renderable.getSlicingMode())?_:T,j=o.getSpatialExtent(),Y=a.getData();let re=null;if(S===aa.I){re=new Y.constructor(V[2]*V[1]*c);let _e=0;for(let B=0;B{var c;const i=n.getProperty().getLabelOutlineThicknessByReference(),o=e._openGLRenderWindow.getGraphicsResourceForObject(i),a=`${i.join("-")}`;if(!((c=o==null?void 0:o.oglObject)!=null&&c.getHandle())||(o==null?void 0:o.hash)!==a){const d=new Uint8Array(1024);for(let h=0;h<1024;++h){const g=typeof i[h]<"u"?i[h]:i[0];d[h]=g}e.labelOutlineThicknessTexture=Dr.newInstance({resizable:!1}),e.labelOutlineThicknessTexture.setOpenGLRenderWindow(e._openGLRenderWindow),e.labelOutlineThicknessTexture.resetFormatAndType(),e.labelOutlineThicknessTexture.setMinificationFilter(Bt.NEAREST),e.labelOutlineThicknessTexture.setMagnificationFilter(Bt.NEAREST),e.labelOutlineThicknessTexture.create2DFromRaw(1024,1,1,pn.UNSIGNED_CHAR,d),i&&(e._openGLRenderWindow.setGraphicsResourceForObject(i,e.labelOutlineThicknessTexture,a),i!==e._labelOutlineThicknessArray&&(e._openGLRenderWindow.registerGraphicsResourceUser(i,t),e._openGLRenderWindow.unregisterGraphicsResourceUser(e._labelOutlineThicknessArray,t)),e._labelOutlineThicknessArray=i)}else e.labelOutlineThicknessTexture=o.oglObject},t.getRenderTargetSize=()=>{if(e._useSmallViewport)return[e._smallViewportWidth,e._smallViewportHeight];const{usize:n,vsize:i}=e._openGLRenderer.getTiledSizeAndOrigin();return[n,i]},t.getRenderTargetOffset=()=>{const{lowerLeftU:n,lowerLeftV:i}=e._openGLRenderer.getTiledSizeAndOrigin();return[n,i]},t.delete=a1(()=>{e._openGLRenderWindow&&r(e._openGLRenderWindow)},t.delete)}const PJ={VBOBuildTime:0,VBOBuildString:null,openGLTexture:null,tris:null,imagemat:null,imagematinv:null,colorTexture:null,pwfTexture:null,labelOutlineThicknessTexture:null,labelOutlineThicknessTextureString:null,lastHaveSeenDepthRequest:!1,haveSeenDepthRequest:!1,lastTextureComponents:0};function RJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,PJ,r),gi.extend(t,e,r),wu.implementReplaceShaderCoincidentOffset(t,e,r),wu.implementBuildShadersWithReplacements(t,e,r),e.tris=Lu.newInstance(),e.imagemat=Vt(new Float64Array(16)),e.imagematinv=Vt(new Float64Array(16)),e.projectionToWorld=Vt(new Float64Array(16)),e.idxToView=Vt(new Float64Array(16)),e.idxNormalMatrix=xs(new Float64Array(9)),e.modelToView=Vt(new Float64Array(16)),e.projectionToView=Vt(new Float64Array(16)),Di(t,e,[]),e.VBOBuildTime={},br(e.VBOBuildTime),MJ(t,e)}const QP=hr(RJ,"vtkOpenGLImageMapper");var LJ={newInstance:QP};Ki("vtkAbstractImageMapper",QP);const lf={MAX:0,MIN:1,AVERAGE:2},{vtkErrorMacro:dm}=ne;function AJ(t,e){e.classHierarchy.push("vtkOpenGLImageCPRMapper");function r(n){[e._scalars,e._colorTransferFunc,e._pwFunc].forEach(i=>n.unregisterGraphicsResourceUser(i,t))}t.buildPass=n=>{if(n){e.currentRenderPass=null,e.openGLImageSlice=t.getFirstAncestorOfType("vtkOpenGLImageSlice"),e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer");const i=e._openGLRenderWindow;e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow"),i&&!i.isDeleted()&&i!==e._openGLRenderWindow&&r(i),e.context=e._openGLRenderWindow.getContext(),e.openGLCamera=e._openGLRenderer.getViewNodeFor(e._openGLRenderer.getRenderable().getActiveCamera()),e.tris.setOpenGLRenderWindow(e._openGLRenderWindow)}},t.opaquePass=(n,i)=>{n&&(e.currentRenderPass=i,t.render())},t.opaqueZBufferPass=n=>{n&&(e.haveSeenDepthRequest=!0,e.renderDepth=!0,t.render(),e.renderDepth=!1)},t.getCoincidentParameters=(n,i)=>e.renderable.getResolveCoincidentTopology()===Ts.PolygonOffset?e.renderable.getCoincidentTopologyPolygonOffsetParameters():null,t.render=()=>{const n=e.openGLImageSlice.getRenderable(),i=e._openGLRenderer.getRenderable();t.renderPiece(i,n)},t.renderPiece=(n,i)=>{t.invokeEvent({type:"StartEvent"}),e.renderable.update(),t.invokeEvent({type:"EndEvent"}),e.renderable.preRenderCheck()&&(e.currentImageDataInput=e.renderable.getInputData(0),e.currentCenterlineInput=e.renderable.getOrientedCenterline(),t.renderPieceStart(n,i),t.renderPieceDraw(n,i),t.renderPieceFinish(n,i))},t.renderPieceStart=(n,i)=>{t.updateBufferObjects(n,i)},t.renderPieceDraw=(n,i)=>{const o=e.context;e.volumeTexture.activate(),e.colorTexture.activate(),e.pwfTexture.activate(),e.tris.getCABO().getElementCount()&&(t.updateShaders(e.tris,n,i),o.drawArrays(o.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release()),e.volumeTexture.deactivate(),e.colorTexture.deactivate(),e.pwfTexture.deactivate()},t.renderPieceFinish=(n,i)=>{},t.updateBufferObjects=(n,i)=>{t.getNeedToRebuildBufferObjects(n,i)&&t.buildBufferObjects(n,i),i.getProperty().getInterpolationType()===kf.NEAREST?(e.volumeTexture.setMinificationFilter(Bt.NEAREST),e.volumeTexture.setMagnificationFilter(Bt.NEAREST),e.colorTexture.setMinificationFilter(Bt.NEAREST),e.colorTexture.setMagnificationFilter(Bt.NEAREST),e.pwfTexture.setMinificationFilter(Bt.NEAREST),e.pwfTexture.setMagnificationFilter(Bt.NEAREST)):(e.volumeTexture.setMinificationFilter(Bt.LINEAR),e.volumeTexture.setMagnificationFilter(Bt.LINEAR),e.colorTexture.setMinificationFilter(Bt.LINEAR),e.colorTexture.setMagnificationFilter(Bt.LINEAR),e.pwfTexture.setMinificationFilter(Bt.LINEAR),e.pwfTexture.setMagnificationFilter(Bt.LINEAR))},t.getNeedToRebuildBufferObjects=(n,i)=>{var a;const o=e.VBOBuildTime.getMTime();return o{var D,b,I,P;const o=e.currentImageDataInput,a=e.currentCenterlineInput,s=(D=o==null?void 0:o.getPointData())==null?void 0:D.getScalars();if(!s)return;const c=e._openGLRenderWindow.getGraphicsResourceForObject(s),l=tT(o,s),f=!((b=c==null?void 0:c.oglObject)!=null&&b.getHandle())||(c==null?void 0:c.hash)!==l,u=e.renderable.getUpdatedExtents(),d=!!u.length;if(f){e.volumeTexture=Dr.newInstance(),e.volumeTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const M=o.getDimensions();e.volumeTexture.setOglNorm16Ext(e.context.getExtension("EXT_texture_norm16")),e.volumeTexture.resetFormatAndType(),e.volumeTexture.create3DFilterableFromDataArray(M[0],M[1],M[2],s,e.renderable.getPreferSizeOverAccuracy()),e._openGLRenderWindow.setGraphicsResourceForObject(s,e.volumeTexture,l),s!==e._scalars&&(e._openGLRenderWindow.registerGraphicsResourceUser(s,t),e._openGLRenderWindow.unregisterGraphicsResourceUser(e._scalars,t)),e._scalars=s}else e.volumeTexture=c.oglObject;if(d){e.renderable.setUpdatedExtents([]);const M=o.getDimensions();e.volumeTexture.create3DFilterableFromDataArray(M[0],M[1],M[2],s,!1,u)}const h=s.getNumberOfComponents(),g=i.getProperty(),p=g.getIndependentComponents(),v=p?h:1,y=p?2*v:1,m=g.getRGBTransferFunction(),w=ec(m,p,v),x=e._openGLRenderWindow.getGraphicsResourceForObject(m);if(!((I=x==null?void 0:x.oglObject)!=null&&I.getHandle())||(x==null?void 0:x.hash)!==w){const L=1024*y*3,V=new Uint8ClampedArray(L);if(e.colorTexture=Dr.newInstance(),e.colorTexture.setOpenGLRenderWindow(e._openGLRenderWindow),m){const G=new Float32Array(3072);for(let A=0;A{const a=e.volumeTexture.getComponents(),s=o.getProperty().getIndependentComponents(),c=!!e.renderable.getCenterPoint(),l=e.renderable.getUseUniformOrientation(),f=e.renderable.isProjectionEnabled()&&e.renderable.getProjectionMode();return n.getProgram()===0||e.lastUseCenterPoint!==c||e.lastUseUniformOrientation!==l||e.lastProjectionMode!==f||e.lastHaveSeenDepthRequest!==e.haveSeenDepthRequest||e.lastTextureComponents!==a||e.lastIndependentComponents!==s?(e.lastUseCenterPoint=c,e.lastUseUniformOrientation=l,e.lastProjectionMode=f,e.lastHaveSeenDepthRequest=e.haveSeenDepthRequest,e.lastTextureComponents=a,e.lastIndependentComponents=s,!0):!1},t.buildShaders=(n,i,o)=>{t.getShaderTemplate(n,i,o),t.replaceShaderValues(n,i,o)},t.replaceShaderValues=(n,i,o)=>{let a=n.Vertex,s=n.Fragment;const c=["vec3 applyQuaternionToVec(vec4 q, vec3 v) {"," float uvx = q.y * v.z - q.z * v.y;"," float uvy = q.z * v.x - q.x * v.z;"," float uvz = q.x * v.y - q.y * v.x;"," float uuvx = q.y * uvz - q.z * uvy;"," float uuvy = q.z * uvx - q.x * uvz;"," float uuvz = q.x * uvy - q.y * uvx;"," float w2 = q.w * 2.0;"," uvx *= w2;"," uvy *= w2;"," uvz *= w2;"," uuvx *= 2.0;"," uuvy *= 2.0;"," uuvz *= 2.0;"," return vec3(v.x + uvx + uuvx, v.y + uvy + uuvy, v.z + uvz + uuvz);","}"];a=Re.substitute(a,"//VTK::Camera::Dec",["uniform mat4 MCPCMatrix;"]).result,a=Re.substitute(a,"//VTK::PositionVC::Impl",[" gl_Position = MCPCMatrix * vertexMC;"]).result;const l=["attribute vec3 centerlinePosition;","attribute float quadIndex;","uniform float width;","out vec2 quadOffsetVSOutput;","out vec3 centerlinePosVSOutput;"],f=e.renderable.isProjectionEnabled(),u=e.renderable.getUseUniformOrientation();u?(l.push("out vec3 samplingDirVSOutput;","uniform vec4 centerlineOrientation;","uniform vec3 tangentDirection;",...c),f&&l.push("out vec3 projectionDirVSOutput;","uniform vec3 bitangentDirection;")):l.push("out vec4 centerlineTopOrientationVSOutput;","out vec4 centerlineBotOrientationVSOutput;","attribute vec4 centerlineTopOrientation;","attribute vec4 centerlineBotOrientation;"),a=Re.substitute(a,"//VTK::Color::Dec",l).result;const d=["quadOffsetVSOutput = vec2(width * (mod(quadIndex, 2.0) == 0.0 ? -0.5 : 0.5), quadIndex > 1.0 ? 0.0 : 1.0);","centerlinePosVSOutput = centerlinePosition;"];u?(d.push("samplingDirVSOutput = applyQuaternionToVec(centerlineOrientation, tangentDirection);"),f&&d.push("projectionDirVSOutput = applyQuaternionToVec(centerlineOrientation, bitangentDirection);")):d.push("centerlineTopOrientationVSOutput = centerlineTopOrientation;","centerlineBotOrientationVSOutput = centerlineBotOrientation;"),a=Re.substitute(a,"//VTK::Color::Impl",d).result;const h=e.volumeTexture.getComponents(),g=o.getProperty().getIndependentComponents();let p=["uniform mat4 MCTCMatrix; // Model coordinates to texture coordinates","in vec2 quadOffsetVSOutput;","in vec3 centerlinePosVSOutput;","uniform highp sampler3D volumeTexture;","uniform sampler2D colorTexture1;","uniform sampler2D pwfTexture1;","uniform float opacity;","uniform vec4 backgroundColor;","uniform float cshift0;","uniform float cscale0;","uniform float pwfshift0;","uniform float pwfscale0;"];f&&p.push("uniform vec3 volumeSizeMC;","uniform int projectionSlabNumberOfSamples;","uniform float projectionConstantOffset;","uniform float projectionStepLength;"),u?(p.push("in vec3 samplingDirVSOutput;"),f&&p.push("in vec3 projectionDirVSOutput;")):(p.push("uniform vec3 tangentDirection;","in vec4 centerlineTopOrientationVSOutput;","in vec4 centerlineBotOrientationVSOutput;",...c),f&&p.push("uniform vec3 bitangentDirection;"));const v=e.renderable.getCenterPoint();if(v&&p.push("uniform vec3 globalCenterPoint;"),g){for(let m=1;m 0.999 || qCosAngle < -0.999) {"," // Use LERP instead of SLERP when the two quaternions are close or opposite"," interpolatedOrientation = normalize(mix(q0, q1, quadOffsetVSOutput.y));","} else {"," float omega = acos(qCosAngle);"," interpolatedOrientation = normalize(sin((1.0 - quadOffsetVSOutput.y) * omega) * q0 + sin(quadOffsetVSOutput.y * omega) * q1);","}","vec3 samplingDirection = applyQuaternionToVec(interpolatedOrientation, tangentDirection);"),f&&y.push("vec3 projectionDirection = applyQuaternionToVec(interpolatedOrientation, bitangentDirection);")),v?y.push("float baseOffset = dot(samplingDirection, globalCenterPoint - centerlinePosVSOutput);","float horizontalOffset = quadOffsetVSOutput.x + baseOffset;"):y.push("float horizontalOffset = quadOffsetVSOutput.x;"),y.push("vec3 volumePosMC = centerlinePosVSOutput + horizontalOffset * samplingDirection;","vec3 volumePosTC = (MCTCMatrix * vec4(volumePosMC, 1.0)).xyz;","if (any(lessThan(volumePosTC, vec3(0.0))) || any(greaterThan(volumePosTC, vec3(1.0))))","{"," // set the background color and exit"," gl_FragData[0] = backgroundColor;"," return;","}"),f){const m=e.renderable.getProjectionMode();switch(m){case lf.MIN:y.push("const vec4 initialProjectionTextureValue = vec4(1.0);");break;case lf.MAX:case lf.AVERAGE:default:y.push("const vec4 initialProjectionTextureValue = vec4(0.0);");break}switch(y.push("vec3 projectionScaledDirection = projectionDirection / volumeSizeMC;","vec3 projectionStep = projectionStepLength * projectionScaledDirection;","vec3 projectionStartPosition = volumePosTC + projectionConstantOffset * projectionScaledDirection;","vec4 tvalue = initialProjectionTextureValue;","for (int projectionSampleIdx = 0; projectionSampleIdx < projectionSlabNumberOfSamples; ++projectionSampleIdx) {"," vec3 projectionSamplePosition = projectionStartPosition + float(projectionSampleIdx) * projectionStep;"," vec4 sampledTextureValue = texture(volumeTexture, projectionSamplePosition);"),m){case lf.MAX:y.push(" tvalue = max(tvalue, sampledTextureValue);");break;case lf.MIN:y.push(" tvalue = min(tvalue, sampledTextureValue);");break;case lf.AVERAGE:default:y.push(" tvalue = tvalue + sampledTextureValue;");break}y.push("}"),m===lf.AVERAGE&&y.push("tvalue = tvalue / float(projectionSlabNumberOfSamples);")}else y.push("vec4 tvalue = texture(volumeTexture, volumePosTC);");if(g){const m=["r","g","b","a"];for(let w=0;w{let a=n.Vertex,s=n.Fragment;if(e.renderable.getNumberOfClippingPlanes()){let c=e.renderable.getNumberOfClippingPlanes();c>6&&(ne.vtkErrorMacro("OpenGL has a limit of 6 clipping planes"),c=6),a=Re.substitute(a,"//VTK::Clip::Dec",["uniform int numClipPlanes;","uniform vec4 clipPlanes[6];","varying float clipDistancesVSOutput[6];"]).result,a=Re.substitute(a,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);"," }"]).result,s=Re.substitute(s,"//VTK::Clip::Dec",["uniform int numClipPlanes;","varying float clipDistancesVSOutput[6];"]).result,s=Re.substitute(s,"//VTK::Clip::Impl",["for (int planeNum = 0; planeNum < 6; planeNum++)"," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," if (clipDistancesVSOutput[planeNum] < 0.0) discard;"," }"]).result}n.Vertex=a,n.Fragment=s},t.getShaderTemplate=(n,i,o)=>{n.Vertex=eT,n.Fragment=p1,n.Geometry=""},t.setMapperShaderParameters=(n,i,o)=>{const a=n.getProgram(),s=n.getCABO();s.getElementCount()&&(e.VBOBuildTime.getMTime()>n.getAttributeUpdateTime().getMTime()||n.getShaderSourceTime().getMTime()>n.getAttributeUpdateTime().getMTime())&&(a.isAttributeUsed("vertexMC")&&(n.getVAO().addAttributeArray(a,s,"vertexMC",s.getVertexOffset(),s.getStride(),e.context.FLOAT,3,e.context.FALSE)||dm("Error setting vertexMC in shader VAO.")),n.getCABO().getCustomData().forEach(h=>{h&&a.isAttributeUsed(h.name)&&!n.getVAO().addAttributeArray(a,s,h.name,h.offset,s.getStride(),e.context.FLOAT,h.components,e.context.FALSE)&&dm(`Error setting ${h.name} in shader VAO.`)}),n.getAttributeUpdateTime().modified());const c=e.volumeTexture.getTextureUnit();if(a.setUniformi("volumeTexture",c),a.setUniformf("width",e.renderable.getWidth()),n.getProgram().setUniform4fv("backgroundColor",e.renderable.getBackgroundColor()),a.isUniformUsed("tangentDirection")){const h=e.renderable.getTangentDirection();n.getProgram().setUniform3fArray("tangentDirection",h)}if(a.isUniformUsed("bitangentDirection")){const h=e.renderable.getBitangentDirection();n.getProgram().setUniform3fArray("bitangentDirection",h)}if(a.isUniformUsed("centerlineOrientation")){const h=e.renderable.getUniformOrientation();n.getProgram().setUniform4fv("centerlineOrientation",h)}if(a.isUniformUsed("globalCenterPoint")){const h=e.renderable.getCenterPoint();a.setUniform3fArray("globalCenterPoint",h)}if(e.renderable.isProjectionEnabled()){const h=e.currentImageDataInput,g=h.getSpacing(),p=h.getDimensions(),v=e.renderable.getProjectionSlabThickness(),y=e.renderable.getProjectionSlabNumberOfSamples(),m=BK([],g,p);a.setUniform3fArray("volumeSizeMC",m),a.setUniformi("projectionSlabNumberOfSamples",y);const w=-.5*v;a.setUniformf("projectionConstantOffset",w);const x=v/(y-1);a.setUniformf("projectionStepLength",x)}const l=e.currentImageDataInput,f=l.getWorldToIndex(),u=P_(new Float32Array(16),PM([],l.getDimensions())),d=yv(u,u,f);if(a.setUniformMatrix("MCTCMatrix",d),e.haveSeenDepthRequest&&n.getProgram().setUniformi("depthRequest",e.renderDepth?1:0),e.renderable.getNumberOfClippingPlanes()){let h=e.renderable.getNumberOfClippingPlanes();h>6&&(ne.vtkErrorMacro("OpenGL has a limit of 6 clipping planes"),h=6);const p=s.getCoordShiftAndScaleEnabled()?s.getInverseShiftAndScaleMatrix():null,v=p?ri(e.imagematinv,o.getMatrix()):o.getMatrix();p&&(Fn(v,v),On(v,v,p),Fn(v,v)),Fn(e.imagemat,e.currentImageDataInput.getIndexToWorld()),On(e.imagematinv,v,e.imagemat);const y=[];for(let m=0;m{const a=e.openGLImageSlice.getKeyMatrices().mcwc,s=e.openGLCamera.getKeyMatrices(i).wcpc;if(On(e.imagemat,s,a),n.getCABO().getCoordShiftAndScaleEnabled()){const c=n.getCABO().getInverseShiftAndScaleMatrix();On(e.imagemat,e.imagemat,c)}n.getProgram().setUniformMatrix("MCPCMatrix",e.imagemat)},t.setPropertyShaderParameters=(n,i,o)=>{const a=n.getProgram(),s=o.getProperty(),c=s.getOpacity();a.setUniformf("opacity",c);const l=e.volumeTexture.getComponents(),f=s.getIndependentComponents();if(f)for(let g=0;g{if(t.getNeedToRebuildShaders(n,i,o)){const a={Vertex:null,Fragment:null,Geometry:null};t.buildShaders(a,i,o);const s=e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(a.Vertex,a.Fragment,a.Geometry);s!==n.getProgram()&&(n.setProgram(s),n.getVAO().releaseGraphicsResources()),n.getShaderSourceTime().modified()}else e._openGLRenderWindow.getShaderCache().readyShaderProgram(n.getProgram());n.getVAO().bind(),t.setMapperShaderParameters(n,i,o),t.setCameraShaderParameters(n,i,o),t.setPropertyShaderParameters(n,i,o)},t.delete=ne.chain(()=>{e._openGLRenderWindow&&r(e._openGLRenderWindow)},t.delete)}const NJ={currentRenderPass:null,volumeTexture:null,colorTexture:null,pwfTexture:null,tris:null,lastHaveSeenDepthRequest:!1,haveSeenDepthRequest:!1,lastTextureComponents:0,lastIndependentComponents:0,imagemat:null,imagematinv:null};function kJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,NJ,r),gi.extend(t,e,r),wu.implementReplaceShaderCoincidentOffset(t,e,r),ne.algo(t,e,2,0),e.tris=Lu.newInstance(),e.volumeTexture=null,e.colorTexture=null,e.pwfTexture=null,e.imagemat=Vt(new Float64Array(16)),e.imagematinv=Vt(new Float64Array(16)),e.VBOBuildTime={},ne.obj(e.VBOBuildTime,{mtime:0}),AJ(t,e)}const eR=ne.newInstance(kJ,"vtkOpenGLImageCPRMapper"),VJ={};var FJ={newInstance:eR,...VJ};Ki("vtkImageCPRMapper",eR);function UJ(t,e){e.classHierarchy.push("vtkOpenGLImageSlice"),t.buildPass=r=>{if(!(!e.renderable||!e.renderable.getVisibility())&&r){if(!e.renderable)return;e._openGLRenderWindow=t.getLastAncestorOfType("vtkOpenGLRenderWindow"),e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e.context=e._openGLRenderWindow.getContext(),t.prepareNodes(),t.addMissingNode(e.renderable.getMapper()),t.removeUnusedNodes()}},t.traverseZBufferPass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.traverseOpaqueZBufferPass=r=>t.traverseOpaquePass(r),t.traverseOpaquePass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||!e.renderable.getIsOpaque()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.traverseTranslucentPass=r=>{!e.renderable||!e.renderable.getNestedVisibility()||e.renderable.getIsOpaque()||e._openGLRenderer.getSelector()&&!e.renderable.getNestedPickable()||(t.apply(r,!0),e.children.forEach(n=>{n.traverse(r)}),t.apply(r,!1))},t.queryPass=(r,n)=>{if(r){if(!e.renderable||!e.renderable.getVisibility())return;e.renderable.getIsOpaque()?n.incrementOpaqueActorCount():n.incrementTranslucentActorCount()}},t.zBufferPass=(r,n)=>t.opaquePass(r,n),t.opaqueZBufferPass=(r,n)=>t.opaquePass(r,n),t.opaquePass=(r,n)=>{r&&e.context.depthMask(!0)},t.translucentPass=(r,n)=>{e.context.depthMask(!r)},t.getKeyMatrices=()=>(e.renderable.getMTime()>e.keyMatrixTime.getMTime()&&(ri(e.keyMatrices.mcwc,e.renderable.getMatrix()),Fn(e.keyMatrices.mcwc,e.keyMatrices.mcwc),e.keyMatrixTime.modified()),e.keyMatrices)}const BJ={context:null,keyMatrixTime:null,keyMatrices:null};function GJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,BJ,r),gi.extend(t,e,r),e.keyMatrixTime={},br(e.keyMatrixTime,{mtime:0}),e.keyMatrices={mcwc:Vt(new Float64Array(16))},Di(t,e,["context"]),UJ(t,e)}const tR=hr(GJ,"vtkOpenGLImageSlice");var WJ={newInstance:tR};Ki("vtkImageSlice",tR);const{vtkDebugMacro:zJ}=So;function $J(t,e){e.classHierarchy.push("vtkOpenGLPixelSpaceCallbackMapper"),t.opaquePass=(r,n)=>{e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow");const i=e._openGLRenderer.getAspectRatio(),o=e._openGLRenderer?e._openGLRenderer.getRenderable().getActiveCamera():null,a=e._openGLRenderer.getTiledSizeAndOrigin();let s=null;if(e.renderable.getUseZValues()){const c=n.getZBufferTexture(),l=Math.floor(c.getWidth()),f=Math.floor(c.getHeight()),u=e._openGLRenderWindow.getContext();c.bind();const d=n.getFramebuffer();d?d.saveCurrentBindingsAndBuffers():zJ("No framebuffer to save/restore");const h=u.createFramebuffer();u.bindFramebuffer(u.FRAMEBUFFER,h),u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,c.getHandle(),0),u.checkFramebufferStatus(u.FRAMEBUFFER)===u.FRAMEBUFFER_COMPLETE&&(s=new Uint8Array(l*f*4),u.viewport(0,0,l,f),u.readPixels(0,0,l,f,u.RGBA,u.UNSIGNED_BYTE,s)),d&&d.restorePreviousBindingsAndBuffers(),u.deleteFramebuffer(h)}e.renderable.invokeCallback(e.renderable.getInputData(),o,i,a,s)},t.queryPass=(r,n)=>{r&&e.renderable.getUseZValues()&&n.requestDepth()}}const jJ={};function HJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,jJ,r),gi.extend(t,e,r),$J(t,e)}const nR=hr(HJ,"vtkOpenGLPixelSpaceCallbackMapper");var KJ={newInstance:nR};Ki("vtkPixelSpaceCallbackMapper",nR);const{vtkDebugMacro:qJ}=So;function XJ(t,e){e.classHierarchy.push("vtkOpenGLRenderer"),t.buildPass=r=>{if(r){if(!e.renderable)return;t.updateLights(),t.prepareNodes(),t.addMissingNode(e.renderable.getActiveCamera()),t.addMissingNodes(e.renderable.getViewPropsWithNestedProps()),t.removeUnusedNodes()}},t.updateLights=()=>{let r=0;const n=e.renderable.getLightsByReference();for(let i=0;i0&&r++;return r||(qJ("No lights are on, creating one."),e.renderable.createLight()),r},t.zBufferPass=r=>{if(r){let n=0;const i=e.context;e.renderable.getTransparent()||(e.context.clearColor(1,0,0,1),n|=i.COLOR_BUFFER_BIT),e.renderable.getPreserveDepthBuffer()||(i.clearDepth(1),n|=i.DEPTH_BUFFER_BIT,e.context.depthMask(!0));const o=t.getTiledSizeAndOrigin();i.enable(i.SCISSOR_TEST),i.scissor(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),i.viewport(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),i.colorMask(!0,!0,!0,!0),n&&i.clear(n),i.enable(i.DEPTH_TEST)}},t.opaqueZBufferPass=r=>t.zBufferPass(r),t.cameraPass=r=>{r&&t.clear()},t.getAspectRatio=()=>{const r=e._parent.getSizeByReference(),n=e.renderable.getViewportByReference();return r[0]*(n[2]-n[0])/((n[3]-n[1])*r[1])},t.getTiledSizeAndOrigin=()=>{const r=e.renderable.getViewportByReference(),n=[0,0,1,1],i=r[0]-n[0],o=r[1]-n[1],a=e._parent.normalizedDisplayToDisplay(i,o),s=Math.round(a[0]),c=Math.round(a[1]),l=r[2]-n[0],f=r[3]-n[1],u=e._parent.normalizedDisplayToDisplay(l,f);let d=Math.round(u[0])-s,h=Math.round(u[1])-c;return d<0&&(d=0),h<0&&(h=0),{usize:d,vsize:h,lowerLeftU:s,lowerLeftV:c}},t.clear=()=>{let r=0;const n=e.context;if(!e.renderable.getTransparent()){const o=e.renderable.getBackgroundByReference();n.clearColor(o[0],o[1],o[2],o[3]),r|=n.COLOR_BUFFER_BIT}e.renderable.getPreserveDepthBuffer()||(n.clearDepth(1),r|=n.DEPTH_BUFFER_BIT,n.depthMask(!0)),n.colorMask(!0,!0,!0,!0);const i=t.getTiledSizeAndOrigin();n.enable(n.SCISSOR_TEST),n.scissor(i.lowerLeftU,i.lowerLeftV,i.usize,i.vsize),n.viewport(i.lowerLeftU,i.lowerLeftV,i.usize,i.vsize),r&&n.clear(r),n.enable(n.DEPTH_TEST)},t.releaseGraphicsResources=()=>{e.selector!==null&&e.selector.releaseGraphicsResources(),e.renderable&&e.renderable.getViewProps().forEach(r=>{r.modified()})},t.setOpenGLRenderWindow=r=>{e._openGLRenderWindow!==r&&(t.releaseGraphicsResources(),e._openGLRenderWindow=r,e.context=null,r&&(e.context=e._openGLRenderWindow.getContext()))}}const YJ={context:null,_openGLRenderWindow:null,selector:null};function JJ(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,YJ,r),gi.extend(t,e,r),Fo(t,e,["shaderCache"]),Di(t,e,["selector"]),o1(t,e,["openGLRenderWindow"]),XJ(t,e)}const rR=hr(JJ,"vtkOpenGLRenderer");var ZJ={newInstance:rR};Ki("vtkRenderer",rR);const{vtkErrorMacro:k6}=So;function QJ(t,e){e.classHierarchy.push("vtkOpenGLSkybox"),t.buildPass=r=>{if(r){e._openGLRenderer=t.getFirstAncestorOfType("vtkOpenGLRenderer"),e._openGLRenderWindow=e._openGLRenderer.getParent(),e.context=e._openGLRenderWindow.getContext(),e.tris.setOpenGLRenderWindow(e._openGLRenderWindow),e.openGLTexture.setOpenGLRenderWindow(e._openGLRenderWindow);const n=e._openGLRenderer.getRenderable();e.openGLCamera=e._openGLRenderer.getViewNodeFor(n.getActiveCamera())}},t.queryPass=(r,n)=>{if(r){if(!e.renderable||!e.renderable.getVisibility())return;n.incrementOpaqueActorCount()}},t.opaquePass=(r,n)=>{if(r&&!e._openGLRenderer.getSelector()){t.updateBufferObjects(),e.context.depthMask(!0),e._openGLRenderWindow.getShaderCache().readyShaderProgram(e.tris.getProgram()),e.openGLTexture.render(e._openGLRenderWindow);const i=e.openGLTexture.getTextureUnit();e.tris.getProgram().setUniformi("sbtexture",i);const o=e._openGLRenderer.getRenderable(),a=e.openGLCamera.getKeyMatrices(o),s=new Float64Array(16);if(oi(s,a.wcpc),e.tris.getProgram().setUniformMatrix("IMCPCMatrix",s),e.lastFormat==="box"){const c=o.getActiveCamera().getPosition();e.tris.getProgram().setUniform3f("camPos",c[0],c[1],c[2])}e.tris.getVAO().bind(),e.context.drawArrays(e.context.TRIANGLES,0,e.tris.getCABO().getElementCount()),e.tris.getVAO().release(),e.openGLTexture.deactivate()}},t.updateBufferObjects=()=>{if(!e.tris.getCABO().getElementCount()){const n=new Float32Array(12);for(let s=0;s<4;s++)n[s*3]=s%2*2-1,n[s*3+1]=s>1?1:-1,n[s*3+2]=1;const i=Yt.newInstance({numberOfComponents:3,values:n});i.setName("points");const o=new Uint16Array(8);o[0]=3,o[1]=0,o[2]=1,o[3]=3,o[4]=3,o[5]=0,o[6]=3,o[7]=2;const a=Yt.newInstance({numberOfComponents:1,values:o});e.tris.getCABO().createVBO(a,"polys",Wa.SURFACE,{points:i,cellOffset:0})}e.renderable.getFormat()!==e.lastFormat&&(e.lastFormat=e.renderable.getFormat(),e.lastFormat==="box"&&e.tris.setProgram(e._openGLRenderWindow.getShaderCache().readyShaderProgramArray(`//VTK::System::Dec attribute vec3 vertexMC; uniform mat4 IMCPCMatrix; varying vec3 TexCoords; @@ -3393,14 +3393,14 @@ fn main( .DicomMicroscopyViewer .ol-tooltip { font-size: 16px !important; } -`;let $h=null;const _9=Symbol.for("map"),T9=Symbol.for("affine"),bae="postrender",Qd=class Qd extends U0{constructor(e){super({...e,canvas:e.canvas||Mc(e.element)}),this.internalCamera={rotation:0,centerIndex:[0,0],extent:[0,-2,1,-1],xSpacing:1,ySpacing:1,resolution:1,zoom:1},this.voiRange={lower:0,upper:255},this.getProperties=()=>({voiRange:{...this.voiRange}}),this.resetCamera=()=>!0,this.getNumberOfSlices=()=>1,this.getFrameOfReferenceUID=()=>this.frameOfReferenceUID,this.resize=()=>{const n=this.canvas,{clientWidth:i,clientHeight:o}=n;(n.width!==i||n.height!==o)&&(n.width=i,n.height=o),this.refreshRenderValues()},this.canvasToWorld=n=>{if(!this.metadata)return;const i=this.canvasToIndex(n);return i[1]=-i[1],this.indexToWorld(i)},this.worldToCanvas=n=>{if(!this.metadata)return;const i=this.worldToIndex(n);return i[1]=-i[1],this.indexToCanvas([i[0],i[1],0])},this.postrender=()=>{this.refreshRenderValues(),at(this.element,Xe.IMAGE_RENDERED,{element:this.element,viewportId:this.id,viewport:this,renderingEngineId:this.renderingEngineId})},this.getRotation=()=>0,this.canvasToIndex=n=>{const i=this.getTransform();i.invert();const o=i.transformPoint(n.map(a=>a*devicePixelRatio));return[o[0],o[1],0]},this.indexToCanvas=n=>this.getTransform().transformPoint([n[0],n[1]]).map(o=>o/devicePixelRatio),this.customRenderViewportToCanvas=()=>{},this.getImageIds=()=>[this.imageIds[0]],this.renderingEngineId=e.renderingEngineId,this.element.setAttribute("data-viewport-uid",this.id),this.element.setAttribute("data-rendering-engine-uid",this.renderingEngineId),this.element.style.position="relative",this.microscopyElement=document.createElement("div"),this.microscopyElement.setAttribute("class","DicomMicroscopyViewer"),this.microscopyElement.id=Dn(),this.microscopyElement.innerText="Initial",this.microscopyElement.style.background="grey",this.microscopyElement.style.width="100%",this.microscopyElement.style.height="100%",this.microscopyElement.style.position="absolute",this.microscopyElement.style.left="0",this.microscopyElement.style.top="0";const r=this.element.firstElementChild;r.insertBefore(this.microscopyElement,r.childNodes[1]),this.addEventListeners(),this.addWidget("DicomMicroscopyViewer",{getEnabled:()=>!!this.viewer,setEnabled:()=>{this.elementDisabledHandler()}}),this.resize()}static get useCustomRenderingPipeline(){return!0}addEventListeners(){this.canvas.addEventListener(Xe.ELEMENT_DISABLED,this.elementDisabledHandler)}removeEventListeners(){this.canvas.removeEventListener(Xe.ELEMENT_DISABLED,this.elementDisabledHandler)}elementDisabledHandler(){var r;this.removeEventListeners(),(r=this.viewer)==null||r.cleanup(),this.viewer=null,this.element.firstElementChild.removeChild(this.microscopyElement),this.microscopyElement=null}getImageDataMetadata(e=0){var E;const r=this.metadataDicomweb.reduce((D,b)=>(D==null?void 0:D.NumberOfFrames){i.style.filter=r})}setAverageWhite(e){this.averageWhite=e,this.setColorTransform(this.voiRange,e)}getScalarData(){return null}computeTransforms(){const e=Zo(),r=Zo();return f1(e,this.metadata.origin),e[0]=this.metadata.direction[0],e[1]=this.metadata.direction[1],e[2]=this.metadata.direction[2],e[4]=this.metadata.direction[3],e[5]=this.metadata.direction[4],e[6]=this.metadata.direction[5],e[8]=this.metadata.direction[6],e[9]=this.metadata.direction[7],e[10]=this.metadata.direction[8],Qs(e,e,this.metadata.spacing),oi(r,e),{indexToWorld:e,worldToIndex:r}}getImageData(){const{metadata:e}=this;if(!e)return null;const{spacing:r}=e,n={getDirection:()=>e.direction,getDimensions:()=>e.dimensions,getRange:()=>[0,255],getScalarData:()=>this.getScalarData(),getSpacing:()=>e.spacing,worldToIndex:o=>this.worldToIndex(o),indexToWorld:o=>this.indexToWorld(o)};return{dimensions:e.dimensions,spacing:r,numberOfComponents:3,origin:e.origin,direction:e.direction,metadata:{Modality:this.modality,FrameOfReferenceUID:this.frameOfReferenceUID},hasPixelSpacing:this.hasPixelSpacing,calibration:this.calibration,preScale:{scaled:!1},scalarData:this.getScalarData(),imageData:n}}hasImageURI(e){return!0}setCamera(e){const r=this.getCamera(),{parallelScale:n,focalPoint:i}=e,o=this.getView(),{xSpacing:a}=this.internalCamera;if(n){const c=this.element.clientHeight/n,l=1/a/c;o.setResolution(l)}if(i){const c=this.worldToCanvas(i),l=this.canvasToIndex(c);o.setCenter(l)}const s=this.getCamera();this.triggerCameraModifiedEventIfNecessary(r,s)}getCurrentImageId(){return this.imageIds[0]}getFrameNumber(){return 1}getCamera(){this.refreshRenderValues();const{resolution:e,xSpacing:r,centerIndex:n}=this.internalCamera,i=e*r,o=this.indexToCanvas([n[0],n[1],0]),a=this.canvasToWorld(o);return{parallelProjection:!0,focalPoint:a,position:a,viewUp:[0,-1,0],parallelScale:this.element.clientHeight*i,viewPlaneNormal:[0,0,1]}}worldToIndexWSI(e){if(!$h)return;const r=this.viewer[T9],n=$h.applyInverseTransform({coordinate:[e[0],e[1]],affine:r});return[n[0],n[1]]}indexToWorldWSI(e){if(!$h)return;const r=$h.applyTransform({coordinate:[e[0],e[1]],affine:this.viewer[T9]});return[r[0],r[1],0]}worldToIndex(e){const{worldToIndex:r}=this.computeTransforms(),n=Ve();return Jt(n,e,r),n}indexToWorld(e){const{indexToWorld:r}=this.computeTransforms(),n=Ve(),i=bt(...e);return Jt(n,i,r),[n[0],n[1],n[2]]}setDataIds(e,r){(r==null?void 0:r.miniNavigationOverlay)!==!1&&Qd.addMiniNavigationOverlayCss();const n=(r==null?void 0:r.webClient)||mt(Oo.WADO_WEB_CLIENT,e[0]);if(!n)throw new Error(`To use setDataIds on WSI data, you must provide metaData.webClient for ${e[0]}`);return this.setWSI(e,n)}async setWSI(e,r){this.microscopyElement.style.background="black",this.microscopyElement.innerText="Loading",this.imageIds=e;const n=await Qd.getDicomMicroscopyViewer();$h||($h=n.utils),this.frameOfReferenceUID=null;const i=this.imageIds.map(s=>{var u,d,h;const c=r.getDICOMwebMetadata(s);Object.defineProperty(c,"isMultiframe",{value:c.isMultiframe,enumerable:!1}),Object.defineProperty(c,"frameNumber",{value:void 0,enumerable:!1});const l=(u=c["00080008"])==null?void 0:u.Value;(l==null?void 0:l.length)===1&&(c["00080008"].Value=l[0].split("\\"));const f=(h=(d=c["00200052"])==null?void 0:d.Value)==null?void 0:h[0];return this.frameOfReferenceUID?f!==this.frameOfReferenceUID&&(c["00200052"].Value=[this.frameOfReferenceUID]):this.frameOfReferenceUID=f,c}),o=[];i.forEach(s=>{const c=new n.metadata.VLWholeSlideMicroscopyImage({metadata:s}),l=c.ImageType[2];l==="VOLUME"||l==="THUMBNAIL"?o.push(c):console.log("Unknown image type",c.ImageType)}),this.metadataDicomweb=o;const a=new n.viewer.VolumeImageViewer({client:r,metadata:o,controls:["overview","position"],retrieveRendered:!1,bindings:{}});a.render({container:this.microscopyElement}),this.metadata=this.getImageDataMetadata(),a.deactivateDragPanInteraction(),this.viewer=a,this.map=a[_9],this.map.on(bae,this.postrender),this.resize(),this.microscopyElement.innerText="",Object.assign(this.microscopyElement.style,{"--ol-partial-background-color":"rgba(127, 127, 127, 0.7)","--ol-foreground-color":"#000000","--ol-subtle-foreground-color":"#000","--ol-subtle-background-color":"rgba(78, 78, 78, 0.5)",background:"none"})}scroll(e){const r=this.getCamera();this.setCamera({parallelScale:r.parallelScale*(1+.1*e)})}getSliceIndex(){return 0}getView(){if(!this.viewer)return;const e=this.viewer[_9],r=window;return r.map=e,r.viewer=this.viewer,r.view=e==null?void 0:e.getView(),r.wsi=this,e==null?void 0:e.getView()}refreshRenderValues(){const e=this.getView();if(!e)return;const r=e.getResolution();if(!r||rjZ("dicom-microscopy-viewer"),Qd.overlayCssId="overlayCss";let fC=Qd;const xA={[mr.ORTHOGRAPHIC]:ur,[mr.PERSPECTIVE]:ur,[mr.STACK]:lr,[mr.VOLUME_3D]:wA,[mr.VIDEO]:Rp,[mr.WHOLE_SLIDE]:fC};function Sd(t){return xA[t].useCustomRenderingPipeline}const E9=2;class CA{constructor(e){if(this._needsRender=new Set,this._animationFrameSet=!1,this._animationFrameHandle=null,this.renderFrameOfReference=r=>{const i=this._getViewportsAsArray().map(o=>{if(o.getFrameOfReferenceUID()===r)return o.id});this.renderViewports(i)},this._renderFlaggedViewports=()=>{this._throwIfDestroyed(),this.useCPURendering||this.performVtkDrawCall();const r=this._getViewportsAsArray(),n=[];for(let i=0;i{i!=null&&i.element&&at(i.element,Xe.IMAGE_RENDERED,i)})},this.id=e||Dn(),this.useCPURendering=kg(),Tp.set(this),!$Z())throw new Error("@cornerstonejs/core is not initialized, run init() first");this.useCPURendering||(this.offscreenMultiRenderWindow=Pee.newInstance(),this.offScreenCanvasContainer=document.createElement("div"),this.offscreenMultiRenderWindow.setContainer(this.offScreenCanvasContainer)),this._viewports=new Map,this.hasBeenDestroyed=!1}enableElement(e){const r=this._normalizeViewportInputEntry(e);this._throwIfDestroyed();const{element:n,viewportId:i}=r;if(!n)throw new Error("No element provided");this.getViewport(i)&&this.disableElement(i);const{type:a}=r,s=Sd(a);!this.useCPURendering&&!s?this.enableVTKjsDrivenViewport(r):this.addCustomViewport(r);const c=Mc(n),{background:l}=r.defaultOptions;this.fillCanvasWithBackgroundColor(c,l)}disableElement(e){this._throwIfDestroyed();const r=this.getViewport(e);if(!r){console.warn(`viewport ${e} does not exist`);return}this._resetViewport(r),!Sd(r.type)&&!this.useCPURendering&&this.offscreenMultiRenderWindow.removeRenderer(e),this._removeViewport(e),r.isDisabled=!0,this._needsRender.delete(e),this.getViewports().length||this._clearAnimationFrame()}setViewports(e){const r=this._normalizeViewportInputEntries(e);this._throwIfDestroyed(),this._reset();const n=[],i=[];r.forEach(o=>{!this.useCPURendering&&!Sd(o.type)?n.push(o):i.push(o)}),this.setVtkjsDrivenViewports(n),this.setCustomViewports(i),r.forEach(o=>{const a=Mc(o.element),{background:s}=o.defaultOptions;this.fillCanvasWithBackgroundColor(a,s)})}resize(e=!0,r=!0){this._throwIfDestroyed();const n=this._getViewportsAsArray(),i=[],o=[];n.forEach(a=>{Sd(a.type)?o.push(a):i.push(a)}),i.length&&this._resizeVTKViewports(i,r,e),o.length&&this._resizeUsingCustomResizeHandler(o,r,e)}getViewport(e){var r;return(r=this._viewports)==null?void 0:r.get(e)}getViewports(){return this._throwIfDestroyed(),this._getViewportsAsArray()}getStackViewport(e){this._throwIfDestroyed();const r=this.getViewport(e);if(!r)throw new Error(`Viewport with Id ${e} does not exist`);if(!(r instanceof lr))throw new Error(`Viewport with Id ${e} is not a StackViewport.`);return r}getStackViewports(){return this._throwIfDestroyed(),this.getViewports().filter(r=>r instanceof lr)}getVolumeViewports(){this._throwIfDestroyed();const e=this.getViewports(),r=n=>n instanceof Ir;return e.filter(r)}render(){const r=this.getViewports().map(n=>n.id);this._setViewportsToBeRenderedNextFrame(r)}renderViewports(e){this._setViewportsToBeRenderedNextFrame(e)}renderViewport(e){this._setViewportsToBeRenderedNextFrame([e])}destroy(){this.hasBeenDestroyed||(this.useCPURendering||(this._getViewportsAsArray().forEach(r=>{this.offscreenMultiRenderWindow.removeRenderer(r.id)}),this.offscreenMultiRenderWindow.delete(),delete this.offscreenMultiRenderWindow),this._reset(),Tp.delete(this.id),this.hasBeenDestroyed=!0)}fillCanvasWithBackgroundColor(e,r){const n=e.getContext("2d");let i;if(r){const o=r.map(a=>Math.floor(255*a));i=`rgb(${o[0]}, ${o[1]}, ${o[2]})`}else i="black";n.fillStyle=i,n.fillRect(0,0,e.width,e.height)}_normalizeViewportInputEntry(e){const{type:r,defaultOptions:n}=e;let i=n;return(!i||Object.keys(i).length===0)&&(i={background:[0,0,0],orientation:null,displayArea:null},r===mr.ORTHOGRAPHIC&&(i={...i,orientation:Kf.AXIAL})),{...e,defaultOptions:i}}_normalizeViewportInputEntries(e){const r=[];return e.forEach(n=>{r.push(this._normalizeViewportInputEntry(n))}),r}_resizeUsingCustomResizeHandler(e,r=!0,n=!0){e.forEach(i=>{typeof i.resize=="function"&&i.resize()}),e.forEach(i=>{const o=i.getCamera();i.resetCamera(),r&&i.setCamera(o)}),n&&this.render()}_resizeVTKViewports(e,r=!0,n=!0){const i=e.map(o=>Mc(o.element));if(i.forEach(o=>{const a=window.devicePixelRatio||1;o.width=o.clientWidth*a,o.height=o.clientHeight*a}),i.length){const{offScreenCanvasWidth:o,offScreenCanvasHeight:a}=this._resizeOffScreenCanvas(i);this._resize(e,o,a)}e.forEach(o=>{const a=o.getCamera(),s=o.getRotation(),{flipHorizontal:c}=a;o.resetCameraForResize();const l=o.getDisplayArea();r&&(l?(c&&o.setCamera({flipHorizontal:c}),s&&o.setViewPresentation({rotation:s})):o.setCamera(a))}),n&&this.render()}enableVTKjsDrivenViewport(e){const n=this._getViewportsAsArray().filter(f=>Sd(f.type)===!1),i=n.map(f=>f.canvas),o=Mc(e.element);i.push(o);const{offScreenCanvasWidth:a,offScreenCanvasHeight:s}=this._resizeOffScreenCanvas(i),c=this._resize(n,a,s),l={...e,canvas:o};this.addVtkjsDrivenViewport(l,{offScreenCanvasWidth:a,offScreenCanvasHeight:s,xOffset:c})}_removeViewport(e){if(!this.getViewport(e)){console.warn(`viewport ${e} does not exist`);return}this._viewports.delete(e)}addVtkjsDrivenViewport(e,r){const{element:n,canvas:i,viewportId:o,type:a,defaultOptions:s}=e;n.tabIndex=-1;const{offScreenCanvasWidth:c,offScreenCanvasHeight:l,xOffset:f}=r,{sxStartDisplayCoords:u,syStartDisplayCoords:d,sxEndDisplayCoords:h,syEndDisplayCoords:g,sx:p,sy:v,sWidth:y,sHeight:m}=this._getViewportCoordsOnOffScreenCanvas(e,c,l,f);this.offscreenMultiRenderWindow.addRenderer({viewport:[u,d,h,g],id:o,background:s.background?s.background:[0,0,0]});const w={id:o,element:n,renderingEngineId:this.id,type:a,canvas:i,sx:p,sy:v,sWidth:y,sHeight:m,defaultOptions:s||{}};let x;if(a===mr.STACK)x=new lr(w);else if(a===mr.ORTHOGRAPHIC||a===mr.PERSPECTIVE)x=new ur(w);else if(a===mr.VOLUME_3D)x=new wA(w);else throw new Error(`Viewport Type ${a} is not supported`);this._viewports.set(o,x);const C={element:n,viewportId:o,renderingEngineId:this.id};x.suppressEvents||at(Ke,Xe.ELEMENT_ENABLED,C)}addCustomViewport(e){const{element:r,viewportId:n,type:i,defaultOptions:o}=e;r.tabIndex=-1;const a=Mc(r),{clientWidth:s,clientHeight:c}=a;(a.width!==s||a.height!==c)&&(a.width=s,a.height=c);const l={id:n,renderingEngineId:this.id,element:r,type:i,canvas:a,sx:0,sy:0,sWidth:s,sHeight:c,defaultOptions:o||{}},f=xA[i],u=new f(l);this._viewports.set(n,u);const d={element:r,viewportId:n,renderingEngineId:this.id};at(Ke,Xe.ELEMENT_ENABLED,d)}setCustomViewports(e){e.forEach(r=>{this.addCustomViewport(r)})}setVtkjsDrivenViewports(e){if(e.length){const r=e.map(a=>Mc(a.element));r.forEach(a=>{const s=window.devicePixelRatio||1,c=a.getBoundingClientRect();a.width=c.width*s,a.height=c.height*s});const{offScreenCanvasWidth:n,offScreenCanvasHeight:i}=this._resizeOffScreenCanvas(r);let o=0;for(let a=0;aa.height));let o=0;return e.forEach(a=>{o+=a.width}),r.width=o,r.height=i,n.resize(),{offScreenCanvasWidth:o,offScreenCanvasHeight:i}}_resize(e,r,n){let i=0;for(let o=0;o{this._needsRender.add(r)}),this._render()}_render(){this._needsRender.size>0&&!this._animationFrameSet&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedViewports),this._animationFrameSet=!0)}performVtkDrawCall(){const{offscreenMultiRenderWindow:e}=this,r=e.getRenderWindow(),n=e.getRenderers();if(n.length){for(let i=0;i{this._resetViewport(r)}),this._clearAnimationFrame(),this._viewports=new Map}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_downloadOffScreenCanvas(){const e=this._debugRender();Iae(e)}_debugRender(){const{offscreenMultiRenderWindow:e}=this,r=e.getRenderWindow(),n=e.getRenderers();for(let c=0;c{const{sx:l,sy:f,sWidth:u,sHeight:d}=c,h=c.canvas,{width:g,height:p}=h;h.getContext("2d").drawImage(a,l,f,u,d,0,0,g,p)}),s}}function Iae(t){const e=document.createElement("a");e.download="viewport.png",e.href=t,document.body.appendChild(e),e.click(),document.body.removeChild(e)}function SA(t){return new TextDecoder("latin1").decode(t)}function Oae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;const n=SA(t),i=e.exec(n);if(!i)return{text:n};const o=i.index+i[0].length,a=n.substring(0,o);let s=null;const c=r?r.exec(n):null;if(c){const l=n.substr(c.index);s={text:a+l,binaryBuffer:t.slice(o,c.index)}}else s={text:a,binaryBuffer:t.slice(o)};return s}var Mae={arrayBufferToString:SA,extractBinary:Oae};const PT={};function _A(t){return!!PT[t]}function Pae(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"http",e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return PT[t](e)}function TA(t,e){PT[t]=e}var Rae={get:Pae,has:_A,registerType:TA};function EA(){const t=new ArrayBuffer(4),e=new Uint8Array(t),r=new Uint32Array(t);return e[0]=161,e[1]=178,e[2]=195,e[3]=212,r[0]===3569595041?"LittleEndian":r[0]===2712847316?"BigEndian":null}const Lae=EA();function Aae(t,e){if(e<2)return;const r=new Int8Array(t),n=r.length,i=[];for(let o=0;o(DA("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead."),Promise.reject(new Error("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead.")));let G0=0;function l5(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const n=new XMLHttpRequest;return n.open(t,e,!0),r.headers&&Object.entries(r.headers).forEach(i=>{let[o,a]=i;return n.setRequestHeader(o,a)}),r.progressCallback&&n.addEventListener("progress",r.progressCallback),n}function kae(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((r,n)=>{const i=l5("GET",t,e);i.onreadystatechange=o=>{i.readyState===4&&(i.status===200||i.status===0?r(i.response):n({xhr:i,e:o}))},i.responseType="arraybuffer",i.send()})}function Vae(t,e,r){let n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return n&&n.compression?RT():r.ref&&!r.ref.pending?new Promise((i,o)=>{const a=[e,r.ref.basepath,r.ref.id].join("/"),s=l5("GET",a,n);s.onreadystatechange=c=>{s.readyState===1&&(r.ref.pending=!0,++G0===1&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!0)),s.readyState===4&&(r.ref.pending=!1,s.status===200||s.status===0?(r.buffer=s.response,r.ref.encode==="JSON"?r.values=JSON.parse(r.buffer):(jw.ENDIANNESS!==r.ref.encode&&jw.ENDIANNESS&&(Nae(`Swap bytes of ${r.name}`),jw.swapBytes(r.buffer,AO[r.dataType])),r.values=ne.newTypedArray(r.dataType,r.buffer)),r.values.length!==r.size&&DA(`Error in FetchArray: ${r.name}, does not have the proper array size. Got ${r.values.length}, instead of ${r.size}`),delete r.ref,--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),t!=null&&t.modified&&t.modified(),i(r)):o({xhr:s,e:c}))},s.responseType=r.dataType!=="string"?"arraybuffer":"text",s.send()}):Promise.resolve(r)}function Fae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r&&r.compression?RT():new Promise((n,i)=>{const o=l5("GET",e,r);o.onreadystatechange=a=>{o.readyState===1&&++G0===1&&t!=null&&t.invokeBusy&&t.invokeBusy(!0),o.readyState===4&&(--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),o.status===200||o.status===0?n(JSON.parse(o.responseText)):i({xhr:o,e:a}))},o.responseType="text",o.send()})}function Uae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r&&r.compression?RT():new Promise((n,i)=>{const o=l5("GET",e,r);o.onreadystatechange=a=>{o.readyState===1&&++G0===1&&t!=null&&t.invokeBusy&&t.invokeBusy(!0),o.readyState===4&&(--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),o.status===200||o.status===0?n(o.responseText):i({xhr:o,e:a}))},o.responseType="text",o.send()})}function Bae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((n,i)=>{const o=new Image;r.crossOrigin&&(o.crossOrigin=r.crossOrigin),o.onload=()=>n(o),o.onerror=i,o.src=e})}const Gae={fetchArray:Vae,fetchJSON:Fae,fetchText:Uae,fetchBinary:kae,fetchImage:Bae};_A("http")||TA("http",t=>Gae);var bA={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Pi,function(){return function(r){var n={};function i(o){if(n[o])return n[o].exports;var a=n[o]={i:o,l:!1,exports:{}};return r[o].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return i.m=r,i.c=n,i.d=function(o,a,s){i.o(o,a)||Object.defineProperty(o,a,{enumerable:!0,get:s})},i.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},i.t=function(o,a){if(1&a&&(o=i(o)),8&a||4&a&&typeof o=="object"&&o&&o.__esModule)return o;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:o}),2&a&&typeof o!="string")for(var c in o)i.d(s,c,(function(l){return o[l]}).bind(null,c));return s},i.n=function(o){var a=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(a,"a",a),a},i.o=function(o,a){return Object.prototype.hasOwnProperty.call(o,a)},i.p="",i(i.s=184)}([function(r,n,i){function o(a){for(var s in a)n.hasOwnProperty(s)||(n[s]=a[s])}Object.defineProperty(n,"__esModule",{value:!0}),o(i(240)),o(i(251)),o(i(175)),o(i(107)),o(i(29)),o(i(73)),o(i(106)),o(i(30)),o(i(252)),o(i(52)),o(i(97)),o(i(253)),o(i(37)),o(i(51)),o(i(173)),o(i(176)),o(i(172)),o(i(108)),o(i(254)),o(i(255)),o(i(256)),o(i(72)),o(i(177)),o(i(105)),o(i(17)),o(i(257)),o(i(12)),o(i(174))},function(r,n,i){var o=this&&this.__values||function(w){var x=typeof Symbol=="function"&&Symbol.iterator,C=x&&w[x],S=0;if(C)return C.call(w);if(w&&typeof w.length=="number")return{next:function(){return w&&S>=w.length&&(w=void 0),{value:w&&w[S++],done:!w}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(212);n.FixedSizeSet=a.FixedSizeSet;var s=i(213);n.ObjectCache=s.ObjectCache;var c=i(214);n.CompareCache=c.CompareCache;var l=i(215);n.Lazy=l.Lazy;var f=i(216);function u(w,x,C){if(y(w))w.forEach(function(_,T){return x.call(C,T,_)});else for(var S in w)w.hasOwnProperty(S)&&x.call(C,S,w[S])}function d(w){var x,C;if(h(w))return w;if(p(w)){var S=[];try{for(var _=o(w),T=_.next();!T.done;T=_.next()){var E=T.value;S.push(d(E))}}catch(I){x={error:I}}finally{try{T&&!T.done&&(C=_.return)&&C.call(_)}finally{if(x)throw x.error}}return S}if(g(w)){S={};for(var D in w)if(w.hasOwnProperty(D)){var b=w[D];S[D]=d(b)}return S}return w}function h(w){return!!w&&Object.prototype.toString.call(w)==="[object Function]"}function g(w){var x=typeof w;return!!w&&(x==="function"||x==="object")}function p(w){return Array.isArray(w)}function v(w){return w instanceof Set}function y(w){return w instanceof Map}function m(w){if(g(w)){var x=Object.getPrototypeOf(w),C=x.constructor;return x&&C&&typeof C=="function"&&C instanceof C&&Function.prototype.toString.call(C)===Function.prototype.toString.call(Object)}return!1}n.StringWalker=f.StringWalker,n.applyMixin=function(w,x){for(var C=[],S=2;S>6|192;else{if(_>55295&&_<56320){if(++S>=w.length)throw new Error("Incomplete surrogate pair.");var T=w.charCodeAt(S);if(T<56320||T>57343)throw new Error("Invalid surrogate character.");_=65536+((1023&_)<<10)+(1023&T),x[C++]=_>>18|240,x[C++]=_>>12&63|128}else x[C++]=_>>12|224;x[C++]=_>>6&63|128}x[C++]=63&_|128}}return x.subarray(0,C)},n.utf8Decode=function(w){for(var x="",C=0;C127)if(S>191&&S<224){if(C>=w.length)throw new Error("Incomplete 2-byte sequence.");S=(31&S)<<6|63&w[C++]}else if(S>223&&S<240){if(C+1>=w.length)throw new Error("Incomplete 3-byte sequence.");S=(15&S)<<12|(63&w[C++])<<6|63&w[C++]}else{if(!(S>239&&S<248))throw new Error("Unknown multi-byte start.");if(C+2>=w.length)throw new Error("Incomplete 4-byte sequence.");S=(7&S)<<18|(63&w[C++])<<12|(63&w[C++])<<6|63&w[C++]}if(S<=65535)x+=String.fromCharCode(S);else{if(!(S<=1114111))throw new Error("Code point exceeds UTF-16 limit.");S-=65536,x+=String.fromCharCode(S>>10|55296),x+=String.fromCharCode(1023&S|56320)}}return x}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),function(o){o[o.Before=0]="Before",o[o.Equal=1]="Equal",o[o.After=2]="After"}(n.BoundaryPosition||(n.BoundaryPosition={})),function(o){o[o.None=0]="None",o[o.Capturing=1]="Capturing",o[o.AtTarget=2]="AtTarget",o[o.Bubbling=3]="Bubbling"}(n.EventPhase||(n.EventPhase={})),function(o){o[o.Element=1]="Element",o[o.Attribute=2]="Attribute",o[o.Text=3]="Text",o[o.CData=4]="CData",o[o.EntityReference=5]="EntityReference",o[o.Entity=6]="Entity",o[o.ProcessingInstruction=7]="ProcessingInstruction",o[o.Comment=8]="Comment",o[o.Document=9]="Document",o[o.DocumentType=10]="DocumentType",o[o.DocumentFragment=11]="DocumentFragment",o[o.Notation=12]="Notation"}(n.NodeType||(n.NodeType={})),function(o){o[o.Disconnected=1]="Disconnected",o[o.Preceding=2]="Preceding",o[o.Following=4]="Following",o[o.Contains=8]="Contains",o[o.ContainedBy=16]="ContainedBy",o[o.ImplementationSpecific=32]="ImplementationSpecific"}(n.Position||(n.Position={})),function(o){o[o.Accept=1]="Accept",o[o.Reject=2]="Reject",o[o.Skip=3]="Skip"}(n.FilterResult||(n.FilterResult={})),function(o){o[o.All=4294967295]="All",o[o.Element=1]="Element",o[o.Attribute=2]="Attribute",o[o.Text=4]="Text",o[o.CDataSection=8]="CDataSection",o[o.EntityReference=16]="EntityReference",o[o.Entity=32]="Entity",o[o.ProcessingInstruction=64]="ProcessingInstruction",o[o.Comment=128]="Comment",o[o.Document=256]="Document",o[o.DocumentType=512]="DocumentType",o[o.DocumentFragment=1024]="DocumentFragment",o[o.Notation=2048]="Notation"}(n.WhatToShow||(n.WhatToShow={})),function(o){o[o.StartToStart=0]="StartToStart",o[o.StartToEnd=1]="StartToEnd",o[o.EndToEnd=2]="EndToEnd",o[o.EndToStart=3]="EndToStart"}(n.HowToCompare||(n.HowToCompare={}))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(241);n.Cast=o.Cast;var a=i(150);n.Guard=a.Guard;var s=i(242);n.EmptySet=s.EmptySet},function(r,n,i){var o=i(11),a=i(55).f,s=i(21),c=i(25),l=i(80),f=i(119),u=i(123);r.exports=function(d,h){var g,p,v,y,m,w=d.target,x=d.global,C=d.stat;if(g=x?o:C?o[w]||l(w,{}):(o[w]||{}).prototype)for(p in h){if(y=h[p],v=d.noTargetGet?(m=a(g,p))&&m.value:g[p],!u(x?p:w+(C?".":"#")+p,d.forced)&&v!==void 0){if(typeof y==typeof v)continue;f(y,v)}(d.sham||v&&v.sham)&&s(y,"sham",!0),c(g,p,y,d)}}},function(r,n,i){var o=i(11),a=i(81),s=i(14),c=i(58),l=i(86),f=i(124),u=a("wks"),d=o.Symbol,h=f?d:d&&d.withoutSetter||c;r.exports=function(g){return s(u,g)||(l&&s(d,g)?u[g]=d[g]:u[g]=h("Symbol."+g)),u[g]}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(1),a=i(29),s=function(){function c(){this._features={mutationObservers:!0,customElements:!0,slots:!0,steps:!0},this._window=null,this._compareCache=new o.CompareCache,this._rangeList=new o.FixedSizeSet}return c.prototype.setFeatures=function(l){if(l===void 0&&(l=!0),o.isObject(l))for(var f in l)this._features[f]=l[f]||!1;else for(var f in this._features)this._features[f]=l},Object.defineProperty(c.prototype,"features",{get:function(){return this._features},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"window",{get:function(){return this._window===null&&(this._window=a.create_window()),this._window},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"compareCache",{get:function(){return this._compareCache},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"rangeList",{get:function(){return this._rangeList},enumerable:!0,configurable:!0}),Object.defineProperty(c,"instance",{get:function(){return c._instance||(c._instance=new c),c._instance},enumerable:!0,configurable:!0}),c}();n.dom=s.instance},function(r,n,i){var o=this&&this.__importStar||function(m){if(m&&m.__esModule)return m;var w={};if(m!=null)for(var x in m)Object.hasOwnProperty.call(m,x)&&(w[x]=m[x]);return w.default=m,w};Object.defineProperty(n,"__esModule",{value:!0});var a=o(i(228));n.base64=a;var s=o(i(146));n.byte=s;var c=o(i(147));n.byteSequence=c;var l=o(i(96));n.codePoint=l;var f=o(i(232));n.json=f;var u=o(i(233));n.list=u;var d=o(i(234));n.map=d;var h=o(i(235));n.namespace=h;var g=o(i(236));n.queue=g;var p=o(i(237));n.set=p;var v=o(i(238));n.stack=v;var y=o(i(239));n.string=y},function(r,n){r.exports=function(i){try{return!!i()}catch{return!0}}},function(r,n,i){var o,a=this&&this.__extends||(o=function(A,k){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(F,j){F.__proto__=j}||function(F,j){for(var Y in j)j.hasOwnProperty(Y)&&(F[Y]=j[Y])})(A,k)},function(A,k){function F(){this.constructor=A}o(A,k),A.prototype=k===null?Object.create(k):(F.prototype=k.prototype,new F)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(A){function k(F,j){j===void 0&&(j="");var Y=A.call(this,j)||this;return Y.name=F,Y}return a(k,A),k}(Error);n.DOMException=s;var c=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"DOMStringSizeError",F)||this}return a(k,A),k}(s);n.DOMStringSizeError=c;var l=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"WrongDocumentError","The object is in the wrong document. "+F)||this}return a(k,A),k}(s);n.WrongDocumentError=l;var f=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NoDataAllowedError",F)||this}return a(k,A),k}(s);n.NoDataAllowedError=f;var u=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NoModificationAllowedError","The object can not be modified. "+F)||this}return a(k,A),k}(s);n.NoModificationAllowedError=u;var d=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotSupportedError","The operation is not supported. "+F)||this}return a(k,A),k}(s);n.NotSupportedError=d;var h=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InUseAttributeError",F)||this}return a(k,A),k}(s);n.InUseAttributeError=h;var g=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidStateError","The object is in an invalid state. "+F)||this}return a(k,A),k}(s);n.InvalidStateError=g;var p=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidModificationError","The object can not be modified in this way. "+F)||this}return a(k,A),k}(s);n.InvalidModificationError=p;var v=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NamespaceError","The operation is not allowed by Namespaces in XML. [XMLNS] "+F)||this}return a(k,A),k}(s);n.NamespaceError=v;var y=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidAccessError","The object does not support the operation or argument. "+F)||this}return a(k,A),k}(s);n.InvalidAccessError=y;var m=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"ValidationError",F)||this}return a(k,A),k}(s);n.ValidationError=m;var w=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"TypeMismatchError",F)||this}return a(k,A),k}(s);n.TypeMismatchError=w;var x=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"SecurityError","The operation is insecure. "+F)||this}return a(k,A),k}(s);n.SecurityError=x;var C=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NetworkError","A network error occurred. "+F)||this}return a(k,A),k}(s);n.NetworkError=C;var S=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"AbortError","The operation was aborted. "+F)||this}return a(k,A),k}(s);n.AbortError=S;var _=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"URLMismatchError","The given URL does not match another URL. "+F)||this}return a(k,A),k}(s);n.URLMismatchError=_;var T=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"QuotaExceededError","The quota has been exceeded. "+F)||this}return a(k,A),k}(s);n.QuotaExceededError=T;var E=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"TimeoutError","The operation timed out. "+F)||this}return a(k,A),k}(s);n.TimeoutError=E;var D=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidNodeTypeError","The supplied node is incorrect or has an incorrect ancestor for this operation. "+F)||this}return a(k,A),k}(s);n.InvalidNodeTypeError=D;var b=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"DataCloneError","The object can not be cloned. "+F)||this}return a(k,A),k}(s);n.DataCloneError=b;var I=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotImplementedError","The DOM method is not implemented by this module. "+F)||this}return a(k,A),k}(s);n.NotImplementedError=I;var P=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"HierarchyRequestError","The operation would yield an incorrect node tree. "+F)||this}return a(k,A),k}(s);n.HierarchyRequestError=P;var M=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotFoundError","The object can not be found here. "+F)||this}return a(k,A),k}(s);n.NotFoundError=M;var L=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"IndexSizeError","The index is not in the allowed range. "+F)||this}return a(k,A),k}(s);n.IndexSizeError=L;var V=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"SyntaxError","The string did not match the expected pattern. "+F)||this}return a(k,A),k}(s);n.SyntaxError=V;var G=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidCharacterError","The string contains invalid characters. "+F)||this}return a(k,A),k}(s);n.InvalidCharacterError=G},function(r,n,i){var o=i(53),a=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],s=["scalar","sequence","mapping"];r.exports=function(c,l){var f,u;if(l=l||{},Object.keys(l).forEach(function(d){if(a.indexOf(d)===-1)throw new o('Unknown option "'+d+'" is met in definition of "'+c+'" YAML type.')}),this.tag=c,this.kind=l.kind||null,this.resolve=l.resolve||function(){return!0},this.construct=l.construct||function(d){return d},this.instanceOf=l.instanceOf||null,this.predicate=l.predicate||null,this.represent=l.represent||null,this.defaultStyle=l.defaultStyle||null,this.styleAliases=(f=l.styleAliases||null,u={},f!==null&&Object.keys(f).forEach(function(d){f[d].forEach(function(h){u[String(h)]=d})}),u),s.indexOf(this.kind)===-1)throw new o('Unknown kind "'+this.kind+'" is specified for "'+c+'" YAML type.')}},function(r,n,i){(function(o){var a=function(s){return s&&s.Math==Math&&s};r.exports=a(typeof globalThis=="object"&&globalThis)||a(typeof window=="object"&&window)||a(typeof self=="object"&&self)||a(typeof o=="object"&&o)||Function("return this")()}).call(this,i(78))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),n.idl_defineConst=function(o,a,s){Object.defineProperty(o,a,{writable:!1,enumerable:!0,configurable:!1,value:s})}},function(r,n){r.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(r,n){var i={}.hasOwnProperty;r.exports=function(o,a){return i.call(o,a)}},function(r,n,i){var o=i(16),a=i(115),s=i(18),c=i(56),l=Object.defineProperty;n.f=o?l:function(f,u,d){if(s(f),u=c(u,!0),s(d),a)try{return l(f,u,d)}catch{}if("get"in d||"set"in d)throw TypeError("Accessors not supported");return"value"in d&&(f[u]=d.value),f}},function(r,n,i){var o=i(8);r.exports=!o(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})},function(r,n,i){var o=this&&this.__values||function(w){var x=typeof Symbol=="function"&&Symbol.iterator,C=x&&w[x],S=0;if(C)return C.call(w);if(w&&typeof w.length=="number")return{next:function(){return w&&S>=w.length&&(w=void 0),{value:w&&w[S++],done:!w}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(3),s=i(2);function c(w,x,C){if(C===void 0&&(C=!1),C&&a.Guard.isElementNode(x)&&a.Guard.isShadowRoot(x.shadowRoot)&&x.shadowRoot._firstChild)return x.shadowRoot._firstChild;if(x._firstChild)return x._firstChild;if(x===w)return null;if(x._nextSibling)return x._nextSibling;for(var S=x._parent;S&&S!==w;){if(S._nextSibling)return S._nextSibling;S=S._parent}return null}function l(){var w;return(w={})[Symbol.iterator]=function(){return{next:function(){return{done:!0,value:null}}}},w}function f(w,x,C,S){x===void 0&&(x=!1),C===void 0&&(C=!1);for(var _=x?w:c(w,w,C);_&&S&&!S(_);)_=c(w,_,C);return _}function u(w,x,C,S,_){S===void 0&&(S=!1);for(var T=c(w,x,S);T&&_&&!_(T);)T=c(w,T,S);return T}function d(w,x,C,S){var _;return x===void 0&&(x=!1),C===void 0&&(C=!1),x||w._children.size!==0?((_={})[Symbol.iterator]=function(){var T=x?w:c(w,w,C);return{next:function(){for(;T&&S&&!S(T);)T=c(w,T,C);if(T===null)return{done:!0,value:null};var E={done:!1,value:T};return T=c(w,T,C),E}}},_):l()}function h(w,x,C){x===void 0&&(x=!1);for(var S=x?w:w._parent;S&&C&&!C(S);)S=S._parent;return S}function g(w,x,C,S){for(var _=x._parent;_&&S&&!S(_);)_=_._parent;return _}function p(w){return a.Guard.isDocumentTypeNode(w)?0:a.Guard.isCharacterDataNode(w)?w._data.length:w._children.size}function v(w,x){if(x===void 0&&(x=!1),x){var C=v(w,!1);return a.Guard.isShadowRoot(C)?v(C._host,!0):C}return w._parent?v(w._parent):w}function y(w,x,C,S){C===void 0&&(C=!1),S===void 0&&(S=!1);for(var _=C?w:S&&a.Guard.isShadowRoot(w)?w._host:w._parent;_!==null;){if(_===x)return!0;_=S&&a.Guard.isShadowRoot(_)?_._host:_._parent}return!1}function m(w){for(var x=v(w),C=0,S=f(x);S!==null;){if(C++,S===w)return C;S=u(x,S)}return-1}n.tree_getFirstDescendantNode=f,n.tree_getNextDescendantNode=u,n.tree_getDescendantNodes=d,n.tree_getDescendantElements=function(w,x,C,S){var _;return x===void 0&&(x=!1),C===void 0&&(C=!1),x||w._children.size!==0?((_={})[Symbol.iterator]=function(){var T=d(w,x,C,function(D){return a.Guard.isElementNode(D)})[Symbol.iterator](),E=T.next().value;return{next:function(){for(;E&&S&&!S(E);)E=T.next().value;if(E===null)return{done:!0,value:null};var D={done:!1,value:E};return E=T.next().value,D}}},_):l()},n.tree_getSiblingNodes=function(w,x,C){var S;return x===void 0&&(x=!1),w._parent&&w._parent._children.size!==0?((S={})[Symbol.iterator]=function(){var _=w._parent?w._parent._firstChild:null;return{next:function(){for(;_&&(C&&!C(_)||!x&&_===w);)_=_._nextSibling;if(_===null)return{done:!0,value:null};var T={done:!1,value:_};return _=_._nextSibling,T}}},S):l()},n.tree_getFirstAncestorNode=h,n.tree_getNextAncestorNode=g,n.tree_getAncestorNodes=function(w,x,C){var S;return x===void 0&&(x=!1),x||w._parent?((S={})[Symbol.iterator]=function(){var _=h(w,x,C);return{next:function(){if(_===null)return{done:!0,value:null};var T={done:!1,value:_};return _=g(0,_,x,C),T}}},S):l()},n.tree_getCommonAncestor=function(w,x){if(w===x)return w._parent;for(var C=[],S=[],_=h(w,!0);_!==null;)C.push(_),_=g(0,_);for(var T=h(x,!0);T!==null;)S.push(T),T=g(0,T);for(var E=C.length,D=S.length,b=null,I=Math.min(E,D);I>0;I--){var P=C[--E];if(P!==S[--D])break;b=P}return b},n.tree_getFollowingNode=function(w,x){if(x._firstChild)return x._firstChild;if(x._nextSibling)return x._nextSibling;for(;;){var C=x._parent;if(C===null||C===w)return null;if(C._nextSibling)return C._nextSibling;x=C}},n.tree_getPrecedingNode=function(w,x){return x===w?null:x._previousSibling?(x=x._previousSibling)._lastChild?x._lastChild:x:x._parent},n.tree_isConstrained=function w(x){var C,S,_,T,E,D;switch(x._nodeType){case s.NodeType.Document:var b=!1,I=!1;try{for(var P=o(x._children),M=P.next();!M.done;M=P.next())switch(M.value._nodeType){case s.NodeType.ProcessingInstruction:case s.NodeType.Comment:break;case s.NodeType.DocumentType:if(b||I)return!1;b=!0;break;case s.NodeType.Element:if(I)return!1;I=!0;break;default:return!1}}catch(k){C={error:k}}finally{try{M&&!M.done&&(S=P.return)&&S.call(P)}finally{if(C)throw C.error}}break;case s.NodeType.DocumentFragment:case s.NodeType.Element:try{for(var L=o(x._children),V=L.next();!V.done;V=L.next())switch(V.value._nodeType){case s.NodeType.Element:case s.NodeType.Text:case s.NodeType.ProcessingInstruction:case s.NodeType.CData:case s.NodeType.Comment:break;default:return!1}}catch(k){_={error:k}}finally{try{V&&!V.done&&(T=L.return)&&T.call(L)}finally{if(_)throw _.error}}break;case s.NodeType.DocumentType:case s.NodeType.Text:case s.NodeType.ProcessingInstruction:case s.NodeType.CData:case s.NodeType.Comment:return!x.hasChildNodes()}try{for(var G=o(x._children),A=G.next();!A.done;A=G.next())if(!w(A.value))return!1}catch(k){E={error:k}}finally{try{A&&!A.done&&(D=G.return)&&D.call(G)}finally{if(E)throw E.error}}return!0},n.tree_nodeLength=p,n.tree_isEmpty=function(w){return p(w)===0},n.tree_rootNode=v,n.tree_isDescendantOf=function(w,x,C,S){C===void 0&&(C=!1),S===void 0&&(S=!1);for(var _=f(w,C,S);_!==null;){if(_===x)return!0;_=u(w,_,C,S)}return!1},n.tree_isAncestorOf=y,n.tree_isHostIncludingAncestorOf=function w(x,C,S){if(S===void 0&&(S=!1),y(x,C,S))return!0;var _=v(x);return!(!a.Guard.isDocumentFragmentNode(_)||_._host===null||!w(_._host,C,S))},n.tree_isSiblingOf=function(w,x,C){return C===void 0&&(C=!1),w!==x?w._parent!==null&&w._parent===x._parent:!!C},n.tree_isPreceding=function(w,x){var C=m(w),S=m(x);return C!==-1&&S!==-1&&v(w)===v(x)&&SC},n.tree_isParentOf=function(w,x){return w._parent===x},n.tree_isChildOf=function(w,x){return x._parent===w},n.tree_previousSibling=function(w){return w._previousSibling},n.tree_nextSibling=function(w){return w._nextSibling},n.tree_firstChild=function(w){return w._firstChild},n.tree_lastChild=function(w){return w._lastChild},n.tree_treePosition=m,n.tree_index=function(w){for(var x=0;w._previousSibling!==null;)x++,w=w._previousSibling;return x},n.tree_retarget=function(w,x){for(;;){if(!w||!a.Guard.isNode(w))return w;var C=v(w);if(!a.Guard.isShadowRoot(C)||x&&a.Guard.isNode(x)&&y(C,x,!0,!0))return w;w=C.host}}},function(r,n,i){var o=i(13);r.exports=function(a){if(!o(a))throw TypeError(String(a)+" is not an object");return a}},function(r,n,i){var o=i(24),a=i(130),s=i(49),c=i(43),l=i(88),f=c.set,u=c.getterFor("Array Iterator");r.exports=l(Array,"Array",function(d,h){f(this,{type:"Array Iterator",target:o(d),index:0,kind:h})},function(){var d=u(this),h=d.target,g=d.kind,p=d.index++;return!h||p>=h.length?(d.target=void 0,{value:void 0,done:!0}):g=="keys"?{value:p,done:!1}:g=="values"?{value:h[p],done:!1}:{value:[p,h[p]],done:!1}},"values"),s.Arguments=s.Array,a("keys"),a("values"),a("entries")},function(r,n,i){var o=i(90),a=i(25),s=i(202);o||a(Object.prototype,"toString",s,{unsafe:!0})},function(r,n,i){var o=i(16),a=i(15),s=i(40);r.exports=o?function(c,l,f){return a.f(c,l,s(1,f))}:function(c,l,f){return c[l]=f,c}},function(r,n,i){var o=i(137).charAt,a=i(43),s=i(88),c=a.set,l=a.getterFor("String Iterator");s(String,"String",function(f){c(this,{type:"String Iterator",string:String(f),index:0})},function(){var f,u=l(this),d=u.string,h=u.index;return h>=d.length?{value:void 0,done:!0}:(f=o(d,h),u.index+=f.length,{value:f,done:!1})})},function(r,n,i){var o=i(11),a=i(203),s=i(19),c=i(21),l=i(5),f=l("iterator"),u=l("toStringTag"),d=s.values;for(var h in a){var g=o[h],p=g&&g.prototype;if(p){if(p[f]!==d)try{c(p,f,d)}catch{p[f]=d}if(p[u]||c(p,u,h),a[h]){for(var v in s)if(p[v]!==s[v])try{c(p,v,s[v])}catch{p[v]=s[v]}}}}},function(r,n,i){var o=i(41),a=i(35);r.exports=function(s){return o(a(s))}},function(r,n,i){var o=i(11),a=i(21),s=i(14),c=i(80),l=i(117),f=i(43),u=f.get,d=f.enforce,h=String(String).split("String");(r.exports=function(g,p,v,y){var m=!!y&&!!y.unsafe,w=!!y&&!!y.enumerable,x=!!y&&!!y.noTargetGet;typeof v=="function"&&(typeof p!="string"||s(v,"name")||a(v,"name",p),d(v).source=h.join(typeof p=="string"?p:"")),g!==o?(m?!x&&g[p]&&(w=!0):delete g[p],w?g[p]=v:a(g,p,v)):w?g[p]=v:c(p,v)})(Function.prototype,"toString",function(){return typeof this=="function"&&u(this).source||l(this)})},function(r,n,i){var o=i(47),a=Math.min;r.exports=function(s){return s>0?a(o(s),9007199254740991):0}},function(r,n,i){var o=i(35);r.exports=function(a){return Object(o(a))}},function(r,n,i){var o=i(16),a=i(8),s=i(14),c=Object.defineProperty,l={},f=function(u){throw u};r.exports=function(u,d){if(s(l,u))return l[u];d||(d={});var h=[][u],g=!!s(d,"ACCESSORS")&&d.ACCESSORS,p=s(d,0)?d[0]:f,v=s(d,1)?d[1]:void 0;return l[u]=!!h&&!a(function(){if(g&&!o)return!0;var y={length:-1};g?c(y,1,{enumerable:!0,get:f}):y[1]=1,h.call(y,p,v)})}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(148),a=i(149),s=i(151),c=i(98),l=i(153),f=i(154),u=i(155),d=i(99),h=i(100),g=i(156),p=i(157),v=i(101),y=i(158),m=i(159),w=i(160),x=i(161),C=i(162),S=i(163),_=i(164),T=i(165),E=i(166),D=i(167),b=i(168),I=i(169),P=i(170);n.create_domImplementation=function(M){return o.DOMImplementationImpl._create(M)},n.create_window=function(){return a.WindowImpl._create()},n.create_xmlDocument=function(){return new s.XMLDocumentImpl},n.create_document=function(){return new c.DocumentImpl},n.create_abortController=function(){return new l.AbortControllerImpl},n.create_abortSignal=function(){return f.AbortSignalImpl._create()},n.create_documentType=function(M,L,V,G){return u.DocumentTypeImpl._create(M,L,V,G)},n.create_element=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_htmlElement=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_htmlUnknownElement=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_documentFragment=function(M){return h.DocumentFragmentImpl._create(M)},n.create_shadowRoot=function(M,L){return g.ShadowRootImpl._create(M,L)},n.create_attr=function(M,L){return p.AttrImpl._create(M,L)},n.create_text=function(M,L){return v.TextImpl._create(M,L)},n.create_cdataSection=function(M,L){return y.CDATASectionImpl._create(M,L)},n.create_comment=function(M,L){return m.CommentImpl._create(M,L)},n.create_processingInstruction=function(M,L,V){return w.ProcessingInstructionImpl._create(M,L,V)},n.create_htmlCollection=function(M,L){return L===void 0&&(L=function(){return!0}),x.HTMLCollectionImpl._create(M,L)},n.create_nodeList=function(M){return C.NodeListImpl._create(M)},n.create_nodeListStatic=function(M,L){return S.NodeListStaticImpl._create(M,L)},n.create_namedNodeMap=function(M){return _.NamedNodeMapImpl._create(M)},n.create_range=function(M,L){return T.RangeImpl._create(M,L)},n.create_nodeIterator=function(M,L,V){return E.NodeIteratorImpl._create(M,L,V)},n.create_treeWalker=function(M,L){return D.TreeWalkerImpl._create(M,L)},n.create_nodeFilter=function(){return b.NodeFilterImpl._create()},n.create_mutationRecord=function(M,L,V,G,A,k,F,j,Y){return I.MutationRecordImpl._create(M,L,V,G,A,k,F,j,Y)},n.create_domTokenList=function(M,L){return P.DOMTokenListImpl._create(M,L)}},function(r,n,i){var o=this&&this.__values||function(p){var v=typeof Symbol=="function"&&Symbol.iterator,y=v&&p[v],m=0;if(y)return y.call(p);if(p&&typeof p.length=="number")return{next:function(){return p&&m>=p.length&&(p=void 0),{value:p&&p[m++],done:!p}}};throw new TypeError(v?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(17),c=i(3),l=i(72),f=new Map;function u(p,v){if(v!==p._root&&s.tree_isAncestorOf(p._reference,v,!0)){if(p._pointerBeforeReference)for(;;){var y=s.tree_getFollowingNode(p._root,v);if(y!==null&&s.tree_isDescendantOf(p._root,y,!0)&&!s.tree_isDescendantOf(v,y,!0))return void(p._reference=y);if(y===null)return void(p._pointerBeforeReference=!1)}if(v._previousSibling===null)v._parent!==null&&(p._reference=v._parent);else{for(var m=v._previousSibling,w=s.tree_getFirstDescendantNode(v._previousSibling,!0,!1);w!==null;)w!==null&&(m=w),w=s.tree_getNextDescendantNode(v._previousSibling,w,!0,!1);p._reference=m}}}function d(p,v,y,m,w){if(c.Guard.isSlot(p)&&v==="name"&&w===null){if(m===y||m===null&&y===""||m===""&&y===null)return;p._name=m===null||m===""?"":m,l.shadowTree_assignSlotablesForATree(s.tree_rootNode(p))}}function h(p,v,y,m,w){if(c.Guard.isSlotable(p)&&v==="slot"&&w===null){if(m===y||m===null&&y===""||m===""&&y===null)return;p._name=m===null||m===""?"":m,l.shadowTree_isAssigned(p)&&l.shadowTree_assignSlotables(p._assignedSlot),l.shadowTree_assignASlot(p)}}function g(p,v,y,m){v==="id"&&m===null&&(p._uniqueIdentifier=y||void 0)}n.dom_runRemovingSteps=function(p,v){},n.dom_runCloningSteps=function(p,v,y,m){},n.dom_runAdoptingSteps=function(p,v){},n.dom_runAttributeChangeSteps=function(p,v,y,m,w){var x,C;a.dom.features.slots&&(h.call(p,p,v,y,m,w),d.call(p,p,v,y,m,w)),g.call(p,p,v,m,w);try{for(var S=o(p._attributeChangeSteps),_=S.next();!_.done;_=S.next())_.value.call(p,p,v,y,m,w)}catch(T){x={error:T}}finally{try{_&&!_.done&&(C=S.return)&&C.call(S)}finally{if(x)throw x.error}}},n.dom_runInsertionSteps=function(p){},n.dom_runNodeIteratorPreRemovingSteps=function(p,v){u.call(p,p,v)},n.dom_hasSupportedTokens=function(p){return f.has(p)},n.dom_getSupportedTokens=function(p){return f.get(p)||new Set},n.dom_runEventConstructingSteps=function(p){},n.dom_runChildTextContentChangeSteps=function(p){}},function(r,n,i){var o=i(4),a=i(11),s=i(46),c=i(44),l=i(16),f=i(86),u=i(124),d=i(8),h=i(14),g=i(59),p=i(13),v=i(18),y=i(27),m=i(24),w=i(56),x=i(40),C=i(60),S=i(61),_=i(82),T=i(190),E=i(85),D=i(55),b=i(15),I=i(79),P=i(21),M=i(25),L=i(81),V=i(57),G=i(45),A=i(58),k=i(5),F=i(125),j=i(126),Y=i(62),re=i(43),ue=i(36).forEach,ce=V("hidden"),pe=k("toPrimitive"),Ee=re.set,Oe=re.getterFor("Symbol"),Se=Object.prototype,B=a.Symbol,O=s("JSON","stringify"),z=D.f,W=b.f,K=T.f,Z=I.f,ee=L("symbols"),xe=L("op-symbols"),De=L("string-to-symbol-registry"),Ne=L("symbol-to-string-registry"),ze=L("wks"),ie=a.QObject,ae=!ie||!ie.prototype||!ie.prototype.findChild,we=l&&d(function(){return C(W({},"a",{get:function(){return W(this,"a",{value:7}).a}})).a!=7})?function($e,tt,nt){var dt=z(Se,tt);dt&&delete Se[tt],W($e,tt,nt),dt&&$e!==Se&&W(Se,tt,dt)}:W,se=function($e,tt){var nt=ee[$e]=C(B.prototype);return Ee(nt,{type:"Symbol",tag:$e,description:tt}),l||(nt.description=tt),nt},ge=u?function($e){return typeof $e=="symbol"}:function($e){return Object($e)instanceof B},Fe=function($e,tt,nt){$e===Se&&Fe(xe,tt,nt),v($e);var dt=w(tt,!0);return v(nt),h(ee,dt)?(nt.enumerable?(h($e,ce)&&$e[ce][dt]&&($e[ce][dt]=!1),nt=C(nt,{enumerable:x(0,!1)})):(h($e,ce)||W($e,ce,x(1,{})),$e[ce][dt]=!0),we($e,dt,nt)):W($e,dt,nt)},oe=function($e,tt){v($e);var nt=m(tt),dt=S(nt).concat(Ie(nt));return ue(dt,function(Lt){l&&!ht.call(nt,Lt)||Fe($e,Lt,nt[Lt])}),$e},ht=function($e){var tt=w($e,!0),nt=Z.call(this,tt);return!(this===Se&&h(ee,tt)&&!h(xe,tt))&&(!(nt||!h(this,tt)||!h(ee,tt)||h(this,ce)&&this[ce][tt])||nt)},wt=function($e,tt){var nt=m($e),dt=w(tt,!0);if(nt!==Se||!h(ee,dt)||h(xe,dt)){var Lt=z(nt,dt);return!Lt||!h(ee,dt)||h(nt,ce)&&nt[ce][dt]||(Lt.enumerable=!0),Lt}},gt=function($e){var tt=K(m($e)),nt=[];return ue(tt,function(dt){h(ee,dt)||h(G,dt)||nt.push(dt)}),nt},Ie=function($e){var tt=$e===Se,nt=K(tt?xe:m($e)),dt=[];return ue(nt,function(Lt){!h(ee,Lt)||tt&&!h(Se,Lt)||dt.push(ee[Lt])}),dt};f||(M((B=function(){if(this instanceof B)throw TypeError("Symbol is not a constructor");var $e=arguments.length&&arguments[0]!==void 0?String(arguments[0]):void 0,tt=A($e),nt=function(dt){this===Se&&nt.call(xe,dt),h(this,ce)&&h(this[ce],tt)&&(this[ce][tt]=!1),we(this,tt,x(1,dt))};return l&&ae&&we(Se,tt,{configurable:!0,set:nt}),se(tt,$e)}).prototype,"toString",function(){return Oe(this).tag}),M(B,"withoutSetter",function($e){return se(A($e),$e)}),I.f=ht,b.f=Fe,D.f=wt,_.f=T.f=gt,E.f=Ie,F.f=function($e){return se(k($e),$e)},l&&(W(B.prototype,"description",{configurable:!0,get:function(){return Oe(this).description}}),c||M(Se,"propertyIsEnumerable",ht,{unsafe:!0}))),o({global:!0,wrap:!0,forced:!f,sham:!f},{Symbol:B}),ue(S(ze),function($e){j($e)}),o({target:"Symbol",stat:!0,forced:!f},{for:function($e){var tt=String($e);if(h(De,tt))return De[tt];var nt=B(tt);return De[tt]=nt,Ne[nt]=tt,nt},keyFor:function($e){if(!ge($e))throw TypeError($e+" is not a symbol");if(h(Ne,$e))return Ne[$e]},useSetter:function(){ae=!0},useSimple:function(){ae=!1}}),o({target:"Object",stat:!0,forced:!f,sham:!l},{create:function($e,tt){return tt===void 0?C($e):oe(C($e),tt)},defineProperty:Fe,defineProperties:oe,getOwnPropertyDescriptor:wt}),o({target:"Object",stat:!0,forced:!f},{getOwnPropertyNames:gt,getOwnPropertySymbols:Ie}),o({target:"Object",stat:!0,forced:d(function(){E.f(1)})},{getOwnPropertySymbols:function($e){return E.f(y($e))}}),O&&o({target:"JSON",stat:!0,forced:!f||d(function(){var $e=B();return O([$e])!="[null]"||O({a:$e})!="{}"||O(Object($e))!="{}"})},{stringify:function($e,tt,nt){for(var dt,Lt=[$e],xt=1;arguments.length>xt;)Lt.push(arguments[xt++]);if(dt=tt,(p(tt)||$e!==void 0)&&!ge($e))return g(tt)||(tt=function(Ft,jt){if(typeof dt=="function"&&(jt=dt.call(this,Ft,jt)),!ge(jt))return jt}),Lt[1]=tt,O.apply(null,Lt)}}),B.prototype[pe]||P(B.prototype,pe,B.prototype.valueOf),Y(B,"Symbol"),G[ce]=!0},function(r,n,i){var o=i(4),a=i(16),s=i(11),c=i(14),l=i(13),f=i(15).f,u=i(119),d=s.Symbol;if(a&&typeof d=="function"&&(!("description"in d.prototype)||d().description!==void 0)){var h={},g=function(){var w=arguments.length<1||arguments[0]===void 0?void 0:String(arguments[0]),x=this instanceof g?new d(w):w===void 0?d():d(w);return w===""&&(h[x]=!0),x};u(g,d);var p=g.prototype=d.prototype;p.constructor=g;var v=p.toString,y=String(d("test"))=="Symbol(test)",m=/^Symbol\((.*)\)[^)]+$/;f(p,"description",{configurable:!0,get:function(){var w=l(this)?this.valueOf():this,x=v.call(w);if(c(h,w))return"";var C=y?x.slice(7,-1):x.replace(m,"$1");return C===""?void 0:C}}),o({global:!0,forced:!0},{Symbol:g})}},function(r,n,i){i(126)("iterator")},function(r,n,i){var o,a=this&&this.__extends||(o=function(y,m){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var C in x)x.hasOwnProperty(C)&&(w[C]=x[C])})(y,m)},function(y,m){function w(){this.constructor=y}o(y,m),y.prototype=m===null?Object.create(m):(w.prototype=m.prototype,new w)}),s=this&&this.__values||function(y){var m=typeof Symbol=="function"&&Symbol.iterator,w=m&&y[m],x=0;if(w)return w.call(y);if(y&&typeof y.length=="number")return{next:function(){return y&&x>=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(6),l=i(2),f=i(70),u=i(3),d=i(9),h=i(0),g=i(152),p=i(12),v=function(y){function m(){var w=y.call(this)||this;return w._parent=null,w._firstChild=null,w._lastChild=null,w._previousSibling=null,w._nextSibling=null,w}return a(m,y),Object.defineProperty(m.prototype,"_childNodes",{get:function(){return this.__childNodes||(this.__childNodes=h.create_nodeList(this))},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverride||c.dom.window._associatedDocument},set:function(w){this._nodeDocumentOverride=w},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"_registeredObserverList",{get:function(){return this.__registeredObserverList||(this.__registeredObserverList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeType",{get:function(){return this._nodeType},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeName",{get:function(){return u.Guard.isElementNode(this)?this._htmlUppercasedQualifiedName:u.Guard.isAttrNode(this)?this._qualifiedName:u.Guard.isExclusiveTextNode(this)?"#text":u.Guard.isCDATASectionNode(this)?"#cdata-section":u.Guard.isProcessingInstructionNode(this)?this._target:u.Guard.isCommentNode(this)?"#comment":u.Guard.isDocumentNode(this)?"#document":u.Guard.isDocumentTypeNode(this)?this._name:u.Guard.isDocumentFragmentNode(this)?"#document-fragment":""},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"baseURI",{get:function(){return g.urlSerializer(this._nodeDocument._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"isConnected",{get:function(){return u.Guard.isElementNode(this)&&h.shadowTree_isConnected(this)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"ownerDocument",{get:function(){return this._nodeType===l.NodeType.Document?null:this._nodeDocument},enumerable:!0,configurable:!0}),m.prototype.getRootNode=function(w){return h.tree_rootNode(this,!!w&&w.composed)},Object.defineProperty(m.prototype,"parentNode",{get:function(){return this._nodeType===l.NodeType.Attribute?null:this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"parentElement",{get:function(){return this._parent&&u.Guard.isElementNode(this._parent)?this._parent:null},enumerable:!0,configurable:!0}),m.prototype.hasChildNodes=function(){return this._firstChild!==null},Object.defineProperty(m.prototype,"childNodes",{get:function(){return this._childNodes},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"firstChild",{get:function(){return this._firstChild},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"lastChild",{get:function(){return this._lastChild},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeValue",{get:function(){return u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(w){w===null&&(w=""),u.Guard.isAttrNode(this)?h.attr_setAnExistingAttributeValue(this,w):u.Guard.isCharacterDataNode(this)&&h.characterData_replaceData(this,0,this._data.length,w)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"textContent",{get:function(){return u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?h.text_descendantTextContent(this):u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(w){w===null&&(w=""),u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?h.node_stringReplaceAll(w,this):u.Guard.isAttrNode(this)?h.attr_setAnExistingAttributeValue(this,w):u.Guard.isCharacterDataNode(this)&&h.characterData_replaceData(this,0,h.tree_nodeLength(this),w)},enumerable:!0,configurable:!0}),m.prototype.normalize=function(){for(var w,x,C,S,_=[],T=h.tree_getFirstDescendantNode(this,!1,!1,function(ue){return u.Guard.isExclusiveTextNode(ue)});T!==null;)_.push(T),T=h.tree_getNextDescendantNode(this,T,!1,!1,function(ue){return u.Guard.isExclusiveTextNode(ue)});for(var E=0;E<_.length;E++){var D=_[E];if(D._parent!==null){var b=h.tree_nodeLength(D);if(b!==0){var I=[],P="";try{for(var M=(w=void 0,s(h.text_contiguousExclusiveTextNodes(D))),L=M.next();!L.done;L=M.next()){var V=L.value;I.push(V),P+=V._data}}catch(ue){w={error:ue}}finally{try{L&&!L.done&&(x=M.return)&&x.call(M)}finally{if(w)throw w.error}}if(h.characterData_replaceData(D,b,0,P),c.dom.rangeList.size!==0)for(var G=D._nextSibling;G!==null&&u.Guard.isExclusiveTextNode(G);){var A=G,k=h.tree_index(A);try{for(var F=(C=void 0,s(c.dom.rangeList)),j=F.next();!j.done;j=F.next()){var Y=j.value;Y._start[0]===A&&(Y._start[0]=D,Y._start[1]+=b),Y._end[0]===A&&(Y._end[0]=D,Y._end[1]+=b),Y._start[0]===A._parent&&Y._start[1]===k&&(Y._start[0]=D,Y._start[1]=b),Y._end[0]===A._parent&&Y._end[1]===k&&(Y._end[0]=D,Y._end[1]=b)}}catch(ue){C={error:ue}}finally{try{j&&!j.done&&(S=F.return)&&S.call(F)}finally{if(C)throw C.error}}b+=h.tree_nodeLength(G),G=G._nextSibling}for(var re=0;reP;P++)if((m||P in D)&&(T=b(_=D[P],P,E),d)){if(h)L[P]=T;else if(T)switch(d){case 3:return!0;case 5:return _;case 6:return P;case 2:f.call(L,_)}else if(v)return!1}return y?-1:p||v?v:L}};r.exports={forEach:u(0),map:u(1),filter:u(2),some:u(3),every:u(4),find:u(5),findIndex:u(6)}},function(r,n,i){var o=this&&this.__values||function(E){var D=typeof Symbol=="function"&&Symbol.iterator,b=D&&E[D],I=0;if(b)return b.call(E);if(E&&typeof E.length=="number")return{next:function(){return E&&I>=E.length&&(E=void 0),{value:E&&E[I++],done:!E}}};throw new TypeError(D?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(E,D){var b=typeof Symbol=="function"&&E[Symbol.iterator];if(!b)return E;var I,P,M=b.call(E),L=[];try{for(;(D===void 0||D-- >0)&&!(I=M.next()).done;)L.push(I.value)}catch(V){P={error:V}}finally{try{I&&!I.done&&(b=M.return)&&b.call(M)}finally{if(P)throw P.error}}return L},s=this&&this.__spread||function(){for(var E=[],D=0;D1)throw new l.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+re+" element nodes.");if(re===1){try{for(var Ee=o(D._children),Oe=Ee.next();!Oe.done;Oe=Ee.next())if(Oe.value._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("The document node already has a document element node.")}catch(Z){M={error:Z}}finally{try{Oe&&!Oe.done&&(L=Ee.return)&&L.call(Ee)}finally{if(M)throw M.error}}if(b){if(Y===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");for(var Se=b._nextSibling;Se;){if(Se._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");Se=Se._nextSibling}}}}else if(j===f.NodeType.Element){try{for(var B=o(D._children),O=B.next();!O.done;O=B.next())if(O.value._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Document already has a document element node. Node is "+E.nodeName+".")}catch(Z){V={error:Z}}finally{try{O&&!O.done&&(G=B.return)&&G.call(B)}finally{if(V)throw V.error}}if(b){if(Y===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+E.nodeName+".");for(Se=b._nextSibling;Se;){if(Se._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+E.nodeName+".");Se=Se._nextSibling}}}else if(j===f.NodeType.DocumentType){try{for(var z=o(D._children),W=z.next();!W.done;W=z.next())if(W.value._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Document already has a document type node. Node is "+E.nodeName+".")}catch(Z){A={error:Z}}finally{try{W&&!W.done&&(k=z.return)&&k.call(z)}finally{if(A)throw A.error}}if(b)for(var K=b._previousSibling;K;){if(K._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+E.nodeName+".");K=K._previousSibling}else for(K=D._firstChild;K;){if(K._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+E.nodeName+".");K=K._nextSibling}}}}function S(E,D,b){C(E,D,b);var I=b;return I===E&&(I=E._nextSibling),x.document_adopt(E,D._nodeDocument),_(E,D,I),E}function _(E,D,b,I){var P,M;if(b!==null||E._nodeType===f.NodeType.DocumentFragment){var L=E._nodeType===f.NodeType.DocumentFragment?E._children.size:1;if(b!==null&&c.dom.rangeList.size!==0){var V=p.tree_index(b);try{for(var G=o(c.dom.rangeList),A=G.next();!A.done;A=G.next()){var k=A.value;k._start[0]===D&&k._start[1]>V&&(k._start[1]+=L),k._end[0]===D&&k._end[1]>V&&(k._end[1]+=L)}}catch(Oe){P={error:Oe}}finally{try{A&&!A.done&&(M=G.return)&&M.call(G)}finally{if(P)throw P.error}}}var F=E._nodeType===f.NodeType.DocumentFragment?new(Array.bind.apply(Array,s([void 0],E._children))):[E];if(E._nodeType===f.NodeType.DocumentFragment)for(;E._firstChild;)T(E._firstChild,E,!0);c.dom.features.mutationObservers&&E._nodeType===f.NodeType.DocumentFragment&&m.observer_queueTreeMutationRecord(E,[],F,null,null);for(var j=b?b._previousSibling:D._lastChild,Y=b===null?-1:p.tree_index(b),re=0;reF&&re._start[1]--,re._end[0]===D&&re._end[1]>F&&re._end[1]--}}catch(De){I={error:De}}finally{try{Y&&!Y.done&&(P=j.return)&&P.call(j)}finally{if(I)throw I.error}}try{for(var ue=o(c.dom.rangeList),ce=ue.next();!ce.done;ce=ue.next())(re=ce.value)._start[0]===D&&re._start[1]>F&&(re._start[1]-=1),re._end[0]===D&&re._end[1]>F&&(re._end[1]-=1)}catch(De){M={error:De}}finally{try{ce&&!ce.done&&(L=ue.return)&&L.call(ue)}finally{if(M)throw M.error}}}if(c.dom.features.steps)try{for(var pe=o(v.nodeIterator_iteratorList()),Ee=pe.next();!Ee.done;Ee=pe.next()){var Oe=Ee.value;Oe._root._nodeDocument===E._nodeDocument&&w.dom_runNodeIteratorPreRemovingSteps(Oe,E)}}catch(De){V={error:De}}finally{try{Ee&&!Ee.done&&(G=pe.return)&&G.call(pe)}finally{if(V)throw V.error}}var Se=E._previousSibling,B=E._nextSibling;u.Guard.isDocumentNode(D)&&u.Guard.isElementNode(E)&&(D._documentElement=null),E._parent=null,D._children.delete(E);var O=E._previousSibling,z=E._nextSibling;E._previousSibling=null,E._nextSibling=null,O&&(O._nextSibling=z),z&&(z._previousSibling=O),O||(D._firstChild=z),z||(D._lastChild=O),c.dom.features.slots&&u.Guard.isSlotable(E)&&E._assignedSlot!==null&&y.shadowTree_isAssigned(E)&&y.shadowTree_assignSlotables(E._assignedSlot),c.dom.features.slots&&u.Guard.isShadowRoot(p.tree_rootNode(D))&&u.Guard.isSlot(D)&&d.isEmpty(D._assignedNodes)&&y.shadowTree_signalASlotChange(D),c.dom.features.slots&&p.tree_getFirstDescendantNode(E,!0,!1,function(De){return u.Guard.isSlot(De)})!==null&&(y.shadowTree_assignSlotablesForATree(p.tree_rootNode(D)),y.shadowTree_assignSlotablesForATree(E)),c.dom.features.steps&&w.dom_runRemovingSteps(E,D),c.dom.features.customElements&&u.Guard.isCustomElementNode(E)&&g.customElement_enqueueACustomElementCallbackReaction(E,"disconnectedCallback",[]);for(var W=p.tree_getFirstDescendantNode(E,!1,!0);W!==null;)c.dom.features.steps&&w.dom_runRemovingSteps(W,E),c.dom.features.customElements&&u.Guard.isCustomElementNode(W)&&g.customElement_enqueueACustomElementCallbackReaction(W,"disconnectedCallback",[]),W=p.tree_getNextDescendantNode(E,W,!1,!0);if(c.dom.features.mutationObservers)for(var K=p.tree_getFirstAncestorNode(D,!0);K!==null;){try{for(var Z=(A=void 0,o(K._registeredObserverList)),ee=Z.next();!ee.done;ee=Z.next()){var xe=ee.value;xe.options.subtree&&E._registeredObserverList.push({observer:xe.observer,options:xe.options,source:xe})}}catch(De){A={error:De}}finally{try{ee&&!ee.done&&(k=Z.return)&&k.call(Z)}finally{if(A)throw A.error}}K=p.tree_getNextAncestorNode(D,K,!0)}c.dom.features.mutationObservers&&(b||m.observer_queueTreeMutationRecord(D,[],[E],Se,B)),c.dom.features.steps&&u.Guard.isTextNode(E)&&w.dom_runChildTextContentChangeSteps(D)}n.mutation_ensurePreInsertionValidity=C,n.mutation_preInsert=S,n.mutation_insert=_,n.mutation_append=function(E,D){return S(E,D,null)},n.mutation_replace=function(E,D,b){var I,P,M,L,V,G,A,k;if(b._nodeType!==f.NodeType.Document&&b._nodeType!==f.NodeType.DocumentFragment&&b._nodeType!==f.NodeType.Element)throw new l.HierarchyRequestError("Only document, document fragment and element nodes can contain child nodes. Parent node is "+b.nodeName+".");if(p.tree_isHostIncludingAncestorOf(b,D,!0))throw new l.HierarchyRequestError("The node to be inserted cannot be an ancestor of parent node. Node is "+D.nodeName+", parent node is "+b.nodeName+".");if(E._parent!==b)throw new l.NotFoundError("The reference child node cannot be found under parent node. Child node is "+E.nodeName+", parent node is "+b.nodeName+".");if(D._nodeType!==f.NodeType.DocumentFragment&&D._nodeType!==f.NodeType.DocumentType&&D._nodeType!==f.NodeType.Element&&D._nodeType!==f.NodeType.Text&&D._nodeType!==f.NodeType.ProcessingInstruction&&D._nodeType!==f.NodeType.CData&&D._nodeType!==f.NodeType.Comment)throw new l.HierarchyRequestError("Only document fragment, document type, element, text, processing instruction, cdata section or comment nodes can be inserted. Node is "+D.nodeName+".");if(D._nodeType===f.NodeType.Text&&b._nodeType===f.NodeType.Document)throw new l.HierarchyRequestError("Cannot insert a text node as a child of a document node. Node is "+D.nodeName+".");if(D._nodeType===f.NodeType.DocumentType&&b._nodeType!==f.NodeType.Document)throw new l.HierarchyRequestError("A document type node can only be inserted under a document node. Parent node is "+b.nodeName+".");if(b._nodeType===f.NodeType.Document){if(D._nodeType===f.NodeType.DocumentFragment){var F=0;try{for(var j=o(D._children),Y=j.next();!Y.done;Y=j.next()){var re=Y.value;if(re._nodeType===f.NodeType.Element)F++;else if(re._nodeType===f.NodeType.Text)throw new l.HierarchyRequestError("Cannot insert text a node as a child of a document node. Node is "+re.nodeName+".")}}catch(xe){I={error:xe}}finally{try{Y&&!Y.done&&(P=j.return)&&P.call(j)}finally{if(I)throw I.error}}if(F>1)throw new l.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+F+" element nodes.");if(F===1){try{for(var ue=o(b._children),ce=ue.next();!ce.done;ce=ue.next())if((O=ce.value)._nodeType===f.NodeType.Element&&O!==E)throw new l.HierarchyRequestError("The document node already has a document element node.")}catch(xe){M={error:xe}}finally{try{ce&&!ce.done&&(L=ue.return)&&L.call(ue)}finally{if(M)throw M.error}}for(var pe=E._nextSibling;pe;){if(pe._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");pe=pe._nextSibling}}}else if(D._nodeType===f.NodeType.Element){try{for(var Ee=o(b._children),Oe=Ee.next();!Oe.done;Oe=Ee.next())if((O=Oe.value)._nodeType===f.NodeType.Element&&O!==E)throw new l.HierarchyRequestError("Document already has a document element node. Node is "+D.nodeName+".")}catch(xe){V={error:xe}}finally{try{Oe&&!Oe.done&&(G=Ee.return)&&G.call(Ee)}finally{if(V)throw V.error}}for(pe=E._nextSibling;pe;){if(pe._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+D.nodeName+".");pe=pe._nextSibling}}else if(D._nodeType===f.NodeType.DocumentType){try{for(var Se=o(b._children),B=Se.next();!B.done;B=Se.next()){var O;if((O=B.value)._nodeType===f.NodeType.DocumentType&&O!==E)throw new l.HierarchyRequestError("Document already has a document type node. Node is "+D.nodeName+".")}}catch(xe){A={error:xe}}finally{try{B&&!B.done&&(k=Se.return)&&k.call(Se)}finally{if(A)throw A.error}}for(var z=E._previousSibling;z;){if(z._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+D.nodeName+".");z=z._previousSibling}}}var W=E._nextSibling;W===D&&(W=D._nextSibling);var K=E._previousSibling;x.document_adopt(D,b._nodeDocument);var Z=[];E._parent!==null&&(Z.push(E),T(E,E._parent,!0));var ee=[];return D._nodeType===f.NodeType.DocumentFragment?ee=Array.from(D._children):ee.push(D),_(D,b,W,!0),c.dom.features.mutationObservers&&m.observer_queueTreeMutationRecord(b,ee,Z,K,W),E},n.mutation_replaceAll=function(E,D){var b,I;E!==null&&x.document_adopt(E,D._nodeDocument);var P=Array.from(D._children),M=[];E&&E._nodeType===f.NodeType.DocumentFragment?M=Array.from(E._children):E!==null&&M.push(E);try{for(var L=o(P),V=L.next();!V.done;V=L.next())T(V.value,D,!0)}catch(G){b={error:G}}finally{try{V&&!V.done&&(I=L.return)&&I.call(L)}finally{if(b)throw b.error}}E!==null&&_(E,D,null,!0),c.dom.features.mutationObservers&&m.observer_queueTreeMutationRecord(D,M,P,null,null)},n.mutation_preRemove=function(E,D){if(E._parent!==D)throw new l.NotFoundError("The child node cannot be found under parent node. Child node is "+E.nodeName+", parent node is "+D.nodeName+".");return T(E,D),E},n.mutation_remove=T},function(r,n,i){function o(a){return a==null}r.exports.isNothing=o,r.exports.isObject=function(a){return typeof a=="object"&&a!==null},r.exports.toArray=function(a){return Array.isArray(a)?a:o(a)?[]:[a]},r.exports.repeat=function(a,s){var c,l="";for(c=0;c0?o:i)(a)}},function(r,n,i){var o=i(8);r.exports=function(a,s){var c=[][a];return!!c&&o(function(){c.call(null,s||function(){throw 1},1)})}},function(r,n){r.exports={}},function(r,n,i){i(31),i(32),i(33),i(220),i(64),i(19),i(65),i(20),i(68),i(66),i(92),i(144),i(22),i(94),i(23);var o=this&&this.__values||function(g){var p=typeof Symbol=="function"&&Symbol.iterator,v=p&&g[p],y=0;if(v)return v.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(g,p){var v=typeof Symbol=="function"&&g[Symbol.iterator];if(!v)return g;var y,m,w=v.call(g),x=[];try{for(;(p===void 0||p-- >0)&&!(y=w.next()).done;)x.push(y.value)}catch(C){m={error:C}}finally{try{y&&!y.done&&(v=w.return)&&v.call(w)}finally{if(m)throw m.error}}return x},s=this&&this.__spread||function(){for(var g=[],p=0;p/g,">");this.text(y)},g.prototype._serializeDocumentFragmentNS=function(p,v,y,m,w){var x,C;try{for(var S=o(p.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;this._serializeNodeNS(T,v,y,m,w)}}catch(E){x={error:E}}finally{try{_&&!_.done&&(C=S.return)&&C.call(S)}finally{if(x)throw x.error}}},g.prototype._serializeDocumentFragment=function(p,v){var y,m;try{for(var w=o(p._children),x=w.next();!x.done;x=w.next()){var C=x.value;this._serializeNode(C,v)}}catch(S){y={error:S}}finally{try{x&&!x.done&&(m=w.return)&&m.call(w)}finally{if(y)throw y.error}}},g.prototype._serializeDocumentType=function(p,v){if(v&&!d.xml_isPubidChar(p.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(v&&(!d.xml_isLegalChar(p.systemId)||p.systemId.indexOf('"')!==-1&&p.systemId.indexOf("'")!==-1))throw new Error("DocType system identifier contains invalid characters (well-formed required).");this.docType(p.name,p.publicId,p.systemId)},g.prototype._serializeProcessingInstruction=function(p,v){if(v&&(p.target.indexOf(":")!==-1||/^xml$/i.test(p.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(v&&(!d.xml_isLegalChar(p.data)||p.data.indexOf("?>")!==-1))throw new Error("Processing instruction data contains invalid characters (well-formed required).");this.instruction(p.target,p.data)},g.prototype._serializeCData=function(p,v){if(v&&p.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters (well-formed required).");this.cdata(p.data)},g.prototype._serializeAttributesNS=function(p,v,y,m,w,x){var C,S,_=[],T=x?new l.LocalNameSet:void 0;try{for(var E=o(p.attributes),D=E.next();!D.done;D=E.next()){var b=D.value;if(x||w||b.namespaceURI!==null){if(x&&T&&T.has(b.namespaceURI,b.localName))throw new Error("Element contains duplicate attributes (well-formed required).");x&&T&&T.set(b.namespaceURI,b.localName);var I=b.namespaceURI,P=null;if(I!==null)if(P=v.get(b.prefix,I),I===u.namespace.XMLNS){if(b.value===u.namespace.XML||b.prefix===null&&w||b.prefix!==null&&(!(b.localName in m)||m[b.localName]!==b.value)&&v.has(b.localName,b.value))continue;if(x&&b.value===u.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(x&&b.value==="")throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");b.prefix==="xmlns"&&(P="xmlns")}else P===null&&(P=b.prefix===null||v.hasPrefix(b.prefix)&&!v.has(b.prefix,I)?this._generatePrefix(I,v,y):b.prefix,_.push([null,"xmlns",P,this._serializeAttributeValue(I,x)]));if(x&&(b.localName.indexOf(":")!==-1||!d.xml_isName(b.localName)||b.localName==="xmlns"&&I===null))throw new Error("Attribute local name contains invalid characters (well-formed required).");_.push([I,P,b.localName,this._serializeAttributeValue(b.value,x)])}else _.push([null,null,b.localName,this._serializeAttributeValue(b.value,x)])}}catch(M){C={error:M}}finally{try{D&&!D.done&&(S=E.return)&&S.call(E)}finally{if(C)throw C.error}}return _},g.prototype._serializeAttributes=function(p,v){var y,m,w=[],x=v?{}:void 0;try{for(var C=o(p.attributes),S=C.next();!S.done;S=C.next()){var _=S.value;if(v){if(v&&x&&_.localName in x)throw new Error("Element contains duplicate attributes (well-formed required).");if(v&&x&&(x[_.localName]=!0),v&&(_.localName.indexOf(":")!==-1||!d.xml_isName(_.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");w.push([null,null,_.localName,this._serializeAttributeValue(_.value,v)])}else w.push([null,null,_.localName,this._serializeAttributeValue(_.value,v)])}}catch(T){y={error:T}}finally{try{S&&!S.done&&(m=C.return)&&m.call(C)}finally{if(y)throw y.error}}return w},g.prototype._recordNamespaceInformation=function(p,v,y){var m,w,x=null;try{for(var C=o(p.attributes),S=C.next();!S.done;S=C.next()){var _=S.value,T=_.namespaceURI,E=_.prefix;if(T===u.namespace.XMLNS){if(E===null){x=_.value;continue}var D=_.localName,b=_.value;if(b===u.namespace.XML||(b===""&&(b=null),v.has(D,b)))continue;v.set(D,b),y[D]=b||""}}}catch(I){m={error:I}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x},g.prototype._generatePrefix=function(p,v,y){var m="ns"+y.value.toString();return y.value++,v.set(m,p),m},g.prototype._serializeAttributeValue=function(p,v){if(v&&p!==null&&!d.xml_isLegalChar(p))throw new Error("Invalid characters in attribute value.");return p===null?"":p.replace(/(?!&([^&;]*);)&/g,"&").replace(//g,">").replace(/"/g,""")},g._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),g}();n.BaseWriter=h},function(r,n,i){var o=this&&this.__values||function(v){var y=typeof Symbol=="function"&&Symbol.iterator,m=y&&v[y],w=0;if(m)return m.call(v);if(v&&typeof v.length=="number")return{next:function(){return v&&w>=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(v,y){var m=typeof Symbol=="function"&&v[Symbol.iterator];if(!m)return v;var w,x,C=m.call(v),S=[];try{for(;(y===void 0||y-- >0)&&!(w=C.next()).done;)S.push(w.value)}catch(_){x={error:_}}finally{try{w&&!w.done&&(m=C.return)&&m.call(C)}finally{if(x)throw x.error}}return S};Object.defineProperty(n,"__esModule",{value:!0});var s=i(6),c=i(3),l=i(7),f=i(29),u=i(17),d=i(97);function h(){var v=s.dom.window;v._mutationObserverMicrotaskQueued||(v._mutationObserverMicrotaskQueued=!0,Promise.resolve().then(function(){g()}))}function g(){var v,y,m,w,x=s.dom.window;x._mutationObserverMicrotaskQueued=!1;var C=l.set.clone(x._mutationObservers),S=l.set.clone(x._signalSlots);l.set.empty(x._signalSlots);var _=function(P){var M=l.list.clone(P._recordQueue);l.list.empty(P._recordQueue);for(var L=0;L"+y+"<\/script>"},v=function(){try{o=document.domain&&new ActiveXObject("htmlfile")}catch{}var y,m;v=o?function(x){x.write(p("")),x.close();var C=x.parentWindow.Object;return x=null,C}(o):((m=u("iframe")).style.display="none",f.appendChild(m),m.src="javascript:",(y=m.contentWindow.document).open(),y.write(p("document.F=Object")),y.close(),y.F);for(var w=c.length;w--;)delete v.prototype[c[w]];return v()};l[h]=!0,r.exports=Object.create||function(y,m){var w;return y!==null?(g.prototype=a(y),w=new g,g.prototype=null,w[h]=y):w=v(),m===void 0?w:s(w,m)}},function(r,n,i){var o=i(121),a=i(84);r.exports=Object.keys||function(s){return o(s,a)}},function(r,n,i){var o=i(15).f,a=i(14),s=i(5)("toStringTag");r.exports=function(c,l,f){c&&!a(c=f?c:c.prototype,s)&&o(c,s,{configurable:!0,value:l})}},function(r,n,i){var o=i(8),a=i(5),s=i(129),c=a("species");r.exports=function(l){return s>=51||!o(function(){var f=[];return(f.constructor={})[c]=function(){return{foo:1}},f[l](Boolean).foo!==1})}},function(r,n,i){var o=i(4),a=i(122).indexOf,s=i(48),c=i(28),l=[].indexOf,f=!!l&&1/[1].indexOf(1,-0)<0,u=s("indexOf"),d=c("indexOf",{ACCESSORS:!0,1:0});o({target:"Array",proto:!0,forced:f||!u||!d},{indexOf:function(h){return f?l.apply(this,arguments)||0:a(this,h,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(16),a=i(15).f,s=Function.prototype,c=s.toString,l=/^\s*function ([^ (]*)/;o&&!("name"in s)&&a(s,"name",{configurable:!0,get:function(){try{return c.call(this).match(l)[1]}catch{return""}}})},function(r,n,i){var o=i(25),a=i(18),s=i(8),c=i(136),l=RegExp.prototype,f=l.toString,u=s(function(){return f.call({source:"a",flags:"b"})!="/a/b"}),d=f.name!="toString";(u||d)&&o(RegExp.prototype,"toString",function(){var h=a(this),g=String(h.source),p=h.flags;return"/"+g+"/"+String(p===void 0&&h instanceof RegExp&&!("flags"in l)?c.call(h):p)},{unsafe:!0})},function(r,n,i){i(31),i(32),i(33),i(19),i(138),i(20),i(66),i(22),i(23);var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)}),s=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(1),l=i(2),f=function(u){function d(h,g){var p=u.call(this,h)||this;return p._writerOptions=c.applyDefaults(g,{format:"object",wellFormed:!1,group:!1,verbose:!1}),p}return a(d,u),d.prototype.serialize=function(h){return this._currentList=[],this._currentIndex=0,this._listRegister=[this._currentList],this.serializeNode(h,this._writerOptions.wellFormed),this._process(this._currentList,this._writerOptions)},d.prototype._process=function(h,g){var p,v,y,m,w,x,C;if(h.length===0)return{};for(var S={},_=!1,T=0,E=0,D=0,b=0,I=0;I2)try{for(var C=s(h),S=C.next();!S.done;S=C.next()){var _=S.value;g[v+(m++).toString()]=_}}catch(T){w={error:T}}finally{try{S&&!S.done&&(x=C.return)&&x.call(C)}finally{if(w)throw w.error}}else g[y>1?v+(m++).toString():v]=h;return m},d.prototype.beginElement=function(h){var g,p,v=[];if(this._currentList.length===0)this._currentList.push(((g={})[h]=v,g));else{var y=this._currentList[this._currentList.length-1];this._isElementNode(y,h)?y[h].length!==0&&c.isArray(y[h][0])?y[h].push(v):y[h]=[y[h],v]:this._currentList.push(((p={})[h]=v,p))}this._currentIndex++,this._listRegister.length>this._currentIndex?this._listRegister[this._currentIndex]=v:this._listRegister.push(v),this._currentList=v},d.prototype.endElement=function(){this._currentList=this._listRegister[--this._currentIndex]},d.prototype.attribute=function(h,g){var p,v;if(this._currentList.length===0)this._currentList.push({"@":(p={},p[h]=g,p)});else{var y=this._currentList[this._currentList.length-1];this._isAttrNode(y)?y["@"][h]=g:this._currentList.push({"@":(v={},v[h]=g,v)})}},d.prototype.comment=function(h){if(this._currentList.length===0)this._currentList.push({"!":h});else{var g=this._currentList[this._currentList.length-1];this._isCommentNode(g)?c.isArray(g["!"])?g["!"].push(h):g["!"]=[g["!"],h]:this._currentList.push({"!":h})}},d.prototype.text=function(h){if(this._currentList.length===0)this._currentList.push({"#":h});else{var g=this._currentList[this._currentList.length-1];this._isTextNode(g)?c.isArray(g["#"])?g["#"].push(h):g["#"]=[g["#"],h]:this._currentList.push({"#":h})}},d.prototype.instruction=function(h,g){var p=g===""?h:h+" "+g;if(this._currentList.length===0)this._currentList.push({"?":p});else{var v=this._currentList[this._currentList.length-1];this._isInstructionNode(v)?c.isArray(v["?"])?v["?"].push(p):v["?"]=[v["?"],p]:this._currentList.push({"?":p})}},d.prototype.cdata=function(h){if(this._currentList.length===0)this._currentList.push({$:h});else{var g=this._currentList[this._currentList.length-1];this._isCDATANode(g)?c.isArray(g.$)?g.$.push(h):g.$=[g.$,h]:this._currentList.push({$:h})}},d.prototype._isAttrNode=function(h){return"@"in h},d.prototype._isTextNode=function(h){return"#"in h},d.prototype._isCommentNode=function(h){return"!"in h},d.prototype._isInstructionNode=function(h){return"?"in h},d.prototype._isCDATANode=function(h){return"$"in h},d.prototype._isElementNode=function(h,g){return g in h},d.prototype._getAttrKey=function(){return this._builderOptions.convert.att},d.prototype._getNodeKey=function(h){switch(h){case l.NodeType.Comment:return this._builderOptions.convert.comment;case l.NodeType.Text:return this._builderOptions.convert.text;case l.NodeType.ProcessingInstruction:return this._builderOptions.convert.ins;case l.NodeType.CData:return this._builderOptions.convert.cdata;default:throw new Error("Invalid node type.")}},d}(i(50).BaseWriter);n.ObjectWriter=f},function(r,n,i){var o=i(4),a=i(93);o({target:"RegExp",proto:!0,forced:/./.exec!==a},{exec:a})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){this._items={},this._nullItems={}}return a.prototype.set=function(s,c){s===null?this._nullItems[c]=!0:(this._items[s]||(this._items[s]={}),this._items[s][c]=!0)},a.prototype.has=function(s,c){return s===null?this._nullItems[c]===!0:!!this._items[s]&&this._items[s][c]===!0},a}();n.LocalNameSet=o},function(r,n,i){var o=this&&this.__read||function(f,u){var d=typeof Symbol=="function"&&f[Symbol.iterator];if(!d)return f;var h,g,p=d.call(f),v=[];try{for(;(u===void 0||u-- >0)&&!(h=p.next()).done;)v.push(h.value)}catch(y){g={error:y}}finally{try{h&&!h.done&&(d=p.return)&&d.call(p)}finally{if(g)throw g.error}}return v};Object.defineProperty(n,"__esModule",{value:!0});var a=i(9),s=i(3),c=i(0),l=function(){function f(){}return Object.defineProperty(f.prototype,"_eventListenerList",{get:function(){return this.__eventListenerList||(this.__eventListenerList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(f.prototype,"_eventHandlerMap",{get:function(){return this.__eventHandlerMap||(this.__eventHandlerMap={})},enumerable:!0,configurable:!0}),f.prototype.addEventListener=function(u,d,h){h===void 0&&(h={passive:!1,once:!1,capture:!1});var g,p=o(c.eventTarget_flattenMore(h),3),v=p[0],y=p[1],m=p[2];d&&(g=s.Guard.isEventListener(d)?d:{handleEvent:d},c.eventTarget_addEventListener(this,{type:u,callback:g,capture:v,passive:y,once:m,removed:!1}))},f.prototype.removeEventListener=function(u,d,h){h===void 0&&(h={capture:!1});var g=c.eventTarget_flatten(h);if(d)for(var p=0;p=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(y,m){var w=typeof Symbol=="function"&&y[Symbol.iterator];if(!w)return y;var x,C,S=w.call(y),_=[];try{for(;(m===void 0||m-- >0)&&!(x=S.next()).done;)_.push(x.value)}catch(T){C={error:T}}finally{try{x&&!x.done&&(w=S.return)&&w.call(S)}finally{if(C)throw C.error}}return _},s=this&&this.__spread||function(){for(var y=[],m=0;m",amp:"&",quot:'"',apos:"'"},s}();n.BaseReader=a},function(r,n,i){var o=i(39);r.exports=o.DEFAULT=new o({include:[i(54)],explicit:[i(299),i(300),i(301)]})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(185);n.XMLBuilderImpl=o.XMLBuilderImpl;var a=i(304);n.XMLBuilderCBImpl=a.XMLBuilderCBImpl;var s=i(183);n.builder=s.builder,n.create=s.create,n.fragment=s.fragment,n.convert=s.convert;var c=i(309);n.createCB=c.createCB,n.fragmentCB=c.fragmentCB},function(r,n){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch{typeof window=="object"&&(i=window)}r.exports=i},function(r,n,i){var o={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,s=a&&!o.call({1:2},1);n.f=s?function(c){var l=a(this,c);return!!l&&l.enumerable}:o},function(r,n,i){var o=i(11),a=i(21);r.exports=function(s,c){try{a(o,s,c)}catch{o[s]=c}return c}},function(r,n,i){var o=i(44),a=i(118);(r.exports=function(s,c){return a[s]||(a[s]=c!==void 0?c:{})})("versions",[]).push({version:"3.6.5",mode:o?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},function(r,n,i){var o=i(121),a=i(84).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(s){return o(s,a)}},function(r,n,i){var o=i(47),a=Math.max,s=Math.min;r.exports=function(c,l){var f=o(c);return f<0?a(f+l,0):s(f,l)}},function(r,n){r.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(r,n){n.f=Object.getOwnPropertySymbols},function(r,n,i){var o=i(8);r.exports=!!Object.getOwnPropertySymbols&&!o(function(){return!String(Symbol())})},function(r,n,i){var o=i(127);r.exports=function(a,s,c){if(o(a),s===void 0)return a;switch(c){case 0:return function(){return a.call(s)};case 1:return function(l){return a.call(s,l)};case 2:return function(l,f){return a.call(s,l,f)};case 3:return function(l,f,u){return a.call(s,l,f,u)}}return function(){return a.apply(s,arguments)}}},function(r,n,i){var o=i(4),a=i(195),s=i(132),c=i(133),l=i(62),f=i(21),u=i(25),d=i(5),h=i(44),g=i(49),p=i(131),v=p.IteratorPrototype,y=p.BUGGY_SAFARI_ITERATORS,m=d("iterator"),w=function(){return this};r.exports=function(x,C,S,_,T,E,D){a(S,C,_);var b,I,P,M=function(j){if(j===T&&k)return k;if(!y&&j in G)return G[j];switch(j){case"keys":case"values":case"entries":return function(){return new S(this,j)}}return function(){return new S(this)}},L=C+" Iterator",V=!1,G=x.prototype,A=G[m]||G["@@iterator"]||T&&G[T],k=!y&&A||M(T),F=C=="Array"&&G.entries||A;if(F&&(b=s(F.call(new x)),v!==Object.prototype&&b.next&&(h||s(b)===v||(c?c(b,v):typeof b[m]!="function"&&f(b,m,w)),l(b,L,!0,!0),h&&(g[L]=w))),T=="values"&&A&&A.name!=="values"&&(V=!0,k=function(){return A.call(this)}),h&&!D||G[m]===k||f(G,m,k),g[C]=k,T)if(I={values:M("values"),keys:E?k:M("keys"),entries:M("entries")},D)for(P in I)(y||V||!(P in G))&&u(G,P,I[P]);else o({target:C,proto:!0,forced:y||V},I);return I}},function(r,n,i){var o=i(4),a=i(13),s=i(59),c=i(83),l=i(26),f=i(24),u=i(134),d=i(5),h=i(63),g=i(28),p=h("slice"),v=g("slice",{ACCESSORS:!0,0:0,1:2}),y=d("species"),m=[].slice,w=Math.max;o({target:"Array",proto:!0,forced:!p||!v},{slice:function(x,C){var S,_,T,E=f(this),D=l(E.length),b=c(x,D),I=c(C===void 0?D:C,D);if(s(E)&&(typeof(S=E.constructor)!="function"||S!==Array&&!s(S.prototype)?a(S)&&(S=S[y])===null&&(S=void 0):S=void 0,S===Array||S===void 0))return m.call(E,b,I);for(_=new(S===void 0?Array:S)(w(I-b,0)),T=0;b({voiRange:{...this.voiRange}}),this.resetCamera=()=>!0,this.getNumberOfSlices=()=>1,this.getFrameOfReferenceUID=()=>this.frameOfReferenceUID,this.resize=()=>{const n=this.canvas,{clientWidth:i,clientHeight:o}=n;(n.width!==i||n.height!==o)&&(n.width=i,n.height=o),this.refreshRenderValues()},this.canvasToWorld=n=>{if(!this.metadata)return;const i=this.canvasToIndex(n);return i[1]=-i[1],this.indexToWorld(i)},this.worldToCanvas=n=>{if(!this.metadata)return;const i=this.worldToIndex(n);return i[1]=-i[1],this.indexToCanvas([i[0],i[1],0])},this.postrender=()=>{this.refreshRenderValues(),at(this.element,Xe.IMAGE_RENDERED,{element:this.element,viewportId:this.id,viewport:this,renderingEngineId:this.renderingEngineId})},this.getRotation=()=>0,this.canvasToIndex=n=>{const i=this.getTransform();i.invert();const o=i.transformPoint(n.map(a=>a*devicePixelRatio));return[o[0],o[1],0]},this.indexToCanvas=n=>this.getTransform().transformPoint([n[0],n[1]]).map(o=>o/devicePixelRatio),this.customRenderViewportToCanvas=()=>{},this.getImageIds=()=>[this.imageIds[0]],this.renderingEngineId=e.renderingEngineId,this.element.setAttribute("data-viewport-uid",this.id),this.element.setAttribute("data-rendering-engine-uid",this.renderingEngineId),this.element.style.position="relative",this.microscopyElement=document.createElement("div"),this.microscopyElement.setAttribute("class","DicomMicroscopyViewer"),this.microscopyElement.id=Dn(),this.microscopyElement.innerText="Initial",this.microscopyElement.style.background="grey",this.microscopyElement.style.width="100%",this.microscopyElement.style.height="100%",this.microscopyElement.style.position="absolute",this.microscopyElement.style.left="0",this.microscopyElement.style.top="0";const r=this.element.firstElementChild;r.insertBefore(this.microscopyElement,r.childNodes[1]),this.addEventListeners(),this.addWidget("DicomMicroscopyViewer",{getEnabled:()=>!!this.viewer,setEnabled:()=>{this.elementDisabledHandler()}}),this.resize()}static get useCustomRenderingPipeline(){return!0}addEventListeners(){this.canvas.addEventListener(Xe.ELEMENT_DISABLED,this.elementDisabledHandler)}removeEventListeners(){this.canvas.removeEventListener(Xe.ELEMENT_DISABLED,this.elementDisabledHandler)}elementDisabledHandler(){var r;this.removeEventListeners(),(r=this.viewer)==null||r.cleanup(),this.viewer=null,this.element.firstElementChild.removeChild(this.microscopyElement),this.microscopyElement=null}getImageDataMetadata(e=0){var E;const r=this.metadataDicomweb.reduce((D,b)=>(D==null?void 0:D.NumberOfFrames){i.style.filter=r})}setAverageWhite(e){this.averageWhite=e,this.setColorTransform(this.voiRange,e)}getScalarData(){return null}computeTransforms(){const e=Zo(),r=Zo();return f1(e,this.metadata.origin),e[0]=this.metadata.direction[0],e[1]=this.metadata.direction[1],e[2]=this.metadata.direction[2],e[4]=this.metadata.direction[3],e[5]=this.metadata.direction[4],e[6]=this.metadata.direction[5],e[8]=this.metadata.direction[6],e[9]=this.metadata.direction[7],e[10]=this.metadata.direction[8],Qs(e,e,this.metadata.spacing),oi(r,e),{indexToWorld:e,worldToIndex:r}}getImageData(){const{metadata:e}=this;if(!e)return null;const{spacing:r}=e,n={getDirection:()=>e.direction,getDimensions:()=>e.dimensions,getRange:()=>[0,255],getScalarData:()=>this.getScalarData(),getSpacing:()=>e.spacing,worldToIndex:o=>this.worldToIndex(o),indexToWorld:o=>this.indexToWorld(o)};return{dimensions:e.dimensions,spacing:r,numberOfComponents:3,origin:e.origin,direction:e.direction,metadata:{Modality:this.modality,FrameOfReferenceUID:this.frameOfReferenceUID},hasPixelSpacing:this.hasPixelSpacing,calibration:this.calibration,preScale:{scaled:!1},scalarData:this.getScalarData(),imageData:n}}hasImageURI(e){return!0}setCamera(e){const r=this.getCamera(),{parallelScale:n,focalPoint:i}=e,o=this.getView(),{xSpacing:a}=this.internalCamera;if(n){const c=this.element.clientHeight/n,l=1/a/c;o.setResolution(l)}if(i){const c=this.worldToCanvas(i),l=this.canvasToIndex(c);o.setCenter(l)}const s=this.getCamera();this.triggerCameraModifiedEventIfNecessary(r,s)}getCurrentImageId(){return this.imageIds[0]}getFrameNumber(){return 1}getCamera(){this.refreshRenderValues();const{resolution:e,xSpacing:r,centerIndex:n}=this.internalCamera,i=e*r,o=this.indexToCanvas([n[0],n[1],0]),a=this.canvasToWorld(o);return{parallelProjection:!0,focalPoint:a,position:a,viewUp:[0,-1,0],parallelScale:this.element.clientHeight*i,viewPlaneNormal:[0,0,1]}}worldToIndexWSI(e){if(!$h)return;const r=this.viewer[T9],n=$h.applyInverseTransform({coordinate:[e[0],e[1]],affine:r});return[n[0],n[1]]}indexToWorldWSI(e){if(!$h)return;const r=$h.applyTransform({coordinate:[e[0],e[1]],affine:this.viewer[T9]});return[r[0],r[1],0]}worldToIndex(e){const{worldToIndex:r}=this.computeTransforms(),n=Ve();return Jt(n,e,r),n}indexToWorld(e){const{indexToWorld:r}=this.computeTransforms(),n=Ve(),i=bt(...e);return Jt(n,i,r),[n[0],n[1],n[2]]}setDataIds(e,r){(r==null?void 0:r.miniNavigationOverlay)!==!1&&Qd.addMiniNavigationOverlayCss();const n=(r==null?void 0:r.webClient)||mt(Oo.WADO_WEB_CLIENT,e[0]);if(!n)throw new Error(`To use setDataIds on WSI data, you must provide metaData.webClient for ${e[0]}`);return this.setWSI(e,n)}async setWSI(e,r){this.microscopyElement.style.background="black",this.microscopyElement.innerText="Loading",this.imageIds=e;const n=await Qd.getDicomMicroscopyViewer();$h||($h=n.utils),this.frameOfReferenceUID=null;const i=this.imageIds.map(s=>{var u,d,h;const c=r.getDICOMwebMetadata(s);Object.defineProperty(c,"isMultiframe",{value:c.isMultiframe,enumerable:!1}),Object.defineProperty(c,"frameNumber",{value:void 0,enumerable:!1});const l=(u=c["00080008"])==null?void 0:u.Value;(l==null?void 0:l.length)===1&&(c["00080008"].Value=l[0].split("\\"));const f=(h=(d=c["00200052"])==null?void 0:d.Value)==null?void 0:h[0];return this.frameOfReferenceUID?f!==this.frameOfReferenceUID&&(c["00200052"].Value=[this.frameOfReferenceUID]):this.frameOfReferenceUID=f,c}),o=[];i.forEach(s=>{const c=new n.metadata.VLWholeSlideMicroscopyImage({metadata:s}),l=c.ImageType[2];l==="VOLUME"||l==="THUMBNAIL"?o.push(c):console.log("Unknown image type",c.ImageType)}),this.metadataDicomweb=o;const a=new n.viewer.VolumeImageViewer({client:r,metadata:o,controls:["overview","position"],retrieveRendered:!1,bindings:{}});a.render({container:this.microscopyElement}),this.metadata=this.getImageDataMetadata(),a.deactivateDragPanInteraction(),this.viewer=a,this.map=a[_9],this.map.on(bae,this.postrender),this.resize(),this.microscopyElement.innerText="",Object.assign(this.microscopyElement.style,{"--ol-partial-background-color":"rgba(127, 127, 127, 0.7)","--ol-foreground-color":"#000000","--ol-subtle-foreground-color":"#000","--ol-subtle-background-color":"rgba(78, 78, 78, 0.5)",background:"none"})}scroll(e){const r=this.getCamera();this.setCamera({parallelScale:r.parallelScale*(1+.1*e)})}getSliceIndex(){return 0}getView(){if(!this.viewer)return;const e=this.viewer[_9],r=window;return r.map=e,r.viewer=this.viewer,r.view=e==null?void 0:e.getView(),r.wsi=this,e==null?void 0:e.getView()}refreshRenderValues(){const e=this.getView();if(!e)return;const r=e.getResolution();if(!r||rjZ("dicom-microscopy-viewer"),Qd.overlayCssId="overlayCss";let fC=Qd;const xA={[mr.ORTHOGRAPHIC]:ur,[mr.PERSPECTIVE]:ur,[mr.STACK]:lr,[mr.VOLUME_3D]:wA,[mr.VIDEO]:Rp,[mr.WHOLE_SLIDE]:fC};function Sd(t){return xA[t].useCustomRenderingPipeline}const E9=2;class CA{constructor(e){if(this._needsRender=new Set,this._animationFrameSet=!1,this._animationFrameHandle=null,this.renderFrameOfReference=r=>{const i=this._getViewportsAsArray().map(o=>{if(o.getFrameOfReferenceUID()===r)return o.id});this.renderViewports(i)},this._renderFlaggedViewports=()=>{this._throwIfDestroyed(),this.useCPURendering||this.performVtkDrawCall();const r=this._getViewportsAsArray(),n=[];for(let i=0;i{i!=null&&i.element&&at(i.element,Xe.IMAGE_RENDERED,i)})},this.id=e||Dn(),this.useCPURendering=kg(),Tp.set(this),!$Z())throw new Error("@cornerstonejs/core is not initialized, run init() first");this.useCPURendering||(this.offscreenMultiRenderWindow=Pee.newInstance(),this.offScreenCanvasContainer=document.createElement("div"),this.offscreenMultiRenderWindow.setContainer(this.offScreenCanvasContainer)),this._viewports=new Map,this.hasBeenDestroyed=!1}enableElement(e){const r=this._normalizeViewportInputEntry(e);this._throwIfDestroyed();const{element:n,viewportId:i}=r;if(!n)throw new Error("No element provided");this.getViewport(i)&&this.disableElement(i);const{type:a}=r,s=Sd(a);!this.useCPURendering&&!s?this.enableVTKjsDrivenViewport(r):this.addCustomViewport(r);const c=Mc(n),{background:l}=r.defaultOptions;this.fillCanvasWithBackgroundColor(c,l)}disableElement(e){this._throwIfDestroyed();const r=this.getViewport(e);if(!r){console.warn(`viewport ${e} does not exist`);return}this._resetViewport(r),!Sd(r.type)&&!this.useCPURendering&&this.offscreenMultiRenderWindow.removeRenderer(e),this._removeViewport(e),r.isDisabled=!0,this._needsRender.delete(e),this.getViewports().length||this._clearAnimationFrame()}setViewports(e){const r=this._normalizeViewportInputEntries(e);this._throwIfDestroyed(),this._reset();const n=[],i=[];r.forEach(o=>{!this.useCPURendering&&!Sd(o.type)?n.push(o):i.push(o)}),this.setVtkjsDrivenViewports(n),this.setCustomViewports(i),r.forEach(o=>{const a=Mc(o.element),{background:s}=o.defaultOptions;this.fillCanvasWithBackgroundColor(a,s)})}resize(e=!0,r=!0){this._throwIfDestroyed();const n=this._getViewportsAsArray(),i=[],o=[];n.forEach(a=>{Sd(a.type)?o.push(a):i.push(a)}),i.length&&this._resizeVTKViewports(i,r,e),o.length&&this._resizeUsingCustomResizeHandler(o,r,e)}getViewport(e){var r;return(r=this._viewports)==null?void 0:r.get(e)}getViewports(){return this._throwIfDestroyed(),this._getViewportsAsArray()}getStackViewport(e){this._throwIfDestroyed();const r=this.getViewport(e);if(!r)throw new Error(`Viewport with Id ${e} does not exist`);if(!(r instanceof lr))throw new Error(`Viewport with Id ${e} is not a StackViewport.`);return r}getStackViewports(){return this._throwIfDestroyed(),this.getViewports().filter(r=>r instanceof lr)}getVolumeViewports(){this._throwIfDestroyed();const e=this.getViewports(),r=n=>n instanceof Ir;return e.filter(r)}render(){const r=this.getViewports().map(n=>n.id);this._setViewportsToBeRenderedNextFrame(r)}renderViewports(e){this._setViewportsToBeRenderedNextFrame(e)}renderViewport(e){this._setViewportsToBeRenderedNextFrame([e])}destroy(){this.hasBeenDestroyed||(this.useCPURendering||(this._getViewportsAsArray().forEach(r=>{this.offscreenMultiRenderWindow.removeRenderer(r.id)}),this.offscreenMultiRenderWindow.delete(),delete this.offscreenMultiRenderWindow),this._reset(),Tp.delete(this.id),this.hasBeenDestroyed=!0)}fillCanvasWithBackgroundColor(e,r){const n=e.getContext("2d");let i;if(r){const o=r.map(a=>Math.floor(255*a));i=`rgb(${o[0]}, ${o[1]}, ${o[2]})`}else i="black";n.fillStyle=i,n.fillRect(0,0,e.width,e.height)}_normalizeViewportInputEntry(e){const{type:r,defaultOptions:n}=e;let i=n;return(!i||Object.keys(i).length===0)&&(i={background:[0,0,0],orientation:null,displayArea:null},r===mr.ORTHOGRAPHIC&&(i={...i,orientation:Kf.AXIAL})),{...e,defaultOptions:i}}_normalizeViewportInputEntries(e){const r=[];return e.forEach(n=>{r.push(this._normalizeViewportInputEntry(n))}),r}_resizeUsingCustomResizeHandler(e,r=!0,n=!0){e.forEach(i=>{typeof i.resize=="function"&&i.resize()}),e.forEach(i=>{const o=i.getCamera();i.resetCamera(),r&&i.setCamera(o)}),n&&this.render()}_resizeVTKViewports(e,r=!0,n=!0){const i=e.map(o=>Mc(o.element));if(i.forEach(o=>{const a=window.devicePixelRatio||1;o.width=o.clientWidth*a,o.height=o.clientHeight*a}),i.length){const{offScreenCanvasWidth:o,offScreenCanvasHeight:a}=this._resizeOffScreenCanvas(i);this._resize(e,o,a)}e.forEach(o=>{const a=o.getCamera(),s=o.getRotation(),{flipHorizontal:c}=a;o.resetCameraForResize();const l=o.getDisplayArea();r&&(l?(c&&o.setCamera({flipHorizontal:c}),s&&o.setViewPresentation({rotation:s})):o.setCamera(a))}),n&&this.render()}enableVTKjsDrivenViewport(e){const n=this._getViewportsAsArray().filter(f=>Sd(f.type)===!1),i=n.map(f=>f.canvas),o=Mc(e.element);i.push(o);const{offScreenCanvasWidth:a,offScreenCanvasHeight:s}=this._resizeOffScreenCanvas(i),c=this._resize(n,a,s),l={...e,canvas:o};this.addVtkjsDrivenViewport(l,{offScreenCanvasWidth:a,offScreenCanvasHeight:s,xOffset:c})}_removeViewport(e){if(!this.getViewport(e)){console.warn(`viewport ${e} does not exist`);return}this._viewports.delete(e)}addVtkjsDrivenViewport(e,r){const{element:n,canvas:i,viewportId:o,type:a,defaultOptions:s}=e;n.tabIndex=-1;const{offScreenCanvasWidth:c,offScreenCanvasHeight:l,xOffset:f}=r,{sxStartDisplayCoords:u,syStartDisplayCoords:d,sxEndDisplayCoords:h,syEndDisplayCoords:g,sx:p,sy:v,sWidth:y,sHeight:m}=this._getViewportCoordsOnOffScreenCanvas(e,c,l,f);this.offscreenMultiRenderWindow.addRenderer({viewport:[u,d,h,g],id:o,background:s.background?s.background:[0,0,0]});const w={id:o,element:n,renderingEngineId:this.id,type:a,canvas:i,sx:p,sy:v,sWidth:y,sHeight:m,defaultOptions:s||{}};let x;if(a===mr.STACK)x=new lr(w);else if(a===mr.ORTHOGRAPHIC||a===mr.PERSPECTIVE)x=new ur(w);else if(a===mr.VOLUME_3D)x=new wA(w);else throw new Error(`Viewport Type ${a} is not supported`);this._viewports.set(o,x);const C={element:n,viewportId:o,renderingEngineId:this.id};x.suppressEvents||at(Ke,Xe.ELEMENT_ENABLED,C)}addCustomViewport(e){const{element:r,viewportId:n,type:i,defaultOptions:o}=e;r.tabIndex=-1;const a=Mc(r),{clientWidth:s,clientHeight:c}=a;(a.width!==s||a.height!==c)&&(a.width=s,a.height=c);const l={id:n,renderingEngineId:this.id,element:r,type:i,canvas:a,sx:0,sy:0,sWidth:s,sHeight:c,defaultOptions:o||{}},f=xA[i],u=new f(l);this._viewports.set(n,u);const d={element:r,viewportId:n,renderingEngineId:this.id};at(Ke,Xe.ELEMENT_ENABLED,d)}setCustomViewports(e){e.forEach(r=>{this.addCustomViewport(r)})}setVtkjsDrivenViewports(e){if(e.length){const r=e.map(a=>Mc(a.element));r.forEach(a=>{const s=window.devicePixelRatio||1,c=a.getBoundingClientRect();a.width=c.width*s,a.height=c.height*s});const{offScreenCanvasWidth:n,offScreenCanvasHeight:i}=this._resizeOffScreenCanvas(r);let o=0;for(let a=0;aa.height));let o=0;return e.forEach(a=>{o+=a.width}),r.width=o,r.height=i,n.resize(),{offScreenCanvasWidth:o,offScreenCanvasHeight:i}}_resize(e,r,n){let i=0;for(let o=0;o{this._needsRender.add(r)}),this._render()}_render(){this._needsRender.size>0&&!this._animationFrameSet&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedViewports),this._animationFrameSet=!0)}performVtkDrawCall(){const{offscreenMultiRenderWindow:e}=this,r=e.getRenderWindow(),n=e.getRenderers();if(n.length){for(let i=0;i{this._resetViewport(r)}),this._clearAnimationFrame(),this._viewports=new Map}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_downloadOffScreenCanvas(){const e=this._debugRender();Iae(e)}_debugRender(){const{offscreenMultiRenderWindow:e}=this,r=e.getRenderWindow(),n=e.getRenderers();for(let c=0;c{const{sx:l,sy:f,sWidth:u,sHeight:d}=c,h=c.canvas,{width:g,height:p}=h;h.getContext("2d").drawImage(a,l,f,u,d,0,0,g,p)}),s}}function Iae(t){const e=document.createElement("a");e.download="viewport.png",e.href=t,document.body.appendChild(e),e.click(),document.body.removeChild(e)}function SA(t){return new TextDecoder("latin1").decode(t)}function Oae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;const n=SA(t),i=e.exec(n);if(!i)return{text:n};const o=i.index+i[0].length,a=n.substring(0,o);let s=null;const c=r?r.exec(n):null;if(c){const l=n.substr(c.index);s={text:a+l,binaryBuffer:t.slice(o,c.index)}}else s={text:a,binaryBuffer:t.slice(o)};return s}var Mae={arrayBufferToString:SA,extractBinary:Oae};const PT={};function _A(t){return!!PT[t]}function Pae(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"http",e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return PT[t](e)}function TA(t,e){PT[t]=e}var Rae={get:Pae,has:_A,registerType:TA};function EA(){const t=new ArrayBuffer(4),e=new Uint8Array(t),r=new Uint32Array(t);return e[0]=161,e[1]=178,e[2]=195,e[3]=212,r[0]===3569595041?"LittleEndian":r[0]===2712847316?"BigEndian":null}const Lae=EA();function Aae(t,e){if(e<2)return;const r=new Int8Array(t),n=r.length,i=[];for(let o=0;o(DA("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead."),Promise.reject(new Error("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead.")));let G0=0;function l5(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const n=new XMLHttpRequest;return n.open(t,e,!0),r.headers&&Object.entries(r.headers).forEach(i=>{let[o,a]=i;return n.setRequestHeader(o,a)}),r.progressCallback&&n.addEventListener("progress",r.progressCallback),n}function kae(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((r,n)=>{const i=l5("GET",t,e);i.onreadystatechange=o=>{i.readyState===4&&(i.status===200||i.status===0?r(i.response):n({xhr:i,e:o}))},i.responseType="arraybuffer",i.send()})}function Vae(t,e,r){let n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return n&&n.compression?RT():r.ref&&!r.ref.pending?new Promise((i,o)=>{const a=[e,r.ref.basepath,r.ref.id].join("/"),s=l5("GET",a,n);s.onreadystatechange=c=>{s.readyState===1&&(r.ref.pending=!0,++G0===1&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!0)),s.readyState===4&&(r.ref.pending=!1,s.status===200||s.status===0?(r.buffer=s.response,r.ref.encode==="JSON"?r.values=JSON.parse(r.buffer):(jw.ENDIANNESS!==r.ref.encode&&jw.ENDIANNESS&&(Nae(`Swap bytes of ${r.name}`),jw.swapBytes(r.buffer,AO[r.dataType])),r.values=ne.newTypedArray(r.dataType,r.buffer)),r.values.length!==r.size&&DA(`Error in FetchArray: ${r.name}, does not have the proper array size. Got ${r.values.length}, instead of ${r.size}`),delete r.ref,--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),t!=null&&t.modified&&t.modified(),i(r)):o({xhr:s,e:c}))},s.responseType=r.dataType!=="string"?"arraybuffer":"text",s.send()}):Promise.resolve(r)}function Fae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r&&r.compression?RT():new Promise((n,i)=>{const o=l5("GET",e,r);o.onreadystatechange=a=>{o.readyState===1&&++G0===1&&t!=null&&t.invokeBusy&&t.invokeBusy(!0),o.readyState===4&&(--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),o.status===200||o.status===0?n(JSON.parse(o.responseText)):i({xhr:o,e:a}))},o.responseType="text",o.send()})}function Uae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r&&r.compression?RT():new Promise((n,i)=>{const o=l5("GET",e,r);o.onreadystatechange=a=>{o.readyState===1&&++G0===1&&t!=null&&t.invokeBusy&&t.invokeBusy(!0),o.readyState===4&&(--G0===0&&(t!=null&&t.invokeBusy)&&t.invokeBusy(!1),o.status===200||o.status===0?n(o.responseText):i({xhr:o,e:a}))},o.responseType="text",o.send()})}function Bae(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((n,i)=>{const o=new Image;r.crossOrigin&&(o.crossOrigin=r.crossOrigin),o.onload=()=>n(o),o.onerror=i,o.src=e})}const Gae={fetchArray:Vae,fetchJSON:Fae,fetchText:Uae,fetchBinary:kae,fetchImage:Bae};_A("http")||TA("http",t=>Gae);var bA={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Pi,function(){return function(r){var n={};function i(o){if(n[o])return n[o].exports;var a=n[o]={i:o,l:!1,exports:{}};return r[o].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return i.m=r,i.c=n,i.d=function(o,a,s){i.o(o,a)||Object.defineProperty(o,a,{enumerable:!0,get:s})},i.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},i.t=function(o,a){if(1&a&&(o=i(o)),8&a||4&a&&typeof o=="object"&&o&&o.__esModule)return o;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:o}),2&a&&typeof o!="string")for(var c in o)i.d(s,c,(function(l){return o[l]}).bind(null,c));return s},i.n=function(o){var a=o&&o.__esModule?function(){return o.default}:function(){return o};return i.d(a,"a",a),a},i.o=function(o,a){return Object.prototype.hasOwnProperty.call(o,a)},i.p="",i(i.s=184)}([function(r,n,i){function o(a){for(var s in a)n.hasOwnProperty(s)||(n[s]=a[s])}Object.defineProperty(n,"__esModule",{value:!0}),o(i(240)),o(i(251)),o(i(175)),o(i(107)),o(i(29)),o(i(73)),o(i(106)),o(i(30)),o(i(252)),o(i(52)),o(i(97)),o(i(253)),o(i(37)),o(i(51)),o(i(173)),o(i(176)),o(i(172)),o(i(108)),o(i(254)),o(i(255)),o(i(256)),o(i(72)),o(i(177)),o(i(105)),o(i(17)),o(i(257)),o(i(12)),o(i(174))},function(r,n,i){var o=this&&this.__values||function(w){var x=typeof Symbol=="function"&&Symbol.iterator,C=x&&w[x],S=0;if(C)return C.call(w);if(w&&typeof w.length=="number")return{next:function(){return w&&S>=w.length&&(w=void 0),{value:w&&w[S++],done:!w}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(212);n.FixedSizeSet=a.FixedSizeSet;var s=i(213);n.ObjectCache=s.ObjectCache;var c=i(214);n.CompareCache=c.CompareCache;var l=i(215);n.Lazy=l.Lazy;var f=i(216);function u(w,x,C){if(y(w))w.forEach(function(_,T){return x.call(C,T,_)});else for(var S in w)w.hasOwnProperty(S)&&x.call(C,S,w[S])}function d(w){var x,C;if(h(w))return w;if(p(w)){var S=[];try{for(var _=o(w),T=_.next();!T.done;T=_.next()){var E=T.value;S.push(d(E))}}catch(I){x={error:I}}finally{try{T&&!T.done&&(C=_.return)&&C.call(_)}finally{if(x)throw x.error}}return S}if(g(w)){S={};for(var D in w)if(w.hasOwnProperty(D)){var b=w[D];S[D]=d(b)}return S}return w}function h(w){return!!w&&Object.prototype.toString.call(w)==="[object Function]"}function g(w){var x=typeof w;return!!w&&(x==="function"||x==="object")}function p(w){return Array.isArray(w)}function v(w){return w instanceof Set}function y(w){return w instanceof Map}function m(w){if(g(w)){var x=Object.getPrototypeOf(w),C=x.constructor;return x&&C&&typeof C=="function"&&C instanceof C&&Function.prototype.toString.call(C)===Function.prototype.toString.call(Object)}return!1}n.StringWalker=f.StringWalker,n.applyMixin=function(w,x){for(var C=[],S=2;S>6|192;else{if(_>55295&&_<56320){if(++S>=w.length)throw new Error("Incomplete surrogate pair.");var T=w.charCodeAt(S);if(T<56320||T>57343)throw new Error("Invalid surrogate character.");_=65536+((1023&_)<<10)+(1023&T),x[C++]=_>>18|240,x[C++]=_>>12&63|128}else x[C++]=_>>12|224;x[C++]=_>>6&63|128}x[C++]=63&_|128}}return x.subarray(0,C)},n.utf8Decode=function(w){for(var x="",C=0;C127)if(S>191&&S<224){if(C>=w.length)throw new Error("Incomplete 2-byte sequence.");S=(31&S)<<6|63&w[C++]}else if(S>223&&S<240){if(C+1>=w.length)throw new Error("Incomplete 3-byte sequence.");S=(15&S)<<12|(63&w[C++])<<6|63&w[C++]}else{if(!(S>239&&S<248))throw new Error("Unknown multi-byte start.");if(C+2>=w.length)throw new Error("Incomplete 4-byte sequence.");S=(7&S)<<18|(63&w[C++])<<12|(63&w[C++])<<6|63&w[C++]}if(S<=65535)x+=String.fromCharCode(S);else{if(!(S<=1114111))throw new Error("Code point exceeds UTF-16 limit.");S-=65536,x+=String.fromCharCode(S>>10|55296),x+=String.fromCharCode(1023&S|56320)}}return x}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),function(o){o[o.Before=0]="Before",o[o.Equal=1]="Equal",o[o.After=2]="After"}(n.BoundaryPosition||(n.BoundaryPosition={})),function(o){o[o.None=0]="None",o[o.Capturing=1]="Capturing",o[o.AtTarget=2]="AtTarget",o[o.Bubbling=3]="Bubbling"}(n.EventPhase||(n.EventPhase={})),function(o){o[o.Element=1]="Element",o[o.Attribute=2]="Attribute",o[o.Text=3]="Text",o[o.CData=4]="CData",o[o.EntityReference=5]="EntityReference",o[o.Entity=6]="Entity",o[o.ProcessingInstruction=7]="ProcessingInstruction",o[o.Comment=8]="Comment",o[o.Document=9]="Document",o[o.DocumentType=10]="DocumentType",o[o.DocumentFragment=11]="DocumentFragment",o[o.Notation=12]="Notation"}(n.NodeType||(n.NodeType={})),function(o){o[o.Disconnected=1]="Disconnected",o[o.Preceding=2]="Preceding",o[o.Following=4]="Following",o[o.Contains=8]="Contains",o[o.ContainedBy=16]="ContainedBy",o[o.ImplementationSpecific=32]="ImplementationSpecific"}(n.Position||(n.Position={})),function(o){o[o.Accept=1]="Accept",o[o.Reject=2]="Reject",o[o.Skip=3]="Skip"}(n.FilterResult||(n.FilterResult={})),function(o){o[o.All=4294967295]="All",o[o.Element=1]="Element",o[o.Attribute=2]="Attribute",o[o.Text=4]="Text",o[o.CDataSection=8]="CDataSection",o[o.EntityReference=16]="EntityReference",o[o.Entity=32]="Entity",o[o.ProcessingInstruction=64]="ProcessingInstruction",o[o.Comment=128]="Comment",o[o.Document=256]="Document",o[o.DocumentType=512]="DocumentType",o[o.DocumentFragment=1024]="DocumentFragment",o[o.Notation=2048]="Notation"}(n.WhatToShow||(n.WhatToShow={})),function(o){o[o.StartToStart=0]="StartToStart",o[o.StartToEnd=1]="StartToEnd",o[o.EndToEnd=2]="EndToEnd",o[o.EndToStart=3]="EndToStart"}(n.HowToCompare||(n.HowToCompare={}))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(241);n.Cast=o.Cast;var a=i(150);n.Guard=a.Guard;var s=i(242);n.EmptySet=s.EmptySet},function(r,n,i){var o=i(11),a=i(55).f,s=i(21),c=i(25),l=i(80),f=i(119),u=i(123);r.exports=function(d,h){var g,p,v,y,m,w=d.target,x=d.global,C=d.stat;if(g=x?o:C?o[w]||l(w,{}):(o[w]||{}).prototype)for(p in h){if(y=h[p],v=d.noTargetGet?(m=a(g,p))&&m.value:g[p],!u(x?p:w+(C?".":"#")+p,d.forced)&&v!==void 0){if(typeof y==typeof v)continue;f(y,v)}(d.sham||v&&v.sham)&&s(y,"sham",!0),c(g,p,y,d)}}},function(r,n,i){var o=i(11),a=i(81),s=i(14),c=i(58),l=i(86),f=i(124),u=a("wks"),d=o.Symbol,h=f?d:d&&d.withoutSetter||c;r.exports=function(g){return s(u,g)||(l&&s(d,g)?u[g]=d[g]:u[g]=h("Symbol."+g)),u[g]}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(1),a=i(29),s=function(){function c(){this._features={mutationObservers:!0,customElements:!0,slots:!0,steps:!0},this._window=null,this._compareCache=new o.CompareCache,this._rangeList=new o.FixedSizeSet}return c.prototype.setFeatures=function(l){if(l===void 0&&(l=!0),o.isObject(l))for(var f in l)this._features[f]=l[f]||!1;else for(var f in this._features)this._features[f]=l},Object.defineProperty(c.prototype,"features",{get:function(){return this._features},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"window",{get:function(){return this._window===null&&(this._window=a.create_window()),this._window},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"compareCache",{get:function(){return this._compareCache},enumerable:!0,configurable:!0}),Object.defineProperty(c.prototype,"rangeList",{get:function(){return this._rangeList},enumerable:!0,configurable:!0}),Object.defineProperty(c,"instance",{get:function(){return c._instance||(c._instance=new c),c._instance},enumerable:!0,configurable:!0}),c}();n.dom=s.instance},function(r,n,i){var o=this&&this.__importStar||function(m){if(m&&m.__esModule)return m;var w={};if(m!=null)for(var x in m)Object.hasOwnProperty.call(m,x)&&(w[x]=m[x]);return w.default=m,w};Object.defineProperty(n,"__esModule",{value:!0});var a=o(i(228));n.base64=a;var s=o(i(146));n.byte=s;var c=o(i(147));n.byteSequence=c;var l=o(i(96));n.codePoint=l;var f=o(i(232));n.json=f;var u=o(i(233));n.list=u;var d=o(i(234));n.map=d;var h=o(i(235));n.namespace=h;var g=o(i(236));n.queue=g;var p=o(i(237));n.set=p;var v=o(i(238));n.stack=v;var y=o(i(239));n.string=y},function(r,n){r.exports=function(i){try{return!!i()}catch{return!0}}},function(r,n,i){var o,a=this&&this.__extends||(o=function(A,k){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(F,j){F.__proto__=j}||function(F,j){for(var Y in j)j.hasOwnProperty(Y)&&(F[Y]=j[Y])})(A,k)},function(A,k){function F(){this.constructor=A}o(A,k),A.prototype=k===null?Object.create(k):(F.prototype=k.prototype,new F)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(A){function k(F,j){j===void 0&&(j="");var Y=A.call(this,j)||this;return Y.name=F,Y}return a(k,A),k}(Error);n.DOMException=s;var c=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"DOMStringSizeError",F)||this}return a(k,A),k}(s);n.DOMStringSizeError=c;var l=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"WrongDocumentError","The object is in the wrong document. "+F)||this}return a(k,A),k}(s);n.WrongDocumentError=l;var f=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NoDataAllowedError",F)||this}return a(k,A),k}(s);n.NoDataAllowedError=f;var u=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NoModificationAllowedError","The object can not be modified. "+F)||this}return a(k,A),k}(s);n.NoModificationAllowedError=u;var d=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotSupportedError","The operation is not supported. "+F)||this}return a(k,A),k}(s);n.NotSupportedError=d;var h=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InUseAttributeError",F)||this}return a(k,A),k}(s);n.InUseAttributeError=h;var g=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidStateError","The object is in an invalid state. "+F)||this}return a(k,A),k}(s);n.InvalidStateError=g;var p=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidModificationError","The object can not be modified in this way. "+F)||this}return a(k,A),k}(s);n.InvalidModificationError=p;var v=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NamespaceError","The operation is not allowed by Namespaces in XML. [XMLNS] "+F)||this}return a(k,A),k}(s);n.NamespaceError=v;var y=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidAccessError","The object does not support the operation or argument. "+F)||this}return a(k,A),k}(s);n.InvalidAccessError=y;var m=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"ValidationError",F)||this}return a(k,A),k}(s);n.ValidationError=m;var w=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"TypeMismatchError",F)||this}return a(k,A),k}(s);n.TypeMismatchError=w;var x=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"SecurityError","The operation is insecure. "+F)||this}return a(k,A),k}(s);n.SecurityError=x;var C=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NetworkError","A network error occurred. "+F)||this}return a(k,A),k}(s);n.NetworkError=C;var S=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"AbortError","The operation was aborted. "+F)||this}return a(k,A),k}(s);n.AbortError=S;var _=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"URLMismatchError","The given URL does not match another URL. "+F)||this}return a(k,A),k}(s);n.URLMismatchError=_;var T=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"QuotaExceededError","The quota has been exceeded. "+F)||this}return a(k,A),k}(s);n.QuotaExceededError=T;var E=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"TimeoutError","The operation timed out. "+F)||this}return a(k,A),k}(s);n.TimeoutError=E;var D=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidNodeTypeError","The supplied node is incorrect or has an incorrect ancestor for this operation. "+F)||this}return a(k,A),k}(s);n.InvalidNodeTypeError=D;var b=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"DataCloneError","The object can not be cloned. "+F)||this}return a(k,A),k}(s);n.DataCloneError=b;var I=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotImplementedError","The DOM method is not implemented by this module. "+F)||this}return a(k,A),k}(s);n.NotImplementedError=I;var P=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"HierarchyRequestError","The operation would yield an incorrect node tree. "+F)||this}return a(k,A),k}(s);n.HierarchyRequestError=P;var M=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"NotFoundError","The object can not be found here. "+F)||this}return a(k,A),k}(s);n.NotFoundError=M;var L=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"IndexSizeError","The index is not in the allowed range. "+F)||this}return a(k,A),k}(s);n.IndexSizeError=L;var V=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"SyntaxError","The string did not match the expected pattern. "+F)||this}return a(k,A),k}(s);n.SyntaxError=V;var G=function(A){function k(F){return F===void 0&&(F=""),A.call(this,"InvalidCharacterError","The string contains invalid characters. "+F)||this}return a(k,A),k}(s);n.InvalidCharacterError=G},function(r,n,i){var o=i(53),a=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],s=["scalar","sequence","mapping"];r.exports=function(c,l){var f,u;if(l=l||{},Object.keys(l).forEach(function(d){if(a.indexOf(d)===-1)throw new o('Unknown option "'+d+'" is met in definition of "'+c+'" YAML type.')}),this.tag=c,this.kind=l.kind||null,this.resolve=l.resolve||function(){return!0},this.construct=l.construct||function(d){return d},this.instanceOf=l.instanceOf||null,this.predicate=l.predicate||null,this.represent=l.represent||null,this.defaultStyle=l.defaultStyle||null,this.styleAliases=(f=l.styleAliases||null,u={},f!==null&&Object.keys(f).forEach(function(d){f[d].forEach(function(h){u[String(h)]=d})}),u),s.indexOf(this.kind)===-1)throw new o('Unknown kind "'+this.kind+'" is specified for "'+c+'" YAML type.')}},function(r,n,i){(function(o){var a=function(s){return s&&s.Math==Math&&s};r.exports=a(typeof globalThis=="object"&&globalThis)||a(typeof window=="object"&&window)||a(typeof self=="object"&&self)||a(typeof o=="object"&&o)||Function("return this")()}).call(this,i(78))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),n.idl_defineConst=function(o,a,s){Object.defineProperty(o,a,{writable:!1,enumerable:!0,configurable:!1,value:s})}},function(r,n){r.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(r,n){var i={}.hasOwnProperty;r.exports=function(o,a){return i.call(o,a)}},function(r,n,i){var o=i(16),a=i(115),s=i(18),c=i(56),l=Object.defineProperty;n.f=o?l:function(f,u,d){if(s(f),u=c(u,!0),s(d),a)try{return l(f,u,d)}catch{}if("get"in d||"set"in d)throw TypeError("Accessors not supported");return"value"in d&&(f[u]=d.value),f}},function(r,n,i){var o=i(8);r.exports=!o(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})},function(r,n,i){var o=this&&this.__values||function(w){var x=typeof Symbol=="function"&&Symbol.iterator,C=x&&w[x],S=0;if(C)return C.call(w);if(w&&typeof w.length=="number")return{next:function(){return w&&S>=w.length&&(w=void 0),{value:w&&w[S++],done:!w}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(3),s=i(2);function c(w,x,C){if(C===void 0&&(C=!1),C&&a.Guard.isElementNode(x)&&a.Guard.isShadowRoot(x.shadowRoot)&&x.shadowRoot._firstChild)return x.shadowRoot._firstChild;if(x._firstChild)return x._firstChild;if(x===w)return null;if(x._nextSibling)return x._nextSibling;for(var S=x._parent;S&&S!==w;){if(S._nextSibling)return S._nextSibling;S=S._parent}return null}function l(){var w;return(w={})[Symbol.iterator]=function(){return{next:function(){return{done:!0,value:null}}}},w}function f(w,x,C,S){x===void 0&&(x=!1),C===void 0&&(C=!1);for(var _=x?w:c(w,w,C);_&&S&&!S(_);)_=c(w,_,C);return _}function u(w,x,C,S,_){S===void 0&&(S=!1);for(var T=c(w,x,S);T&&_&&!_(T);)T=c(w,T,S);return T}function d(w,x,C,S){var _;return x===void 0&&(x=!1),C===void 0&&(C=!1),x||w._children.size!==0?((_={})[Symbol.iterator]=function(){var T=x?w:c(w,w,C);return{next:function(){for(;T&&S&&!S(T);)T=c(w,T,C);if(T===null)return{done:!0,value:null};var E={done:!1,value:T};return T=c(w,T,C),E}}},_):l()}function h(w,x,C){x===void 0&&(x=!1);for(var S=x?w:w._parent;S&&C&&!C(S);)S=S._parent;return S}function g(w,x,C,S){for(var _=x._parent;_&&S&&!S(_);)_=_._parent;return _}function p(w){return a.Guard.isDocumentTypeNode(w)?0:a.Guard.isCharacterDataNode(w)?w._data.length:w._children.size}function v(w,x){if(x===void 0&&(x=!1),x){var C=v(w,!1);return a.Guard.isShadowRoot(C)?v(C._host,!0):C}return w._parent?v(w._parent):w}function y(w,x,C,S){C===void 0&&(C=!1),S===void 0&&(S=!1);for(var _=C?w:S&&a.Guard.isShadowRoot(w)?w._host:w._parent;_!==null;){if(_===x)return!0;_=S&&a.Guard.isShadowRoot(_)?_._host:_._parent}return!1}function m(w){for(var x=v(w),C=0,S=f(x);S!==null;){if(C++,S===w)return C;S=u(x,S)}return-1}n.tree_getFirstDescendantNode=f,n.tree_getNextDescendantNode=u,n.tree_getDescendantNodes=d,n.tree_getDescendantElements=function(w,x,C,S){var _;return x===void 0&&(x=!1),C===void 0&&(C=!1),x||w._children.size!==0?((_={})[Symbol.iterator]=function(){var T=d(w,x,C,function(D){return a.Guard.isElementNode(D)})[Symbol.iterator](),E=T.next().value;return{next:function(){for(;E&&S&&!S(E);)E=T.next().value;if(E===null)return{done:!0,value:null};var D={done:!1,value:E};return E=T.next().value,D}}},_):l()},n.tree_getSiblingNodes=function(w,x,C){var S;return x===void 0&&(x=!1),w._parent&&w._parent._children.size!==0?((S={})[Symbol.iterator]=function(){var _=w._parent?w._parent._firstChild:null;return{next:function(){for(;_&&(C&&!C(_)||!x&&_===w);)_=_._nextSibling;if(_===null)return{done:!0,value:null};var T={done:!1,value:_};return _=_._nextSibling,T}}},S):l()},n.tree_getFirstAncestorNode=h,n.tree_getNextAncestorNode=g,n.tree_getAncestorNodes=function(w,x,C){var S;return x===void 0&&(x=!1),x||w._parent?((S={})[Symbol.iterator]=function(){var _=h(w,x,C);return{next:function(){if(_===null)return{done:!0,value:null};var T={done:!1,value:_};return _=g(0,_,x,C),T}}},S):l()},n.tree_getCommonAncestor=function(w,x){if(w===x)return w._parent;for(var C=[],S=[],_=h(w,!0);_!==null;)C.push(_),_=g(0,_);for(var T=h(x,!0);T!==null;)S.push(T),T=g(0,T);for(var E=C.length,D=S.length,b=null,I=Math.min(E,D);I>0;I--){var P=C[--E];if(P!==S[--D])break;b=P}return b},n.tree_getFollowingNode=function(w,x){if(x._firstChild)return x._firstChild;if(x._nextSibling)return x._nextSibling;for(;;){var C=x._parent;if(C===null||C===w)return null;if(C._nextSibling)return C._nextSibling;x=C}},n.tree_getPrecedingNode=function(w,x){return x===w?null:x._previousSibling?(x=x._previousSibling)._lastChild?x._lastChild:x:x._parent},n.tree_isConstrained=function w(x){var C,S,_,T,E,D;switch(x._nodeType){case s.NodeType.Document:var b=!1,I=!1;try{for(var P=o(x._children),M=P.next();!M.done;M=P.next())switch(M.value._nodeType){case s.NodeType.ProcessingInstruction:case s.NodeType.Comment:break;case s.NodeType.DocumentType:if(b||I)return!1;b=!0;break;case s.NodeType.Element:if(I)return!1;I=!0;break;default:return!1}}catch(k){C={error:k}}finally{try{M&&!M.done&&(S=P.return)&&S.call(P)}finally{if(C)throw C.error}}break;case s.NodeType.DocumentFragment:case s.NodeType.Element:try{for(var L=o(x._children),V=L.next();!V.done;V=L.next())switch(V.value._nodeType){case s.NodeType.Element:case s.NodeType.Text:case s.NodeType.ProcessingInstruction:case s.NodeType.CData:case s.NodeType.Comment:break;default:return!1}}catch(k){_={error:k}}finally{try{V&&!V.done&&(T=L.return)&&T.call(L)}finally{if(_)throw _.error}}break;case s.NodeType.DocumentType:case s.NodeType.Text:case s.NodeType.ProcessingInstruction:case s.NodeType.CData:case s.NodeType.Comment:return!x.hasChildNodes()}try{for(var G=o(x._children),A=G.next();!A.done;A=G.next())if(!w(A.value))return!1}catch(k){E={error:k}}finally{try{A&&!A.done&&(D=G.return)&&D.call(G)}finally{if(E)throw E.error}}return!0},n.tree_nodeLength=p,n.tree_isEmpty=function(w){return p(w)===0},n.tree_rootNode=v,n.tree_isDescendantOf=function(w,x,C,S){C===void 0&&(C=!1),S===void 0&&(S=!1);for(var _=f(w,C,S);_!==null;){if(_===x)return!0;_=u(w,_,C,S)}return!1},n.tree_isAncestorOf=y,n.tree_isHostIncludingAncestorOf=function w(x,C,S){if(S===void 0&&(S=!1),y(x,C,S))return!0;var _=v(x);return!(!a.Guard.isDocumentFragmentNode(_)||_._host===null||!w(_._host,C,S))},n.tree_isSiblingOf=function(w,x,C){return C===void 0&&(C=!1),w!==x?w._parent!==null&&w._parent===x._parent:!!C},n.tree_isPreceding=function(w,x){var C=m(w),S=m(x);return C!==-1&&S!==-1&&v(w)===v(x)&&SC},n.tree_isParentOf=function(w,x){return w._parent===x},n.tree_isChildOf=function(w,x){return x._parent===w},n.tree_previousSibling=function(w){return w._previousSibling},n.tree_nextSibling=function(w){return w._nextSibling},n.tree_firstChild=function(w){return w._firstChild},n.tree_lastChild=function(w){return w._lastChild},n.tree_treePosition=m,n.tree_index=function(w){for(var x=0;w._previousSibling!==null;)x++,w=w._previousSibling;return x},n.tree_retarget=function(w,x){for(;;){if(!w||!a.Guard.isNode(w))return w;var C=v(w);if(!a.Guard.isShadowRoot(C)||x&&a.Guard.isNode(x)&&y(C,x,!0,!0))return w;w=C.host}}},function(r,n,i){var o=i(13);r.exports=function(a){if(!o(a))throw TypeError(String(a)+" is not an object");return a}},function(r,n,i){var o=i(24),a=i(130),s=i(49),c=i(43),l=i(88),f=c.set,u=c.getterFor("Array Iterator");r.exports=l(Array,"Array",function(d,h){f(this,{type:"Array Iterator",target:o(d),index:0,kind:h})},function(){var d=u(this),h=d.target,g=d.kind,p=d.index++;return!h||p>=h.length?(d.target=void 0,{value:void 0,done:!0}):g=="keys"?{value:p,done:!1}:g=="values"?{value:h[p],done:!1}:{value:[p,h[p]],done:!1}},"values"),s.Arguments=s.Array,a("keys"),a("values"),a("entries")},function(r,n,i){var o=i(90),a=i(25),s=i(202);o||a(Object.prototype,"toString",s,{unsafe:!0})},function(r,n,i){var o=i(16),a=i(15),s=i(40);r.exports=o?function(c,l,f){return a.f(c,l,s(1,f))}:function(c,l,f){return c[l]=f,c}},function(r,n,i){var o=i(137).charAt,a=i(43),s=i(88),c=a.set,l=a.getterFor("String Iterator");s(String,"String",function(f){c(this,{type:"String Iterator",string:String(f),index:0})},function(){var f,u=l(this),d=u.string,h=u.index;return h>=d.length?{value:void 0,done:!0}:(f=o(d,h),u.index+=f.length,{value:f,done:!1})})},function(r,n,i){var o=i(11),a=i(203),s=i(19),c=i(21),l=i(5),f=l("iterator"),u=l("toStringTag"),d=s.values;for(var h in a){var g=o[h],p=g&&g.prototype;if(p){if(p[f]!==d)try{c(p,f,d)}catch{p[f]=d}if(p[u]||c(p,u,h),a[h]){for(var v in s)if(p[v]!==s[v])try{c(p,v,s[v])}catch{p[v]=s[v]}}}}},function(r,n,i){var o=i(41),a=i(35);r.exports=function(s){return o(a(s))}},function(r,n,i){var o=i(11),a=i(21),s=i(14),c=i(80),l=i(117),f=i(43),u=f.get,d=f.enforce,h=String(String).split("String");(r.exports=function(g,p,v,y){var m=!!y&&!!y.unsafe,w=!!y&&!!y.enumerable,x=!!y&&!!y.noTargetGet;typeof v=="function"&&(typeof p!="string"||s(v,"name")||a(v,"name",p),d(v).source=h.join(typeof p=="string"?p:"")),g!==o?(m?!x&&g[p]&&(w=!0):delete g[p],w?g[p]=v:a(g,p,v)):w?g[p]=v:c(p,v)})(Function.prototype,"toString",function(){return typeof this=="function"&&u(this).source||l(this)})},function(r,n,i){var o=i(47),a=Math.min;r.exports=function(s){return s>0?a(o(s),9007199254740991):0}},function(r,n,i){var o=i(35);r.exports=function(a){return Object(o(a))}},function(r,n,i){var o=i(16),a=i(8),s=i(14),c=Object.defineProperty,l={},f=function(u){throw u};r.exports=function(u,d){if(s(l,u))return l[u];d||(d={});var h=[][u],g=!!s(d,"ACCESSORS")&&d.ACCESSORS,p=s(d,0)?d[0]:f,v=s(d,1)?d[1]:void 0;return l[u]=!!h&&!a(function(){if(g&&!o)return!0;var y={length:-1};g?c(y,1,{enumerable:!0,get:f}):y[1]=1,h.call(y,p,v)})}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(148),a=i(149),s=i(151),c=i(98),l=i(153),f=i(154),u=i(155),d=i(99),h=i(100),g=i(156),p=i(157),v=i(101),y=i(158),m=i(159),w=i(160),x=i(161),C=i(162),S=i(163),_=i(164),T=i(165),E=i(166),D=i(167),b=i(168),I=i(169),P=i(170);n.create_domImplementation=function(M){return o.DOMImplementationImpl._create(M)},n.create_window=function(){return a.WindowImpl._create()},n.create_xmlDocument=function(){return new s.XMLDocumentImpl},n.create_document=function(){return new c.DocumentImpl},n.create_abortController=function(){return new l.AbortControllerImpl},n.create_abortSignal=function(){return f.AbortSignalImpl._create()},n.create_documentType=function(M,L,V,G){return u.DocumentTypeImpl._create(M,L,V,G)},n.create_element=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_htmlElement=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_htmlUnknownElement=function(M,L,V,G){return d.ElementImpl._create(M,L,V,G)},n.create_documentFragment=function(M){return h.DocumentFragmentImpl._create(M)},n.create_shadowRoot=function(M,L){return g.ShadowRootImpl._create(M,L)},n.create_attr=function(M,L){return p.AttrImpl._create(M,L)},n.create_text=function(M,L){return v.TextImpl._create(M,L)},n.create_cdataSection=function(M,L){return y.CDATASectionImpl._create(M,L)},n.create_comment=function(M,L){return m.CommentImpl._create(M,L)},n.create_processingInstruction=function(M,L,V){return w.ProcessingInstructionImpl._create(M,L,V)},n.create_htmlCollection=function(M,L){return L===void 0&&(L=function(){return!0}),x.HTMLCollectionImpl._create(M,L)},n.create_nodeList=function(M){return C.NodeListImpl._create(M)},n.create_nodeListStatic=function(M,L){return S.NodeListStaticImpl._create(M,L)},n.create_namedNodeMap=function(M){return _.NamedNodeMapImpl._create(M)},n.create_range=function(M,L){return T.RangeImpl._create(M,L)},n.create_nodeIterator=function(M,L,V){return E.NodeIteratorImpl._create(M,L,V)},n.create_treeWalker=function(M,L){return D.TreeWalkerImpl._create(M,L)},n.create_nodeFilter=function(){return b.NodeFilterImpl._create()},n.create_mutationRecord=function(M,L,V,G,A,k,F,j,Y){return I.MutationRecordImpl._create(M,L,V,G,A,k,F,j,Y)},n.create_domTokenList=function(M,L){return P.DOMTokenListImpl._create(M,L)}},function(r,n,i){var o=this&&this.__values||function(p){var v=typeof Symbol=="function"&&Symbol.iterator,y=v&&p[v],m=0;if(y)return y.call(p);if(p&&typeof p.length=="number")return{next:function(){return p&&m>=p.length&&(p=void 0),{value:p&&p[m++],done:!p}}};throw new TypeError(v?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(17),c=i(3),l=i(72),f=new Map;function u(p,v){if(v!==p._root&&s.tree_isAncestorOf(p._reference,v,!0)){if(p._pointerBeforeReference)for(;;){var y=s.tree_getFollowingNode(p._root,v);if(y!==null&&s.tree_isDescendantOf(p._root,y,!0)&&!s.tree_isDescendantOf(v,y,!0))return void(p._reference=y);if(y===null)return void(p._pointerBeforeReference=!1)}if(v._previousSibling===null)v._parent!==null&&(p._reference=v._parent);else{for(var m=v._previousSibling,w=s.tree_getFirstDescendantNode(v._previousSibling,!0,!1);w!==null;)w!==null&&(m=w),w=s.tree_getNextDescendantNode(v._previousSibling,w,!0,!1);p._reference=m}}}function d(p,v,y,m,w){if(c.Guard.isSlot(p)&&v==="name"&&w===null){if(m===y||m===null&&y===""||m===""&&y===null)return;p._name=m===null||m===""?"":m,l.shadowTree_assignSlotablesForATree(s.tree_rootNode(p))}}function h(p,v,y,m,w){if(c.Guard.isSlotable(p)&&v==="slot"&&w===null){if(m===y||m===null&&y===""||m===""&&y===null)return;p._name=m===null||m===""?"":m,l.shadowTree_isAssigned(p)&&l.shadowTree_assignSlotables(p._assignedSlot),l.shadowTree_assignASlot(p)}}function g(p,v,y,m){v==="id"&&m===null&&(p._uniqueIdentifier=y||void 0)}n.dom_runRemovingSteps=function(p,v){},n.dom_runCloningSteps=function(p,v,y,m){},n.dom_runAdoptingSteps=function(p,v){},n.dom_runAttributeChangeSteps=function(p,v,y,m,w){var x,C;a.dom.features.slots&&(h.call(p,p,v,y,m,w),d.call(p,p,v,y,m,w)),g.call(p,p,v,m,w);try{for(var S=o(p._attributeChangeSteps),_=S.next();!_.done;_=S.next())_.value.call(p,p,v,y,m,w)}catch(T){x={error:T}}finally{try{_&&!_.done&&(C=S.return)&&C.call(S)}finally{if(x)throw x.error}}},n.dom_runInsertionSteps=function(p){},n.dom_runNodeIteratorPreRemovingSteps=function(p,v){u.call(p,p,v)},n.dom_hasSupportedTokens=function(p){return f.has(p)},n.dom_getSupportedTokens=function(p){return f.get(p)||new Set},n.dom_runEventConstructingSteps=function(p){},n.dom_runChildTextContentChangeSteps=function(p){}},function(r,n,i){var o=i(4),a=i(11),s=i(46),c=i(44),l=i(16),f=i(86),u=i(124),d=i(8),h=i(14),g=i(59),p=i(13),v=i(18),y=i(27),m=i(24),w=i(56),x=i(40),C=i(60),S=i(61),_=i(82),T=i(190),E=i(85),D=i(55),b=i(15),I=i(79),P=i(21),M=i(25),L=i(81),V=i(57),G=i(45),A=i(58),k=i(5),F=i(125),j=i(126),Y=i(62),re=i(43),ue=i(36).forEach,ce=V("hidden"),pe=k("toPrimitive"),Ee=re.set,Oe=re.getterFor("Symbol"),_e=Object.prototype,B=a.Symbol,O=s("JSON","stringify"),z=D.f,W=b.f,K=T.f,Z=I.f,ee=L("symbols"),xe=L("op-symbols"),De=L("string-to-symbol-registry"),Ne=L("symbol-to-string-registry"),$e=L("wks"),ie=a.QObject,ae=!ie||!ie.prototype||!ie.prototype.findChild,ye=l&&d(function(){return C(W({},"a",{get:function(){return W(this,"a",{value:7}).a}})).a!=7})?function(je,nt,rt){var dt=z(_e,nt);dt&&delete _e[nt],W(je,nt,rt),dt&&je!==_e&&W(_e,nt,dt)}:W,se=function(je,nt){var rt=ee[je]=C(B.prototype);return Ee(rt,{type:"Symbol",tag:je,description:nt}),l||(rt.description=nt),rt},ge=u?function(je){return typeof je=="symbol"}:function(je){return Object(je)instanceof B},Fe=function(je,nt,rt){je===_e&&Fe(xe,nt,rt),v(je);var dt=w(nt,!0);return v(rt),h(ee,dt)?(rt.enumerable?(h(je,ce)&&je[ce][dt]&&(je[ce][dt]=!1),rt=C(rt,{enumerable:x(0,!1)})):(h(je,ce)||W(je,ce,x(1,{})),je[ce][dt]=!0),ye(je,dt,rt)):W(je,dt,rt)},oe=function(je,nt){v(je);var rt=m(nt),dt=S(rt).concat(Ie(rt));return ue(dt,function(Lt){l&&!ht.call(rt,Lt)||Fe(je,Lt,rt[Lt])}),je},ht=function(je){var nt=w(je,!0),rt=Z.call(this,nt);return!(this===_e&&h(ee,nt)&&!h(xe,nt))&&(!(rt||!h(this,nt)||!h(ee,nt)||h(this,ce)&&this[ce][nt])||rt)},wt=function(je,nt){var rt=m(je),dt=w(nt,!0);if(rt!==_e||!h(ee,dt)||h(xe,dt)){var Lt=z(rt,dt);return!Lt||!h(ee,dt)||h(rt,ce)&&rt[ce][dt]||(Lt.enumerable=!0),Lt}},gt=function(je){var nt=K(m(je)),rt=[];return ue(nt,function(dt){h(ee,dt)||h(G,dt)||rt.push(dt)}),rt},Ie=function(je){var nt=je===_e,rt=K(nt?xe:m(je)),dt=[];return ue(rt,function(Lt){!h(ee,Lt)||nt&&!h(_e,Lt)||dt.push(ee[Lt])}),dt};f||(M((B=function(){if(this instanceof B)throw TypeError("Symbol is not a constructor");var je=arguments.length&&arguments[0]!==void 0?String(arguments[0]):void 0,nt=A(je),rt=function(dt){this===_e&&rt.call(xe,dt),h(this,ce)&&h(this[ce],nt)&&(this[ce][nt]=!1),ye(this,nt,x(1,dt))};return l&&ae&&ye(_e,nt,{configurable:!0,set:rt}),se(nt,je)}).prototype,"toString",function(){return Oe(this).tag}),M(B,"withoutSetter",function(je){return se(A(je),je)}),I.f=ht,b.f=Fe,D.f=wt,_.f=T.f=gt,E.f=Ie,F.f=function(je){return se(k(je),je)},l&&(W(B.prototype,"description",{configurable:!0,get:function(){return Oe(this).description}}),c||M(_e,"propertyIsEnumerable",ht,{unsafe:!0}))),o({global:!0,wrap:!0,forced:!f,sham:!f},{Symbol:B}),ue(S($e),function(je){j(je)}),o({target:"Symbol",stat:!0,forced:!f},{for:function(je){var nt=String(je);if(h(De,nt))return De[nt];var rt=B(nt);return De[nt]=rt,Ne[rt]=nt,rt},keyFor:function(je){if(!ge(je))throw TypeError(je+" is not a symbol");if(h(Ne,je))return Ne[je]},useSetter:function(){ae=!0},useSimple:function(){ae=!1}}),o({target:"Object",stat:!0,forced:!f,sham:!l},{create:function(je,nt){return nt===void 0?C(je):oe(C(je),nt)},defineProperty:Fe,defineProperties:oe,getOwnPropertyDescriptor:wt}),o({target:"Object",stat:!0,forced:!f},{getOwnPropertyNames:gt,getOwnPropertySymbols:Ie}),o({target:"Object",stat:!0,forced:d(function(){E.f(1)})},{getOwnPropertySymbols:function(je){return E.f(y(je))}}),O&&o({target:"JSON",stat:!0,forced:!f||d(function(){var je=B();return O([je])!="[null]"||O({a:je})!="{}"||O(Object(je))!="{}"})},{stringify:function(je,nt,rt){for(var dt,Lt=[je],xt=1;arguments.length>xt;)Lt.push(arguments[xt++]);if(dt=nt,(p(nt)||je!==void 0)&&!ge(je))return g(nt)||(nt=function(Ft,jt){if(typeof dt=="function"&&(jt=dt.call(this,Ft,jt)),!ge(jt))return jt}),Lt[1]=nt,O.apply(null,Lt)}}),B.prototype[pe]||P(B.prototype,pe,B.prototype.valueOf),Y(B,"Symbol"),G[ce]=!0},function(r,n,i){var o=i(4),a=i(16),s=i(11),c=i(14),l=i(13),f=i(15).f,u=i(119),d=s.Symbol;if(a&&typeof d=="function"&&(!("description"in d.prototype)||d().description!==void 0)){var h={},g=function(){var w=arguments.length<1||arguments[0]===void 0?void 0:String(arguments[0]),x=this instanceof g?new d(w):w===void 0?d():d(w);return w===""&&(h[x]=!0),x};u(g,d);var p=g.prototype=d.prototype;p.constructor=g;var v=p.toString,y=String(d("test"))=="Symbol(test)",m=/^Symbol\((.*)\)[^)]+$/;f(p,"description",{configurable:!0,get:function(){var w=l(this)?this.valueOf():this,x=v.call(w);if(c(h,w))return"";var C=y?x.slice(7,-1):x.replace(m,"$1");return C===""?void 0:C}}),o({global:!0,forced:!0},{Symbol:g})}},function(r,n,i){i(126)("iterator")},function(r,n,i){var o,a=this&&this.__extends||(o=function(y,m){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var C in x)x.hasOwnProperty(C)&&(w[C]=x[C])})(y,m)},function(y,m){function w(){this.constructor=y}o(y,m),y.prototype=m===null?Object.create(m):(w.prototype=m.prototype,new w)}),s=this&&this.__values||function(y){var m=typeof Symbol=="function"&&Symbol.iterator,w=m&&y[m],x=0;if(w)return w.call(y);if(y&&typeof y.length=="number")return{next:function(){return y&&x>=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(6),l=i(2),f=i(70),u=i(3),d=i(9),h=i(0),g=i(152),p=i(12),v=function(y){function m(){var w=y.call(this)||this;return w._parent=null,w._firstChild=null,w._lastChild=null,w._previousSibling=null,w._nextSibling=null,w}return a(m,y),Object.defineProperty(m.prototype,"_childNodes",{get:function(){return this.__childNodes||(this.__childNodes=h.create_nodeList(this))},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverride||c.dom.window._associatedDocument},set:function(w){this._nodeDocumentOverride=w},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"_registeredObserverList",{get:function(){return this.__registeredObserverList||(this.__registeredObserverList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeType",{get:function(){return this._nodeType},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeName",{get:function(){return u.Guard.isElementNode(this)?this._htmlUppercasedQualifiedName:u.Guard.isAttrNode(this)?this._qualifiedName:u.Guard.isExclusiveTextNode(this)?"#text":u.Guard.isCDATASectionNode(this)?"#cdata-section":u.Guard.isProcessingInstructionNode(this)?this._target:u.Guard.isCommentNode(this)?"#comment":u.Guard.isDocumentNode(this)?"#document":u.Guard.isDocumentTypeNode(this)?this._name:u.Guard.isDocumentFragmentNode(this)?"#document-fragment":""},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"baseURI",{get:function(){return g.urlSerializer(this._nodeDocument._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"isConnected",{get:function(){return u.Guard.isElementNode(this)&&h.shadowTree_isConnected(this)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"ownerDocument",{get:function(){return this._nodeType===l.NodeType.Document?null:this._nodeDocument},enumerable:!0,configurable:!0}),m.prototype.getRootNode=function(w){return h.tree_rootNode(this,!!w&&w.composed)},Object.defineProperty(m.prototype,"parentNode",{get:function(){return this._nodeType===l.NodeType.Attribute?null:this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"parentElement",{get:function(){return this._parent&&u.Guard.isElementNode(this._parent)?this._parent:null},enumerable:!0,configurable:!0}),m.prototype.hasChildNodes=function(){return this._firstChild!==null},Object.defineProperty(m.prototype,"childNodes",{get:function(){return this._childNodes},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"firstChild",{get:function(){return this._firstChild},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"lastChild",{get:function(){return this._lastChild},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"nodeValue",{get:function(){return u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(w){w===null&&(w=""),u.Guard.isAttrNode(this)?h.attr_setAnExistingAttributeValue(this,w):u.Guard.isCharacterDataNode(this)&&h.characterData_replaceData(this,0,this._data.length,w)},enumerable:!0,configurable:!0}),Object.defineProperty(m.prototype,"textContent",{get:function(){return u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?h.text_descendantTextContent(this):u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(w){w===null&&(w=""),u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?h.node_stringReplaceAll(w,this):u.Guard.isAttrNode(this)?h.attr_setAnExistingAttributeValue(this,w):u.Guard.isCharacterDataNode(this)&&h.characterData_replaceData(this,0,h.tree_nodeLength(this),w)},enumerable:!0,configurable:!0}),m.prototype.normalize=function(){for(var w,x,C,S,_=[],T=h.tree_getFirstDescendantNode(this,!1,!1,function(ue){return u.Guard.isExclusiveTextNode(ue)});T!==null;)_.push(T),T=h.tree_getNextDescendantNode(this,T,!1,!1,function(ue){return u.Guard.isExclusiveTextNode(ue)});for(var E=0;E<_.length;E++){var D=_[E];if(D._parent!==null){var b=h.tree_nodeLength(D);if(b!==0){var I=[],P="";try{for(var M=(w=void 0,s(h.text_contiguousExclusiveTextNodes(D))),L=M.next();!L.done;L=M.next()){var V=L.value;I.push(V),P+=V._data}}catch(ue){w={error:ue}}finally{try{L&&!L.done&&(x=M.return)&&x.call(M)}finally{if(w)throw w.error}}if(h.characterData_replaceData(D,b,0,P),c.dom.rangeList.size!==0)for(var G=D._nextSibling;G!==null&&u.Guard.isExclusiveTextNode(G);){var A=G,k=h.tree_index(A);try{for(var F=(C=void 0,s(c.dom.rangeList)),j=F.next();!j.done;j=F.next()){var Y=j.value;Y._start[0]===A&&(Y._start[0]=D,Y._start[1]+=b),Y._end[0]===A&&(Y._end[0]=D,Y._end[1]+=b),Y._start[0]===A._parent&&Y._start[1]===k&&(Y._start[0]=D,Y._start[1]=b),Y._end[0]===A._parent&&Y._end[1]===k&&(Y._end[0]=D,Y._end[1]=b)}}catch(ue){C={error:ue}}finally{try{j&&!j.done&&(S=F.return)&&S.call(F)}finally{if(C)throw C.error}}b+=h.tree_nodeLength(G),G=G._nextSibling}for(var re=0;reP;P++)if((m||P in D)&&(T=b(_=D[P],P,E),d)){if(h)L[P]=T;else if(T)switch(d){case 3:return!0;case 5:return _;case 6:return P;case 2:f.call(L,_)}else if(v)return!1}return y?-1:p||v?v:L}};r.exports={forEach:u(0),map:u(1),filter:u(2),some:u(3),every:u(4),find:u(5),findIndex:u(6)}},function(r,n,i){var o=this&&this.__values||function(E){var D=typeof Symbol=="function"&&Symbol.iterator,b=D&&E[D],I=0;if(b)return b.call(E);if(E&&typeof E.length=="number")return{next:function(){return E&&I>=E.length&&(E=void 0),{value:E&&E[I++],done:!E}}};throw new TypeError(D?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(E,D){var b=typeof Symbol=="function"&&E[Symbol.iterator];if(!b)return E;var I,P,M=b.call(E),L=[];try{for(;(D===void 0||D-- >0)&&!(I=M.next()).done;)L.push(I.value)}catch(V){P={error:V}}finally{try{I&&!I.done&&(b=M.return)&&b.call(M)}finally{if(P)throw P.error}}return L},s=this&&this.__spread||function(){for(var E=[],D=0;D1)throw new l.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+re+" element nodes.");if(re===1){try{for(var Ee=o(D._children),Oe=Ee.next();!Oe.done;Oe=Ee.next())if(Oe.value._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("The document node already has a document element node.")}catch(Z){M={error:Z}}finally{try{Oe&&!Oe.done&&(L=Ee.return)&&L.call(Ee)}finally{if(M)throw M.error}}if(b){if(Y===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");for(var _e=b._nextSibling;_e;){if(_e._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");_e=_e._nextSibling}}}}else if(j===f.NodeType.Element){try{for(var B=o(D._children),O=B.next();!O.done;O=B.next())if(O.value._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Document already has a document element node. Node is "+E.nodeName+".")}catch(Z){V={error:Z}}finally{try{O&&!O.done&&(G=B.return)&&G.call(B)}finally{if(V)throw V.error}}if(b){if(Y===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+E.nodeName+".");for(_e=b._nextSibling;_e;){if(_e._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+E.nodeName+".");_e=_e._nextSibling}}}else if(j===f.NodeType.DocumentType){try{for(var z=o(D._children),W=z.next();!W.done;W=z.next())if(W.value._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Document already has a document type node. Node is "+E.nodeName+".")}catch(Z){A={error:Z}}finally{try{W&&!W.done&&(k=z.return)&&k.call(z)}finally{if(A)throw A.error}}if(b)for(var K=b._previousSibling;K;){if(K._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+E.nodeName+".");K=K._previousSibling}else for(K=D._firstChild;K;){if(K._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+E.nodeName+".");K=K._nextSibling}}}}function S(E,D,b){C(E,D,b);var I=b;return I===E&&(I=E._nextSibling),x.document_adopt(E,D._nodeDocument),_(E,D,I),E}function _(E,D,b,I){var P,M;if(b!==null||E._nodeType===f.NodeType.DocumentFragment){var L=E._nodeType===f.NodeType.DocumentFragment?E._children.size:1;if(b!==null&&c.dom.rangeList.size!==0){var V=p.tree_index(b);try{for(var G=o(c.dom.rangeList),A=G.next();!A.done;A=G.next()){var k=A.value;k._start[0]===D&&k._start[1]>V&&(k._start[1]+=L),k._end[0]===D&&k._end[1]>V&&(k._end[1]+=L)}}catch(Oe){P={error:Oe}}finally{try{A&&!A.done&&(M=G.return)&&M.call(G)}finally{if(P)throw P.error}}}var F=E._nodeType===f.NodeType.DocumentFragment?new(Array.bind.apply(Array,s([void 0],E._children))):[E];if(E._nodeType===f.NodeType.DocumentFragment)for(;E._firstChild;)T(E._firstChild,E,!0);c.dom.features.mutationObservers&&E._nodeType===f.NodeType.DocumentFragment&&m.observer_queueTreeMutationRecord(E,[],F,null,null);for(var j=b?b._previousSibling:D._lastChild,Y=b===null?-1:p.tree_index(b),re=0;reF&&re._start[1]--,re._end[0]===D&&re._end[1]>F&&re._end[1]--}}catch(De){I={error:De}}finally{try{Y&&!Y.done&&(P=j.return)&&P.call(j)}finally{if(I)throw I.error}}try{for(var ue=o(c.dom.rangeList),ce=ue.next();!ce.done;ce=ue.next())(re=ce.value)._start[0]===D&&re._start[1]>F&&(re._start[1]-=1),re._end[0]===D&&re._end[1]>F&&(re._end[1]-=1)}catch(De){M={error:De}}finally{try{ce&&!ce.done&&(L=ue.return)&&L.call(ue)}finally{if(M)throw M.error}}}if(c.dom.features.steps)try{for(var pe=o(v.nodeIterator_iteratorList()),Ee=pe.next();!Ee.done;Ee=pe.next()){var Oe=Ee.value;Oe._root._nodeDocument===E._nodeDocument&&w.dom_runNodeIteratorPreRemovingSteps(Oe,E)}}catch(De){V={error:De}}finally{try{Ee&&!Ee.done&&(G=pe.return)&&G.call(pe)}finally{if(V)throw V.error}}var _e=E._previousSibling,B=E._nextSibling;u.Guard.isDocumentNode(D)&&u.Guard.isElementNode(E)&&(D._documentElement=null),E._parent=null,D._children.delete(E);var O=E._previousSibling,z=E._nextSibling;E._previousSibling=null,E._nextSibling=null,O&&(O._nextSibling=z),z&&(z._previousSibling=O),O||(D._firstChild=z),z||(D._lastChild=O),c.dom.features.slots&&u.Guard.isSlotable(E)&&E._assignedSlot!==null&&y.shadowTree_isAssigned(E)&&y.shadowTree_assignSlotables(E._assignedSlot),c.dom.features.slots&&u.Guard.isShadowRoot(p.tree_rootNode(D))&&u.Guard.isSlot(D)&&d.isEmpty(D._assignedNodes)&&y.shadowTree_signalASlotChange(D),c.dom.features.slots&&p.tree_getFirstDescendantNode(E,!0,!1,function(De){return u.Guard.isSlot(De)})!==null&&(y.shadowTree_assignSlotablesForATree(p.tree_rootNode(D)),y.shadowTree_assignSlotablesForATree(E)),c.dom.features.steps&&w.dom_runRemovingSteps(E,D),c.dom.features.customElements&&u.Guard.isCustomElementNode(E)&&g.customElement_enqueueACustomElementCallbackReaction(E,"disconnectedCallback",[]);for(var W=p.tree_getFirstDescendantNode(E,!1,!0);W!==null;)c.dom.features.steps&&w.dom_runRemovingSteps(W,E),c.dom.features.customElements&&u.Guard.isCustomElementNode(W)&&g.customElement_enqueueACustomElementCallbackReaction(W,"disconnectedCallback",[]),W=p.tree_getNextDescendantNode(E,W,!1,!0);if(c.dom.features.mutationObservers)for(var K=p.tree_getFirstAncestorNode(D,!0);K!==null;){try{for(var Z=(A=void 0,o(K._registeredObserverList)),ee=Z.next();!ee.done;ee=Z.next()){var xe=ee.value;xe.options.subtree&&E._registeredObserverList.push({observer:xe.observer,options:xe.options,source:xe})}}catch(De){A={error:De}}finally{try{ee&&!ee.done&&(k=Z.return)&&k.call(Z)}finally{if(A)throw A.error}}K=p.tree_getNextAncestorNode(D,K,!0)}c.dom.features.mutationObservers&&(b||m.observer_queueTreeMutationRecord(D,[],[E],_e,B)),c.dom.features.steps&&u.Guard.isTextNode(E)&&w.dom_runChildTextContentChangeSteps(D)}n.mutation_ensurePreInsertionValidity=C,n.mutation_preInsert=S,n.mutation_insert=_,n.mutation_append=function(E,D){return S(E,D,null)},n.mutation_replace=function(E,D,b){var I,P,M,L,V,G,A,k;if(b._nodeType!==f.NodeType.Document&&b._nodeType!==f.NodeType.DocumentFragment&&b._nodeType!==f.NodeType.Element)throw new l.HierarchyRequestError("Only document, document fragment and element nodes can contain child nodes. Parent node is "+b.nodeName+".");if(p.tree_isHostIncludingAncestorOf(b,D,!0))throw new l.HierarchyRequestError("The node to be inserted cannot be an ancestor of parent node. Node is "+D.nodeName+", parent node is "+b.nodeName+".");if(E._parent!==b)throw new l.NotFoundError("The reference child node cannot be found under parent node. Child node is "+E.nodeName+", parent node is "+b.nodeName+".");if(D._nodeType!==f.NodeType.DocumentFragment&&D._nodeType!==f.NodeType.DocumentType&&D._nodeType!==f.NodeType.Element&&D._nodeType!==f.NodeType.Text&&D._nodeType!==f.NodeType.ProcessingInstruction&&D._nodeType!==f.NodeType.CData&&D._nodeType!==f.NodeType.Comment)throw new l.HierarchyRequestError("Only document fragment, document type, element, text, processing instruction, cdata section or comment nodes can be inserted. Node is "+D.nodeName+".");if(D._nodeType===f.NodeType.Text&&b._nodeType===f.NodeType.Document)throw new l.HierarchyRequestError("Cannot insert a text node as a child of a document node. Node is "+D.nodeName+".");if(D._nodeType===f.NodeType.DocumentType&&b._nodeType!==f.NodeType.Document)throw new l.HierarchyRequestError("A document type node can only be inserted under a document node. Parent node is "+b.nodeName+".");if(b._nodeType===f.NodeType.Document){if(D._nodeType===f.NodeType.DocumentFragment){var F=0;try{for(var j=o(D._children),Y=j.next();!Y.done;Y=j.next()){var re=Y.value;if(re._nodeType===f.NodeType.Element)F++;else if(re._nodeType===f.NodeType.Text)throw new l.HierarchyRequestError("Cannot insert text a node as a child of a document node. Node is "+re.nodeName+".")}}catch(xe){I={error:xe}}finally{try{Y&&!Y.done&&(P=j.return)&&P.call(j)}finally{if(I)throw I.error}}if(F>1)throw new l.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+F+" element nodes.");if(F===1){try{for(var ue=o(b._children),ce=ue.next();!ce.done;ce=ue.next())if((O=ce.value)._nodeType===f.NodeType.Element&&O!==E)throw new l.HierarchyRequestError("The document node already has a document element node.")}catch(xe){M={error:xe}}finally{try{ce&&!ce.done&&(L=ue.return)&&L.call(ue)}finally{if(M)throw M.error}}for(var pe=E._nextSibling;pe;){if(pe._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node.");pe=pe._nextSibling}}}else if(D._nodeType===f.NodeType.Element){try{for(var Ee=o(b._children),Oe=Ee.next();!Oe.done;Oe=Ee.next())if((O=Oe.value)._nodeType===f.NodeType.Element&&O!==E)throw new l.HierarchyRequestError("Document already has a document element node. Node is "+D.nodeName+".")}catch(xe){V={error:xe}}finally{try{Oe&&!Oe.done&&(G=Ee.return)&&G.call(Ee)}finally{if(V)throw V.error}}for(pe=E._nextSibling;pe;){if(pe._nodeType===f.NodeType.DocumentType)throw new l.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+D.nodeName+".");pe=pe._nextSibling}}else if(D._nodeType===f.NodeType.DocumentType){try{for(var _e=o(b._children),B=_e.next();!B.done;B=_e.next()){var O;if((O=B.value)._nodeType===f.NodeType.DocumentType&&O!==E)throw new l.HierarchyRequestError("Document already has a document type node. Node is "+D.nodeName+".")}}catch(xe){A={error:xe}}finally{try{B&&!B.done&&(k=_e.return)&&k.call(_e)}finally{if(A)throw A.error}}for(var z=E._previousSibling;z;){if(z._nodeType===f.NodeType.Element)throw new l.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+D.nodeName+".");z=z._previousSibling}}}var W=E._nextSibling;W===D&&(W=D._nextSibling);var K=E._previousSibling;x.document_adopt(D,b._nodeDocument);var Z=[];E._parent!==null&&(Z.push(E),T(E,E._parent,!0));var ee=[];return D._nodeType===f.NodeType.DocumentFragment?ee=Array.from(D._children):ee.push(D),_(D,b,W,!0),c.dom.features.mutationObservers&&m.observer_queueTreeMutationRecord(b,ee,Z,K,W),E},n.mutation_replaceAll=function(E,D){var b,I;E!==null&&x.document_adopt(E,D._nodeDocument);var P=Array.from(D._children),M=[];E&&E._nodeType===f.NodeType.DocumentFragment?M=Array.from(E._children):E!==null&&M.push(E);try{for(var L=o(P),V=L.next();!V.done;V=L.next())T(V.value,D,!0)}catch(G){b={error:G}}finally{try{V&&!V.done&&(I=L.return)&&I.call(L)}finally{if(b)throw b.error}}E!==null&&_(E,D,null,!0),c.dom.features.mutationObservers&&m.observer_queueTreeMutationRecord(D,M,P,null,null)},n.mutation_preRemove=function(E,D){if(E._parent!==D)throw new l.NotFoundError("The child node cannot be found under parent node. Child node is "+E.nodeName+", parent node is "+D.nodeName+".");return T(E,D),E},n.mutation_remove=T},function(r,n,i){function o(a){return a==null}r.exports.isNothing=o,r.exports.isObject=function(a){return typeof a=="object"&&a!==null},r.exports.toArray=function(a){return Array.isArray(a)?a:o(a)?[]:[a]},r.exports.repeat=function(a,s){var c,l="";for(c=0;c0?o:i)(a)}},function(r,n,i){var o=i(8);r.exports=function(a,s){var c=[][a];return!!c&&o(function(){c.call(null,s||function(){throw 1},1)})}},function(r,n){r.exports={}},function(r,n,i){i(31),i(32),i(33),i(220),i(64),i(19),i(65),i(20),i(68),i(66),i(92),i(144),i(22),i(94),i(23);var o=this&&this.__values||function(g){var p=typeof Symbol=="function"&&Symbol.iterator,v=p&&g[p],y=0;if(v)return v.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(g,p){var v=typeof Symbol=="function"&&g[Symbol.iterator];if(!v)return g;var y,m,w=v.call(g),x=[];try{for(;(p===void 0||p-- >0)&&!(y=w.next()).done;)x.push(y.value)}catch(C){m={error:C}}finally{try{y&&!y.done&&(v=w.return)&&v.call(w)}finally{if(m)throw m.error}}return x},s=this&&this.__spread||function(){for(var g=[],p=0;p/g,">");this.text(y)},g.prototype._serializeDocumentFragmentNS=function(p,v,y,m,w){var x,C;try{for(var S=o(p.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;this._serializeNodeNS(T,v,y,m,w)}}catch(E){x={error:E}}finally{try{_&&!_.done&&(C=S.return)&&C.call(S)}finally{if(x)throw x.error}}},g.prototype._serializeDocumentFragment=function(p,v){var y,m;try{for(var w=o(p._children),x=w.next();!x.done;x=w.next()){var C=x.value;this._serializeNode(C,v)}}catch(S){y={error:S}}finally{try{x&&!x.done&&(m=w.return)&&m.call(w)}finally{if(y)throw y.error}}},g.prototype._serializeDocumentType=function(p,v){if(v&&!d.xml_isPubidChar(p.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(v&&(!d.xml_isLegalChar(p.systemId)||p.systemId.indexOf('"')!==-1&&p.systemId.indexOf("'")!==-1))throw new Error("DocType system identifier contains invalid characters (well-formed required).");this.docType(p.name,p.publicId,p.systemId)},g.prototype._serializeProcessingInstruction=function(p,v){if(v&&(p.target.indexOf(":")!==-1||/^xml$/i.test(p.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(v&&(!d.xml_isLegalChar(p.data)||p.data.indexOf("?>")!==-1))throw new Error("Processing instruction data contains invalid characters (well-formed required).");this.instruction(p.target,p.data)},g.prototype._serializeCData=function(p,v){if(v&&p.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters (well-formed required).");this.cdata(p.data)},g.prototype._serializeAttributesNS=function(p,v,y,m,w,x){var C,S,_=[],T=x?new l.LocalNameSet:void 0;try{for(var E=o(p.attributes),D=E.next();!D.done;D=E.next()){var b=D.value;if(x||w||b.namespaceURI!==null){if(x&&T&&T.has(b.namespaceURI,b.localName))throw new Error("Element contains duplicate attributes (well-formed required).");x&&T&&T.set(b.namespaceURI,b.localName);var I=b.namespaceURI,P=null;if(I!==null)if(P=v.get(b.prefix,I),I===u.namespace.XMLNS){if(b.value===u.namespace.XML||b.prefix===null&&w||b.prefix!==null&&(!(b.localName in m)||m[b.localName]!==b.value)&&v.has(b.localName,b.value))continue;if(x&&b.value===u.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(x&&b.value==="")throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");b.prefix==="xmlns"&&(P="xmlns")}else P===null&&(P=b.prefix===null||v.hasPrefix(b.prefix)&&!v.has(b.prefix,I)?this._generatePrefix(I,v,y):b.prefix,_.push([null,"xmlns",P,this._serializeAttributeValue(I,x)]));if(x&&(b.localName.indexOf(":")!==-1||!d.xml_isName(b.localName)||b.localName==="xmlns"&&I===null))throw new Error("Attribute local name contains invalid characters (well-formed required).");_.push([I,P,b.localName,this._serializeAttributeValue(b.value,x)])}else _.push([null,null,b.localName,this._serializeAttributeValue(b.value,x)])}}catch(M){C={error:M}}finally{try{D&&!D.done&&(S=E.return)&&S.call(E)}finally{if(C)throw C.error}}return _},g.prototype._serializeAttributes=function(p,v){var y,m,w=[],x=v?{}:void 0;try{for(var C=o(p.attributes),S=C.next();!S.done;S=C.next()){var _=S.value;if(v){if(v&&x&&_.localName in x)throw new Error("Element contains duplicate attributes (well-formed required).");if(v&&x&&(x[_.localName]=!0),v&&(_.localName.indexOf(":")!==-1||!d.xml_isName(_.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");w.push([null,null,_.localName,this._serializeAttributeValue(_.value,v)])}else w.push([null,null,_.localName,this._serializeAttributeValue(_.value,v)])}}catch(T){y={error:T}}finally{try{S&&!S.done&&(m=C.return)&&m.call(C)}finally{if(y)throw y.error}}return w},g.prototype._recordNamespaceInformation=function(p,v,y){var m,w,x=null;try{for(var C=o(p.attributes),S=C.next();!S.done;S=C.next()){var _=S.value,T=_.namespaceURI,E=_.prefix;if(T===u.namespace.XMLNS){if(E===null){x=_.value;continue}var D=_.localName,b=_.value;if(b===u.namespace.XML||(b===""&&(b=null),v.has(D,b)))continue;v.set(D,b),y[D]=b||""}}}catch(I){m={error:I}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x},g.prototype._generatePrefix=function(p,v,y){var m="ns"+y.value.toString();return y.value++,v.set(m,p),m},g.prototype._serializeAttributeValue=function(p,v){if(v&&p!==null&&!d.xml_isLegalChar(p))throw new Error("Invalid characters in attribute value.");return p===null?"":p.replace(/(?!&([^&;]*);)&/g,"&").replace(//g,">").replace(/"/g,""")},g._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),g}();n.BaseWriter=h},function(r,n,i){var o=this&&this.__values||function(v){var y=typeof Symbol=="function"&&Symbol.iterator,m=y&&v[y],w=0;if(m)return m.call(v);if(v&&typeof v.length=="number")return{next:function(){return v&&w>=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(v,y){var m=typeof Symbol=="function"&&v[Symbol.iterator];if(!m)return v;var w,x,C=m.call(v),S=[];try{for(;(y===void 0||y-- >0)&&!(w=C.next()).done;)S.push(w.value)}catch(_){x={error:_}}finally{try{w&&!w.done&&(m=C.return)&&m.call(C)}finally{if(x)throw x.error}}return S};Object.defineProperty(n,"__esModule",{value:!0});var s=i(6),c=i(3),l=i(7),f=i(29),u=i(17),d=i(97);function h(){var v=s.dom.window;v._mutationObserverMicrotaskQueued||(v._mutationObserverMicrotaskQueued=!0,Promise.resolve().then(function(){g()}))}function g(){var v,y,m,w,x=s.dom.window;x._mutationObserverMicrotaskQueued=!1;var C=l.set.clone(x._mutationObservers),S=l.set.clone(x._signalSlots);l.set.empty(x._signalSlots);var _=function(P){var M=l.list.clone(P._recordQueue);l.list.empty(P._recordQueue);for(var L=0;L"+y+"<\/script>"},v=function(){try{o=document.domain&&new ActiveXObject("htmlfile")}catch{}var y,m;v=o?function(x){x.write(p("")),x.close();var C=x.parentWindow.Object;return x=null,C}(o):((m=u("iframe")).style.display="none",f.appendChild(m),m.src="javascript:",(y=m.contentWindow.document).open(),y.write(p("document.F=Object")),y.close(),y.F);for(var w=c.length;w--;)delete v.prototype[c[w]];return v()};l[h]=!0,r.exports=Object.create||function(y,m){var w;return y!==null?(g.prototype=a(y),w=new g,g.prototype=null,w[h]=y):w=v(),m===void 0?w:s(w,m)}},function(r,n,i){var o=i(121),a=i(84);r.exports=Object.keys||function(s){return o(s,a)}},function(r,n,i){var o=i(15).f,a=i(14),s=i(5)("toStringTag");r.exports=function(c,l,f){c&&!a(c=f?c:c.prototype,s)&&o(c,s,{configurable:!0,value:l})}},function(r,n,i){var o=i(8),a=i(5),s=i(129),c=a("species");r.exports=function(l){return s>=51||!o(function(){var f=[];return(f.constructor={})[c]=function(){return{foo:1}},f[l](Boolean).foo!==1})}},function(r,n,i){var o=i(4),a=i(122).indexOf,s=i(48),c=i(28),l=[].indexOf,f=!!l&&1/[1].indexOf(1,-0)<0,u=s("indexOf"),d=c("indexOf",{ACCESSORS:!0,1:0});o({target:"Array",proto:!0,forced:f||!u||!d},{indexOf:function(h){return f?l.apply(this,arguments)||0:a(this,h,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(16),a=i(15).f,s=Function.prototype,c=s.toString,l=/^\s*function ([^ (]*)/;o&&!("name"in s)&&a(s,"name",{configurable:!0,get:function(){try{return c.call(this).match(l)[1]}catch{return""}}})},function(r,n,i){var o=i(25),a=i(18),s=i(8),c=i(136),l=RegExp.prototype,f=l.toString,u=s(function(){return f.call({source:"a",flags:"b"})!="/a/b"}),d=f.name!="toString";(u||d)&&o(RegExp.prototype,"toString",function(){var h=a(this),g=String(h.source),p=h.flags;return"/"+g+"/"+String(p===void 0&&h instanceof RegExp&&!("flags"in l)?c.call(h):p)},{unsafe:!0})},function(r,n,i){i(31),i(32),i(33),i(19),i(138),i(20),i(66),i(22),i(23);var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)}),s=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(1),l=i(2),f=function(u){function d(h,g){var p=u.call(this,h)||this;return p._writerOptions=c.applyDefaults(g,{format:"object",wellFormed:!1,group:!1,verbose:!1}),p}return a(d,u),d.prototype.serialize=function(h){return this._currentList=[],this._currentIndex=0,this._listRegister=[this._currentList],this.serializeNode(h,this._writerOptions.wellFormed),this._process(this._currentList,this._writerOptions)},d.prototype._process=function(h,g){var p,v,y,m,w,x,C;if(h.length===0)return{};for(var S={},_=!1,T=0,E=0,D=0,b=0,I=0;I2)try{for(var C=s(h),S=C.next();!S.done;S=C.next()){var _=S.value;g[v+(m++).toString()]=_}}catch(T){w={error:T}}finally{try{S&&!S.done&&(x=C.return)&&x.call(C)}finally{if(w)throw w.error}}else g[y>1?v+(m++).toString():v]=h;return m},d.prototype.beginElement=function(h){var g,p,v=[];if(this._currentList.length===0)this._currentList.push(((g={})[h]=v,g));else{var y=this._currentList[this._currentList.length-1];this._isElementNode(y,h)?y[h].length!==0&&c.isArray(y[h][0])?y[h].push(v):y[h]=[y[h],v]:this._currentList.push(((p={})[h]=v,p))}this._currentIndex++,this._listRegister.length>this._currentIndex?this._listRegister[this._currentIndex]=v:this._listRegister.push(v),this._currentList=v},d.prototype.endElement=function(){this._currentList=this._listRegister[--this._currentIndex]},d.prototype.attribute=function(h,g){var p,v;if(this._currentList.length===0)this._currentList.push({"@":(p={},p[h]=g,p)});else{var y=this._currentList[this._currentList.length-1];this._isAttrNode(y)?y["@"][h]=g:this._currentList.push({"@":(v={},v[h]=g,v)})}},d.prototype.comment=function(h){if(this._currentList.length===0)this._currentList.push({"!":h});else{var g=this._currentList[this._currentList.length-1];this._isCommentNode(g)?c.isArray(g["!"])?g["!"].push(h):g["!"]=[g["!"],h]:this._currentList.push({"!":h})}},d.prototype.text=function(h){if(this._currentList.length===0)this._currentList.push({"#":h});else{var g=this._currentList[this._currentList.length-1];this._isTextNode(g)?c.isArray(g["#"])?g["#"].push(h):g["#"]=[g["#"],h]:this._currentList.push({"#":h})}},d.prototype.instruction=function(h,g){var p=g===""?h:h+" "+g;if(this._currentList.length===0)this._currentList.push({"?":p});else{var v=this._currentList[this._currentList.length-1];this._isInstructionNode(v)?c.isArray(v["?"])?v["?"].push(p):v["?"]=[v["?"],p]:this._currentList.push({"?":p})}},d.prototype.cdata=function(h){if(this._currentList.length===0)this._currentList.push({$:h});else{var g=this._currentList[this._currentList.length-1];this._isCDATANode(g)?c.isArray(g.$)?g.$.push(h):g.$=[g.$,h]:this._currentList.push({$:h})}},d.prototype._isAttrNode=function(h){return"@"in h},d.prototype._isTextNode=function(h){return"#"in h},d.prototype._isCommentNode=function(h){return"!"in h},d.prototype._isInstructionNode=function(h){return"?"in h},d.prototype._isCDATANode=function(h){return"$"in h},d.prototype._isElementNode=function(h,g){return g in h},d.prototype._getAttrKey=function(){return this._builderOptions.convert.att},d.prototype._getNodeKey=function(h){switch(h){case l.NodeType.Comment:return this._builderOptions.convert.comment;case l.NodeType.Text:return this._builderOptions.convert.text;case l.NodeType.ProcessingInstruction:return this._builderOptions.convert.ins;case l.NodeType.CData:return this._builderOptions.convert.cdata;default:throw new Error("Invalid node type.")}},d}(i(50).BaseWriter);n.ObjectWriter=f},function(r,n,i){var o=i(4),a=i(93);o({target:"RegExp",proto:!0,forced:/./.exec!==a},{exec:a})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){this._items={},this._nullItems={}}return a.prototype.set=function(s,c){s===null?this._nullItems[c]=!0:(this._items[s]||(this._items[s]={}),this._items[s][c]=!0)},a.prototype.has=function(s,c){return s===null?this._nullItems[c]===!0:!!this._items[s]&&this._items[s][c]===!0},a}();n.LocalNameSet=o},function(r,n,i){var o=this&&this.__read||function(f,u){var d=typeof Symbol=="function"&&f[Symbol.iterator];if(!d)return f;var h,g,p=d.call(f),v=[];try{for(;(u===void 0||u-- >0)&&!(h=p.next()).done;)v.push(h.value)}catch(y){g={error:y}}finally{try{h&&!h.done&&(d=p.return)&&d.call(p)}finally{if(g)throw g.error}}return v};Object.defineProperty(n,"__esModule",{value:!0});var a=i(9),s=i(3),c=i(0),l=function(){function f(){}return Object.defineProperty(f.prototype,"_eventListenerList",{get:function(){return this.__eventListenerList||(this.__eventListenerList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(f.prototype,"_eventHandlerMap",{get:function(){return this.__eventHandlerMap||(this.__eventHandlerMap={})},enumerable:!0,configurable:!0}),f.prototype.addEventListener=function(u,d,h){h===void 0&&(h={passive:!1,once:!1,capture:!1});var g,p=o(c.eventTarget_flattenMore(h),3),v=p[0],y=p[1],m=p[2];d&&(g=s.Guard.isEventListener(d)?d:{handleEvent:d},c.eventTarget_addEventListener(this,{type:u,callback:g,capture:v,passive:y,once:m,removed:!1}))},f.prototype.removeEventListener=function(u,d,h){h===void 0&&(h={capture:!1});var g=c.eventTarget_flatten(h);if(d)for(var p=0;p=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(y,m){var w=typeof Symbol=="function"&&y[Symbol.iterator];if(!w)return y;var x,C,S=w.call(y),_=[];try{for(;(m===void 0||m-- >0)&&!(x=S.next()).done;)_.push(x.value)}catch(T){C={error:T}}finally{try{x&&!x.done&&(w=S.return)&&w.call(S)}finally{if(C)throw C.error}}return _},s=this&&this.__spread||function(){for(var y=[],m=0;m",amp:"&",quot:'"',apos:"'"},s}();n.BaseReader=a},function(r,n,i){var o=i(39);r.exports=o.DEFAULT=new o({include:[i(54)],explicit:[i(299),i(300),i(301)]})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(185);n.XMLBuilderImpl=o.XMLBuilderImpl;var a=i(304);n.XMLBuilderCBImpl=a.XMLBuilderCBImpl;var s=i(183);n.builder=s.builder,n.create=s.create,n.fragment=s.fragment,n.convert=s.convert;var c=i(309);n.createCB=c.createCB,n.fragmentCB=c.fragmentCB},function(r,n){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch{typeof window=="object"&&(i=window)}r.exports=i},function(r,n,i){var o={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,s=a&&!o.call({1:2},1);n.f=s?function(c){var l=a(this,c);return!!l&&l.enumerable}:o},function(r,n,i){var o=i(11),a=i(21);r.exports=function(s,c){try{a(o,s,c)}catch{o[s]=c}return c}},function(r,n,i){var o=i(44),a=i(118);(r.exports=function(s,c){return a[s]||(a[s]=c!==void 0?c:{})})("versions",[]).push({version:"3.6.5",mode:o?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},function(r,n,i){var o=i(121),a=i(84).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(s){return o(s,a)}},function(r,n,i){var o=i(47),a=Math.max,s=Math.min;r.exports=function(c,l){var f=o(c);return f<0?a(f+l,0):s(f,l)}},function(r,n){r.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(r,n){n.f=Object.getOwnPropertySymbols},function(r,n,i){var o=i(8);r.exports=!!Object.getOwnPropertySymbols&&!o(function(){return!String(Symbol())})},function(r,n,i){var o=i(127);r.exports=function(a,s,c){if(o(a),s===void 0)return a;switch(c){case 0:return function(){return a.call(s)};case 1:return function(l){return a.call(s,l)};case 2:return function(l,f){return a.call(s,l,f)};case 3:return function(l,f,u){return a.call(s,l,f,u)}}return function(){return a.apply(s,arguments)}}},function(r,n,i){var o=i(4),a=i(195),s=i(132),c=i(133),l=i(62),f=i(21),u=i(25),d=i(5),h=i(44),g=i(49),p=i(131),v=p.IteratorPrototype,y=p.BUGGY_SAFARI_ITERATORS,m=d("iterator"),w=function(){return this};r.exports=function(x,C,S,_,T,E,D){a(S,C,_);var b,I,P,M=function(j){if(j===T&&k)return k;if(!y&&j in G)return G[j];switch(j){case"keys":case"values":case"entries":return function(){return new S(this,j)}}return function(){return new S(this)}},L=C+" Iterator",V=!1,G=x.prototype,A=G[m]||G["@@iterator"]||T&&G[T],k=!y&&A||M(T),F=C=="Array"&&G.entries||A;if(F&&(b=s(F.call(new x)),v!==Object.prototype&&b.next&&(h||s(b)===v||(c?c(b,v):typeof b[m]!="function"&&f(b,m,w)),l(b,L,!0,!0),h&&(g[L]=w))),T=="values"&&A&&A.name!=="values"&&(V=!0,k=function(){return A.call(this)}),h&&!D||G[m]===k||f(G,m,k),g[C]=k,T)if(I={values:M("values"),keys:E?k:M("keys"),entries:M("entries")},D)for(P in I)(y||V||!(P in G))&&u(G,P,I[P]);else o({target:C,proto:!0,forced:y||V},I);return I}},function(r,n,i){var o=i(4),a=i(13),s=i(59),c=i(83),l=i(26),f=i(24),u=i(134),d=i(5),h=i(63),g=i(28),p=h("slice"),v=g("slice",{ACCESSORS:!0,0:0,1:2}),y=d("species"),m=[].slice,w=Math.max;o({target:"Array",proto:!0,forced:!p||!v},{slice:function(x,C){var S,_,T,E=f(this),D=l(E.length),b=c(x,D),I=c(C===void 0?D:C,D);if(s(E)&&(typeof(S=E.constructor)!="function"||S!==Array&&!s(S.prototype)?a(S)&&(S=S[y])===null&&(S=void 0):S=void 0,S===Array||S===void 0))return m.call(E,b,I);for(_=new(S===void 0?Array:S)(w(I-b,0)),T=0;b0&&(!x.multiline||x.multiline&&p[x.lastIndex-1]!==` -`)&&(_="(?: "+_+")",E=" "+E,T++),y=new RegExp("^(?:"+_+")",S)),g&&(y=new RegExp("^"+_+"$(?!\\s)",S)),d&&(v=x.lastIndex),m=l.call(C?y:x,E),C?m?(m.input=m.input.slice(T),m[0]=m[0].slice(T),m.index=x.lastIndex,x.lastIndex+=m[0].length):x.lastIndex=0:d&&m&&(x.lastIndex=x.global?m.index+m[0].length:v),g&&m&&m.length>1&&f.call(m[0],y,function(){for(w=1;w]*>)/g,y=/\$([$&'`]|\d\d?)/g;o("replace",2,function(m,w,x,C){var S=C.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,_=C.REPLACE_KEEPS_$0,T=S?"$":"$0";return[function(D,b){var I=f(this),P=D==null?void 0:D[m];return P!==void 0?P.call(D,I,b):w.call(String(I),D,b)},function(D,b){if(!S&&_||typeof b=="string"&&b.indexOf(T)===-1){var I=x(w,D,this,b);if(I.done)return I.value}var P=a(D),M=String(this),L=typeof b=="function";L||(b=String(b));var V=P.global;if(V){var G=P.unicode;P.lastIndex=0}for(var A=[];;){var k=d(P,M);if(k===null||(A.push(k),!V))break;String(k[0])===""&&(P.lastIndex=u(M,c(P.lastIndex),G))}for(var F,j="",Y=0,re=0;re=Y&&(j+=M.slice(Y,ce)+B,Y=ce+ue.length)}return j+M.slice(Y)}];function E(D,b,I,P,M,L){var V=I+D.length,G=P.length,A=y;return M!==void 0&&(M=s(M),A=v),w.call(L,A,function(k,F){var j;switch(F.charAt(0)){case"$":return"$";case"&":return D;case"`":return b.slice(0,I);case"'":return b.slice(V);case"<":j=M[F.slice(1,-1)];break;default:var Y=+F;if(Y===0)return k;if(Y>G){var re=p(Y/10);return re===0?k:re<=G?P[re-1]===void 0?F.charAt(1):P[re-1]+F.charAt(1):k}j=P[Y-1]}return j===void 0?"":j})}})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){this._items={},this._nullItems=[]}return a.prototype.copy=function(){var s=new a;for(var c in this._items)s._items[c]=this._items[c].slice(0);return s._nullItems=this._nullItems.slice(0),s},a.prototype.get=function(s,c){var l=c===null?this._nullItems:this._items[c]||null;if(l===null)return null;for(var f=null,u=0;u=b.length&&(b=void 0),{value:b&&b[M++],done:!b}}};throw new TypeError(I?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(b,I){var P=typeof Symbol=="function"&&b[Symbol.iterator];if(!P)return b;var M,L,V=P.call(b),G=[];try{for(;(I===void 0||I-- >0)&&!(M=V.next()).done;)G.push(M.value)}catch(A){L={error:A}}finally{try{M&&!M.done&&(P=V.return)&&P.call(V)}finally{if(L)throw L.error}}return G},s=this&&this.__spread||function(){for(var b=[],I=0;I=0;xe--)if((Ne=ee[xe]).shadowAdjustedTarget!==null){Z=Ne;break}if(Z!==null)if(f.Guard.isNode(Z.shadowAdjustedTarget)&&f.Guard.isShadowRoot(g.tree_rootNode(Z.shadowAdjustedTarget,!0)))k=!0;else if(f.Guard.isNode(Z.relatedTarget)&&f.Guard.isShadowRoot(g.tree_rootNode(Z.relatedTarget,!0)))k=!0;else for(var De=0;De=0;xe--)(Ne=ee[xe]).shadowAdjustedTarget!==null?b._eventPhase=l.EventPhase.AtTarget:b._eventPhase=l.EventPhase.Capturing,C(Ne,b,"capturing",M);for(xe=0;xe0&&(A=L[V-1]).shadowAdjustedTarget!==null)&&(I._target=A.shadowAdjustedTarget)}if(I._relatedTarget=b.relatedTarget,I._touchTargetList=b.touchTargetList,!I._stopPropagationFlag){I._currentTarget=b.invocationTarget;var k=I._currentTarget._eventListenerList,F=new(Array.bind.apply(Array,s([void 0],k)));if(!S(I,F,P,b,M)&&I._isTrusted){var j=I._type;j==="animationend"?I._type="webkitAnimationEnd":j==="animationiteration"?I._type="webkitAnimationIteration":j==="animationstart"?I._type="webkitAnimationStart":j==="transitionend"&&(I._type="webkitTransitionEnd"),S(I,F,P,b,M),I._type=j}}}function S(b,I,P,M,L){L===void 0&&(L={value:!1});for(var V=!1,G=0;G=x.length&&(x=void 0),{value:x&&x[_++],done:!x}}};throw new TypeError(C?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(x,C){var S=typeof Symbol=="function"&&x[Symbol.iterator];if(!S)return x;var _,T,E=S.call(x),D=[];try{for(;(C===void 0||C-- >0)&&!(_=E.next()).done;)D.push(_.value)}catch(b){T={error:b}}finally{try{_&&!_.done&&(S=E.return)&&S.call(E)}finally{if(T)throw T.error}}return D};Object.defineProperty(n,"__esModule",{value:!0});var l=i(6),f=i(2),u=i(9),d=i(34),h=i(3),g=i(1),p=i(7),v=i(152),y=i(0),m=i(12),w=function(x){function C(){var S=x.call(this)||this;return S._children=new Set,S._encoding={name:"UTF-8",labels:["unicode-1-1-utf-8","utf-8","utf8"]},S._contentType="application/xml",S._URL={scheme:"about",username:"",password:"",host:null,port:null,path:["blank"],query:null,fragment:null,_cannotBeABaseURLFlag:!0,_blobURLEntry:null},S._origin=null,S._type="xml",S._mode="no-quirks",S._documentElement=null,S._hasNamespaces=!1,S._nodeDocumentOverwrite=null,S}return a(C,x),Object.defineProperty(C.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverwrite||this},set:function(S){this._nodeDocumentOverwrite=S},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"implementation",{get:function(){return this._implementation||(this._implementation=y.create_domImplementation(this))},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"URL",{get:function(){return v.urlSerializer(this._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"documentURI",{get:function(){return this.URL},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"origin",{get:function(){return"null"},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"compatMode",{get:function(){return this._mode==="quirks"?"BackCompat":"CSS1Compat"},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"characterSet",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"charset",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"inputEncoding",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"contentType",{get:function(){return this._contentType},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"doctype",{get:function(){var S,_;try{for(var T=s(this._children),E=T.next();!E.done;E=T.next()){var D=E.value;if(h.Guard.isDocumentTypeNode(D))return D}}catch(b){S={error:b}}finally{try{E&&!E.done&&(_=T.return)&&_.call(T)}finally{if(S)throw S.error}}return null},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"documentElement",{get:function(){return this._documentElement},enumerable:!0,configurable:!0}),C.prototype.getElementsByTagName=function(S){return y.node_listOfElementsWithQualifiedName(S,this)},C.prototype.getElementsByTagNameNS=function(S,_){return y.node_listOfElementsWithNamespace(S,_,this)},C.prototype.getElementsByClassName=function(S){return y.node_listOfElementsWithClassNames(S,this)},C.prototype.createElement=function(S,_){if(!y.xml_isName(S))throw new u.InvalidCharacterError;this._type==="html"&&(S=S.toLowerCase());var T=null;_!==void 0&&(T=g.isString(_)?_:_.is);var E=this._type==="html"||this._contentType==="application/xhtml+xml"?p.namespace.HTML:null;return y.element_createAnElement(this,S,E,null,T,!0)},C.prototype.createElementNS=function(S,_,T){return y.document_internalCreateElementNS(this,S,_,T)},C.prototype.createDocumentFragment=function(){return y.create_documentFragment(this)},C.prototype.createTextNode=function(S){return y.create_text(this,S)},C.prototype.createCDATASection=function(S){if(this._type==="html")throw new u.NotSupportedError;if(S.indexOf("]]>")!==-1)throw new u.InvalidCharacterError;return y.create_cdataSection(this,S)},C.prototype.createComment=function(S){return y.create_comment(this,S)},C.prototype.createProcessingInstruction=function(S,_){if(!y.xml_isName(S))throw new u.InvalidCharacterError;if(_.indexOf("?>")!==-1)throw new u.InvalidCharacterError;return y.create_processingInstruction(this,S,_)},C.prototype.importNode=function(S,_){if(_===void 0&&(_=!1),h.Guard.isDocumentNode(S)||h.Guard.isShadowRoot(S))throw new u.NotSupportedError;return y.node_clone(S,this,_)},C.prototype.adoptNode=function(S){if(h.Guard.isDocumentNode(S))throw new u.NotSupportedError;if(h.Guard.isShadowRoot(S))throw new u.HierarchyRequestError;return y.document_adopt(S,this),S},C.prototype.createAttribute=function(S){if(!y.xml_isName(S))throw new u.InvalidCharacterError;return this._type==="html"&&(S=S.toLowerCase()),y.create_attr(this,S)},C.prototype.createAttributeNS=function(S,_){var T=c(y.namespace_validateAndExtract(S,_),3),E=T[0],D=T[1],b=T[2],I=y.create_attr(this,b);return I._namespace=E,I._namespacePrefix=D,I},C.prototype.createEvent=function(S){return y.event_createLegacyEvent(S)},C.prototype.createRange=function(){var S=y.create_range();return S._start=[this,0],S._end=[this,0],S},C.prototype.createNodeIterator=function(S,_,T){_===void 0&&(_=f.WhatToShow.All),T===void 0&&(T=null);var E=y.create_nodeIterator(S,S,!0);return E._whatToShow=_,E._iteratorCollection=y.create_nodeList(S),g.isFunction(T)?(E._filter=y.create_nodeFilter(),E._filter.acceptNode=T):E._filter=T,E},C.prototype.createTreeWalker=function(S,_,T){_===void 0&&(_=f.WhatToShow.All),T===void 0&&(T=null);var E=y.create_treeWalker(S,S);return E._whatToShow=_,g.isFunction(T)?(E._filter=y.create_nodeFilter(),E._filter.acceptNode=T):E._filter=T,E},C.prototype._getTheParent=function(S){return S._type==="load"?null:l.dom.window},C.prototype.getElementById=function(S){throw new Error("Mixin: NonElementParentNode not implemented.")},Object.defineProperty(C.prototype,"children",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"firstElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"lastElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"childElementCount",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),C.prototype.prepend=function(){for(var S=[],_=0;_=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(v,y){var m=typeof Symbol=="function"&&v[Symbol.iterator];if(!m)return v;var w,x,C=m.call(v),S=[];try{for(;(y===void 0||y-- >0)&&!(w=C.next()).done;)S.push(w.value)}catch(_){x={error:_}}finally{try{w&&!w.done&&(m=C.return)&&m.call(C)}finally{if(x)throw x.error}}return S};Object.defineProperty(n,"__esModule",{value:!0});var l=i(2),f=i(34),u=i(9),d=i(7),h=i(0),g=i(12),p=function(v){function y(){var m=v.call(this)||this;return m._children=new Set,m._namespace=null,m._namespacePrefix=null,m._localName="",m._customElementState="undefined",m._customElementDefinition=null,m._is=null,m._shadowRoot=null,m._attributeList=h.create_namedNodeMap(m),m._attributeChangeSteps=[],m._name="",m._assignedSlot=null,m}return a(y,v),Object.defineProperty(y.prototype,"namespaceURI",{get:function(){return this._namespace},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"prefix",{get:function(){return this._namespacePrefix},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"localName",{get:function(){return this._localName},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"tagName",{get:function(){return this._htmlUppercasedQualifiedName},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"id",{get:function(){return h.element_getAnAttributeValue(this,"id")},set:function(m){h.element_setAnAttributeValue(this,"id",m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"className",{get:function(){return h.element_getAnAttributeValue(this,"class")},set:function(m){h.element_setAnAttributeValue(this,"class",m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"classList",{get:function(){var m=h.element_getAnAttributeByName("class",this);return m===null&&(m=h.create_attr(this._nodeDocument,"class")),h.create_domTokenList(this,m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"slot",{get:function(){return h.element_getAnAttributeValue(this,"slot")},set:function(m){h.element_setAnAttributeValue(this,"slot",m)},enumerable:!0,configurable:!0}),y.prototype.hasAttributes=function(){return this._attributeList.length!==0},Object.defineProperty(y.prototype,"attributes",{get:function(){return this._attributeList},enumerable:!0,configurable:!0}),y.prototype.getAttributeNames=function(){var m,w,x=[];try{for(var C=s(this._attributeList),S=C.next();!S.done;S=C.next()){var _=S.value;x.push(_._qualifiedName)}}catch(T){m={error:T}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x},y.prototype.getAttribute=function(m){var w=h.element_getAnAttributeByName(m,this);return w?w._value:null},y.prototype.getAttributeNS=function(m,w){var x=h.element_getAnAttributeByNamespaceAndLocalName(m,w,this);return x?x._value:null},y.prototype.setAttribute=function(m,w){if(!h.xml_isName(m))throw new u.InvalidCharacterError;this._namespace===d.namespace.HTML&&this._nodeDocument._type==="html"&&(m=m.toLowerCase());for(var x=null,C=0;C=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(2),l=i(71),f=i(0),u=i(12),d=function(h){function g(p){p===void 0&&(p="");var v=h.call(this,p)||this;return v._name="",v._assignedSlot=null,v}return a(g,h),Object.defineProperty(g.prototype,"wholeText",{get:function(){var p,v,y="";try{for(var m=s(f.text_contiguousTextNodes(this,!0)),w=m.next();!w.done;w=m.next())y+=w.value._data}catch(x){p={error:x}}finally{try{w&&!w.done&&(v=m.return)&&v.call(m)}finally{if(p)throw p.error}}return y},enumerable:!0,configurable:!0}),g.prototype.splitText=function(p){return f.text_split(this,p)},Object.defineProperty(g.prototype,"assignedSlot",{get:function(){throw new Error("Mixin: Slotable not implemented.")},enumerable:!0,configurable:!0}),g._create=function(p,v){v===void 0&&(v="");var y=new g(v);return y._nodeDocument=p,y},g}(l.CharacterDataImpl);n.TextImpl=d,u.idl_defineConst(d.prototype,"_nodeType",c.NodeType.Text)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){}return Object.defineProperty(a.prototype,"_startNode",{get:function(){return this._start[0]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_startOffset",{get:function(){return this._start[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_endNode",{get:function(){return this._end[0]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_endOffset",{get:function(){return this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_collapsed",{get:function(){return this._start[0]===this._end[0]&&this._start[1]===this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"startContainer",{get:function(){return this._startNode},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"startOffset",{get:function(){return this._startOffset},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"endContainer",{get:function(){return this._endNode},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"endOffset",{get:function(){return this._endOffset},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"collapsed",{get:function(){return this._collapsed},enumerable:!0,configurable:!0}),a}();n.AbstractRangeImpl=o},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=function(){function s(c){this._activeFlag=!1,this._root=c,this._whatToShow=o.WhatToShow.All,this._filter=null}return Object.defineProperty(s.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"whatToShow",{get:function(){return this._whatToShow},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"filter",{get:function(){return this._filter},enumerable:!0,configurable:!0}),s}();n.TraverserImpl=a},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(0),s=i(12),c=function(){function l(f,u){this._target=null,this._relatedTarget=null,this._touchTargetList=[],this._path=[],this._currentTarget=null,this._eventPhase=o.EventPhase.None,this._stopPropagationFlag=!1,this._stopImmediatePropagationFlag=!1,this._canceledFlag=!1,this._inPassiveListenerFlag=!1,this._composedFlag=!1,this._initializedFlag=!1,this._dispatchFlag=!1,this._isTrusted=!1,this._bubbles=!1,this._cancelable=!1,this._type=f,u&&(this._bubbles=u.bubbles||!1,this._cancelable=u.cancelable||!1,this._composedFlag=u.composed||!1),this._initializedFlag=!0,this._timeStamp=new Date().getTime()}return Object.defineProperty(l.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"srcElement",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"currentTarget",{get:function(){return this._currentTarget},enumerable:!0,configurable:!0}),l.prototype.composedPath=function(){var f=[],u=this._path;if(u.length===0)return f;var d=this._currentTarget;if(d===null)throw new Error("Event currentTarget is null.");f.push(d);for(var h=0,g=0,p=u.length-1;p>=0;){if(u[p].rootOfClosedTree&&g++,u[p].invocationTarget===d){h=p;break}u[p].slotInClosedTree&&g--,p--}var v=g,y=g;for(p=h-1;p>=0;)u[p].rootOfClosedTree&&v++,v<=y&&f.unshift(u[p].invocationTarget),u[p].slotInClosedTree&&--v0)&&!(x=S.next()).done;)_.push(x.value)}catch(T){C={error:T}}finally{try{x&&!x.done&&(w=S.return)&&w.call(S)}finally{if(C)throw C.error}}return _},a=this&&this.__values||function(y){var m=typeof Symbol=="function"&&Symbol.iterator,w=m&&y[m],x=0;if(w)return w.call(y);if(y&&typeof y.length=="number")return{next:function(){return y&&x>=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=i(6),c=i(3),l=i(1),f=i(99),u=i(73),d=i(17),h=i(173),g=i(30),p=i(52),v=i(37);n.document_elementInterface=function(y,m){return f.ElementImpl},n.document_internalCreateElementNS=function(y,m,w,x){var C=o(h.namespace_validateAndExtract(m,w),3),S=C[0],_=C[1],T=C[2],E=null;return x!==void 0&&(E=l.isString(x)?x:x.is),p.element_createAnElement(y,T,S,_,E,!0)},n.document_adopt=function(y,m){var w,x;if(y._nodeDocument!==m||y._parent!==null){var C=y._nodeDocument;if(y._parent&&v.mutation_remove(y,y._parent),m!==C)for(var S=d.tree_getFirstDescendantNode(y,!0,!0);S!==null;){if(S._nodeDocument=m,c.Guard.isElementNode(S))try{for(var _=(w=void 0,a(S._attributeList._asArray())),T=_.next();!T.done;T=_.next())T.value._nodeDocument=m}catch(E){w={error:E}}finally{try{T&&!T.done&&(x=_.return)&&x.call(_)}finally{if(w)throw w.error}}s.dom.features.customElements&&c.Guard.isElementNode(S)&&S._customElementState==="custom"&&u.customElement_enqueueACustomElementCallbackReaction(S,"adoptedCallback",[C,m]),s.dom.features.steps&&g.dom_runAdoptingSteps(S,C),S=d.tree_getNextDescendantNode(y,S,!0,!0)}}}},function(r,n,i){var o=this&&this.__values||function(d){var h=typeof Symbol=="function"&&Symbol.iterator,g=h&&d[h],p=0;if(g)return g.call(d);if(d&&typeof d.length=="number")return{next:function(){return d&&p>=d.length&&(d=void 0),{value:d&&d[p++],done:!d}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(9),l=i(17),f=i(51),u=i(30);n.characterData_replaceData=function(d,h,g,p){var v,y,m=l.tree_nodeLength(d);if(h>m)throw new c.IndexSizeError("Offset exceeds character data length. Offset: "+h+", Length: "+m+", Node is "+d.nodeName+".");h+g>m&&(g=m-h),a.dom.features.mutationObservers&&f.observer_queueMutationRecord("characterData",d,null,null,d._data,[],[],null,null);var w=d._data.substring(0,h)+p+d._data.substring(h+g);d._data=w;try{for(var x=o(a.dom.rangeList),C=x.next();!C.done;C=x.next()){var S=C.value;S._start[0]===d&&S._start[1]>h&&S._start[1]<=h+g&&(S._start[1]=h),S._end[0]===d&&S._end[1]>h&&S._end[1]<=h+g&&(S._end[1]=h),S._start[0]===d&&S._start[1]>h+g&&(S._start[1]+=p.length-g),S._end[0]===d&&S._end[1]>h+g&&(S._end[1]+=p.length-g)}}catch(_){v={error:_}}finally{try{C&&!C.done&&(y=x.return)&&y.call(x)}finally{if(v)throw v.error}}a.dom.features.steps&&s.Guard.isTextNode(d)&&d._parent!==null&&u.dom_runChildTextContentChangeSteps(d._parent)},n.characterData_substringData=function(d,h,g){var p=l.tree_nodeLength(d);if(h>p)throw new c.IndexSizeError("Offset exceeds character data length. Offset: "+h+", Length: "+p+", Node is "+d.nodeName+".");return h+g>p?d._data.substr(h):d._data.substr(h,g)}},function(r,n,i){var o=this&&this.__read||function(u,d){var h=typeof Symbol=="function"&&u[Symbol.iterator];if(!h)return u;var g,p,v=h.call(u),y=[];try{for(;(d===void 0||d-- >0)&&!(g=v.next()).done;)y.push(g.value)}catch(m){p={error:m}}finally{try{g&&!g.done&&(h=v.return)&&h.call(v)}finally{if(p)throw p.error}}return y},a=this&&this.__spread||function(){for(var u=[],d=0;d=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(7);function l(u){var d=c.string.splitAStringOnASCIIWhitespace(u);return new Set(d)}function f(u){return a(u).join(" ")}n.orderedSet_parse=l,n.orderedSet_serialize=f,n.orderedSet_sanitize=function(u){return f(l(u))},n.orderedSet_contains=function(u,d,h){var g,p,v,y;try{for(var m=s(d),w=m.next();!w.done;w=m.next()){var x=w.value,C=!1;try{for(var S=(v=void 0,s(u)),_=S.next();!_.done;_=S.next()){var T=_.value;if(h){if(T===x){C=!0;break}}else if(T.toUpperCase()===x.toUpperCase()){C=!0;break}}}catch(E){v={error:E}}finally{try{_&&!_.done&&(y=S.return)&&y.call(S)}finally{if(v)throw v.error}}if(!C)return!1}}catch(E){g={error:E}}finally{try{w&&!w.done&&(p=m.return)&&p.call(m)}finally{if(g)throw g.error}}return!0}},function(r,n,i){i(179),Object.defineProperty(n,"__esModule",{value:!0});var o=i(262),a=i(110),s=i(1);a.dom.setFeatures(!1),n.createDocument=function(){var c=new o.DOMImplementation().createDocument(null,"root",null);return c.documentElement&&c.removeChild(c.documentElement),c},n.sanitizeInput=function(c,l){if(c==null)return c;if(l===void 0)return c+"";var f="";c+="";for(var u=0;u=32&&d<=55295||d>=57344&&d<=65533)f+=c.charAt(u);else if(d>=55296&&d<=56319&&u=56320&&h<=57343?(d=1024*(d-55296)+h-56320+65536,f+=String.fromCodePoint(d),u++):f+=s.isString(l)?l:l(c.charAt(u),u,c)}else f+=s.isString(l)?l:l(c.charAt(u),u,c)}return f}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(1),a=i(153);n.AbortController=a.AbortControllerImpl;var s=i(154);n.AbortSignal=s.AbortSignalImpl;var c=i(102);n.AbstractRange=c.AbstractRangeImpl;var l=i(157);n.Attr=l.AttrImpl;var f=i(158);n.CDATASection=f.CDATASectionImpl;var u=i(71);n.CharacterData=u.CharacterDataImpl;var d=i(263),h=i(159);n.Comment=h.CommentImpl;var g=i(171);n.CustomEvent=g.CustomEventImpl;var p=i(100);n.DocumentFragment=p.DocumentFragmentImpl;var v=i(98);n.Document=v.DocumentImpl;var y=i(264),m=i(155);n.DocumentType=m.DocumentTypeImpl;var w=i(6);n.dom=w.dom;var x=i(148);n.DOMImplementation=x.DOMImplementationImpl;var C=i(170);n.DOMTokenList=C.DOMTokenListImpl;var S=i(99);n.Element=S.ElementImpl;var _=i(104);n.Event=_.EventImpl;var T=i(70);n.EventTarget=T.EventTargetImpl;var E=i(161);n.HTMLCollection=E.HTMLCollectionImpl;var D=i(265);n.MutationObserver=D.MutationObserverImpl;var b=i(169);n.MutationRecord=b.MutationRecordImpl;var I=i(164);n.NamedNodeMap=I.NamedNodeMapImpl;var P=i(168);n.NodeFilter=P.NodeFilterImpl;var M=i(34);n.Node=M.NodeImpl;var L=i(166);n.NodeIterator=L.NodeIteratorImpl;var V=i(162);n.NodeList=V.NodeListImpl;var G=i(163);n.NodeListStatic=G.NodeListStaticImpl;var A=i(266),k=i(267),F=i(268),j=i(160);n.ProcessingInstruction=j.ProcessingInstructionImpl;var Y=i(165);n.Range=Y.RangeImpl;var re=i(156);n.ShadowRoot=re.ShadowRootImpl;var ue=i(269),ce=i(270);n.StaticRange=ce.StaticRangeImpl;var pe=i(101);n.Text=pe.TextImpl;var Ee=i(103);n.Traverser=Ee.TraverserImpl;var Oe=i(167);n.TreeWalker=Oe.TreeWalkerImpl;var Se=i(149);n.Window=Se.WindowImpl;var B=i(151);n.XMLDocument=B.XMLDocumentImpl,o.applyMixin(S.ElementImpl,d.ChildNodeImpl),o.applyMixin(u.CharacterDataImpl,d.ChildNodeImpl),o.applyMixin(m.DocumentTypeImpl,d.ChildNodeImpl),o.applyMixin(v.DocumentImpl,y.DocumentOrShadowRootImpl),o.applyMixin(re.ShadowRootImpl,y.DocumentOrShadowRootImpl),o.applyMixin(S.ElementImpl,A.NonDocumentTypeChildNodeImpl),o.applyMixin(u.CharacterDataImpl,A.NonDocumentTypeChildNodeImpl),o.applyMixin(v.DocumentImpl,k.NonElementParentNodeImpl),o.applyMixin(p.DocumentFragmentImpl,k.NonElementParentNodeImpl),o.applyMixin(v.DocumentImpl,F.ParentNodeImpl),o.applyMixin(p.DocumentFragmentImpl,F.ParentNodeImpl),o.applyMixin(S.ElementImpl,F.ParentNodeImpl),o.applyMixin(pe.TextImpl,ue.SlotableImpl),o.applyMixin(S.ElementImpl,ue.SlotableImpl)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),function(o){o[o.EOF=0]="EOF",o[o.Declaration=1]="Declaration",o[o.DocType=2]="DocType",o[o.Element=3]="Element",o[o.Text=4]="Text",o[o.CDATA=5]="CDATA",o[o.PI=6]="PI",o[o.Comment=7]="Comment",o[o.ClosingTag=8]="ClosingTag"}(n.TokenType||(n.TokenType={}))},function(r,n,i){i(64),i(20),i(66);var o,a=this&&this.__extends||(o=function(l,f){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,d){u.__proto__=d}||function(u,d){for(var h in d)d.hasOwnProperty(h)&&(u[h]=d[h])})(l,f)},function(l,f){function u(){this.constructor=l}o(l,f),l.prototype=f===null?Object.create(f):(u.prototype=f.prototype,new u)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(1),c=function(l){function f(){return l!==null&&l.apply(this,arguments)||this}return a(f,l),f.prototype._parse=function(u,d){var h=this,g=this._builderOptions,p=null;return s.isFunction(d)?p=this.parse(u,d.apply(this)):s.isArray(d)||s.isSet(d)?s.forEachArray(d,function(v){return p=h.parse(u,v)},this):s.isMap(d)||s.isObject(d)?s.forEachObject(d,function(v,y){if(s.isFunction(y)&&(y=y.apply(h)),g.ignoreConverters||v.indexOf(g.convert.att)!==0)if(g.ignoreConverters||v.indexOf(g.convert.text)!==0)if(g.ignoreConverters||v.indexOf(g.convert.cdata)!==0)if(g.ignoreConverters||v.indexOf(g.convert.comment)!==0)if(g.ignoreConverters||v.indexOf(g.convert.ins)!==0){if(!((s.isArray(y)||s.isSet(y))&&s.isEmpty(y))){if((s.isMap(y)||s.isObject(y))&&s.isEmpty(y))p=h.element(u,void 0,h.sanitize(v))||p;else if(g.keepNullNodes||y!=null)if(s.isArray(y)||s.isSet(y))s.forEachArray(y,function(S){var _={};_[v]=S,p=h.parse(u,_)},h);else if(s.isMap(y)||s.isObject(y))(m=h.element(u,void 0,h.sanitize(v)))&&(p=m,h.parse(m,y));else if(y!=null&&y!==""){var m;(m=h.element(u,void 0,h.sanitize(v)))&&(p=m,h.text(m,h._decodeText(h.sanitize(y))))}else p=h.element(u,void 0,h.sanitize(v))||p}}else if(s.isString(y)){var w=y.indexOf(" "),x=w===-1?y:y.substr(0,w),C=w===-1?"":y.substr(w+1);p=h.instruction(u,h.sanitize(x),h.sanitize(C))||p}else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){var _=S.indexOf(" "),T=_===-1?S:S.substr(0,_),E=_===-1?"":S.substr(_+1);p=h.instruction(u,h.sanitize(T),h.sanitize(E))||p},h):s.forEachObject(y,function(S,_){return p=h.instruction(u,h.sanitize(S),h.sanitize(_))||p},h);else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){return p=h.comment(u,h.sanitize(S))||p},h):p=h.comment(u,h.sanitize(y))||p;else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){return p=h.cdata(u,h.sanitize(S))||p},h):p=h.cdata(u,h.sanitize(y))||p;else p=s.isMap(y)||s.isObject(y)?h.parse(u,y):h.text(u,h._decodeText(h.sanitize(y)))||p;else if(v===g.convert.att){if(s.isArray(y)||s.isSet(y))throw new Error("Invalid attribute: "+y.toString()+". "+u._debugInfo());s.forEachObject(y,function(S,_){p=h.attribute(u,void 0,h.sanitize(S),h._decodeAttributeValue(h.sanitize(_)))||p})}else p=h.attribute(u,void 0,h.sanitize(v.substr(g.convert.att.length)),h._decodeAttributeValue(h.sanitize(y)))||p},this):(g.keepNullNodes||d!=null)&&(p=this.text(u,this._decodeText(this.sanitize(d)))||p),p||u},f}(i(75).BaseReader);n.ObjectReader=c},function(r,n,i){var o=i(39);r.exports=new o({explicit:[i(286),i(287),i(288)]})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(a){this.level=0,this._builderOptions=a,this._writerOptions=a};n.BaseCBWriter=o},function(r,n,i){var o=i(16),a=i(8),s=i(116);r.exports=!o&&!a(function(){return Object.defineProperty(s("div"),"a",{get:function(){return 7}}).a!=7})},function(r,n,i){var o=i(11),a=i(13),s=o.document,c=a(s)&&a(s.createElement);r.exports=function(l){return c?s.createElement(l):{}}},function(r,n,i){var o=i(118),a=Function.toString;typeof o.inspectSource!="function"&&(o.inspectSource=function(s){return a.call(s)}),r.exports=o.inspectSource},function(r,n,i){var o=i(11),a=i(80),s=o["__core-js_shared__"]||a("__core-js_shared__",{});r.exports=s},function(r,n,i){var o=i(14),a=i(187),s=i(55),c=i(15);r.exports=function(l,f){for(var u=a(f),d=c.f,h=s.f,g=0;gh;)o(d,u=f[h++])&&(~s(g,u)||g.push(u));return g}},function(r,n,i){var o=i(24),a=i(26),s=i(83),c=function(l){return function(f,u,d){var h,g=o(f),p=a(g.length),v=s(d,p);if(l&&u!=u){for(;p>v;)if((h=g[v++])!=h)return!0}else for(;p>v;v++)if((l||v in g)&&g[v]===u)return l||v||0;return!l&&-1}};r.exports={includes:c(!0),indexOf:c(!1)}},function(r,n,i){var o=i(8),a=/#|\.prototype\./,s=function(d,h){var g=l[c(d)];return g==u||g!=f&&(typeof h=="function"?o(h):!!h)},c=s.normalize=function(d){return String(d).replace(a,".").toLowerCase()},l=s.data={},f=s.NATIVE="N",u=s.POLYFILL="P";r.exports=s},function(r,n,i){var o=i(86);r.exports=o&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},function(r,n,i){var o=i(5);n.f=o},function(r,n,i){var o=i(120),a=i(14),s=i(125),c=i(15).f;r.exports=function(l){var f=o.Symbol||(o.Symbol={});a(f,l)||c(f,l,{value:s.f(l)})}},function(r,n){r.exports=function(i){if(typeof i!="function")throw TypeError(String(i)+" is not a function");return i}},function(r,n,i){var o=i(13),a=i(59),s=i(5)("species");r.exports=function(c,l){var f;return a(c)&&(typeof(f=c.constructor)!="function"||f!==Array&&!a(f.prototype)?o(f)&&(f=f[s])===null&&(f=void 0):f=void 0),new(f===void 0?Array:f)(l===0?0:l)}},function(r,n,i){var o,a,s=i(11),c=i(193),l=s.process,f=l&&l.versions,u=f&&f.v8;u?a=(o=u.split("."))[0]+o[1]:c&&(!(o=c.match(/Edge\/(\d+)/))||o[1]>=74)&&(o=c.match(/Chrome\/(\d+)/))&&(a=o[1]),r.exports=a&&+a},function(r,n,i){var o=i(5),a=i(60),s=i(15),c=o("unscopables"),l=Array.prototype;l[c]==null&&s.f(l,c,{configurable:!0,value:a(null)}),r.exports=function(f){l[c][f]=!0}},function(r,n,i){var o,a,s,c=i(132),l=i(21),f=i(14),u=i(5),d=i(44),h=u("iterator"),g=!1;[].keys&&("next"in(s=[].keys())?(a=c(c(s)))!==Object.prototype&&(o=a):g=!0),o==null&&(o={}),d||f(o,h)||l(o,h,function(){return this}),r.exports={IteratorPrototype:o,BUGGY_SAFARI_ITERATORS:g}},function(r,n,i){var o=i(14),a=i(27),s=i(57),c=i(196),l=s("IE_PROTO"),f=Object.prototype;r.exports=c?Object.getPrototypeOf:function(u){return u=a(u),o(u,l)?u[l]:typeof u.constructor=="function"&&u instanceof u.constructor?u.constructor.prototype:u instanceof Object?f:null}},function(r,n,i){var o=i(18),a=i(197);r.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s,c=!1,l={};try{(s=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(l,[]),c=l instanceof Array}catch{}return function(f,u){return o(f),a(u),c?s.call(f,u):f.__proto__=u,f}}():void 0)},function(r,n,i){var o=i(56),a=i(15),s=i(40);r.exports=function(c,l,f){var u=o(l);u in c?a.f(c,u,s(0,f)):c[u]=f}},function(r,n,i){var o=i(90),a=i(42),s=i(5)("toStringTag"),c=a(function(){return arguments}())=="Arguments";r.exports=o?a:function(l){var f,u,d;return l===void 0?"Undefined":l===null?"Null":typeof(u=function(h,g){try{return h[g]}catch{}}(f=Object(l),s))=="string"?u:c?a(f):(d=a(f))=="Object"&&typeof f.callee=="function"?"Arguments":d}},function(r,n,i){var o=i(18);r.exports=function(){var a=o(this),s="";return a.global&&(s+="g"),a.ignoreCase&&(s+="i"),a.multiline&&(s+="m"),a.dotAll&&(s+="s"),a.unicode&&(s+="u"),a.sticky&&(s+="y"),s}},function(r,n,i){var o=i(47),a=i(35),s=function(c){return function(l,f){var u,d,h=String(a(l)),g=o(f),p=h.length;return g<0||g>=p?c?"":void 0:(u=h.charCodeAt(g))<55296||u>56319||g+1===p||(d=h.charCodeAt(g+1))<56320||d>57343?c?h.charAt(g):u:c?h.slice(g,g+2):d-56320+(u-55296<<10)+65536}};r.exports={codeAt:s(!1),charAt:s(!0)}},function(r,n,i){var o=i(4),a=i(27),s=i(61);o({target:"Object",stat:!0,forced:i(8)(function(){s(1)})},{keys:function(c){return s(a(c))}})},function(r,n,i){var o=i(4),a=i(11),s=i(123),c=i(25),l=i(140),f=i(141),u=i(142),d=i(13),h=i(8),g=i(208),p=i(62),v=i(209);r.exports=function(y,m,w){var x=y.indexOf("Map")!==-1,C=y.indexOf("Weak")!==-1,S=x?"set":"add",_=a[y],T=_&&_.prototype,E=_,D={},b=function(G){var A=T[G];c(T,G,G=="add"?function(k){return A.call(this,k===0?0:k),this}:G=="delete"?function(k){return!(C&&!d(k))&&A.call(this,k===0?0:k)}:G=="get"?function(k){return C&&!d(k)?void 0:A.call(this,k===0?0:k)}:G=="has"?function(k){return!(C&&!d(k))&&A.call(this,k===0?0:k)}:function(k,F){return A.call(this,k===0?0:k,F),this})};if(s(y,typeof _!="function"||!(C||T.forEach&&!h(function(){new _().entries().next()}))))E=w.getConstructor(m,y,x,S),l.REQUIRED=!0;else if(s(y,!0)){var I=new E,P=I[S](C?{}:-0,1)!=I,M=h(function(){I.has(1)}),L=g(function(G){new _(G)}),V=!C&&h(function(){for(var G=new _,A=5;A--;)G[S](A,A);return!G.has(-0)});L||((E=m(function(G,A){u(G,E,y);var k=v(new _,G,E);return A!=null&&f(A,k[S],k,x),k})).prototype=T,T.constructor=E),(M||V)&&(b("delete"),b("has"),x&&b("get")),(V||P)&&b(S),C&&T.clear&&delete T.clear}return D[y]=E,o({global:!0,forced:E!=_},D),p(E,y),C||w.setStrong(E,y,x),E}},function(r,n,i){var o=i(45),a=i(13),s=i(14),c=i(15).f,l=i(58),f=i(204),u=l("meta"),d=0,h=Object.isExtensible||function(){return!0},g=function(v){c(v,u,{value:{objectID:"O"+ ++d,weakData:{}}})},p=r.exports={REQUIRED:!1,fastKey:function(v,y){if(!a(v))return typeof v=="symbol"?v:(typeof v=="string"?"S":"P")+v;if(!s(v,u)){if(!h(v))return"F";if(!y)return"E";g(v)}return v[u].objectID},getWeakData:function(v,y){if(!s(v,u)){if(!h(v))return!0;if(!y)return!1;g(v)}return v[u].weakData},onFreeze:function(v){return f&&p.REQUIRED&&h(v)&&!s(v,u)&&g(v),v}};o[u]=!0},function(r,n,i){var o=i(18),a=i(205),s=i(26),c=i(87),l=i(206),f=i(207),u=function(d,h){this.stopped=d,this.result=h};(r.exports=function(d,h,g,p,v){var y,m,w,x,C,S,_,T=c(h,g,p?2:1);if(v)y=d;else{if(typeof(m=l(d))!="function")throw TypeError("Target is not iterable");if(a(m)){for(w=0,x=s(d.length);x>w;w++)if((C=p?T(o(_=d[w])[0],_[1]):T(d[w]))&&C instanceof u)return C;return new u(!1)}y=m.call(d)}for(S=y.next;!(_=S.call(y)).done;)if(typeof(C=f(y,T,_.value,p))=="object"&&C&&C instanceof u)return C;return new u(!1)}).stop=function(d){return new u(!0,d)}},function(r,n){r.exports=function(i,o,a){if(!(i instanceof o))throw TypeError("Incorrect "+(a?a+" ":"")+"invocation");return i}},function(r,n,i){var o=i(15).f,a=i(60),s=i(210),c=i(87),l=i(142),f=i(141),u=i(88),d=i(211),h=i(16),g=i(140).fastKey,p=i(43),v=p.set,y=p.getterFor;r.exports={getConstructor:function(m,w,x,C){var S=m(function(D,b){l(D,S,w),v(D,{type:w,index:a(null),first:void 0,last:void 0,size:0}),h||(D.size=0),b!=null&&f(b,D[C],D,x)}),_=y(w),T=function(D,b,I){var P,M,L=_(D),V=E(D,b);return V?V.value=I:(L.last=V={index:M=g(b,!0),key:b,value:I,previous:P=L.last,next:void 0,removed:!1},L.first||(L.first=V),P&&(P.next=V),h?L.size++:D.size++,M!=="F"&&(L.index[M]=V)),D},E=function(D,b){var I,P=_(D),M=g(b);if(M!=="F")return P.index[M];for(I=P.first;I;I=I.next)if(I.key==b)return I};return s(S.prototype,{clear:function(){for(var D=_(this),b=D.index,I=D.first;I;)I.removed=!0,I.previous&&(I.previous=I.previous.next=void 0),delete b[I.index],I=I.next;D.first=D.last=void 0,h?D.size=0:this.size=0},delete:function(D){var b=_(this),I=E(this,D);if(I){var P=I.next,M=I.previous;delete b.index[I.index],I.removed=!0,M&&(M.next=P),P&&(P.previous=M),b.first==I&&(b.first=P),b.last==I&&(b.last=M),h?b.size--:this.size--}return!!I},forEach:function(D){for(var b,I=_(this),P=c(D,arguments.length>1?arguments[1]:void 0,3);b=b?b.next:I.first;)for(P(b.value,b.key,this);b&&b.removed;)b=b.previous},has:function(D){return!!E(this,D)}}),s(S.prototype,x?{get:function(D){var b=E(this,D);return b&&b.value},set:function(D,b){return T(this,D===0?0:D,b)}}:{add:function(D){return T(this,D=D===0?0:D,D)}}),h&&o(S.prototype,"size",{get:function(){return _(this).size}}),S},setStrong:function(m,w,x){var C=w+" Iterator",S=y(w),_=y(C);u(m,w,function(T,E){v(this,{type:C,target:T,state:S(T),kind:E,last:void 0})},function(){for(var T=_(this),E=T.kind,D=T.last;D&&D.removed;)D=D.previous;return T.target&&(T.last=D=D?D.next:T.state.first)?E=="keys"?{value:D.key,done:!1}:E=="values"?{value:D.value,done:!1}:{value:[D.key,D.value],done:!1}:(T.target=void 0,{value:void 0,done:!0})},x?"entries":"values",!x,!0),d(w)}}},function(r,n,i){var o,a=i(4),s=i(55).f,c=i(26),l=i(222),f=i(35),u=i(224),d=i(44),h="".endsWith,g=Math.min,p=u("endsWith");a({target:"String",proto:!0,forced:!!(d||p||(o=s(String.prototype,"endsWith"),!o||o.writable))&&!p},{endsWith:function(v){var y=String(f(this));l(v);var m=arguments.length>1?arguments[1]:void 0,w=c(y.length),x=m===void 0?w:g(c(m),w),C=String(v);return h?h.call(y,C,x):y.slice(x-C.length,x)===C}})},function(r,n,i){(function(o){/*! +`)&&(_="(?: "+_+")",E=" "+E,T++),y=new RegExp("^(?:"+_+")",S)),g&&(y=new RegExp("^"+_+"$(?!\\s)",S)),d&&(v=x.lastIndex),m=l.call(C?y:x,E),C?m?(m.input=m.input.slice(T),m[0]=m[0].slice(T),m.index=x.lastIndex,x.lastIndex+=m[0].length):x.lastIndex=0:d&&m&&(x.lastIndex=x.global?m.index+m[0].length:v),g&&m&&m.length>1&&f.call(m[0],y,function(){for(w=1;w]*>)/g,y=/\$([$&'`]|\d\d?)/g;o("replace",2,function(m,w,x,C){var S=C.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,_=C.REPLACE_KEEPS_$0,T=S?"$":"$0";return[function(D,b){var I=f(this),P=D==null?void 0:D[m];return P!==void 0?P.call(D,I,b):w.call(String(I),D,b)},function(D,b){if(!S&&_||typeof b=="string"&&b.indexOf(T)===-1){var I=x(w,D,this,b);if(I.done)return I.value}var P=a(D),M=String(this),L=typeof b=="function";L||(b=String(b));var V=P.global;if(V){var G=P.unicode;P.lastIndex=0}for(var A=[];;){var k=d(P,M);if(k===null||(A.push(k),!V))break;String(k[0])===""&&(P.lastIndex=u(M,c(P.lastIndex),G))}for(var F,j="",Y=0,re=0;re=Y&&(j+=M.slice(Y,ce)+B,Y=ce+ue.length)}return j+M.slice(Y)}];function E(D,b,I,P,M,L){var V=I+D.length,G=P.length,A=y;return M!==void 0&&(M=s(M),A=v),w.call(L,A,function(k,F){var j;switch(F.charAt(0)){case"$":return"$";case"&":return D;case"`":return b.slice(0,I);case"'":return b.slice(V);case"<":j=M[F.slice(1,-1)];break;default:var Y=+F;if(Y===0)return k;if(Y>G){var re=p(Y/10);return re===0?k:re<=G?P[re-1]===void 0?F.charAt(1):P[re-1]+F.charAt(1):k}j=P[Y-1]}return j===void 0?"":j})}})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){this._items={},this._nullItems=[]}return a.prototype.copy=function(){var s=new a;for(var c in this._items)s._items[c]=this._items[c].slice(0);return s._nullItems=this._nullItems.slice(0),s},a.prototype.get=function(s,c){var l=c===null?this._nullItems:this._items[c]||null;if(l===null)return null;for(var f=null,u=0;u=b.length&&(b=void 0),{value:b&&b[M++],done:!b}}};throw new TypeError(I?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(b,I){var P=typeof Symbol=="function"&&b[Symbol.iterator];if(!P)return b;var M,L,V=P.call(b),G=[];try{for(;(I===void 0||I-- >0)&&!(M=V.next()).done;)G.push(M.value)}catch(A){L={error:A}}finally{try{M&&!M.done&&(P=V.return)&&P.call(V)}finally{if(L)throw L.error}}return G},s=this&&this.__spread||function(){for(var b=[],I=0;I=0;xe--)if((Ne=ee[xe]).shadowAdjustedTarget!==null){Z=Ne;break}if(Z!==null)if(f.Guard.isNode(Z.shadowAdjustedTarget)&&f.Guard.isShadowRoot(g.tree_rootNode(Z.shadowAdjustedTarget,!0)))k=!0;else if(f.Guard.isNode(Z.relatedTarget)&&f.Guard.isShadowRoot(g.tree_rootNode(Z.relatedTarget,!0)))k=!0;else for(var De=0;De=0;xe--)(Ne=ee[xe]).shadowAdjustedTarget!==null?b._eventPhase=l.EventPhase.AtTarget:b._eventPhase=l.EventPhase.Capturing,C(Ne,b,"capturing",M);for(xe=0;xe0&&(A=L[V-1]).shadowAdjustedTarget!==null)&&(I._target=A.shadowAdjustedTarget)}if(I._relatedTarget=b.relatedTarget,I._touchTargetList=b.touchTargetList,!I._stopPropagationFlag){I._currentTarget=b.invocationTarget;var k=I._currentTarget._eventListenerList,F=new(Array.bind.apply(Array,s([void 0],k)));if(!S(I,F,P,b,M)&&I._isTrusted){var j=I._type;j==="animationend"?I._type="webkitAnimationEnd":j==="animationiteration"?I._type="webkitAnimationIteration":j==="animationstart"?I._type="webkitAnimationStart":j==="transitionend"&&(I._type="webkitTransitionEnd"),S(I,F,P,b,M),I._type=j}}}function S(b,I,P,M,L){L===void 0&&(L={value:!1});for(var V=!1,G=0;G=x.length&&(x=void 0),{value:x&&x[_++],done:!x}}};throw new TypeError(C?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(x,C){var S=typeof Symbol=="function"&&x[Symbol.iterator];if(!S)return x;var _,T,E=S.call(x),D=[];try{for(;(C===void 0||C-- >0)&&!(_=E.next()).done;)D.push(_.value)}catch(b){T={error:b}}finally{try{_&&!_.done&&(S=E.return)&&S.call(E)}finally{if(T)throw T.error}}return D};Object.defineProperty(n,"__esModule",{value:!0});var l=i(6),f=i(2),u=i(9),d=i(34),h=i(3),g=i(1),p=i(7),v=i(152),y=i(0),m=i(12),w=function(x){function C(){var S=x.call(this)||this;return S._children=new Set,S._encoding={name:"UTF-8",labels:["unicode-1-1-utf-8","utf-8","utf8"]},S._contentType="application/xml",S._URL={scheme:"about",username:"",password:"",host:null,port:null,path:["blank"],query:null,fragment:null,_cannotBeABaseURLFlag:!0,_blobURLEntry:null},S._origin=null,S._type="xml",S._mode="no-quirks",S._documentElement=null,S._hasNamespaces=!1,S._nodeDocumentOverwrite=null,S}return a(C,x),Object.defineProperty(C.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverwrite||this},set:function(S){this._nodeDocumentOverwrite=S},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"implementation",{get:function(){return this._implementation||(this._implementation=y.create_domImplementation(this))},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"URL",{get:function(){return v.urlSerializer(this._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"documentURI",{get:function(){return this.URL},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"origin",{get:function(){return"null"},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"compatMode",{get:function(){return this._mode==="quirks"?"BackCompat":"CSS1Compat"},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"characterSet",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"charset",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"inputEncoding",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"contentType",{get:function(){return this._contentType},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"doctype",{get:function(){var S,_;try{for(var T=s(this._children),E=T.next();!E.done;E=T.next()){var D=E.value;if(h.Guard.isDocumentTypeNode(D))return D}}catch(b){S={error:b}}finally{try{E&&!E.done&&(_=T.return)&&_.call(T)}finally{if(S)throw S.error}}return null},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"documentElement",{get:function(){return this._documentElement},enumerable:!0,configurable:!0}),C.prototype.getElementsByTagName=function(S){return y.node_listOfElementsWithQualifiedName(S,this)},C.prototype.getElementsByTagNameNS=function(S,_){return y.node_listOfElementsWithNamespace(S,_,this)},C.prototype.getElementsByClassName=function(S){return y.node_listOfElementsWithClassNames(S,this)},C.prototype.createElement=function(S,_){if(!y.xml_isName(S))throw new u.InvalidCharacterError;this._type==="html"&&(S=S.toLowerCase());var T=null;_!==void 0&&(T=g.isString(_)?_:_.is);var E=this._type==="html"||this._contentType==="application/xhtml+xml"?p.namespace.HTML:null;return y.element_createAnElement(this,S,E,null,T,!0)},C.prototype.createElementNS=function(S,_,T){return y.document_internalCreateElementNS(this,S,_,T)},C.prototype.createDocumentFragment=function(){return y.create_documentFragment(this)},C.prototype.createTextNode=function(S){return y.create_text(this,S)},C.prototype.createCDATASection=function(S){if(this._type==="html")throw new u.NotSupportedError;if(S.indexOf("]]>")!==-1)throw new u.InvalidCharacterError;return y.create_cdataSection(this,S)},C.prototype.createComment=function(S){return y.create_comment(this,S)},C.prototype.createProcessingInstruction=function(S,_){if(!y.xml_isName(S))throw new u.InvalidCharacterError;if(_.indexOf("?>")!==-1)throw new u.InvalidCharacterError;return y.create_processingInstruction(this,S,_)},C.prototype.importNode=function(S,_){if(_===void 0&&(_=!1),h.Guard.isDocumentNode(S)||h.Guard.isShadowRoot(S))throw new u.NotSupportedError;return y.node_clone(S,this,_)},C.prototype.adoptNode=function(S){if(h.Guard.isDocumentNode(S))throw new u.NotSupportedError;if(h.Guard.isShadowRoot(S))throw new u.HierarchyRequestError;return y.document_adopt(S,this),S},C.prototype.createAttribute=function(S){if(!y.xml_isName(S))throw new u.InvalidCharacterError;return this._type==="html"&&(S=S.toLowerCase()),y.create_attr(this,S)},C.prototype.createAttributeNS=function(S,_){var T=c(y.namespace_validateAndExtract(S,_),3),E=T[0],D=T[1],b=T[2],I=y.create_attr(this,b);return I._namespace=E,I._namespacePrefix=D,I},C.prototype.createEvent=function(S){return y.event_createLegacyEvent(S)},C.prototype.createRange=function(){var S=y.create_range();return S._start=[this,0],S._end=[this,0],S},C.prototype.createNodeIterator=function(S,_,T){_===void 0&&(_=f.WhatToShow.All),T===void 0&&(T=null);var E=y.create_nodeIterator(S,S,!0);return E._whatToShow=_,E._iteratorCollection=y.create_nodeList(S),g.isFunction(T)?(E._filter=y.create_nodeFilter(),E._filter.acceptNode=T):E._filter=T,E},C.prototype.createTreeWalker=function(S,_,T){_===void 0&&(_=f.WhatToShow.All),T===void 0&&(T=null);var E=y.create_treeWalker(S,S);return E._whatToShow=_,g.isFunction(T)?(E._filter=y.create_nodeFilter(),E._filter.acceptNode=T):E._filter=T,E},C.prototype._getTheParent=function(S){return S._type==="load"?null:l.dom.window},C.prototype.getElementById=function(S){throw new Error("Mixin: NonElementParentNode not implemented.")},Object.defineProperty(C.prototype,"children",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"firstElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"lastElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(C.prototype,"childElementCount",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),C.prototype.prepend=function(){for(var S=[],_=0;_=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(v,y){var m=typeof Symbol=="function"&&v[Symbol.iterator];if(!m)return v;var w,x,C=m.call(v),S=[];try{for(;(y===void 0||y-- >0)&&!(w=C.next()).done;)S.push(w.value)}catch(_){x={error:_}}finally{try{w&&!w.done&&(m=C.return)&&m.call(C)}finally{if(x)throw x.error}}return S};Object.defineProperty(n,"__esModule",{value:!0});var l=i(2),f=i(34),u=i(9),d=i(7),h=i(0),g=i(12),p=function(v){function y(){var m=v.call(this)||this;return m._children=new Set,m._namespace=null,m._namespacePrefix=null,m._localName="",m._customElementState="undefined",m._customElementDefinition=null,m._is=null,m._shadowRoot=null,m._attributeList=h.create_namedNodeMap(m),m._attributeChangeSteps=[],m._name="",m._assignedSlot=null,m}return a(y,v),Object.defineProperty(y.prototype,"namespaceURI",{get:function(){return this._namespace},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"prefix",{get:function(){return this._namespacePrefix},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"localName",{get:function(){return this._localName},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"tagName",{get:function(){return this._htmlUppercasedQualifiedName},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"id",{get:function(){return h.element_getAnAttributeValue(this,"id")},set:function(m){h.element_setAnAttributeValue(this,"id",m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"className",{get:function(){return h.element_getAnAttributeValue(this,"class")},set:function(m){h.element_setAnAttributeValue(this,"class",m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"classList",{get:function(){var m=h.element_getAnAttributeByName("class",this);return m===null&&(m=h.create_attr(this._nodeDocument,"class")),h.create_domTokenList(this,m)},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"slot",{get:function(){return h.element_getAnAttributeValue(this,"slot")},set:function(m){h.element_setAnAttributeValue(this,"slot",m)},enumerable:!0,configurable:!0}),y.prototype.hasAttributes=function(){return this._attributeList.length!==0},Object.defineProperty(y.prototype,"attributes",{get:function(){return this._attributeList},enumerable:!0,configurable:!0}),y.prototype.getAttributeNames=function(){var m,w,x=[];try{for(var C=s(this._attributeList),S=C.next();!S.done;S=C.next()){var _=S.value;x.push(_._qualifiedName)}}catch(T){m={error:T}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x},y.prototype.getAttribute=function(m){var w=h.element_getAnAttributeByName(m,this);return w?w._value:null},y.prototype.getAttributeNS=function(m,w){var x=h.element_getAnAttributeByNamespaceAndLocalName(m,w,this);return x?x._value:null},y.prototype.setAttribute=function(m,w){if(!h.xml_isName(m))throw new u.InvalidCharacterError;this._namespace===d.namespace.HTML&&this._nodeDocument._type==="html"&&(m=m.toLowerCase());for(var x=null,C=0;C=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(2),l=i(71),f=i(0),u=i(12),d=function(h){function g(p){p===void 0&&(p="");var v=h.call(this,p)||this;return v._name="",v._assignedSlot=null,v}return a(g,h),Object.defineProperty(g.prototype,"wholeText",{get:function(){var p,v,y="";try{for(var m=s(f.text_contiguousTextNodes(this,!0)),w=m.next();!w.done;w=m.next())y+=w.value._data}catch(x){p={error:x}}finally{try{w&&!w.done&&(v=m.return)&&v.call(m)}finally{if(p)throw p.error}}return y},enumerable:!0,configurable:!0}),g.prototype.splitText=function(p){return f.text_split(this,p)},Object.defineProperty(g.prototype,"assignedSlot",{get:function(){throw new Error("Mixin: Slotable not implemented.")},enumerable:!0,configurable:!0}),g._create=function(p,v){v===void 0&&(v="");var y=new g(v);return y._nodeDocument=p,y},g}(l.CharacterDataImpl);n.TextImpl=d,u.idl_defineConst(d.prototype,"_nodeType",c.NodeType.Text)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(){}return Object.defineProperty(a.prototype,"_startNode",{get:function(){return this._start[0]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_startOffset",{get:function(){return this._start[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_endNode",{get:function(){return this._end[0]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_endOffset",{get:function(){return this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"_collapsed",{get:function(){return this._start[0]===this._end[0]&&this._start[1]===this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"startContainer",{get:function(){return this._startNode},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"startOffset",{get:function(){return this._startOffset},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"endContainer",{get:function(){return this._endNode},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"endOffset",{get:function(){return this._endOffset},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"collapsed",{get:function(){return this._collapsed},enumerable:!0,configurable:!0}),a}();n.AbstractRangeImpl=o},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=function(){function s(c){this._activeFlag=!1,this._root=c,this._whatToShow=o.WhatToShow.All,this._filter=null}return Object.defineProperty(s.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"whatToShow",{get:function(){return this._whatToShow},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"filter",{get:function(){return this._filter},enumerable:!0,configurable:!0}),s}();n.TraverserImpl=a},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(0),s=i(12),c=function(){function l(f,u){this._target=null,this._relatedTarget=null,this._touchTargetList=[],this._path=[],this._currentTarget=null,this._eventPhase=o.EventPhase.None,this._stopPropagationFlag=!1,this._stopImmediatePropagationFlag=!1,this._canceledFlag=!1,this._inPassiveListenerFlag=!1,this._composedFlag=!1,this._initializedFlag=!1,this._dispatchFlag=!1,this._isTrusted=!1,this._bubbles=!1,this._cancelable=!1,this._type=f,u&&(this._bubbles=u.bubbles||!1,this._cancelable=u.cancelable||!1,this._composedFlag=u.composed||!1),this._initializedFlag=!0,this._timeStamp=new Date().getTime()}return Object.defineProperty(l.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"srcElement",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"currentTarget",{get:function(){return this._currentTarget},enumerable:!0,configurable:!0}),l.prototype.composedPath=function(){var f=[],u=this._path;if(u.length===0)return f;var d=this._currentTarget;if(d===null)throw new Error("Event currentTarget is null.");f.push(d);for(var h=0,g=0,p=u.length-1;p>=0;){if(u[p].rootOfClosedTree&&g++,u[p].invocationTarget===d){h=p;break}u[p].slotInClosedTree&&g--,p--}var v=g,y=g;for(p=h-1;p>=0;)u[p].rootOfClosedTree&&v++,v<=y&&f.unshift(u[p].invocationTarget),u[p].slotInClosedTree&&--v0)&&!(x=S.next()).done;)_.push(x.value)}catch(T){C={error:T}}finally{try{x&&!x.done&&(w=S.return)&&w.call(S)}finally{if(C)throw C.error}}return _},a=this&&this.__values||function(y){var m=typeof Symbol=="function"&&Symbol.iterator,w=m&&y[m],x=0;if(w)return w.call(y);if(y&&typeof y.length=="number")return{next:function(){return y&&x>=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=i(6),c=i(3),l=i(1),f=i(99),u=i(73),d=i(17),h=i(173),g=i(30),p=i(52),v=i(37);n.document_elementInterface=function(y,m){return f.ElementImpl},n.document_internalCreateElementNS=function(y,m,w,x){var C=o(h.namespace_validateAndExtract(m,w),3),S=C[0],_=C[1],T=C[2],E=null;return x!==void 0&&(E=l.isString(x)?x:x.is),p.element_createAnElement(y,T,S,_,E,!0)},n.document_adopt=function(y,m){var w,x;if(y._nodeDocument!==m||y._parent!==null){var C=y._nodeDocument;if(y._parent&&v.mutation_remove(y,y._parent),m!==C)for(var S=d.tree_getFirstDescendantNode(y,!0,!0);S!==null;){if(S._nodeDocument=m,c.Guard.isElementNode(S))try{for(var _=(w=void 0,a(S._attributeList._asArray())),T=_.next();!T.done;T=_.next())T.value._nodeDocument=m}catch(E){w={error:E}}finally{try{T&&!T.done&&(x=_.return)&&x.call(_)}finally{if(w)throw w.error}}s.dom.features.customElements&&c.Guard.isElementNode(S)&&S._customElementState==="custom"&&u.customElement_enqueueACustomElementCallbackReaction(S,"adoptedCallback",[C,m]),s.dom.features.steps&&g.dom_runAdoptingSteps(S,C),S=d.tree_getNextDescendantNode(y,S,!0,!0)}}}},function(r,n,i){var o=this&&this.__values||function(d){var h=typeof Symbol=="function"&&Symbol.iterator,g=h&&d[h],p=0;if(g)return g.call(d);if(d&&typeof d.length=="number")return{next:function(){return d&&p>=d.length&&(d=void 0),{value:d&&d[p++],done:!d}}};throw new TypeError(h?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(9),l=i(17),f=i(51),u=i(30);n.characterData_replaceData=function(d,h,g,p){var v,y,m=l.tree_nodeLength(d);if(h>m)throw new c.IndexSizeError("Offset exceeds character data length. Offset: "+h+", Length: "+m+", Node is "+d.nodeName+".");h+g>m&&(g=m-h),a.dom.features.mutationObservers&&f.observer_queueMutationRecord("characterData",d,null,null,d._data,[],[],null,null);var w=d._data.substring(0,h)+p+d._data.substring(h+g);d._data=w;try{for(var x=o(a.dom.rangeList),C=x.next();!C.done;C=x.next()){var S=C.value;S._start[0]===d&&S._start[1]>h&&S._start[1]<=h+g&&(S._start[1]=h),S._end[0]===d&&S._end[1]>h&&S._end[1]<=h+g&&(S._end[1]=h),S._start[0]===d&&S._start[1]>h+g&&(S._start[1]+=p.length-g),S._end[0]===d&&S._end[1]>h+g&&(S._end[1]+=p.length-g)}}catch(_){v={error:_}}finally{try{C&&!C.done&&(y=x.return)&&y.call(x)}finally{if(v)throw v.error}}a.dom.features.steps&&s.Guard.isTextNode(d)&&d._parent!==null&&u.dom_runChildTextContentChangeSteps(d._parent)},n.characterData_substringData=function(d,h,g){var p=l.tree_nodeLength(d);if(h>p)throw new c.IndexSizeError("Offset exceeds character data length. Offset: "+h+", Length: "+p+", Node is "+d.nodeName+".");return h+g>p?d._data.substr(h):d._data.substr(h,g)}},function(r,n,i){var o=this&&this.__read||function(u,d){var h=typeof Symbol=="function"&&u[Symbol.iterator];if(!h)return u;var g,p,v=h.call(u),y=[];try{for(;(d===void 0||d-- >0)&&!(g=v.next()).done;)y.push(g.value)}catch(m){p={error:m}}finally{try{g&&!g.done&&(h=v.return)&&h.call(v)}finally{if(p)throw p.error}}return y},a=this&&this.__spread||function(){for(var u=[],d=0;d=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(7);function l(u){var d=c.string.splitAStringOnASCIIWhitespace(u);return new Set(d)}function f(u){return a(u).join(" ")}n.orderedSet_parse=l,n.orderedSet_serialize=f,n.orderedSet_sanitize=function(u){return f(l(u))},n.orderedSet_contains=function(u,d,h){var g,p,v,y;try{for(var m=s(d),w=m.next();!w.done;w=m.next()){var x=w.value,C=!1;try{for(var S=(v=void 0,s(u)),_=S.next();!_.done;_=S.next()){var T=_.value;if(h){if(T===x){C=!0;break}}else if(T.toUpperCase()===x.toUpperCase()){C=!0;break}}}catch(E){v={error:E}}finally{try{_&&!_.done&&(y=S.return)&&y.call(S)}finally{if(v)throw v.error}}if(!C)return!1}}catch(E){g={error:E}}finally{try{w&&!w.done&&(p=m.return)&&p.call(m)}finally{if(g)throw g.error}}return!0}},function(r,n,i){i(179),Object.defineProperty(n,"__esModule",{value:!0});var o=i(262),a=i(110),s=i(1);a.dom.setFeatures(!1),n.createDocument=function(){var c=new o.DOMImplementation().createDocument(null,"root",null);return c.documentElement&&c.removeChild(c.documentElement),c},n.sanitizeInput=function(c,l){if(c==null)return c;if(l===void 0)return c+"";var f="";c+="";for(var u=0;u=32&&d<=55295||d>=57344&&d<=65533)f+=c.charAt(u);else if(d>=55296&&d<=56319&&u=56320&&h<=57343?(d=1024*(d-55296)+h-56320+65536,f+=String.fromCodePoint(d),u++):f+=s.isString(l)?l:l(c.charAt(u),u,c)}else f+=s.isString(l)?l:l(c.charAt(u),u,c)}return f}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(1),a=i(153);n.AbortController=a.AbortControllerImpl;var s=i(154);n.AbortSignal=s.AbortSignalImpl;var c=i(102);n.AbstractRange=c.AbstractRangeImpl;var l=i(157);n.Attr=l.AttrImpl;var f=i(158);n.CDATASection=f.CDATASectionImpl;var u=i(71);n.CharacterData=u.CharacterDataImpl;var d=i(263),h=i(159);n.Comment=h.CommentImpl;var g=i(171);n.CustomEvent=g.CustomEventImpl;var p=i(100);n.DocumentFragment=p.DocumentFragmentImpl;var v=i(98);n.Document=v.DocumentImpl;var y=i(264),m=i(155);n.DocumentType=m.DocumentTypeImpl;var w=i(6);n.dom=w.dom;var x=i(148);n.DOMImplementation=x.DOMImplementationImpl;var C=i(170);n.DOMTokenList=C.DOMTokenListImpl;var S=i(99);n.Element=S.ElementImpl;var _=i(104);n.Event=_.EventImpl;var T=i(70);n.EventTarget=T.EventTargetImpl;var E=i(161);n.HTMLCollection=E.HTMLCollectionImpl;var D=i(265);n.MutationObserver=D.MutationObserverImpl;var b=i(169);n.MutationRecord=b.MutationRecordImpl;var I=i(164);n.NamedNodeMap=I.NamedNodeMapImpl;var P=i(168);n.NodeFilter=P.NodeFilterImpl;var M=i(34);n.Node=M.NodeImpl;var L=i(166);n.NodeIterator=L.NodeIteratorImpl;var V=i(162);n.NodeList=V.NodeListImpl;var G=i(163);n.NodeListStatic=G.NodeListStaticImpl;var A=i(266),k=i(267),F=i(268),j=i(160);n.ProcessingInstruction=j.ProcessingInstructionImpl;var Y=i(165);n.Range=Y.RangeImpl;var re=i(156);n.ShadowRoot=re.ShadowRootImpl;var ue=i(269),ce=i(270);n.StaticRange=ce.StaticRangeImpl;var pe=i(101);n.Text=pe.TextImpl;var Ee=i(103);n.Traverser=Ee.TraverserImpl;var Oe=i(167);n.TreeWalker=Oe.TreeWalkerImpl;var _e=i(149);n.Window=_e.WindowImpl;var B=i(151);n.XMLDocument=B.XMLDocumentImpl,o.applyMixin(S.ElementImpl,d.ChildNodeImpl),o.applyMixin(u.CharacterDataImpl,d.ChildNodeImpl),o.applyMixin(m.DocumentTypeImpl,d.ChildNodeImpl),o.applyMixin(v.DocumentImpl,y.DocumentOrShadowRootImpl),o.applyMixin(re.ShadowRootImpl,y.DocumentOrShadowRootImpl),o.applyMixin(S.ElementImpl,A.NonDocumentTypeChildNodeImpl),o.applyMixin(u.CharacterDataImpl,A.NonDocumentTypeChildNodeImpl),o.applyMixin(v.DocumentImpl,k.NonElementParentNodeImpl),o.applyMixin(p.DocumentFragmentImpl,k.NonElementParentNodeImpl),o.applyMixin(v.DocumentImpl,F.ParentNodeImpl),o.applyMixin(p.DocumentFragmentImpl,F.ParentNodeImpl),o.applyMixin(S.ElementImpl,F.ParentNodeImpl),o.applyMixin(pe.TextImpl,ue.SlotableImpl),o.applyMixin(S.ElementImpl,ue.SlotableImpl)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),function(o){o[o.EOF=0]="EOF",o[o.Declaration=1]="Declaration",o[o.DocType=2]="DocType",o[o.Element=3]="Element",o[o.Text=4]="Text",o[o.CDATA=5]="CDATA",o[o.PI=6]="PI",o[o.Comment=7]="Comment",o[o.ClosingTag=8]="ClosingTag"}(n.TokenType||(n.TokenType={}))},function(r,n,i){i(64),i(20),i(66);var o,a=this&&this.__extends||(o=function(l,f){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,d){u.__proto__=d}||function(u,d){for(var h in d)d.hasOwnProperty(h)&&(u[h]=d[h])})(l,f)},function(l,f){function u(){this.constructor=l}o(l,f),l.prototype=f===null?Object.create(f):(u.prototype=f.prototype,new u)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(1),c=function(l){function f(){return l!==null&&l.apply(this,arguments)||this}return a(f,l),f.prototype._parse=function(u,d){var h=this,g=this._builderOptions,p=null;return s.isFunction(d)?p=this.parse(u,d.apply(this)):s.isArray(d)||s.isSet(d)?s.forEachArray(d,function(v){return p=h.parse(u,v)},this):s.isMap(d)||s.isObject(d)?s.forEachObject(d,function(v,y){if(s.isFunction(y)&&(y=y.apply(h)),g.ignoreConverters||v.indexOf(g.convert.att)!==0)if(g.ignoreConverters||v.indexOf(g.convert.text)!==0)if(g.ignoreConverters||v.indexOf(g.convert.cdata)!==0)if(g.ignoreConverters||v.indexOf(g.convert.comment)!==0)if(g.ignoreConverters||v.indexOf(g.convert.ins)!==0){if(!((s.isArray(y)||s.isSet(y))&&s.isEmpty(y))){if((s.isMap(y)||s.isObject(y))&&s.isEmpty(y))p=h.element(u,void 0,h.sanitize(v))||p;else if(g.keepNullNodes||y!=null)if(s.isArray(y)||s.isSet(y))s.forEachArray(y,function(S){var _={};_[v]=S,p=h.parse(u,_)},h);else if(s.isMap(y)||s.isObject(y))(m=h.element(u,void 0,h.sanitize(v)))&&(p=m,h.parse(m,y));else if(y!=null&&y!==""){var m;(m=h.element(u,void 0,h.sanitize(v)))&&(p=m,h.text(m,h._decodeText(h.sanitize(y))))}else p=h.element(u,void 0,h.sanitize(v))||p}}else if(s.isString(y)){var w=y.indexOf(" "),x=w===-1?y:y.substr(0,w),C=w===-1?"":y.substr(w+1);p=h.instruction(u,h.sanitize(x),h.sanitize(C))||p}else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){var _=S.indexOf(" "),T=_===-1?S:S.substr(0,_),E=_===-1?"":S.substr(_+1);p=h.instruction(u,h.sanitize(T),h.sanitize(E))||p},h):s.forEachObject(y,function(S,_){return p=h.instruction(u,h.sanitize(S),h.sanitize(_))||p},h);else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){return p=h.comment(u,h.sanitize(S))||p},h):p=h.comment(u,h.sanitize(y))||p;else s.isArray(y)||s.isSet(y)?s.forEachArray(y,function(S){return p=h.cdata(u,h.sanitize(S))||p},h):p=h.cdata(u,h.sanitize(y))||p;else p=s.isMap(y)||s.isObject(y)?h.parse(u,y):h.text(u,h._decodeText(h.sanitize(y)))||p;else if(v===g.convert.att){if(s.isArray(y)||s.isSet(y))throw new Error("Invalid attribute: "+y.toString()+". "+u._debugInfo());s.forEachObject(y,function(S,_){p=h.attribute(u,void 0,h.sanitize(S),h._decodeAttributeValue(h.sanitize(_)))||p})}else p=h.attribute(u,void 0,h.sanitize(v.substr(g.convert.att.length)),h._decodeAttributeValue(h.sanitize(y)))||p},this):(g.keepNullNodes||d!=null)&&(p=this.text(u,this._decodeText(this.sanitize(d)))||p),p||u},f}(i(75).BaseReader);n.ObjectReader=c},function(r,n,i){var o=i(39);r.exports=new o({explicit:[i(286),i(287),i(288)]})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(a){this.level=0,this._builderOptions=a,this._writerOptions=a};n.BaseCBWriter=o},function(r,n,i){var o=i(16),a=i(8),s=i(116);r.exports=!o&&!a(function(){return Object.defineProperty(s("div"),"a",{get:function(){return 7}}).a!=7})},function(r,n,i){var o=i(11),a=i(13),s=o.document,c=a(s)&&a(s.createElement);r.exports=function(l){return c?s.createElement(l):{}}},function(r,n,i){var o=i(118),a=Function.toString;typeof o.inspectSource!="function"&&(o.inspectSource=function(s){return a.call(s)}),r.exports=o.inspectSource},function(r,n,i){var o=i(11),a=i(80),s=o["__core-js_shared__"]||a("__core-js_shared__",{});r.exports=s},function(r,n,i){var o=i(14),a=i(187),s=i(55),c=i(15);r.exports=function(l,f){for(var u=a(f),d=c.f,h=s.f,g=0;gh;)o(d,u=f[h++])&&(~s(g,u)||g.push(u));return g}},function(r,n,i){var o=i(24),a=i(26),s=i(83),c=function(l){return function(f,u,d){var h,g=o(f),p=a(g.length),v=s(d,p);if(l&&u!=u){for(;p>v;)if((h=g[v++])!=h)return!0}else for(;p>v;v++)if((l||v in g)&&g[v]===u)return l||v||0;return!l&&-1}};r.exports={includes:c(!0),indexOf:c(!1)}},function(r,n,i){var o=i(8),a=/#|\.prototype\./,s=function(d,h){var g=l[c(d)];return g==u||g!=f&&(typeof h=="function"?o(h):!!h)},c=s.normalize=function(d){return String(d).replace(a,".").toLowerCase()},l=s.data={},f=s.NATIVE="N",u=s.POLYFILL="P";r.exports=s},function(r,n,i){var o=i(86);r.exports=o&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},function(r,n,i){var o=i(5);n.f=o},function(r,n,i){var o=i(120),a=i(14),s=i(125),c=i(15).f;r.exports=function(l){var f=o.Symbol||(o.Symbol={});a(f,l)||c(f,l,{value:s.f(l)})}},function(r,n){r.exports=function(i){if(typeof i!="function")throw TypeError(String(i)+" is not a function");return i}},function(r,n,i){var o=i(13),a=i(59),s=i(5)("species");r.exports=function(c,l){var f;return a(c)&&(typeof(f=c.constructor)!="function"||f!==Array&&!a(f.prototype)?o(f)&&(f=f[s])===null&&(f=void 0):f=void 0),new(f===void 0?Array:f)(l===0?0:l)}},function(r,n,i){var o,a,s=i(11),c=i(193),l=s.process,f=l&&l.versions,u=f&&f.v8;u?a=(o=u.split("."))[0]+o[1]:c&&(!(o=c.match(/Edge\/(\d+)/))||o[1]>=74)&&(o=c.match(/Chrome\/(\d+)/))&&(a=o[1]),r.exports=a&&+a},function(r,n,i){var o=i(5),a=i(60),s=i(15),c=o("unscopables"),l=Array.prototype;l[c]==null&&s.f(l,c,{configurable:!0,value:a(null)}),r.exports=function(f){l[c][f]=!0}},function(r,n,i){var o,a,s,c=i(132),l=i(21),f=i(14),u=i(5),d=i(44),h=u("iterator"),g=!1;[].keys&&("next"in(s=[].keys())?(a=c(c(s)))!==Object.prototype&&(o=a):g=!0),o==null&&(o={}),d||f(o,h)||l(o,h,function(){return this}),r.exports={IteratorPrototype:o,BUGGY_SAFARI_ITERATORS:g}},function(r,n,i){var o=i(14),a=i(27),s=i(57),c=i(196),l=s("IE_PROTO"),f=Object.prototype;r.exports=c?Object.getPrototypeOf:function(u){return u=a(u),o(u,l)?u[l]:typeof u.constructor=="function"&&u instanceof u.constructor?u.constructor.prototype:u instanceof Object?f:null}},function(r,n,i){var o=i(18),a=i(197);r.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s,c=!1,l={};try{(s=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(l,[]),c=l instanceof Array}catch{}return function(f,u){return o(f),a(u),c?s.call(f,u):f.__proto__=u,f}}():void 0)},function(r,n,i){var o=i(56),a=i(15),s=i(40);r.exports=function(c,l,f){var u=o(l);u in c?a.f(c,u,s(0,f)):c[u]=f}},function(r,n,i){var o=i(90),a=i(42),s=i(5)("toStringTag"),c=a(function(){return arguments}())=="Arguments";r.exports=o?a:function(l){var f,u,d;return l===void 0?"Undefined":l===null?"Null":typeof(u=function(h,g){try{return h[g]}catch{}}(f=Object(l),s))=="string"?u:c?a(f):(d=a(f))=="Object"&&typeof f.callee=="function"?"Arguments":d}},function(r,n,i){var o=i(18);r.exports=function(){var a=o(this),s="";return a.global&&(s+="g"),a.ignoreCase&&(s+="i"),a.multiline&&(s+="m"),a.dotAll&&(s+="s"),a.unicode&&(s+="u"),a.sticky&&(s+="y"),s}},function(r,n,i){var o=i(47),a=i(35),s=function(c){return function(l,f){var u,d,h=String(a(l)),g=o(f),p=h.length;return g<0||g>=p?c?"":void 0:(u=h.charCodeAt(g))<55296||u>56319||g+1===p||(d=h.charCodeAt(g+1))<56320||d>57343?c?h.charAt(g):u:c?h.slice(g,g+2):d-56320+(u-55296<<10)+65536}};r.exports={codeAt:s(!1),charAt:s(!0)}},function(r,n,i){var o=i(4),a=i(27),s=i(61);o({target:"Object",stat:!0,forced:i(8)(function(){s(1)})},{keys:function(c){return s(a(c))}})},function(r,n,i){var o=i(4),a=i(11),s=i(123),c=i(25),l=i(140),f=i(141),u=i(142),d=i(13),h=i(8),g=i(208),p=i(62),v=i(209);r.exports=function(y,m,w){var x=y.indexOf("Map")!==-1,C=y.indexOf("Weak")!==-1,S=x?"set":"add",_=a[y],T=_&&_.prototype,E=_,D={},b=function(G){var A=T[G];c(T,G,G=="add"?function(k){return A.call(this,k===0?0:k),this}:G=="delete"?function(k){return!(C&&!d(k))&&A.call(this,k===0?0:k)}:G=="get"?function(k){return C&&!d(k)?void 0:A.call(this,k===0?0:k)}:G=="has"?function(k){return!(C&&!d(k))&&A.call(this,k===0?0:k)}:function(k,F){return A.call(this,k===0?0:k,F),this})};if(s(y,typeof _!="function"||!(C||T.forEach&&!h(function(){new _().entries().next()}))))E=w.getConstructor(m,y,x,S),l.REQUIRED=!0;else if(s(y,!0)){var I=new E,P=I[S](C?{}:-0,1)!=I,M=h(function(){I.has(1)}),L=g(function(G){new _(G)}),V=!C&&h(function(){for(var G=new _,A=5;A--;)G[S](A,A);return!G.has(-0)});L||((E=m(function(G,A){u(G,E,y);var k=v(new _,G,E);return A!=null&&f(A,k[S],k,x),k})).prototype=T,T.constructor=E),(M||V)&&(b("delete"),b("has"),x&&b("get")),(V||P)&&b(S),C&&T.clear&&delete T.clear}return D[y]=E,o({global:!0,forced:E!=_},D),p(E,y),C||w.setStrong(E,y,x),E}},function(r,n,i){var o=i(45),a=i(13),s=i(14),c=i(15).f,l=i(58),f=i(204),u=l("meta"),d=0,h=Object.isExtensible||function(){return!0},g=function(v){c(v,u,{value:{objectID:"O"+ ++d,weakData:{}}})},p=r.exports={REQUIRED:!1,fastKey:function(v,y){if(!a(v))return typeof v=="symbol"?v:(typeof v=="string"?"S":"P")+v;if(!s(v,u)){if(!h(v))return"F";if(!y)return"E";g(v)}return v[u].objectID},getWeakData:function(v,y){if(!s(v,u)){if(!h(v))return!0;if(!y)return!1;g(v)}return v[u].weakData},onFreeze:function(v){return f&&p.REQUIRED&&h(v)&&!s(v,u)&&g(v),v}};o[u]=!0},function(r,n,i){var o=i(18),a=i(205),s=i(26),c=i(87),l=i(206),f=i(207),u=function(d,h){this.stopped=d,this.result=h};(r.exports=function(d,h,g,p,v){var y,m,w,x,C,S,_,T=c(h,g,p?2:1);if(v)y=d;else{if(typeof(m=l(d))!="function")throw TypeError("Target is not iterable");if(a(m)){for(w=0,x=s(d.length);x>w;w++)if((C=p?T(o(_=d[w])[0],_[1]):T(d[w]))&&C instanceof u)return C;return new u(!1)}y=m.call(d)}for(S=y.next;!(_=S.call(y)).done;)if(typeof(C=f(y,T,_.value,p))=="object"&&C&&C instanceof u)return C;return new u(!1)}).stop=function(d){return new u(!0,d)}},function(r,n){r.exports=function(i,o,a){if(!(i instanceof o))throw TypeError("Incorrect "+(a?a+" ":"")+"invocation");return i}},function(r,n,i){var o=i(15).f,a=i(60),s=i(210),c=i(87),l=i(142),f=i(141),u=i(88),d=i(211),h=i(16),g=i(140).fastKey,p=i(43),v=p.set,y=p.getterFor;r.exports={getConstructor:function(m,w,x,C){var S=m(function(D,b){l(D,S,w),v(D,{type:w,index:a(null),first:void 0,last:void 0,size:0}),h||(D.size=0),b!=null&&f(b,D[C],D,x)}),_=y(w),T=function(D,b,I){var P,M,L=_(D),V=E(D,b);return V?V.value=I:(L.last=V={index:M=g(b,!0),key:b,value:I,previous:P=L.last,next:void 0,removed:!1},L.first||(L.first=V),P&&(P.next=V),h?L.size++:D.size++,M!=="F"&&(L.index[M]=V)),D},E=function(D,b){var I,P=_(D),M=g(b);if(M!=="F")return P.index[M];for(I=P.first;I;I=I.next)if(I.key==b)return I};return s(S.prototype,{clear:function(){for(var D=_(this),b=D.index,I=D.first;I;)I.removed=!0,I.previous&&(I.previous=I.previous.next=void 0),delete b[I.index],I=I.next;D.first=D.last=void 0,h?D.size=0:this.size=0},delete:function(D){var b=_(this),I=E(this,D);if(I){var P=I.next,M=I.previous;delete b.index[I.index],I.removed=!0,M&&(M.next=P),P&&(P.previous=M),b.first==I&&(b.first=P),b.last==I&&(b.last=M),h?b.size--:this.size--}return!!I},forEach:function(D){for(var b,I=_(this),P=c(D,arguments.length>1?arguments[1]:void 0,3);b=b?b.next:I.first;)for(P(b.value,b.key,this);b&&b.removed;)b=b.previous},has:function(D){return!!E(this,D)}}),s(S.prototype,x?{get:function(D){var b=E(this,D);return b&&b.value},set:function(D,b){return T(this,D===0?0:D,b)}}:{add:function(D){return T(this,D=D===0?0:D,D)}}),h&&o(S.prototype,"size",{get:function(){return _(this).size}}),S},setStrong:function(m,w,x){var C=w+" Iterator",S=y(w),_=y(C);u(m,w,function(T,E){v(this,{type:C,target:T,state:S(T),kind:E,last:void 0})},function(){for(var T=_(this),E=T.kind,D=T.last;D&&D.removed;)D=D.previous;return T.target&&(T.last=D=D?D.next:T.state.first)?E=="keys"?{value:D.key,done:!1}:E=="values"?{value:D.value,done:!1}:{value:[D.key,D.value],done:!1}:(T.target=void 0,{value:void 0,done:!0})},x?"entries":"values",!x,!0),d(w)}}},function(r,n,i){var o,a=i(4),s=i(55).f,c=i(26),l=i(222),f=i(35),u=i(224),d=i(44),h="".endsWith,g=Math.min,p=u("endsWith");a({target:"String",proto:!0,forced:!!(d||p||(o=s(String.prototype,"endsWith"),!o||o.writable))&&!p},{endsWith:function(v){var y=String(f(this));l(v);var m=arguments.length>1?arguments[1]:void 0,w=c(y.length),x=m===void 0?w:g(c(m),w),C=String(v);return h?h.call(y,C,x):y.slice(x-C.length,x)===C}})},function(r,n,i){(function(o){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */var a=i(229),s=i(230),c=i(231);function l(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function f(B,O){if(l()=l())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+l().toString(16)+" bytes");return 0|B}function y(B,O){if(u.isBuffer(B))return B.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(B)||B instanceof ArrayBuffer))return B.byteLength;typeof B!="string"&&(B=""+B);var z=B.length;if(z===0)return 0;for(var W=!1;;)switch(O){case"ascii":case"latin1":case"binary":return z;case"utf8":case"utf-8":case void 0:return Ee(B).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*z;case"hex":return z>>>1;case"base64":return Oe(B).length;default:if(W)return Ee(B).length;O=(""+O).toLowerCase(),W=!0}}function m(B,O,z){var W=!1;if((O===void 0||O<0)&&(O=0),O>this.length||((z===void 0||z>this.length)&&(z=this.length),z<=0)||(z>>>=0)<=(O>>>=0))return"";for(B||(B="utf8");;)switch(B){case"hex":return V(this,O,z);case"utf8":case"utf-8":return P(this,O,z);case"ascii":return M(this,O,z);case"latin1":case"binary":return L(this,O,z);case"base64":return I(this,O,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,O,z);default:if(W)throw new TypeError("Unknown encoding: "+B);B=(B+"").toLowerCase(),W=!0}}function w(B,O,z){var W=B[O];B[O]=B[z],B[z]=W}function x(B,O,z,W,K){if(B.length===0)return-1;if(typeof z=="string"?(W=z,z=0):z>2147483647?z=2147483647:z<-2147483648&&(z=-2147483648),z=+z,isNaN(z)&&(z=K?0:B.length-1),z<0&&(z=B.length+z),z>=B.length){if(K)return-1;z=B.length-1}else if(z<0){if(!K)return-1;z=0}if(typeof O=="string"&&(O=u.from(O,W)),u.isBuffer(O))return O.length===0?-1:C(B,O,z,W,K);if(typeof O=="number")return O&=255,u.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?K?Uint8Array.prototype.indexOf.call(B,O,z):Uint8Array.prototype.lastIndexOf.call(B,O,z):C(B,[O],z,W,K);throw new TypeError("val must be string, number or Buffer")}function C(B,O,z,W,K){var Z,ee=1,xe=B.length,De=O.length;if(W!==void 0&&((W=String(W).toLowerCase())==="ucs2"||W==="ucs-2"||W==="utf16le"||W==="utf-16le")){if(B.length<2||O.length<2)return-1;ee=2,xe/=2,De/=2,z/=2}function Ne(we,se){return ee===1?we[se]:we.readUInt16BE(se*ee)}if(K){var ze=-1;for(Z=z;Zxe&&(z=xe-De),Z=z;Z>=0;Z--){for(var ie=!0,ae=0;aeK&&(W=K):W=K;var Z=O.length;if(Z%2!=0)throw new TypeError("Invalid hex string");W>Z/2&&(W=Z/2);for(var ee=0;ee>8,De=ee%256,Ne.push(De),Ne.push(xe);return Ne}(O,B.length-z),B,z,W)}function I(B,O,z){return O===0&&z===B.length?a.fromByteArray(B):a.fromByteArray(B.slice(O,z))}function P(B,O,z){z=Math.min(B.length,z);for(var W=[],K=O;K239?4:Ne>223?3:Ne>191?2:1;if(K+ie<=z)switch(ie){case 1:Ne<128&&(ze=Ne);break;case 2:(192&(Z=B[K+1]))==128&&(De=(31&Ne)<<6|63&Z)>127&&(ze=De);break;case 3:Z=B[K+1],ee=B[K+2],(192&Z)==128&&(192&ee)==128&&(De=(15&Ne)<<12|(63&Z)<<6|63&ee)>2047&&(De<55296||De>57343)&&(ze=De);break;case 4:Z=B[K+1],ee=B[K+2],xe=B[K+3],(192&Z)==128&&(192&ee)==128&&(192&xe)==128&&(De=(15&Ne)<<18|(63&Z)<<12|(63&ee)<<6|63&xe)>65535&&De<1114112&&(ze=De)}ze===null?(ze=65533,ie=1):ze>65535&&(ze-=65536,W.push(ze>>>10&1023|55296),ze=56320|1023&ze),W.push(ze),K+=ie}return function(ae){var we=ae.length;if(we<=4096)return String.fromCharCode.apply(String,ae);for(var se="",ge=0;ge0&&(B=this.toString("hex",0,O).match(/.{2}/g).join(" "),this.length>O&&(B+=" ... ")),""},u.prototype.compare=function(B,O,z,W,K){if(!u.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(O===void 0&&(O=0),z===void 0&&(z=B?B.length:0),W===void 0&&(W=0),K===void 0&&(K=this.length),O<0||z>B.length||W<0||K>this.length)throw new RangeError("out of range index");if(W>=K&&O>=z)return 0;if(W>=K)return-1;if(O>=z)return 1;if(this===B)return 0;for(var Z=(K>>>=0)-(W>>>=0),ee=(z>>>=0)-(O>>>=0),xe=Math.min(Z,ee),De=this.slice(W,K),Ne=B.slice(O,z),ze=0;zeK)&&(z=K),B.length>0&&(z<0||O<0)||O>this.length)throw new RangeError("Attempt to write outside buffer bounds");W||(W="utf8");for(var Z=!1;;)switch(W){case"hex":return S(this,B,O,z);case"utf8":case"utf-8":return _(this,B,O,z);case"ascii":return T(this,B,O,z);case"latin1":case"binary":return E(this,B,O,z);case"base64":return D(this,B,O,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,B,O,z);default:if(Z)throw new TypeError("Unknown encoding: "+W);W=(""+W).toLowerCase(),Z=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(B,O,z){var W="";z=Math.min(B.length,z);for(var K=O;KW)&&(z=W);for(var K="",Z=O;Zz)throw new RangeError("Trying to access beyond buffer length")}function k(B,O,z,W,K,Z){if(!u.isBuffer(B))throw new TypeError('"buffer" argument must be a Buffer instance');if(O>K||OB.length)throw new RangeError("Index out of range")}function F(B,O,z,W){O<0&&(O=65535+O+1);for(var K=0,Z=Math.min(B.length-z,2);K>>8*(W?K:1-K)}function j(B,O,z,W){O<0&&(O=4294967295+O+1);for(var K=0,Z=Math.min(B.length-z,4);K>>8*(W?K:3-K)&255}function Y(B,O,z,W,K,Z){if(z+W>B.length)throw new RangeError("Index out of range");if(z<0)throw new RangeError("Index out of range")}function re(B,O,z,W,K){return K||Y(B,0,z,4),s.write(B,O,z,W,23,4),z+4}function ue(B,O,z,W,K){return K||Y(B,0,z,8),s.write(B,O,z,W,52,8),z+8}u.prototype.slice=function(B,O){var z,W=this.length;if((B=~~B)<0?(B+=W)<0&&(B=0):B>W&&(B=W),(O=O===void 0?W:~~O)<0?(O+=W)<0&&(O=0):O>W&&(O=W),O0&&(K*=256);)W+=this[B+--O]*K;return W},u.prototype.readUInt8=function(B,O){return O||A(B,1,this.length),this[B]},u.prototype.readUInt16LE=function(B,O){return O||A(B,2,this.length),this[B]|this[B+1]<<8},u.prototype.readUInt16BE=function(B,O){return O||A(B,2,this.length),this[B]<<8|this[B+1]},u.prototype.readUInt32LE=function(B,O){return O||A(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},u.prototype.readUInt32BE=function(B,O){return O||A(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},u.prototype.readIntLE=function(B,O,z){B|=0,O|=0,z||A(B,O,this.length);for(var W=this[B],K=1,Z=0;++Z=(K*=128)&&(W-=Math.pow(2,8*O)),W},u.prototype.readIntBE=function(B,O,z){B|=0,O|=0,z||A(B,O,this.length);for(var W=O,K=1,Z=this[B+--W];W>0&&(K*=256);)Z+=this[B+--W]*K;return Z>=(K*=128)&&(Z-=Math.pow(2,8*O)),Z},u.prototype.readInt8=function(B,O){return O||A(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},u.prototype.readInt16LE=function(B,O){O||A(B,2,this.length);var z=this[B]|this[B+1]<<8;return 32768&z?4294901760|z:z},u.prototype.readInt16BE=function(B,O){O||A(B,2,this.length);var z=this[B+1]|this[B]<<8;return 32768&z?4294901760|z:z},u.prototype.readInt32LE=function(B,O){return O||A(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},u.prototype.readInt32BE=function(B,O){return O||A(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},u.prototype.readFloatLE=function(B,O){return O||A(B,4,this.length),s.read(this,B,!0,23,4)},u.prototype.readFloatBE=function(B,O){return O||A(B,4,this.length),s.read(this,B,!1,23,4)},u.prototype.readDoubleLE=function(B,O){return O||A(B,8,this.length),s.read(this,B,!0,52,8)},u.prototype.readDoubleBE=function(B,O){return O||A(B,8,this.length),s.read(this,B,!1,52,8)},u.prototype.writeUIntLE=function(B,O,z,W){B=+B,O|=0,z|=0,W||k(this,B,O,z,Math.pow(2,8*z)-1,0);var K=1,Z=0;for(this[O]=255&B;++Z=0&&(Z*=256);)this[O+K]=B/Z&255;return O+z},u.prototype.writeUInt8=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,1,255,0),u.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[O]=255&B,O+1},u.prototype.writeUInt16LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8):F(this,B,O,!0),O+2},u.prototype.writeUInt16BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>8,this[O+1]=255&B):F(this,B,O,!1),O+2},u.prototype.writeUInt32LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[O+3]=B>>>24,this[O+2]=B>>>16,this[O+1]=B>>>8,this[O]=255&B):j(this,B,O,!0),O+4},u.prototype.writeUInt32BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>24,this[O+1]=B>>>16,this[O+2]=B>>>8,this[O+3]=255&B):j(this,B,O,!1),O+4},u.prototype.writeIntLE=function(B,O,z,W){if(B=+B,O|=0,!W){var K=Math.pow(2,8*z-1);k(this,B,O,z,K-1,-K)}var Z=0,ee=1,xe=0;for(this[O]=255&B;++Z>0)-xe&255;return O+z},u.prototype.writeIntBE=function(B,O,z,W){if(B=+B,O|=0,!W){var K=Math.pow(2,8*z-1);k(this,B,O,z,K-1,-K)}var Z=z-1,ee=1,xe=0;for(this[O+Z]=255&B;--Z>=0&&(ee*=256);)B<0&&xe===0&&this[O+Z+1]!==0&&(xe=1),this[O+Z]=(B/ee>>0)-xe&255;return O+z},u.prototype.writeInt8=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,1,127,-128),u.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[O]=255&B,O+1},u.prototype.writeInt16LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8):F(this,B,O,!0),O+2},u.prototype.writeInt16BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>8,this[O+1]=255&B):F(this,B,O,!1),O+2},u.prototype.writeInt32LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8,this[O+2]=B>>>16,this[O+3]=B>>>24):j(this,B,O,!0),O+4},u.prototype.writeInt32BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>24,this[O+1]=B>>>16,this[O+2]=B>>>8,this[O+3]=255&B):j(this,B,O,!1),O+4},u.prototype.writeFloatLE=function(B,O,z){return re(this,B,O,!0,z)},u.prototype.writeFloatBE=function(B,O,z){return re(this,B,O,!1,z)},u.prototype.writeDoubleLE=function(B,O,z){return ue(this,B,O,!0,z)},u.prototype.writeDoubleBE=function(B,O,z){return ue(this,B,O,!1,z)},u.prototype.copy=function(B,O,z,W){if(z||(z=0),W||W===0||(W=this.length),O>=B.length&&(O=B.length),O||(O=0),W>0&&W=this.length)throw new RangeError("sourceStart out of bounds");if(W<0)throw new RangeError("sourceEnd out of bounds");W>this.length&&(W=this.length),B.length-O=0;--K)B[K+O]=this[K+z];else if(Z<1e3||!u.TYPED_ARRAY_SUPPORT)for(K=0;K>>=0,z=z===void 0?this.length:z>>>0,B||(B=0),typeof B=="number")for(Z=O;Z55295&&z<57344){if(!K){if(z>56319){(O-=3)>-1&&Z.push(239,191,189);continue}if(ee+1===W){(O-=3)>-1&&Z.push(239,191,189);continue}K=z;continue}if(z<56320){(O-=3)>-1&&Z.push(239,191,189),K=z;continue}z=65536+(K-55296<<10|z-56320)}else K&&(O-=3)>-1&&Z.push(239,191,189);if(K=null,z<128){if((O-=1)<0)break;Z.push(z)}else if(z<2048){if((O-=2)<0)break;Z.push(z>>6|192,63&z|128)}else if(z<65536){if((O-=3)<0)break;Z.push(z>>12|224,z>>6&63|128,63&z|128)}else{if(!(z<1114112))throw new Error("Invalid code point");if((O-=4)<0)break;Z.push(z>>18|240,z>>12&63|128,z>>6&63|128,63&z|128)}}return Z}function Oe(B){return a.toByteArray(function(O){if((O=function(z){return z.trim?z.trim():z.replace(/^\s+|\s+$/g,"")}(O).replace(ce,"")).length<2)return"";for(;O.length%4!=0;)O+="=";return O}(B))}function Se(B,O,z,W){for(var K=0;K=O.length||K>=B.length);++K)O[K+z]=B[K];return K}}).call(this,i(78))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),n.isASCIIByte=function(o){return o>=0&&o<=127}},function(r,n,i){var o=this&&this.__read||function(s,c){var l=typeof Symbol=="function"&&s[Symbol.iterator];if(!l)return s;var f,u,d=l.call(s),h=[];try{for(;(c===void 0||c-- >0)&&!(f=d.next()).done;)h.push(f.value)}catch(g){u={error:g}}finally{try{f&&!f.done&&(l=d.return)&&l.call(d)}finally{if(u)throw u.error}}return h},a=this&&this.__spread||function(){for(var s=[],c=0;c=65&&l<=90&&(s[c]=l+32)}},n.byteUppercase=function(s){for(var c=0;c=97&&l<=122&&(s[c]=l-32)}},n.byteCaseInsensitiveMatch=function(s,c){if(s.length!==c.length)return!1;for(var l=0;l=65&&f<=90&&(f+=32),u>=65&&u<=90&&(u+=32),f!==u)return!1}return!0},n.startsWith=function(s,c){for(var l=0;;){if(l>=s.length)return!1;if(l>=c.length)return!0;if(s[l]!==c[l])return!1;l++}},n.byteLessThan=function(s,c){for(var l=0;;){if(l>=s.length)return!1;if(l>=c.length)return!0;var f=s[l],u=c[l];if(fu)return!1;l++}},n.isomorphicDecode=function(s){return String.fromCodePoint.apply(String,a(s))}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(6),a=i(7),s=i(0),c=i(12),l=function(){function f(u){this._associatedDocument=u||o.dom.window.document}return f.prototype.createDocumentType=function(u,d,h){return s.namespace_validate(u),s.create_documentType(this._associatedDocument,u,d,h)},f.prototype.createDocument=function(u,d,h){h===void 0&&(h=null);var g=s.create_xmlDocument(),p=null;return d&&(p=s.document_internalCreateElementNS(g,u,d)),h&&g.appendChild(h),p&&g.appendChild(p),g._origin=this._associatedDocument._origin,u===a.namespace.HTML?g._contentType="application/xhtml+xml":u===a.namespace.SVG?g._contentType="image/svg+xml":g._contentType="application/xml",g},f.prototype.createHTMLDocument=function(u){var d=s.create_document();d._type="html",d._contentType="text/html",d.appendChild(s.create_documentType(d,"html","",""));var h=s.element_createAnElement(d,"html",a.namespace.HTML);d.appendChild(h);var g=s.element_createAnElement(d,"head",a.namespace.HTML);if(h.appendChild(g),u!==void 0){var p=s.element_createAnElement(d,"title",a.namespace.HTML);g.appendChild(p);var v=s.create_text(d,u);p.appendChild(v)}var y=s.element_createAnElement(d,"body",a.namespace.HTML);return h.appendChild(y),d._origin=this._associatedDocument._origin,d},f.prototype.hasFeature=function(){return!0},f._create=function(u){return new f(u)},f}();n.DOMImplementationImpl=l,c.idl_defineConst(l.prototype,"_ID","@oozcitak/dom")},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(70),c=i(1),l=i(0),f=function(u){function d(){var h=u.call(this)||this;return h._signalSlots=new Set,h._mutationObserverMicrotaskQueued=!1,h._mutationObservers=new Set,h._iteratorList=new c.FixedSizeSet,h._associatedDocument=l.create_document(),h}return a(d,u),Object.defineProperty(d.prototype,"document",{get:function(){return this._associatedDocument},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"event",{get:function(){return this._currentEvent},enumerable:!0,configurable:!0}),d._create=function(){return new d},d}(s.EventTargetImpl);n.WindowImpl=f},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=function(){function s(){}return s.isNode=function(c){return!!c&&c._nodeType!==void 0},s.isDocumentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Document},s.isDocumentTypeNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.DocumentType},s.isDocumentFragmentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.DocumentFragment},s.isAttrNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Attribute},s.isCharacterDataNode=function(c){if(!s.isNode(c))return!1;var l=c._nodeType;return l===o.NodeType.Text||l===o.NodeType.ProcessingInstruction||l===o.NodeType.Comment||l===o.NodeType.CData},s.isTextNode=function(c){return s.isNode(c)&&(c._nodeType===o.NodeType.Text||c._nodeType===o.NodeType.CData)},s.isExclusiveTextNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Text},s.isCDATASectionNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.CData},s.isCommentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Comment},s.isProcessingInstructionNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.ProcessingInstruction},s.isElementNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Element},s.isCustomElementNode=function(c){return s.isElementNode(c)&&c._customElementState==="custom"},s.isShadowRoot=function(c){return!!c&&c.host!==void 0},s.isMouseEvent=function(c){return!!c&&c.screenX!==void 0&&c.screenY!=null},s.isSlotable=function(c){return!!c&&c._name!==void 0&&c._assignedSlot!==void 0&&(s.isTextNode(c)||s.isElementNode(c))},s.isSlot=function(c){return!!c&&c._name!==void 0&&c._assignedNodes!==void 0&&s.isElementNode(c)},s.isWindow=function(c){return!!c&&c.navigator!==void 0},s.isEventListener=function(c){return!!c&&c.handleEvent!==void 0},s.isRegisteredObserver=function(c){return!!c&&c.observer!==void 0&&c.options!==void 0},s.isTransientRegisteredObserver=function(c){return!!c&&c.source!==void 0&&s.isRegisteredObserver(c)},s}();n.Guard=a},function(r,n,i){var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(){return c.call(this)||this}return a(l,c),l}(i(98).DocumentImpl);n.XMLDocumentImpl=s},function(r,n,i){var o=this&&this.__values||function(W){var K=typeof Symbol=="function"&&Symbol.iterator,Z=K&&W[K],ee=0;if(Z)return Z.call(W);if(W&&typeof W.length=="number")return{next:function(){return W&&ee>=W.length&&(W=void 0),{value:W&&W[ee++],done:!W}}};throw new TypeError(K?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(W,K){var Z=typeof Symbol=="function"&&W[Symbol.iterator];if(!Z)return W;var ee,xe,De=Z.call(W),Ne=[];try{for(;(K===void 0||K-- >0)&&!(ee=De.next()).done;)Ne.push(ee.value)}catch(ze){xe={error:ze}}finally{try{ee&&!ee.done&&(Z=De.return)&&Z.call(De)}finally{if(xe)throw xe.error}}return Ne};Object.defineProperty(n,"__esModule",{value:!0});var s,c=i(1),l=i(243),f=i(7),u=i(244),d={ftp:21,file:null,http:80,https:443,ws:80,wss:443},h=/[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,g=/[ "<>`]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,p=/[ "<>`#?{}]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,v=/[ "<>`#?{}/:;=@\[\]\\\^\|]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,y=/[0-9A-Za-z!\$&-\/:;=\?@_~\xA0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uD83E\uD840-\uD87E\uD880-\uD8BE\uD8C0-\uD8FE\uD900-\uD93E\uD940-\uD97E\uD980-\uD9BE\uD9C0-\uD9FE\uDA00-\uDA3E\uDA40-\uDA7E\uDA80-\uDABE\uDAC0-\uDAFE\uDB00-\uDB3E\uDB40-\uDB7E\uDB80-\uDBBE\uDBC0-\uDBFE][\uDC00-\uDFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDC00-\uDFFD]/,m=/[\0\t\f\r #%/:?@\[\\\]]/;function w(W){s!==void 0&&s.call(null,"Validation Error: "+W)}function x(){return{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null}}function C(W){return W in d}function S(W){return C(W.scheme)}function _(W){return d[W]||null}function T(W){return W.username!==""||W.password!==""}function E(W,K){var Z,ee;K===void 0&&(K=!1);var xe=W.scheme+":";if(W.host!==null?(xe+="//",T(W)&&(xe+=W.username,W.password!==""&&(xe+=":"+W.password),xe+="@"),xe+=D(W.host),W.port!==null&&(xe+=":"+W.port)):W.host===null&&W.scheme==="file"&&(xe+="//"),W._cannotBeABaseURLFlag)xe+=W.path[0];else try{for(var De=o(W.path),Ne=De.next();!Ne.done;Ne=De.next())xe+="/"+Ne.value}catch(ze){Z={error:ze}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}return W.query!==null&&(xe+="?"+W.query),K||W.fragment===null||(xe+="#"+W.fragment),xe}function D(W){return c.isNumber(W)?b(W):c.isArray(W)?"["+I(W)+"]":W}function b(W){for(var K="",Z=W,ee=1;ee<=4;ee++)K=(Z%256).toString()+K,ee!==4&&(K="."+K),Z=Math.floor(Z/256);return K}function I(W){for(var K="",Z=null,ee=-1,xe=0,De=0,Ne=0;Ne<8;Ne++)if(W[Ne]===0){xe=1;for(var ze=Ne+1;ze<8&&W[ze]===0;ze++)xe++;xe>De&&(De=xe,ee=Ne)}De>1&&(Z=ee);for(var ie=!1,ae=0;ae<8;ae++)ie&&W[ae]===0||(ie&&(ie=!1),Z!==ae?(K+=W[ae].toString(16),ae!==7&&(K+=":")):(K+=ae===0?"::":":",ie=!0));return K}function P(W,K,Z,ee,xe){var De,Ne,ze,ie;if(ee===void 0){ee={scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null};var ae=/^[\u0000-\u001F\u0020]+/,we=/[\u0000-\u001F\u0020]+$/;(ae.test(W)||we.test(W))&&w("Input string contains leading or trailing control characters or space."),W=(W=W.replace(ae,"")).replace(we,"")}var se=/[\u0009\u000A\u000D]/g;se.test(W)&&w("Input string contains tab or newline characters."),W=W.replace(se,"");var ge=xe===void 0?l.ParserState.SchemeStart:xe;K===void 0&&(K=null);for(var Fe=Z===void 0||Z==="replacement"||Z==="UTF-16BE"||Z==="UTF-16LE"?"UTF-8":Z,oe="",ht=!1,wt=!1,gt=!1,Ie=new c.StringWalker(W);;){switch(ge){case l.ParserState.SchemeStart:if(f.codePoint.ASCIIAlpha.test(Ie.c()))oe+=Ie.c().toLowerCase(),ge=l.ParserState.Scheme;else{if(xe!==void 0)return w("Invalid scheme start character."),null;ge=l.ParserState.NoScheme,Ie.pointer--}break;case l.ParserState.Scheme:if(f.codePoint.ASCIIAlphanumeric.test(Ie.c())||Ie.c()==="+"||Ie.c()==="-"||Ie.c()===".")oe+=Ie.c().toLowerCase();else{if(Ie.c()!==":"){if(xe===void 0){oe="",ge=l.ParserState.NoScheme,Ie.pointer=0;continue}return w("Invalid input string."),null}if(xe!==void 0&&(C(ee.scheme)&&!C(oe)||!C(ee.scheme)&&C(oe)||(T(ee)||ee.port!==null)&&oe==="file"||ee.scheme==="file"&&(ee.host===""||ee.host===null)))return ee;if(ee.scheme=oe,xe!==void 0)return ee.port===_(ee.scheme)&&(ee.port=null),ee;oe="",ee.scheme==="file"?(Ie.remaining().startsWith("//")||w("Invalid file URL scheme, '//' expected."),ge=l.ParserState.File):S(ee)&&K!==null&&K.scheme===ee.scheme?ge=l.ParserState.SpecialRelativeOrAuthority:S(ee)?ge=l.ParserState.SpecialAuthoritySlashes:Ie.remaining().startsWith("/")?(ge=l.ParserState.PathOrAuthority,Ie.pointer++):(ee._cannotBeABaseURLFlag=!0,ee.path.push(""),ge=l.ParserState.CannotBeABaseURLPath)}break;case l.ParserState.NoScheme:if(K===null||K._cannotBeABaseURLFlag&&Ie.c()!=="#")return w("Invalid input string."),null;K._cannotBeABaseURLFlag&&Ie.c()==="#"?(ee.scheme=K.scheme,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ee._cannotBeABaseURLFlag=!0,ge=l.ParserState.Fragment):K.scheme!=="file"?(ge=l.ParserState.Relative,Ie.pointer--):(ge=l.ParserState.File,Ie.pointer--);break;case l.ParserState.SpecialRelativeOrAuthority:Ie.c()==="/"&&Ie.remaining().startsWith("/")?(ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer++):(w("Invalid input string."),ge=l.ParserState.Relative,Ie.pointer--);break;case l.ParserState.PathOrAuthority:Ie.c()==="/"?ge=l.ParserState.Authority:(ge=l.ParserState.Path,Ie.pointer--);break;case l.ParserState.Relative:if(K===null)throw new Error("Invalid parser state. Base URL is null.");switch(ee.scheme=K.scheme,Ie.c()){case"":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query=K.query;break;case"/":ge=l.ParserState.RelativeSlash;break;case"?":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query="",ge=l.ParserState.Query;break;case"#":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ge=l.ParserState.Fragment;break;default:S(ee)&&Ie.c()==="\\"?(w("Invalid input string."),ge=l.ParserState.RelativeSlash):(ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.path.length!==0&&ee.path.splice(ee.path.length-1,1),ge=l.ParserState.Path,Ie.pointer--)}break;case l.ParserState.RelativeSlash:if(!S(ee)||Ie.c()!=="/"&&Ie.c()!=="\\")if(Ie.c()==="/")ge=l.ParserState.Authority;else{if(K===null)throw new Error("Invalid parser state. Base URL is null.");ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ge=l.ParserState.Path,Ie.pointer--}else Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.SpecialAuthorityIgnoreSlashes;break;case l.ParserState.SpecialAuthoritySlashes:Ie.c()==="/"&&Ie.remaining().startsWith("/")?(ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer++):(w("Expected '//'."),ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer--);break;case l.ParserState.SpecialAuthorityIgnoreSlashes:Ie.c()!=="/"&&Ie.c()!=="\\"?(ge=l.ParserState.Authority,Ie.pointer--):w("Unexpected '/' or '\\'.");break;case l.ParserState.Authority:if(Ie.c()==="@"){w("Unexpected '@'."),ht&&(oe="%40"+oe),ht=!0;try{for(var $e=(De=void 0,o(oe)),tt=$e.next();!tt.done;tt=$e.next()){var nt=tt.value;if(nt!==":"||gt){var dt=Se(nt,v);gt?ee.password+=dt:ee.username+=dt}else gt=!0}}catch(bn){De={error:bn}}finally{try{tt&&!tt.done&&(Ne=$e.return)&&Ne.call($e)}finally{if(De)throw De.error}}oe=""}else if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"){if(ht&&oe==="")return w("Invalid input string."),null;Ie.pointer-=oe.length+1,oe="",ge=l.ParserState.Host}else oe+=Ie.c();break;case l.ParserState.Host:case l.ParserState.Hostname:if(xe!==void 0&&ee.scheme==="file")Ie.pointer--,ge=l.ParserState.FileHost;else if(Ie.c()!==":"||wt)if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"){if(Ie.pointer--,S(ee)&&oe==="")return w("Invalid input string."),null;if(xe!==void 0&&oe===""&&(T(ee)||ee.port!==null))return w("Invalid input string."),ee;if((xt=F(oe,!S(ee)))===null)return null;if(ee.host=xt,oe="",ge=l.ParserState.PathStart,xe!==void 0)return ee}else Ie.c()==="["&&(wt=!0),Ie.c()==="]"&&(wt=!1),oe+=Ie.c();else{if(oe==="")return w("Invalid input string."),null;if((xt=F(oe,!S(ee)))===null)return null;if(ee.host=xt,oe="",ge=l.ParserState.Port,xe===l.ParserState.Hostname)return ee}break;case l.ParserState.Port:if(f.codePoint.ASCIIDigit.test(Ie.c()))oe+=Ie.c();else{if(!(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"||xe))return w("Invalid input string."),null;if(oe!==""&&oe!==""){var Lt=parseInt(oe,10);if(Lt>Math.pow(2,16)-1)return w("Invalid port number."),null;ee.port=Lt===_(ee.scheme)?null:Lt,oe=""}if(xe!==void 0)return ee;ge=l.ParserState.PathStart,Ie.pointer--}break;case l.ParserState.File:if(ee.scheme="file",Ie.c()==="/"||Ie.c()==="\\")Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.FileSlash;else if(K!==null&&K.scheme==="file")switch(Ie.c()){case"":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query=K.query;break;case"?":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query="",ge=l.ParserState.Query;break;case"#":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ge=l.ParserState.Fragment;break;default:k(Ie.substring())?w("Unexpected windows drive letter in input string."):(ee.host=K.host,ee.path=f.list.clone(K.path),V(ee)),ge=l.ParserState.Path,Ie.pointer--}else ge=l.ParserState.Path,Ie.pointer--;break;case l.ParserState.FileSlash:Ie.c()==="/"||Ie.c()==="\\"?(Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.FileHost):(K===null||K.scheme!=="file"||k(Ie.substring())||(G(K.path[0])?ee.path.push(K.path[0]):ee.host=K.host),ge=l.ParserState.Path,Ie.pointer--);break;case l.ParserState.FileHost:if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="\\"||Ie.c()==="?"||Ie.c()==="#")if(Ie.pointer--,xe===void 0&&A(oe))w("Unexpected windows drive letter in input string."),ge=l.ParserState.Path;else if(oe===""){if(ee.host="",xe!==void 0)return ee;ge=l.ParserState.PathStart}else{var xt;if((xt=F(oe,!S(ee)))===null)return null;if(xt==="localhost"&&(xt=""),ee.host=xt,xe!==void 0)return ee;oe="",ge=l.ParserState.PathStart}else oe+=Ie.c();break;case l.ParserState.PathStart:S(ee)?(Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.Path,Ie.c()!=="/"&&Ie.c()!=="\\"&&Ie.pointer--):xe===void 0&&Ie.c()==="?"?(ee.query="",ge=l.ParserState.Query):xe===void 0&&Ie.c()==="#"?(ee.fragment="",ge=l.ParserState.Fragment):Ie.c()!==""&&(ge=l.ParserState.Path,Ie.c()!=="/"&&Ie.pointer--);break;case l.ParserState.Path:if(Ie.c()===""||Ie.c()==="/"||S(ee)&&Ie.c()==="\\"||xe===void 0&&(Ie.c()==="?"||Ie.c()==="#")){if(S(ee)&&Ie.c()==="\\"&&w("Invalid input string."),L(oe))V(ee),Ie.c()==="/"||S(ee)&&Ie.c()==="\\"||ee.path.push("");else if(!M(oe)||Ie.c()==="/"||S(ee)&&Ie.c()==="\\"){if(!M(oe)){if(ee.scheme==="file"&&ee.path.length===0&&A(oe)){ee.host!==null&&ee.host!==""&&(w("Invalid input string."),ee.host="");var Ft=Array.from(oe);oe=Ft.slice(0,1)+":"+Ft.slice(2)}ee.path.push(oe)}}else ee.path.push("");if(oe="",ee.scheme==="file"&&(Ie.c()===""||Ie.c()==="?"||Ie.c()==="#"))for(;ee.path.length>1&&ee.path[0]==="";)w("Invalid input string."),ee.path.splice(0,1);Ie.c()==="?"&&(ee.query="",ge=l.ParserState.Query),Ie.c()==="#"&&(ee.fragment="",ge=l.ParserState.Fragment)}else y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),oe+=Se(Ie.c(),p);break;case l.ParserState.CannotBeABaseURLPath:Ie.c()==="?"?(ee.query="",ge=l.ParserState.Query):Ie.c()==="#"?(ee.fragment="",ge=l.ParserState.Fragment):(Ie.c()===""||y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),Ie.c()!==""&&(ee.path[0]+=Se(Ie.c(),h)));break;case l.ParserState.Query:if(Fe==="UTF-8"||S(ee)&&ee.scheme!=="ws"&&ee.scheme!=="wss"||(Fe="UTF-8"),xe===void 0&&Ie.c()==="#")ee.fragment="",ge=l.ParserState.Fragment;else if(Ie.c()!==""){if(y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),Fe.toUpperCase()!=="UTF-8")throw new Error("Only UTF-8 encoding is supported.");var jt=c.utf8Encode(Ie.c());if(jt.length>=3&&jt[0]===38&&jt[1]===35&&jt[jt.length-1]===59)jt=jt.subarray(2,jt.length-1),ee.query+="%26%23"+f.byteSequence.isomorphicDecode(jt)+"%3B";else try{for(var Pn=(ze=void 0,o(jt)),$n=Pn.next();!$n.done;$n=Pn.next()){var fn=$n.value;fn<33||fn>126||fn===34||fn===35||fn===60||fn===62||fn===39&&S(ee)?ee.query+=pe(fn):ee.query+=String.fromCharCode(fn)}}catch(bn){ze={error:bn}}finally{try{$n&&!$n.done&&(ie=Pn.return)&&ie.call(Pn)}finally{if(ze)throw ze.error}}}break;case l.ParserState.Fragment:Ie.c()===""||(Ie.c()==="\0"?w("NULL character in input string."):(y.test(Ie.c())||Ie.c()==="%"||w("Unexpected character in fragment string."),Ie.c()!=="%"||/^[A-Za-z0-9][A-Za-z0-9]/.test(Ie.remaining())||w("Unexpected character in fragment string."),ee.fragment+=Se(Ie.c(),g)))}if(Ie.eof)break;Ie.pointer++}return ee}function M(W){return W==="."||W.toLowerCase()==="%2e"}function L(W){var K=W.toLowerCase();return K===".."||K===".%2e"||K==="%2e."||K==="%2e%2e"}function V(W){var K=W.path;K.length!==0&&(W.scheme==="file"&&K.length===1&&G(K[0])||W.path.splice(W.path.length-1,1))}function G(W){return W.length>=2&&f.codePoint.ASCIIAlpha.test(W[0])&&W[1]===":"}function A(W){return W.length>=2&&f.codePoint.ASCIIAlpha.test(W[0])&&(W[1]===":"||W[1]==="|")}function k(W){return W.length>=2&&A(W)&&(W.length===2||W[2]==="/"||W[2]==="\\"||W[2]==="?"||W[2]==="#")}function F(W,K){if(K===void 0&&(K=!1),W.startsWith("["))return W.endsWith("]")?re(W.substring(1,W.length-1)):(w("Expected ']' after '['."),null);if(K)return ue(W);var Z=z(c.utf8Decode(Oe(W)));if(Z===null||m.test(Z))return w("Invalid domain."),null;var ee=Y(Z);return ee===null||c.isNumber(ee)?ee:Z}function j(W,K){K===void 0&&(K={value:!1});var Z=10;return W.startsWith("0x")||W.startsWith("0X")?(K.value=!0,W=W.substr(2),Z=16):W.length>=2&&W[0]==="0"&&(K.value=!0,W=W.substr(1),Z=8),W===""?0:(Z===10?/^[0-9]+$/:Z===16?/^[0-9A-Fa-f]+$/:/^[0-7]+$/).test(W)?parseInt(W,Z):null}function Y(W){var K,Z,ee,xe,De={value:!1},Ne=W.split(".");if(Ne[Ne.length-1]===""&&(De.value=!0,Ne.length>1&&Ne.pop()),Ne.length>4)return W;var ze=[];try{for(var ie=o(Ne),ae=ie.next();!ae.done;ae=ie.next()){var we=ae.value;if(we===""||(wt=j(we,De))===null)return W;ze.push(wt)}}catch(gt){K={error:gt}}finally{try{ae&&!ae.done&&(Z=ie.return)&&Z.call(ie)}finally{if(K)throw K.error}}De.value&&w("Invalid IP v4 address.");for(var se=0;se255&&(w("Invalid IP v4 address."),se=Math.pow(256,5-ze.length))return w("Invalid IP v4 address."),null;var ge=ze[ze.length-1];ze.pop();var Fe=0;try{for(var oe=o(ze),ht=oe.next();!ht.done;ht=oe.next()){var wt;ge+=(wt=ht.value)*Math.pow(256,3-Fe),Fe++}}catch(gt){ee={error:gt}}finally{try{ht&&!ht.done&&(xe=oe.return)&&xe.call(oe)}finally{if(ee)throw ee.error}}return ge}function re(W){var K,Z=[0,0,0,0,0,0,0,0],ee=0,xe=null,De=new c.StringWalker(W);if(De.c()===":"){if(!De.remaining().startsWith(":"))return w("Invalid IP v6 address."),null;De.pointer+=2,xe=ee+=1}for(;De.c()!=="";){if(ee===8)return w("Invalid IP v6 address."),null;if(De.c()!==":"){for(var Ne=0,ze=0;ze<4&&f.codePoint.ASCIIHexDigit.test(De.c());)Ne=16*Ne+parseInt(De.c(),16),De.pointer++,ze++;if(De.c()==="."){if(ze===0||(De.pointer-=ze,ee>6))return w("Invalid IP v6 address."),null;for(var ie=0;De.c()!=="";){var ae=null;if(ie>0){if(!(De.c()==="."&&ie<4))return w("Invalid IP v6 address."),null;De.pointer++}if(!f.codePoint.ASCIIDigit.test(De.c()))return w("Invalid IP v6 address."),null;for(;f.codePoint.ASCIIDigit.test(De.c());){var we=parseInt(De.c(),10);if(ae===null)ae=we;else{if(ae===0)return w("Invalid IP v6 address."),null;ae=10*ae+we}if(ae>255)return w("Invalid IP v6 address."),null;De.pointer++}if(ae===null)return w("Invalid IP v6 address."),null;Z[ee]=256*Z[ee]+ae,++ie!==2&&ie!==4||ee++}if(ie!==4)return w("Invalid IP v6 address."),null;break}if(De.c()===":"){if(De.pointer++,De.c()==="")return w("Invalid IP v6 address."),null}else if(De.c()!=="")return w("Invalid IP v6 address."),null;Z[ee]=Ne,ee++}else{if(xe!==null)return w("Invalid IP v6 address."),null;De.pointer++,xe=++ee}}if(xe!==null){var se=ee-xe;for(ee=7;ee!==0&&se>0;)K=a([Z[xe+se-1],Z[ee]],2),Z[ee]=K[0],Z[xe+se-1]=K[1],ee--,se--}else if(xe===null&&ee!==8)return w("Invalid IP v6 address."),null;return Z}function ue(W){var K,Z;if(/[\x00\t\f\r #/:?@\[\\\]]/.test(W))return w("Invalid host string."),null;var ee="";try{for(var xe=o(W),De=xe.next();!De.done;De=xe.next())ee+=Se(De.value,h)}catch(Ne){K={error:Ne}}finally{try{De&&!De.done&&(Z=xe.return)&&Z.call(xe)}finally{if(K)throw K.error}}return ee}function ce(W){return null}function pe(W){return"%"+("00"+W.toString(16).toUpperCase()).slice(-2)}function Ee(W){for(var K=function(ze){return ze>=48&&ze<=57||ze>=65&&ze<=70||ze>=97&&ze<=102},Z=new Uint8Array(W.length),ee=0,xe=0;xe=W.length-2)Z[ee]=De,ee++;else if(De!==37||K(W[xe+1])&&K(W[xe+2])){var Ne=parseInt(c.utf8Decode(Uint8Array.of(W[xe+1],W[xe+2])),16);Z[ee]=Ne,ee++,xe+=2}else Z[ee]=De,ee++}return Z.subarray(0,ee)}function Oe(W){return Ee(c.utf8Encode(W))}function Se(W,K){var Z,ee;if(!K.test(W))return W;var xe=c.utf8Encode(W),De="";try{for(var Ne=o(xe),ze=Ne.next();!ze.done;ze=Ne.next())De+=pe(ze.value)}catch(ie){Z={error:ie}}finally{try{ze&&!ze.done&&(ee=Ne.return)&&ee.call(Ne)}finally{if(Z)throw Z.error}}return De}function B(W){var K,Z,ee,xe,De=[],Ne=[];try{for(var ze=o(W),ie=ze.next();!ie.done;ie=ze.next()){var ae=ie.value;ae===38?(De.push(Uint8Array.from(Ne)),Ne=[]):Ne.push(ae)}}catch(tt){K={error:tt}}finally{try{ie&&!ie.done&&(Z=ze.return)&&Z.call(ze)}finally{if(K)throw K.error}}Ne.length!==0&&De.push(Uint8Array.from(Ne));var we=[];try{for(var se=o(De),ge=se.next();!ge.done;ge=se.next()){var Fe=ge.value;if(Fe.length!==0){for(var oe=Fe.indexOf(61),ht=oe!==-1?Fe.slice(0,oe):Fe,wt=oe!==-1?Fe.slice(oe+1):new Uint8Array,gt=0;gt=48&&Ne<=57||Ne>=65&&Ne<=90||Ne===95||Ne>=97&&Ne<=122?String.fromCodePoint(Ne):pe(Ne)}}catch(ze){K={error:ze}}finally{try{De&&!De.done&&(Z=xe.return)&&Z.call(xe)}finally{if(K)throw K.error}}return ee}function z(W,K){var Z=u.domainToASCII(W);return Z===""?(w("Invalid domain name."),null):Z}n.setValidationErrorCallback=function(W){s=W},n.newURL=x,n.isSpecialScheme=C,n.isSpecial=S,n.defaultPort=_,n.includesCredentials=T,n.cannotHaveAUsernamePasswordPort=function(W){return W.host===null||W.host===""||W._cannotBeABaseURLFlag||W.scheme==="file"},n.urlSerializer=E,n.hostSerializer=D,n.iPv4Serializer=b,n.iPv6Serializer=I,n.urlParser=function(W,K,Z){var ee=P(W,K,Z);return ee===null?null:(ee.scheme!=="blob"||(ee._blobURLEntry=null),ee)},n.basicURLParser=P,n.setTheUsername=function(W,K){var Z,ee,xe="";try{for(var De=o(K),Ne=De.next();!Ne.done;Ne=De.next())xe+=Se(Ne.value,v)}catch(ze){Z={error:ze}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}W.username=xe},n.setThePassword=function(W,K){var Z,ee,xe="";try{for(var De=o(K),Ne=De.next();!Ne.done;Ne=De.next())xe+=Se(Ne.value,v)}catch(ze){Z={error:ze}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}W.password=xe},n.isSingleDotPathSegment=M,n.isDoubleDotPathSegment=L,n.shorten=V,n.isNormalizedWindowsDriveLetter=G,n.isWindowsDriveLetter=A,n.startsWithAWindowsDriveLetter=k,n.hostParser=F,n.iPv4NumberParser=j,n.iPv4Parser=Y,n.iPv6Parser=re,n.opaqueHostParser=ue,n.resolveABlobURL=ce,n.percentEncode=pe,n.percentDecode=Ee,n.stringPercentDecode=Oe,n.utf8PercentEncode=Se,n.hostEquals=function(W,K){return W===K},n.urlEquals=function(W,K,Z){return Z===void 0&&(Z=!1),E(W,Z)===E(K,Z)},n.urlEncodedStringParser=function(W){return B(c.utf8Encode(W))},n.urlEncodedParser=B,n.urlEncodedByteSerializer=O,n.urlEncodedSerializer=function(W,K){var Z,ee;if((K===void 0||K==="replacement"||K==="UTF-16BE"||K==="UTF-16LE"?"UTF-8":K).toUpperCase()!=="UTF-8")throw new Error("Only UTF-8 encoding is supported.");var xe="";try{for(var De=o(W),Ne=De.next();!Ne.done;Ne=De.next()){var ze=Ne.value,ie=O(c.utf8Encode(ze[0])),ae=ze[1];ae=O(c.utf8Encode(ae)),xe!==""&&(xe+="&"),xe+=ie+"="+ae}}catch(we){Z={error:we}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}return xe},n.origin=function W(K){switch(K.scheme){case"blob":K._blobURLEntry;var Z=P(K.path[0]);return Z===null?l.OpaqueOrigin:W(Z);case"ftp":case"http":case"https":case"ws":case"wss":return[K.scheme,K.host===null?"":K.host,K.port,null];case"file":default:return l.OpaqueOrigin}},n.domainToASCII=z,n.domainToUnicode=function(W,K){var Z=u.domainToUnicode(W);return Z===""&&w("Invalid domain name."),Z},n.asciiSerializationOfAnOrigin=function(W){if(W[0]===""&&W[1]===""&&W[2]===null&&W[3]===null)return"null";var K=W[0]+"://"+D(W[1]);return W[2]!==null&&(K+=":"+W[2].toString()),K}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(0),a=function(){function s(){this._signal=o.create_abortSignal()}return Object.defineProperty(s.prototype,"signal",{get:function(){return this._signal},enumerable:!0,configurable:!0}),s.prototype.abort=function(){o.abort_signalAbort(this._signal)},s}();n.AbortControllerImpl=a},function(r,n,i){var o,a=this&&this.__extends||(o=function(f,u){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var g in h)h.hasOwnProperty(g)&&(d[g]=h[g])})(f,u)},function(f,u){function d(){this.constructor=f}o(f,u),f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(70),c=i(0),l=function(f){function u(){var d=f.call(this)||this;return d._abortedFlag=!1,d._abortAlgorithms=new Set,d}return a(u,f),Object.defineProperty(u.prototype,"aborted",{get:function(){return this._abortedFlag},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"onabort",{get:function(){return c.event_getterEventHandlerIDLAttribute(this,"onabort")},set:function(d){c.event_setterEventHandlerIDLAttribute(this,"onabort",d)},enumerable:!0,configurable:!0}),u._create=function(){return new u},u}(s.EventTargetImpl);n.AbortSignalImpl=l},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(2),c=i(34),l=i(12),f=function(u){function d(h,g,p){var v=u.call(this)||this;return v._name="",v._publicId="",v._systemId="",v._name=h,v._publicId=g,v._systemId=p,v}return a(d,u),Object.defineProperty(d.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"publicId",{get:function(){return this._publicId},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"systemId",{get:function(){return this._systemId},enumerable:!0,configurable:!0}),d.prototype.before=function(){for(var h=[],g=0;g=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(1),c=i(0),l=function(){function f(u){return this._live=!0,this._filter=null,this._length=0,this._root=u,new Proxy(this,this)}return Object.defineProperty(f.prototype,"length",{get:function(){return this._root._children.size},enumerable:!0,configurable:!0}),f.prototype.item=function(u){if(u<0||u>this.length-1)return null;if(u=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(1),c=function(){function l(f){return this._live=!1,this._items=[],this._length=0,this._root=f,this._items=[],this._filter=function(u){return!0},new Proxy(this,this)}return Object.defineProperty(l.prototype,"length",{get:function(){return this._items.length},enumerable:!0,configurable:!0}),l.prototype.item=function(f){return f<0||f>this.length-1?null:this._items[f]},l.prototype.keys=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=0;return{next:(function(){return u===this.length?{done:!0,value:null}:{done:!1,value:u++}}).bind(this)}}).bind(this),f},l.prototype.values=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=this[Symbol.iterator]();return{next:function(){return u.next()}}}).bind(this),f},l.prototype.entries=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=this[Symbol.iterator](),d=0;return{next:function(){var h=u.next();return h.done?{done:!0,value:null}:{done:!1,value:[d++,h.value]}}}}).bind(this),f},l.prototype[Symbol.iterator]=function(){var f=this._items[Symbol.iterator]();return{next:function(){return f.next()}}},l.prototype.forEach=function(f,u){var d,h;u===void 0&&(u=a.dom.window);var g=0;try{for(var p=o(this._items),v=p.next();!v.done;v=p.next()){var y=v.value;f.call(u,y,g++,this)}}catch(m){d={error:m}}finally{try{v&&!v.done&&(h=p.return)&&h.call(p)}finally{if(d)throw d.error}}},l.prototype.get=function(f,u,d){if(!s.isString(u))return Reflect.get(f,u,d);var h=Number(u);return isNaN(h)?Reflect.get(f,u,d):f._items[h]||void 0},l.prototype.set=function(f,u,d,h){if(!s.isString(u))return Reflect.set(f,u,d,h);var g=Number(u);return isNaN(g)?Reflect.set(f,u,d,h):g>=0&&g=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(6),l=i(2),f=i(102),u=i(9),d=i(0),h=i(12),g=i(3),p=function(v){function y(){var m=v.call(this)||this,w=c.dom.window._associatedDocument;return m._start=[w,0],m._end=[w,0],c.dom.rangeList.add(m),m}return a(y,v),Object.defineProperty(y.prototype,"commonAncestorContainer",{get:function(){for(var m=this._start[0];!d.tree_isAncestorOf(this._end[0],m,!0);){if(m._parent===null)throw new Error("Parent node is null.");m=m._parent}return m},enumerable:!0,configurable:!0}),y.prototype.setStart=function(m,w){d.range_setTheStart(this,m,w)},y.prototype.setEnd=function(m,w){d.range_setTheEnd(this,m,w)},y.prototype.setStartBefore=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheStart(this,w,d.tree_index(m))},y.prototype.setStartAfter=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheStart(this,w,d.tree_index(m)+1)},y.prototype.setEndBefore=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheEnd(this,w,d.tree_index(m))},y.prototype.setEndAfter=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheEnd(this,w,d.tree_index(m)+1)},y.prototype.collapse=function(m){m?this._end=this._start:this._start=this._end},y.prototype.selectNode=function(m){d.range_select(m,this)},y.prototype.selectNodeContents=function(m){if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;var w=d.tree_nodeLength(m);this._start=[m,0],this._end=[m,w]},y.prototype.compareBoundaryPoints=function(m,w){if(m!==l.HowToCompare.StartToStart&&m!==l.HowToCompare.StartToEnd&&m!==l.HowToCompare.EndToEnd&&m!==l.HowToCompare.EndToStart)throw new u.NotSupportedError;if(d.range_root(this)!==d.range_root(w))throw new u.WrongDocumentError;var x,C;switch(m){case l.HowToCompare.StartToStart:x=this._start,C=w._start;break;case l.HowToCompare.StartToEnd:x=this._end,C=w._start;break;case l.HowToCompare.EndToEnd:x=this._end,C=w._end;break;case l.HowToCompare.EndToStart:x=this._start,C=w._end;break;default:throw new u.NotSupportedError}var S=d.boundaryPoint_position(x,C);return S===l.BoundaryPosition.Before?-1:S===l.BoundaryPosition.After?1:0},y.prototype.deleteContents=function(){var m,w,x,C;if(!d.range_collapsed(this)){var S=this._startNode,_=this._startOffset,T=this._endNode,E=this._endOffset;if(S===T&&g.Guard.isCharacterDataNode(S))d.characterData_replaceData(S,_,E-_,"");else{var D,b,I=[];try{for(var P=s(d.range_getContainedNodes(this)),M=P.next();!M.done;M=P.next()){var L=(k=M.value)._parent;L!==null&&d.range_isContained(L,this)||I.push(k)}}catch(F){m={error:F}}finally{try{M&&!M.done&&(w=P.return)&&w.call(P)}finally{if(m)throw m.error}}if(d.tree_isAncestorOf(T,S,!0))D=S,b=_;else{for(var V=S;V._parent!==null&&!d.tree_isAncestorOf(T,V._parent,!0);)V=V._parent;if(V._parent===null)throw new Error("Parent node is null.");D=V._parent,b=d.tree_index(V)+1}g.Guard.isCharacterDataNode(S)&&d.characterData_replaceData(S,_,d.tree_nodeLength(S)-_,"");try{for(var G=s(I),A=G.next();!A.done;A=G.next()){var k;(k=A.value)._parent&&d.mutation_remove(k,k._parent)}}catch(F){x={error:F}}finally{try{A&&!A.done&&(C=G.return)&&C.call(G)}finally{if(x)throw x.error}}g.Guard.isCharacterDataNode(T)&&d.characterData_replaceData(T,0,E,""),this._start=[D,b],this._end=[D,b]}}},y.prototype.extractContents=function(){return d.range_extract(this)},y.prototype.cloneContents=function(){return d.range_cloneTheContents(this)},y.prototype.insertNode=function(m){return d.range_insert(m,this)},y.prototype.surroundContents=function(m){var w,x;try{for(var C=s(d.range_getPartiallyContainedNodes(this)),S=C.next();!S.done;S=C.next()){var _=S.value;if(!g.Guard.isTextNode(_))throw new u.InvalidStateError}}catch(E){w={error:E}}finally{try{S&&!S.done&&(x=C.return)&&x.call(C)}finally{if(w)throw w.error}}if(g.Guard.isDocumentNode(m)||g.Guard.isDocumentTypeNode(m)||g.Guard.isDocumentFragmentNode(m))throw new u.InvalidNodeTypeError;var T=d.range_extract(this);m._children.size!==0&&d.mutation_replaceAll(null,m),d.range_insert(m,this),d.mutation_append(T,m),d.range_select(m,this)},y.prototype.cloneRange=function(){return d.create_range(this._start,this._end)},y.prototype.detach=function(){c.dom.rangeList.delete(this)},y.prototype.isPointInRange=function(m,w){if(d.tree_rootNode(m)!==d.range_root(this))return!1;if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;if(w>d.tree_nodeLength(m))throw new u.IndexSizeError;var x=[m,w];return d.boundaryPoint_position(x,this._start)!==l.BoundaryPosition.Before&&d.boundaryPoint_position(x,this._end)!==l.BoundaryPosition.After},y.prototype.comparePoint=function(m,w){if(d.tree_rootNode(m)!==d.range_root(this))throw new u.WrongDocumentError;if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;if(w>d.tree_nodeLength(m))throw new u.IndexSizeError;var x=[m,w];return d.boundaryPoint_position(x,this._start)===l.BoundaryPosition.Before?-1:d.boundaryPoint_position(x,this._end)===l.BoundaryPosition.After?1:0},y.prototype.intersectsNode=function(m){if(d.tree_rootNode(m)!==d.range_root(this))return!1;var w=m._parent;if(w===null)return!0;var x=d.tree_index(m);return d.boundaryPoint_position([w,x],this._end)===l.BoundaryPosition.Before&&d.boundaryPoint_position([w,x+1],this._start)===l.BoundaryPosition.After},y.prototype.toString=function(){var m,w,x="";if(this._startNode===this._endNode&&g.Guard.isTextNode(this._startNode))return this._startNode._data.substring(this._startOffset,this._endOffset);g.Guard.isTextNode(this._startNode)&&(x+=this._startNode._data.substring(this._startOffset));try{for(var C=s(d.range_getContainedNodes(this)),S=C.next();!S.done;S=C.next()){var _=S.value;g.Guard.isTextNode(_)&&(x+=_._data)}}catch(T){m={error:T}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return g.Guard.isTextNode(this._endNode)&&(x+=this._endNode._data.substring(0,this._endOffset)),x},y._create=function(m,w){var x=new y;return m&&(x._start=m),w&&(x._end=w),x},y.START_TO_START=0,y.START_TO_END=1,y.END_TO_END=2,y.END_TO_START=3,y}(f.AbstractRangeImpl);n.RangeImpl=p,h.idl_defineConst(p.prototype,"START_TO_START",0),h.idl_defineConst(p.prototype,"START_TO_END",1),h.idl_defineConst(p.prototype,"END_TO_END",2),h.idl_defineConst(p.prototype,"END_TO_START",3)},function(r,n,i){var o,a=this&&this.__extends||(o=function(f,u){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var g in h)h.hasOwnProperty(g)&&(d[g]=h[g])})(f,u)},function(f,u){function d(){this.constructor=f}o(f,u),f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(103),c=i(0),l=function(f){function u(d,h,g){var p=f.call(this,d)||this;return p._iteratorCollection=void 0,p._reference=h,p._pointerBeforeReference=g,c.nodeIterator_iteratorList().add(p),p}return a(u,f),Object.defineProperty(u.prototype,"referenceNode",{get:function(){return this._reference},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"pointerBeforeReferenceNode",{get:function(){return this._pointerBeforeReference},enumerable:!0,configurable:!0}),u.prototype.nextNode=function(){return c.nodeIterator_traverse(this,!0)},u.prototype.previousNode=function(){return c.nodeIterator_traverse(this,!1)},u.prototype.detach=function(){c.nodeIterator_iteratorList().delete(this)},u._create=function(d,h,g){return new u(d,h,g)},u}(s.TraverserImpl);n.NodeIteratorImpl=l},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(2),c=i(103),l=i(0),f=function(u){function d(h,g){var p=u.call(this,h)||this;return p._current=g,p}return a(d,u),Object.defineProperty(d.prototype,"currentNode",{get:function(){return this._current},set:function(h){this._current=h},enumerable:!0,configurable:!0}),d.prototype.parentNode=function(){for(var h=this._current;h!==null&&h!==this._root;)if((h=h._parent)!==null&&l.traversal_filter(this,h)===s.FilterResult.Accept)return this._current=h,h;return null},d.prototype.firstChild=function(){return l.treeWalker_traverseChildren(this,!0)},d.prototype.lastChild=function(){return l.treeWalker_traverseChildren(this,!1)},d.prototype.nextSibling=function(){return l.treeWalker_traverseSiblings(this,!0)},d.prototype.previousNode=function(){for(var h=this._current;h!==this._root;){for(var g=h._previousSibling;g;){h=g;for(var p=l.traversal_filter(this,h);p!==s.FilterResult.Reject&&h._lastChild;)h=h._lastChild,p=l.traversal_filter(this,h);if(p===s.FilterResult.Accept)return this._current=h,h;g=h._previousSibling}if(h===this._root||h._parent===null)return null;if(h=h._parent,l.traversal_filter(this,h)===s.FilterResult.Accept)return this._current=h,h}return null},d.prototype.previousSibling=function(){return l.treeWalker_traverseSiblings(this,!1)},d.prototype.nextNode=function(){for(var h=this._current,g=s.FilterResult.Accept;;){for(;g!==s.FilterResult.Reject&&h._firstChild;)if(h=h._firstChild,(g=l.traversal_filter(this,h))===s.FilterResult.Accept)return this._current=h,h;for(var p=null,v=h;v!==null;){if(v===this._root)return null;if((p=v._nextSibling)!==null){h=p;break}v=v._parent}if((g=l.traversal_filter(this,h))===s.FilterResult.Accept)return this._current=h,h}},d._create=function(h,g){return new d(h,g)},d}(c.TraverserImpl);n.TreeWalkerImpl=f},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(12),s=function(){function c(){}return c.prototype.acceptNode=function(l){return o.FilterResult.Accept},c._create=function(){return new c},c.FILTER_ACCEPT=1,c.FILTER_REJECT=2,c.FILTER_SKIP=3,c.SHOW_ALL=4294967295,c.SHOW_ELEMENT=1,c.SHOW_ATTRIBUTE=2,c.SHOW_TEXT=4,c.SHOW_CDATA_SECTION=8,c.SHOW_ENTITY_REFERENCE=16,c.SHOW_ENTITY=32,c.SHOW_PROCESSING_INSTRUCTION=64,c.SHOW_COMMENT=128,c.SHOW_DOCUMENT=256,c.SHOW_DOCUMENT_TYPE=512,c.SHOW_DOCUMENT_FRAGMENT=1024,c.SHOW_NOTATION=2048,c}();n.NodeFilterImpl=s,a.idl_defineConst(s.prototype,"FILTER_ACCEPT",1),a.idl_defineConst(s.prototype,"FILTER_REJECT",2),a.idl_defineConst(s.prototype,"FILTER_SKIP",3),a.idl_defineConst(s.prototype,"SHOW_ALL",4294967295),a.idl_defineConst(s.prototype,"SHOW_ELEMENT",1),a.idl_defineConst(s.prototype,"SHOW_ATTRIBUTE",2),a.idl_defineConst(s.prototype,"SHOW_TEXT",4),a.idl_defineConst(s.prototype,"SHOW_CDATA_SECTION",8),a.idl_defineConst(s.prototype,"SHOW_ENTITY_REFERENCE",16),a.idl_defineConst(s.prototype,"SHOW_ENTITY",32),a.idl_defineConst(s.prototype,"SHOW_PROCESSING_INSTRUCTION",64),a.idl_defineConst(s.prototype,"SHOW_COMMENT",128),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT",256),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT_TYPE",512),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT_FRAGMENT",1024),a.idl_defineConst(s.prototype,"SHOW_NOTATION",2048)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(s,c,l,f,u,d,h,g,p){this._type=s,this._target=c,this._addedNodes=l,this._removedNodes=f,this._previousSibling=u,this._nextSibling=d,this._attributeName=h,this._attributeNamespace=g,this._oldValue=p}return Object.defineProperty(a.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"addedNodes",{get:function(){return this._addedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"removedNodes",{get:function(){return this._removedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"attributeName",{get:function(){return this._attributeName},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"attributeNamespace",{get:function(){return this._attributeNamespace},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"oldValue",{get:function(){return this._oldValue},enumerable:!0,configurable:!0}),a._create=function(s,c,l,f,u,d,h,g,p){return new a(s,c,l,f,u,d,h,g,p)},a}();n.MutationRecordImpl=o},function(r,n,i){var o=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(9),c=i(7),l=i(0),f=function(){function u(d,h){this._element=d,this._attribute=h,this._tokenSet=new Set;var g=h._localName,p=l.element_getAnAttributeValue(d,g),v=this;this._element._attributeChangeSteps.push(function(y,m,w,x,C){m===v._attribute._localName&&C===null&&(x?v._tokenSet=l.orderedSet_parse(x):v._tokenSet.clear())}),a.dom.features.steps&&l.dom_runAttributeChangeSteps(d,g,p,p,null)}return Object.defineProperty(u.prototype,"length",{get:function(){return this._tokenSet.size},enumerable:!0,configurable:!0}),u.prototype.item=function(d){var h,g,p=0;try{for(var v=o(this._tokenSet),y=v.next();!y.done;y=v.next()){var m=y.value;if(p===d)return m;p++}}catch(w){h={error:w}}finally{try{y&&!y.done&&(g=v.return)&&g.call(v)}finally{if(h)throw h.error}}return null},u.prototype.contains=function(d){return this._tokenSet.has(d)},u.prototype.add=function(){for(var d,h,g=[],p=0;p=97&&s<=122||s>=65&&s<=90||s===58||s===95||s>=192&&s<=214||s>=216&&s<=246||s>=248&&s<=767||s>=880&&s<=893||s>=895&&s<=8191||s>=8204&&s<=8205||s>=8304&&s<=8591||s>=11264&&s<=12271||s>=12289&&s<=55295||s>=63744&&s<=64975||s>=65008&&s<=65533)&&(a===0||!(s===45||s===46||s>=48&&s<=57||s===183||s>=768&&s<=879||s>=8255&&s<=8256))){if(s>=55296&&s<=56319&&a=56320&&c<=57343&&(a++,(s=1024*(s-55296)+c-56320+65536)>=65536&&s<=983039))continue}return!1}}return!0},n.xml_isQName=function(o){for(var a=!1,s=0;s=97&&c<=122||c>=65&&c<=90||c===95||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8204&&c<=8205||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533)&&(s===0||!(c===45||c===46||c>=48&&c<=57||c===183||c>=768&&c<=879||c>=8255&&c<=8256))){if(s===0||c!==58){if(c>=55296&&c<=56319&&s=56320&&l<=57343&&(s++,(c=1024*(c-55296)+l-56320+65536)>=65536&&c<=983039))continue}return!1}if(a||s===o.length-1)return!1;a=!0}}return!0},n.xml_isLegalChar=function(o){for(var a=0;a=32&&s<=55295||s>=57344&&s<=65533)){if(s>=55296&&s<=56319&&a=56320&&c<=57343&&(a++,(s=1024*(s-55296)+c-56320+65536)>=65536&&s<=1114111))continue}return!1}}return!0},n.xml_isPubidChar=function(o){for(var a=0;a=97&&s<=122||s>=65&&s<=90||s>=39&&s<=59||s===32||s===13||s===10||s>=35&&s<=37||s===33||s===61||s===63||s===64||s===95))return!1}return!0}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(17);n.boundaryPoint_position=function s(c,l){var f=c[0],u=c[1],d=l[0],h=l[1];if(console.assert(a.tree_rootNode(f)===a.tree_rootNode(d),"Boundary points must share the same root node."),f===d)return u===h?o.BoundaryPosition.Equal:u=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(7),l=i(29),f=i(108),u=i(30),d=i(37),h=i(52);n.node_stringReplaceAll=function(g,p){var v=null;g!==""&&(v=l.create_text(p._nodeDocument,g)),d.mutation_replaceAll(v,p)},n.node_clone=function g(p,v,y){var m,w,x,C,S;if(v===void 0&&(v=null),y===void 0&&(y=!1),v===null&&(v=p._nodeDocument),s.Guard.isElementNode(p)){S=h.element_createAnElement(v,p._localName,p._namespace,p._namespacePrefix,p._is,!1);try{for(var _=o(p._attributeList),T=_.next();!T.done;T=_.next()){var E=g(T.value,v);h.element_append(E,S)}}catch(L){m={error:L}}finally{try{T&&!T.done&&(w=_.return)&&w.call(_)}finally{if(m)throw m.error}}}else if(s.Guard.isDocumentNode(p)){var D=l.create_document();D._encoding=p._encoding,D._contentType=p._contentType,D._URL=p._URL,D._origin=p._origin,D._type=p._type,D._mode=p._mode,S=D}else if(s.Guard.isDocumentTypeNode(p))S=l.create_documentType(v,p._name,p._publicId,p._systemId);else if(s.Guard.isAttrNode(p)){var b=l.create_attr(v,p.localName);b._namespace=p._namespace,b._namespacePrefix=p._namespacePrefix,b._value=p._value,S=b}else S=s.Guard.isExclusiveTextNode(p)?l.create_text(v,p._data):s.Guard.isCDATASectionNode(p)?l.create_cdataSection(v,p._data):s.Guard.isCommentNode(p)?l.create_comment(v,p._data):s.Guard.isProcessingInstructionNode(p)?l.create_processingInstruction(v,p._target,p._data):s.Guard.isDocumentFragmentNode(p)?l.create_documentFragment(v):Object.create(p);if(s.Guard.isDocumentNode(S)?(S._nodeDocument=S,v=S):S._nodeDocument=v,a.dom.features.steps&&u.dom_runCloningSteps(S,p,v,y),y)try{for(var I=o(p._children),P=I.next();!P.done;P=I.next()){var M=g(P.value,v,!0);d.mutation_append(M,S)}}catch(L){x={error:L}}finally{try{P&&!P.done&&(C=I.return)&&C.call(I)}finally{if(x)throw x.error}}return S},n.node_equals=function g(p,v){var y,m,w,x;if(p._nodeType!==v._nodeType)return!1;if(s.Guard.isDocumentTypeNode(p)&&s.Guard.isDocumentTypeNode(v)){if(p._name!==v._name||p._publicId!==v._publicId||p._systemId!==v._systemId)return!1}else if(s.Guard.isElementNode(p)&&s.Guard.isElementNode(v)){if(p._namespace!==v._namespace||p._namespacePrefix!==v._namespacePrefix||p._localName!==v._localName||p._attributeList.length!==v._attributeList.length)return!1}else if(s.Guard.isAttrNode(p)&&s.Guard.isAttrNode(v)){if(p._namespace!==v._namespace||p._localName!==v._localName||p._value!==v._value)return!1}else if(s.Guard.isProcessingInstructionNode(p)&&s.Guard.isProcessingInstructionNode(v)){if(p._target!==v._target||p._data!==v._data)return!1}else if(s.Guard.isCharacterDataNode(p)&&s.Guard.isCharacterDataNode(v)&&p._data!==v._data)return!1;if(s.Guard.isElementNode(p)&&s.Guard.isElementNode(v)){var C={};try{for(var S=o(p._attributeList),_=S.next();!_.done;_=S.next())C[(D=_.value)._localName]=D}catch(V){y={error:V}}finally{try{_&&!_.done&&(m=S.return)&&m.call(S)}finally{if(y)throw y.error}}try{for(var T=o(v._attributeList),E=T.next();!E.done;E=T.next()){var D,b=E.value;if(!(D=C[b._localName])||!g(D,b))return!1}}catch(V){w={error:V}}finally{try{E&&!E.done&&(x=T.return)&&x.call(T)}finally{if(w)throw w.error}}}if(p._children.size!==v._children.size)return!1;for(var I=p._children[Symbol.iterator](),P=v._children[Symbol.iterator](),M=I.next(),L=P.next();!M.done&&!L.done;){if(!g(M.value,L.value))return!1;M=I.next(),L=P.next()}return!0},n.node_listOfElementsWithQualifiedName=function(g,p){return g==="*"?l.create_htmlCollection(p):p._nodeDocument._type==="html"?l.create_htmlCollection(p,function(v){return v._namespace===c.namespace.HTML&&v._qualifiedName===g.toLowerCase()||v._namespace!==c.namespace.HTML&&v._qualifiedName===g}):l.create_htmlCollection(p,function(v){return v._qualifiedName===g})},n.node_listOfElementsWithNamespace=function(g,p,v){return g===""&&(g=null),g==="*"&&p==="*"?l.create_htmlCollection(v):g==="*"?l.create_htmlCollection(v,function(y){return y._localName===p}):p==="*"?l.create_htmlCollection(v,function(y){return y._namespace===g}):l.create_htmlCollection(v,function(y){return y._localName===p&&y._namespace===g})},n.node_listOfElementsWithClassNames=function(g,p){var v=f.orderedSet_parse(g);if(v.size===0)return l.create_htmlCollection(p,function(){return!1});var y=p._nodeDocument._mode!=="quirks";return l.create_htmlCollection(p,function(m){var w=m.classList;return f.orderedSet_contains(w._tokenSet,v,y)})},n.node_locateANamespacePrefix=function g(p,v){if(p._namespace===v&&p._namespacePrefix!==null)return p._namespacePrefix;for(var y=0;y=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(9),l=i(29),f=i(17),u=i(107),d=i(37);n.text_contiguousTextNodes=function(h,g){var p;return g===void 0&&(g=!1),(p={})[Symbol.iterator]=function(){for(var v=h;v&&s.Guard.isTextNode(v._previousSibling);)v=v._previousSibling;return{next:function(){if(v&&!g&&v===h&&(v=s.Guard.isTextNode(v._nextSibling)?v._nextSibling:null),v===null)return{done:!0,value:null};var y={done:!1,value:v};return v=s.Guard.isTextNode(v._nextSibling)?v._nextSibling:null,y}}},p},n.text_contiguousExclusiveTextNodes=function(h,g){var p;return g===void 0&&(g=!1),(p={})[Symbol.iterator]=function(){for(var v=h;v&&s.Guard.isExclusiveTextNode(v._previousSibling);)v=v._previousSibling;return{next:function(){if(v&&!g&&v===h&&(v=s.Guard.isExclusiveTextNode(v._nextSibling)?v._nextSibling:null),v===null)return{done:!0,value:null};var y={done:!1,value:v};return v=s.Guard.isExclusiveTextNode(v._nextSibling)?v._nextSibling:null,y}}},p},n.text_descendantTextContent=function(h){for(var g="",p=f.tree_getFirstDescendantNode(h,!1,!1,function(v){return s.Guard.isTextNode(v)});p!==null;)g+=p._data,p=f.tree_getNextDescendantNode(h,p,!1,!1,function(v){return s.Guard.isTextNode(v)});return g},n.text_split=function(h,g){var p,v,y=h._data.length;if(g>y)throw new c.IndexSizeError;var m=y-g,w=u.characterData_substringData(h,g,m),x=l.create_text(h._nodeDocument,w),C=h._parent;if(C!==null){d.mutation_insert(x,C,h._nextSibling);try{for(var S=o(a.dom.rangeList),_=S.next();!_.done;_=S.next()){var T=_.value;T._start[0]===h&&T._start[1]>g&&(T._start[0]=x,T._start[1]-=g),T._end[0]===h&&T._end[1]>g&&(T._end[0]=x,T._end[1]-=g);var E=f.tree_index(h);T._start[0]===C&&T._start[1]===E+1&&T._start[1]++,T._end[0]===C&&T._end[1]===E+1&&T._end[1]++}}catch(D){p={error:D}}finally{try{_&&!_.done&&(v=S.return)&&v.call(S)}finally{if(p)throw p.error}}}return u.characterData_replaceData(h,g,m,""),x}},function(r,n,i){var o=i(4),a=i(41),s=i(24),c=i(48),l=[].join,f=a!=Object,u=c("join",",");o({target:"Array",proto:!0,forced:f||!u},{join:function(d){return l.call(s(this),d===void 0?",":d)}})},function(r,n,i){var o=i(4),a=i(83),s=String.fromCharCode,c=String.fromCodePoint;o({target:"String",stat:!0,forced:!!c&&c.length!=1},{fromCodePoint:function(l){for(var f,u=[],d=arguments.length,h=0;d>h;){if(f=+arguments[h++],a(f,1114111)!==f)throw RangeError(f+" is not a valid code point");u.push(f<65536?s(f):s(55296+((f-=65536)>>10),f%1024+56320))}return u.join("")}})},function(r,n,i){var o=this&&this.__read||function(c,l){var f=typeof Symbol=="function"&&c[Symbol.iterator];if(!f)return c;var u,d,h=f.call(c),g=[];try{for(;(l===void 0||l-- >0)&&!(u=h.next()).done;)g.push(u.value)}catch(p){d={error:p}}finally{try{u&&!u.done&&(f=h.return)&&f.call(h)}finally{if(d)throw d.error}}return g};Object.defineProperty(n,"__esModule",{value:!0});var a=i(111),s=function(){function c(l,f){this._options={skipWhitespaceOnlyText:!1},this.err={line:-1,col:-1,index:-1,str:""},this._str=l,this._index=0,this._length=l.length,f&&(this._options.skipWhitespaceOnlyText=f.skipWhitespaceOnlyText||!1)}return c.prototype.nextToken=function(){if(this.eof())return{type:a.TokenType.EOF};var l=this.skipIfStartsWith("<")?this.openBracket():this.text();return this._options.skipWhitespaceOnlyText&&l.type===a.TokenType.Text&&c.isWhiteSpaceToken(l)&&(l=this.nextToken()),l},c.prototype.openBracket=function(){return this.skipIfStartsWith("?")?this.skipIfStartsWith("xml")?c.isSpace(this._str[this._index])?this.declaration():(this.seek(-3),this.pi()):this.pi():this.skipIfStartsWith("!")?this.skipIfStartsWith("--")?this.comment():this.skipIfStartsWith("[CDATA[")?this.cdata():this.skipIfStartsWith("DOCTYPE")?this.doctype():void this.throwError("Invalid '!' in opening tag."):this.skipIfStartsWith("/")?this.closeTag():this.openTag()},c.prototype.declaration=function(){for(var l="",f="",u="";!this.eof();){if(this.skipSpace(),this.skipIfStartsWith("?>"))return{type:a.TokenType.Declaration,version:l,encoding:f,standalone:u};var d=o(this.attribute(),2),h=d[0],g=d[1];h==="version"?l=g:h==="encoding"?f=g:h==="standalone"?u=g:this.throwError("Invalid attribute name: "+h)}this.throwError("Missing declaration end symbol `?>`")},c.prototype.doctype=function(){var l="",f="";this.skipSpace();var u=this.takeUntil2("[",">",!0);return this.skipSpace(),this.skipIfStartsWith("PUBLIC")?(l=this.quotedString(),f=this.quotedString()):this.skipIfStartsWith("SYSTEM")&&(f=this.quotedString()),this.skipSpace(),this.skipIfStartsWith("[")&&(this.skipUntil("]"),this.skipIfStartsWith("]")||this.throwError("Missing end bracket of DTD internal subset")),this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing doctype end symbol `>`"),{type:a.TokenType.DocType,name:u,pubId:l,sysId:f}},c.prototype.pi=function(){var l=this.takeUntilStartsWith("?>",!0);if(this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.skipSpace(),this.skipIfStartsWith("?>"))return{type:a.TokenType.PI,target:l,data:""};var f=this.takeUntilStartsWith("?>");return this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.seek(2),{type:a.TokenType.PI,target:l,data:f}},c.prototype.text=function(){var l=this.takeUntil("<");return{type:a.TokenType.Text,data:l}},c.prototype.comment=function(){var l=this.takeUntilStartsWith("-->");return this.eof()&&this.throwError("Missing comment end symbol `-->`"),this.seek(3),{type:a.TokenType.Comment,data:l}},c.prototype.cdata=function(){var l=this.takeUntilStartsWith("]]>");return this.eof()&&this.throwError("Missing CDATA end symbol `]>`"),this.seek(3),{type:a.TokenType.CDATA,data:l}},c.prototype.openTag=function(){this.skipSpace();var l=this.takeUntil2(">","/",!0);if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:a.TokenType.Element,name:l,attributes:[],selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:a.TokenType.Element,name:l,attributes:[],selfClosing:!0};for(var f=[];!this.eof();){if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:a.TokenType.Element,name:l,attributes:f,selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:a.TokenType.Element,name:l,attributes:f,selfClosing:!0};var u=this.attribute();f.push(u)}this.throwError("Missing opening element tag end symbol `>`")},c.prototype.closeTag=function(){this.skipSpace();var l=this.takeUntil(">",!0);return this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing closing element tag end symbol `>`"),{type:a.TokenType.ClosingTag,name:l}},c.prototype.attribute=function(){this.skipSpace();var l=this.takeUntil("=",!0);return this.skipSpace(),this.skipIfStartsWith("=")||this.throwError("Missing equals sign before attribute value"),[l,this.quotedString()]},c.prototype.quotedString=function(){this.skipSpace();var l=this.take(1);c.isQuote(l)||this.throwError("Missing start quote character before quoted value");var f=this.takeUntil(l);return this.skipIfStartsWith(l)||this.throwError("Missing end quote character after quoted value"),f},c.prototype.eof=function(){return this._index>=this._length},c.prototype.skipIfStartsWith=function(l){var f=l.length;if(f===1)return this._str[this._index]===l&&(this._index++,!0);for(var u=0;uthis._length&&(this._index=this._length)},c.prototype.skipSpace=function(){for(;!this.eof()&&c.isSpace(this._str[this._index]);)this._index++},c.prototype.take=function(l){if(l===1)return this._str[this._index++];var f=this._index;return this.seek(l),this._str.slice(f,this._index)},c.prototype.takeUntil=function(l,f){f===void 0&&(f=!1);for(var u=this._index;this._index=l())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+l().toString(16)+" bytes");return 0|B}function y(B,O){if(u.isBuffer(B))return B.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(B)||B instanceof ArrayBuffer))return B.byteLength;typeof B!="string"&&(B=""+B);var z=B.length;if(z===0)return 0;for(var W=!1;;)switch(O){case"ascii":case"latin1":case"binary":return z;case"utf8":case"utf-8":case void 0:return Ee(B).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*z;case"hex":return z>>>1;case"base64":return Oe(B).length;default:if(W)return Ee(B).length;O=(""+O).toLowerCase(),W=!0}}function m(B,O,z){var W=!1;if((O===void 0||O<0)&&(O=0),O>this.length||((z===void 0||z>this.length)&&(z=this.length),z<=0)||(z>>>=0)<=(O>>>=0))return"";for(B||(B="utf8");;)switch(B){case"hex":return V(this,O,z);case"utf8":case"utf-8":return P(this,O,z);case"ascii":return M(this,O,z);case"latin1":case"binary":return L(this,O,z);case"base64":return I(this,O,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,O,z);default:if(W)throw new TypeError("Unknown encoding: "+B);B=(B+"").toLowerCase(),W=!0}}function w(B,O,z){var W=B[O];B[O]=B[z],B[z]=W}function x(B,O,z,W,K){if(B.length===0)return-1;if(typeof z=="string"?(W=z,z=0):z>2147483647?z=2147483647:z<-2147483648&&(z=-2147483648),z=+z,isNaN(z)&&(z=K?0:B.length-1),z<0&&(z=B.length+z),z>=B.length){if(K)return-1;z=B.length-1}else if(z<0){if(!K)return-1;z=0}if(typeof O=="string"&&(O=u.from(O,W)),u.isBuffer(O))return O.length===0?-1:C(B,O,z,W,K);if(typeof O=="number")return O&=255,u.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?K?Uint8Array.prototype.indexOf.call(B,O,z):Uint8Array.prototype.lastIndexOf.call(B,O,z):C(B,[O],z,W,K);throw new TypeError("val must be string, number or Buffer")}function C(B,O,z,W,K){var Z,ee=1,xe=B.length,De=O.length;if(W!==void 0&&((W=String(W).toLowerCase())==="ucs2"||W==="ucs-2"||W==="utf16le"||W==="utf-16le")){if(B.length<2||O.length<2)return-1;ee=2,xe/=2,De/=2,z/=2}function Ne(ye,se){return ee===1?ye[se]:ye.readUInt16BE(se*ee)}if(K){var $e=-1;for(Z=z;Zxe&&(z=xe-De),Z=z;Z>=0;Z--){for(var ie=!0,ae=0;aeK&&(W=K):W=K;var Z=O.length;if(Z%2!=0)throw new TypeError("Invalid hex string");W>Z/2&&(W=Z/2);for(var ee=0;ee>8,De=ee%256,Ne.push(De),Ne.push(xe);return Ne}(O,B.length-z),B,z,W)}function I(B,O,z){return O===0&&z===B.length?a.fromByteArray(B):a.fromByteArray(B.slice(O,z))}function P(B,O,z){z=Math.min(B.length,z);for(var W=[],K=O;K239?4:Ne>223?3:Ne>191?2:1;if(K+ie<=z)switch(ie){case 1:Ne<128&&($e=Ne);break;case 2:(192&(Z=B[K+1]))==128&&(De=(31&Ne)<<6|63&Z)>127&&($e=De);break;case 3:Z=B[K+1],ee=B[K+2],(192&Z)==128&&(192&ee)==128&&(De=(15&Ne)<<12|(63&Z)<<6|63&ee)>2047&&(De<55296||De>57343)&&($e=De);break;case 4:Z=B[K+1],ee=B[K+2],xe=B[K+3],(192&Z)==128&&(192&ee)==128&&(192&xe)==128&&(De=(15&Ne)<<18|(63&Z)<<12|(63&ee)<<6|63&xe)>65535&&De<1114112&&($e=De)}$e===null?($e=65533,ie=1):$e>65535&&($e-=65536,W.push($e>>>10&1023|55296),$e=56320|1023&$e),W.push($e),K+=ie}return function(ae){var ye=ae.length;if(ye<=4096)return String.fromCharCode.apply(String,ae);for(var se="",ge=0;ge0&&(B=this.toString("hex",0,O).match(/.{2}/g).join(" "),this.length>O&&(B+=" ... ")),""},u.prototype.compare=function(B,O,z,W,K){if(!u.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(O===void 0&&(O=0),z===void 0&&(z=B?B.length:0),W===void 0&&(W=0),K===void 0&&(K=this.length),O<0||z>B.length||W<0||K>this.length)throw new RangeError("out of range index");if(W>=K&&O>=z)return 0;if(W>=K)return-1;if(O>=z)return 1;if(this===B)return 0;for(var Z=(K>>>=0)-(W>>>=0),ee=(z>>>=0)-(O>>>=0),xe=Math.min(Z,ee),De=this.slice(W,K),Ne=B.slice(O,z),$e=0;$eK)&&(z=K),B.length>0&&(z<0||O<0)||O>this.length)throw new RangeError("Attempt to write outside buffer bounds");W||(W="utf8");for(var Z=!1;;)switch(W){case"hex":return S(this,B,O,z);case"utf8":case"utf-8":return _(this,B,O,z);case"ascii":return T(this,B,O,z);case"latin1":case"binary":return E(this,B,O,z);case"base64":return D(this,B,O,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,B,O,z);default:if(Z)throw new TypeError("Unknown encoding: "+W);W=(""+W).toLowerCase(),Z=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(B,O,z){var W="";z=Math.min(B.length,z);for(var K=O;KW)&&(z=W);for(var K="",Z=O;Zz)throw new RangeError("Trying to access beyond buffer length")}function k(B,O,z,W,K,Z){if(!u.isBuffer(B))throw new TypeError('"buffer" argument must be a Buffer instance');if(O>K||OB.length)throw new RangeError("Index out of range")}function F(B,O,z,W){O<0&&(O=65535+O+1);for(var K=0,Z=Math.min(B.length-z,2);K>>8*(W?K:1-K)}function j(B,O,z,W){O<0&&(O=4294967295+O+1);for(var K=0,Z=Math.min(B.length-z,4);K>>8*(W?K:3-K)&255}function Y(B,O,z,W,K,Z){if(z+W>B.length)throw new RangeError("Index out of range");if(z<0)throw new RangeError("Index out of range")}function re(B,O,z,W,K){return K||Y(B,0,z,4),s.write(B,O,z,W,23,4),z+4}function ue(B,O,z,W,K){return K||Y(B,0,z,8),s.write(B,O,z,W,52,8),z+8}u.prototype.slice=function(B,O){var z,W=this.length;if((B=~~B)<0?(B+=W)<0&&(B=0):B>W&&(B=W),(O=O===void 0?W:~~O)<0?(O+=W)<0&&(O=0):O>W&&(O=W),O0&&(K*=256);)W+=this[B+--O]*K;return W},u.prototype.readUInt8=function(B,O){return O||A(B,1,this.length),this[B]},u.prototype.readUInt16LE=function(B,O){return O||A(B,2,this.length),this[B]|this[B+1]<<8},u.prototype.readUInt16BE=function(B,O){return O||A(B,2,this.length),this[B]<<8|this[B+1]},u.prototype.readUInt32LE=function(B,O){return O||A(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},u.prototype.readUInt32BE=function(B,O){return O||A(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},u.prototype.readIntLE=function(B,O,z){B|=0,O|=0,z||A(B,O,this.length);for(var W=this[B],K=1,Z=0;++Z=(K*=128)&&(W-=Math.pow(2,8*O)),W},u.prototype.readIntBE=function(B,O,z){B|=0,O|=0,z||A(B,O,this.length);for(var W=O,K=1,Z=this[B+--W];W>0&&(K*=256);)Z+=this[B+--W]*K;return Z>=(K*=128)&&(Z-=Math.pow(2,8*O)),Z},u.prototype.readInt8=function(B,O){return O||A(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},u.prototype.readInt16LE=function(B,O){O||A(B,2,this.length);var z=this[B]|this[B+1]<<8;return 32768&z?4294901760|z:z},u.prototype.readInt16BE=function(B,O){O||A(B,2,this.length);var z=this[B+1]|this[B]<<8;return 32768&z?4294901760|z:z},u.prototype.readInt32LE=function(B,O){return O||A(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},u.prototype.readInt32BE=function(B,O){return O||A(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},u.prototype.readFloatLE=function(B,O){return O||A(B,4,this.length),s.read(this,B,!0,23,4)},u.prototype.readFloatBE=function(B,O){return O||A(B,4,this.length),s.read(this,B,!1,23,4)},u.prototype.readDoubleLE=function(B,O){return O||A(B,8,this.length),s.read(this,B,!0,52,8)},u.prototype.readDoubleBE=function(B,O){return O||A(B,8,this.length),s.read(this,B,!1,52,8)},u.prototype.writeUIntLE=function(B,O,z,W){B=+B,O|=0,z|=0,W||k(this,B,O,z,Math.pow(2,8*z)-1,0);var K=1,Z=0;for(this[O]=255&B;++Z=0&&(Z*=256);)this[O+K]=B/Z&255;return O+z},u.prototype.writeUInt8=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,1,255,0),u.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[O]=255&B,O+1},u.prototype.writeUInt16LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8):F(this,B,O,!0),O+2},u.prototype.writeUInt16BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>8,this[O+1]=255&B):F(this,B,O,!1),O+2},u.prototype.writeUInt32LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[O+3]=B>>>24,this[O+2]=B>>>16,this[O+1]=B>>>8,this[O]=255&B):j(this,B,O,!0),O+4},u.prototype.writeUInt32BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>24,this[O+1]=B>>>16,this[O+2]=B>>>8,this[O+3]=255&B):j(this,B,O,!1),O+4},u.prototype.writeIntLE=function(B,O,z,W){if(B=+B,O|=0,!W){var K=Math.pow(2,8*z-1);k(this,B,O,z,K-1,-K)}var Z=0,ee=1,xe=0;for(this[O]=255&B;++Z>0)-xe&255;return O+z},u.prototype.writeIntBE=function(B,O,z,W){if(B=+B,O|=0,!W){var K=Math.pow(2,8*z-1);k(this,B,O,z,K-1,-K)}var Z=z-1,ee=1,xe=0;for(this[O+Z]=255&B;--Z>=0&&(ee*=256);)B<0&&xe===0&&this[O+Z+1]!==0&&(xe=1),this[O+Z]=(B/ee>>0)-xe&255;return O+z},u.prototype.writeInt8=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,1,127,-128),u.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[O]=255&B,O+1},u.prototype.writeInt16LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8):F(this,B,O,!0),O+2},u.prototype.writeInt16BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>8,this[O+1]=255&B):F(this,B,O,!1),O+2},u.prototype.writeInt32LE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[O]=255&B,this[O+1]=B>>>8,this[O+2]=B>>>16,this[O+3]=B>>>24):j(this,B,O,!0),O+4},u.prototype.writeInt32BE=function(B,O,z){return B=+B,O|=0,z||k(this,B,O,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),u.TYPED_ARRAY_SUPPORT?(this[O]=B>>>24,this[O+1]=B>>>16,this[O+2]=B>>>8,this[O+3]=255&B):j(this,B,O,!1),O+4},u.prototype.writeFloatLE=function(B,O,z){return re(this,B,O,!0,z)},u.prototype.writeFloatBE=function(B,O,z){return re(this,B,O,!1,z)},u.prototype.writeDoubleLE=function(B,O,z){return ue(this,B,O,!0,z)},u.prototype.writeDoubleBE=function(B,O,z){return ue(this,B,O,!1,z)},u.prototype.copy=function(B,O,z,W){if(z||(z=0),W||W===0||(W=this.length),O>=B.length&&(O=B.length),O||(O=0),W>0&&W=this.length)throw new RangeError("sourceStart out of bounds");if(W<0)throw new RangeError("sourceEnd out of bounds");W>this.length&&(W=this.length),B.length-O=0;--K)B[K+O]=this[K+z];else if(Z<1e3||!u.TYPED_ARRAY_SUPPORT)for(K=0;K>>=0,z=z===void 0?this.length:z>>>0,B||(B=0),typeof B=="number")for(Z=O;Z55295&&z<57344){if(!K){if(z>56319){(O-=3)>-1&&Z.push(239,191,189);continue}if(ee+1===W){(O-=3)>-1&&Z.push(239,191,189);continue}K=z;continue}if(z<56320){(O-=3)>-1&&Z.push(239,191,189),K=z;continue}z=65536+(K-55296<<10|z-56320)}else K&&(O-=3)>-1&&Z.push(239,191,189);if(K=null,z<128){if((O-=1)<0)break;Z.push(z)}else if(z<2048){if((O-=2)<0)break;Z.push(z>>6|192,63&z|128)}else if(z<65536){if((O-=3)<0)break;Z.push(z>>12|224,z>>6&63|128,63&z|128)}else{if(!(z<1114112))throw new Error("Invalid code point");if((O-=4)<0)break;Z.push(z>>18|240,z>>12&63|128,z>>6&63|128,63&z|128)}}return Z}function Oe(B){return a.toByteArray(function(O){if((O=function(z){return z.trim?z.trim():z.replace(/^\s+|\s+$/g,"")}(O).replace(ce,"")).length<2)return"";for(;O.length%4!=0;)O+="=";return O}(B))}function _e(B,O,z,W){for(var K=0;K=O.length||K>=B.length);++K)O[K+z]=B[K];return K}}).call(this,i(78))},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),n.isASCIIByte=function(o){return o>=0&&o<=127}},function(r,n,i){var o=this&&this.__read||function(s,c){var l=typeof Symbol=="function"&&s[Symbol.iterator];if(!l)return s;var f,u,d=l.call(s),h=[];try{for(;(c===void 0||c-- >0)&&!(f=d.next()).done;)h.push(f.value)}catch(g){u={error:g}}finally{try{f&&!f.done&&(l=d.return)&&l.call(d)}finally{if(u)throw u.error}}return h},a=this&&this.__spread||function(){for(var s=[],c=0;c=65&&l<=90&&(s[c]=l+32)}},n.byteUppercase=function(s){for(var c=0;c=97&&l<=122&&(s[c]=l-32)}},n.byteCaseInsensitiveMatch=function(s,c){if(s.length!==c.length)return!1;for(var l=0;l=65&&f<=90&&(f+=32),u>=65&&u<=90&&(u+=32),f!==u)return!1}return!0},n.startsWith=function(s,c){for(var l=0;;){if(l>=s.length)return!1;if(l>=c.length)return!0;if(s[l]!==c[l])return!1;l++}},n.byteLessThan=function(s,c){for(var l=0;;){if(l>=s.length)return!1;if(l>=c.length)return!0;var f=s[l],u=c[l];if(fu)return!1;l++}},n.isomorphicDecode=function(s){return String.fromCodePoint.apply(String,a(s))}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(6),a=i(7),s=i(0),c=i(12),l=function(){function f(u){this._associatedDocument=u||o.dom.window.document}return f.prototype.createDocumentType=function(u,d,h){return s.namespace_validate(u),s.create_documentType(this._associatedDocument,u,d,h)},f.prototype.createDocument=function(u,d,h){h===void 0&&(h=null);var g=s.create_xmlDocument(),p=null;return d&&(p=s.document_internalCreateElementNS(g,u,d)),h&&g.appendChild(h),p&&g.appendChild(p),g._origin=this._associatedDocument._origin,u===a.namespace.HTML?g._contentType="application/xhtml+xml":u===a.namespace.SVG?g._contentType="image/svg+xml":g._contentType="application/xml",g},f.prototype.createHTMLDocument=function(u){var d=s.create_document();d._type="html",d._contentType="text/html",d.appendChild(s.create_documentType(d,"html","",""));var h=s.element_createAnElement(d,"html",a.namespace.HTML);d.appendChild(h);var g=s.element_createAnElement(d,"head",a.namespace.HTML);if(h.appendChild(g),u!==void 0){var p=s.element_createAnElement(d,"title",a.namespace.HTML);g.appendChild(p);var v=s.create_text(d,u);p.appendChild(v)}var y=s.element_createAnElement(d,"body",a.namespace.HTML);return h.appendChild(y),d._origin=this._associatedDocument._origin,d},f.prototype.hasFeature=function(){return!0},f._create=function(u){return new f(u)},f}();n.DOMImplementationImpl=l,c.idl_defineConst(l.prototype,"_ID","@oozcitak/dom")},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(70),c=i(1),l=i(0),f=function(u){function d(){var h=u.call(this)||this;return h._signalSlots=new Set,h._mutationObserverMicrotaskQueued=!1,h._mutationObservers=new Set,h._iteratorList=new c.FixedSizeSet,h._associatedDocument=l.create_document(),h}return a(d,u),Object.defineProperty(d.prototype,"document",{get:function(){return this._associatedDocument},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"event",{get:function(){return this._currentEvent},enumerable:!0,configurable:!0}),d._create=function(){return new d},d}(s.EventTargetImpl);n.WindowImpl=f},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=function(){function s(){}return s.isNode=function(c){return!!c&&c._nodeType!==void 0},s.isDocumentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Document},s.isDocumentTypeNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.DocumentType},s.isDocumentFragmentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.DocumentFragment},s.isAttrNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Attribute},s.isCharacterDataNode=function(c){if(!s.isNode(c))return!1;var l=c._nodeType;return l===o.NodeType.Text||l===o.NodeType.ProcessingInstruction||l===o.NodeType.Comment||l===o.NodeType.CData},s.isTextNode=function(c){return s.isNode(c)&&(c._nodeType===o.NodeType.Text||c._nodeType===o.NodeType.CData)},s.isExclusiveTextNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Text},s.isCDATASectionNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.CData},s.isCommentNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Comment},s.isProcessingInstructionNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.ProcessingInstruction},s.isElementNode=function(c){return s.isNode(c)&&c._nodeType===o.NodeType.Element},s.isCustomElementNode=function(c){return s.isElementNode(c)&&c._customElementState==="custom"},s.isShadowRoot=function(c){return!!c&&c.host!==void 0},s.isMouseEvent=function(c){return!!c&&c.screenX!==void 0&&c.screenY!=null},s.isSlotable=function(c){return!!c&&c._name!==void 0&&c._assignedSlot!==void 0&&(s.isTextNode(c)||s.isElementNode(c))},s.isSlot=function(c){return!!c&&c._name!==void 0&&c._assignedNodes!==void 0&&s.isElementNode(c)},s.isWindow=function(c){return!!c&&c.navigator!==void 0},s.isEventListener=function(c){return!!c&&c.handleEvent!==void 0},s.isRegisteredObserver=function(c){return!!c&&c.observer!==void 0&&c.options!==void 0},s.isTransientRegisteredObserver=function(c){return!!c&&c.source!==void 0&&s.isRegisteredObserver(c)},s}();n.Guard=a},function(r,n,i){var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(){return c.call(this)||this}return a(l,c),l}(i(98).DocumentImpl);n.XMLDocumentImpl=s},function(r,n,i){var o=this&&this.__values||function(W){var K=typeof Symbol=="function"&&Symbol.iterator,Z=K&&W[K],ee=0;if(Z)return Z.call(W);if(W&&typeof W.length=="number")return{next:function(){return W&&ee>=W.length&&(W=void 0),{value:W&&W[ee++],done:!W}}};throw new TypeError(K?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(W,K){var Z=typeof Symbol=="function"&&W[Symbol.iterator];if(!Z)return W;var ee,xe,De=Z.call(W),Ne=[];try{for(;(K===void 0||K-- >0)&&!(ee=De.next()).done;)Ne.push(ee.value)}catch($e){xe={error:$e}}finally{try{ee&&!ee.done&&(Z=De.return)&&Z.call(De)}finally{if(xe)throw xe.error}}return Ne};Object.defineProperty(n,"__esModule",{value:!0});var s,c=i(1),l=i(243),f=i(7),u=i(244),d={ftp:21,file:null,http:80,https:443,ws:80,wss:443},h=/[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,g=/[ "<>`]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,p=/[ "<>`#?{}]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,v=/[ "<>`#?{}/:;=@\[\]\\\^\|]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,y=/[0-9A-Za-z!\$&-\/:;=\?@_~\xA0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uD83E\uD840-\uD87E\uD880-\uD8BE\uD8C0-\uD8FE\uD900-\uD93E\uD940-\uD97E\uD980-\uD9BE\uD9C0-\uD9FE\uDA00-\uDA3E\uDA40-\uDA7E\uDA80-\uDABE\uDAC0-\uDAFE\uDB00-\uDB3E\uDB40-\uDB7E\uDB80-\uDBBE\uDBC0-\uDBFE][\uDC00-\uDFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDC00-\uDFFD]/,m=/[\0\t\f\r #%/:?@\[\\\]]/;function w(W){s!==void 0&&s.call(null,"Validation Error: "+W)}function x(){return{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null}}function C(W){return W in d}function S(W){return C(W.scheme)}function _(W){return d[W]||null}function T(W){return W.username!==""||W.password!==""}function E(W,K){var Z,ee;K===void 0&&(K=!1);var xe=W.scheme+":";if(W.host!==null?(xe+="//",T(W)&&(xe+=W.username,W.password!==""&&(xe+=":"+W.password),xe+="@"),xe+=D(W.host),W.port!==null&&(xe+=":"+W.port)):W.host===null&&W.scheme==="file"&&(xe+="//"),W._cannotBeABaseURLFlag)xe+=W.path[0];else try{for(var De=o(W.path),Ne=De.next();!Ne.done;Ne=De.next())xe+="/"+Ne.value}catch($e){Z={error:$e}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}return W.query!==null&&(xe+="?"+W.query),K||W.fragment===null||(xe+="#"+W.fragment),xe}function D(W){return c.isNumber(W)?b(W):c.isArray(W)?"["+I(W)+"]":W}function b(W){for(var K="",Z=W,ee=1;ee<=4;ee++)K=(Z%256).toString()+K,ee!==4&&(K="."+K),Z=Math.floor(Z/256);return K}function I(W){for(var K="",Z=null,ee=-1,xe=0,De=0,Ne=0;Ne<8;Ne++)if(W[Ne]===0){xe=1;for(var $e=Ne+1;$e<8&&W[$e]===0;$e++)xe++;xe>De&&(De=xe,ee=Ne)}De>1&&(Z=ee);for(var ie=!1,ae=0;ae<8;ae++)ie&&W[ae]===0||(ie&&(ie=!1),Z!==ae?(K+=W[ae].toString(16),ae!==7&&(K+=":")):(K+=ae===0?"::":":",ie=!0));return K}function P(W,K,Z,ee,xe){var De,Ne,$e,ie;if(ee===void 0){ee={scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null};var ae=/^[\u0000-\u001F\u0020]+/,ye=/[\u0000-\u001F\u0020]+$/;(ae.test(W)||ye.test(W))&&w("Input string contains leading or trailing control characters or space."),W=(W=W.replace(ae,"")).replace(ye,"")}var se=/[\u0009\u000A\u000D]/g;se.test(W)&&w("Input string contains tab or newline characters."),W=W.replace(se,"");var ge=xe===void 0?l.ParserState.SchemeStart:xe;K===void 0&&(K=null);for(var Fe=Z===void 0||Z==="replacement"||Z==="UTF-16BE"||Z==="UTF-16LE"?"UTF-8":Z,oe="",ht=!1,wt=!1,gt=!1,Ie=new c.StringWalker(W);;){switch(ge){case l.ParserState.SchemeStart:if(f.codePoint.ASCIIAlpha.test(Ie.c()))oe+=Ie.c().toLowerCase(),ge=l.ParserState.Scheme;else{if(xe!==void 0)return w("Invalid scheme start character."),null;ge=l.ParserState.NoScheme,Ie.pointer--}break;case l.ParserState.Scheme:if(f.codePoint.ASCIIAlphanumeric.test(Ie.c())||Ie.c()==="+"||Ie.c()==="-"||Ie.c()===".")oe+=Ie.c().toLowerCase();else{if(Ie.c()!==":"){if(xe===void 0){oe="",ge=l.ParserState.NoScheme,Ie.pointer=0;continue}return w("Invalid input string."),null}if(xe!==void 0&&(C(ee.scheme)&&!C(oe)||!C(ee.scheme)&&C(oe)||(T(ee)||ee.port!==null)&&oe==="file"||ee.scheme==="file"&&(ee.host===""||ee.host===null)))return ee;if(ee.scheme=oe,xe!==void 0)return ee.port===_(ee.scheme)&&(ee.port=null),ee;oe="",ee.scheme==="file"?(Ie.remaining().startsWith("//")||w("Invalid file URL scheme, '//' expected."),ge=l.ParserState.File):S(ee)&&K!==null&&K.scheme===ee.scheme?ge=l.ParserState.SpecialRelativeOrAuthority:S(ee)?ge=l.ParserState.SpecialAuthoritySlashes:Ie.remaining().startsWith("/")?(ge=l.ParserState.PathOrAuthority,Ie.pointer++):(ee._cannotBeABaseURLFlag=!0,ee.path.push(""),ge=l.ParserState.CannotBeABaseURLPath)}break;case l.ParserState.NoScheme:if(K===null||K._cannotBeABaseURLFlag&&Ie.c()!=="#")return w("Invalid input string."),null;K._cannotBeABaseURLFlag&&Ie.c()==="#"?(ee.scheme=K.scheme,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ee._cannotBeABaseURLFlag=!0,ge=l.ParserState.Fragment):K.scheme!=="file"?(ge=l.ParserState.Relative,Ie.pointer--):(ge=l.ParserState.File,Ie.pointer--);break;case l.ParserState.SpecialRelativeOrAuthority:Ie.c()==="/"&&Ie.remaining().startsWith("/")?(ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer++):(w("Invalid input string."),ge=l.ParserState.Relative,Ie.pointer--);break;case l.ParserState.PathOrAuthority:Ie.c()==="/"?ge=l.ParserState.Authority:(ge=l.ParserState.Path,Ie.pointer--);break;case l.ParserState.Relative:if(K===null)throw new Error("Invalid parser state. Base URL is null.");switch(ee.scheme=K.scheme,Ie.c()){case"":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query=K.query;break;case"/":ge=l.ParserState.RelativeSlash;break;case"?":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query="",ge=l.ParserState.Query;break;case"#":ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ge=l.ParserState.Fragment;break;default:S(ee)&&Ie.c()==="\\"?(w("Invalid input string."),ge=l.ParserState.RelativeSlash):(ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ee.path=f.list.clone(K.path),ee.path.length!==0&&ee.path.splice(ee.path.length-1,1),ge=l.ParserState.Path,Ie.pointer--)}break;case l.ParserState.RelativeSlash:if(!S(ee)||Ie.c()!=="/"&&Ie.c()!=="\\")if(Ie.c()==="/")ge=l.ParserState.Authority;else{if(K===null)throw new Error("Invalid parser state. Base URL is null.");ee.username=K.username,ee.password=K.password,ee.host=K.host,ee.port=K.port,ge=l.ParserState.Path,Ie.pointer--}else Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.SpecialAuthorityIgnoreSlashes;break;case l.ParserState.SpecialAuthoritySlashes:Ie.c()==="/"&&Ie.remaining().startsWith("/")?(ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer++):(w("Expected '//'."),ge=l.ParserState.SpecialAuthorityIgnoreSlashes,Ie.pointer--);break;case l.ParserState.SpecialAuthorityIgnoreSlashes:Ie.c()!=="/"&&Ie.c()!=="\\"?(ge=l.ParserState.Authority,Ie.pointer--):w("Unexpected '/' or '\\'.");break;case l.ParserState.Authority:if(Ie.c()==="@"){w("Unexpected '@'."),ht&&(oe="%40"+oe),ht=!0;try{for(var je=(De=void 0,o(oe)),nt=je.next();!nt.done;nt=je.next()){var rt=nt.value;if(rt!==":"||gt){var dt=_e(rt,v);gt?ee.password+=dt:ee.username+=dt}else gt=!0}}catch(bn){De={error:bn}}finally{try{nt&&!nt.done&&(Ne=je.return)&&Ne.call(je)}finally{if(De)throw De.error}}oe=""}else if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"){if(ht&&oe==="")return w("Invalid input string."),null;Ie.pointer-=oe.length+1,oe="",ge=l.ParserState.Host}else oe+=Ie.c();break;case l.ParserState.Host:case l.ParserState.Hostname:if(xe!==void 0&&ee.scheme==="file")Ie.pointer--,ge=l.ParserState.FileHost;else if(Ie.c()!==":"||wt)if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"){if(Ie.pointer--,S(ee)&&oe==="")return w("Invalid input string."),null;if(xe!==void 0&&oe===""&&(T(ee)||ee.port!==null))return w("Invalid input string."),ee;if((xt=F(oe,!S(ee)))===null)return null;if(ee.host=xt,oe="",ge=l.ParserState.PathStart,xe!==void 0)return ee}else Ie.c()==="["&&(wt=!0),Ie.c()==="]"&&(wt=!1),oe+=Ie.c();else{if(oe==="")return w("Invalid input string."),null;if((xt=F(oe,!S(ee)))===null)return null;if(ee.host=xt,oe="",ge=l.ParserState.Port,xe===l.ParserState.Hostname)return ee}break;case l.ParserState.Port:if(f.codePoint.ASCIIDigit.test(Ie.c()))oe+=Ie.c();else{if(!(Ie.c()===""||Ie.c()==="/"||Ie.c()==="?"||Ie.c()==="#"||S(ee)&&Ie.c()==="\\"||xe))return w("Invalid input string."),null;if(oe!==""&&oe!==""){var Lt=parseInt(oe,10);if(Lt>Math.pow(2,16)-1)return w("Invalid port number."),null;ee.port=Lt===_(ee.scheme)?null:Lt,oe=""}if(xe!==void 0)return ee;ge=l.ParserState.PathStart,Ie.pointer--}break;case l.ParserState.File:if(ee.scheme="file",Ie.c()==="/"||Ie.c()==="\\")Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.FileSlash;else if(K!==null&&K.scheme==="file")switch(Ie.c()){case"":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query=K.query;break;case"?":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query="",ge=l.ParserState.Query;break;case"#":ee.host=K.host,ee.path=f.list.clone(K.path),ee.query=K.query,ee.fragment="",ge=l.ParserState.Fragment;break;default:k(Ie.substring())?w("Unexpected windows drive letter in input string."):(ee.host=K.host,ee.path=f.list.clone(K.path),V(ee)),ge=l.ParserState.Path,Ie.pointer--}else ge=l.ParserState.Path,Ie.pointer--;break;case l.ParserState.FileSlash:Ie.c()==="/"||Ie.c()==="\\"?(Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.FileHost):(K===null||K.scheme!=="file"||k(Ie.substring())||(G(K.path[0])?ee.path.push(K.path[0]):ee.host=K.host),ge=l.ParserState.Path,Ie.pointer--);break;case l.ParserState.FileHost:if(Ie.c()===""||Ie.c()==="/"||Ie.c()==="\\"||Ie.c()==="?"||Ie.c()==="#")if(Ie.pointer--,xe===void 0&&A(oe))w("Unexpected windows drive letter in input string."),ge=l.ParserState.Path;else if(oe===""){if(ee.host="",xe!==void 0)return ee;ge=l.ParserState.PathStart}else{var xt;if((xt=F(oe,!S(ee)))===null)return null;if(xt==="localhost"&&(xt=""),ee.host=xt,xe!==void 0)return ee;oe="",ge=l.ParserState.PathStart}else oe+=Ie.c();break;case l.ParserState.PathStart:S(ee)?(Ie.c()==="\\"&&w("Invalid input string."),ge=l.ParserState.Path,Ie.c()!=="/"&&Ie.c()!=="\\"&&Ie.pointer--):xe===void 0&&Ie.c()==="?"?(ee.query="",ge=l.ParserState.Query):xe===void 0&&Ie.c()==="#"?(ee.fragment="",ge=l.ParserState.Fragment):Ie.c()!==""&&(ge=l.ParserState.Path,Ie.c()!=="/"&&Ie.pointer--);break;case l.ParserState.Path:if(Ie.c()===""||Ie.c()==="/"||S(ee)&&Ie.c()==="\\"||xe===void 0&&(Ie.c()==="?"||Ie.c()==="#")){if(S(ee)&&Ie.c()==="\\"&&w("Invalid input string."),L(oe))V(ee),Ie.c()==="/"||S(ee)&&Ie.c()==="\\"||ee.path.push("");else if(!M(oe)||Ie.c()==="/"||S(ee)&&Ie.c()==="\\"){if(!M(oe)){if(ee.scheme==="file"&&ee.path.length===0&&A(oe)){ee.host!==null&&ee.host!==""&&(w("Invalid input string."),ee.host="");var Ft=Array.from(oe);oe=Ft.slice(0,1)+":"+Ft.slice(2)}ee.path.push(oe)}}else ee.path.push("");if(oe="",ee.scheme==="file"&&(Ie.c()===""||Ie.c()==="?"||Ie.c()==="#"))for(;ee.path.length>1&&ee.path[0]==="";)w("Invalid input string."),ee.path.splice(0,1);Ie.c()==="?"&&(ee.query="",ge=l.ParserState.Query),Ie.c()==="#"&&(ee.fragment="",ge=l.ParserState.Fragment)}else y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),oe+=_e(Ie.c(),p);break;case l.ParserState.CannotBeABaseURLPath:Ie.c()==="?"?(ee.query="",ge=l.ParserState.Query):Ie.c()==="#"?(ee.fragment="",ge=l.ParserState.Fragment):(Ie.c()===""||y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),Ie.c()!==""&&(ee.path[0]+=_e(Ie.c(),h)));break;case l.ParserState.Query:if(Fe==="UTF-8"||S(ee)&&ee.scheme!=="ws"&&ee.scheme!=="wss"||(Fe="UTF-8"),xe===void 0&&Ie.c()==="#")ee.fragment="",ge=l.ParserState.Fragment;else if(Ie.c()!==""){if(y.test(Ie.c())||Ie.c()==="%"||w("Character is not a URL code point or a percent encoded character."),Ie.c()!=="%"||/^[0-9a-fA-F][0-9a-fA-F]/.test(Ie.remaining())||w("Percent encoded character must be followed by two hex digits."),Fe.toUpperCase()!=="UTF-8")throw new Error("Only UTF-8 encoding is supported.");var jt=c.utf8Encode(Ie.c());if(jt.length>=3&&jt[0]===38&&jt[1]===35&&jt[jt.length-1]===59)jt=jt.subarray(2,jt.length-1),ee.query+="%26%23"+f.byteSequence.isomorphicDecode(jt)+"%3B";else try{for(var Pn=($e=void 0,o(jt)),$n=Pn.next();!$n.done;$n=Pn.next()){var fn=$n.value;fn<33||fn>126||fn===34||fn===35||fn===60||fn===62||fn===39&&S(ee)?ee.query+=pe(fn):ee.query+=String.fromCharCode(fn)}}catch(bn){$e={error:bn}}finally{try{$n&&!$n.done&&(ie=Pn.return)&&ie.call(Pn)}finally{if($e)throw $e.error}}}break;case l.ParserState.Fragment:Ie.c()===""||(Ie.c()==="\0"?w("NULL character in input string."):(y.test(Ie.c())||Ie.c()==="%"||w("Unexpected character in fragment string."),Ie.c()!=="%"||/^[A-Za-z0-9][A-Za-z0-9]/.test(Ie.remaining())||w("Unexpected character in fragment string."),ee.fragment+=_e(Ie.c(),g)))}if(Ie.eof)break;Ie.pointer++}return ee}function M(W){return W==="."||W.toLowerCase()==="%2e"}function L(W){var K=W.toLowerCase();return K===".."||K===".%2e"||K==="%2e."||K==="%2e%2e"}function V(W){var K=W.path;K.length!==0&&(W.scheme==="file"&&K.length===1&&G(K[0])||W.path.splice(W.path.length-1,1))}function G(W){return W.length>=2&&f.codePoint.ASCIIAlpha.test(W[0])&&W[1]===":"}function A(W){return W.length>=2&&f.codePoint.ASCIIAlpha.test(W[0])&&(W[1]===":"||W[1]==="|")}function k(W){return W.length>=2&&A(W)&&(W.length===2||W[2]==="/"||W[2]==="\\"||W[2]==="?"||W[2]==="#")}function F(W,K){if(K===void 0&&(K=!1),W.startsWith("["))return W.endsWith("]")?re(W.substring(1,W.length-1)):(w("Expected ']' after '['."),null);if(K)return ue(W);var Z=z(c.utf8Decode(Oe(W)));if(Z===null||m.test(Z))return w("Invalid domain."),null;var ee=Y(Z);return ee===null||c.isNumber(ee)?ee:Z}function j(W,K){K===void 0&&(K={value:!1});var Z=10;return W.startsWith("0x")||W.startsWith("0X")?(K.value=!0,W=W.substr(2),Z=16):W.length>=2&&W[0]==="0"&&(K.value=!0,W=W.substr(1),Z=8),W===""?0:(Z===10?/^[0-9]+$/:Z===16?/^[0-9A-Fa-f]+$/:/^[0-7]+$/).test(W)?parseInt(W,Z):null}function Y(W){var K,Z,ee,xe,De={value:!1},Ne=W.split(".");if(Ne[Ne.length-1]===""&&(De.value=!0,Ne.length>1&&Ne.pop()),Ne.length>4)return W;var $e=[];try{for(var ie=o(Ne),ae=ie.next();!ae.done;ae=ie.next()){var ye=ae.value;if(ye===""||(wt=j(ye,De))===null)return W;$e.push(wt)}}catch(gt){K={error:gt}}finally{try{ae&&!ae.done&&(Z=ie.return)&&Z.call(ie)}finally{if(K)throw K.error}}De.value&&w("Invalid IP v4 address.");for(var se=0;se<$e.length;se++)if($e[se]>255&&(w("Invalid IP v4 address."),se<$e.length-1))return null;if($e[$e.length-1]>=Math.pow(256,5-$e.length))return w("Invalid IP v4 address."),null;var ge=$e[$e.length-1];$e.pop();var Fe=0;try{for(var oe=o($e),ht=oe.next();!ht.done;ht=oe.next()){var wt;ge+=(wt=ht.value)*Math.pow(256,3-Fe),Fe++}}catch(gt){ee={error:gt}}finally{try{ht&&!ht.done&&(xe=oe.return)&&xe.call(oe)}finally{if(ee)throw ee.error}}return ge}function re(W){var K,Z=[0,0,0,0,0,0,0,0],ee=0,xe=null,De=new c.StringWalker(W);if(De.c()===":"){if(!De.remaining().startsWith(":"))return w("Invalid IP v6 address."),null;De.pointer+=2,xe=ee+=1}for(;De.c()!=="";){if(ee===8)return w("Invalid IP v6 address."),null;if(De.c()!==":"){for(var Ne=0,$e=0;$e<4&&f.codePoint.ASCIIHexDigit.test(De.c());)Ne=16*Ne+parseInt(De.c(),16),De.pointer++,$e++;if(De.c()==="."){if($e===0||(De.pointer-=$e,ee>6))return w("Invalid IP v6 address."),null;for(var ie=0;De.c()!=="";){var ae=null;if(ie>0){if(!(De.c()==="."&&ie<4))return w("Invalid IP v6 address."),null;De.pointer++}if(!f.codePoint.ASCIIDigit.test(De.c()))return w("Invalid IP v6 address."),null;for(;f.codePoint.ASCIIDigit.test(De.c());){var ye=parseInt(De.c(),10);if(ae===null)ae=ye;else{if(ae===0)return w("Invalid IP v6 address."),null;ae=10*ae+ye}if(ae>255)return w("Invalid IP v6 address."),null;De.pointer++}if(ae===null)return w("Invalid IP v6 address."),null;Z[ee]=256*Z[ee]+ae,++ie!==2&&ie!==4||ee++}if(ie!==4)return w("Invalid IP v6 address."),null;break}if(De.c()===":"){if(De.pointer++,De.c()==="")return w("Invalid IP v6 address."),null}else if(De.c()!=="")return w("Invalid IP v6 address."),null;Z[ee]=Ne,ee++}else{if(xe!==null)return w("Invalid IP v6 address."),null;De.pointer++,xe=++ee}}if(xe!==null){var se=ee-xe;for(ee=7;ee!==0&&se>0;)K=a([Z[xe+se-1],Z[ee]],2),Z[ee]=K[0],Z[xe+se-1]=K[1],ee--,se--}else if(xe===null&&ee!==8)return w("Invalid IP v6 address."),null;return Z}function ue(W){var K,Z;if(/[\x00\t\f\r #/:?@\[\\\]]/.test(W))return w("Invalid host string."),null;var ee="";try{for(var xe=o(W),De=xe.next();!De.done;De=xe.next())ee+=_e(De.value,h)}catch(Ne){K={error:Ne}}finally{try{De&&!De.done&&(Z=xe.return)&&Z.call(xe)}finally{if(K)throw K.error}}return ee}function ce(W){return null}function pe(W){return"%"+("00"+W.toString(16).toUpperCase()).slice(-2)}function Ee(W){for(var K=function($e){return $e>=48&&$e<=57||$e>=65&&$e<=70||$e>=97&&$e<=102},Z=new Uint8Array(W.length),ee=0,xe=0;xe=W.length-2)Z[ee]=De,ee++;else if(De!==37||K(W[xe+1])&&K(W[xe+2])){var Ne=parseInt(c.utf8Decode(Uint8Array.of(W[xe+1],W[xe+2])),16);Z[ee]=Ne,ee++,xe+=2}else Z[ee]=De,ee++}return Z.subarray(0,ee)}function Oe(W){return Ee(c.utf8Encode(W))}function _e(W,K){var Z,ee;if(!K.test(W))return W;var xe=c.utf8Encode(W),De="";try{for(var Ne=o(xe),$e=Ne.next();!$e.done;$e=Ne.next())De+=pe($e.value)}catch(ie){Z={error:ie}}finally{try{$e&&!$e.done&&(ee=Ne.return)&&ee.call(Ne)}finally{if(Z)throw Z.error}}return De}function B(W){var K,Z,ee,xe,De=[],Ne=[];try{for(var $e=o(W),ie=$e.next();!ie.done;ie=$e.next()){var ae=ie.value;ae===38?(De.push(Uint8Array.from(Ne)),Ne=[]):Ne.push(ae)}}catch(nt){K={error:nt}}finally{try{ie&&!ie.done&&(Z=$e.return)&&Z.call($e)}finally{if(K)throw K.error}}Ne.length!==0&&De.push(Uint8Array.from(Ne));var ye=[];try{for(var se=o(De),ge=se.next();!ge.done;ge=se.next()){var Fe=ge.value;if(Fe.length!==0){for(var oe=Fe.indexOf(61),ht=oe!==-1?Fe.slice(0,oe):Fe,wt=oe!==-1?Fe.slice(oe+1):new Uint8Array,gt=0;gt=48&&Ne<=57||Ne>=65&&Ne<=90||Ne===95||Ne>=97&&Ne<=122?String.fromCodePoint(Ne):pe(Ne)}}catch($e){K={error:$e}}finally{try{De&&!De.done&&(Z=xe.return)&&Z.call(xe)}finally{if(K)throw K.error}}return ee}function z(W,K){var Z=u.domainToASCII(W);return Z===""?(w("Invalid domain name."),null):Z}n.setValidationErrorCallback=function(W){s=W},n.newURL=x,n.isSpecialScheme=C,n.isSpecial=S,n.defaultPort=_,n.includesCredentials=T,n.cannotHaveAUsernamePasswordPort=function(W){return W.host===null||W.host===""||W._cannotBeABaseURLFlag||W.scheme==="file"},n.urlSerializer=E,n.hostSerializer=D,n.iPv4Serializer=b,n.iPv6Serializer=I,n.urlParser=function(W,K,Z){var ee=P(W,K,Z);return ee===null?null:(ee.scheme!=="blob"||(ee._blobURLEntry=null),ee)},n.basicURLParser=P,n.setTheUsername=function(W,K){var Z,ee,xe="";try{for(var De=o(K),Ne=De.next();!Ne.done;Ne=De.next())xe+=_e(Ne.value,v)}catch($e){Z={error:$e}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}W.username=xe},n.setThePassword=function(W,K){var Z,ee,xe="";try{for(var De=o(K),Ne=De.next();!Ne.done;Ne=De.next())xe+=_e(Ne.value,v)}catch($e){Z={error:$e}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}W.password=xe},n.isSingleDotPathSegment=M,n.isDoubleDotPathSegment=L,n.shorten=V,n.isNormalizedWindowsDriveLetter=G,n.isWindowsDriveLetter=A,n.startsWithAWindowsDriveLetter=k,n.hostParser=F,n.iPv4NumberParser=j,n.iPv4Parser=Y,n.iPv6Parser=re,n.opaqueHostParser=ue,n.resolveABlobURL=ce,n.percentEncode=pe,n.percentDecode=Ee,n.stringPercentDecode=Oe,n.utf8PercentEncode=_e,n.hostEquals=function(W,K){return W===K},n.urlEquals=function(W,K,Z){return Z===void 0&&(Z=!1),E(W,Z)===E(K,Z)},n.urlEncodedStringParser=function(W){return B(c.utf8Encode(W))},n.urlEncodedParser=B,n.urlEncodedByteSerializer=O,n.urlEncodedSerializer=function(W,K){var Z,ee;if((K===void 0||K==="replacement"||K==="UTF-16BE"||K==="UTF-16LE"?"UTF-8":K).toUpperCase()!=="UTF-8")throw new Error("Only UTF-8 encoding is supported.");var xe="";try{for(var De=o(W),Ne=De.next();!Ne.done;Ne=De.next()){var $e=Ne.value,ie=O(c.utf8Encode($e[0])),ae=$e[1];ae=O(c.utf8Encode(ae)),xe!==""&&(xe+="&"),xe+=ie+"="+ae}}catch(ye){Z={error:ye}}finally{try{Ne&&!Ne.done&&(ee=De.return)&&ee.call(De)}finally{if(Z)throw Z.error}}return xe},n.origin=function W(K){switch(K.scheme){case"blob":K._blobURLEntry;var Z=P(K.path[0]);return Z===null?l.OpaqueOrigin:W(Z);case"ftp":case"http":case"https":case"ws":case"wss":return[K.scheme,K.host===null?"":K.host,K.port,null];case"file":default:return l.OpaqueOrigin}},n.domainToASCII=z,n.domainToUnicode=function(W,K){var Z=u.domainToUnicode(W);return Z===""&&w("Invalid domain name."),Z},n.asciiSerializationOfAnOrigin=function(W){if(W[0]===""&&W[1]===""&&W[2]===null&&W[3]===null)return"null";var K=W[0]+"://"+D(W[1]);return W[2]!==null&&(K+=":"+W[2].toString()),K}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(0),a=function(){function s(){this._signal=o.create_abortSignal()}return Object.defineProperty(s.prototype,"signal",{get:function(){return this._signal},enumerable:!0,configurable:!0}),s.prototype.abort=function(){o.abort_signalAbort(this._signal)},s}();n.AbortControllerImpl=a},function(r,n,i){var o,a=this&&this.__extends||(o=function(f,u){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var g in h)h.hasOwnProperty(g)&&(d[g]=h[g])})(f,u)},function(f,u){function d(){this.constructor=f}o(f,u),f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(70),c=i(0),l=function(f){function u(){var d=f.call(this)||this;return d._abortedFlag=!1,d._abortAlgorithms=new Set,d}return a(u,f),Object.defineProperty(u.prototype,"aborted",{get:function(){return this._abortedFlag},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"onabort",{get:function(){return c.event_getterEventHandlerIDLAttribute(this,"onabort")},set:function(d){c.event_setterEventHandlerIDLAttribute(this,"onabort",d)},enumerable:!0,configurable:!0}),u._create=function(){return new u},u}(s.EventTargetImpl);n.AbortSignalImpl=l},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(2),c=i(34),l=i(12),f=function(u){function d(h,g,p){var v=u.call(this)||this;return v._name="",v._publicId="",v._systemId="",v._name=h,v._publicId=g,v._systemId=p,v}return a(d,u),Object.defineProperty(d.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"publicId",{get:function(){return this._publicId},enumerable:!0,configurable:!0}),Object.defineProperty(d.prototype,"systemId",{get:function(){return this._systemId},enumerable:!0,configurable:!0}),d.prototype.before=function(){for(var h=[],g=0;g=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(1),c=i(0),l=function(){function f(u){return this._live=!0,this._filter=null,this._length=0,this._root=u,new Proxy(this,this)}return Object.defineProperty(f.prototype,"length",{get:function(){return this._root._children.size},enumerable:!0,configurable:!0}),f.prototype.item=function(u){if(u<0||u>this.length-1)return null;if(u=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(1),c=function(){function l(f){return this._live=!1,this._items=[],this._length=0,this._root=f,this._items=[],this._filter=function(u){return!0},new Proxy(this,this)}return Object.defineProperty(l.prototype,"length",{get:function(){return this._items.length},enumerable:!0,configurable:!0}),l.prototype.item=function(f){return f<0||f>this.length-1?null:this._items[f]},l.prototype.keys=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=0;return{next:(function(){return u===this.length?{done:!0,value:null}:{done:!1,value:u++}}).bind(this)}}).bind(this),f},l.prototype.values=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=this[Symbol.iterator]();return{next:function(){return u.next()}}}).bind(this),f},l.prototype.entries=function(){var f;return(f={})[Symbol.iterator]=(function(){var u=this[Symbol.iterator](),d=0;return{next:function(){var h=u.next();return h.done?{done:!0,value:null}:{done:!1,value:[d++,h.value]}}}}).bind(this),f},l.prototype[Symbol.iterator]=function(){var f=this._items[Symbol.iterator]();return{next:function(){return f.next()}}},l.prototype.forEach=function(f,u){var d,h;u===void 0&&(u=a.dom.window);var g=0;try{for(var p=o(this._items),v=p.next();!v.done;v=p.next()){var y=v.value;f.call(u,y,g++,this)}}catch(m){d={error:m}}finally{try{v&&!v.done&&(h=p.return)&&h.call(p)}finally{if(d)throw d.error}}},l.prototype.get=function(f,u,d){if(!s.isString(u))return Reflect.get(f,u,d);var h=Number(u);return isNaN(h)?Reflect.get(f,u,d):f._items[h]||void 0},l.prototype.set=function(f,u,d,h){if(!s.isString(u))return Reflect.set(f,u,d,h);var g=Number(u);return isNaN(g)?Reflect.set(f,u,d,h):g>=0&&g=v.length&&(v=void 0),{value:v&&v[w++],done:!v}}};throw new TypeError(y?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(6),l=i(2),f=i(102),u=i(9),d=i(0),h=i(12),g=i(3),p=function(v){function y(){var m=v.call(this)||this,w=c.dom.window._associatedDocument;return m._start=[w,0],m._end=[w,0],c.dom.rangeList.add(m),m}return a(y,v),Object.defineProperty(y.prototype,"commonAncestorContainer",{get:function(){for(var m=this._start[0];!d.tree_isAncestorOf(this._end[0],m,!0);){if(m._parent===null)throw new Error("Parent node is null.");m=m._parent}return m},enumerable:!0,configurable:!0}),y.prototype.setStart=function(m,w){d.range_setTheStart(this,m,w)},y.prototype.setEnd=function(m,w){d.range_setTheEnd(this,m,w)},y.prototype.setStartBefore=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheStart(this,w,d.tree_index(m))},y.prototype.setStartAfter=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheStart(this,w,d.tree_index(m)+1)},y.prototype.setEndBefore=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheEnd(this,w,d.tree_index(m))},y.prototype.setEndAfter=function(m){var w=m._parent;if(w===null)throw new u.InvalidNodeTypeError;d.range_setTheEnd(this,w,d.tree_index(m)+1)},y.prototype.collapse=function(m){m?this._end=this._start:this._start=this._end},y.prototype.selectNode=function(m){d.range_select(m,this)},y.prototype.selectNodeContents=function(m){if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;var w=d.tree_nodeLength(m);this._start=[m,0],this._end=[m,w]},y.prototype.compareBoundaryPoints=function(m,w){if(m!==l.HowToCompare.StartToStart&&m!==l.HowToCompare.StartToEnd&&m!==l.HowToCompare.EndToEnd&&m!==l.HowToCompare.EndToStart)throw new u.NotSupportedError;if(d.range_root(this)!==d.range_root(w))throw new u.WrongDocumentError;var x,C;switch(m){case l.HowToCompare.StartToStart:x=this._start,C=w._start;break;case l.HowToCompare.StartToEnd:x=this._end,C=w._start;break;case l.HowToCompare.EndToEnd:x=this._end,C=w._end;break;case l.HowToCompare.EndToStart:x=this._start,C=w._end;break;default:throw new u.NotSupportedError}var S=d.boundaryPoint_position(x,C);return S===l.BoundaryPosition.Before?-1:S===l.BoundaryPosition.After?1:0},y.prototype.deleteContents=function(){var m,w,x,C;if(!d.range_collapsed(this)){var S=this._startNode,_=this._startOffset,T=this._endNode,E=this._endOffset;if(S===T&&g.Guard.isCharacterDataNode(S))d.characterData_replaceData(S,_,E-_,"");else{var D,b,I=[];try{for(var P=s(d.range_getContainedNodes(this)),M=P.next();!M.done;M=P.next()){var L=(k=M.value)._parent;L!==null&&d.range_isContained(L,this)||I.push(k)}}catch(F){m={error:F}}finally{try{M&&!M.done&&(w=P.return)&&w.call(P)}finally{if(m)throw m.error}}if(d.tree_isAncestorOf(T,S,!0))D=S,b=_;else{for(var V=S;V._parent!==null&&!d.tree_isAncestorOf(T,V._parent,!0);)V=V._parent;if(V._parent===null)throw new Error("Parent node is null.");D=V._parent,b=d.tree_index(V)+1}g.Guard.isCharacterDataNode(S)&&d.characterData_replaceData(S,_,d.tree_nodeLength(S)-_,"");try{for(var G=s(I),A=G.next();!A.done;A=G.next()){var k;(k=A.value)._parent&&d.mutation_remove(k,k._parent)}}catch(F){x={error:F}}finally{try{A&&!A.done&&(C=G.return)&&C.call(G)}finally{if(x)throw x.error}}g.Guard.isCharacterDataNode(T)&&d.characterData_replaceData(T,0,E,""),this._start=[D,b],this._end=[D,b]}}},y.prototype.extractContents=function(){return d.range_extract(this)},y.prototype.cloneContents=function(){return d.range_cloneTheContents(this)},y.prototype.insertNode=function(m){return d.range_insert(m,this)},y.prototype.surroundContents=function(m){var w,x;try{for(var C=s(d.range_getPartiallyContainedNodes(this)),S=C.next();!S.done;S=C.next()){var _=S.value;if(!g.Guard.isTextNode(_))throw new u.InvalidStateError}}catch(E){w={error:E}}finally{try{S&&!S.done&&(x=C.return)&&x.call(C)}finally{if(w)throw w.error}}if(g.Guard.isDocumentNode(m)||g.Guard.isDocumentTypeNode(m)||g.Guard.isDocumentFragmentNode(m))throw new u.InvalidNodeTypeError;var T=d.range_extract(this);m._children.size!==0&&d.mutation_replaceAll(null,m),d.range_insert(m,this),d.mutation_append(T,m),d.range_select(m,this)},y.prototype.cloneRange=function(){return d.create_range(this._start,this._end)},y.prototype.detach=function(){c.dom.rangeList.delete(this)},y.prototype.isPointInRange=function(m,w){if(d.tree_rootNode(m)!==d.range_root(this))return!1;if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;if(w>d.tree_nodeLength(m))throw new u.IndexSizeError;var x=[m,w];return d.boundaryPoint_position(x,this._start)!==l.BoundaryPosition.Before&&d.boundaryPoint_position(x,this._end)!==l.BoundaryPosition.After},y.prototype.comparePoint=function(m,w){if(d.tree_rootNode(m)!==d.range_root(this))throw new u.WrongDocumentError;if(g.Guard.isDocumentTypeNode(m))throw new u.InvalidNodeTypeError;if(w>d.tree_nodeLength(m))throw new u.IndexSizeError;var x=[m,w];return d.boundaryPoint_position(x,this._start)===l.BoundaryPosition.Before?-1:d.boundaryPoint_position(x,this._end)===l.BoundaryPosition.After?1:0},y.prototype.intersectsNode=function(m){if(d.tree_rootNode(m)!==d.range_root(this))return!1;var w=m._parent;if(w===null)return!0;var x=d.tree_index(m);return d.boundaryPoint_position([w,x],this._end)===l.BoundaryPosition.Before&&d.boundaryPoint_position([w,x+1],this._start)===l.BoundaryPosition.After},y.prototype.toString=function(){var m,w,x="";if(this._startNode===this._endNode&&g.Guard.isTextNode(this._startNode))return this._startNode._data.substring(this._startOffset,this._endOffset);g.Guard.isTextNode(this._startNode)&&(x+=this._startNode._data.substring(this._startOffset));try{for(var C=s(d.range_getContainedNodes(this)),S=C.next();!S.done;S=C.next()){var _=S.value;g.Guard.isTextNode(_)&&(x+=_._data)}}catch(T){m={error:T}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return g.Guard.isTextNode(this._endNode)&&(x+=this._endNode._data.substring(0,this._endOffset)),x},y._create=function(m,w){var x=new y;return m&&(x._start=m),w&&(x._end=w),x},y.START_TO_START=0,y.START_TO_END=1,y.END_TO_END=2,y.END_TO_START=3,y}(f.AbstractRangeImpl);n.RangeImpl=p,h.idl_defineConst(p.prototype,"START_TO_START",0),h.idl_defineConst(p.prototype,"START_TO_END",1),h.idl_defineConst(p.prototype,"END_TO_END",2),h.idl_defineConst(p.prototype,"END_TO_START",3)},function(r,n,i){var o,a=this&&this.__extends||(o=function(f,u){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var g in h)h.hasOwnProperty(g)&&(d[g]=h[g])})(f,u)},function(f,u){function d(){this.constructor=f}o(f,u),f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(103),c=i(0),l=function(f){function u(d,h,g){var p=f.call(this,d)||this;return p._iteratorCollection=void 0,p._reference=h,p._pointerBeforeReference=g,c.nodeIterator_iteratorList().add(p),p}return a(u,f),Object.defineProperty(u.prototype,"referenceNode",{get:function(){return this._reference},enumerable:!0,configurable:!0}),Object.defineProperty(u.prototype,"pointerBeforeReferenceNode",{get:function(){return this._pointerBeforeReference},enumerable:!0,configurable:!0}),u.prototype.nextNode=function(){return c.nodeIterator_traverse(this,!0)},u.prototype.previousNode=function(){return c.nodeIterator_traverse(this,!1)},u.prototype.detach=function(){c.nodeIterator_iteratorList().delete(this)},u._create=function(d,h,g){return new u(d,h,g)},u}(s.TraverserImpl);n.NodeIteratorImpl=l},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(2),c=i(103),l=i(0),f=function(u){function d(h,g){var p=u.call(this,h)||this;return p._current=g,p}return a(d,u),Object.defineProperty(d.prototype,"currentNode",{get:function(){return this._current},set:function(h){this._current=h},enumerable:!0,configurable:!0}),d.prototype.parentNode=function(){for(var h=this._current;h!==null&&h!==this._root;)if((h=h._parent)!==null&&l.traversal_filter(this,h)===s.FilterResult.Accept)return this._current=h,h;return null},d.prototype.firstChild=function(){return l.treeWalker_traverseChildren(this,!0)},d.prototype.lastChild=function(){return l.treeWalker_traverseChildren(this,!1)},d.prototype.nextSibling=function(){return l.treeWalker_traverseSiblings(this,!0)},d.prototype.previousNode=function(){for(var h=this._current;h!==this._root;){for(var g=h._previousSibling;g;){h=g;for(var p=l.traversal_filter(this,h);p!==s.FilterResult.Reject&&h._lastChild;)h=h._lastChild,p=l.traversal_filter(this,h);if(p===s.FilterResult.Accept)return this._current=h,h;g=h._previousSibling}if(h===this._root||h._parent===null)return null;if(h=h._parent,l.traversal_filter(this,h)===s.FilterResult.Accept)return this._current=h,h}return null},d.prototype.previousSibling=function(){return l.treeWalker_traverseSiblings(this,!1)},d.prototype.nextNode=function(){for(var h=this._current,g=s.FilterResult.Accept;;){for(;g!==s.FilterResult.Reject&&h._firstChild;)if(h=h._firstChild,(g=l.traversal_filter(this,h))===s.FilterResult.Accept)return this._current=h,h;for(var p=null,v=h;v!==null;){if(v===this._root)return null;if((p=v._nextSibling)!==null){h=p;break}v=v._parent}if((g=l.traversal_filter(this,h))===s.FilterResult.Accept)return this._current=h,h}},d._create=function(h,g){return new d(h,g)},d}(c.TraverserImpl);n.TreeWalkerImpl=f},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(12),s=function(){function c(){}return c.prototype.acceptNode=function(l){return o.FilterResult.Accept},c._create=function(){return new c},c.FILTER_ACCEPT=1,c.FILTER_REJECT=2,c.FILTER_SKIP=3,c.SHOW_ALL=4294967295,c.SHOW_ELEMENT=1,c.SHOW_ATTRIBUTE=2,c.SHOW_TEXT=4,c.SHOW_CDATA_SECTION=8,c.SHOW_ENTITY_REFERENCE=16,c.SHOW_ENTITY=32,c.SHOW_PROCESSING_INSTRUCTION=64,c.SHOW_COMMENT=128,c.SHOW_DOCUMENT=256,c.SHOW_DOCUMENT_TYPE=512,c.SHOW_DOCUMENT_FRAGMENT=1024,c.SHOW_NOTATION=2048,c}();n.NodeFilterImpl=s,a.idl_defineConst(s.prototype,"FILTER_ACCEPT",1),a.idl_defineConst(s.prototype,"FILTER_REJECT",2),a.idl_defineConst(s.prototype,"FILTER_SKIP",3),a.idl_defineConst(s.prototype,"SHOW_ALL",4294967295),a.idl_defineConst(s.prototype,"SHOW_ELEMENT",1),a.idl_defineConst(s.prototype,"SHOW_ATTRIBUTE",2),a.idl_defineConst(s.prototype,"SHOW_TEXT",4),a.idl_defineConst(s.prototype,"SHOW_CDATA_SECTION",8),a.idl_defineConst(s.prototype,"SHOW_ENTITY_REFERENCE",16),a.idl_defineConst(s.prototype,"SHOW_ENTITY",32),a.idl_defineConst(s.prototype,"SHOW_PROCESSING_INSTRUCTION",64),a.idl_defineConst(s.prototype,"SHOW_COMMENT",128),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT",256),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT_TYPE",512),a.idl_defineConst(s.prototype,"SHOW_DOCUMENT_FRAGMENT",1024),a.idl_defineConst(s.prototype,"SHOW_NOTATION",2048)},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(s,c,l,f,u,d,h,g,p){this._type=s,this._target=c,this._addedNodes=l,this._removedNodes=f,this._previousSibling=u,this._nextSibling=d,this._attributeName=h,this._attributeNamespace=g,this._oldValue=p}return Object.defineProperty(a.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"addedNodes",{get:function(){return this._addedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"removedNodes",{get:function(){return this._removedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"attributeName",{get:function(){return this._attributeName},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"attributeNamespace",{get:function(){return this._attributeNamespace},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"oldValue",{get:function(){return this._oldValue},enumerable:!0,configurable:!0}),a._create=function(s,c,l,f,u,d,h,g,p){return new a(s,c,l,f,u,d,h,g,p)},a}();n.MutationRecordImpl=o},function(r,n,i){var o=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(9),c=i(7),l=i(0),f=function(){function u(d,h){this._element=d,this._attribute=h,this._tokenSet=new Set;var g=h._localName,p=l.element_getAnAttributeValue(d,g),v=this;this._element._attributeChangeSteps.push(function(y,m,w,x,C){m===v._attribute._localName&&C===null&&(x?v._tokenSet=l.orderedSet_parse(x):v._tokenSet.clear())}),a.dom.features.steps&&l.dom_runAttributeChangeSteps(d,g,p,p,null)}return Object.defineProperty(u.prototype,"length",{get:function(){return this._tokenSet.size},enumerable:!0,configurable:!0}),u.prototype.item=function(d){var h,g,p=0;try{for(var v=o(this._tokenSet),y=v.next();!y.done;y=v.next()){var m=y.value;if(p===d)return m;p++}}catch(w){h={error:w}}finally{try{y&&!y.done&&(g=v.return)&&g.call(v)}finally{if(h)throw h.error}}return null},u.prototype.contains=function(d){return this._tokenSet.has(d)},u.prototype.add=function(){for(var d,h,g=[],p=0;p=97&&s<=122||s>=65&&s<=90||s===58||s===95||s>=192&&s<=214||s>=216&&s<=246||s>=248&&s<=767||s>=880&&s<=893||s>=895&&s<=8191||s>=8204&&s<=8205||s>=8304&&s<=8591||s>=11264&&s<=12271||s>=12289&&s<=55295||s>=63744&&s<=64975||s>=65008&&s<=65533)&&(a===0||!(s===45||s===46||s>=48&&s<=57||s===183||s>=768&&s<=879||s>=8255&&s<=8256))){if(s>=55296&&s<=56319&&a=56320&&c<=57343&&(a++,(s=1024*(s-55296)+c-56320+65536)>=65536&&s<=983039))continue}return!1}}return!0},n.xml_isQName=function(o){for(var a=!1,s=0;s=97&&c<=122||c>=65&&c<=90||c===95||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8204&&c<=8205||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533)&&(s===0||!(c===45||c===46||c>=48&&c<=57||c===183||c>=768&&c<=879||c>=8255&&c<=8256))){if(s===0||c!==58){if(c>=55296&&c<=56319&&s=56320&&l<=57343&&(s++,(c=1024*(c-55296)+l-56320+65536)>=65536&&c<=983039))continue}return!1}if(a||s===o.length-1)return!1;a=!0}}return!0},n.xml_isLegalChar=function(o){for(var a=0;a=32&&s<=55295||s>=57344&&s<=65533)){if(s>=55296&&s<=56319&&a=56320&&c<=57343&&(a++,(s=1024*(s-55296)+c-56320+65536)>=65536&&s<=1114111))continue}return!1}}return!0},n.xml_isPubidChar=function(o){for(var a=0;a=97&&s<=122||s>=65&&s<=90||s>=39&&s<=59||s===32||s===13||s===10||s>=35&&s<=37||s===33||s===61||s===63||s===64||s===95))return!1}return!0}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(17);n.boundaryPoint_position=function s(c,l){var f=c[0],u=c[1],d=l[0],h=l[1];if(console.assert(a.tree_rootNode(f)===a.tree_rootNode(d),"Boundary points must share the same root node."),f===d)return u===h?o.BoundaryPosition.Equal:u=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(7),l=i(29),f=i(108),u=i(30),d=i(37),h=i(52);n.node_stringReplaceAll=function(g,p){var v=null;g!==""&&(v=l.create_text(p._nodeDocument,g)),d.mutation_replaceAll(v,p)},n.node_clone=function g(p,v,y){var m,w,x,C,S;if(v===void 0&&(v=null),y===void 0&&(y=!1),v===null&&(v=p._nodeDocument),s.Guard.isElementNode(p)){S=h.element_createAnElement(v,p._localName,p._namespace,p._namespacePrefix,p._is,!1);try{for(var _=o(p._attributeList),T=_.next();!T.done;T=_.next()){var E=g(T.value,v);h.element_append(E,S)}}catch(L){m={error:L}}finally{try{T&&!T.done&&(w=_.return)&&w.call(_)}finally{if(m)throw m.error}}}else if(s.Guard.isDocumentNode(p)){var D=l.create_document();D._encoding=p._encoding,D._contentType=p._contentType,D._URL=p._URL,D._origin=p._origin,D._type=p._type,D._mode=p._mode,S=D}else if(s.Guard.isDocumentTypeNode(p))S=l.create_documentType(v,p._name,p._publicId,p._systemId);else if(s.Guard.isAttrNode(p)){var b=l.create_attr(v,p.localName);b._namespace=p._namespace,b._namespacePrefix=p._namespacePrefix,b._value=p._value,S=b}else S=s.Guard.isExclusiveTextNode(p)?l.create_text(v,p._data):s.Guard.isCDATASectionNode(p)?l.create_cdataSection(v,p._data):s.Guard.isCommentNode(p)?l.create_comment(v,p._data):s.Guard.isProcessingInstructionNode(p)?l.create_processingInstruction(v,p._target,p._data):s.Guard.isDocumentFragmentNode(p)?l.create_documentFragment(v):Object.create(p);if(s.Guard.isDocumentNode(S)?(S._nodeDocument=S,v=S):S._nodeDocument=v,a.dom.features.steps&&u.dom_runCloningSteps(S,p,v,y),y)try{for(var I=o(p._children),P=I.next();!P.done;P=I.next()){var M=g(P.value,v,!0);d.mutation_append(M,S)}}catch(L){x={error:L}}finally{try{P&&!P.done&&(C=I.return)&&C.call(I)}finally{if(x)throw x.error}}return S},n.node_equals=function g(p,v){var y,m,w,x;if(p._nodeType!==v._nodeType)return!1;if(s.Guard.isDocumentTypeNode(p)&&s.Guard.isDocumentTypeNode(v)){if(p._name!==v._name||p._publicId!==v._publicId||p._systemId!==v._systemId)return!1}else if(s.Guard.isElementNode(p)&&s.Guard.isElementNode(v)){if(p._namespace!==v._namespace||p._namespacePrefix!==v._namespacePrefix||p._localName!==v._localName||p._attributeList.length!==v._attributeList.length)return!1}else if(s.Guard.isAttrNode(p)&&s.Guard.isAttrNode(v)){if(p._namespace!==v._namespace||p._localName!==v._localName||p._value!==v._value)return!1}else if(s.Guard.isProcessingInstructionNode(p)&&s.Guard.isProcessingInstructionNode(v)){if(p._target!==v._target||p._data!==v._data)return!1}else if(s.Guard.isCharacterDataNode(p)&&s.Guard.isCharacterDataNode(v)&&p._data!==v._data)return!1;if(s.Guard.isElementNode(p)&&s.Guard.isElementNode(v)){var C={};try{for(var S=o(p._attributeList),_=S.next();!_.done;_=S.next())C[(D=_.value)._localName]=D}catch(V){y={error:V}}finally{try{_&&!_.done&&(m=S.return)&&m.call(S)}finally{if(y)throw y.error}}try{for(var T=o(v._attributeList),E=T.next();!E.done;E=T.next()){var D,b=E.value;if(!(D=C[b._localName])||!g(D,b))return!1}}catch(V){w={error:V}}finally{try{E&&!E.done&&(x=T.return)&&x.call(T)}finally{if(w)throw w.error}}}if(p._children.size!==v._children.size)return!1;for(var I=p._children[Symbol.iterator](),P=v._children[Symbol.iterator](),M=I.next(),L=P.next();!M.done&&!L.done;){if(!g(M.value,L.value))return!1;M=I.next(),L=P.next()}return!0},n.node_listOfElementsWithQualifiedName=function(g,p){return g==="*"?l.create_htmlCollection(p):p._nodeDocument._type==="html"?l.create_htmlCollection(p,function(v){return v._namespace===c.namespace.HTML&&v._qualifiedName===g.toLowerCase()||v._namespace!==c.namespace.HTML&&v._qualifiedName===g}):l.create_htmlCollection(p,function(v){return v._qualifiedName===g})},n.node_listOfElementsWithNamespace=function(g,p,v){return g===""&&(g=null),g==="*"&&p==="*"?l.create_htmlCollection(v):g==="*"?l.create_htmlCollection(v,function(y){return y._localName===p}):p==="*"?l.create_htmlCollection(v,function(y){return y._namespace===g}):l.create_htmlCollection(v,function(y){return y._localName===p&&y._namespace===g})},n.node_listOfElementsWithClassNames=function(g,p){var v=f.orderedSet_parse(g);if(v.size===0)return l.create_htmlCollection(p,function(){return!1});var y=p._nodeDocument._mode!=="quirks";return l.create_htmlCollection(p,function(m){var w=m.classList;return f.orderedSet_contains(w._tokenSet,v,y)})},n.node_locateANamespacePrefix=function g(p,v){if(p._namespace===v&&p._namespacePrefix!==null)return p._namespacePrefix;for(var y=0;y=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(9),l=i(29),f=i(17),u=i(107),d=i(37);n.text_contiguousTextNodes=function(h,g){var p;return g===void 0&&(g=!1),(p={})[Symbol.iterator]=function(){for(var v=h;v&&s.Guard.isTextNode(v._previousSibling);)v=v._previousSibling;return{next:function(){if(v&&!g&&v===h&&(v=s.Guard.isTextNode(v._nextSibling)?v._nextSibling:null),v===null)return{done:!0,value:null};var y={done:!1,value:v};return v=s.Guard.isTextNode(v._nextSibling)?v._nextSibling:null,y}}},p},n.text_contiguousExclusiveTextNodes=function(h,g){var p;return g===void 0&&(g=!1),(p={})[Symbol.iterator]=function(){for(var v=h;v&&s.Guard.isExclusiveTextNode(v._previousSibling);)v=v._previousSibling;return{next:function(){if(v&&!g&&v===h&&(v=s.Guard.isExclusiveTextNode(v._nextSibling)?v._nextSibling:null),v===null)return{done:!0,value:null};var y={done:!1,value:v};return v=s.Guard.isExclusiveTextNode(v._nextSibling)?v._nextSibling:null,y}}},p},n.text_descendantTextContent=function(h){for(var g="",p=f.tree_getFirstDescendantNode(h,!1,!1,function(v){return s.Guard.isTextNode(v)});p!==null;)g+=p._data,p=f.tree_getNextDescendantNode(h,p,!1,!1,function(v){return s.Guard.isTextNode(v)});return g},n.text_split=function(h,g){var p,v,y=h._data.length;if(g>y)throw new c.IndexSizeError;var m=y-g,w=u.characterData_substringData(h,g,m),x=l.create_text(h._nodeDocument,w),C=h._parent;if(C!==null){d.mutation_insert(x,C,h._nextSibling);try{for(var S=o(a.dom.rangeList),_=S.next();!_.done;_=S.next()){var T=_.value;T._start[0]===h&&T._start[1]>g&&(T._start[0]=x,T._start[1]-=g),T._end[0]===h&&T._end[1]>g&&(T._end[0]=x,T._end[1]-=g);var E=f.tree_index(h);T._start[0]===C&&T._start[1]===E+1&&T._start[1]++,T._end[0]===C&&T._end[1]===E+1&&T._end[1]++}}catch(D){p={error:D}}finally{try{_&&!_.done&&(v=S.return)&&v.call(S)}finally{if(p)throw p.error}}}return u.characterData_replaceData(h,g,m,""),x}},function(r,n,i){var o=i(4),a=i(41),s=i(24),c=i(48),l=[].join,f=a!=Object,u=c("join",",");o({target:"Array",proto:!0,forced:f||!u},{join:function(d){return l.call(s(this),d===void 0?",":d)}})},function(r,n,i){var o=i(4),a=i(83),s=String.fromCharCode,c=String.fromCodePoint;o({target:"String",stat:!0,forced:!!c&&c.length!=1},{fromCodePoint:function(l){for(var f,u=[],d=arguments.length,h=0;d>h;){if(f=+arguments[h++],a(f,1114111)!==f)throw RangeError(f+" is not a valid code point");u.push(f<65536?s(f):s(55296+((f-=65536)>>10),f%1024+56320))}return u.join("")}})},function(r,n,i){var o=this&&this.__read||function(c,l){var f=typeof Symbol=="function"&&c[Symbol.iterator];if(!f)return c;var u,d,h=f.call(c),g=[];try{for(;(l===void 0||l-- >0)&&!(u=h.next()).done;)g.push(u.value)}catch(p){d={error:p}}finally{try{u&&!u.done&&(f=h.return)&&f.call(h)}finally{if(d)throw d.error}}return g};Object.defineProperty(n,"__esModule",{value:!0});var a=i(111),s=function(){function c(l,f){this._options={skipWhitespaceOnlyText:!1},this.err={line:-1,col:-1,index:-1,str:""},this._str=l,this._index=0,this._length=l.length,f&&(this._options.skipWhitespaceOnlyText=f.skipWhitespaceOnlyText||!1)}return c.prototype.nextToken=function(){if(this.eof())return{type:a.TokenType.EOF};var l=this.skipIfStartsWith("<")?this.openBracket():this.text();return this._options.skipWhitespaceOnlyText&&l.type===a.TokenType.Text&&c.isWhiteSpaceToken(l)&&(l=this.nextToken()),l},c.prototype.openBracket=function(){return this.skipIfStartsWith("?")?this.skipIfStartsWith("xml")?c.isSpace(this._str[this._index])?this.declaration():(this.seek(-3),this.pi()):this.pi():this.skipIfStartsWith("!")?this.skipIfStartsWith("--")?this.comment():this.skipIfStartsWith("[CDATA[")?this.cdata():this.skipIfStartsWith("DOCTYPE")?this.doctype():void this.throwError("Invalid '!' in opening tag."):this.skipIfStartsWith("/")?this.closeTag():this.openTag()},c.prototype.declaration=function(){for(var l="",f="",u="";!this.eof();){if(this.skipSpace(),this.skipIfStartsWith("?>"))return{type:a.TokenType.Declaration,version:l,encoding:f,standalone:u};var d=o(this.attribute(),2),h=d[0],g=d[1];h==="version"?l=g:h==="encoding"?f=g:h==="standalone"?u=g:this.throwError("Invalid attribute name: "+h)}this.throwError("Missing declaration end symbol `?>`")},c.prototype.doctype=function(){var l="",f="";this.skipSpace();var u=this.takeUntil2("[",">",!0);return this.skipSpace(),this.skipIfStartsWith("PUBLIC")?(l=this.quotedString(),f=this.quotedString()):this.skipIfStartsWith("SYSTEM")&&(f=this.quotedString()),this.skipSpace(),this.skipIfStartsWith("[")&&(this.skipUntil("]"),this.skipIfStartsWith("]")||this.throwError("Missing end bracket of DTD internal subset")),this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing doctype end symbol `>`"),{type:a.TokenType.DocType,name:u,pubId:l,sysId:f}},c.prototype.pi=function(){var l=this.takeUntilStartsWith("?>",!0);if(this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.skipSpace(),this.skipIfStartsWith("?>"))return{type:a.TokenType.PI,target:l,data:""};var f=this.takeUntilStartsWith("?>");return this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.seek(2),{type:a.TokenType.PI,target:l,data:f}},c.prototype.text=function(){var l=this.takeUntil("<");return{type:a.TokenType.Text,data:l}},c.prototype.comment=function(){var l=this.takeUntilStartsWith("-->");return this.eof()&&this.throwError("Missing comment end symbol `-->`"),this.seek(3),{type:a.TokenType.Comment,data:l}},c.prototype.cdata=function(){var l=this.takeUntilStartsWith("]]>");return this.eof()&&this.throwError("Missing CDATA end symbol `]>`"),this.seek(3),{type:a.TokenType.CDATA,data:l}},c.prototype.openTag=function(){this.skipSpace();var l=this.takeUntil2(">","/",!0);if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:a.TokenType.Element,name:l,attributes:[],selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:a.TokenType.Element,name:l,attributes:[],selfClosing:!0};for(var f=[];!this.eof();){if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:a.TokenType.Element,name:l,attributes:f,selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:a.TokenType.Element,name:l,attributes:f,selfClosing:!0};var u=this.attribute();f.push(u)}this.throwError("Missing opening element tag end symbol `>`")},c.prototype.closeTag=function(){this.skipSpace();var l=this.takeUntil(">",!0);return this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing closing element tag end symbol `>`"),{type:a.TokenType.ClosingTag,name:l}},c.prototype.attribute=function(){this.skipSpace();var l=this.takeUntil("=",!0);return this.skipSpace(),this.skipIfStartsWith("=")||this.throwError("Missing equals sign before attribute value"),[l,this.quotedString()]},c.prototype.quotedString=function(){this.skipSpace();var l=this.take(1);c.isQuote(l)||this.throwError("Missing start quote character before quoted value");var f=this.takeUntil(l);return this.skipIfStartsWith(l)||this.throwError("Missing end quote character after quoted value"),f},c.prototype.eof=function(){return this._index>=this._length},c.prototype.skipIfStartsWith=function(l){var f=l.length;if(f===1)return this._str[this._index]===l&&(this._index++,!0);for(var u=0;uthis._length&&(this._index=this._length)},c.prototype.skipSpace=function(){for(;!this.eof()&&c.isSpace(this._str[this._index]);)this._index++},c.prototype.take=function(l){if(l===1)return this._str[this._index++];var f=this._index;return this.seek(l),this._str.slice(f,this._index)},c.prototype.takeUntil=function(l,f){f===void 0&&(f=!1);for(var u=this._index;this._indexthis._index){g=u.index;break}throw this.err={line:d,col:this._index-h,index:this._index,str:this._str.substring(h,g)},new Error(l+` Index: `+this.err.index+` @@ -3408,25 +3408,25 @@ Ln: `+this.err.line+", Col: "+this.err.col+` Input: `+this.err.str)},c.prototype[Symbol.iterator]=function(){return this._index=0,{next:(function(){var l=this.nextToken();return l.type===a.TokenType.EOF?{done:!0,value:null}:{done:!1,value:l}}).bind(this)}},c}();n.XMLStringLexer=s},function(r,n,i){var o=i(39);r.exports=new o({include:[i(182)]})},function(r,n,i){var o=i(39);r.exports=new o({include:[i(113)],implicit:[i(289),i(290),i(291),i(292)]})},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(91),a=i(1),s=i(3),c=i(77),l=i(109);function f(g,p){var v=d(g===void 0||u(g)?g:o.DefaultBuilderOptions),y=u(g)?p:g,m=l.createDocument();h(m,v);var w=new c.XMLBuilderImpl(m);return y!==void 0&&w.ele(y),w}function u(g){if(!a.isPlainObject(g))return!1;for(var p in g)if(g.hasOwnProperty(p)&&!o.XMLBuilderOptionKeys.has(p))return!1;return!0}function d(g){g===void 0&&(g={});var p=a.applyDefaults(g,o.DefaultBuilderOptions);if(p.convert.att.length===0||p.convert.ins.length===0||p.convert.text.length===0||p.convert.cdata.length===0||p.convert.comment.length===0)throw new Error("JS object converter strings cannot be zero length.");return p}function h(g,p,v){var y=g;y._xmlBuilderOptions=p,y._isFragment=v}n.builder=function(g,p){var v=d(u(g)?g:o.DefaultBuilderOptions),y=s.Guard.isNode(g)||a.isArray(g)?g:p;if(y===void 0)throw new Error("Invalid arguments.");if(a.isArray(y)){for(var m=[],w=0;w0)&&!(x=S.next()).done;)_.push(x.value)}catch(T){C={error:T}}finally{try{x&&!x.done&&(w=S.return)&&w.call(S)}finally{if(C)throw C.error}}return _},a=this&&this.__values||function(y){var m=typeof Symbol=="function"&&Symbol.iterator,w=m&&y[m],x=0;if(w)return w.call(y);if(y&&typeof y.length=="number")return{next:function(){return y&&x>=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=i(91),c=i(1),l=i(217),f=i(2),u=i(3),d=i(0),h=i(109),g=i(7),p=i(276),v=function(){function y(m){this._domNode=m}return Object.defineProperty(y.prototype,"node",{get:function(){return this._domNode},enumerable:!0,configurable:!0}),Object.defineProperty(y.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),y.prototype.set=function(m){return this._options=c.applyDefaults(c.applyDefaults(this._options,m,!0),s.DefaultBuilderOptions),this},y.prototype.ele=function(m,w,x){var C,S,_,T,E,D;if(c.isObject(m))return new p.ObjectReader(this._options).parse(this,m);if(m!==null&&/^\s*0&&(m===void 0&&(m=w.slice(C+1)),w=w.slice(0,C)),m===void 0)m=x?this._options.defaultNamespace.ele:this._options.defaultNamespace.att;else if(m!==null&&m[0]==="@"){var S=m.slice(1);if((m=this._options.namespaceAlias[S])===void 0)throw new Error("Namespace alias `"+S+"` is not defined. "+this._debugInfo())}return[m,w]},y.prototype._updateNamespace=function(m){var w,x,C,S,_=this._domNode;if(u.Guard.isElementNode(_)&&m!==null&&_.namespaceURI!==m){var T=o(d.namespace_extractQName(_.prefix?_.prefix+":"+_.localName:_.localName),2),E=T[0],D=T[1],b=d.create_element(this._doc,D,m,E);try{for(var I=a(_.attributes),P=I.next();!P.done;P=I.next()){var M=P.value,L=M.prefix?M.prefix+":"+M.localName:M.localName,V=o(d.namespace_extractQName(L),1)[0],G=M.namespaceURI;G===null&&V!==null&&(G=_.lookupNamespaceURI(V)),G===null?b.setAttribute(L,M.value):b.setAttributeNS(G,L,M.value)}}catch(ue){w={error:ue}}finally{try{P&&!P.done&&(x=I.return)&&x.call(I)}finally{if(w)throw w.error}}var A=_.parentNode;if(A===null)throw new Error("Parent node is null."+this._debugInfo());A.replaceChild(b,_),this._domNode=b;try{for(var k=a(_.childNodes),F=k.next();!F.done;F=k.next()){var j=F.value.cloneNode(!0);if(b.appendChild(j),u.Guard.isElementNode(j)){var Y=o(d.namespace_extractQName(j.prefix?j.prefix+":"+j.localName:j.localName),1)[0],re=b.lookupNamespaceURI(Y);new y(j)._updateNamespace(re)}}}catch(ue){C={error:ue}}finally{try{F&&!F.done&&(S=k.return)&&S.call(k)}finally{if(C)throw C.error}}}},Object.defineProperty(y.prototype,"_doc",{get:function(){var m=this.node;if(u.Guard.isDocumentNode(m))return m;var w=m.ownerDocument;if(!w)throw new Error("Owner document is null. "+this._debugInfo());return w},enumerable:!0,configurable:!0}),y.prototype._debugInfo=function(m){var w=this.node,x=w.parentNode;m=m||w.nodeName;var C=x?x.nodeName:"";return C?"node: <"+m+">, parent: <"+C+">":"node: <"+m+">"},Object.defineProperty(y.prototype,"_options",{get:function(){var m=this._doc;if(m._xmlBuilderOptions===void 0)throw new Error("Builder options is not set.");return m._xmlBuilderOptions},set:function(m){this._doc._xmlBuilderOptions=m},enumerable:!0,configurable:!0}),y}();n.XMLBuilderImpl=v},function(r,n,i){var o=i(11),a=i(117),s=o.WeakMap;r.exports=typeof s=="function"&&/native code/.test(a(s))},function(r,n,i){var o=i(46),a=i(82),s=i(85),c=i(18);r.exports=o("Reflect","ownKeys")||function(l){var f=a.f(c(l)),u=s.f;return u?f.concat(u(l)):f}},function(r,n,i){var o=i(16),a=i(15),s=i(18),c=i(61);r.exports=o?Object.defineProperties:function(l,f){s(l);for(var u,d=c(f),h=d.length,g=0;h>g;)a.f(l,u=d[g++],f[u]);return l}},function(r,n,i){var o=i(46);r.exports=o("document","documentElement")},function(r,n,i){var o=i(24),a=i(82).f,s={}.toString,c=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];r.exports.f=function(l){return c&&s.call(l)=="[object Window]"?function(f){try{return a(f)}catch{return c.slice()}}(l):a(o(l))}},function(r,n,i){var o=i(4),a=i(36).every,s=i(48),c=i(28),l=s("every"),f=c("every");o({target:"Array",proto:!0,forced:!l||!f},{every:function(u){return a(this,u,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(4),a=i(36).filter,s=i(63),c=i(28),l=s("filter"),f=c("filter");o({target:"Array",proto:!0,forced:!l||!f},{filter:function(u){return a(this,u,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(46);r.exports=o("navigator","userAgent")||""},function(r,n,i){var o=i(4),a=i(36).find,s=i(130),c=i(28),l=!0,f=c("find");"find"in[]&&Array(1).find(function(){l=!1}),o({target:"Array",proto:!0,forced:l||!f},{find:function(u){return a(this,u,arguments.length>1?arguments[1]:void 0)}}),s("find")},function(r,n,i){var o=i(131).IteratorPrototype,a=i(60),s=i(40),c=i(62),l=i(49),f=function(){return this};r.exports=function(u,d,h){var g=d+" Iterator";return u.prototype=a(o,{next:s(1,h)}),c(u,g,!1,!0),l[g]=f,u}},function(r,n,i){var o=i(8);r.exports=!o(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})},function(r,n,i){var o=i(13);r.exports=function(a){if(!o(a)&&a!==null)throw TypeError("Can't set "+String(a)+" as a prototype");return a}},function(r,n,i){var o=i(4),a=i(36).map,s=i(63),c=i(28),l=s("map"),f=c("map");o({target:"Array",proto:!0,forced:!l||!f},{map:function(u){return a(this,u,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(4),a=i(200).left,s=i(48),c=i(28),l=s("reduce"),f=c("reduce",{1:0});o({target:"Array",proto:!0,forced:!l||!f},{reduce:function(u){return a(this,u,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(127),a=i(27),s=i(41),c=i(26),l=function(f){return function(u,d,h,g){o(d);var p=a(u),v=s(p),y=c(p.length),m=f?y-1:0,w=f?-1:1;if(h<2)for(;;){if(m in v){g=v[m],m+=w;break}if(m+=w,f?m<0:y<=m)throw TypeError("Reduce of empty array with no initial value")}for(;f?m>=0:y>m;m+=w)m in v&&(g=d(g,v[m],m,p));return g}};r.exports={left:l(!1),right:l(!0)}},function(r,n,i){var o=i(4),a=i(36).some,s=i(48),c=i(28),l=s("some"),f=c("some");o({target:"Array",proto:!0,forced:!l||!f},{some:function(u){return a(this,u,arguments.length>1?arguments[1]:void 0)}})},function(r,n,i){var o=i(90),a=i(135);r.exports=o?{}.toString:function(){return"[object "+a(this)+"]"}},function(r,n){r.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(r,n,i){var o=i(8);r.exports=!o(function(){return Object.isExtensible(Object.preventExtensions({}))})},function(r,n,i){var o=i(5),a=i(49),s=o("iterator"),c=Array.prototype;r.exports=function(l){return l!==void 0&&(a.Array===l||c[s]===l)}},function(r,n,i){var o=i(135),a=i(49),s=i(5)("iterator");r.exports=function(c){if(c!=null)return c[s]||c["@@iterator"]||a[o(c)]}},function(r,n,i){var o=i(18);r.exports=function(a,s,c,l){try{return l?s(o(c)[0],c[1]):s(c)}catch(u){var f=a.return;throw f!==void 0&&o(f.call(a)),u}}},function(r,n,i){var o=i(5)("iterator"),a=!1;try{var s=0,c={next:function(){return{done:!!s++}},return:function(){a=!0}};c[o]=function(){return this},Array.from(c,function(){throw 2})}catch{}r.exports=function(l,f){if(!f&&!a)return!1;var u=!1;try{var d={};d[o]=function(){return{next:function(){return{done:u=!0}}}},l(d)}catch{}return u}},function(r,n,i){var o=i(13),a=i(133);r.exports=function(s,c,l){var f,u;return a&&typeof(f=c.constructor)=="function"&&f!==l&&o(u=f.prototype)&&u!==l.prototype&&a(s,u),s}},function(r,n,i){var o=i(25);r.exports=function(a,s,c){for(var l in s)o(a,l,s[l],c);return a}},function(r,n,i){var o=i(46),a=i(15),s=i(5),c=i(16),l=s("species");r.exports=function(f){var u=o(f),d=a.f;c&&u&&!u[l]&&d(u,l,{configurable:!0,get:function(){return this}})}},function(r,n,i){var o=this&&this.__generator||function(c,l){var f,u,d,h,g={label:0,sent:function(){if(1&d[0])throw d[1];return d[1]},trys:[],ops:[]};return h={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(h[Symbol.iterator]=function(){return this}),h;function p(v){return function(y){return function(m){if(f)throw new TypeError("Generator is already executing.");for(;g;)try{if(f=1,u&&(d=2&m[0]?u.return:m[0]?u.throw||((d=u.return)&&d.call(u),0):u.next)&&!(d=d.call(u,m[1])).done)return d;switch(u=0,d&&(m=[2&m[0],d.value]),m[0]){case 0:case 1:d=m;break;case 4:return g.label++,{value:m[1],done:!1};case 5:g.label++,u=m[1],m=[0];continue;case 7:m=g.ops.pop(),g.trys.pop();continue;default:if(d=g.trys,!((d=d.length>0&&d[d.length-1])||m[0]!==6&&m[0]!==2)){g=0;continue}if(m[0]===3&&(!d||m[1]>d[0]&&m[1]=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=function(){function c(l){l===void 0&&(l=1e3),this._items=new Set,this._limit=l}return c.prototype.add=function(l){if(this._items.add(l),this._items.size>this._limit){var f=this._items.values().next();f.done||this._items.delete(f.value)}return this},c.prototype.delete=function(l){return this._items.delete(l)},c.prototype.has=function(l){return this._items.has(l)},c.prototype.clear=function(){this._items.clear()},Object.defineProperty(c.prototype,"size",{get:function(){return this._items.size},enumerable:!0,configurable:!0}),c.prototype.forEach=function(l,f){var u=this;this._items.forEach(function(d){return l.call(f,d,d,u)})},c.prototype.keys=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.keys())];case 1:return l.sent(),[2]}})},c.prototype.values=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.values())];case 1:return l.sent(),[2]}})},c.prototype.entries=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.entries())];case 1:return l.sent(),[2]}})},c.prototype[Symbol.iterator]=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items)];case 1:return l.sent(),[2]}})},Object.defineProperty(c.prototype,Symbol.toStringTag,{get:function(){return"FixedSizeSet"},enumerable:!0,configurable:!0}),c}();n.FixedSizeSet=s},function(r,n,i){var o=this&&this.__generator||function(c,l){var f,u,d,h,g={label:0,sent:function(){if(1&d[0])throw d[1];return d[1]},trys:[],ops:[]};return h={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(h[Symbol.iterator]=function(){return this}),h;function p(v){return function(y){return function(m){if(f)throw new TypeError("Generator is already executing.");for(;g;)try{if(f=1,u&&(d=2&m[0]?u.return:m[0]?u.throw||((d=u.return)&&d.call(u),0):u.next)&&!(d=d.call(u,m[1])).done)return d;switch(u=0,d&&(m=[2&m[0],d.value]),m[0]){case 0:case 1:d=m;break;case 4:return g.label++,{value:m[1],done:!1};case 5:g.label++,u=m[1],m=[0];continue;case 7:m=g.ops.pop(),g.trys.pop();continue;default:if(d=g.trys,!((d=d.length>0&&d[d.length-1])||m[0]!==6&&m[0]!==2)){g=0;continue}if(m[0]===3&&(!d||m[1]>d[0]&&m[1]=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=function(){function c(l){l===void 0&&(l=1e3),this._items=new Map,this._limit=l}return c.prototype.get=function(l){return this._items.get(l)},c.prototype.set=function(l,f){if(this._items.set(l,f),this._items.size>this._limit){var u=this._items.keys().next();u.done||this._items.delete(u.value)}},c.prototype.delete=function(l){return this._items.delete(l)},c.prototype.has=function(l){return this._items.has(l)},c.prototype.clear=function(){this._items.clear()},Object.defineProperty(c.prototype,"size",{get:function(){return this._items.size},enumerable:!0,configurable:!0}),c.prototype.forEach=function(l,f){this._items.forEach(function(u,d){return l.call(f,d,u)})},c.prototype.keys=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.keys())];case 1:return l.sent(),[2]}})},c.prototype.values=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.values())];case 1:return l.sent(),[2]}})},c.prototype.entries=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items.entries())];case 1:return l.sent(),[2]}})},c.prototype[Symbol.iterator]=function(){return o(this,function(l){switch(l.label){case 0:return[5,a(this._items)];case 1:return l.sent(),[2]}})},Object.defineProperty(c.prototype,Symbol.toStringTag,{get:function(){return"ObjectCache"},enumerable:!0,configurable:!0}),c}();n.ObjectCache=s},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(s){s===void 0&&(s=1e3),this._items=new Map,this._limit=s}return a.prototype.check=function(s,c){if(this._items.get(s)===c)return!0;if(this._items.get(c)===s)return!1;var l=Math.random()<.5;if(l?this._items.set(s,c):this._items.set(c,s),this._items.size>this._limit){var f=this._items.keys().next();f.done||this._items.delete(f.value)}return l},a}();n.CompareCache=o},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(s){this._initialized=!1,this._value=void 0,this._initFunc=s}return Object.defineProperty(a.prototype,"value",{get:function(){return this._initialized||(this._value=this._initFunc(),this._initialized=!0),this._value},enumerable:!0,configurable:!0}),a}();n.Lazy=o},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function a(s){this._pointer=0,this._chars=Array.from(s),this._length=this._chars.length}return Object.defineProperty(a.prototype,"eof",{get:function(){return this._pointer>=this._length},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),a.prototype.codePoint=function(){if(this._codePoint===void 0)if(this.eof)this._codePoint=-1;else{var s=this._chars[this._pointer].codePointAt(0);this._codePoint=s!==void 0?s:-1}return this._codePoint},a.prototype.c=function(){return this._c===void 0&&(this._c=this.eof?"":this._chars[this._pointer]),this._c},a.prototype.remaining=function(){return this._remaining===void 0&&(this._remaining=this.eof?"":this._chars.slice(this._pointer+1).join("")),this._remaining},a.prototype.substring=function(){return this._substring===void 0&&(this._substring=this.eof?"":this._chars.slice(this._pointer).join("")),this._substring},Object.defineProperty(a.prototype,"pointer",{get:function(){return this._pointer},set:function(s){s!==this._pointer&&(this._pointer=s,this._codePoint=void 0,this._c=void 0,this._remaining=void 0,this._substring=void 0)},enumerable:!0,configurable:!0}),a}();n.StringWalker=o},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(218);n.MapWriter=o.MapWriter;var a=i(258);n.XMLWriter=a.XMLWriter;var s=i(67);n.ObjectWriter=s.ObjectWriter;var c=i(260);n.JSONWriter=c.JSONWriter;var l=i(261);n.YAMLWriter=l.YAMLWriter},function(r,n,i){i(19),i(219),i(20),i(22),i(23);var o,a=this&&this.__extends||(o=function(f,u){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var g in h)h.hasOwnProperty(g)&&(d[g]=h[g])})(f,u)},function(f,u){function d(){this.constructor=f}o(f,u),f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(1),c=i(67),l=function(f){function u(d,h){var g=f.call(this,d)||this;return g._writerOptions=s.applyDefaults(h,{format:"map",wellFormed:!1,group:!1,verbose:!1}),g}return a(u,f),u.prototype.serialize=function(d){var h=s.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1,verbose:!1}),g=new c.ObjectWriter(this._builderOptions,h).serialize(d);return this._convertObject(g)},u.prototype._convertObject=function(d){if(s.isArray(d)){for(var h=0;h=51||!a(function(){var x=[];return x[v]=!1,x.concat()[0]!==x}),m=h("concat"),w=function(x){if(!c(x))return!1;var C=x[v];return C!==void 0?!!C:s(x)};o({target:"Array",proto:!0,forced:!y||!m},{concat:function(x){var C,S,_,T,E,D=l(this),b=d(D,0),I=0;for(C=-1,_=arguments.length;C<_;C++)if(w(E=C===-1?D:arguments[C])){if(I+(T=f(E.length))>9007199254740991)throw TypeError("Maximum allowed index exceeded");for(S=0;S=9007199254740991)throw TypeError("Maximum allowed index exceeded");u(b,I++,E)}return b.length=I,b}})},function(r,n,i){var o=i(8);function a(s,c){return RegExp(s,c)}n.UNSUPPORTED_Y=o(function(){var s=a("a","y");return s.lastIndex=2,s.exec("abcd")!=null}),n.BROKEN_CARET=o(function(){var s=a("^r","gy");return s.lastIndex=2,s.exec("str")!=null})},function(r,n,i){var o=i(223);r.exports=function(a){if(o(a))throw TypeError("The method doesn't accept regular expressions");return a}},function(r,n,i){var o=i(13),a=i(42),s=i(5)("match");r.exports=function(c){var l;return o(c)&&((l=c[s])!==void 0?!!l:a(c)=="RegExp")}},function(r,n,i){var o=i(5)("match");r.exports=function(a){var s=/./;try{"/./"[a](s)}catch{try{return s[o]=!1,"/./"[a](s)}catch{}}return!1}},function(r,n,i){i(68);var o=i(25),a=i(8),s=i(5),c=i(93),l=i(21),f=s("species"),u=!a(function(){var v=/./;return v.exec=function(){var y=[];return y.groups={a:"7"},y},"".replace(v,"$")!=="7"}),d="a".replace(/./,"$0")==="$0",h=s("replace"),g=!!/./[h]&&/./[h]("a","$0")==="",p=!a(function(){var v=/(?:)/,y=v.exec;v.exec=function(){return y.apply(this,arguments)};var m="ab".split(v);return m.length!==2||m[0]!=="a"||m[1]!=="b"});r.exports=function(v,y,m,w){var x=s(v),C=!a(function(){var b={};return b[x]=function(){return 7},""[v](b)!=7}),S=C&&!a(function(){var b=!1,I=/a/;return v==="split"&&((I={}).constructor={},I.constructor[f]=function(){return I},I.flags="",I[x]=/./[x]),I.exec=function(){return b=!0,null},I[x](""),!b});if(!C||!S||v==="replace"&&(!u||!d||g)||v==="split"&&!p){var _=/./[x],T=m(x,""[v],function(b,I,P,M,L){return I.exec===c?C&&!L?{done:!0,value:_.call(I,P,M)}:{done:!0,value:b.call(P,I,M)}:{done:!1}},{REPLACE_KEEPS_$0:d,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:g}),E=T[0],D=T[1];o(String.prototype,v,E),o(RegExp.prototype,x,y==2?function(b,I){return D.call(b,this,I)}:function(b){return D.call(b,this)})}w&&l(RegExp.prototype[x],"sham",!0)}},function(r,n,i){var o=i(137).charAt;r.exports=function(a,s,c){return s+(c?o(a,s).length:1)}},function(r,n,i){var o=i(42),a=i(93);r.exports=function(s,c){var l=s.exec;if(typeof l=="function"){var f=l.call(s,c);if(typeof f!="object")throw TypeError("RegExp exec method returned something other than an Object or null");return f}if(o(s)!=="RegExp")throw TypeError("RegExp#exec called on incompatible receiver");return a.call(s,c)}},function(r,n,i){(function(o){Object.defineProperty(n,"__esModule",{value:!0});var a=i(96);n.forgivingBase64Encode=function(s){return o.from(s).toString("base64")},n.forgivingBase64Decode=function(s){return s===""?"":((s=s.replace(a.ASCIIWhiteSpace,"")).length%4==0&&(s.endsWith("==")?s=s.substr(0,s.length-2):s.endsWith("=")&&(s=s.substr(0,s.length-1))),s.length%4==1?null:/[0-9A-Za-z+/]/.test(s)?o.from(s,"base64").toString("utf8"):null)}}).call(this,i(145).Buffer)},function(r,n,i){n.byteLength=function(h){var g=u(h),p=g[0],v=g[1];return 3*(p+v)/4-v},n.toByteArray=function(h){var g,p,v=u(h),y=v[0],m=v[1],w=new s(function(S,_,T){return 3*(_+T)/4-T}(0,y,m)),x=0,C=m>0?y-4:y;for(p=0;p>16&255,w[x++]=g>>8&255,w[x++]=255&g;return m===2&&(g=a[h.charCodeAt(p)]<<2|a[h.charCodeAt(p+1)]>>4,w[x++]=255&g),m===1&&(g=a[h.charCodeAt(p)]<<10|a[h.charCodeAt(p+1)]<<4|a[h.charCodeAt(p+2)]>>2,w[x++]=g>>8&255,w[x++]=255&g),w},n.fromByteArray=function(h){for(var g,p=h.length,v=p%3,y=[],m=0,w=p-v;mw?w:m+16383));return v===1?(g=h[p-1],y.push(o[g>>2]+o[g<<4&63]+"==")):v===2&&(g=(h[p-2]<<8)+h[p-1],y.push(o[g>>10]+o[g>>4&63]+o[g<<2&63]+"=")),y.join("")};for(var o=[],a=[],s=typeof Uint8Array<"u"?Uint8Array:Array,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,f=c.length;l0)throw new Error("Invalid string. Length must be a multiple of 4");var p=h.indexOf("=");return p===-1&&(p=g),[p,p===g?0:4-p%4]}function d(h,g,p){for(var v,y,m=[],w=g;w>18&63]+o[y>>12&63]+o[y>>6&63]+o[63&y]);return m.join("")}a[45]=62,a[95]=63},function(r,n){n.read=function(i,o,a,s,c){var l,f,u=8*c-s-1,d=(1<>1,g=-7,p=a?c-1:0,v=a?-1:1,y=i[o+p];for(p+=v,l=y&(1<<-g)-1,y>>=-g,g+=u;g>0;l=256*l+i[o+p],p+=v,g-=8);for(f=l&(1<<-g)-1,l>>=-g,g+=s;g>0;f=256*f+i[o+p],p+=v,g-=8);if(l===0)l=1-h;else{if(l===d)return f?NaN:1/0*(y?-1:1);f+=Math.pow(2,s),l-=h}return(y?-1:1)*f*Math.pow(2,l-s)},n.write=function(i,o,a,s,c,l){var f,u,d,h=8*l-c-1,g=(1<>1,v=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=s?0:l-1,m=s?1:-1,w=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(u=isNaN(o)?1:0,f=g):(f=Math.floor(Math.log(o)/Math.LN2),o*(d=Math.pow(2,-f))<1&&(f--,d*=2),(o+=f+p>=1?v/d:v*Math.pow(2,1-p))*d>=2&&(f++,d/=2),f+p>=g?(u=0,f=g):f+p>=1?(u=(o*d-1)*Math.pow(2,c),f+=p):(u=o*Math.pow(2,p-1)*Math.pow(2,c),f=0));c>=8;i[a+y]=255&u,y+=m,u/=256,c-=8);for(f=f<0;i[a+y]=255&f,y+=m,f/=256,h-=8);i[a+y-m]|=128*w}},function(r,n){var i={}.toString;r.exports=Array.isArray||function(o){return i.call(o)=="[object Array]"}},function(r,n,i){var o=this&&this.__values||function(c){var l=typeof Symbol=="function"&&Symbol.iterator,f=l&&c[l],u=0;if(f)return f.call(c);if(c&&typeof c.length=="number")return{next:function(){return c&&u>=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(1);function s(c){var l,f;if(c===null||a.isString(c)||a.isNumber(c))return c;if(a.isArray(c)){var u=new Array;try{for(var d=o(c),h=d.next();!h.done;h=d.next()){var g=h.value;u.push(s(g))}}catch(y){l={error:y}}finally{try{h&&!h.done&&(f=d.return)&&f.call(d)}finally{if(l)throw l.error}}return u}if(a.isObject(c)){u=new Map;for(var p in c)if(c.hasOwnProperty(p)){var v=c[p];u.set(p,s(v))}return u}return c}n.parseJSONFromBytes=function(c){var l=a.utf8Decode(c);return JSON.parse.call(void 0,l)},n.serializeJSONToBytes=function(c){var l=JSON.stringify.call(void 0,c);return a.utf8Encode(l)},n.parseJSONIntoInfraValues=function(c){return s(JSON.parse.call(void 0,c))},n.convertAJSONDerivedJavaScriptValueToAnInfraValue=s},function(r,n,i){var o=this&&this.__generator||function(f,u){var d,h,g,p,v={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return p={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function y(m){return function(w){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;v;)try{if(d=1,h&&(g=2&x[0]?h.return:x[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,x[1])).done)return g;switch(h=0,g&&(x=[2&x[0],g.value]),x[0]){case 0:case 1:g=x;break;case 4:return v.label++,{value:x[1],done:!1};case 5:v.label++,h=x[1],x=[0];continue;case 7:x=v.ops.pop(),v.trys.pop();continue;default:if(g=v.trys,!((g=g.length>0&&g[g.length-1])||x[0]!==6&&x[0]!==2)){v=0;continue}if(x[0]===3&&(!g||x[1]>g[0]&&x[1]0)&&!(h=p.next()).done;)v.push(h.value)}catch(y){g={error:y}}finally{try{h&&!h.done&&(d=p.return)&&d.call(p)}finally{if(g)throw g.error}}return v},s=this&&this.__spread||function(){for(var f=[],u=0;u=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var l=i(1);n.append=function(f,u){f.push(u)},n.extend=function(f,u){f.push.apply(f,s(u))},n.prepend=function(f,u){f.unshift(u)},n.replace=function(f,u,d){var h,g,p=0;try{for(var v=c(f),y=v.next();!y.done;y=v.next()){var m=y.value;if(l.isFunction(u))u.call(null,m)&&(f[p]=d);else if(m===u)return void(f[p]=d);p++}}catch(w){h={error:w}}finally{try{y&&!y.done&&(g=v.return)&&g.call(v)}finally{if(h)throw h.error}}},n.insert=function(f,u,d){f.splice(d,0,u)},n.remove=function(f,u){for(var d=f.length;d--;){var h=f[d];if(l.isFunction(u))u.call(null,h)&&f.splice(d,1);else if(h===u)return void f.splice(d,1)}},n.empty=function(f){f.length=0},n.contains=function(f,u){var d,h;try{for(var g=c(f),p=g.next();!p.done;p=g.next()){var v=p.value;if(l.isFunction(u)){if(u.call(null,v))return!0}else if(v===u)return!0}}catch(y){d={error:y}}finally{try{p&&!p.done&&(h=g.return)&&h.call(g)}finally{if(d)throw d.error}}return!1},n.size=function(f,u){var d,h;if(u===void 0)return f.length;var g=0;try{for(var p=c(f),v=p.next();!v.done;v=p.next()){var y=v.value;u.call(null,y)&&g++}}catch(m){d={error:m}}finally{try{v&&!v.done&&(h=p.return)&&h.call(p)}finally{if(d)throw d.error}}return g},n.isEmpty=function(f){return f.length===0},n.forEach=function(f,u){var d,h,g,p,v,y;return o(this,function(m){switch(m.label){case 0:return u!==void 0?[3,2]:[5,c(f)];case 1:return m.sent(),[3,9];case 2:m.trys.push([2,7,8,9]),d=c(f),h=d.next(),m.label=3;case 3:return h.done?[3,6]:(g=h.value,u.call(null,g)?[4,g]:[3,5]);case 4:m.sent(),m.label=5;case 5:return h=d.next(),[3,3];case 6:return[3,9];case 7:return p=m.sent(),v={error:p},[3,9];case 8:try{h&&!h.done&&(y=d.return)&&y.call(d)}finally{if(v)throw v.error}return[7];case 9:return[2]}})},n.clone=function(f){return new(Array.bind.apply(Array,s([void 0],f)))},n.sortInAscendingOrder=function(f,u){return f.sort(function(d,h){return u.call(null,d,h)?-1:1})},n.sortInDescendingOrder=function(f,u){return f.sort(function(d,h){return u.call(null,d,h)?1:-1})}},function(r,n,i){var o=this&&this.__generator||function(f,u){var d,h,g,p,v={label:0,sent:function(){if(1&g[0])throw g[1];return g[1]},trys:[],ops:[]};return p={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function y(m){return function(w){return function(x){if(d)throw new TypeError("Generator is already executing.");for(;v;)try{if(d=1,h&&(g=2&x[0]?h.return:x[0]?h.throw||((g=h.return)&&g.call(h),0):h.next)&&!(g=g.call(h,x[1])).done)return g;switch(h=0,g&&(x=[2&x[0],g.value]),x[0]){case 0:case 1:g=x;break;case 4:return v.label++,{value:x[1],done:!1};case 5:v.label++,h=x[1],x=[0];continue;case 7:x=v.ops.pop(),v.trys.pop();continue;default:if(g=v.trys,!((g=g.length>0&&g[g.length-1])||x[0]!==6&&x[0]!==2)){v=0;continue}if(x[0]===3&&(!g||x[1]>g[0]&&x[1]=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(f,u){var d=typeof Symbol=="function"&&f[Symbol.iterator];if(!d)return f;var h,g,p=d.call(f),v=[];try{for(;(u===void 0||u-- >0)&&!(h=p.next()).done;)v.push(h.value)}catch(y){g={error:y}}finally{try{h&&!h.done&&(d=p.return)&&d.call(p)}finally{if(g)throw g.error}}return v},c=this&&this.__spread||function(){for(var f=[],u=0;u0&&p[p.length-1])||C[0]!==6&&C[0]!==2)){y=0;continue}if(C[0]===3&&(!p||C[1]>p[0]&&C[1]=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(u,d){var h=typeof Symbol=="function"&&u[Symbol.iterator];if(!h)return u;var g,p,v=h.call(u),y=[];try{for(;(d===void 0||d-- >0)&&!(g=v.next()).done;)y.push(g.value)}catch(m){p={error:m}}finally{try{g&&!g.done&&(h=v.return)&&h.call(v)}finally{if(p)throw p.error}}return y},c=this&&this.__spread||function(){for(var u=[],d=0;d=y.length&&(y=void 0),{value:y&&y[x++],done:!y}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(96),s=i(147),c=i(146),l=i(1);function f(y,m){for(var w=0;;){var x=w=65&&T<=90?String.fromCodePoint(T+32):_}}catch(E){m={error:E}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x}function g(y){return y.replace(/^[\t\n\f\r ]+/,"").replace(/[\t\n\f\r ]+$/,"")}function p(y,m,w){if(!l.isArray(m))return p(y,Array.from(m),w);for(var x="";w.position=97&&T<=122?String.fromCodePoint(T-32):_}}catch(E){m={error:E}}finally{try{S&&!S.done&&(w=C.return)&&w.call(C)}finally{if(m)throw m.error}}return x},n.asciiCaseInsensitiveMatch=function(y,m){return h(y)===h(m)},n.asciiEncode=function(y){return console.assert(d(y),"asciiEncode requires an ASCII string."),u(y)},n.asciiDecode=function(y){var m,w;try{for(var x=o(y),C=x.next();!C.done;C=x.next()){var S=C.value;console.assert(c.isASCIIByte(S),"asciiDecode requires an ASCII byte sequence.")}}catch(_){m={error:_}}finally{try{C&&!C.done&&(w=x.return)&&w.call(x)}finally{if(m)throw m.error}}return s.isomorphicDecode(y)},n.stripNewlines=function(y){return y.replace(/[\n\r]/g,"")},n.normalizeNewlines=function(y){return y.replace(/\r\n/g,` `).replace(/\r/g,` `)},n.stripLeadingAndTrailingASCIIWhitespace=g,n.stripAndCollapseASCIIWhitespace=function(y){return g(y.replace(/[\t\n\f\r ]{2,}/g," "))},n.collectASequenceOfCodePoints=p,n.skipASCIIWhitespace=v,n.strictlySplit=function y(m,w){if(!l.isArray(m))return y(Array.from(m),w);var x={position:0},C=[],S=p(function(_){return w!==_},m,x);for(C.push(S);x.position=s.length&&(s=void 0),{value:s&&s[f++],done:!s}}};throw new TypeError(c?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(97);n.abort_add=function(s,c){c._abortedFlag||c._abortAlgorithms.add(s)},n.abort_remove=function(s,c){c._abortAlgorithms.delete(s)},n.abort_signalAbort=function(s){var c,l;if(!s._abortedFlag){s._abortedFlag=!0;try{for(var f=o(s._abortAlgorithms),u=f.next();!u.done;u=f.next())u.value.call(s)}catch(d){c={error:d}}finally{try{u&&!u.done&&(l=f.return)&&l.call(f)}finally{if(c)throw c.error}}s._abortAlgorithms.clear(),a.event_fireAnEvent("abort",s)}}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(150),a=function(){function s(){}return s.asNode=function(c){if(o.Guard.isNode(c))return c;throw new Error("Invalid object. Node expected.")},s}();n.Cast=a},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function s(){}return Object.defineProperty(s.prototype,"size",{get:function(){return 0},enumerable:!0,configurable:!0}),s.prototype.add=function(c){throw new Error("Cannot add to an empty set.")},s.prototype.clear=function(){},s.prototype.delete=function(c){return!1},s.prototype.forEach=function(c,l){},s.prototype.has=function(c){return!1},s.prototype[Symbol.iterator]=function(){return new a},s.prototype.entries=function(){return new a},s.prototype.keys=function(){return new a},s.prototype.values=function(){return new a},Object.defineProperty(s.prototype,Symbol.toStringTag,{get:function(){return"EmptySet"},enumerable:!0,configurable:!0}),s}();n.EmptySet=o;var a=function(){function s(){}return s.prototype[Symbol.iterator]=function(){return this},s.prototype.next=function(){return{done:!0,value:null}},s}()},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),function(o){o[o.SchemeStart=0]="SchemeStart",o[o.Scheme=1]="Scheme",o[o.NoScheme=2]="NoScheme",o[o.SpecialRelativeOrAuthority=3]="SpecialRelativeOrAuthority",o[o.PathOrAuthority=4]="PathOrAuthority",o[o.Relative=5]="Relative",o[o.RelativeSlash=6]="RelativeSlash",o[o.SpecialAuthoritySlashes=7]="SpecialAuthoritySlashes",o[o.SpecialAuthorityIgnoreSlashes=8]="SpecialAuthorityIgnoreSlashes",o[o.Authority=9]="Authority",o[o.Host=10]="Host",o[o.Hostname=11]="Hostname",o[o.Port=12]="Port",o[o.File=13]="File",o[o.FileSlash=14]="FileSlash",o[o.FileHost=15]="FileHost",o[o.PathStart=16]="PathStart",o[o.Path=17]="Path",o[o.CannotBeABaseURLPath=18]="CannotBeABaseURLPath",o[o.Query=19]="Query",o[o.Fragment=20]="Fragment"}(n.ParserState||(n.ParserState={})),n.OpaqueOrigin=["","",null,null]},function(r,n,i){var o=i(245),a=i(247);function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=C,n.resolve=function(S,_){return C(S,!1,!0).resolve(_)},n.resolveObject=function(S,_){return S?C(S,!1,!0).resolveObject(_):_},n.format=function(S){return a.isString(S)&&(S=C(S)),S instanceof s?S.format():s.prototype.format.call(S)},n.Url=s;var c=/^([a-z0-9.+-]+:)/i,l=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,u=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r",` -`," "]),d=["'"].concat(u),h=["%","/","?",";","#"].concat(d),g=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},m={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},x=i(248);function C(S,_,T){if(S&&a.isObject(S)&&S instanceof s)return S;var E=new s;return E.parse(S,_,T),E}s.prototype.parse=function(S,_,T){if(!a.isString(S))throw new TypeError("Parameter 'url' must be a string, not "+typeof S);var E=S.indexOf("?"),D=E!==-1&&E127?pe+="x":pe+=ce[Ee];if(!pe.match(p)){var Se=re.slice(0,F),B=re.slice(F+1),O=ce.match(v);O&&(Se.push(O[1]),B.unshift(O[2])),B.length&&(I="/"+B.join(".")+I),this.hostname=Se.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),Y||(this.hostname=o.toASCII(this.hostname));var z=this.port?":"+this.port:"",W=this.hostname||"";this.host=W+z,this.href+=this.host,Y&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),I[0]!=="/"&&(I="/"+I))}if(!y[L])for(F=0,ue=d.length;F0)&&T.host.split("@"))&&(T.auth=O.shift(),T.host=T.hostname=O.shift())),T.search=S.search,T.query=S.query,a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.href=T.format(),T;if(!ce.length)return T.pathname=null,T.search?T.path="/"+T.search:T.path=null,T.href=T.format(),T;for(var Ee=ce.slice(-1)[0],Oe=(T.host||S.host||ce.length>1)&&(Ee==="."||Ee==="..")||Ee==="",Se=0,B=ce.length;B>=0;B--)(Ee=ce[B])==="."?ce.splice(B,1):Ee===".."?(ce.splice(B,1),Se++):Se&&(ce.splice(B,1),Se--);if(!re&&!ue)for(;Se--;Se)ce.unshift("..");!re||ce[0]===""||ce[0]&&ce[0].charAt(0)==="/"||ce.unshift(""),Oe&&ce.join("/").substr(-1)!=="/"&&ce.push("");var O,z=ce[0]===""||ce[0]&&ce[0].charAt(0)==="/";return pe&&(T.hostname=T.host=z?"":ce.length?ce.shift():"",(O=!!(T.host&&T.host.indexOf("@")>0)&&T.host.split("@"))&&(T.auth=O.shift(),T.host=T.hostname=O.shift())),(re=re||T.host&&ce.length)&&!z&&ce.unshift(""),ce.length?T.pathname=ce.join("/"):(T.pathname=null,T.path=null),a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.auth=S.auth||T.auth,T.slashes=T.slashes||S.slashes,T.href=T.format(),T},s.prototype.parseHost=function(){var S=this.host,_=l.exec(S);_&&((_=_[0])!==":"&&(this.port=_.substr(1)),S=S.substr(0,S.length-_.length)),S&&(this.hostname=S)}},function(r,n,i){(function(o,a){var s;/*! https://mths.be/punycode v1.4.1 by @mathias */(function(c){n&&n.nodeType,o&&o.nodeType;var l=typeof a=="object"&&a;l.global!==l&&l.window!==l&&l.self;var f,u=2147483647,d=/^xn--/,h=/[^\x20-\x7E]/,g=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},v=Math.floor,y=String.fromCharCode;function m(b){throw new RangeError(p[b])}function w(b,I){for(var P=b.length,M=[];P--;)M[P]=I(b[P]);return M}function x(b,I){var P=b.split("@"),M="";return P.length>1&&(M=P[0]+"@",b=P[1]),M+w((b=b.replace(g,".")).split("."),I).join(".")}function C(b){for(var I,P,M=[],L=0,V=b.length;L=55296&&I<=56319&&L65535&&(P+=y((I-=65536)>>>10&1023|55296),I=56320|1023&I),P+=y(I)}).join("")}function _(b,I){return b+22+75*(b<26)-((I!=0)<<5)}function T(b,I,P){var M=0;for(b=P?v(b/700):b>>1,b+=v(b/I);b>455;M+=36)b=v(b/35);return v(M+36*b/(b+38))}function E(b){var I,P,M,L,V,G,A,k,F,j,Y,re=[],ue=b.length,ce=0,pe=128,Ee=72;for((P=b.lastIndexOf("-"))<0&&(P=0),M=0;M=128&&m("not-basic"),re.push(b.charCodeAt(M));for(L=P>0?P+1:0;L=ue&&m("invalid-input"),((k=(Y=b.charCodeAt(L++))-48<10?Y-22:Y-65<26?Y-65:Y-97<26?Y-97:36)>=36||k>v((u-ce)/G))&&m("overflow"),ce+=k*G,!(k<(F=A<=Ee?1:A>=Ee+26?26:A-Ee));A+=36)G>v(u/(j=36-F))&&m("overflow"),G*=j;Ee=T(ce-V,I=re.length+1,V==0),v(ce/I)>u-pe&&m("overflow"),pe+=v(ce/I),ce%=I,re.splice(ce++,0,pe)}return S(re)}function D(b){var I,P,M,L,V,G,A,k,F,j,Y,re,ue,ce,pe,Ee=[];for(re=(b=C(b)).length,I=128,P=0,V=72,G=0;G=I&&Yv((u-P)/(ue=M+1))&&m("overflow"),P+=(A-I)*ue,I=A,G=0;Gu&&m("overflow"),Y==I){for(k=P,F=36;!(k<(j=F<=V?1:F>=V+26?26:F-V));F+=36)pe=k-j,ce=36-j,Ee.push(y(_(j+pe%ce,0))),k=v(pe/ce);Ee.push(y(_(k,0))),V=T(P,ue,M==L),P=0,++M}++P,++I}return Ee.join("")}f={version:"1.4.1",ucs2:{decode:C,encode:S},decode:E,encode:D,toASCII:function(b){return x(b,function(I){return h.test(I)?"xn--"+D(I):I})},toUnicode:function(b){return x(b,function(I){return d.test(I)?E(I.slice(4).toLowerCase()):I})}},(s=(function(){return f}).call(n,i,n,o))===void 0||(o.exports=s)})()}).call(this,i(246)(r),i(78))},function(r,n){r.exports=function(i){return i.webpackPolyfill||(i.deprecate=function(){},i.paths=[],i.children||(i.children=[]),Object.defineProperty(i,"loaded",{enumerable:!0,get:function(){return i.l}}),Object.defineProperty(i,"id",{enumerable:!0,get:function(){return i.i}}),i.webpackPolyfill=1),i}},function(r,n,i){r.exports={isString:function(o){return typeof o=="string"},isObject:function(o){return typeof o=="object"&&o!==null},isNull:function(o){return o===null},isNullOrUndefined:function(o){return o==null}}},function(r,n,i){n.decode=n.parse=i(249),n.encode=n.stringify=i(250)},function(r,n,i){function o(s,c){return Object.prototype.hasOwnProperty.call(s,c)}r.exports=function(s,c,l,f){c=c||"&",l=l||"=";var u={};if(typeof s!="string"||s.length===0)return u;var d=/\+/g;s=s.split(c);var h=1e3;f&&typeof f.maxKeys=="number"&&(h=f.maxKeys);var g=s.length;h>0&&g>h&&(g=h);for(var p=0;p=0?(v=x.substr(0,C),y=x.substr(C+1)):(v=x,y=""),m=decodeURIComponent(v),w=decodeURIComponent(y),o(u,m)?a(u[m])?u[m].push(w):u[m]=[u[m],w]:u[m]=w}return u};var a=Array.isArray||function(s){return Object.prototype.toString.call(s)==="[object Array]"}},function(r,n,i){var o=function(l){switch(typeof l){case"string":return l;case"boolean":return l?"true":"false";case"number":return isFinite(l)?l:"";default:return""}};r.exports=function(l,f,u,d){return f=f||"&",u=u||"=",l===null&&(l=void 0),typeof l=="object"?s(c(l),function(h){var g=encodeURIComponent(o(h))+u;return a(l[h])?s(l[h],function(p){return g+encodeURIComponent(o(p))}).join(f):g+encodeURIComponent(o(l[h]))}).join(f):d?encodeURIComponent(o(d))+u+encodeURIComponent(o(l)):""};var a=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"};function s(l,f){if(l.map)return l.map(f);for(var u=[],d=0;d=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(1);function s(c){return a.isBoolean(c)?c:c.capture||!1}n.eventTarget_flatten=s,n.eventTarget_flattenMore=function(c){var l=s(c),f=!1,u=!1;return a.isBoolean(c)||(f=c.once||!1,u=c.passive||!1),[l,u,f]},n.eventTarget_addEventListener=function(c,l){if(l.callback!==null){for(var f=0;f=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(1),s=i(29);n.parentNode_convertNodesIntoANode=function(c,l){for(var f,u,d=null,h=0;h=_.length&&(_=void 0),{value:_&&_[D++],done:!_}}};throw new TypeError(T?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(_,T){var E=typeof Symbol=="function"&&_[Symbol.iterator];if(!E)return _;var D,b,I=E.call(_),P=[];try{for(;(T===void 0||T-- >0)&&!(D=I.next()).done;)P.push(D.value)}catch(M){b={error:M}}finally{try{D&&!D.done&&(E=I.return)&&E.call(I)}finally{if(b)throw b.error}}return P},s=this&&this.__spread||function(){for(var _=[],T=0;T0;ce--){var pe;if(C(pe=ue[ce],_)){re=pe;break}}var Ee,Oe,Se=[];try{for(var B=o(k._children),O=B.next();!O.done;O=B.next())if(x(xe=O.value,_)){if(f.Guard.isDocumentTypeNode(xe))throw new l.HierarchyRequestError;Se.push(xe)}}catch(De){D={error:De}}finally{try{O&&!O.done&&(b=B.return)&&b.call(B)}finally{if(D)throw D.error}}if(d.tree_isAncestorOf(G,L,!0))Ee=L,Oe=V;else{for(var z=L;z._parent!==null&&!d.tree_isAncestorOf(G,z._parent);)z=z._parent;if(z._parent===null)throw new Error("Parent node is null.");Ee=z._parent,Oe=1+d.tree_index(z)}if(f.Guard.isCharacterDataNode(F))(W=p.node_clone(L))._data=g.characterData_substringData(L,V,d.tree_nodeLength(L)-V),v.mutation_append(W,M),g.characterData_replaceData(L,V,d.tree_nodeLength(L)-V,"");else if(F!==null){var W=p.node_clone(F);v.mutation_append(W,M);var K=S(u.create_range([L,V],[F,d.tree_nodeLength(F)]));v.mutation_append(K,W)}try{for(var Z=o(Se),ee=Z.next();!ee.done;ee=Z.next()){var xe=ee.value;v.mutation_append(xe,M)}}catch(De){I={error:De}}finally{try{ee&&!ee.done&&(P=Z.return)&&P.call(Z)}finally{if(I)throw I.error}}return f.Guard.isCharacterDataNode(re)?((W=p.node_clone(G))._data=g.characterData_substringData(G,0,A),v.mutation_append(W,M),g.characterData_replaceData(G,0,A,"")):re!==null&&(W=p.node_clone(re),v.mutation_append(W,M),K=S(u.create_range([re,0],[G,A])),v.mutation_append(K,W)),_._start=[Ee,Oe],_._end=[Ee,Oe],M}n.range_collapsed=m,n.range_root=w,n.range_isContained=x,n.range_isPartiallyContained=C,n.range_setTheStart=function(_,T,E){if(f.Guard.isDocumentTypeNode(T))throw new l.InvalidNodeTypeError;if(E>d.tree_nodeLength(T))throw new l.IndexSizeError;var D=[T,E];w(_)===d.tree_rootNode(T)&&h.boundaryPoint_position(D,_._end)!==c.BoundaryPosition.After||(_._end=D),_._start=D},n.range_setTheEnd=function(_,T,E){if(f.Guard.isDocumentTypeNode(T))throw new l.InvalidNodeTypeError;if(E>d.tree_nodeLength(T))throw new l.IndexSizeError;var D=[T,E];w(_)===d.tree_rootNode(T)&&h.boundaryPoint_position(D,_._start)!==c.BoundaryPosition.Before||(_._start=D),_._end=D},n.range_select=function(_,T){var E=_._parent;if(E===null)throw new l.InvalidNodeTypeError;var D=d.tree_index(_);T._start=[E,D],T._end=[E,D+1]},n.range_extract=S,n.range_cloneTheContents=function _(T){var E,D,b,I,P,M,L=u.create_documentFragment(T._startNode._nodeDocument);if(m(T))return L;var V=T._startNode,G=T._startOffset,A=T._endNode,k=T._endOffset;V===A&&f.Guard.isCharacterDataNode(V)&&((O=p.node_clone(V))._data=g.characterData_substringData(V,G,k-G),v.mutation_append(O,L));for(var F=V;!d.tree_isAncestorOf(A,F,!0);){if(F._parent===null)throw new Error("Parent node is null.");F=F._parent}var j=null;if(!d.tree_isAncestorOf(A,V,!0))try{for(var Y=o(F._children),re=Y.next();!re.done;re=Y.next())if(C(Ee=re.value,T)){j=Ee;break}}catch(ee){E={error:ee}}finally{try{re&&!re.done&&(D=Y.return)&&D.call(Y)}finally{if(E)throw E.error}}var ue=null;if(!d.tree_isAncestorOf(V,A,!0))for(var ce=s(F._children),pe=ce.length-1;pe>0;pe--){var Ee;if(C(Ee=ce[pe],T)){ue=Ee;break}}var Oe=[];try{for(var Se=o(F._children),B=Se.next();!B.done;B=Se.next())if(x(Z=B.value,T)){if(f.Guard.isDocumentTypeNode(Z))throw new l.HierarchyRequestError;Oe.push(Z)}}catch(ee){b={error:ee}}finally{try{B&&!B.done&&(I=Se.return)&&I.call(Se)}finally{if(b)throw b.error}}if(f.Guard.isCharacterDataNode(j))(O=p.node_clone(V))._data=g.characterData_substringData(V,G,d.tree_nodeLength(V)-G),v.mutation_append(O,L);else if(j!==null){var O=p.node_clone(j);v.mutation_append(O,L);var z=_(u.create_range([V,G],[j,d.tree_nodeLength(j)]));v.mutation_append(z,O)}try{for(var W=o(Oe),K=W.next();!K.done;K=W.next()){var Z=K.value,O=p.node_clone(Z);v.mutation_append(O,L)}}catch(ee){P={error:ee}}finally{try{K&&!K.done&&(M=W.return)&&M.call(W)}finally{if(P)throw P.error}}return f.Guard.isCharacterDataNode(ue)?((O=p.node_clone(A))._data=g.characterData_substringData(A,0,k),v.mutation_append(O,L)):ue!==null&&(O=p.node_clone(ue),L.append(O),z=S(u.create_range([ue,0],[A,k])),v.mutation_append(z,O)),L},n.range_insert=function(_,T){var E,D;if(f.Guard.isProcessingInstructionNode(T._startNode)||f.Guard.isCommentNode(T._startNode)||f.Guard.isTextNode(T._startNode)&&T._startNode._parent===null||T._startNode===_)throw new l.HierarchyRequestError;var b,I=null;if(f.Guard.isTextNode(T._startNode))I=T._startNode;else{var P=0;try{for(var M=o(T._startNode._children),L=M.next();!L.done;L=M.next()){var V=L.value;if(P===T._startOffset){I=V;break}P++}}catch(A){E={error:A}}finally{try{L&&!L.done&&(D=M.return)&&D.call(M)}finally{if(E)throw E.error}}}if(I===null)b=T._startNode;else{if(I._parent===null)throw new Error("Parent node is null.");b=I._parent}v.mutation_ensurePreInsertionValidity(_,b,I),f.Guard.isTextNode(T._startNode)&&(I=y.text_split(T._startNode,T._startOffset)),_===I&&(I=_._nextSibling),_._parent!==null&&v.mutation_remove(_,_._parent);var G=I===null?d.tree_nodeLength(b):d.tree_index(I);f.Guard.isDocumentFragmentNode(_)?G+=d.tree_nodeLength(_):G++,v.mutation_preInsert(_,b,I),m(T)&&(T._end=[b,G])},n.range_getContainedNodes=function(_){var T;return(T={})[Symbol.iterator]=function(){var E=_.commonAncestorContainer,D=d.tree_getFirstDescendantNode(E);return{next:function(){for(;D&&!x(D,_);)D=d.tree_getNextDescendantNode(E,D);if(D===null)return{done:!0,value:null};var b={done:!1,value:D};return D=d.tree_getNextDescendantNode(E,D),b}}},T},n.range_getPartiallyContainedNodes=function(_){var T;return(T={})[Symbol.iterator]=function(){var E=_.commonAncestorContainer,D=d.tree_getFirstDescendantNode(E);return{next:function(){for(;D&&!C(D,_);)D=d.tree_getNextDescendantNode(E,D);if(D===null)return{done:!0,value:null};var b={done:!1,value:D};return D=d.tree_getNextDescendantNode(E,D),b}}},T}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(9);n.selectors_scopeMatchASelectorsString=function(a,s){throw new o.NotSupportedError}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(105);n.treeWalker_traverseChildren=function(s,c){for(var l=c?s._current._firstChild:s._current._lastChild;l!==null;){var f=a.traversal_filter(s,l);if(f===o.FilterResult.Accept)return s._current=l,l;if(f===o.FilterResult.Skip){var u=c?l._firstChild:l._lastChild;if(u!==null){l=u;continue}}for(;l!==null;){var d=c?l._nextSibling:l._previousSibling;if(d!==null){l=d;break}var h=l._parent;if(h===null||h===s._root||h===s._current)return null;l=h}}return null},n.treeWalker_traverseSiblings=function(s,c){var l=s._current;if(l===s._root)return null;for(;;){for(var f=c?l._nextSibling:l._previousSibling;f!==null;){l=f;var u=a.traversal_filter(s,l);if(u===o.FilterResult.Accept)return s._current=l,l;f=c?l._firstChild:l._lastChild,u!==o.FilterResult.Reject&&f!==null||(f=c?l._nextSibling:l._previousSibling)}if((l=l._parent)===null||l===s._root||a.traversal_filter(s,l)===o.FilterResult.Accept)return null}}},function(r,n,i){i(89),i(74);var o,a=this&&this.__extends||(o=function(d,h){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,p){g.__proto__=p}||function(g,p){for(var v in p)p.hasOwnProperty(v)&&(g[v]=p[v])})(d,h)},function(d,h){function g(){this.constructor=d}o(d,h),d.prototype=h===null?Object.create(h):(g.prototype=h.prototype,new g)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(1),c=i(2),l=i(50),f=i(3),u=function(d){function h(g,p){var v=d.call(this,g)||this;return v._indentation={},v._lengthToLastNewline=0,v._writerOptions=s.applyDefaults(p,{wellFormed:!1,headless:!1,prettyPrint:!1,indent:" ",newline:` +`," "]),d=["'"].concat(u),h=["%","/","?",";","#"].concat(d),g=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,v=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},m={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},x=i(248);function C(S,_,T){if(S&&a.isObject(S)&&S instanceof s)return S;var E=new s;return E.parse(S,_,T),E}s.prototype.parse=function(S,_,T){if(!a.isString(S))throw new TypeError("Parameter 'url' must be a string, not "+typeof S);var E=S.indexOf("?"),D=E!==-1&&E127?pe+="x":pe+=ce[Ee];if(!pe.match(p)){var _e=re.slice(0,F),B=re.slice(F+1),O=ce.match(v);O&&(_e.push(O[1]),B.unshift(O[2])),B.length&&(I="/"+B.join(".")+I),this.hostname=_e.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),Y||(this.hostname=o.toASCII(this.hostname));var z=this.port?":"+this.port:"",W=this.hostname||"";this.host=W+z,this.href+=this.host,Y&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),I[0]!=="/"&&(I="/"+I))}if(!y[L])for(F=0,ue=d.length;F0)&&T.host.split("@"))&&(T.auth=O.shift(),T.host=T.hostname=O.shift())),T.search=S.search,T.query=S.query,a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.href=T.format(),T;if(!ce.length)return T.pathname=null,T.search?T.path="/"+T.search:T.path=null,T.href=T.format(),T;for(var Ee=ce.slice(-1)[0],Oe=(T.host||S.host||ce.length>1)&&(Ee==="."||Ee==="..")||Ee==="",_e=0,B=ce.length;B>=0;B--)(Ee=ce[B])==="."?ce.splice(B,1):Ee===".."?(ce.splice(B,1),_e++):_e&&(ce.splice(B,1),_e--);if(!re&&!ue)for(;_e--;_e)ce.unshift("..");!re||ce[0]===""||ce[0]&&ce[0].charAt(0)==="/"||ce.unshift(""),Oe&&ce.join("/").substr(-1)!=="/"&&ce.push("");var O,z=ce[0]===""||ce[0]&&ce[0].charAt(0)==="/";return pe&&(T.hostname=T.host=z?"":ce.length?ce.shift():"",(O=!!(T.host&&T.host.indexOf("@")>0)&&T.host.split("@"))&&(T.auth=O.shift(),T.host=T.hostname=O.shift())),(re=re||T.host&&ce.length)&&!z&&ce.unshift(""),ce.length?T.pathname=ce.join("/"):(T.pathname=null,T.path=null),a.isNull(T.pathname)&&a.isNull(T.search)||(T.path=(T.pathname?T.pathname:"")+(T.search?T.search:"")),T.auth=S.auth||T.auth,T.slashes=T.slashes||S.slashes,T.href=T.format(),T},s.prototype.parseHost=function(){var S=this.host,_=l.exec(S);_&&((_=_[0])!==":"&&(this.port=_.substr(1)),S=S.substr(0,S.length-_.length)),S&&(this.hostname=S)}},function(r,n,i){(function(o,a){var s;/*! https://mths.be/punycode v1.4.1 by @mathias */(function(c){n&&n.nodeType,o&&o.nodeType;var l=typeof a=="object"&&a;l.global!==l&&l.window!==l&&l.self;var f,u=2147483647,d=/^xn--/,h=/[^\x20-\x7E]/,g=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},v=Math.floor,y=String.fromCharCode;function m(b){throw new RangeError(p[b])}function w(b,I){for(var P=b.length,M=[];P--;)M[P]=I(b[P]);return M}function x(b,I){var P=b.split("@"),M="";return P.length>1&&(M=P[0]+"@",b=P[1]),M+w((b=b.replace(g,".")).split("."),I).join(".")}function C(b){for(var I,P,M=[],L=0,V=b.length;L=55296&&I<=56319&&L65535&&(P+=y((I-=65536)>>>10&1023|55296),I=56320|1023&I),P+=y(I)}).join("")}function _(b,I){return b+22+75*(b<26)-((I!=0)<<5)}function T(b,I,P){var M=0;for(b=P?v(b/700):b>>1,b+=v(b/I);b>455;M+=36)b=v(b/35);return v(M+36*b/(b+38))}function E(b){var I,P,M,L,V,G,A,k,F,j,Y,re=[],ue=b.length,ce=0,pe=128,Ee=72;for((P=b.lastIndexOf("-"))<0&&(P=0),M=0;M=128&&m("not-basic"),re.push(b.charCodeAt(M));for(L=P>0?P+1:0;L=ue&&m("invalid-input"),((k=(Y=b.charCodeAt(L++))-48<10?Y-22:Y-65<26?Y-65:Y-97<26?Y-97:36)>=36||k>v((u-ce)/G))&&m("overflow"),ce+=k*G,!(k<(F=A<=Ee?1:A>=Ee+26?26:A-Ee));A+=36)G>v(u/(j=36-F))&&m("overflow"),G*=j;Ee=T(ce-V,I=re.length+1,V==0),v(ce/I)>u-pe&&m("overflow"),pe+=v(ce/I),ce%=I,re.splice(ce++,0,pe)}return S(re)}function D(b){var I,P,M,L,V,G,A,k,F,j,Y,re,ue,ce,pe,Ee=[];for(re=(b=C(b)).length,I=128,P=0,V=72,G=0;G=I&&Yv((u-P)/(ue=M+1))&&m("overflow"),P+=(A-I)*ue,I=A,G=0;Gu&&m("overflow"),Y==I){for(k=P,F=36;!(k<(j=F<=V?1:F>=V+26?26:F-V));F+=36)pe=k-j,ce=36-j,Ee.push(y(_(j+pe%ce,0))),k=v(pe/ce);Ee.push(y(_(k,0))),V=T(P,ue,M==L),P=0,++M}++P,++I}return Ee.join("")}f={version:"1.4.1",ucs2:{decode:C,encode:S},decode:E,encode:D,toASCII:function(b){return x(b,function(I){return h.test(I)?"xn--"+D(I):I})},toUnicode:function(b){return x(b,function(I){return d.test(I)?E(I.slice(4).toLowerCase()):I})}},(s=(function(){return f}).call(n,i,n,o))===void 0||(o.exports=s)})()}).call(this,i(246)(r),i(78))},function(r,n){r.exports=function(i){return i.webpackPolyfill||(i.deprecate=function(){},i.paths=[],i.children||(i.children=[]),Object.defineProperty(i,"loaded",{enumerable:!0,get:function(){return i.l}}),Object.defineProperty(i,"id",{enumerable:!0,get:function(){return i.i}}),i.webpackPolyfill=1),i}},function(r,n,i){r.exports={isString:function(o){return typeof o=="string"},isObject:function(o){return typeof o=="object"&&o!==null},isNull:function(o){return o===null},isNullOrUndefined:function(o){return o==null}}},function(r,n,i){n.decode=n.parse=i(249),n.encode=n.stringify=i(250)},function(r,n,i){function o(s,c){return Object.prototype.hasOwnProperty.call(s,c)}r.exports=function(s,c,l,f){c=c||"&",l=l||"=";var u={};if(typeof s!="string"||s.length===0)return u;var d=/\+/g;s=s.split(c);var h=1e3;f&&typeof f.maxKeys=="number"&&(h=f.maxKeys);var g=s.length;h>0&&g>h&&(g=h);for(var p=0;p=0?(v=x.substr(0,C),y=x.substr(C+1)):(v=x,y=""),m=decodeURIComponent(v),w=decodeURIComponent(y),o(u,m)?a(u[m])?u[m].push(w):u[m]=[u[m],w]:u[m]=w}return u};var a=Array.isArray||function(s){return Object.prototype.toString.call(s)==="[object Array]"}},function(r,n,i){var o=function(l){switch(typeof l){case"string":return l;case"boolean":return l?"true":"false";case"number":return isFinite(l)?l:"";default:return""}};r.exports=function(l,f,u,d){return f=f||"&",u=u||"=",l===null&&(l=void 0),typeof l=="object"?s(c(l),function(h){var g=encodeURIComponent(o(h))+u;return a(l[h])?s(l[h],function(p){return g+encodeURIComponent(o(p))}).join(f):g+encodeURIComponent(o(l[h]))}).join(f):d?encodeURIComponent(o(d))+u+encodeURIComponent(o(l)):""};var a=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"};function s(l,f){if(l.map)return l.map(f);for(var u=[],d=0;d=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(1);function s(c){return a.isBoolean(c)?c:c.capture||!1}n.eventTarget_flatten=s,n.eventTarget_flattenMore=function(c){var l=s(c),f=!1,u=!1;return a.isBoolean(c)||(f=c.once||!1,u=c.passive||!1),[l,u,f]},n.eventTarget_addEventListener=function(c,l){if(l.callback!==null){for(var f=0;f=c.length&&(c=void 0),{value:c&&c[u++],done:!c}}};throw new TypeError(l?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(1),s=i(29);n.parentNode_convertNodesIntoANode=function(c,l){for(var f,u,d=null,h=0;h=_.length&&(_=void 0),{value:_&&_[D++],done:!_}}};throw new TypeError(T?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(_,T){var E=typeof Symbol=="function"&&_[Symbol.iterator];if(!E)return _;var D,b,I=E.call(_),P=[];try{for(;(T===void 0||T-- >0)&&!(D=I.next()).done;)P.push(D.value)}catch(M){b={error:M}}finally{try{D&&!D.done&&(E=I.return)&&E.call(I)}finally{if(b)throw b.error}}return P},s=this&&this.__spread||function(){for(var _=[],T=0;T0;ce--){var pe;if(C(pe=ue[ce],_)){re=pe;break}}var Ee,Oe,_e=[];try{for(var B=o(k._children),O=B.next();!O.done;O=B.next())if(x(xe=O.value,_)){if(f.Guard.isDocumentTypeNode(xe))throw new l.HierarchyRequestError;_e.push(xe)}}catch(De){D={error:De}}finally{try{O&&!O.done&&(b=B.return)&&b.call(B)}finally{if(D)throw D.error}}if(d.tree_isAncestorOf(G,L,!0))Ee=L,Oe=V;else{for(var z=L;z._parent!==null&&!d.tree_isAncestorOf(G,z._parent);)z=z._parent;if(z._parent===null)throw new Error("Parent node is null.");Ee=z._parent,Oe=1+d.tree_index(z)}if(f.Guard.isCharacterDataNode(F))(W=p.node_clone(L))._data=g.characterData_substringData(L,V,d.tree_nodeLength(L)-V),v.mutation_append(W,M),g.characterData_replaceData(L,V,d.tree_nodeLength(L)-V,"");else if(F!==null){var W=p.node_clone(F);v.mutation_append(W,M);var K=S(u.create_range([L,V],[F,d.tree_nodeLength(F)]));v.mutation_append(K,W)}try{for(var Z=o(_e),ee=Z.next();!ee.done;ee=Z.next()){var xe=ee.value;v.mutation_append(xe,M)}}catch(De){I={error:De}}finally{try{ee&&!ee.done&&(P=Z.return)&&P.call(Z)}finally{if(I)throw I.error}}return f.Guard.isCharacterDataNode(re)?((W=p.node_clone(G))._data=g.characterData_substringData(G,0,A),v.mutation_append(W,M),g.characterData_replaceData(G,0,A,"")):re!==null&&(W=p.node_clone(re),v.mutation_append(W,M),K=S(u.create_range([re,0],[G,A])),v.mutation_append(K,W)),_._start=[Ee,Oe],_._end=[Ee,Oe],M}n.range_collapsed=m,n.range_root=w,n.range_isContained=x,n.range_isPartiallyContained=C,n.range_setTheStart=function(_,T,E){if(f.Guard.isDocumentTypeNode(T))throw new l.InvalidNodeTypeError;if(E>d.tree_nodeLength(T))throw new l.IndexSizeError;var D=[T,E];w(_)===d.tree_rootNode(T)&&h.boundaryPoint_position(D,_._end)!==c.BoundaryPosition.After||(_._end=D),_._start=D},n.range_setTheEnd=function(_,T,E){if(f.Guard.isDocumentTypeNode(T))throw new l.InvalidNodeTypeError;if(E>d.tree_nodeLength(T))throw new l.IndexSizeError;var D=[T,E];w(_)===d.tree_rootNode(T)&&h.boundaryPoint_position(D,_._start)!==c.BoundaryPosition.Before||(_._start=D),_._end=D},n.range_select=function(_,T){var E=_._parent;if(E===null)throw new l.InvalidNodeTypeError;var D=d.tree_index(_);T._start=[E,D],T._end=[E,D+1]},n.range_extract=S,n.range_cloneTheContents=function _(T){var E,D,b,I,P,M,L=u.create_documentFragment(T._startNode._nodeDocument);if(m(T))return L;var V=T._startNode,G=T._startOffset,A=T._endNode,k=T._endOffset;V===A&&f.Guard.isCharacterDataNode(V)&&((O=p.node_clone(V))._data=g.characterData_substringData(V,G,k-G),v.mutation_append(O,L));for(var F=V;!d.tree_isAncestorOf(A,F,!0);){if(F._parent===null)throw new Error("Parent node is null.");F=F._parent}var j=null;if(!d.tree_isAncestorOf(A,V,!0))try{for(var Y=o(F._children),re=Y.next();!re.done;re=Y.next())if(C(Ee=re.value,T)){j=Ee;break}}catch(ee){E={error:ee}}finally{try{re&&!re.done&&(D=Y.return)&&D.call(Y)}finally{if(E)throw E.error}}var ue=null;if(!d.tree_isAncestorOf(V,A,!0))for(var ce=s(F._children),pe=ce.length-1;pe>0;pe--){var Ee;if(C(Ee=ce[pe],T)){ue=Ee;break}}var Oe=[];try{for(var _e=o(F._children),B=_e.next();!B.done;B=_e.next())if(x(Z=B.value,T)){if(f.Guard.isDocumentTypeNode(Z))throw new l.HierarchyRequestError;Oe.push(Z)}}catch(ee){b={error:ee}}finally{try{B&&!B.done&&(I=_e.return)&&I.call(_e)}finally{if(b)throw b.error}}if(f.Guard.isCharacterDataNode(j))(O=p.node_clone(V))._data=g.characterData_substringData(V,G,d.tree_nodeLength(V)-G),v.mutation_append(O,L);else if(j!==null){var O=p.node_clone(j);v.mutation_append(O,L);var z=_(u.create_range([V,G],[j,d.tree_nodeLength(j)]));v.mutation_append(z,O)}try{for(var W=o(Oe),K=W.next();!K.done;K=W.next()){var Z=K.value,O=p.node_clone(Z);v.mutation_append(O,L)}}catch(ee){P={error:ee}}finally{try{K&&!K.done&&(M=W.return)&&M.call(W)}finally{if(P)throw P.error}}return f.Guard.isCharacterDataNode(ue)?((O=p.node_clone(A))._data=g.characterData_substringData(A,0,k),v.mutation_append(O,L)):ue!==null&&(O=p.node_clone(ue),L.append(O),z=S(u.create_range([ue,0],[A,k])),v.mutation_append(z,O)),L},n.range_insert=function(_,T){var E,D;if(f.Guard.isProcessingInstructionNode(T._startNode)||f.Guard.isCommentNode(T._startNode)||f.Guard.isTextNode(T._startNode)&&T._startNode._parent===null||T._startNode===_)throw new l.HierarchyRequestError;var b,I=null;if(f.Guard.isTextNode(T._startNode))I=T._startNode;else{var P=0;try{for(var M=o(T._startNode._children),L=M.next();!L.done;L=M.next()){var V=L.value;if(P===T._startOffset){I=V;break}P++}}catch(A){E={error:A}}finally{try{L&&!L.done&&(D=M.return)&&D.call(M)}finally{if(E)throw E.error}}}if(I===null)b=T._startNode;else{if(I._parent===null)throw new Error("Parent node is null.");b=I._parent}v.mutation_ensurePreInsertionValidity(_,b,I),f.Guard.isTextNode(T._startNode)&&(I=y.text_split(T._startNode,T._startOffset)),_===I&&(I=_._nextSibling),_._parent!==null&&v.mutation_remove(_,_._parent);var G=I===null?d.tree_nodeLength(b):d.tree_index(I);f.Guard.isDocumentFragmentNode(_)?G+=d.tree_nodeLength(_):G++,v.mutation_preInsert(_,b,I),m(T)&&(T._end=[b,G])},n.range_getContainedNodes=function(_){var T;return(T={})[Symbol.iterator]=function(){var E=_.commonAncestorContainer,D=d.tree_getFirstDescendantNode(E);return{next:function(){for(;D&&!x(D,_);)D=d.tree_getNextDescendantNode(E,D);if(D===null)return{done:!0,value:null};var b={done:!1,value:D};return D=d.tree_getNextDescendantNode(E,D),b}}},T},n.range_getPartiallyContainedNodes=function(_){var T;return(T={})[Symbol.iterator]=function(){var E=_.commonAncestorContainer,D=d.tree_getFirstDescendantNode(E);return{next:function(){for(;D&&!C(D,_);)D=d.tree_getNextDescendantNode(E,D);if(D===null)return{done:!0,value:null};var b={done:!1,value:D};return D=d.tree_getNextDescendantNode(E,D),b}}},T}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(9);n.selectors_scopeMatchASelectorsString=function(a,s){throw new o.NotSupportedError}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(2),a=i(105);n.treeWalker_traverseChildren=function(s,c){for(var l=c?s._current._firstChild:s._current._lastChild;l!==null;){var f=a.traversal_filter(s,l);if(f===o.FilterResult.Accept)return s._current=l,l;if(f===o.FilterResult.Skip){var u=c?l._firstChild:l._lastChild;if(u!==null){l=u;continue}}for(;l!==null;){var d=c?l._nextSibling:l._previousSibling;if(d!==null){l=d;break}var h=l._parent;if(h===null||h===s._root||h===s._current)return null;l=h}}return null},n.treeWalker_traverseSiblings=function(s,c){var l=s._current;if(l===s._root)return null;for(;;){for(var f=c?l._nextSibling:l._previousSibling;f!==null;){l=f;var u=a.traversal_filter(s,l);if(u===o.FilterResult.Accept)return s._current=l,l;f=c?l._firstChild:l._lastChild,u!==o.FilterResult.Reject&&f!==null||(f=c?l._nextSibling:l._previousSibling)}if((l=l._parent)===null||l===s._root||a.traversal_filter(s,l)===o.FilterResult.Accept)return null}}},function(r,n,i){i(89),i(74);var o,a=this&&this.__extends||(o=function(d,h){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,p){g.__proto__=p}||function(g,p){for(var v in p)p.hasOwnProperty(v)&&(g[v]=p[v])})(d,h)},function(d,h){function g(){this.constructor=d}o(d,h),d.prototype=h===null?Object.create(h):(g.prototype=h.prototype,new g)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(1),c=i(2),l=i(50),f=i(3),u=function(d){function h(g,p){var v=d.call(this,g)||this;return v._indentation={},v._lengthToLastNewline=0,v._writerOptions=s.applyDefaults(p,{wellFormed:!1,headless:!1,prettyPrint:!1,indent:" ",newline:` `,offset:0,width:0,allowEmptyTags:!1,indentTextOnlyNodes:!1,spaceBeforeSlash:!1}),v}return a(h,d),h.prototype.serialize=function(g){return this._refs={suppressPretty:!1,emptyNode:!1,markup:""},g.nodeType!==c.NodeType.Document||this._writerOptions.headless||this.declaration(this._builderOptions.version,this._builderOptions.encoding,this._builderOptions.standalone),this.serializeNode(g,this._writerOptions.wellFormed),this._writerOptions.prettyPrint&&this._refs.markup.slice(-this._writerOptions.newline.length)===this._writerOptions.newline&&(this._refs.markup=this._refs.markup.slice(0,-this._writerOptions.newline.length)),this._refs.markup},h.prototype.declaration=function(g,p,v){this._beginLine(),this._refs.markup+='",this._endLine()},h.prototype.docType=function(g,p,v){this._beginLine(),this._refs.markup+=p&&v?"':p?"':v?"':"",this._endLine()},h.prototype.openTagBegin=function(g){this._beginLine(),this._refs.markup+="<"+g},h.prototype.openTagEnd=function(g,p,v){if(this._refs.suppressPretty=!1,this._refs.emptyNode=!1,this._writerOptions.prettyPrint&&!p&&!v){for(var y=!0,m=!0,w=this.currentNode.firstChild,x=0,C=0;w;){if(f.Guard.isExclusiveTextNode(w))C++;else{if(!f.Guard.isCDATASectionNode(w)){y=!1,m=!1;break}x++}w.data!==""&&(m=!1),w=w.nextSibling}this._refs.suppressPretty=!this._writerOptions.indentTextOnlyNodes&&y&&(x<=1&&C===0||x===0),this._refs.emptyNode=m}(v||p||this._refs.emptyNode)&&this._writerOptions.allowEmptyTags?this._refs.markup+=">":this._refs.markup+=v?" />":p||this._refs.emptyNode?this._writerOptions.spaceBeforeSlash?" />":"/>":">",this._endLine()},h.prototype.closeTag=function(g){this._refs.emptyNode||(this._beginLine(),this._refs.markup+=""),this._refs.suppressPretty=!1,this._refs.emptyNode=!1,this._endLine()},h.prototype.attribute=function(g,p){var v=g+'="'+p+'"';this._writerOptions.prettyPrint&&this._writerOptions.width>0&&this._refs.markup.length-this._lengthToLastNewline+1+v.length>this._writerOptions.width?(this._endLine(),this._beginLine(),this._refs.markup+=this._indent(1)+v):this._refs.markup+=" "+v},h.prototype.text=function(g){g!==""&&(this._beginLine(),this._refs.markup+=g,this._endLine())},h.prototype.cdata=function(g){g!==""&&(this._beginLine(),this._refs.markup+="",this._endLine())},h.prototype.comment=function(g){this._beginLine(),this._refs.markup+="",this._endLine()},h.prototype.instruction=function(g,p){this._beginLine(),this._refs.markup+="",this._endLine()},h.prototype._beginLine=function(){this._writerOptions.prettyPrint&&!this._refs.suppressPretty&&(this._refs.markup+=this._indent(this._writerOptions.offset+this.level))},h.prototype._endLine=function(){this._writerOptions.prettyPrint&&!this._refs.suppressPretty&&(this._refs.markup+=this._writerOptions.newline,this._lengthToLastNewline=this._refs.markup.length)},h.prototype._indent=function(g){if(g<=0)return"";if(this._indentation[g]!==void 0)return this._indentation[g];var p=this._writerOptions.indent.repeat(g);return this._indentation[g]=p,p},h}(l.BaseWriter);n.XMLWriter=u},function(r,n,i){var o=i(47),a=i(35);r.exports="".repeat||function(s){var c=String(a(this)),l="",f=o(s);if(f<0||f==1/0)throw RangeError("Wrong number of repetitions");for(;f>0;(f>>>=1)&&(c+=c))1&f&&(l+=c);return l}},function(r,n,i){i(31),i(32),i(33),i(19),i(178),i(20),i(22),i(23);var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)}),s=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(67),l=i(1),f=function(u){function d(h,g){var p=u.call(this,h)||this;return p._writerOptions=l.applyDefaults(g,{wellFormed:!1,prettyPrint:!1,indent:" ",newline:` `,offset:0,group:!1,verbose:!1}),p}return a(d,u),d.prototype.serialize=function(h){var g=l.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1}),p=new c.ObjectWriter(this._builderOptions,g).serialize(h);return this._beginLine(this._writerOptions,0)+this._convertObject(p,this._writerOptions)},d.prototype._convertObject=function(h,g,p){var v,y,m=this;p===void 0&&(p=0);var w="",x=this._isLeafNode(h);if(l.isArray(h)){w+="[";var C=h.length,S=0;try{for(var _=s(h),T=_.next();!T.done;T=_.next()){var E=T.value;w+=this._endLine(g,p+1)+this._beginLine(g,p+1)+this._convertObject(E,g,p+1),S0?new Array(p).join(h.indent):""},d.prototype._endLine=function(h,g){return h.prettyPrint?h.newline:""},d.prototype._key=function(h){return'"'+h+'":'},d.prototype._val=function(h){return JSON.stringify(h)},d.prototype._isLeafNode=function(h){return this._descendantCount(h)<=1},d.prototype._descendantCount=function(h,g){var p=this;return g===void 0&&(g=0),l.isArray(h)?l.forEachArray(h,function(v){return g+=p._descendantCount(v,g)},this):l.isObject(h)?l.forEachObject(h,function(v,y){return g+=p._descendantCount(y,g)},this):g++,g},d}(i(50).BaseWriter);n.JSONWriter=f},function(r,n,i){i(31),i(32),i(33),i(19),i(178),i(89),i(20),i(22),i(23);var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)}),s=this&&this.__values||function(u){var d=typeof Symbol=="function"&&Symbol.iterator,h=d&&u[d],g=0;if(h)return h.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&g>=u.length&&(u=void 0),{value:u&&u[g++],done:!u}}};throw new TypeError(d?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var c=i(67),l=i(1),f=function(u){function d(h,g){var p=u.call(this,h)||this;if(p._writerOptions=l.applyDefaults(g,{wellFormed:!1,indent:" ",newline:` -`,offset:0,group:!1,verbose:!1}),p._writerOptions.indent.length<2)throw new Error("YAML indententation string must be at least two characters long.");if(p._writerOptions.offset<0)throw new Error("YAML offset should be zero or a positive number.");return p}return a(d,u),d.prototype.serialize=function(h){var g=l.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1}),p=new c.ObjectWriter(this._builderOptions,g).serialize(h),v=this._beginLine(this._writerOptions,0)+"---"+this._endLine(this._writerOptions)+this._convertObject(p,this._writerOptions,0);return v.slice(-this._writerOptions.newline.length)===this._writerOptions.newline&&(v=v.slice(0,-this._writerOptions.newline.length)),v},d.prototype._convertObject=function(h,g,p,v){var y,m,w=this;v===void 0&&(v=!1);var x="";if(l.isArray(h))try{for(var C=s(h),S=C.next();!S.done;S=C.next()){var _=S.value;x+=this._beginLine(g,p,!0),l.isObject(_)?l.isEmpty(_)?x+='""'+this._endLine(g):x+=this._convertObject(_,g,p,!0):x+=this._val(_)+this._endLine(g)}}catch(T){y={error:T}}finally{try{S&&!S.done&&(m=C.return)&&m.call(C)}finally{if(y)throw y.error}}else l.forEachObject(h,function(T,E){v?(x+=w._key(T),v=!1):x+=w._beginLine(g,p)+w._key(T),l.isObject(E)?l.isEmpty(E)?x+=' ""'+w._endLine(g):x+=w._endLine(g)+w._convertObject(E,g,p+1):x+=" "+w._val(E)+w._endLine(g)},this);return x},d.prototype._beginLine=function(h,g,p){p===void 0&&(p=!1);var v=h.offset+g+1,y=new Array(v).join(h.indent);return p?y.substr(0,y.length-2)+"-"+y.substr(-1,1):y},d.prototype._endLine=function(h){return h.newline},d.prototype._key=function(h){return'"'+h+'":'},d.prototype._val=function(h){return JSON.stringify(h)},d}(i(50).BaseWriter);n.YAMLWriter=f},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0}),i(110).dom.setFeatures(!0);var o=i(110);n.DOMImplementation=o.DOMImplementation;var a=i(271);n.DOMParser=a.DOMParser;var s=i(274);n.XMLSerializer=s.XMLSerializer},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(3),a=i(0),s=function(){function c(){}return c.prototype.before=function(){for(var l=[],f=0;f=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(7),l=function(){function f(u){this._nodeList=[],this._recordQueue=[],this._callback=u;var d=a.dom.window;c.set.append(d._mutationObservers,this)}return f.prototype.observe=function(u,d){var h,g;if((d=d||{childList:!1,subtree:!1}).attributeOldValue===void 0&&d.attributeFilter===void 0||d.attributes!==void 0||(d.attributes=!0),d.characterDataOldValue!==void 0&&d.characterData===void 0&&(d.characterData=!0),!d.childList&&!d.attributes&&!d.characterData)throw new TypeError;if(d.attributeOldValue&&!d.attributes)throw new TypeError;if(d.attributeFilter!==void 0&&!d.attributes)throw new TypeError;if(d.characterDataOldValue&&!d.characterData)throw new TypeError;var p=!1,v=d,y=function(C){var S,_;if(C.observer===m){p=!0;try{for(var T=(S=void 0,o(m._nodeList)),E=T.next();!E.done;E=T.next()){var D=E.value;c.list.remove(D._registeredObserverList,function(b){return s.Guard.isTransientRegisteredObserver(b)&&b.source===C})}}catch(b){S={error:b}}finally{try{E&&!E.done&&(_=T.return)&&_.call(T)}finally{if(S)throw S.error}}C.options=v}},m=this;try{for(var w=o(u._registeredObserverList),x=w.next();!x.done;x=w.next())y(x.value)}catch(C){h={error:C}}finally{try{x&&!x.done&&(g=w.return)&&g.call(w)}finally{if(h)throw h.error}}p||(u._registeredObserverList.push({observer:this,options:d}),this._nodeList.push(u))},f.prototype.disconnect=function(){var u,d,h=this;try{for(var g=o(this._nodeList),p=g.next();!p.done;p=g.next()){var v=p.value;c.list.remove(v._registeredObserverList,function(y){return y.observer===h})}}catch(y){u={error:y}}finally{try{p&&!p.done&&(d=g.return)&&d.call(g)}finally{if(u)throw u.error}}this._recordQueue=[]},f.prototype.takeRecords=function(){var u=this._recordQueue;return this._recordQueue=[],u},f}();n.MutationObserverImpl=l},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(3),a=function(){function s(){}return Object.defineProperty(s.prototype,"previousElementSibling",{get:function(){for(var c=o.Cast.asNode(this)._previousSibling;c;){if(o.Guard.isElementNode(c))return c;c=c._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"nextElementSibling",{get:function(){for(var c=o.Cast.asNode(this)._nextSibling;c;){if(o.Guard.isElementNode(c))return c;c=c._nextSibling}return null},enumerable:!0,configurable:!0}),s}();n.NonDocumentTypeChildNodeImpl=a},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(3),a=i(0),s=function(){function c(){}return c.prototype.getElementById=function(l){for(var f=a.tree_getFirstDescendantNode(o.Cast.asNode(this),!1,!1,function(u){return o.Guard.isElementNode(u)});f!==null;){if(f._uniqueIdentifier===l)return f;f=a.tree_getNextDescendantNode(o.Cast.asNode(this),f,!1,!1,function(u){return o.Guard.isElementNode(u)})}return null},c}();n.NonElementParentNodeImpl=s},function(r,n,i){var o=this&&this.__values||function(l){var f=typeof Symbol=="function"&&Symbol.iterator,u=f&&l[f],d=0;if(u)return u.call(l);if(l&&typeof l.length=="number")return{next:function(){return l&&d>=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(3),s=i(0),c=function(){function l(){}return Object.defineProperty(l.prototype,"children",{get:function(){return s.create_htmlCollection(a.Cast.asNode(this))},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"firstElementChild",{get:function(){for(var f=a.Cast.asNode(this)._firstChild;f;){if(a.Guard.isElementNode(f))return f;f=f._nextSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"lastElementChild",{get:function(){for(var f=a.Cast.asNode(this)._lastChild;f;){if(a.Guard.isElementNode(f))return f;f=f._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"childElementCount",{get:function(){var f,u,d=0;try{for(var h=o(a.Cast.asNode(this)._children),g=h.next();!g.done;g=h.next()){var p=g.value;a.Guard.isElementNode(p)&&d++}}catch(v){f={error:v}}finally{try{g&&!g.done&&(u=h.return)&&u.call(h)}finally{if(f)throw f.error}}return d},enumerable:!0,configurable:!0}),l.prototype.prepend=function(){for(var f=[],u=0;u0)&&!(v=m.next()).done;)w.push(v.value)}catch(x){y={error:x}}finally{try{v&&!v.done&&(p=m.return)&&p.call(m)}finally{if(y)throw y.error}}return w},a=this&&this.__values||function(h){var g=typeof Symbol=="function"&&Symbol.iterator,p=g&&h[g],v=0;if(p)return p.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=i(180),c=i(111),l=i(7),f=i(0),u=i(69),d=function(){function h(){}return h.prototype.parse=function(g){for(var p,v,y,m,w=new s.XMLStringLexer(g,{skipWhitespaceOnlyText:!0}),x=f.create_document(),C=x,S=w.nextToken();S.type!==c.TokenType.EOF;){switch(S.type){case c.TokenType.Declaration:var _=S;if(_.version!=="1.0")throw new Error("Invalid xml version: "+_.version);break;case c.TokenType.DocType:var T=S;if(!f.xml_isPubidChar(T.pubId))throw new Error("DocType public identifier does not match PubidChar construct.");if(!f.xml_isLegalChar(T.sysId)||T.sysId.indexOf('"')!==-1&&T.sysId.indexOf("'")!==-1)throw new Error("DocType system identifier contains invalid characters.");C.appendChild(x.implementation.createDocumentType(T.name,T.pubId,T.sysId));break;case c.TokenType.CDATA:var E=S;if(!f.xml_isLegalChar(E.data)||E.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters.");C.appendChild(x.createCDATASection(E.data));break;case c.TokenType.Comment:var D=S;if(!f.xml_isLegalChar(D.data)||D.data.indexOf("--")!==-1||D.data.endsWith("-"))throw new Error("Comment data contains invalid characters.");C.appendChild(x.createComment(D.data));break;case c.TokenType.PI:var b=S;if(b.target.indexOf(":")!==-1||/^xml$/i.test(b.target))throw new Error("Processing instruction target contains invalid characters.");if(!f.xml_isLegalChar(b.data)||b.data.indexOf("?>")!==-1)throw new Error("Processing instruction data contains invalid characters.");C.appendChild(x.createProcessingInstruction(b.target,b.data));break;case c.TokenType.Text:var I=S;if(!f.xml_isLegalChar(I.data))throw new Error("Text data contains invalid characters.");C.appendChild(x.createTextNode(this._decodeText(I.data)));break;case c.TokenType.Element:var P=S,M=o(f.namespace_extractQName(P.name),2),L=M[0],V=M[1];if(V.indexOf(":")!==-1||!f.xml_isName(V))throw new Error("Node local name contains invalid characters.");if(L==="xmlns")throw new Error("An element cannot have the 'xmlns' prefix.");var G=C.lookupNamespaceURI(L),A={};try{for(var k=(p=void 0,a(P.attributes)),F=k.next();!F.done;F=k.next()){var j=o(F.value,2),Y=j[0],re=j[1];if(Y==="xmlns")G=re;else{var ue=o(f.namespace_extractQName(Y),2),ce=ue[0],pe=ue[1];ce==="xmlns"&&(pe===L&&(G=re),A[pe]=re)}}}catch(K){p={error:K}}finally{try{F&&!F.done&&(v=k.return)&&v.call(k)}finally{if(p)throw p.error}}var Ee=G!==null?x.createElementNS(G,P.name):x.createElement(P.name);C.appendChild(Ee);var Oe=new u.LocalNameSet;try{for(var Se=(y=void 0,a(P.attributes)),B=Se.next();!B.done;B=Se.next()){var O=o(B.value,2),z=(Y=O[0],re=O[1],o(f.namespace_extractQName(Y),2)),W=(ce=z[0],pe=z[1],null);if(ce==="xmlns"||ce===null&&pe==="xmlns"?W=l.namespace.XMLNS:(W=Ee.lookupNamespaceURI(ce))!==null&&Ee.isDefaultNamespace(W)?W=null:W===null&&ce!==null&&(W=A[ce]||null),Oe.has(W,pe))throw new Error("Element contains duplicate attributes.");if(Oe.set(W,pe),W===l.namespace.XMLNS&&re===l.namespace.XMLNS)throw new Error("XMLNS namespace is reserved.");if(pe.indexOf(":")!==-1||!f.xml_isName(pe))throw new Error("Attribute local name contains invalid characters.");if(ce==="xmlns"&&re==="")throw new Error("Empty XML namespace is not allowed.");W!==null?Ee.setAttributeNS(W,Y,this._decodeAttributeValue(re)):Ee.setAttribute(Y,this._decodeAttributeValue(re))}}catch(K){y={error:K}}finally{try{B&&!B.done&&(m=Se.return)&&m.call(Se)}finally{if(y)throw y.error}}P.selfClosing||(C=Ee);break;case c.TokenType.ClosingTag:if(S.name!==C.nodeName)throw new Error("Closing tag name does not match opening tag name.");C._parent&&(C=C._parent)}S=w.nextToken()}return x},h.prototype._decodeText=function(g){return g==null?g:g.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},h.prototype._decodeAttributeValue=function(g){return g==null?g:g.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},h}();n.XMLParserImpl=d},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(275);n.XMLSerializer=o.XMLSerializerImpl},function(r,n,i){var o=this&&this.__values||function(h){var g=typeof Symbol=="function"&&Symbol.iterator,p=g&&h[g],v=0;if(p)return p.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(2),s=i(69),c=i(95),l=i(9),f=i(7),u=i(0),d=function(){function h(){}return h.prototype.serializeToString=function(g){return this._xmlSerialization(g,!1)},h.prototype._xmlSerialization=function(g,p){if(g._nodeDocument===void 0||g._nodeDocument._hasNamespaces){var v=new c.NamespacePrefixMap;v.set("xml",f.namespace.XML);try{return this._serializeNodeNS(g,null,v,{value:1},p)}catch{throw new l.InvalidStateError}}else try{return this._serializeNode(g,p)}catch{throw new l.InvalidStateError}},h.prototype._serializeNodeNS=function(g,p,v,y,m){switch(g.nodeType){case a.NodeType.Element:return this._serializeElementNS(g,p,v,y,m);case a.NodeType.Document:return this._serializeDocumentNS(g,p,v,y,m);case a.NodeType.Comment:return this._serializeComment(g,m);case a.NodeType.Text:return this._serializeText(g,m);case a.NodeType.DocumentFragment:return this._serializeDocumentFragmentNS(g,p,v,y,m);case a.NodeType.DocumentType:return this._serializeDocumentType(g,m);case a.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(g,m);case a.NodeType.CData:return this._serializeCData(g,m);default:throw new Error("Unknown node type: "+g.nodeType)}},h.prototype._serializeNode=function(g,p){switch(g.nodeType){case a.NodeType.Element:return this._serializeElement(g,p);case a.NodeType.Document:return this._serializeDocument(g,p);case a.NodeType.Comment:return this._serializeComment(g,p);case a.NodeType.Text:return this._serializeText(g,p);case a.NodeType.DocumentFragment:return this._serializeDocumentFragment(g,p);case a.NodeType.DocumentType:return this._serializeDocumentType(g,p);case a.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(g,p);case a.NodeType.CData:return this._serializeCData(g,p);default:throw new Error("Unknown node type: "+g.nodeType)}},h.prototype._serializeElementNS=function(g,p,v,y,m){var w,x;if(m&&(g.localName.indexOf(":")!==-1||!u.xml_isName(g.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var C="<",S="",_=!1,T=!1,E=v.copy(),D={},b=this._recordNamespaceInformation(g,E,D),I=p,P=g.namespaceURI;if(I===P)b!==null&&(T=!0),C+=S=P===f.namespace.XML?"xml:"+g.localName:g.localName;else{var M=g.prefix,L=null;if(M===null&&P===b||(L=E.get(M,P)),M==="xmlns"){if(m)throw new Error("An element cannot have the 'xmlns' prefix (well-formed required).");L=M}L!==null?(S=L+":"+g.localName,b!==null&&b!==f.namespace.XML&&(I=b||null),C+=S):M!==null?(M in D&&(M=this._generatePrefix(P,E,y)),E.set(M,P),C+=S+=M+":"+g.localName,C+=" xmlns:"+M+'="'+this._serializeAttributeValue(P,m)+'"',b!==null&&(I=b||null)):b===null||b!==null&&b!==P?(T=!0,I=P,C+=S+=g.localName,C+=' xmlns="'+this._serializeAttributeValue(P,m)+'"'):(I=P,C+=S+=g.localName)}C+=this._serializeAttributesNS(g,E,y,D,T,m);var V=P===f.namespace.HTML;if(V&&g.childNodes.length===0&&h._VoidElementNames.has(g.localName)?(C+=" /",_=!0):V||g.childNodes.length!==0||(C+="/",_=!0),C+=">",_)return C;if(!(V&&g.localName==="template"))try{for(var G=o(g._children||g.childNodes),A=G.next();!A.done;A=G.next()){var k=A.value;C+=this._serializeNodeNS(k,I,E,y,m)}}catch(F){w={error:F}}finally{try{A&&!A.done&&(x=G.return)&&x.call(G)}finally{if(w)throw w.error}}return C+=""},h.prototype._serializeDocumentNS=function(g,p,v,y,m){var w,x;if(m&&g.documentElement===null)throw new Error("Missing document element (well-formed required).");var C="";try{for(var S=o(g._children||g.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;C+=this._serializeNodeNS(T,p,v,y,m)}}catch(E){w={error:E}}finally{try{_&&!_.done&&(x=S.return)&&x.call(S)}finally{if(w)throw w.error}}return C},h.prototype._serializeComment=function(g,p){if(p&&(!u.xml_isLegalChar(g.data)||g.data.indexOf("--")!==-1||g.data.endsWith("-")))throw new Error("Comment data contains invalid characters (well-formed required).");return""},h.prototype._serializeText=function(g,p){if(p&&!u.xml_isLegalChar(g.data))throw new Error("Text data contains invalid characters (well-formed required).");for(var v="",y=0;y"?">":m}return v},h.prototype._serializeDocumentFragmentNS=function(g,p,v,y,m){var w,x,C="";try{for(var S=o(g._children||g.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;C+=this._serializeNodeNS(T,p,v,y,m)}}catch(E){w={error:E}}finally{try{_&&!_.done&&(x=S.return)&&x.call(S)}finally{if(w)throw w.error}}return C},h.prototype._serializeDocumentType=function(g,p){if(p&&!u.xml_isPubidChar(g.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(p&&(!u.xml_isLegalChar(g.systemId)||g.systemId.indexOf('"')!==-1&&g.systemId.indexOf("'")!==-1))throw new Error("DocType system identifier contains invalid characters (well-formed required).");return g.publicId&&g.systemId?"':g.publicId?"':g.systemId?"':""},h.prototype._serializeProcessingInstruction=function(g,p){if(p&&(g.target.indexOf(":")!==-1||/^xml$/i.test(g.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(p&&(!u.xml_isLegalChar(g.data)||g.data.indexOf("?>")!==-1))throw new Error("Processing instruction data contains invalid characters (well-formed required).");return""},h.prototype._serializeCData=function(g,p){if(p&&g.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters (well-formed required).");return""},h.prototype._serializeAttributesNS=function(g,p,v,y,m,w){var x,C,S="",_=w?new s.LocalNameSet:void 0;try{for(var T=o(g.attributes),E=T.next();!E.done;E=T.next()){var D=E.value;if(m||w||D.namespaceURI!==null){if(w&&_&&_.has(D.namespaceURI,D.localName))throw new Error("Element contains duplicate attributes (well-formed required).");w&&_&&_.set(D.namespaceURI,D.localName);var b=D.namespaceURI,I=null;if(b!==null)if(I=p.get(D.prefix,b),b===f.namespace.XMLNS){if(D.value===f.namespace.XML||D.prefix===null&&m||D.prefix!==null&&(!(D.localName in y)||y[D.localName]!==D.value)&&p.has(D.localName,D.value))continue;if(w&&D.value===f.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(w&&D.value==="")throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");D.prefix==="xmlns"&&(I="xmlns")}else I===null&&(S+=" xmlns:"+(I=D.prefix===null||p.hasPrefix(D.prefix)&&!p.has(D.prefix,b)?this._generatePrefix(b,p,v):D.prefix)+'="'+this._serializeAttributeValue(b,w)+'"');if(S+=" ",I!==null&&(S+=I+":"),w&&(D.localName.indexOf(":")!==-1||!u.xml_isName(D.localName)||D.localName==="xmlns"&&b===null))throw new Error("Attribute local name contains invalid characters (well-formed required).");S+=D.localName+'="'+this._serializeAttributeValue(D.value,w)+'"'}else S+=" "+D.localName+'="'+this._serializeAttributeValue(D.value,w)+'"'}}catch(P){x={error:P}}finally{try{E&&!E.done&&(C=T.return)&&C.call(T)}finally{if(x)throw x.error}}return S},h.prototype._recordNamespaceInformation=function(g,p,v){var y,m,w=null;try{for(var x=o(g.attributes),C=x.next();!C.done;C=x.next()){var S=C.value,_=S.namespaceURI,T=S.prefix;if(_===f.namespace.XMLNS){if(T===null){w=S.value;continue}var E=S.localName,D=S.value;if(D===f.namespace.XML||(D===""&&(D=null),p.has(E,D)))continue;p.set(E,D),v[E]=D||""}}}catch(b){y={error:b}}finally{try{C&&!C.done&&(m=x.return)&&m.call(x)}finally{if(y)throw y.error}}return w},h.prototype._generatePrefix=function(g,p,v){var y="ns"+v.value;return v.value++,p.set(y,g),y},h.prototype._serializeAttributeValue=function(g,p){if(p&&g!==null&&!u.xml_isLegalChar(g))throw new Error("Invalid characters in attribute value.");if(g===null)return"";for(var v="",y=0;y"?">":m}return v},h.prototype._serializeElement=function(g,p){var v,y;if(p&&(g.localName.indexOf(":")!==-1||!u.xml_isName(g.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var m=!1,w=g.localName,x="<"+w;if(x+=this._serializeAttributes(g,p),g._children.size===0&&(x+="/",m=!0),x+=">",m)return x;try{for(var C=o(g._children),S=C.next();!S.done;S=C.next()){var _=S.value;x+=this._serializeNode(_,p)}}catch(T){v={error:T}}finally{try{S&&!S.done&&(y=C.return)&&y.call(C)}finally{if(v)throw v.error}}return x+=""},h.prototype._serializeDocument=function(g,p){var v,y;if(p&&g.documentElement===null)throw new Error("Missing document element (well-formed required).");var m="";try{for(var w=o(g._children),x=w.next();!x.done;x=w.next()){var C=x.value;m+=this._serializeNode(C,p)}}catch(S){v={error:S}}finally{try{x&&!x.done&&(y=w.return)&&y.call(w)}finally{if(v)throw v.error}}return m},h.prototype._serializeDocumentFragment=function(g,p){var v,y,m="";try{for(var w=o(g._children),x=w.next();!x.done;x=w.next()){var C=x.value;m+=this._serializeNode(C,p)}}catch(S){v={error:S}}finally{try{x&&!x.done&&(y=w.return)&&y.call(w)}finally{if(v)throw v.error}}return m},h.prototype._serializeAttributes=function(g,p){var v,y,m="",w=p?{}:void 0;try{for(var x=o(g.attributes),C=x.next();!C.done;C=x.next()){var S=C.value;if(p&&w&&S.localName in w)throw new Error("Element contains duplicate attributes (well-formed required).");if(p&&w&&(w[S.localName]=!0),p&&(S.localName.indexOf(":")!==-1||!u.xml_isName(S.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");m+=" "+S.localName+'="'+this._serializeAttributeValue(S.value,p)+'"'}}catch(_){v={error:_}}finally{try{C&&!C.done&&(y=x.return)&&y.call(x)}finally{if(v)throw v.error}}return m},h._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),h}();n.XMLSerializerImpl=d},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(277);n.XMLReader=o.XMLReader;var a=i(112);n.ObjectReader=a.ObjectReader;var s=i(280);n.JSONReader=s.JSONReader;var c=i(281);n.YAMLReader=c.YAMLReader},function(r,n,i){i(31),i(32),i(33),i(19),i(65),i(20),i(22),i(23);var o,a=this&&this.__extends||(o=function(g,p){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,y){v.__proto__=y}||function(v,y){for(var m in y)y.hasOwnProperty(m)&&(v[m]=y[m])})(g,p)},function(g,p){function v(){this.constructor=g}o(g,p),g.prototype=p===null?Object.create(p):(v.prototype=p.prototype,new v)}),s=this&&this.__read||function(g,p){var v=typeof Symbol=="function"&&g[Symbol.iterator];if(!v)return g;var y,m,w=v.call(g),x=[];try{for(;(p===void 0||p-- >0)&&!(y=w.next()).done;)x.push(y.value)}catch(C){m={error:C}}finally{try{y&&!y.done&&(v=w.return)&&v.call(w)}finally{if(m)throw m.error}}return x},c=this&&this.__values||function(g){var p=typeof Symbol=="function"&&Symbol.iterator,v=p&&g[p],y=0;if(v)return v.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var l=i(180),f=i(111),u=i(7),d=i(0),h=function(g){function p(){return g!==null&&g.apply(this,arguments)||this}return a(p,g),p.prototype._parse=function(v,y){for(var m,w,x,C,S=new l.XMLStringLexer(y,{skipWhitespaceOnlyText:!0}),_=v,T=v,E=S.nextToken();E.type!==f.TokenType.EOF;){switch(E.type){case f.TokenType.Declaration:var D=E,b=this.sanitize(D.version);if(b!=="1.0")throw new Error("Invalid xml version: "+b);var I={version:b};D.encoding&&(I.encoding=this.sanitize(D.encoding)),D.standalone&&(I.standalone=this.sanitize(D.standalone)==="yes"),T.set(I);break;case f.TokenType.DocType:var P=E;T=this.docType(T,this.sanitize(P.name),this.sanitize(P.pubId),this.sanitize(P.sysId))||T;break;case f.TokenType.CDATA:var M=E;T=this.cdata(T,this.sanitize(M.data))||T;break;case f.TokenType.Comment:var L=E;T=this.comment(T,this.sanitize(L.data))||T;break;case f.TokenType.PI:var V=E;T=this.instruction(T,this.sanitize(V.target),this.sanitize(V.data))||T;break;case f.TokenType.Text:var G=E;T=this.text(T,this._decodeText(this.sanitize(G.data)))||T;break;case f.TokenType.Element:var A=E,k=this.sanitize(A.name),F=s(d.namespace_extractQName(k),1)[0],j=T.node.lookupNamespaceURI(F),Y={};try{for(var re=(m=void 0,c(A.attributes)),ue=re.next();!ue.done;ue=re.next()){var ce=s(ue.value,2),pe=ce[0],Ee=ce[1];if(pe=this.sanitize(pe),Ee=this.sanitize(Ee),pe==="xmlns")j=Ee;else{var Oe=s(d.namespace_extractQName(pe),2),Se=Oe[0],B=Oe[1];Se==="xmlns"&&(B===F&&(j=Ee),Y[B]=Ee)}}}catch(xe){m={error:xe}}finally{try{ue&&!ue.done&&(w=re.return)&&w.call(re)}finally{if(m)throw m.error}}var O=j!==null?this.element(T,j,k):this.element(T,void 0,k);if(O===void 0)break;T.node===v.node&&(_=O);try{for(var z=(x=void 0,c(A.attributes)),W=z.next();!W.done;W=z.next()){var K=s(W.value,2);pe=K[0],Ee=K[1],pe=this.sanitize(pe),Ee=this.sanitize(Ee);var Z=s(d.namespace_extractQName(pe),2),ee=(Se=Z[0],B=Z[1],null);Se==="xmlns"||Se===null&&B==="xmlns"?ee=u.namespace.XMLNS:(ee=O.node.lookupNamespaceURI(Se))!==null&&O.node.isDefaultNamespace(ee)?ee=null:ee===null&&Se!==null&&(ee=Y[Se]||null),ee!==null?this.attribute(O,ee,pe,this._decodeAttributeValue(Ee)):this.attribute(O,void 0,pe,this._decodeAttributeValue(Ee))}}catch(xe){x={error:xe}}finally{try{W&&!W.done&&(C=z.return)&&C.call(z)}finally{if(x)throw x.error}}A.selfClosing||(T=O);break;case f.TokenType.ClosingTag:T.node.parentNode&&(T=T.up())}E=S.nextToken()}return _},p}(i(75).BaseReader);n.XMLReader=h},function(r,n,i){var o=i(4),a=i(279);o({target:"Object",stat:!0,forced:Object.assign!==a},{assign:a})},function(r,n,i){var o=i(16),a=i(8),s=i(61),c=i(85),l=i(79),f=i(27),u=i(41),d=Object.assign,h=Object.defineProperty;r.exports=!d||a(function(){if(o&&d({b:1},d(h({},"a",{enumerable:!0,get:function(){h(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var g={},p={},v=Symbol();return g[v]=7,"abcdefghijklmnopqrst".split("").forEach(function(y){p[y]=y}),d({},g)[v]!=7||s(d({},p)).join("")!="abcdefghijklmnopqrst"})?function(g,p){for(var v=f(g),y=arguments.length,m=1,w=c.f,x=l.f;y>m;)for(var C,S=u(arguments[m++]),_=w?s(S).concat(w(S)):s(S),T=_.length,E=0;T>E;)C=_[E++],o&&!x.call(S,C)||(v[C]=S[C]);return v}:d},function(r,n,i){var o,a=this&&this.__extends||(o=function(l,f){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,d){u.__proto__=d}||function(u,d){for(var h in d)d.hasOwnProperty(h)&&(u[h]=d[h])})(l,f)},function(l,f){function u(){this.constructor=l}o(l,f),l.prototype=f===null?Object.create(f):(u.prototype=f.prototype,new u)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(112),c=function(l){function f(){return l!==null&&l.apply(this,arguments)||this}return a(f,l),f.prototype._parse=function(u,d){return new s.ObjectReader(this._builderOptions).parse(u,JSON.parse(d))},f}(i(75).BaseReader);n.JSONReader=c},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(112),c=i(75),l=i(282),f=function(u){function d(){return u!==null&&u.apply(this,arguments)||this}return a(d,u),d.prototype._parse=function(h,g){var p=l.safeLoad(g);if(p===void 0)throw new Error("Unable to parse YAML document.");return new s.ObjectReader(this._builderOptions).parse(h,p)},d}(c.BaseReader);n.YAMLReader=f},function(r,n,i){var o=i(283);r.exports=o},function(r,n,i){var o=i(284),a=i(303);function s(c){return function(){throw new Error("Function "+c+" is deprecated and cannot be used.")}}r.exports.Type=i(10),r.exports.Schema=i(39),r.exports.FAILSAFE_SCHEMA=i(113),r.exports.JSON_SCHEMA=i(182),r.exports.CORE_SCHEMA=i(181),r.exports.DEFAULT_SAFE_SCHEMA=i(54),r.exports.DEFAULT_FULL_SCHEMA=i(76),r.exports.load=o.load,r.exports.loadAll=o.loadAll,r.exports.safeLoad=o.safeLoad,r.exports.safeLoadAll=o.safeLoadAll,r.exports.dump=a.dump,r.exports.safeDump=a.safeDump,r.exports.YAMLException=i(53),r.exports.MINIMAL_SCHEMA=i(113),r.exports.SAFE_SCHEMA=i(54),r.exports.DEFAULT_SCHEMA=i(76),r.exports.scan=s("scan"),r.exports.parse=s("parse"),r.exports.compose=s("compose"),r.exports.addConstructor=s("addConstructor")},function(r,n,i){var o=i(38),a=i(53),s=i(285),c=i(54),l=i(76),f=Object.prototype.hasOwnProperty,u=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,d=/[\x85\u2028\u2029]/,h=/[,\[\]\{\}]/,g=/^(?:!|!!|![a-z\-]+!)$/i,p=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function v(O){return Object.prototype.toString.call(O)}function y(O){return O===10||O===13}function m(O){return O===9||O===32}function w(O){return O===9||O===32||O===10||O===13}function x(O){return O===44||O===91||O===93||O===123||O===125}function C(O){var z;return 48<=O&&O<=57?O-48:97<=(z=32|O)&&z<=102?z-97+10:-1}function S(O){return O===48?"\0":O===97?"\x07":O===98?"\b":O===116||O===9?" ":O===110?` -`:O===118?"\v":O===102?"\f":O===114?"\r":O===101?"\x1B":O===32?" ":O===34?'"':O===47?"/":O===92?"\\":O===78?"…":O===95?" ":O===76?"\u2028":O===80?"\u2029":""}function _(O){return O<=65535?String.fromCharCode(O):String.fromCharCode(55296+(O-65536>>10),56320+(O-65536&1023))}for(var T=new Array(256),E=new Array(256),D=0;D<256;D++)T[D]=S(D)?1:0,E[D]=S(D);function b(O,z){this.input=O,this.filename=z.filename||null,this.schema=z.schema||l,this.onWarning=z.onWarning||null,this.legacy=z.legacy||!1,this.json=z.json||!1,this.listener=z.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=O.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function I(O,z){return new a(z,new s(O.filename,O.input,O.position,O.line,O.position-O.lineStart))}function P(O,z){throw I(O,z)}function M(O,z){O.onWarning&&O.onWarning.call(null,I(O,z))}var L={YAML:function(O,z,W){var K,Z,ee;O.version!==null&&P(O,"duplication of %YAML directive"),W.length!==1&&P(O,"YAML directive accepts exactly one argument"),(K=/^([0-9]+)\.([0-9]+)$/.exec(W[0]))===null&&P(O,"ill-formed argument of the YAML directive"),Z=parseInt(K[1],10),ee=parseInt(K[2],10),Z!==1&&P(O,"unacceptable YAML version of the document"),O.version=W[0],O.checkLineBreaks=ee<2,ee!==1&&ee!==2&&M(O,"unsupported YAML version of the document")},TAG:function(O,z,W){var K,Z;W.length!==2&&P(O,"TAG directive accepts exactly two arguments"),K=W[0],Z=W[1],g.test(K)||P(O,"ill-formed tag handle (first argument) of the TAG directive"),f.call(O.tagMap,K)&&P(O,'there is a previously declared suffix for "'+K+'" tag handle'),p.test(Z)||P(O,"ill-formed tag prefix (second argument) of the TAG directive"),O.tagMap[K]=Z}};function V(O,z,W,K){var Z,ee,xe,De;if(z1&&(O.result+=o.repeat(` -`,z-1))}function re(O,z){var W,K,Z=O.tag,ee=O.anchor,xe=[],De=!1;for(O.anchor!==null&&(O.anchorMap[O.anchor]=xe),K=O.input.charCodeAt(O.position);K!==0&&K===45&&w(O.input.charCodeAt(O.position+1));)if(De=!0,O.position++,F(O,!0,-1)&&O.lineIndent<=z)xe.push(null),K=O.input.charCodeAt(O.position);else if(W=O.line,pe(O,z,3,!1,!0),xe.push(O.result),F(O,!0,-1),K=O.input.charCodeAt(O.position),(O.line===W||O.lineIndent>z)&&K!==0)P(O,"bad indentation of a sequence entry");else if(O.lineIndentz?se=1:O.lineIndent===z?se=0:O.lineIndentz?se=1:O.lineIndent===z?se=0:O.lineIndentht)&&(pe(oe,ht,4,!0,Ie)&&(fn?Pn=oe.result:$n=oe.result),fn||(A(oe,xt,Ft,jt,Pn,$n,$e,tt),jt=Pn=$n=null),F(oe,!0,-1),nt=oe.input.charCodeAt(oe.position)),oe.lineIndent>ht&&nt!==0)P(oe,"bad indentation of a mapping entry");else if(oe.lineIndent=0))break;Ie===0?P(oe,"bad explicit indentation width of a block scalar; it cannot be less than one"):Lt?P(oe,"repeat of an indentation width identifier"):(xt=ht+Ie-1,Lt=!0)}if(m($e)){do $e=oe.input.charCodeAt(++oe.position);while(m($e));if($e===35)do $e=oe.input.charCodeAt(++oe.position);while(!y($e)&&$e!==0)}for(;$e!==0;){for(k(oe),oe.lineIndent=0,$e=oe.input.charCodeAt(oe.position);(!Lt||oe.lineIndentxt&&(xt=oe.lineIndent),y($e))Ft++;else{if(oe.lineIndent=f.length&&(f=void 0),{value:f&&f[h++],done:!f}}};throw new TypeError(u?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(6),s=i(3),c=i(7),l=function(){function f(u){this._nodeList=[],this._recordQueue=[],this._callback=u;var d=a.dom.window;c.set.append(d._mutationObservers,this)}return f.prototype.observe=function(u,d){var h,g;if((d=d||{childList:!1,subtree:!1}).attributeOldValue===void 0&&d.attributeFilter===void 0||d.attributes!==void 0||(d.attributes=!0),d.characterDataOldValue!==void 0&&d.characterData===void 0&&(d.characterData=!0),!d.childList&&!d.attributes&&!d.characterData)throw new TypeError;if(d.attributeOldValue&&!d.attributes)throw new TypeError;if(d.attributeFilter!==void 0&&!d.attributes)throw new TypeError;if(d.characterDataOldValue&&!d.characterData)throw new TypeError;var p=!1,v=d,y=function(C){var S,_;if(C.observer===m){p=!0;try{for(var T=(S=void 0,o(m._nodeList)),E=T.next();!E.done;E=T.next()){var D=E.value;c.list.remove(D._registeredObserverList,function(b){return s.Guard.isTransientRegisteredObserver(b)&&b.source===C})}}catch(b){S={error:b}}finally{try{E&&!E.done&&(_=T.return)&&_.call(T)}finally{if(S)throw S.error}}C.options=v}},m=this;try{for(var w=o(u._registeredObserverList),x=w.next();!x.done;x=w.next())y(x.value)}catch(C){h={error:C}}finally{try{x&&!x.done&&(g=w.return)&&g.call(w)}finally{if(h)throw h.error}}p||(u._registeredObserverList.push({observer:this,options:d}),this._nodeList.push(u))},f.prototype.disconnect=function(){var u,d,h=this;try{for(var g=o(this._nodeList),p=g.next();!p.done;p=g.next()){var v=p.value;c.list.remove(v._registeredObserverList,function(y){return y.observer===h})}}catch(y){u={error:y}}finally{try{p&&!p.done&&(d=g.return)&&d.call(g)}finally{if(u)throw u.error}}this._recordQueue=[]},f.prototype.takeRecords=function(){var u=this._recordQueue;return this._recordQueue=[],u},f}();n.MutationObserverImpl=l},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(3),a=function(){function s(){}return Object.defineProperty(s.prototype,"previousElementSibling",{get:function(){for(var c=o.Cast.asNode(this)._previousSibling;c;){if(o.Guard.isElementNode(c))return c;c=c._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(s.prototype,"nextElementSibling",{get:function(){for(var c=o.Cast.asNode(this)._nextSibling;c;){if(o.Guard.isElementNode(c))return c;c=c._nextSibling}return null},enumerable:!0,configurable:!0}),s}();n.NonDocumentTypeChildNodeImpl=a},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(3),a=i(0),s=function(){function c(){}return c.prototype.getElementById=function(l){for(var f=a.tree_getFirstDescendantNode(o.Cast.asNode(this),!1,!1,function(u){return o.Guard.isElementNode(u)});f!==null;){if(f._uniqueIdentifier===l)return f;f=a.tree_getNextDescendantNode(o.Cast.asNode(this),f,!1,!1,function(u){return o.Guard.isElementNode(u)})}return null},c}();n.NonElementParentNodeImpl=s},function(r,n,i){var o=this&&this.__values||function(l){var f=typeof Symbol=="function"&&Symbol.iterator,u=f&&l[f],d=0;if(u)return u.call(l);if(l&&typeof l.length=="number")return{next:function(){return l&&d>=l.length&&(l=void 0),{value:l&&l[d++],done:!l}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(3),s=i(0),c=function(){function l(){}return Object.defineProperty(l.prototype,"children",{get:function(){return s.create_htmlCollection(a.Cast.asNode(this))},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"firstElementChild",{get:function(){for(var f=a.Cast.asNode(this)._firstChild;f;){if(a.Guard.isElementNode(f))return f;f=f._nextSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"lastElementChild",{get:function(){for(var f=a.Cast.asNode(this)._lastChild;f;){if(a.Guard.isElementNode(f))return f;f=f._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"childElementCount",{get:function(){var f,u,d=0;try{for(var h=o(a.Cast.asNode(this)._children),g=h.next();!g.done;g=h.next()){var p=g.value;a.Guard.isElementNode(p)&&d++}}catch(v){f={error:v}}finally{try{g&&!g.done&&(u=h.return)&&u.call(h)}finally{if(f)throw f.error}}return d},enumerable:!0,configurable:!0}),l.prototype.prepend=function(){for(var f=[],u=0;u0)&&!(v=m.next()).done;)w.push(v.value)}catch(x){y={error:x}}finally{try{v&&!v.done&&(p=m.return)&&p.call(m)}finally{if(y)throw y.error}}return w},a=this&&this.__values||function(h){var g=typeof Symbol=="function"&&Symbol.iterator,p=g&&h[g],v=0;if(p)return p.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=i(180),c=i(111),l=i(7),f=i(0),u=i(69),d=function(){function h(){}return h.prototype.parse=function(g){for(var p,v,y,m,w=new s.XMLStringLexer(g,{skipWhitespaceOnlyText:!0}),x=f.create_document(),C=x,S=w.nextToken();S.type!==c.TokenType.EOF;){switch(S.type){case c.TokenType.Declaration:var _=S;if(_.version!=="1.0")throw new Error("Invalid xml version: "+_.version);break;case c.TokenType.DocType:var T=S;if(!f.xml_isPubidChar(T.pubId))throw new Error("DocType public identifier does not match PubidChar construct.");if(!f.xml_isLegalChar(T.sysId)||T.sysId.indexOf('"')!==-1&&T.sysId.indexOf("'")!==-1)throw new Error("DocType system identifier contains invalid characters.");C.appendChild(x.implementation.createDocumentType(T.name,T.pubId,T.sysId));break;case c.TokenType.CDATA:var E=S;if(!f.xml_isLegalChar(E.data)||E.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters.");C.appendChild(x.createCDATASection(E.data));break;case c.TokenType.Comment:var D=S;if(!f.xml_isLegalChar(D.data)||D.data.indexOf("--")!==-1||D.data.endsWith("-"))throw new Error("Comment data contains invalid characters.");C.appendChild(x.createComment(D.data));break;case c.TokenType.PI:var b=S;if(b.target.indexOf(":")!==-1||/^xml$/i.test(b.target))throw new Error("Processing instruction target contains invalid characters.");if(!f.xml_isLegalChar(b.data)||b.data.indexOf("?>")!==-1)throw new Error("Processing instruction data contains invalid characters.");C.appendChild(x.createProcessingInstruction(b.target,b.data));break;case c.TokenType.Text:var I=S;if(!f.xml_isLegalChar(I.data))throw new Error("Text data contains invalid characters.");C.appendChild(x.createTextNode(this._decodeText(I.data)));break;case c.TokenType.Element:var P=S,M=o(f.namespace_extractQName(P.name),2),L=M[0],V=M[1];if(V.indexOf(":")!==-1||!f.xml_isName(V))throw new Error("Node local name contains invalid characters.");if(L==="xmlns")throw new Error("An element cannot have the 'xmlns' prefix.");var G=C.lookupNamespaceURI(L),A={};try{for(var k=(p=void 0,a(P.attributes)),F=k.next();!F.done;F=k.next()){var j=o(F.value,2),Y=j[0],re=j[1];if(Y==="xmlns")G=re;else{var ue=o(f.namespace_extractQName(Y),2),ce=ue[0],pe=ue[1];ce==="xmlns"&&(pe===L&&(G=re),A[pe]=re)}}}catch(K){p={error:K}}finally{try{F&&!F.done&&(v=k.return)&&v.call(k)}finally{if(p)throw p.error}}var Ee=G!==null?x.createElementNS(G,P.name):x.createElement(P.name);C.appendChild(Ee);var Oe=new u.LocalNameSet;try{for(var _e=(y=void 0,a(P.attributes)),B=_e.next();!B.done;B=_e.next()){var O=o(B.value,2),z=(Y=O[0],re=O[1],o(f.namespace_extractQName(Y),2)),W=(ce=z[0],pe=z[1],null);if(ce==="xmlns"||ce===null&&pe==="xmlns"?W=l.namespace.XMLNS:(W=Ee.lookupNamespaceURI(ce))!==null&&Ee.isDefaultNamespace(W)?W=null:W===null&&ce!==null&&(W=A[ce]||null),Oe.has(W,pe))throw new Error("Element contains duplicate attributes.");if(Oe.set(W,pe),W===l.namespace.XMLNS&&re===l.namespace.XMLNS)throw new Error("XMLNS namespace is reserved.");if(pe.indexOf(":")!==-1||!f.xml_isName(pe))throw new Error("Attribute local name contains invalid characters.");if(ce==="xmlns"&&re==="")throw new Error("Empty XML namespace is not allowed.");W!==null?Ee.setAttributeNS(W,Y,this._decodeAttributeValue(re)):Ee.setAttribute(Y,this._decodeAttributeValue(re))}}catch(K){y={error:K}}finally{try{B&&!B.done&&(m=_e.return)&&m.call(_e)}finally{if(y)throw y.error}}P.selfClosing||(C=Ee);break;case c.TokenType.ClosingTag:if(S.name!==C.nodeName)throw new Error("Closing tag name does not match opening tag name.");C._parent&&(C=C._parent)}S=w.nextToken()}return x},h.prototype._decodeText=function(g){return g==null?g:g.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},h.prototype._decodeAttributeValue=function(g){return g==null?g:g.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},h}();n.XMLParserImpl=d},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(275);n.XMLSerializer=o.XMLSerializerImpl},function(r,n,i){var o=this&&this.__values||function(h){var g=typeof Symbol=="function"&&Symbol.iterator,p=g&&h[g],v=0;if(p)return p.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(g?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=i(2),s=i(69),c=i(95),l=i(9),f=i(7),u=i(0),d=function(){function h(){}return h.prototype.serializeToString=function(g){return this._xmlSerialization(g,!1)},h.prototype._xmlSerialization=function(g,p){if(g._nodeDocument===void 0||g._nodeDocument._hasNamespaces){var v=new c.NamespacePrefixMap;v.set("xml",f.namespace.XML);try{return this._serializeNodeNS(g,null,v,{value:1},p)}catch{throw new l.InvalidStateError}}else try{return this._serializeNode(g,p)}catch{throw new l.InvalidStateError}},h.prototype._serializeNodeNS=function(g,p,v,y,m){switch(g.nodeType){case a.NodeType.Element:return this._serializeElementNS(g,p,v,y,m);case a.NodeType.Document:return this._serializeDocumentNS(g,p,v,y,m);case a.NodeType.Comment:return this._serializeComment(g,m);case a.NodeType.Text:return this._serializeText(g,m);case a.NodeType.DocumentFragment:return this._serializeDocumentFragmentNS(g,p,v,y,m);case a.NodeType.DocumentType:return this._serializeDocumentType(g,m);case a.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(g,m);case a.NodeType.CData:return this._serializeCData(g,m);default:throw new Error("Unknown node type: "+g.nodeType)}},h.prototype._serializeNode=function(g,p){switch(g.nodeType){case a.NodeType.Element:return this._serializeElement(g,p);case a.NodeType.Document:return this._serializeDocument(g,p);case a.NodeType.Comment:return this._serializeComment(g,p);case a.NodeType.Text:return this._serializeText(g,p);case a.NodeType.DocumentFragment:return this._serializeDocumentFragment(g,p);case a.NodeType.DocumentType:return this._serializeDocumentType(g,p);case a.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(g,p);case a.NodeType.CData:return this._serializeCData(g,p);default:throw new Error("Unknown node type: "+g.nodeType)}},h.prototype._serializeElementNS=function(g,p,v,y,m){var w,x;if(m&&(g.localName.indexOf(":")!==-1||!u.xml_isName(g.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var C="<",S="",_=!1,T=!1,E=v.copy(),D={},b=this._recordNamespaceInformation(g,E,D),I=p,P=g.namespaceURI;if(I===P)b!==null&&(T=!0),C+=S=P===f.namespace.XML?"xml:"+g.localName:g.localName;else{var M=g.prefix,L=null;if(M===null&&P===b||(L=E.get(M,P)),M==="xmlns"){if(m)throw new Error("An element cannot have the 'xmlns' prefix (well-formed required).");L=M}L!==null?(S=L+":"+g.localName,b!==null&&b!==f.namespace.XML&&(I=b||null),C+=S):M!==null?(M in D&&(M=this._generatePrefix(P,E,y)),E.set(M,P),C+=S+=M+":"+g.localName,C+=" xmlns:"+M+'="'+this._serializeAttributeValue(P,m)+'"',b!==null&&(I=b||null)):b===null||b!==null&&b!==P?(T=!0,I=P,C+=S+=g.localName,C+=' xmlns="'+this._serializeAttributeValue(P,m)+'"'):(I=P,C+=S+=g.localName)}C+=this._serializeAttributesNS(g,E,y,D,T,m);var V=P===f.namespace.HTML;if(V&&g.childNodes.length===0&&h._VoidElementNames.has(g.localName)?(C+=" /",_=!0):V||g.childNodes.length!==0||(C+="/",_=!0),C+=">",_)return C;if(!(V&&g.localName==="template"))try{for(var G=o(g._children||g.childNodes),A=G.next();!A.done;A=G.next()){var k=A.value;C+=this._serializeNodeNS(k,I,E,y,m)}}catch(F){w={error:F}}finally{try{A&&!A.done&&(x=G.return)&&x.call(G)}finally{if(w)throw w.error}}return C+=""},h.prototype._serializeDocumentNS=function(g,p,v,y,m){var w,x;if(m&&g.documentElement===null)throw new Error("Missing document element (well-formed required).");var C="";try{for(var S=o(g._children||g.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;C+=this._serializeNodeNS(T,p,v,y,m)}}catch(E){w={error:E}}finally{try{_&&!_.done&&(x=S.return)&&x.call(S)}finally{if(w)throw w.error}}return C},h.prototype._serializeComment=function(g,p){if(p&&(!u.xml_isLegalChar(g.data)||g.data.indexOf("--")!==-1||g.data.endsWith("-")))throw new Error("Comment data contains invalid characters (well-formed required).");return""},h.prototype._serializeText=function(g,p){if(p&&!u.xml_isLegalChar(g.data))throw new Error("Text data contains invalid characters (well-formed required).");for(var v="",y=0;y"?">":m}return v},h.prototype._serializeDocumentFragmentNS=function(g,p,v,y,m){var w,x,C="";try{for(var S=o(g._children||g.childNodes),_=S.next();!_.done;_=S.next()){var T=_.value;C+=this._serializeNodeNS(T,p,v,y,m)}}catch(E){w={error:E}}finally{try{_&&!_.done&&(x=S.return)&&x.call(S)}finally{if(w)throw w.error}}return C},h.prototype._serializeDocumentType=function(g,p){if(p&&!u.xml_isPubidChar(g.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(p&&(!u.xml_isLegalChar(g.systemId)||g.systemId.indexOf('"')!==-1&&g.systemId.indexOf("'")!==-1))throw new Error("DocType system identifier contains invalid characters (well-formed required).");return g.publicId&&g.systemId?"':g.publicId?"':g.systemId?"':""},h.prototype._serializeProcessingInstruction=function(g,p){if(p&&(g.target.indexOf(":")!==-1||/^xml$/i.test(g.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(p&&(!u.xml_isLegalChar(g.data)||g.data.indexOf("?>")!==-1))throw new Error("Processing instruction data contains invalid characters (well-formed required).");return""},h.prototype._serializeCData=function(g,p){if(p&&g.data.indexOf("]]>")!==-1)throw new Error("CDATA contains invalid characters (well-formed required).");return""},h.prototype._serializeAttributesNS=function(g,p,v,y,m,w){var x,C,S="",_=w?new s.LocalNameSet:void 0;try{for(var T=o(g.attributes),E=T.next();!E.done;E=T.next()){var D=E.value;if(m||w||D.namespaceURI!==null){if(w&&_&&_.has(D.namespaceURI,D.localName))throw new Error("Element contains duplicate attributes (well-formed required).");w&&_&&_.set(D.namespaceURI,D.localName);var b=D.namespaceURI,I=null;if(b!==null)if(I=p.get(D.prefix,b),b===f.namespace.XMLNS){if(D.value===f.namespace.XML||D.prefix===null&&m||D.prefix!==null&&(!(D.localName in y)||y[D.localName]!==D.value)&&p.has(D.localName,D.value))continue;if(w&&D.value===f.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(w&&D.value==="")throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");D.prefix==="xmlns"&&(I="xmlns")}else I===null&&(S+=" xmlns:"+(I=D.prefix===null||p.hasPrefix(D.prefix)&&!p.has(D.prefix,b)?this._generatePrefix(b,p,v):D.prefix)+'="'+this._serializeAttributeValue(b,w)+'"');if(S+=" ",I!==null&&(S+=I+":"),w&&(D.localName.indexOf(":")!==-1||!u.xml_isName(D.localName)||D.localName==="xmlns"&&b===null))throw new Error("Attribute local name contains invalid characters (well-formed required).");S+=D.localName+'="'+this._serializeAttributeValue(D.value,w)+'"'}else S+=" "+D.localName+'="'+this._serializeAttributeValue(D.value,w)+'"'}}catch(P){x={error:P}}finally{try{E&&!E.done&&(C=T.return)&&C.call(T)}finally{if(x)throw x.error}}return S},h.prototype._recordNamespaceInformation=function(g,p,v){var y,m,w=null;try{for(var x=o(g.attributes),C=x.next();!C.done;C=x.next()){var S=C.value,_=S.namespaceURI,T=S.prefix;if(_===f.namespace.XMLNS){if(T===null){w=S.value;continue}var E=S.localName,D=S.value;if(D===f.namespace.XML||(D===""&&(D=null),p.has(E,D)))continue;p.set(E,D),v[E]=D||""}}}catch(b){y={error:b}}finally{try{C&&!C.done&&(m=x.return)&&m.call(x)}finally{if(y)throw y.error}}return w},h.prototype._generatePrefix=function(g,p,v){var y="ns"+v.value;return v.value++,p.set(y,g),y},h.prototype._serializeAttributeValue=function(g,p){if(p&&g!==null&&!u.xml_isLegalChar(g))throw new Error("Invalid characters in attribute value.");if(g===null)return"";for(var v="",y=0;y"?">":m}return v},h.prototype._serializeElement=function(g,p){var v,y;if(p&&(g.localName.indexOf(":")!==-1||!u.xml_isName(g.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var m=!1,w=g.localName,x="<"+w;if(x+=this._serializeAttributes(g,p),g._children.size===0&&(x+="/",m=!0),x+=">",m)return x;try{for(var C=o(g._children),S=C.next();!S.done;S=C.next()){var _=S.value;x+=this._serializeNode(_,p)}}catch(T){v={error:T}}finally{try{S&&!S.done&&(y=C.return)&&y.call(C)}finally{if(v)throw v.error}}return x+=""},h.prototype._serializeDocument=function(g,p){var v,y;if(p&&g.documentElement===null)throw new Error("Missing document element (well-formed required).");var m="";try{for(var w=o(g._children),x=w.next();!x.done;x=w.next()){var C=x.value;m+=this._serializeNode(C,p)}}catch(S){v={error:S}}finally{try{x&&!x.done&&(y=w.return)&&y.call(w)}finally{if(v)throw v.error}}return m},h.prototype._serializeDocumentFragment=function(g,p){var v,y,m="";try{for(var w=o(g._children),x=w.next();!x.done;x=w.next()){var C=x.value;m+=this._serializeNode(C,p)}}catch(S){v={error:S}}finally{try{x&&!x.done&&(y=w.return)&&y.call(w)}finally{if(v)throw v.error}}return m},h.prototype._serializeAttributes=function(g,p){var v,y,m="",w=p?{}:void 0;try{for(var x=o(g.attributes),C=x.next();!C.done;C=x.next()){var S=C.value;if(p&&w&&S.localName in w)throw new Error("Element contains duplicate attributes (well-formed required).");if(p&&w&&(w[S.localName]=!0),p&&(S.localName.indexOf(":")!==-1||!u.xml_isName(S.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");m+=" "+S.localName+'="'+this._serializeAttributeValue(S.value,p)+'"'}}catch(_){v={error:_}}finally{try{C&&!C.done&&(y=x.return)&&y.call(x)}finally{if(v)throw v.error}}return m},h._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),h}();n.XMLSerializerImpl=d},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(277);n.XMLReader=o.XMLReader;var a=i(112);n.ObjectReader=a.ObjectReader;var s=i(280);n.JSONReader=s.JSONReader;var c=i(281);n.YAMLReader=c.YAMLReader},function(r,n,i){i(31),i(32),i(33),i(19),i(65),i(20),i(22),i(23);var o,a=this&&this.__extends||(o=function(g,p){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,y){v.__proto__=y}||function(v,y){for(var m in y)y.hasOwnProperty(m)&&(v[m]=y[m])})(g,p)},function(g,p){function v(){this.constructor=g}o(g,p),g.prototype=p===null?Object.create(p):(v.prototype=p.prototype,new v)}),s=this&&this.__read||function(g,p){var v=typeof Symbol=="function"&&g[Symbol.iterator];if(!v)return g;var y,m,w=v.call(g),x=[];try{for(;(p===void 0||p-- >0)&&!(y=w.next()).done;)x.push(y.value)}catch(C){m={error:C}}finally{try{y&&!y.done&&(v=w.return)&&v.call(w)}finally{if(m)throw m.error}}return x},c=this&&this.__values||function(g){var p=typeof Symbol=="function"&&Symbol.iterator,v=p&&g[p],y=0;if(v)return v.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&y>=g.length&&(g=void 0),{value:g&&g[y++],done:!g}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var l=i(180),f=i(111),u=i(7),d=i(0),h=function(g){function p(){return g!==null&&g.apply(this,arguments)||this}return a(p,g),p.prototype._parse=function(v,y){for(var m,w,x,C,S=new l.XMLStringLexer(y,{skipWhitespaceOnlyText:!0}),_=v,T=v,E=S.nextToken();E.type!==f.TokenType.EOF;){switch(E.type){case f.TokenType.Declaration:var D=E,b=this.sanitize(D.version);if(b!=="1.0")throw new Error("Invalid xml version: "+b);var I={version:b};D.encoding&&(I.encoding=this.sanitize(D.encoding)),D.standalone&&(I.standalone=this.sanitize(D.standalone)==="yes"),T.set(I);break;case f.TokenType.DocType:var P=E;T=this.docType(T,this.sanitize(P.name),this.sanitize(P.pubId),this.sanitize(P.sysId))||T;break;case f.TokenType.CDATA:var M=E;T=this.cdata(T,this.sanitize(M.data))||T;break;case f.TokenType.Comment:var L=E;T=this.comment(T,this.sanitize(L.data))||T;break;case f.TokenType.PI:var V=E;T=this.instruction(T,this.sanitize(V.target),this.sanitize(V.data))||T;break;case f.TokenType.Text:var G=E;T=this.text(T,this._decodeText(this.sanitize(G.data)))||T;break;case f.TokenType.Element:var A=E,k=this.sanitize(A.name),F=s(d.namespace_extractQName(k),1)[0],j=T.node.lookupNamespaceURI(F),Y={};try{for(var re=(m=void 0,c(A.attributes)),ue=re.next();!ue.done;ue=re.next()){var ce=s(ue.value,2),pe=ce[0],Ee=ce[1];if(pe=this.sanitize(pe),Ee=this.sanitize(Ee),pe==="xmlns")j=Ee;else{var Oe=s(d.namespace_extractQName(pe),2),_e=Oe[0],B=Oe[1];_e==="xmlns"&&(B===F&&(j=Ee),Y[B]=Ee)}}}catch(xe){m={error:xe}}finally{try{ue&&!ue.done&&(w=re.return)&&w.call(re)}finally{if(m)throw m.error}}var O=j!==null?this.element(T,j,k):this.element(T,void 0,k);if(O===void 0)break;T.node===v.node&&(_=O);try{for(var z=(x=void 0,c(A.attributes)),W=z.next();!W.done;W=z.next()){var K=s(W.value,2);pe=K[0],Ee=K[1],pe=this.sanitize(pe),Ee=this.sanitize(Ee);var Z=s(d.namespace_extractQName(pe),2),ee=(_e=Z[0],B=Z[1],null);_e==="xmlns"||_e===null&&B==="xmlns"?ee=u.namespace.XMLNS:(ee=O.node.lookupNamespaceURI(_e))!==null&&O.node.isDefaultNamespace(ee)?ee=null:ee===null&&_e!==null&&(ee=Y[_e]||null),ee!==null?this.attribute(O,ee,pe,this._decodeAttributeValue(Ee)):this.attribute(O,void 0,pe,this._decodeAttributeValue(Ee))}}catch(xe){x={error:xe}}finally{try{W&&!W.done&&(C=z.return)&&C.call(z)}finally{if(x)throw x.error}}A.selfClosing||(T=O);break;case f.TokenType.ClosingTag:T.node.parentNode&&(T=T.up())}E=S.nextToken()}return _},p}(i(75).BaseReader);n.XMLReader=h},function(r,n,i){var o=i(4),a=i(279);o({target:"Object",stat:!0,forced:Object.assign!==a},{assign:a})},function(r,n,i){var o=i(16),a=i(8),s=i(61),c=i(85),l=i(79),f=i(27),u=i(41),d=Object.assign,h=Object.defineProperty;r.exports=!d||a(function(){if(o&&d({b:1},d(h({},"a",{enumerable:!0,get:function(){h(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var g={},p={},v=Symbol();return g[v]=7,"abcdefghijklmnopqrst".split("").forEach(function(y){p[y]=y}),d({},g)[v]!=7||s(d({},p)).join("")!="abcdefghijklmnopqrst"})?function(g,p){for(var v=f(g),y=arguments.length,m=1,w=c.f,x=l.f;y>m;)for(var C,S=u(arguments[m++]),_=w?s(S).concat(w(S)):s(S),T=_.length,E=0;T>E;)C=_[E++],o&&!x.call(S,C)||(v[C]=S[C]);return v}:d},function(r,n,i){var o,a=this&&this.__extends||(o=function(l,f){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,d){u.__proto__=d}||function(u,d){for(var h in d)d.hasOwnProperty(h)&&(u[h]=d[h])})(l,f)},function(l,f){function u(){this.constructor=l}o(l,f),l.prototype=f===null?Object.create(f):(u.prototype=f.prototype,new u)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(112),c=function(l){function f(){return l!==null&&l.apply(this,arguments)||this}return a(f,l),f.prototype._parse=function(u,d){return new s.ObjectReader(this._builderOptions).parse(u,JSON.parse(d))},f}(i(75).BaseReader);n.JSONReader=c},function(r,n,i){var o,a=this&&this.__extends||(o=function(u,d){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,g){h.__proto__=g}||function(h,g){for(var p in g)g.hasOwnProperty(p)&&(h[p]=g[p])})(u,d)},function(u,d){function h(){this.constructor=u}o(u,d),u.prototype=d===null?Object.create(d):(h.prototype=d.prototype,new h)});Object.defineProperty(n,"__esModule",{value:!0});var s=i(112),c=i(75),l=i(282),f=function(u){function d(){return u!==null&&u.apply(this,arguments)||this}return a(d,u),d.prototype._parse=function(h,g){var p=l.safeLoad(g);if(p===void 0)throw new Error("Unable to parse YAML document.");return new s.ObjectReader(this._builderOptions).parse(h,p)},d}(c.BaseReader);n.YAMLReader=f},function(r,n,i){var o=i(283);r.exports=o},function(r,n,i){var o=i(284),a=i(303);function s(c){return function(){throw new Error("Function "+c+" is deprecated and cannot be used.")}}r.exports.Type=i(10),r.exports.Schema=i(39),r.exports.FAILSAFE_SCHEMA=i(113),r.exports.JSON_SCHEMA=i(182),r.exports.CORE_SCHEMA=i(181),r.exports.DEFAULT_SAFE_SCHEMA=i(54),r.exports.DEFAULT_FULL_SCHEMA=i(76),r.exports.load=o.load,r.exports.loadAll=o.loadAll,r.exports.safeLoad=o.safeLoad,r.exports.safeLoadAll=o.safeLoadAll,r.exports.dump=a.dump,r.exports.safeDump=a.safeDump,r.exports.YAMLException=i(53),r.exports.MINIMAL_SCHEMA=i(113),r.exports.SAFE_SCHEMA=i(54),r.exports.DEFAULT_SCHEMA=i(76),r.exports.scan=s("scan"),r.exports.parse=s("parse"),r.exports.compose=s("compose"),r.exports.addConstructor=s("addConstructor")},function(r,n,i){var o=i(38),a=i(53),s=i(285),c=i(54),l=i(76),f=Object.prototype.hasOwnProperty,u=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,d=/[\x85\u2028\u2029]/,h=/[,\[\]\{\}]/,g=/^(?:!|!!|![a-z\-]+!)$/i,p=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function v(O){return Object.prototype.toString.call(O)}function y(O){return O===10||O===13}function m(O){return O===9||O===32}function w(O){return O===9||O===32||O===10||O===13}function x(O){return O===44||O===91||O===93||O===123||O===125}function C(O){var z;return 48<=O&&O<=57?O-48:97<=(z=32|O)&&z<=102?z-97+10:-1}function S(O){return O===48?"\0":O===97?"\x07":O===98?"\b":O===116||O===9?" ":O===110?` +`:O===118?"\v":O===102?"\f":O===114?"\r":O===101?"\x1B":O===32?" ":O===34?'"':O===47?"/":O===92?"\\":O===78?"…":O===95?" ":O===76?"\u2028":O===80?"\u2029":""}function _(O){return O<=65535?String.fromCharCode(O):String.fromCharCode(55296+(O-65536>>10),56320+(O-65536&1023))}for(var T=new Array(256),E=new Array(256),D=0;D<256;D++)T[D]=S(D)?1:0,E[D]=S(D);function b(O,z){this.input=O,this.filename=z.filename||null,this.schema=z.schema||l,this.onWarning=z.onWarning||null,this.legacy=z.legacy||!1,this.json=z.json||!1,this.listener=z.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=O.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function I(O,z){return new a(z,new s(O.filename,O.input,O.position,O.line,O.position-O.lineStart))}function P(O,z){throw I(O,z)}function M(O,z){O.onWarning&&O.onWarning.call(null,I(O,z))}var L={YAML:function(O,z,W){var K,Z,ee;O.version!==null&&P(O,"duplication of %YAML directive"),W.length!==1&&P(O,"YAML directive accepts exactly one argument"),(K=/^([0-9]+)\.([0-9]+)$/.exec(W[0]))===null&&P(O,"ill-formed argument of the YAML directive"),Z=parseInt(K[1],10),ee=parseInt(K[2],10),Z!==1&&P(O,"unacceptable YAML version of the document"),O.version=W[0],O.checkLineBreaks=ee<2,ee!==1&&ee!==2&&M(O,"unsupported YAML version of the document")},TAG:function(O,z,W){var K,Z;W.length!==2&&P(O,"TAG directive accepts exactly two arguments"),K=W[0],Z=W[1],g.test(K)||P(O,"ill-formed tag handle (first argument) of the TAG directive"),f.call(O.tagMap,K)&&P(O,'there is a previously declared suffix for "'+K+'" tag handle'),p.test(Z)||P(O,"ill-formed tag prefix (second argument) of the TAG directive"),O.tagMap[K]=Z}};function V(O,z,W,K){var Z,ee,xe,De;if(z1&&(O.result+=o.repeat(` +`,z-1))}function re(O,z){var W,K,Z=O.tag,ee=O.anchor,xe=[],De=!1;for(O.anchor!==null&&(O.anchorMap[O.anchor]=xe),K=O.input.charCodeAt(O.position);K!==0&&K===45&&w(O.input.charCodeAt(O.position+1));)if(De=!0,O.position++,F(O,!0,-1)&&O.lineIndent<=z)xe.push(null),K=O.input.charCodeAt(O.position);else if(W=O.line,pe(O,z,3,!1,!0),xe.push(O.result),F(O,!0,-1),K=O.input.charCodeAt(O.position),(O.line===W||O.lineIndent>z)&&K!==0)P(O,"bad indentation of a sequence entry");else if(O.lineIndentz?se=1:O.lineIndent===z?se=0:O.lineIndentz?se=1:O.lineIndent===z?se=0:O.lineIndentht)&&(pe(oe,ht,4,!0,Ie)&&(fn?Pn=oe.result:$n=oe.result),fn||(A(oe,xt,Ft,jt,Pn,$n,je,nt),jt=Pn=$n=null),F(oe,!0,-1),rt=oe.input.charCodeAt(oe.position)),oe.lineIndent>ht&&rt!==0)P(oe,"bad indentation of a mapping entry");else if(oe.lineIndent=0))break;Ie===0?P(oe,"bad explicit indentation width of a block scalar; it cannot be less than one"):Lt?P(oe,"repeat of an indentation width identifier"):(xt=ht+Ie-1,Lt=!0)}if(m(je)){do je=oe.input.charCodeAt(++oe.position);while(m(je));if(je===35)do je=oe.input.charCodeAt(++oe.position);while(!y(je)&&je!==0)}for(;je!==0;){for(k(oe),oe.lineIndent=0,je=oe.input.charCodeAt(oe.position);(!Lt||oe.lineIndentxt&&(xt=oe.lineIndent),y(je))Ft++;else{if(oe.lineIndent0){for(Ie=tt,$e=0;Ie>0;Ie--)(tt=C(nt=oe.input.charCodeAt(++oe.position)))>=0?$e=($e<<4)+tt:P(oe,"expected hexadecimal character");oe.result+=_($e),oe.position++}else P(oe,"unknown escape sequence");wt=gt=oe.position}else y(nt)?(V(oe,wt,gt,!0),Y(oe,F(oe,!1,ht)),wt=gt=oe.position):oe.position===oe.lineStart&&j(oe)?P(oe,"unexpected end of the document within a double quoted scalar"):(oe.position++,gt=oe.position)}P(oe,"unexpected end of the stream within a double quoted scalar")}(O,ae)?Fe=!0:function(oe){var ht,wt,gt;if((gt=oe.input.charCodeAt(oe.position))!==42)return!1;for(gt=oe.input.charCodeAt(++oe.position),ht=oe.position;gt!==0&&!w(gt)&&!x(gt);)gt=oe.input.charCodeAt(++oe.position);return oe.position===ht&&P(oe,"name of an alias node must contain at least one character"),wt=oe.input.slice(ht,oe.position),oe.anchorMap.hasOwnProperty(wt)||P(oe,'unidentified alias "'+wt+'"'),oe.result=oe.anchorMap[wt],F(oe,!0,-1),!0}(O)?(Fe=!0,O.tag===null&&O.anchor===null||P(O,"alias node should not have any properties")):function(oe,ht,wt){var gt,Ie,$e,tt,nt,dt,Lt,xt,Ft=oe.kind,jt=oe.result;if(w(xt=oe.input.charCodeAt(oe.position))||x(xt)||xt===35||xt===38||xt===42||xt===33||xt===124||xt===62||xt===39||xt===34||xt===37||xt===64||xt===96||(xt===63||xt===45)&&(w(gt=oe.input.charCodeAt(oe.position+1))||wt&&x(gt)))return!1;for(oe.kind="scalar",oe.result="",Ie=$e=oe.position,tt=!1;xt!==0;){if(xt===58){if(w(gt=oe.input.charCodeAt(oe.position+1))||wt&&x(gt))break}else if(xt===35){if(w(oe.input.charCodeAt(oe.position-1)))break}else{if(oe.position===oe.lineStart&&j(oe)||wt&&x(xt))break;if(y(xt)){if(nt=oe.line,dt=oe.lineStart,Lt=oe.lineIndent,F(oe,!1,-1),oe.lineIndent>=ht){tt=!0,xt=oe.input.charCodeAt(oe.position);continue}oe.position=$e,oe.line=nt,oe.lineStart=dt,oe.lineIndent=Lt;break}}tt&&(V(oe,Ie,$e,!1),Y(oe,oe.line-nt),Ie=$e=oe.position,tt=!1),m(xt)||($e=oe.position+1),xt=oe.input.charCodeAt(++oe.position)}return V(oe,Ie,$e,!1),!!oe.result||(oe.kind=Ft,oe.result=jt,!1)}(O,ae,W===1)&&(Fe=!0,O.tag===null&&(O.tag="?")),O.anchor!==null&&(O.anchorMap[O.anchor]=O.result)):se===0&&(Fe=De&&re(O,we))),O.tag!==null&&O.tag!=="!")if(O.tag==="?"){for(O.result!==null&&O.kind!=="scalar"&&P(O,'unacceptable node kind for ! tag; it should be "scalar", not "'+O.kind+'"'),Ne=0,ze=O.implicitTypes.length;Ne tag; it should be "'+ie.kind+'", not "'+O.kind+'"'),ie.resolve(O.result)?(O.result=ie.construct(O.result),O.anchor!==null&&(O.anchorMap[O.anchor]=O.result)):P(O,"cannot resolve a node with !<"+O.tag+"> explicit tag")):P(O,"unknown tag !<"+O.tag+">");return O.listener!==null&&O.listener("close",O),O.tag!==null||O.anchor!==null||Fe}function Ee(O){var z,W,K,Z,ee=O.position,xe=!1;for(O.version=null,O.checkLineBreaks=O.legacy,O.tagMap={},O.anchorMap={};(Z=O.input.charCodeAt(O.position))!==0&&(F(O,!0,-1),Z=O.input.charCodeAt(O.position),!(O.lineIndent>0||Z!==37));){for(xe=!0,Z=O.input.charCodeAt(++O.position),z=O.position;Z!==0&&!w(Z);)Z=O.input.charCodeAt(++O.position);for(K=[],(W=O.input.slice(z,O.position)).length<1&&P(O,"directive name must not be less than one character in length");Z!==0;){for(;m(Z);)Z=O.input.charCodeAt(++O.position);if(Z===35){do Z=O.input.charCodeAt(++O.position);while(Z!==0&&!y(Z));break}if(y(Z))break;for(z=O.position;Z!==0&&!w(Z);)Z=O.input.charCodeAt(++O.position);K.push(O.input.slice(z,O.position))}Z!==0&&k(O),f.call(L,W)?L[W](O,W,K):M(O,'unknown document directive "'+W+'"')}F(O,!0,-1),O.lineIndent===0&&O.input.charCodeAt(O.position)===45&&O.input.charCodeAt(O.position+1)===45&&O.input.charCodeAt(O.position+2)===45?(O.position+=3,F(O,!0,-1)):xe&&P(O,"directives end mark is expected"),pe(O,O.lineIndent-1,4,!1,!0),F(O,!0,-1),O.checkLineBreaks&&d.test(O.input.slice(ee,O.position))&&M(O,"non-ASCII line breaks are interpreted as content"),O.documents.push(O.result),O.position===O.lineStart&&j(O)?O.input.charCodeAt(O.position)===46&&(O.position+=3,F(O,!0,-1)):O.position0&&`\0\r +`,dt?1+Ft:Ft),dt=!0,Lt=!0,Ft=0,wt=oe.position;!y(je)&&je!==0;)je=oe.input.charCodeAt(++oe.position);V(oe,wt,oe.position,!1)}}return!0}(O,ae)||function(oe,ht){var wt,gt,Ie;if((wt=oe.input.charCodeAt(oe.position))!==39)return!1;for(oe.kind="scalar",oe.result="",oe.position++,gt=Ie=oe.position;(wt=oe.input.charCodeAt(oe.position))!==0;)if(wt===39){if(V(oe,gt,oe.position,!0),(wt=oe.input.charCodeAt(++oe.position))!==39)return!0;gt=oe.position,oe.position++,Ie=oe.position}else y(wt)?(V(oe,gt,Ie,!0),Y(oe,F(oe,!1,ht)),gt=Ie=oe.position):oe.position===oe.lineStart&&j(oe)?P(oe,"unexpected end of the document within a single quoted scalar"):(oe.position++,Ie=oe.position);P(oe,"unexpected end of the stream within a single quoted scalar")}(O,ae)||function(oe,ht){var wt,gt,Ie,je,nt,rt,dt;if((rt=oe.input.charCodeAt(oe.position))!==34)return!1;for(oe.kind="scalar",oe.result="",oe.position++,wt=gt=oe.position;(rt=oe.input.charCodeAt(oe.position))!==0;){if(rt===34)return V(oe,wt,oe.position,!0),oe.position++,!0;if(rt===92){if(V(oe,wt,oe.position,!0),y(rt=oe.input.charCodeAt(++oe.position)))F(oe,!1,ht);else if(rt<256&&T[rt])oe.result+=E[rt],oe.position++;else if((nt=(dt=rt)===120?2:dt===117?4:dt===85?8:0)>0){for(Ie=nt,je=0;Ie>0;Ie--)(nt=C(rt=oe.input.charCodeAt(++oe.position)))>=0?je=(je<<4)+nt:P(oe,"expected hexadecimal character");oe.result+=_(je),oe.position++}else P(oe,"unknown escape sequence");wt=gt=oe.position}else y(rt)?(V(oe,wt,gt,!0),Y(oe,F(oe,!1,ht)),wt=gt=oe.position):oe.position===oe.lineStart&&j(oe)?P(oe,"unexpected end of the document within a double quoted scalar"):(oe.position++,gt=oe.position)}P(oe,"unexpected end of the stream within a double quoted scalar")}(O,ae)?Fe=!0:function(oe){var ht,wt,gt;if((gt=oe.input.charCodeAt(oe.position))!==42)return!1;for(gt=oe.input.charCodeAt(++oe.position),ht=oe.position;gt!==0&&!w(gt)&&!x(gt);)gt=oe.input.charCodeAt(++oe.position);return oe.position===ht&&P(oe,"name of an alias node must contain at least one character"),wt=oe.input.slice(ht,oe.position),oe.anchorMap.hasOwnProperty(wt)||P(oe,'unidentified alias "'+wt+'"'),oe.result=oe.anchorMap[wt],F(oe,!0,-1),!0}(O)?(Fe=!0,O.tag===null&&O.anchor===null||P(O,"alias node should not have any properties")):function(oe,ht,wt){var gt,Ie,je,nt,rt,dt,Lt,xt,Ft=oe.kind,jt=oe.result;if(w(xt=oe.input.charCodeAt(oe.position))||x(xt)||xt===35||xt===38||xt===42||xt===33||xt===124||xt===62||xt===39||xt===34||xt===37||xt===64||xt===96||(xt===63||xt===45)&&(w(gt=oe.input.charCodeAt(oe.position+1))||wt&&x(gt)))return!1;for(oe.kind="scalar",oe.result="",Ie=je=oe.position,nt=!1;xt!==0;){if(xt===58){if(w(gt=oe.input.charCodeAt(oe.position+1))||wt&&x(gt))break}else if(xt===35){if(w(oe.input.charCodeAt(oe.position-1)))break}else{if(oe.position===oe.lineStart&&j(oe)||wt&&x(xt))break;if(y(xt)){if(rt=oe.line,dt=oe.lineStart,Lt=oe.lineIndent,F(oe,!1,-1),oe.lineIndent>=ht){nt=!0,xt=oe.input.charCodeAt(oe.position);continue}oe.position=je,oe.line=rt,oe.lineStart=dt,oe.lineIndent=Lt;break}}nt&&(V(oe,Ie,je,!1),Y(oe,oe.line-rt),Ie=je=oe.position,nt=!1),m(xt)||(je=oe.position+1),xt=oe.input.charCodeAt(++oe.position)}return V(oe,Ie,je,!1),!!oe.result||(oe.kind=Ft,oe.result=jt,!1)}(O,ae,W===1)&&(Fe=!0,O.tag===null&&(O.tag="?")),O.anchor!==null&&(O.anchorMap[O.anchor]=O.result)):se===0&&(Fe=De&&re(O,ye))),O.tag!==null&&O.tag!=="!")if(O.tag==="?"){for(O.result!==null&&O.kind!=="scalar"&&P(O,'unacceptable node kind for ! tag; it should be "scalar", not "'+O.kind+'"'),Ne=0,$e=O.implicitTypes.length;Ne<$e;Ne+=1)if((ie=O.implicitTypes[Ne]).resolve(O.result)){O.result=ie.construct(O.result),O.tag=ie.tag,O.anchor!==null&&(O.anchorMap[O.anchor]=O.result);break}}else f.call(O.typeMap[O.kind||"fallback"],O.tag)?(ie=O.typeMap[O.kind||"fallback"][O.tag],O.result!==null&&ie.kind!==O.kind&&P(O,"unacceptable node kind for !<"+O.tag+'> tag; it should be "'+ie.kind+'", not "'+O.kind+'"'),ie.resolve(O.result)?(O.result=ie.construct(O.result),O.anchor!==null&&(O.anchorMap[O.anchor]=O.result)):P(O,"cannot resolve a node with !<"+O.tag+"> explicit tag")):P(O,"unknown tag !<"+O.tag+">");return O.listener!==null&&O.listener("close",O),O.tag!==null||O.anchor!==null||Fe}function Ee(O){var z,W,K,Z,ee=O.position,xe=!1;for(O.version=null,O.checkLineBreaks=O.legacy,O.tagMap={},O.anchorMap={};(Z=O.input.charCodeAt(O.position))!==0&&(F(O,!0,-1),Z=O.input.charCodeAt(O.position),!(O.lineIndent>0||Z!==37));){for(xe=!0,Z=O.input.charCodeAt(++O.position),z=O.position;Z!==0&&!w(Z);)Z=O.input.charCodeAt(++O.position);for(K=[],(W=O.input.slice(z,O.position)).length<1&&P(O,"directive name must not be less than one character in length");Z!==0;){for(;m(Z);)Z=O.input.charCodeAt(++O.position);if(Z===35){do Z=O.input.charCodeAt(++O.position);while(Z!==0&&!y(Z));break}if(y(Z))break;for(z=O.position;Z!==0&&!w(Z);)Z=O.input.charCodeAt(++O.position);K.push(O.input.slice(z,O.position))}Z!==0&&k(O),f.call(L,W)?L[W](O,W,K):M(O,'unknown document directive "'+W+'"')}F(O,!0,-1),O.lineIndent===0&&O.input.charCodeAt(O.position)===45&&O.input.charCodeAt(O.position+1)===45&&O.input.charCodeAt(O.position+2)===45?(O.position+=3,F(O,!0,-1)):xe&&P(O,"directives end mark is expected"),pe(O,O.lineIndent-1,4,!1,!0),F(O,!0,-1),O.checkLineBreaks&&d.test(O.input.slice(ee,O.position))&&M(O,"non-ASCII line breaks are interpreted as content"),O.documents.push(O.result),O.position===O.lineStart&&j(O)?O.input.charCodeAt(O.position)===46&&(O.position+=3,F(O,!0,-1)):O.position0&&`\0\r …\u2028\u2029`.indexOf(this.buffer.charAt(f-1))===-1;)if(f-=1,this.position-f>c/2-1){l=" ... ",f+=5;break}for(u="",d=this.position;dc/2-1){u=" ... ",d-=5;break}return h=this.buffer.slice(f,d),o.repeat(" ",s)+l+h+u+` `+o.repeat(" ",s+this.position-f+l.length)+"^"},a.prototype.toString=function(s){var c,l="";return this.name&&(l+='in "'+this.name+'" '),l+="at line "+(this.line+1)+", column "+(this.column+1),s||(c=this.getSnippet())&&(l+=`: `+c),l},r.exports=a},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:str",{kind:"scalar",construct:function(a){return a!==null?a:""}})},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(a){return a!==null?a:[]}})},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:map",{kind:"mapping",construct:function(a){return a!==null?a:{}}})},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:null",{kind:"scalar",resolve:function(a){if(a===null)return!0;var s=a.length;return s===1&&a==="~"||s===4&&(a==="null"||a==="Null"||a==="NULL")},construct:function(){return null},predicate:function(a){return a===null},represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(a){if(a===null)return!1;var s=a.length;return s===4&&(a==="true"||a==="True"||a==="TRUE")||s===5&&(a==="false"||a==="False"||a==="FALSE")},construct:function(a){return a==="true"||a==="True"||a==="TRUE"},predicate:function(a){return Object.prototype.toString.call(a)==="[object Boolean]"},represent:{lowercase:function(a){return a?"true":"false"},uppercase:function(a){return a?"TRUE":"FALSE"},camelcase:function(a){return a?"True":"False"}},defaultStyle:"lowercase"})},function(r,n,i){var o=i(38),a=i(10);function s(l){return 48<=l&&l<=55}function c(l){return 48<=l&&l<=57}r.exports=new a("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(l){if(l===null)return!1;var f,u,d=l.length,h=0,g=!1;if(!d)return!1;if((f=l[h])!=="-"&&f!=="+"||(f=l[++h]),f==="0"){if(h+1===d)return!0;if((f=l[++h])==="b"){for(h++;h=0?"0b"+l.toString(2):"-0b"+l.toString(2).slice(1)},octal:function(l){return l>=0?"0"+l.toString(8):"-0"+l.toString(8).slice(1)},decimal:function(l){return l.toString(10)},hexadecimal:function(l){return l>=0?"0x"+l.toString(16).toUpperCase():"-0x"+l.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})},function(r,n,i){var o=i(38),a=i(10),s=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),c=/^[-+]?[0-9]+e/;r.exports=new a("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(l){return l!==null&&!(!s.test(l)||l[l.length-1]==="_")},construct:function(l){var f,u,d,h;return u=(f=l.replace(/_/g,"").toLowerCase())[0]==="-"?-1:1,h=[],"+-".indexOf(f[0])>=0&&(f=f.slice(1)),f===".inf"?u===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:f===".nan"?NaN:f.indexOf(":")>=0?(f.split(":").forEach(function(g){h.unshift(parseFloat(g,10))}),f=0,d=1,h.forEach(function(g){f+=g*d,d*=60}),u*f):u*parseFloat(f,10)},predicate:function(l){return Object.prototype.toString.call(l)==="[object Number]"&&(l%1!=0||o.isNegativeZero(l))},represent:function(l,f){var u;if(isNaN(l))switch(f){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===l)switch(f){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===l)switch(f){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(o.isNegativeZero(l))return"-0.0";return u=l.toString(10),c.test(u)?u.replace("e",".e"):u},defaultStyle:"lowercase"})},function(r,n,i){var o=i(10),a=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),s=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");r.exports=new o("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(c){return c!==null&&(a.exec(c)!==null||s.exec(c)!==null)},construct:function(c){var l,f,u,d,h,g,p,v,y=0,m=null;if((l=a.exec(c))===null&&(l=s.exec(c)),l===null)throw new Error("Date resolve error");if(f=+l[1],u=+l[2]-1,d=+l[3],!l[4])return new Date(Date.UTC(f,u,d));if(h=+l[4],g=+l[5],p=+l[6],l[7]){for(y=l[7].slice(0,3);y.length<3;)y+="0";y=+y}return l[9]&&(m=6e4*(60*+l[10]+ +(l[11]||0)),l[9]==="-"&&(m=-m)),v=new Date(Date.UTC(f,u,d,h,g,p,y)),m&&v.setTime(v.getTime()-m),v},instanceOf:Date,represent:function(c){return c.toISOString()}})},function(r,n,i){var o=i(10);r.exports=new o("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(a){return a==="<<"||a===null}})},function(r,n,i){var o;try{o=i(145).Buffer}catch{}var a=i(10),s=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= \r`;r.exports=new a("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(c){if(c===null)return!1;var l,f,u=0,d=c.length,h=s;for(f=0;f64)){if(l<0)return!1;u+=6}return u%8==0},construct:function(c){var l,f,u=c.replace(/[\r\n=]/g,""),d=u.length,h=s,g=0,p=[];for(l=0;l>16&255),p.push(g>>8&255),p.push(255&g)),g=g<<6|h.indexOf(u.charAt(l));return(f=d%4*6)===0?(p.push(g>>16&255),p.push(g>>8&255),p.push(255&g)):f===18?(p.push(g>>10&255),p.push(g>>2&255)):f===12&&p.push(g>>4&255),o?o.from?o.from(p):new o(p):p},predicate:function(c){return o&&o.isBuffer(c)},represent:function(c){var l,f,u="",d=0,h=c.length,g=s;for(l=0;l>18&63],u+=g[d>>12&63],u+=g[d>>6&63],u+=g[63&d]),d=(d<<8)+c[l];return(f=h%3)===0?(u+=g[d>>18&63],u+=g[d>>12&63],u+=g[d>>6&63],u+=g[63&d]):f===2?(u+=g[d>>10&63],u+=g[d>>4&63],u+=g[d<<2&63],u+=g[64]):f===1&&(u+=g[d>>2&63],u+=g[d<<4&63],u+=g[64],u+=g[64]),u}})},function(r,n,i){var o=i(10),a=Object.prototype.hasOwnProperty,s=Object.prototype.toString;r.exports=new o("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(c){if(c===null)return!0;var l,f,u,d,h,g=[],p=c;for(l=0,f=p.length;l3||s[s.length-l.length-1]!=="/"))},construct:function(a){var s=a,c=/\/([gim]*)$/.exec(a),l="";return s[0]==="/"&&(c&&(l=c[1]),s=s.slice(1,s.length-l.length-1)),new RegExp(s,l)},predicate:function(a){return Object.prototype.toString.call(a)==="[object RegExp]"},represent:function(a){var s="/"+a.source+"/";return a.global&&(s+="g"),a.multiline&&(s+="m"),a.ignoreCase&&(s+="i"),s}})},function(r,n,i){var o;try{o=i(302)}catch{typeof window<"u"&&(o=window.esprima)}var a=i(10);r.exports=new a("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:function(s){if(s===null)return!1;try{var c="("+s+")",l=o.parse(c,{range:!0});return l.type==="Program"&&l.body.length===1&&l.body[0].type==="ExpressionStatement"&&(l.body[0].expression.type==="ArrowFunctionExpression"||l.body[0].expression.type==="FunctionExpression")}catch{return!1}},construct:function(s){var c,l="("+s+")",f=o.parse(l,{range:!0}),u=[];if(f.type!=="Program"||f.body.length!==1||f.body[0].type!=="ExpressionStatement"||f.body[0].expression.type!=="ArrowFunctionExpression"&&f.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return f.body[0].expression.params.forEach(function(d){u.push(d.name)}),c=f.body[0].expression.body.range,f.body[0].expression.body.type==="BlockStatement"?new Function(u,l.slice(c[0]+1,c[1]-1)):new Function(u,"return "+l.slice(c[0],c[1]))},predicate:function(s){return Object.prototype.toString.call(s)==="[object Function]"},represent:function(s){return s.toString()}})},function(r,n,i){var o;o=function(){return function(a){var s={};function c(l){if(s[l])return s[l].exports;var f=s[l]={exports:{},id:l,loaded:!1};return a[l].call(f.exports,f,f.exports,c),f.loaded=!0,f.exports}return c.m=a,c.c=s,c.p="",c(0)}([function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(1),f=c(3),u=c(8),d=c(15);function h(p,v,y){var m=null,w=function(D,b){y&&y(D,b),m&&m.visit(D,b)},x=typeof y=="function"?w:null,C=!1;if(v){C=typeof v.comment=="boolean"&&v.comment;var S=typeof v.attachComment=="boolean"&&v.attachComment;(C||S)&&((m=new l.CommentHandler).attach=S,v.comment=!0,x=w)}var _,T=!1;v&&typeof v.sourceType=="string"&&(T=v.sourceType==="module"),_=v&&typeof v.jsx=="boolean"&&v.jsx?new f.JSXParser(p,v,x):new u.Parser(p,v,x);var E=T?_.parseModule():_.parseScript();return C&&m&&(E.comments=m.comments),_.config.tokens&&(E.tokens=_.tokens),_.config.tolerant&&(E.errors=_.errorHandler.errors),E}s.parse=h,s.parseModule=function(p,v,y){var m=v||{};return m.sourceType="module",h(p,m,y)},s.parseScript=function(p,v,y){var m=v||{};return m.sourceType="script",h(p,m,y)},s.tokenize=function(p,v,y){var m,w=new d.Tokenizer(p,v);m=[];try{for(;;){var x=w.getNextToken();if(!x)break;y&&(x=y(x)),m.push(x)}}catch(C){w.errorHandler.tolerate(C)}return w.errorHandler.tolerant&&(m.errors=w.errors()),m};var g=c(2);s.Syntax=g.Syntax,s.version="4.0.1"},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(2),f=function(){function u(){this.attach=!1,this.comments=[],this.stack=[],this.leading=[],this.trailing=[]}return u.prototype.insertInnerComments=function(d,h){if(d.type===l.Syntax.BlockStatement&&d.body.length===0){for(var g=[],p=this.leading.length-1;p>=0;--p){var v=this.leading[p];h.end.offset>=v.start&&(g.unshift(v.comment),this.leading.splice(p,1),this.trailing.splice(p,1))}g.length&&(d.innerComments=g)}},u.prototype.findTrailingComments=function(d){var h=[];if(this.trailing.length>0){for(var g=this.trailing.length-1;g>=0;--g){var p=this.trailing[g];p.start>=d.end.offset&&h.unshift(p.comment)}return this.trailing.length=0,h}var v=this.stack[this.stack.length-1];if(v&&v.node.trailingComments){var y=v.node.trailingComments[0];y&&y.range[0]>=d.end.offset&&(h=v.node.trailingComments,delete v.node.trailingComments)}return h},u.prototype.findLeadingComments=function(d){for(var h,g=[];this.stack.length>0&&(y=this.stack[this.stack.length-1])&&y.start>=d.start.offset;)h=y.node,this.stack.pop();if(h){for(var p=(h.leadingComments?h.leadingComments.length:0)-1;p>=0;--p){var v=h.leadingComments[p];v.range[1]<=d.start.offset&&(g.unshift(v),h.leadingComments.splice(p,1))}return h.leadingComments&&h.leadingComments.length===0&&delete h.leadingComments,g}for(p=this.leading.length-1;p>=0;--p){var y;(y=this.leading[p]).start<=d.start.offset&&(g.unshift(y.comment),this.leading.splice(p,1))}return g},u.prototype.visitNode=function(d,h){if(!(d.type===l.Syntax.Program&&d.body.length>0)){this.insertInnerComments(d,h);var g=this.findTrailingComments(h),p=this.findLeadingComments(h);p.length>0&&(d.leadingComments=p),g.length>0&&(d.trailingComments=g),this.stack.push({node:d,start:h.start.offset})}},u.prototype.visitComment=function(d,h){var g=d.type[0]==="L"?"Line":"Block",p={type:g,value:d.value};if(d.range&&(p.range=d.range),d.loc&&(p.loc=d.loc),this.comments.push(p),this.attach){var v={comment:{type:g,value:d.value,range:[h.start.offset,h.end.offset]},start:h.start.offset};d.loc&&(v.comment.loc=d.loc),d.type=g,this.leading.push(v),this.trailing.push(v)}},u.prototype.visit=function(d,h){d.type==="LineComment"||d.type==="BlockComment"?this.visitComment(d,h):this.attach&&this.visitNode(d,h)},u}();s.CommentHandler=f},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(a,s,c){var l,f=this&&this.__extends||(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,C){x.__proto__=C}||function(x,C){for(var S in C)C.hasOwnProperty(S)&&(x[S]=C[S])},function(x,C){function S(){this.constructor=x}l(x,C),x.prototype=C===null?Object.create(C):(S.prototype=C.prototype,new S)});Object.defineProperty(s,"__esModule",{value:!0});var u=c(4),d=c(5),h=c(6),g=c(7),p=c(8),v=c(13),y=c(14);function m(x){var C;switch(x.type){case h.JSXSyntax.JSXIdentifier:C=x.name;break;case h.JSXSyntax.JSXNamespacedName:var S=x;C=m(S.namespace)+":"+m(S.name);break;case h.JSXSyntax.JSXMemberExpression:var _=x;C=m(_.object)+"."+m(_.property)}return C}v.TokenName[100]="JSXIdentifier",v.TokenName[101]="JSXText";var w=function(x){function C(S,_,T){return x.call(this,S,_,T)||this}return f(C,x),C.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():x.prototype.parsePrimaryExpression.call(this)},C.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.line,this.scanner.lineStart=this.startMarker.index-this.startMarker.column},C.prototype.finishJSX=function(){this.nextToken()},C.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},C.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},C.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},C.prototype.scanXHTMLEntity=function(S){for(var _="&",T=!0,E=!1,D=!1,b=!1;!this.scanner.eof()&&T&&!E;){var I=this.scanner.source[this.scanner.index];if(I===S)break;if(E=I===";",_+=I,++this.scanner.index,!E)switch(_.length){case 2:D=I==="#";break;case 3:D&&(T=(b=I==="x")||u.Character.isDecimalDigit(I.charCodeAt(0)),D=D&&!b);break;default:T=(T=T&&!(D&&!u.Character.isDecimalDigit(I.charCodeAt(0))))&&!(b&&!u.Character.isHexDigit(I.charCodeAt(0)))}}if(T&&E&&_.length>2){var P=_.substr(1,_.length-2);D&&P.length>1?_=String.fromCharCode(parseInt(P.substr(1),10)):b&&P.length>2?_=String.fromCharCode(parseInt("0"+P.substr(1),16)):D||b||!y.XHTMLEntities[P]||(_=y.XHTMLEntities[P])}return _},C.prototype.lexJSX=function(){var S=this.scanner.source.charCodeAt(this.scanner.index);if(S===60||S===62||S===47||S===58||S===61||S===123||S===125)return{type:7,value:I=this.scanner.source[this.scanner.index++],lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index};if(S===34||S===39){for(var _=this.scanner.index,T=this.scanner.source[this.scanner.index++],E="";!this.scanner.eof()&&(P=this.scanner.source[this.scanner.index++])!==T;)E+=P==="&"?this.scanXHTMLEntity(T):P;return{type:8,value:E,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:_,end:this.scanner.index}}if(S===46){var D=this.scanner.source.charCodeAt(this.scanner.index+1),b=this.scanner.source.charCodeAt(this.scanner.index+2),I=D===46&&b===46?"...":".";return _=this.scanner.index,this.scanner.index+=I.length,{type:7,value:I,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:_,end:this.scanner.index}}if(S===96)return{type:10,value:"",lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(u.Character.isIdentifierStart(S)&&S!==92){for(_=this.scanner.index,++this.scanner.index;!this.scanner.eof();){var P=this.scanner.source.charCodeAt(this.scanner.index);if(u.Character.isIdentifierPart(P)&&P!==92)++this.scanner.index;else{if(P!==45)break;++this.scanner.index}}return{type:100,value:this.scanner.source.slice(_,this.scanner.index),lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:_,end:this.scanner.index}}return this.scanner.lex()},C.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;var S=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(S)),S},C.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;for(var S=this.scanner.index,_="";!this.scanner.eof();){var T=this.scanner.source[this.scanner.index];if(T==="{"||T==="<")break;++this.scanner.index,_+=T,u.Character.isLineTerminator(T.charCodeAt(0))&&(++this.scanner.lineNumber,T==="\r"&&this.scanner.source[this.scanner.index]===` -`&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart;var E={type:101,value:_,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:S,end:this.scanner.index};return _.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(E)),E},C.prototype.peekJSXToken=function(){var S=this.scanner.saveState();this.scanner.scanComments();var _=this.lexJSX();return this.scanner.restoreState(S),_},C.prototype.expectJSX=function(S){var _=this.nextJSXToken();_.type===7&&_.value===S||this.throwUnexpectedToken(_)},C.prototype.matchJSX=function(S){var _=this.peekJSXToken();return _.type===7&&_.value===S},C.prototype.parseJSXIdentifier=function(){var S=this.createJSXNode(),_=this.nextJSXToken();return _.type!==100&&this.throwUnexpectedToken(_),this.finalize(S,new d.JSXIdentifier(_.value))},C.prototype.parseJSXElementName=function(){var S=this.createJSXNode(),_=this.parseJSXIdentifier();if(this.matchJSX(":")){var T=_;this.expectJSX(":");var E=this.parseJSXIdentifier();_=this.finalize(S,new d.JSXNamespacedName(T,E))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var D=_;this.expectJSX(".");var b=this.parseJSXIdentifier();_=this.finalize(S,new d.JSXMemberExpression(D,b))}return _},C.prototype.parseJSXAttributeName=function(){var S,_=this.createJSXNode(),T=this.parseJSXIdentifier();if(this.matchJSX(":")){var E=T;this.expectJSX(":");var D=this.parseJSXIdentifier();S=this.finalize(_,new d.JSXNamespacedName(E,D))}else S=T;return S},C.prototype.parseJSXStringLiteralAttribute=function(){var S=this.createJSXNode(),_=this.nextJSXToken();_.type!==8&&this.throwUnexpectedToken(_);var T=this.getTokenRaw(_);return this.finalize(S,new g.Literal(_.value,T))},C.prototype.parseJSXExpressionAttribute=function(){var S=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var _=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(S,new d.JSXExpressionContainer(_))},C.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},C.prototype.parseJSXNameValueAttribute=function(){var S=this.createJSXNode(),_=this.parseJSXAttributeName(),T=null;return this.matchJSX("=")&&(this.expectJSX("="),T=this.parseJSXAttributeValue()),this.finalize(S,new d.JSXAttribute(_,T))},C.prototype.parseJSXSpreadAttribute=function(){var S=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var _=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(S,new d.JSXSpreadAttribute(_))},C.prototype.parseJSXAttributes=function(){for(var S=[];!this.matchJSX("/")&&!this.matchJSX(">");){var _=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();S.push(_)}return S},C.prototype.parseJSXOpeningElement=function(){var S=this.createJSXNode();this.expectJSX("<");var _=this.parseJSXElementName(),T=this.parseJSXAttributes(),E=this.matchJSX("/");return E&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(S,new d.JSXOpeningElement(_,E,T))},C.prototype.parseJSXBoundaryElement=function(){var S=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var _=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(S,new d.JSXClosingElement(_))}var T=this.parseJSXElementName(),E=this.parseJSXAttributes(),D=this.matchJSX("/");return D&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(S,new d.JSXOpeningElement(T,D,E))},C.prototype.parseJSXEmptyExpression=function(){var S=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.finalize(S,new d.JSXEmptyExpression)},C.prototype.parseJSXExpressionContainer=function(){var S,_=this.createJSXNode();return this.expectJSX("{"),this.matchJSX("}")?(S=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),S=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(_,new d.JSXExpressionContainer(S))},C.prototype.parseJSXChildren=function(){for(var S=[];!this.scanner.eof();){var _=this.createJSXChildNode(),T=this.nextJSXText();if(T.start0))break;b=this.finalize(S.node,new d.JSXElement(S.opening,S.children,S.closing)),(S=_[_.length-1]).children.push(b),_.pop()}}return S},C.prototype.parseJSXElement=function(){var S=this.createJSXNode(),_=this.parseJSXOpeningElement(),T=[],E=null;if(!_.selfClosing){var D=this.parseComplexJSXElement({node:S,opening:_,closing:E,children:T});T=D.children,E=D.closing}return this.finalize(S,new d.JSXElement(_,T,E))},C.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var S=this.parseJSXElement();return this.finishJSX(),S},C.prototype.isStartOfExpression=function(){return x.prototype.isStartOfExpression.call(this)||this.match("<")},C}(p.Parser);s.JSXParser=w},function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var c={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};s.Character={fromCodePoint:function(l){return l<65536?String.fromCharCode(l):String.fromCharCode(55296+(l-65536>>10))+String.fromCharCode(56320+(l-65536&1023))},isWhiteSpace:function(l){return l===32||l===9||l===11||l===12||l===160||l>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(l)>=0},isLineTerminator:function(l){return l===10||l===13||l===8232||l===8233},isIdentifierStart:function(l){return l===36||l===95||l>=65&&l<=90||l>=97&&l<=122||l===92||l>=128&&c.NonAsciiIdentifierStart.test(s.Character.fromCodePoint(l))},isIdentifierPart:function(l){return l===36||l===95||l>=65&&l<=90||l>=97&&l<=122||l>=48&&l<=57||l===92||l>=128&&c.NonAsciiIdentifierPart.test(s.Character.fromCodePoint(l))},isDecimalDigit:function(l){return l>=48&&l<=57},isHexDigit:function(l){return l>=48&&l<=57||l>=65&&l<=70||l>=97&&l<=102},isOctalDigit:function(l){return l>=48&&l<=55}}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(6),f=function(C){this.type=l.JSXSyntax.JSXClosingElement,this.name=C};s.JSXClosingElement=f;var u=function(C,S,_){this.type=l.JSXSyntax.JSXElement,this.openingElement=C,this.children=S,this.closingElement=_};s.JSXElement=u;var d=function(){this.type=l.JSXSyntax.JSXEmptyExpression};s.JSXEmptyExpression=d;var h=function(C){this.type=l.JSXSyntax.JSXExpressionContainer,this.expression=C};s.JSXExpressionContainer=h;var g=function(C){this.type=l.JSXSyntax.JSXIdentifier,this.name=C};s.JSXIdentifier=g;var p=function(C,S){this.type=l.JSXSyntax.JSXMemberExpression,this.object=C,this.property=S};s.JSXMemberExpression=p;var v=function(C,S){this.type=l.JSXSyntax.JSXAttribute,this.name=C,this.value=S};s.JSXAttribute=v;var y=function(C,S){this.type=l.JSXSyntax.JSXNamespacedName,this.namespace=C,this.name=S};s.JSXNamespacedName=y;var m=function(C,S,_){this.type=l.JSXSyntax.JSXOpeningElement,this.name=C,this.selfClosing=S,this.attributes=_};s.JSXOpeningElement=m;var w=function(C){this.type=l.JSXSyntax.JSXSpreadAttribute,this.argument=C};s.JSXSpreadAttribute=w;var x=function(C,S){this.type=l.JSXSyntax.JSXText,this.value=C,this.raw=S};s.JSXText=x},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(2),f=function(Be){this.type=l.Syntax.ArrayExpression,this.elements=Be};s.ArrayExpression=f;var u=function(Be){this.type=l.Syntax.ArrayPattern,this.elements=Be};s.ArrayPattern=u;var d=function(Be,ft,Ut){this.type=l.Syntax.ArrowFunctionExpression,this.id=null,this.params=Be,this.body=ft,this.generator=!1,this.expression=Ut,this.async=!1};s.ArrowFunctionExpression=d;var h=function(Be,ft,Ut){this.type=l.Syntax.AssignmentExpression,this.operator=Be,this.left=ft,this.right=Ut};s.AssignmentExpression=h;var g=function(Be,ft){this.type=l.Syntax.AssignmentPattern,this.left=Be,this.right=ft};s.AssignmentPattern=g;var p=function(Be,ft,Ut){this.type=l.Syntax.ArrowFunctionExpression,this.id=null,this.params=Be,this.body=ft,this.generator=!1,this.expression=Ut,this.async=!0};s.AsyncArrowFunctionExpression=p;var v=function(Be,ft,Ut){this.type=l.Syntax.FunctionDeclaration,this.id=Be,this.params=ft,this.body=Ut,this.generator=!1,this.expression=!1,this.async=!0};s.AsyncFunctionDeclaration=v;var y=function(Be,ft,Ut){this.type=l.Syntax.FunctionExpression,this.id=Be,this.params=ft,this.body=Ut,this.generator=!1,this.expression=!1,this.async=!0};s.AsyncFunctionExpression=y;var m=function(Be){this.type=l.Syntax.AwaitExpression,this.argument=Be};s.AwaitExpression=m;var w=function(Be,ft,Ut){var Sn=Be==="||"||Be==="&&";this.type=Sn?l.Syntax.LogicalExpression:l.Syntax.BinaryExpression,this.operator=Be,this.left=ft,this.right=Ut};s.BinaryExpression=w;var x=function(Be){this.type=l.Syntax.BlockStatement,this.body=Be};s.BlockStatement=x;var C=function(Be){this.type=l.Syntax.BreakStatement,this.label=Be};s.BreakStatement=C;var S=function(Be,ft){this.type=l.Syntax.CallExpression,this.callee=Be,this.arguments=ft};s.CallExpression=S;var _=function(Be,ft){this.type=l.Syntax.CatchClause,this.param=Be,this.body=ft};s.CatchClause=_;var T=function(Be){this.type=l.Syntax.ClassBody,this.body=Be};s.ClassBody=T;var E=function(Be,ft,Ut){this.type=l.Syntax.ClassDeclaration,this.id=Be,this.superClass=ft,this.body=Ut};s.ClassDeclaration=E;var D=function(Be,ft,Ut){this.type=l.Syntax.ClassExpression,this.id=Be,this.superClass=ft,this.body=Ut};s.ClassExpression=D;var b=function(Be,ft){this.type=l.Syntax.MemberExpression,this.computed=!0,this.object=Be,this.property=ft};s.ComputedMemberExpression=b;var I=function(Be,ft,Ut){this.type=l.Syntax.ConditionalExpression,this.test=Be,this.consequent=ft,this.alternate=Ut};s.ConditionalExpression=I;var P=function(Be){this.type=l.Syntax.ContinueStatement,this.label=Be};s.ContinueStatement=P;var M=function(){this.type=l.Syntax.DebuggerStatement};s.DebuggerStatement=M;var L=function(Be,ft){this.type=l.Syntax.ExpressionStatement,this.expression=Be,this.directive=ft};s.Directive=L;var V=function(Be,ft){this.type=l.Syntax.DoWhileStatement,this.body=Be,this.test=ft};s.DoWhileStatement=V;var G=function(){this.type=l.Syntax.EmptyStatement};s.EmptyStatement=G;var A=function(Be){this.type=l.Syntax.ExportAllDeclaration,this.source=Be};s.ExportAllDeclaration=A;var k=function(Be){this.type=l.Syntax.ExportDefaultDeclaration,this.declaration=Be};s.ExportDefaultDeclaration=k;var F=function(Be,ft,Ut){this.type=l.Syntax.ExportNamedDeclaration,this.declaration=Be,this.specifiers=ft,this.source=Ut};s.ExportNamedDeclaration=F;var j=function(Be,ft){this.type=l.Syntax.ExportSpecifier,this.exported=ft,this.local=Be};s.ExportSpecifier=j;var Y=function(Be){this.type=l.Syntax.ExpressionStatement,this.expression=Be};s.ExpressionStatement=Y;var re=function(Be,ft,Ut){this.type=l.Syntax.ForInStatement,this.left=Be,this.right=ft,this.body=Ut,this.each=!1};s.ForInStatement=re;var ue=function(Be,ft,Ut){this.type=l.Syntax.ForOfStatement,this.left=Be,this.right=ft,this.body=Ut};s.ForOfStatement=ue;var ce=function(Be,ft,Ut,Sn){this.type=l.Syntax.ForStatement,this.init=Be,this.test=ft,this.update=Ut,this.body=Sn};s.ForStatement=ce;var pe=function(Be,ft,Ut,Sn){this.type=l.Syntax.FunctionDeclaration,this.id=Be,this.params=ft,this.body=Ut,this.generator=Sn,this.expression=!1,this.async=!1};s.FunctionDeclaration=pe;var Ee=function(Be,ft,Ut,Sn){this.type=l.Syntax.FunctionExpression,this.id=Be,this.params=ft,this.body=Ut,this.generator=Sn,this.expression=!1,this.async=!1};s.FunctionExpression=Ee;var Oe=function(Be){this.type=l.Syntax.Identifier,this.name=Be};s.Identifier=Oe;var Se=function(Be,ft,Ut){this.type=l.Syntax.IfStatement,this.test=Be,this.consequent=ft,this.alternate=Ut};s.IfStatement=Se;var B=function(Be,ft){this.type=l.Syntax.ImportDeclaration,this.specifiers=Be,this.source=ft};s.ImportDeclaration=B;var O=function(Be){this.type=l.Syntax.ImportDefaultSpecifier,this.local=Be};s.ImportDefaultSpecifier=O;var z=function(Be){this.type=l.Syntax.ImportNamespaceSpecifier,this.local=Be};s.ImportNamespaceSpecifier=z;var W=function(Be,ft){this.type=l.Syntax.ImportSpecifier,this.local=Be,this.imported=ft};s.ImportSpecifier=W;var K=function(Be,ft){this.type=l.Syntax.LabeledStatement,this.label=Be,this.body=ft};s.LabeledStatement=K;var Z=function(Be,ft){this.type=l.Syntax.Literal,this.value=Be,this.raw=ft};s.Literal=Z;var ee=function(Be,ft){this.type=l.Syntax.MetaProperty,this.meta=Be,this.property=ft};s.MetaProperty=ee;var xe=function(Be,ft,Ut,Sn,Qn){this.type=l.Syntax.MethodDefinition,this.key=Be,this.computed=ft,this.value=Ut,this.kind=Sn,this.static=Qn};s.MethodDefinition=xe;var De=function(Be){this.type=l.Syntax.Program,this.body=Be,this.sourceType="module"};s.Module=De;var Ne=function(Be,ft){this.type=l.Syntax.NewExpression,this.callee=Be,this.arguments=ft};s.NewExpression=Ne;var ze=function(Be){this.type=l.Syntax.ObjectExpression,this.properties=Be};s.ObjectExpression=ze;var ie=function(Be){this.type=l.Syntax.ObjectPattern,this.properties=Be};s.ObjectPattern=ie;var ae=function(Be,ft,Ut,Sn,Qn,Pt){this.type=l.Syntax.Property,this.key=ft,this.computed=Ut,this.value=Sn,this.kind=Be,this.method=Qn,this.shorthand=Pt};s.Property=ae;var we=function(Be,ft,Ut,Sn){this.type=l.Syntax.Literal,this.value=Be,this.raw=ft,this.regex={pattern:Ut,flags:Sn}};s.RegexLiteral=we;var se=function(Be){this.type=l.Syntax.RestElement,this.argument=Be};s.RestElement=se;var ge=function(Be){this.type=l.Syntax.ReturnStatement,this.argument=Be};s.ReturnStatement=ge;var Fe=function(Be){this.type=l.Syntax.Program,this.body=Be,this.sourceType="script"};s.Script=Fe;var oe=function(Be){this.type=l.Syntax.SequenceExpression,this.expressions=Be};s.SequenceExpression=oe;var ht=function(Be){this.type=l.Syntax.SpreadElement,this.argument=Be};s.SpreadElement=ht;var wt=function(Be,ft){this.type=l.Syntax.MemberExpression,this.computed=!1,this.object=Be,this.property=ft};s.StaticMemberExpression=wt;var gt=function(){this.type=l.Syntax.Super};s.Super=gt;var Ie=function(Be,ft){this.type=l.Syntax.SwitchCase,this.test=Be,this.consequent=ft};s.SwitchCase=Ie;var $e=function(Be,ft){this.type=l.Syntax.SwitchStatement,this.discriminant=Be,this.cases=ft};s.SwitchStatement=$e;var tt=function(Be,ft){this.type=l.Syntax.TaggedTemplateExpression,this.tag=Be,this.quasi=ft};s.TaggedTemplateExpression=tt;var nt=function(Be,ft){this.type=l.Syntax.TemplateElement,this.value=Be,this.tail=ft};s.TemplateElement=nt;var dt=function(Be,ft){this.type=l.Syntax.TemplateLiteral,this.quasis=Be,this.expressions=ft};s.TemplateLiteral=dt;var Lt=function(){this.type=l.Syntax.ThisExpression};s.ThisExpression=Lt;var xt=function(Be){this.type=l.Syntax.ThrowStatement,this.argument=Be};s.ThrowStatement=xt;var Ft=function(Be,ft,Ut){this.type=l.Syntax.TryStatement,this.block=Be,this.handler=ft,this.finalizer=Ut};s.TryStatement=Ft;var jt=function(Be,ft){this.type=l.Syntax.UnaryExpression,this.operator=Be,this.argument=ft,this.prefix=!0};s.UnaryExpression=jt;var Pn=function(Be,ft,Ut){this.type=l.Syntax.UpdateExpression,this.operator=Be,this.argument=ft,this.prefix=Ut};s.UpdateExpression=Pn;var $n=function(Be,ft){this.type=l.Syntax.VariableDeclaration,this.declarations=Be,this.kind=ft};s.VariableDeclaration=$n;var fn=function(Be,ft){this.type=l.Syntax.VariableDeclarator,this.id=Be,this.init=ft};s.VariableDeclarator=fn;var bn=function(Be,ft){this.type=l.Syntax.WhileStatement,this.test=Be,this.body=ft};s.WhileStatement=bn;var Xi=function(Be,ft){this.type=l.Syntax.WithStatement,this.object=Be,this.body=ft};s.WithStatement=Xi;var Mr=function(Be,ft){this.type=l.Syntax.YieldExpression,this.argument=Be,this.delegate=ft};s.YieldExpression=Mr},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(9),f=c(10),u=c(11),d=c(7),h=c(12),g=c(2),p=c(13),v=function(){function y(m,w,x){w===void 0&&(w={}),this.config={range:typeof w.range=="boolean"&&w.range,loc:typeof w.loc=="boolean"&&w.loc,source:null,tokens:typeof w.tokens=="boolean"&&w.tokens,comment:typeof w.comment=="boolean"&&w.comment,tolerant:typeof w.tolerant=="boolean"&&w.tolerant},this.config.loc&&w.source&&w.source!==null&&(this.config.source=String(w.source)),this.delegate=x,this.errorHandler=new f.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new h.Scanner(m,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.lookahead={type:2,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.hasLineTerminator=!1,this.context={isModule:!1,await:!1,allowIn:!0,allowStrictDirective:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:!1},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.lastMarker={index:0,line:this.scanner.lineNumber,column:0},this.nextToken(),this.lastMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}return y.prototype.throwError=function(m){for(var w=[],x=1;x0&&this.delegate)for(var w=0;w>="||m===">>>="||m==="&="||m==="^="||m==="|="},y.prototype.isolateCoverGrammar=function(m){var w=this.context.isBindingElement,x=this.context.isAssignmentTarget,C=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var S=m.call(this);return this.context.firstCoverInitializedNameError!==null&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=w,this.context.isAssignmentTarget=x,this.context.firstCoverInitializedNameError=C,S},y.prototype.inheritCoverGrammar=function(m){var w=this.context.isBindingElement,x=this.context.isAssignmentTarget,C=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var S=m.call(this);return this.context.isBindingElement=this.context.isBindingElement&&w,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&x,this.context.firstCoverInitializedNameError=C||this.context.firstCoverInitializedNameError,S},y.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(this.lookahead.type===2||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.line=this.startMarker.line,this.lastMarker.column=this.startMarker.column)},y.prototype.parsePrimaryExpression=function(){var m,w,x,C=this.createNode();switch(this.lookahead.type){case 3:(this.context.isModule||this.context.await)&&this.lookahead.value==="await"&&this.tolerateUnexpectedToken(this.lookahead),m=this.matchAsyncFunction()?this.parseFunctionExpression():this.finalize(C,new d.Identifier(this.nextToken().value));break;case 6:case 8:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,u.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(w.value,x));break;case 1:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(w.value==="true",x));break;case 5:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(null,x));break;case 10:m=this.parseTemplateLiteral();break;case 7:switch(this.lookahead.value){case"(":this.context.isBindingElement=!1,m=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":m=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":m=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,w=this.nextRegexToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.RegexLiteral(w.regex,x,w.pattern,w.flags));break;default:m=this.throwUnexpectedToken(this.nextToken())}break;case 4:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?m=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?m=this.finalize(C,new d.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?m=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),m=this.finalize(C,new d.ThisExpression)):m=this.matchKeyword("class")?this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:m=this.throwUnexpectedToken(this.nextToken())}return m},y.prototype.parseSpreadElement=function(){var m=this.createNode();this.expect("...");var w=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(m,new d.SpreadElement(w))},y.prototype.parseArrayInitializer=function(){var m=this.createNode(),w=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),w.push(null);else if(this.match("...")){var x=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),w.push(x)}else w.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(m,new d.ArrayExpression(w))},y.prototype.parsePropertyMethod=function(m){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var w=this.context.strict,x=this.context.allowStrictDirective;this.context.allowStrictDirective=m.simple;var C=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&m.firstRestricted&&this.tolerateUnexpectedToken(m.firstRestricted,m.message),this.context.strict&&m.stricted&&this.tolerateUnexpectedToken(m.stricted,m.message),this.context.strict=w,this.context.allowStrictDirective=x,C},y.prototype.parsePropertyMethodFunction=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters(),C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parsePropertyMethodAsyncFunction=function(){var m=this.createNode(),w=this.context.allowYield,x=this.context.await;this.context.allowYield=!1,this.context.await=!0;var C=this.parseFormalParameters(),S=this.parsePropertyMethod(C);return this.context.allowYield=w,this.context.await=x,this.finalize(m,new d.AsyncFunctionExpression(null,C.params,S))},y.prototype.parseObjectPropertyKey=function(){var m,w=this.createNode(),x=this.nextToken();switch(x.type){case 8:case 6:this.context.strict&&x.octal&&this.tolerateUnexpectedToken(x,u.Messages.StrictOctalLiteral);var C=this.getTokenRaw(x);m=this.finalize(w,new d.Literal(x.value,C));break;case 3:case 1:case 5:case 4:m=this.finalize(w,new d.Identifier(x.value));break;case 7:x.value==="["?(m=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):m=this.throwUnexpectedToken(x);break;default:m=this.throwUnexpectedToken(x)}return m},y.prototype.isPropertyKey=function(m,w){return m.type===g.Syntax.Identifier&&m.name===w||m.type===g.Syntax.Literal&&m.value===w},y.prototype.parseObjectProperty=function(m){var w,x=this.createNode(),C=this.lookahead,S=null,_=null,T=!1,E=!1,D=!1,b=!1;if(C.type===3){var I=C.value;this.nextToken(),T=this.match("["),S=(b=!(this.hasLineTerminator||I!=="async"||this.match(":")||this.match("(")||this.match("*")||this.match(",")))?this.parseObjectPropertyKey():this.finalize(x,new d.Identifier(I))}else this.match("*")?this.nextToken():(T=this.match("["),S=this.parseObjectPropertyKey());var P=this.qualifiedPropertyName(this.lookahead);if(C.type===3&&!b&&C.value==="get"&&P)w="get",T=this.match("["),S=this.parseObjectPropertyKey(),this.context.allowYield=!1,_=this.parseGetterMethod();else if(C.type===3&&!b&&C.value==="set"&&P)w="set",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseSetterMethod();else if(C.type===7&&C.value==="*"&&P)w="init",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseGeneratorMethod(),E=!0;else if(S||this.throwUnexpectedToken(this.lookahead),w="init",this.match(":")&&!b)!T&&this.isPropertyKey(S,"__proto__")&&(m.value&&this.tolerateError(u.Messages.DuplicateProtoProperty),m.value=!0),this.nextToken(),_=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))_=b?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),E=!0;else if(C.type===3)if(I=this.finalize(x,new d.Identifier(C.value)),this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),D=!0;var M=this.isolateCoverGrammar(this.parseAssignmentExpression);_=this.finalize(x,new d.AssignmentPattern(I,M))}else D=!0,_=I;else this.throwUnexpectedToken(this.nextToken());return this.finalize(x,new d.Property(w,S,T,_,E,D))},y.prototype.parseObjectInitializer=function(){var m=this.createNode();this.expect("{");for(var w=[],x={value:!1};!this.match("}");)w.push(this.parseObjectProperty(x)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(m,new d.ObjectExpression(w))},y.prototype.parseTemplateHead=function(){l.assert(this.lookahead.head,"Template literal must start with a template head");var m=this.createNode(),w=this.nextToken(),x=w.value,C=w.cooked;return this.finalize(m,new d.TemplateElement({raw:x,cooked:C},w.tail))},y.prototype.parseTemplateElement=function(){this.lookahead.type!==10&&this.throwUnexpectedToken();var m=this.createNode(),w=this.nextToken(),x=w.value,C=w.cooked;return this.finalize(m,new d.TemplateElement({raw:x,cooked:C},w.tail))},y.prototype.parseTemplateLiteral=function(){var m=this.createNode(),w=[],x=[],C=this.parseTemplateHead();for(x.push(C);!C.tail;)w.push(this.parseExpression()),C=this.parseTemplateElement(),x.push(C);return this.finalize(m,new d.TemplateLiteral(x,w))},y.prototype.reinterpretExpressionAsPattern=function(m){switch(m.type){case g.Syntax.Identifier:case g.Syntax.MemberExpression:case g.Syntax.RestElement:case g.Syntax.AssignmentPattern:break;case g.Syntax.SpreadElement:m.type=g.Syntax.RestElement,this.reinterpretExpressionAsPattern(m.argument);break;case g.Syntax.ArrayExpression:m.type=g.Syntax.ArrayPattern;for(var w=0;w")||this.expect("=>"),m={type:"ArrowParameterPlaceHolder",params:[],async:!1};else{var w=this.lookahead,x=[];if(this.match("..."))m=this.parseRestElement(x),this.expect(")"),this.match("=>")||this.expect("=>"),m={type:"ArrowParameterPlaceHolder",params:[m],async:!1};else{var C=!1;if(this.context.isBindingElement=!0,m=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var S=[];for(this.context.isAssignmentTarget=!1,S.push(m);this.lookahead.type!==2&&this.match(",");){if(this.nextToken(),this.match(")")){this.nextToken();for(var _=0;_")||this.expect("=>"),this.context.isBindingElement=!1,_=0;_")&&(m.type===g.Syntax.Identifier&&m.name==="yield"&&(C=!0,m={type:"ArrowParameterPlaceHolder",params:[m],async:!1}),!C)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),m.type===g.Syntax.SequenceExpression)for(_=0;_")){for(var E=0;E0){this.nextToken(),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var S=[m,this.lookahead],_=w,T=this.isolateCoverGrammar(this.parseExponentiationExpression),E=[_,x.value,T],D=[C];!((C=this.binaryPrecedence(this.lookahead))<=0);){for(;E.length>2&&C<=D[D.length-1];){T=E.pop();var b=E.pop();D.pop(),_=E.pop(),S.pop();var I=this.startNode(S[S.length-1]);E.push(this.finalize(I,new d.BinaryExpression(b,_,T)))}E.push(this.nextToken().value),D.push(C),S.push(this.lookahead),E.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var P=E.length-1;w=E[P];for(var M=S.pop();P>1;){var L=S.pop(),V=M&&M.lineStart;I=this.startNode(L,V),b=E[P-1],w=this.finalize(I,new d.BinaryExpression(b,E[P-2],w)),P-=2,M=L}}return w},y.prototype.parseConditionalExpression=function(){var m=this.lookahead,w=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var x=this.context.allowIn;this.context.allowIn=!0;var C=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=x,this.expect(":");var S=this.isolateCoverGrammar(this.parseAssignmentExpression);w=this.finalize(this.startNode(m),new d.ConditionalExpression(w,C,S)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return w},y.prototype.checkPatternParam=function(m,w){switch(w.type){case g.Syntax.Identifier:this.validateParam(m,w,w.name);break;case g.Syntax.RestElement:this.checkPatternParam(m,w.argument);break;case g.Syntax.AssignmentPattern:this.checkPatternParam(m,w.left);break;case g.Syntax.ArrayPattern:for(var x=0;x")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var S=m.async,_=this.reinterpretAsCoverFormalsList(m);if(_){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var T=this.context.strict,E=this.context.allowStrictDirective;this.context.allowStrictDirective=_.simple;var D=this.context.allowYield,b=this.context.await;this.context.allowYield=!0,this.context.await=S;var I=this.startNode(w);this.expect("=>");var P=void 0;if(this.match("{")){var M=this.context.allowIn;this.context.allowIn=!0,P=this.parseFunctionSourceElements(),this.context.allowIn=M}else P=this.isolateCoverGrammar(this.parseAssignmentExpression);var L=P.type!==g.Syntax.BlockStatement;this.context.strict&&_.firstRestricted&&this.throwUnexpectedToken(_.firstRestricted,_.message),this.context.strict&&_.stricted&&this.tolerateUnexpectedToken(_.stricted,_.message),m=S?this.finalize(I,new d.AsyncArrowFunctionExpression(_.params,P,L)):this.finalize(I,new d.ArrowFunctionExpression(_.params,P,L)),this.context.strict=T,this.context.allowStrictDirective=E,this.context.allowYield=D,this.context.await=b}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(u.Messages.InvalidLHSInAssignment),this.context.strict&&m.type===g.Syntax.Identifier){var V=m;this.scanner.isRestrictedWord(V.name)&&this.tolerateUnexpectedToken(x,u.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(V.name)&&this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(m):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1);var G=(x=this.nextToken()).value,A=this.isolateCoverGrammar(this.parseAssignmentExpression);m=this.finalize(this.startNode(w),new d.AssignmentExpression(G,m,A)),this.context.firstCoverInitializedNameError=null}}return m},y.prototype.parseExpression=function(){var m=this.lookahead,w=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var x=[];for(x.push(w);this.lookahead.type!==2&&this.match(",");)this.nextToken(),x.push(this.isolateCoverGrammar(this.parseAssignmentExpression));w=this.finalize(this.startNode(m),new d.SequenceExpression(x))}return w},y.prototype.parseStatementListItem=function(){var m;if(this.context.isAssignmentTarget=!0,this.context.isBindingElement=!0,this.lookahead.type===4)switch(this.lookahead.value){case"export":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,u.Messages.IllegalExportDeclaration),m=this.parseExportDeclaration();break;case"import":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,u.Messages.IllegalImportDeclaration),m=this.parseImportDeclaration();break;case"const":m=this.parseLexicalDeclaration({inFor:!1});break;case"function":m=this.parseFunctionDeclaration();break;case"class":m=this.parseClassDeclaration();break;case"let":m=this.isLexicalDeclaration()?this.parseLexicalDeclaration({inFor:!1}):this.parseStatement();break;default:m=this.parseStatement()}else m=this.parseStatement();return m},y.prototype.parseBlock=function(){var m=this.createNode();this.expect("{");for(var w=[];!this.match("}");)w.push(this.parseStatementListItem());return this.expect("}"),this.finalize(m,new d.BlockStatement(w))},y.prototype.parseLexicalBinding=function(m,w){var x=this.createNode(),C=this.parsePattern([],m);this.context.strict&&C.type===g.Syntax.Identifier&&this.scanner.isRestrictedWord(C.name)&&this.tolerateError(u.Messages.StrictVarName);var S=null;return m==="const"?this.matchKeyword("in")||this.matchContextualKeyword("of")||(this.match("=")?(this.nextToken(),S=this.isolateCoverGrammar(this.parseAssignmentExpression)):this.throwError(u.Messages.DeclarationMissingInitializer,"const")):(!w.inFor&&C.type!==g.Syntax.Identifier||this.match("="))&&(this.expect("="),S=this.isolateCoverGrammar(this.parseAssignmentExpression)),this.finalize(x,new d.VariableDeclarator(C,S))},y.prototype.parseBindingList=function(m,w){for(var x=[this.parseLexicalBinding(m,w)];this.match(",");)this.nextToken(),x.push(this.parseLexicalBinding(m,w));return x},y.prototype.isLexicalDeclaration=function(){var m=this.scanner.saveState();this.scanner.scanComments();var w=this.scanner.lex();return this.scanner.restoreState(m),w.type===3||w.type===7&&w.value==="["||w.type===7&&w.value==="{"||w.type===4&&w.value==="let"||w.type===4&&w.value==="yield"},y.prototype.parseLexicalDeclaration=function(m){var w=this.createNode(),x=this.nextToken().value;l.assert(x==="let"||x==="const","Lexical declaration must be either let or const");var C=this.parseBindingList(x,m);return this.consumeSemicolon(),this.finalize(w,new d.VariableDeclaration(C,x))},y.prototype.parseBindingRestElement=function(m,w){var x=this.createNode();this.expect("...");var C=this.parsePattern(m,w);return this.finalize(x,new d.RestElement(C))},y.prototype.parseArrayPattern=function(m,w){var x=this.createNode();this.expect("[");for(var C=[];!this.match("]");)if(this.match(","))this.nextToken(),C.push(null);else{if(this.match("...")){C.push(this.parseBindingRestElement(m,w));break}C.push(this.parsePatternWithDefault(m,w)),this.match("]")||this.expect(",")}return this.expect("]"),this.finalize(x,new d.ArrayPattern(C))},y.prototype.parsePropertyPattern=function(m,w){var x,C,S=this.createNode(),_=!1,T=!1;if(this.lookahead.type===3){var E=this.lookahead;x=this.parseVariableIdentifier();var D=this.finalize(S,new d.Identifier(E.value));if(this.match("=")){m.push(E),T=!0,this.nextToken();var b=this.parseAssignmentExpression();C=this.finalize(this.startNode(E),new d.AssignmentPattern(D,b))}else this.match(":")?(this.expect(":"),C=this.parsePatternWithDefault(m,w)):(m.push(E),T=!0,C=D)}else _=this.match("["),x=this.parseObjectPropertyKey(),this.expect(":"),C=this.parsePatternWithDefault(m,w);return this.finalize(S,new d.Property("init",x,_,C,!1,T))},y.prototype.parseObjectPattern=function(m,w){var x=this.createNode(),C=[];for(this.expect("{");!this.match("}");)C.push(this.parsePropertyPattern(m,w)),this.match("}")||this.expect(",");return this.expect("}"),this.finalize(x,new d.ObjectPattern(C))},y.prototype.parsePattern=function(m,w){var x;return this.match("[")?x=this.parseArrayPattern(m,w):this.match("{")?x=this.parseObjectPattern(m,w):(!this.matchKeyword("let")||w!=="const"&&w!=="let"||this.tolerateUnexpectedToken(this.lookahead,u.Messages.LetInLexicalBinding),m.push(this.lookahead),x=this.parseVariableIdentifier(w)),x},y.prototype.parsePatternWithDefault=function(m,w){var x=this.lookahead,C=this.parsePattern(m,w);if(this.match("=")){this.nextToken();var S=this.context.allowYield;this.context.allowYield=!0;var _=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowYield=S,C=this.finalize(this.startNode(x),new d.AssignmentPattern(C,_))}return C},y.prototype.parseVariableIdentifier=function(m){var w=this.createNode(),x=this.nextToken();return x.type===4&&x.value==="yield"?this.context.strict?this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord):this.context.allowYield||this.throwUnexpectedToken(x):x.type!==3?this.context.strict&&x.type===4&&this.scanner.isStrictModeReservedWord(x.value)?this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord):(this.context.strict||x.value!=="let"||m!=="var")&&this.throwUnexpectedToken(x):(this.context.isModule||this.context.await)&&x.type===3&&x.value==="await"&&this.tolerateUnexpectedToken(x),this.finalize(w,new d.Identifier(x.value))},y.prototype.parseVariableDeclaration=function(m){var w=this.createNode(),x=this.parsePattern([],"var");this.context.strict&&x.type===g.Syntax.Identifier&&this.scanner.isRestrictedWord(x.name)&&this.tolerateError(u.Messages.StrictVarName);var C=null;return this.match("=")?(this.nextToken(),C=this.isolateCoverGrammar(this.parseAssignmentExpression)):x.type===g.Syntax.Identifier||m.inFor||this.expect("="),this.finalize(w,new d.VariableDeclarator(x,C))},y.prototype.parseVariableDeclarationList=function(m){var w={inFor:m.inFor},x=[];for(x.push(this.parseVariableDeclaration(w));this.match(",");)this.nextToken(),x.push(this.parseVariableDeclaration(w));return x},y.prototype.parseVariableStatement=function(){var m=this.createNode();this.expectKeyword("var");var w=this.parseVariableDeclarationList({inFor:!1});return this.consumeSemicolon(),this.finalize(m,new d.VariableDeclaration(w,"var"))},y.prototype.parseEmptyStatement=function(){var m=this.createNode();return this.expect(";"),this.finalize(m,new d.EmptyStatement)},y.prototype.parseExpressionStatement=function(){var m=this.createNode(),w=this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ExpressionStatement(w))},y.prototype.parseIfClause=function(){return this.context.strict&&this.matchKeyword("function")&&this.tolerateError(u.Messages.StrictFunction),this.parseStatement()},y.prototype.parseIfStatement=function(){var m,w=this.createNode(),x=null;this.expectKeyword("if"),this.expect("(");var C=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement)):(this.expect(")"),m=this.parseIfClause(),this.matchKeyword("else")&&(this.nextToken(),x=this.parseIfClause())),this.finalize(w,new d.IfStatement(C,m,x))},y.prototype.parseDoWhileStatement=function(){var m=this.createNode();this.expectKeyword("do");var w=this.context.inIteration;this.context.inIteration=!0;var x=this.parseStatement();this.context.inIteration=w,this.expectKeyword("while"),this.expect("(");var C=this.parseExpression();return!this.match(")")&&this.config.tolerant?this.tolerateUnexpectedToken(this.nextToken()):(this.expect(")"),this.match(";")&&this.nextToken()),this.finalize(m,new d.DoWhileStatement(x,C))},y.prototype.parseWhileStatement=function(){var m,w=this.createNode();this.expectKeyword("while"),this.expect("(");var x=this.parseExpression();if(!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement);else{this.expect(")");var C=this.context.inIteration;this.context.inIteration=!0,m=this.parseStatement(),this.context.inIteration=C}return this.finalize(w,new d.WhileStatement(x,m))},y.prototype.parseForStatement=function(){var m,w,x,C=null,S=null,_=null,T=!0,E=this.createNode();if(this.expectKeyword("for"),this.expect("("),this.match(";"))this.nextToken();else if(this.matchKeyword("var")){C=this.createNode(),this.nextToken();var D=this.context.allowIn;this.context.allowIn=!1;var b=this.parseVariableDeclarationList({inFor:!0});if(this.context.allowIn=D,b.length===1&&this.matchKeyword("in")){var I=b[0];I.init&&(I.id.type===g.Syntax.ArrayPattern||I.id.type===g.Syntax.ObjectPattern||this.context.strict)&&this.tolerateError(u.Messages.ForInOfLoopInitializer,"for-in"),C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.nextToken(),m=C,w=this.parseExpression(),C=null}else b.length===1&&b[0].init===null&&this.matchContextualKeyword("of")?(C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.nextToken(),m=C,w=this.parseAssignmentExpression(),C=null,T=!1):(C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.expect(";"))}else if(this.matchKeyword("const")||this.matchKeyword("let")){C=this.createNode();var P=this.nextToken().value;this.context.strict||this.lookahead.value!=="in"?(D=this.context.allowIn,this.context.allowIn=!1,b=this.parseBindingList(P,{inFor:!0}),this.context.allowIn=D,b.length===1&&b[0].init===null&&this.matchKeyword("in")?(C=this.finalize(C,new d.VariableDeclaration(b,P)),this.nextToken(),m=C,w=this.parseExpression(),C=null):b.length===1&&b[0].init===null&&this.matchContextualKeyword("of")?(C=this.finalize(C,new d.VariableDeclaration(b,P)),this.nextToken(),m=C,w=this.parseAssignmentExpression(),C=null,T=!1):(this.consumeSemicolon(),C=this.finalize(C,new d.VariableDeclaration(b,P)))):(C=this.finalize(C,new d.Identifier(P)),this.nextToken(),m=C,w=this.parseExpression(),C=null)}else{var M=this.lookahead;if(D=this.context.allowIn,this.context.allowIn=!1,C=this.inheritCoverGrammar(this.parseAssignmentExpression),this.context.allowIn=D,this.matchKeyword("in"))this.context.isAssignmentTarget&&C.type!==g.Syntax.AssignmentExpression||this.tolerateError(u.Messages.InvalidLHSInForIn),this.nextToken(),this.reinterpretExpressionAsPattern(C),m=C,w=this.parseExpression(),C=null;else if(this.matchContextualKeyword("of"))this.context.isAssignmentTarget&&C.type!==g.Syntax.AssignmentExpression||this.tolerateError(u.Messages.InvalidLHSInForLoop),this.nextToken(),this.reinterpretExpressionAsPattern(C),m=C,w=this.parseAssignmentExpression(),C=null,T=!1;else{if(this.match(",")){for(var L=[C];this.match(",");)this.nextToken(),L.push(this.isolateCoverGrammar(this.parseAssignmentExpression));C=this.finalize(this.startNode(M),new d.SequenceExpression(L))}this.expect(";")}}if(m===void 0&&(this.match(";")||(S=this.parseExpression()),this.expect(";"),this.match(")")||(_=this.parseExpression())),!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),x=this.finalize(this.createNode(),new d.EmptyStatement);else{this.expect(")");var V=this.context.inIteration;this.context.inIteration=!0,x=this.isolateCoverGrammar(this.parseStatement),this.context.inIteration=V}return m===void 0?this.finalize(E,new d.ForStatement(C,S,_,x)):T?this.finalize(E,new d.ForInStatement(m,w,x)):this.finalize(E,new d.ForOfStatement(m,w,x))},y.prototype.parseContinueStatement=function(){var m=this.createNode();this.expectKeyword("continue");var w=null;if(this.lookahead.type===3&&!this.hasLineTerminator){var x=this.parseVariableIdentifier();w=x;var C="$"+x.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,C)||this.throwError(u.Messages.UnknownLabel,x.name)}return this.consumeSemicolon(),w!==null||this.context.inIteration||this.throwError(u.Messages.IllegalContinue),this.finalize(m,new d.ContinueStatement(w))},y.prototype.parseBreakStatement=function(){var m=this.createNode();this.expectKeyword("break");var w=null;if(this.lookahead.type===3&&!this.hasLineTerminator){var x=this.parseVariableIdentifier(),C="$"+x.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,C)||this.throwError(u.Messages.UnknownLabel,x.name),w=x}return this.consumeSemicolon(),w!==null||this.context.inIteration||this.context.inSwitch||this.throwError(u.Messages.IllegalBreak),this.finalize(m,new d.BreakStatement(w))},y.prototype.parseReturnStatement=function(){this.context.inFunctionBody||this.tolerateError(u.Messages.IllegalReturn);var m=this.createNode();this.expectKeyword("return");var w=(this.match(";")||this.match("}")||this.hasLineTerminator||this.lookahead.type===2)&&this.lookahead.type!==8&&this.lookahead.type!==10?null:this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ReturnStatement(w))},y.prototype.parseWithStatement=function(){this.context.strict&&this.tolerateError(u.Messages.StrictModeWith);var m,w=this.createNode();this.expectKeyword("with"),this.expect("(");var x=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement)):(this.expect(")"),m=this.parseStatement()),this.finalize(w,new d.WithStatement(x,m))},y.prototype.parseSwitchCase=function(){var m,w=this.createNode();this.matchKeyword("default")?(this.nextToken(),m=null):(this.expectKeyword("case"),m=this.parseExpression()),this.expect(":");for(var x=[];!(this.match("}")||this.matchKeyword("default")||this.matchKeyword("case"));)x.push(this.parseStatementListItem());return this.finalize(w,new d.SwitchCase(m,x))},y.prototype.parseSwitchStatement=function(){var m=this.createNode();this.expectKeyword("switch"),this.expect("(");var w=this.parseExpression();this.expect(")");var x=this.context.inSwitch;this.context.inSwitch=!0;var C=[],S=!1;for(this.expect("{");!this.match("}");){var _=this.parseSwitchCase();_.test===null&&(S&&this.throwError(u.Messages.MultipleDefaultsInSwitch),S=!0),C.push(_)}return this.expect("}"),this.context.inSwitch=x,this.finalize(m,new d.SwitchStatement(w,C))},y.prototype.parseLabelledStatement=function(){var m,w=this.createNode(),x=this.parseExpression();if(x.type===g.Syntax.Identifier&&this.match(":")){this.nextToken();var C=x,S="$"+C.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,S)&&this.throwError(u.Messages.Redeclaration,"Label",C.name),this.context.labelSet[S]=!0;var _=void 0;if(this.matchKeyword("class"))this.tolerateUnexpectedToken(this.lookahead),_=this.parseClassDeclaration();else if(this.matchKeyword("function")){var T=this.lookahead,E=this.parseFunctionDeclaration();this.context.strict?this.tolerateUnexpectedToken(T,u.Messages.StrictFunction):E.generator&&this.tolerateUnexpectedToken(T,u.Messages.GeneratorInLegacyContext),_=E}else _=this.parseStatement();delete this.context.labelSet[S],m=new d.LabeledStatement(C,_)}else this.consumeSemicolon(),m=new d.ExpressionStatement(x);return this.finalize(w,m)},y.prototype.parseThrowStatement=function(){var m=this.createNode();this.expectKeyword("throw"),this.hasLineTerminator&&this.throwError(u.Messages.NewlineAfterThrow);var w=this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ThrowStatement(w))},y.prototype.parseCatchClause=function(){var m=this.createNode();this.expectKeyword("catch"),this.expect("("),this.match(")")&&this.throwUnexpectedToken(this.lookahead);for(var w=[],x=this.parsePattern(w),C={},S=0;S0&&this.tolerateError(u.Messages.BadGetterArity);var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parseSetterMethod=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters();x.params.length!==1?this.tolerateError(u.Messages.BadSetterArity):x.params[0]instanceof d.RestElement&&this.tolerateError(u.Messages.BadSetterRestParameter);var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parseGeneratorMethod=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters();this.context.allowYield=!1;var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!0))},y.prototype.isStartOfExpression=function(){var m=!0,w=this.lookahead.value;switch(this.lookahead.type){case 7:m=w==="["||w==="("||w==="{"||w==="+"||w==="-"||w==="!"||w==="~"||w==="++"||w==="--"||w==="/"||w==="/=";break;case 4:m=w==="class"||w==="delete"||w==="function"||w==="let"||w==="new"||w==="super"||w==="this"||w==="typeof"||w==="void"||w==="yield"}return m},y.prototype.parseYieldExpression=function(){var m=this.createNode();this.expectKeyword("yield");var w=null,x=!1;if(!this.hasLineTerminator){var C=this.context.allowYield;this.context.allowYield=!1,(x=this.match("*"))?(this.nextToken(),w=this.parseAssignmentExpression()):this.isStartOfExpression()&&(w=this.parseAssignmentExpression()),this.context.allowYield=C}return this.finalize(m,new d.YieldExpression(w,x))},y.prototype.parseClassElement=function(m){var w=this.lookahead,x=this.createNode(),C="",S=null,_=null,T=!1,E=!1,D=!1,b=!1;if(this.match("*"))this.nextToken();else if(T=this.match("["),(S=this.parseObjectPropertyKey()).name==="static"&&(this.qualifiedPropertyName(this.lookahead)||this.match("*"))&&(w=this.lookahead,D=!0,T=this.match("["),this.match("*")?this.nextToken():S=this.parseObjectPropertyKey()),w.type===3&&!this.hasLineTerminator&&w.value==="async"){var I=this.lookahead.value;I!==":"&&I!=="("&&I!=="*"&&(b=!0,w=this.lookahead,S=this.parseObjectPropertyKey(),w.type===3&&w.value==="constructor"&&this.tolerateUnexpectedToken(w,u.Messages.ConstructorIsAsync))}var P=this.qualifiedPropertyName(this.lookahead);return w.type===3?w.value==="get"&&P?(C="get",T=this.match("["),S=this.parseObjectPropertyKey(),this.context.allowYield=!1,_=this.parseGetterMethod()):w.value==="set"&&P&&(C="set",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseSetterMethod()):w.type===7&&w.value==="*"&&P&&(C="init",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseGeneratorMethod(),E=!0),!C&&S&&this.match("(")&&(C="init",_=b?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),E=!0),C||this.throwUnexpectedToken(this.lookahead),C==="init"&&(C="method"),T||(D&&this.isPropertyKey(S,"prototype")&&this.throwUnexpectedToken(w,u.Messages.StaticPrototype),!D&&this.isPropertyKey(S,"constructor")&&((C!=="method"||!E||_&&_.generator)&&this.throwUnexpectedToken(w,u.Messages.ConstructorSpecialMethod),m.value?this.throwUnexpectedToken(w,u.Messages.DuplicateConstructor):m.value=!0,C="constructor")),this.finalize(x,new d.MethodDefinition(S,T,_,C,D))},y.prototype.parseClassElementList=function(){var m=[],w={value:!1};for(this.expect("{");!this.match("}");)this.match(";")?this.nextToken():m.push(this.parseClassElement(w));return this.expect("}"),m},y.prototype.parseClassBody=function(){var m=this.createNode(),w=this.parseClassElementList();return this.finalize(m,new d.ClassBody(w))},y.prototype.parseClassDeclaration=function(m){var w=this.createNode(),x=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var C=m&&this.lookahead.type!==3?null:this.parseVariableIdentifier(),S=null;this.matchKeyword("extends")&&(this.nextToken(),S=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var _=this.parseClassBody();return this.context.strict=x,this.finalize(w,new d.ClassDeclaration(C,S,_))},y.prototype.parseClassExpression=function(){var m=this.createNode(),w=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var x=this.lookahead.type===3?this.parseVariableIdentifier():null,C=null;this.matchKeyword("extends")&&(this.nextToken(),C=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var S=this.parseClassBody();return this.context.strict=w,this.finalize(m,new d.ClassExpression(x,C,S))},y.prototype.parseModule=function(){this.context.strict=!0,this.context.isModule=!0,this.scanner.isModule=!0;for(var m=this.createNode(),w=this.parseDirectivePrologues();this.lookahead.type!==2;)w.push(this.parseStatementListItem());return this.finalize(m,new d.Module(w))},y.prototype.parseScript=function(){for(var m=this.createNode(),w=this.parseDirectivePrologues();this.lookahead.type!==2;)w.push(this.parseStatementListItem());return this.finalize(m,new d.Script(w))},y.prototype.parseModuleSpecifier=function(){var m=this.createNode();this.lookahead.type!==8&&this.throwError(u.Messages.InvalidModuleSpecifier);var w=this.nextToken(),x=this.getTokenRaw(w);return this.finalize(m,new d.Literal(w.value,x))},y.prototype.parseImportSpecifier=function(){var m,w,x=this.createNode();return this.lookahead.type===3?(w=m=this.parseVariableIdentifier(),this.matchContextualKeyword("as")&&(this.nextToken(),w=this.parseVariableIdentifier())):(w=m=this.parseIdentifierName(),this.matchContextualKeyword("as")?(this.nextToken(),w=this.parseVariableIdentifier()):this.throwUnexpectedToken(this.nextToken())),this.finalize(x,new d.ImportSpecifier(w,m))},y.prototype.parseNamedImports=function(){this.expect("{");for(var m=[];!this.match("}");)m.push(this.parseImportSpecifier()),this.match("}")||this.expect(",");return this.expect("}"),m},y.prototype.parseImportDefaultSpecifier=function(){var m=this.createNode(),w=this.parseIdentifierName();return this.finalize(m,new d.ImportDefaultSpecifier(w))},y.prototype.parseImportNamespaceSpecifier=function(){var m=this.createNode();this.expect("*"),this.matchContextualKeyword("as")||this.throwError(u.Messages.NoAsAfterImportNamespace),this.nextToken();var w=this.parseIdentifierName();return this.finalize(m,new d.ImportNamespaceSpecifier(w))},y.prototype.parseImportDeclaration=function(){this.context.inFunctionBody&&this.throwError(u.Messages.IllegalImportDeclaration);var m,w=this.createNode();this.expectKeyword("import");var x=[];if(this.lookahead.type===8)m=this.parseModuleSpecifier();else{if(this.match("{")?x=x.concat(this.parseNamedImports()):this.match("*")?x.push(this.parseImportNamespaceSpecifier()):this.isIdentifierName(this.lookahead)&&!this.matchKeyword("default")?(x.push(this.parseImportDefaultSpecifier()),this.match(",")&&(this.nextToken(),this.match("*")?x.push(this.parseImportNamespaceSpecifier()):this.match("{")?x=x.concat(this.parseNamedImports()):this.throwUnexpectedToken(this.lookahead))):this.throwUnexpectedToken(this.nextToken()),!this.matchContextualKeyword("from")){var C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause;this.throwError(C,this.lookahead.value)}this.nextToken(),m=this.parseModuleSpecifier()}return this.consumeSemicolon(),this.finalize(w,new d.ImportDeclaration(x,m))},y.prototype.parseExportSpecifier=function(){var m=this.createNode(),w=this.parseIdentifierName(),x=w;return this.matchContextualKeyword("as")&&(this.nextToken(),x=this.parseIdentifierName()),this.finalize(m,new d.ExportSpecifier(w,x))},y.prototype.parseExportDeclaration=function(){this.context.inFunctionBody&&this.throwError(u.Messages.IllegalExportDeclaration);var m,w=this.createNode();if(this.expectKeyword("export"),this.matchKeyword("default"))if(this.nextToken(),this.matchKeyword("function")){var x=this.parseFunctionDeclaration(!0);m=this.finalize(w,new d.ExportDefaultDeclaration(x))}else this.matchKeyword("class")?(x=this.parseClassDeclaration(!0),m=this.finalize(w,new d.ExportDefaultDeclaration(x))):this.matchContextualKeyword("async")?(x=this.matchAsyncFunction()?this.parseFunctionDeclaration(!0):this.parseAssignmentExpression(),m=this.finalize(w,new d.ExportDefaultDeclaration(x))):(this.matchContextualKeyword("from")&&this.throwError(u.Messages.UnexpectedToken,this.lookahead.value),x=this.match("{")?this.parseObjectInitializer():this.match("[")?this.parseArrayInitializer():this.parseAssignmentExpression(),this.consumeSemicolon(),m=this.finalize(w,new d.ExportDefaultDeclaration(x)));else if(this.match("*")){if(this.nextToken(),!this.matchContextualKeyword("from")){var C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause;this.throwError(C,this.lookahead.value)}this.nextToken();var S=this.parseModuleSpecifier();this.consumeSemicolon(),m=this.finalize(w,new d.ExportAllDeclaration(S))}else if(this.lookahead.type===4){switch(x=void 0,this.lookahead.value){case"let":case"const":x=this.parseLexicalDeclaration({inFor:!1});break;case"var":case"class":case"function":x=this.parseStatementListItem();break;default:this.throwUnexpectedToken(this.lookahead)}m=this.finalize(w,new d.ExportNamedDeclaration(x,[],null))}else if(this.matchAsyncFunction())x=this.parseFunctionDeclaration(),m=this.finalize(w,new d.ExportNamedDeclaration(x,[],null));else{var _=[],T=null,E=!1;for(this.expect("{");!this.match("}");)E=E||this.matchKeyword("default"),_.push(this.parseExportSpecifier()),this.match("}")||this.expect(",");this.expect("}"),this.matchContextualKeyword("from")?(this.nextToken(),T=this.parseModuleSpecifier(),this.consumeSemicolon()):E?(C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause,this.throwError(C,this.lookahead.value)):this.consumeSemicolon(),m=this.finalize(w,new d.ExportNamedDeclaration(null,_,T))}return m},y}();s.Parser=v},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.assert=function(c,l){if(!c)throw new Error("ASSERT: "+l)}},function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var c=function(){function l(){this.errors=[],this.tolerant=!1}return l.prototype.recordError=function(f){this.errors.push(f)},l.prototype.tolerate=function(f){if(!this.tolerant)throw f;this.recordError(f)},l.prototype.constructError=function(f,u){var d=new Error(f);try{throw d}catch(h){Object.create&&Object.defineProperty&&(d=Object.create(h),Object.defineProperty(d,"column",{value:u}))}return d},l.prototype.createError=function(f,u,d,h){var g="Line "+u+": "+h,p=this.constructError(g,d);return p.index=f,p.lineNumber=u,p.description=h,p},l.prototype.throwError=function(f,u,d,h){throw this.createError(f,u,d,h)},l.prototype.tolerateError=function(f,u,d,h){var g=this.createError(f,u,d,h);if(!this.tolerant)throw g;this.recordError(g)},l}();s.ErrorHandler=c},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.Messages={BadGetterArity:"Getter must not have any formal parameters",BadSetterArity:"Setter must have exactly one formal parameter",BadSetterRestParameter:"Setter function argument must not be a rest parameter",ConstructorIsAsync:"Class constructor may not be an async method",ConstructorSpecialMethod:"Class constructor may not be an accessor",DeclarationMissingInitializer:"Missing initializer in %0 declaration",DefaultRestParameter:"Unexpected token =",DuplicateBinding:"Duplicate binding %0",DuplicateConstructor:"A class may only have one constructor",DuplicateProtoProperty:"Duplicate __proto__ fields are not allowed in object literals",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInLegacyContext:"Generator declarations are not allowed in legacy contexts",IllegalBreak:"Illegal break statement",IllegalContinue:"Illegal continue statement",IllegalExportDeclaration:"Unexpected token",IllegalImportDeclaration:"Unexpected token",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"Illegal return statement",InvalidEscapedReservedWord:"Keyword must not contain escaped characters",InvalidHexEscapeSequence:"Invalid hexadecimal escape sequence",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",InvalidLHSInForLoop:"Invalid left-hand side in for-loop",InvalidModuleSpecifier:"Unexpected token",InvalidRegExp:"Invalid regular expression",LetInLexicalBinding:"let is disallowed as a lexically bound name",MissingFromClause:"Unexpected token",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NewlineAfterThrow:"Illegal newline after throw",NoAsAfterImportNamespace:"Unexpected token",NoCatchOrFinally:"Missing catch or finally after try",ParameterAfterRestParameter:"Rest parameter must be last formal parameter",Redeclaration:"%0 '%1' has already been declared",StaticPrototype:"Classes may not have static property named prototype",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictModeWith:"Strict mode code may not include a with statement",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",TemplateOctalLiteral:"Octal literals are not allowed in template strings.",UnexpectedEOS:"Unexpected end of input",UnexpectedIdentifier:"Unexpected identifier",UnexpectedNumber:"Unexpected number",UnexpectedReserved:"Unexpected reserved word",UnexpectedString:"Unexpected string",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedToken:"Unexpected token %0",UnexpectedTokenIllegal:"Unexpected token ILLEGAL",UnknownLabel:"Undefined label '%0'",UnterminatedRegExp:"Invalid regular expression: missing /"}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(9),f=c(4),u=c(11);function d(p){return"0123456789abcdef".indexOf(p.toLowerCase())}function h(p){return"01234567".indexOf(p)}var g=function(){function p(v,y){this.source=v,this.errorHandler=y,this.trackComment=!1,this.isModule=!1,this.length=v.length,this.index=0,this.lineNumber=v.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return p.prototype.saveState=function(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart}},p.prototype.restoreState=function(v){this.index=v.index,this.lineNumber=v.lineNumber,this.lineStart=v.lineStart},p.prototype.eof=function(){return this.index>=this.length},p.prototype.throwUnexpectedToken=function(v){return v===void 0&&(v=u.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,v)},p.prototype.tolerateUnexpectedToken=function(v){v===void 0&&(v=u.Messages.UnexpectedTokenIllegal),this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,v)},p.prototype.skipSingleLineComment=function(v){var y,m,w=[];for(this.trackComment&&(w=[],y=this.index-v,m={start:{line:this.lineNumber,column:this.index-this.lineStart-v},end:{}});!this.eof();){var x=this.source.charCodeAt(this.index);if(++this.index,f.Character.isLineTerminator(x)){if(this.trackComment){m.end={line:this.lineNumber,column:this.index-this.lineStart-1};var C={multiLine:!1,slice:[y+v,this.index-1],range:[y,this.index-1],loc:m};w.push(C)}return x===13&&this.source.charCodeAt(this.index)===10&&++this.index,++this.lineNumber,this.lineStart=this.index,w}}return this.trackComment&&(m.end={line:this.lineNumber,column:this.index-this.lineStart},C={multiLine:!1,slice:[y+v,this.index],range:[y,this.index],loc:m},w.push(C)),w},p.prototype.skipMultiLineComment=function(){var v,y,m=[];for(this.trackComment&&(m=[],v=this.index-2,y={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var w=this.source.charCodeAt(this.index);if(f.Character.isLineTerminator(w))w===13&&this.source.charCodeAt(this.index+1)===10&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(w===42){if(this.source.charCodeAt(this.index+1)===47){if(this.index+=2,this.trackComment){y.end={line:this.lineNumber,column:this.index-this.lineStart};var x={multiLine:!0,slice:[v+2,this.index-2],range:[v,this.index],loc:y};m.push(x)}return m}++this.index}else++this.index}return this.trackComment&&(y.end={line:this.lineNumber,column:this.index-this.lineStart},x={multiLine:!0,slice:[v+2,this.index],range:[v,this.index],loc:y},m.push(x)),this.tolerateUnexpectedToken(),m},p.prototype.scanComments=function(){var v;this.trackComment&&(v=[]);for(var y=this.index===0;!this.eof();){var m=this.source.charCodeAt(this.index);if(f.Character.isWhiteSpace(m))++this.index;else if(f.Character.isLineTerminator(m))++this.index,m===13&&this.source.charCodeAt(this.index)===10&&++this.index,++this.lineNumber,this.lineStart=this.index,y=!0;else if(m===47)if((m=this.source.charCodeAt(this.index+1))===47){this.index+=2;var w=this.skipSingleLineComment(2);this.trackComment&&(v=v.concat(w)),y=!0}else{if(m!==42)break;this.index+=2,w=this.skipMultiLineComment(),this.trackComment&&(v=v.concat(w))}else if(y&&m===45){if(this.source.charCodeAt(this.index+1)!==45||this.source.charCodeAt(this.index+2)!==62)break;this.index+=3,w=this.skipSingleLineComment(3),this.trackComment&&(v=v.concat(w))}else{if(m!==60||this.isModule||this.source.slice(this.index+1,this.index+4)!=="!--")break;this.index+=4,w=this.skipSingleLineComment(4),this.trackComment&&(v=v.concat(w))}}return v},p.prototype.isFutureReservedWord=function(v){switch(v){case"enum":case"export":case"import":case"super":return!0;default:return!1}},p.prototype.isStrictModeReservedWord=function(v){switch(v){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},p.prototype.isRestrictedWord=function(v){return v==="eval"||v==="arguments"},p.prototype.isKeyword=function(v){switch(v.length){case 2:return v==="if"||v==="in"||v==="do";case 3:return v==="var"||v==="for"||v==="new"||v==="try"||v==="let";case 4:return v==="this"||v==="else"||v==="case"||v==="void"||v==="with"||v==="enum";case 5:return v==="while"||v==="break"||v==="catch"||v==="throw"||v==="const"||v==="yield"||v==="class"||v==="super";case 6:return v==="return"||v==="typeof"||v==="delete"||v==="switch"||v==="export"||v==="import";case 7:return v==="default"||v==="finally"||v==="extends";case 8:return v==="function"||v==="continue"||v==="debugger";case 10:return v==="instanceof";default:return!1}},p.prototype.codePointAt=function(v){var y=this.source.charCodeAt(v);if(y>=55296&&y<=56319){var m=this.source.charCodeAt(v+1);m>=56320&&m<=57343&&(y=1024*(y-55296)+m-56320+65536)}return y},p.prototype.scanHexEscape=function(v){for(var y=v==="u"?4:2,m=0,w=0;w1114111||v!=="}")&&this.throwUnexpectedToken(),f.Character.fromCodePoint(y)},p.prototype.getIdentifier=function(){for(var v=this.index++;!this.eof();){var y=this.source.charCodeAt(this.index);if(y===92)return this.index=v,this.getComplexIdentifier();if(y>=55296&&y<57343)return this.index=v,this.getComplexIdentifier();if(!f.Character.isIdentifierPart(y))break;++this.index}return this.source.slice(v,this.index)},p.prototype.getComplexIdentifier=function(){var v,y=this.codePointAt(this.index),m=f.Character.fromCodePoint(y);for(this.index+=m.length,y===92&&(this.source.charCodeAt(this.index)!==117&&this.throwUnexpectedToken(),++this.index,this.source[this.index]==="{"?(++this.index,v=this.scanUnicodeCodePointEscape()):(v=this.scanHexEscape("u"))!==null&&v!=="\\"&&f.Character.isIdentifierStart(v.charCodeAt(0))||this.throwUnexpectedToken(),m=v);!this.eof()&&(y=this.codePointAt(this.index),f.Character.isIdentifierPart(y));)m+=v=f.Character.fromCodePoint(y),this.index+=v.length,y===92&&(m=m.substr(0,m.length-1),this.source.charCodeAt(this.index)!==117&&this.throwUnexpectedToken(),++this.index,this.source[this.index]==="{"?(++this.index,v=this.scanUnicodeCodePointEscape()):(v=this.scanHexEscape("u"))!==null&&v!=="\\"&&f.Character.isIdentifierPart(v.charCodeAt(0))||this.throwUnexpectedToken(),m+=v);return m},p.prototype.octalToDecimal=function(v){var y=v!=="0",m=h(v);return!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(y=!0,m=8*m+h(this.source[this.index++]),"0123".indexOf(v)>=0&&!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(m=8*m+h(this.source[this.index++]))),{code:m,octal:y}},p.prototype.scanIdentifier=function(){var v,y=this.index,m=this.source.charCodeAt(y)===92?this.getComplexIdentifier():this.getIdentifier();if((v=m.length===1?3:this.isKeyword(m)?4:m==="null"?5:m==="true"||m==="false"?1:3)!=3&&y+m.length!==this.index){var w=this.index;this.index=y,this.tolerateUnexpectedToken(u.Messages.InvalidEscapedReservedWord),this.index=w}return{type:v,value:m,lineNumber:this.lineNumber,lineStart:this.lineStart,start:y,end:this.index}},p.prototype.scanPunctuator=function(){var v=this.index,y=this.source[this.index];switch(y){case"(":case"{":y==="{"&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,this.source[this.index]==="."&&this.source[this.index+1]==="."&&(this.index+=2,y="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:(y=this.source.substr(this.index,4))===">>>="?this.index+=4:(y=y.substr(0,3))==="==="||y==="!=="||y===">>>"||y==="<<="||y===">>="||y==="**="?this.index+=3:(y=y.substr(0,2))==="&&"||y==="||"||y==="=="||y==="!="||y==="+="||y==="-="||y==="*="||y==="/="||y==="++"||y==="--"||y==="<<"||y===">>"||y==="&="||y==="|="||y==="^="||y==="%="||y==="<="||y===">="||y==="=>"||y==="**"?this.index+=2:(y=this.source[this.index],"<>=!+-*%&|^/".indexOf(y)>=0&&++this.index)}return this.index===v&&this.throwUnexpectedToken(),{type:7,value:y,lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanHexLiteral=function(v){for(var y="";!this.eof()&&f.Character.isHexDigit(this.source.charCodeAt(this.index));)y+=this.source[this.index++];return y.length===0&&this.throwUnexpectedToken(),f.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:6,value:parseInt("0x"+y,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanBinaryLiteral=function(v){for(var y,m="";!this.eof()&&((y=this.source[this.index])==="0"||y==="1");)m+=this.source[this.index++];return m.length===0&&this.throwUnexpectedToken(),this.eof()||(y=this.source.charCodeAt(this.index),(f.Character.isIdentifierStart(y)||f.Character.isDecimalDigit(y))&&this.throwUnexpectedToken()),{type:6,value:parseInt(m,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanOctalLiteral=function(v,y){var m="",w=!1;for(f.Character.isOctalDigit(v.charCodeAt(0))?(w=!0,m="0"+this.source[this.index++]):++this.index;!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index));)m+=this.source[this.index++];return w||m.length!==0||this.throwUnexpectedToken(),(f.Character.isIdentifierStart(this.source.charCodeAt(this.index))||f.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:6,value:parseInt(m,8),octal:w,lineNumber:this.lineNumber,lineStart:this.lineStart,start:y,end:this.index}},p.prototype.isImplicitOctalLiteral=function(){for(var v=this.index+1;v0&&this.config.tokens&&this.tokens.push(this.convertToken(E)),E},C.prototype.peekJSXToken=function(){var S=this.scanner.saveState();this.scanner.scanComments();var _=this.lexJSX();return this.scanner.restoreState(S),_},C.prototype.expectJSX=function(S){var _=this.nextJSXToken();_.type===7&&_.value===S||this.throwUnexpectedToken(_)},C.prototype.matchJSX=function(S){var _=this.peekJSXToken();return _.type===7&&_.value===S},C.prototype.parseJSXIdentifier=function(){var S=this.createJSXNode(),_=this.nextJSXToken();return _.type!==100&&this.throwUnexpectedToken(_),this.finalize(S,new d.JSXIdentifier(_.value))},C.prototype.parseJSXElementName=function(){var S=this.createJSXNode(),_=this.parseJSXIdentifier();if(this.matchJSX(":")){var T=_;this.expectJSX(":");var E=this.parseJSXIdentifier();_=this.finalize(S,new d.JSXNamespacedName(T,E))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var D=_;this.expectJSX(".");var b=this.parseJSXIdentifier();_=this.finalize(S,new d.JSXMemberExpression(D,b))}return _},C.prototype.parseJSXAttributeName=function(){var S,_=this.createJSXNode(),T=this.parseJSXIdentifier();if(this.matchJSX(":")){var E=T;this.expectJSX(":");var D=this.parseJSXIdentifier();S=this.finalize(_,new d.JSXNamespacedName(E,D))}else S=T;return S},C.prototype.parseJSXStringLiteralAttribute=function(){var S=this.createJSXNode(),_=this.nextJSXToken();_.type!==8&&this.throwUnexpectedToken(_);var T=this.getTokenRaw(_);return this.finalize(S,new g.Literal(_.value,T))},C.prototype.parseJSXExpressionAttribute=function(){var S=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var _=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(S,new d.JSXExpressionContainer(_))},C.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},C.prototype.parseJSXNameValueAttribute=function(){var S=this.createJSXNode(),_=this.parseJSXAttributeName(),T=null;return this.matchJSX("=")&&(this.expectJSX("="),T=this.parseJSXAttributeValue()),this.finalize(S,new d.JSXAttribute(_,T))},C.prototype.parseJSXSpreadAttribute=function(){var S=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var _=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(S,new d.JSXSpreadAttribute(_))},C.prototype.parseJSXAttributes=function(){for(var S=[];!this.matchJSX("/")&&!this.matchJSX(">");){var _=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();S.push(_)}return S},C.prototype.parseJSXOpeningElement=function(){var S=this.createJSXNode();this.expectJSX("<");var _=this.parseJSXElementName(),T=this.parseJSXAttributes(),E=this.matchJSX("/");return E&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(S,new d.JSXOpeningElement(_,E,T))},C.prototype.parseJSXBoundaryElement=function(){var S=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var _=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(S,new d.JSXClosingElement(_))}var T=this.parseJSXElementName(),E=this.parseJSXAttributes(),D=this.matchJSX("/");return D&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(S,new d.JSXOpeningElement(T,D,E))},C.prototype.parseJSXEmptyExpression=function(){var S=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.finalize(S,new d.JSXEmptyExpression)},C.prototype.parseJSXExpressionContainer=function(){var S,_=this.createJSXNode();return this.expectJSX("{"),this.matchJSX("}")?(S=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),S=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(_,new d.JSXExpressionContainer(S))},C.prototype.parseJSXChildren=function(){for(var S=[];!this.scanner.eof();){var _=this.createJSXChildNode(),T=this.nextJSXText();if(T.start0))break;b=this.finalize(S.node,new d.JSXElement(S.opening,S.children,S.closing)),(S=_[_.length-1]).children.push(b),_.pop()}}return S},C.prototype.parseJSXElement=function(){var S=this.createJSXNode(),_=this.parseJSXOpeningElement(),T=[],E=null;if(!_.selfClosing){var D=this.parseComplexJSXElement({node:S,opening:_,closing:E,children:T});T=D.children,E=D.closing}return this.finalize(S,new d.JSXElement(_,T,E))},C.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var S=this.parseJSXElement();return this.finishJSX(),S},C.prototype.isStartOfExpression=function(){return x.prototype.isStartOfExpression.call(this)||this.match("<")},C}(p.Parser);s.JSXParser=w},function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var c={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};s.Character={fromCodePoint:function(l){return l<65536?String.fromCharCode(l):String.fromCharCode(55296+(l-65536>>10))+String.fromCharCode(56320+(l-65536&1023))},isWhiteSpace:function(l){return l===32||l===9||l===11||l===12||l===160||l>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(l)>=0},isLineTerminator:function(l){return l===10||l===13||l===8232||l===8233},isIdentifierStart:function(l){return l===36||l===95||l>=65&&l<=90||l>=97&&l<=122||l===92||l>=128&&c.NonAsciiIdentifierStart.test(s.Character.fromCodePoint(l))},isIdentifierPart:function(l){return l===36||l===95||l>=65&&l<=90||l>=97&&l<=122||l>=48&&l<=57||l===92||l>=128&&c.NonAsciiIdentifierPart.test(s.Character.fromCodePoint(l))},isDecimalDigit:function(l){return l>=48&&l<=57},isHexDigit:function(l){return l>=48&&l<=57||l>=65&&l<=70||l>=97&&l<=102},isOctalDigit:function(l){return l>=48&&l<=55}}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(6),f=function(C){this.type=l.JSXSyntax.JSXClosingElement,this.name=C};s.JSXClosingElement=f;var u=function(C,S,_){this.type=l.JSXSyntax.JSXElement,this.openingElement=C,this.children=S,this.closingElement=_};s.JSXElement=u;var d=function(){this.type=l.JSXSyntax.JSXEmptyExpression};s.JSXEmptyExpression=d;var h=function(C){this.type=l.JSXSyntax.JSXExpressionContainer,this.expression=C};s.JSXExpressionContainer=h;var g=function(C){this.type=l.JSXSyntax.JSXIdentifier,this.name=C};s.JSXIdentifier=g;var p=function(C,S){this.type=l.JSXSyntax.JSXMemberExpression,this.object=C,this.property=S};s.JSXMemberExpression=p;var v=function(C,S){this.type=l.JSXSyntax.JSXAttribute,this.name=C,this.value=S};s.JSXAttribute=v;var y=function(C,S){this.type=l.JSXSyntax.JSXNamespacedName,this.namespace=C,this.name=S};s.JSXNamespacedName=y;var m=function(C,S,_){this.type=l.JSXSyntax.JSXOpeningElement,this.name=C,this.selfClosing=S,this.attributes=_};s.JSXOpeningElement=m;var w=function(C){this.type=l.JSXSyntax.JSXSpreadAttribute,this.argument=C};s.JSXSpreadAttribute=w;var x=function(C,S){this.type=l.JSXSyntax.JSXText,this.value=C,this.raw=S};s.JSXText=x},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(2),f=function(Ue){this.type=l.Syntax.ArrayExpression,this.elements=Ue};s.ArrayExpression=f;var u=function(Ue){this.type=l.Syntax.ArrayPattern,this.elements=Ue};s.ArrayPattern=u;var d=function(Ue,ft,Ut){this.type=l.Syntax.ArrowFunctionExpression,this.id=null,this.params=Ue,this.body=ft,this.generator=!1,this.expression=Ut,this.async=!1};s.ArrowFunctionExpression=d;var h=function(Ue,ft,Ut){this.type=l.Syntax.AssignmentExpression,this.operator=Ue,this.left=ft,this.right=Ut};s.AssignmentExpression=h;var g=function(Ue,ft){this.type=l.Syntax.AssignmentPattern,this.left=Ue,this.right=ft};s.AssignmentPattern=g;var p=function(Ue,ft,Ut){this.type=l.Syntax.ArrowFunctionExpression,this.id=null,this.params=Ue,this.body=ft,this.generator=!1,this.expression=Ut,this.async=!0};s.AsyncArrowFunctionExpression=p;var v=function(Ue,ft,Ut){this.type=l.Syntax.FunctionDeclaration,this.id=Ue,this.params=ft,this.body=Ut,this.generator=!1,this.expression=!1,this.async=!0};s.AsyncFunctionDeclaration=v;var y=function(Ue,ft,Ut){this.type=l.Syntax.FunctionExpression,this.id=Ue,this.params=ft,this.body=Ut,this.generator=!1,this.expression=!1,this.async=!0};s.AsyncFunctionExpression=y;var m=function(Ue){this.type=l.Syntax.AwaitExpression,this.argument=Ue};s.AwaitExpression=m;var w=function(Ue,ft,Ut){var Sn=Ue==="||"||Ue==="&&";this.type=Sn?l.Syntax.LogicalExpression:l.Syntax.BinaryExpression,this.operator=Ue,this.left=ft,this.right=Ut};s.BinaryExpression=w;var x=function(Ue){this.type=l.Syntax.BlockStatement,this.body=Ue};s.BlockStatement=x;var C=function(Ue){this.type=l.Syntax.BreakStatement,this.label=Ue};s.BreakStatement=C;var S=function(Ue,ft){this.type=l.Syntax.CallExpression,this.callee=Ue,this.arguments=ft};s.CallExpression=S;var _=function(Ue,ft){this.type=l.Syntax.CatchClause,this.param=Ue,this.body=ft};s.CatchClause=_;var T=function(Ue){this.type=l.Syntax.ClassBody,this.body=Ue};s.ClassBody=T;var E=function(Ue,ft,Ut){this.type=l.Syntax.ClassDeclaration,this.id=Ue,this.superClass=ft,this.body=Ut};s.ClassDeclaration=E;var D=function(Ue,ft,Ut){this.type=l.Syntax.ClassExpression,this.id=Ue,this.superClass=ft,this.body=Ut};s.ClassExpression=D;var b=function(Ue,ft){this.type=l.Syntax.MemberExpression,this.computed=!0,this.object=Ue,this.property=ft};s.ComputedMemberExpression=b;var I=function(Ue,ft,Ut){this.type=l.Syntax.ConditionalExpression,this.test=Ue,this.consequent=ft,this.alternate=Ut};s.ConditionalExpression=I;var P=function(Ue){this.type=l.Syntax.ContinueStatement,this.label=Ue};s.ContinueStatement=P;var M=function(){this.type=l.Syntax.DebuggerStatement};s.DebuggerStatement=M;var L=function(Ue,ft){this.type=l.Syntax.ExpressionStatement,this.expression=Ue,this.directive=ft};s.Directive=L;var V=function(Ue,ft){this.type=l.Syntax.DoWhileStatement,this.body=Ue,this.test=ft};s.DoWhileStatement=V;var G=function(){this.type=l.Syntax.EmptyStatement};s.EmptyStatement=G;var A=function(Ue){this.type=l.Syntax.ExportAllDeclaration,this.source=Ue};s.ExportAllDeclaration=A;var k=function(Ue){this.type=l.Syntax.ExportDefaultDeclaration,this.declaration=Ue};s.ExportDefaultDeclaration=k;var F=function(Ue,ft,Ut){this.type=l.Syntax.ExportNamedDeclaration,this.declaration=Ue,this.specifiers=ft,this.source=Ut};s.ExportNamedDeclaration=F;var j=function(Ue,ft){this.type=l.Syntax.ExportSpecifier,this.exported=ft,this.local=Ue};s.ExportSpecifier=j;var Y=function(Ue){this.type=l.Syntax.ExpressionStatement,this.expression=Ue};s.ExpressionStatement=Y;var re=function(Ue,ft,Ut){this.type=l.Syntax.ForInStatement,this.left=Ue,this.right=ft,this.body=Ut,this.each=!1};s.ForInStatement=re;var ue=function(Ue,ft,Ut){this.type=l.Syntax.ForOfStatement,this.left=Ue,this.right=ft,this.body=Ut};s.ForOfStatement=ue;var ce=function(Ue,ft,Ut,Sn){this.type=l.Syntax.ForStatement,this.init=Ue,this.test=ft,this.update=Ut,this.body=Sn};s.ForStatement=ce;var pe=function(Ue,ft,Ut,Sn){this.type=l.Syntax.FunctionDeclaration,this.id=Ue,this.params=ft,this.body=Ut,this.generator=Sn,this.expression=!1,this.async=!1};s.FunctionDeclaration=pe;var Ee=function(Ue,ft,Ut,Sn){this.type=l.Syntax.FunctionExpression,this.id=Ue,this.params=ft,this.body=Ut,this.generator=Sn,this.expression=!1,this.async=!1};s.FunctionExpression=Ee;var Oe=function(Ue){this.type=l.Syntax.Identifier,this.name=Ue};s.Identifier=Oe;var _e=function(Ue,ft,Ut){this.type=l.Syntax.IfStatement,this.test=Ue,this.consequent=ft,this.alternate=Ut};s.IfStatement=_e;var B=function(Ue,ft){this.type=l.Syntax.ImportDeclaration,this.specifiers=Ue,this.source=ft};s.ImportDeclaration=B;var O=function(Ue){this.type=l.Syntax.ImportDefaultSpecifier,this.local=Ue};s.ImportDefaultSpecifier=O;var z=function(Ue){this.type=l.Syntax.ImportNamespaceSpecifier,this.local=Ue};s.ImportNamespaceSpecifier=z;var W=function(Ue,ft){this.type=l.Syntax.ImportSpecifier,this.local=Ue,this.imported=ft};s.ImportSpecifier=W;var K=function(Ue,ft){this.type=l.Syntax.LabeledStatement,this.label=Ue,this.body=ft};s.LabeledStatement=K;var Z=function(Ue,ft){this.type=l.Syntax.Literal,this.value=Ue,this.raw=ft};s.Literal=Z;var ee=function(Ue,ft){this.type=l.Syntax.MetaProperty,this.meta=Ue,this.property=ft};s.MetaProperty=ee;var xe=function(Ue,ft,Ut,Sn,Qn){this.type=l.Syntax.MethodDefinition,this.key=Ue,this.computed=ft,this.value=Ut,this.kind=Sn,this.static=Qn};s.MethodDefinition=xe;var De=function(Ue){this.type=l.Syntax.Program,this.body=Ue,this.sourceType="module"};s.Module=De;var Ne=function(Ue,ft){this.type=l.Syntax.NewExpression,this.callee=Ue,this.arguments=ft};s.NewExpression=Ne;var $e=function(Ue){this.type=l.Syntax.ObjectExpression,this.properties=Ue};s.ObjectExpression=$e;var ie=function(Ue){this.type=l.Syntax.ObjectPattern,this.properties=Ue};s.ObjectPattern=ie;var ae=function(Ue,ft,Ut,Sn,Qn,Pt){this.type=l.Syntax.Property,this.key=ft,this.computed=Ut,this.value=Sn,this.kind=Ue,this.method=Qn,this.shorthand=Pt};s.Property=ae;var ye=function(Ue,ft,Ut,Sn){this.type=l.Syntax.Literal,this.value=Ue,this.raw=ft,this.regex={pattern:Ut,flags:Sn}};s.RegexLiteral=ye;var se=function(Ue){this.type=l.Syntax.RestElement,this.argument=Ue};s.RestElement=se;var ge=function(Ue){this.type=l.Syntax.ReturnStatement,this.argument=Ue};s.ReturnStatement=ge;var Fe=function(Ue){this.type=l.Syntax.Program,this.body=Ue,this.sourceType="script"};s.Script=Fe;var oe=function(Ue){this.type=l.Syntax.SequenceExpression,this.expressions=Ue};s.SequenceExpression=oe;var ht=function(Ue){this.type=l.Syntax.SpreadElement,this.argument=Ue};s.SpreadElement=ht;var wt=function(Ue,ft){this.type=l.Syntax.MemberExpression,this.computed=!1,this.object=Ue,this.property=ft};s.StaticMemberExpression=wt;var gt=function(){this.type=l.Syntax.Super};s.Super=gt;var Ie=function(Ue,ft){this.type=l.Syntax.SwitchCase,this.test=Ue,this.consequent=ft};s.SwitchCase=Ie;var je=function(Ue,ft){this.type=l.Syntax.SwitchStatement,this.discriminant=Ue,this.cases=ft};s.SwitchStatement=je;var nt=function(Ue,ft){this.type=l.Syntax.TaggedTemplateExpression,this.tag=Ue,this.quasi=ft};s.TaggedTemplateExpression=nt;var rt=function(Ue,ft){this.type=l.Syntax.TemplateElement,this.value=Ue,this.tail=ft};s.TemplateElement=rt;var dt=function(Ue,ft){this.type=l.Syntax.TemplateLiteral,this.quasis=Ue,this.expressions=ft};s.TemplateLiteral=dt;var Lt=function(){this.type=l.Syntax.ThisExpression};s.ThisExpression=Lt;var xt=function(Ue){this.type=l.Syntax.ThrowStatement,this.argument=Ue};s.ThrowStatement=xt;var Ft=function(Ue,ft,Ut){this.type=l.Syntax.TryStatement,this.block=Ue,this.handler=ft,this.finalizer=Ut};s.TryStatement=Ft;var jt=function(Ue,ft){this.type=l.Syntax.UnaryExpression,this.operator=Ue,this.argument=ft,this.prefix=!0};s.UnaryExpression=jt;var Pn=function(Ue,ft,Ut){this.type=l.Syntax.UpdateExpression,this.operator=Ue,this.argument=ft,this.prefix=Ut};s.UpdateExpression=Pn;var $n=function(Ue,ft){this.type=l.Syntax.VariableDeclaration,this.declarations=Ue,this.kind=ft};s.VariableDeclaration=$n;var fn=function(Ue,ft){this.type=l.Syntax.VariableDeclarator,this.id=Ue,this.init=ft};s.VariableDeclarator=fn;var bn=function(Ue,ft){this.type=l.Syntax.WhileStatement,this.test=Ue,this.body=ft};s.WhileStatement=bn;var Xi=function(Ue,ft){this.type=l.Syntax.WithStatement,this.object=Ue,this.body=ft};s.WithStatement=Xi;var Mr=function(Ue,ft){this.type=l.Syntax.YieldExpression,this.argument=Ue,this.delegate=ft};s.YieldExpression=Mr},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(9),f=c(10),u=c(11),d=c(7),h=c(12),g=c(2),p=c(13),v=function(){function y(m,w,x){w===void 0&&(w={}),this.config={range:typeof w.range=="boolean"&&w.range,loc:typeof w.loc=="boolean"&&w.loc,source:null,tokens:typeof w.tokens=="boolean"&&w.tokens,comment:typeof w.comment=="boolean"&&w.comment,tolerant:typeof w.tolerant=="boolean"&&w.tolerant},this.config.loc&&w.source&&w.source!==null&&(this.config.source=String(w.source)),this.delegate=x,this.errorHandler=new f.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new h.Scanner(m,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.lookahead={type:2,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.hasLineTerminator=!1,this.context={isModule:!1,await:!1,allowIn:!0,allowStrictDirective:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:!1},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.lastMarker={index:0,line:this.scanner.lineNumber,column:0},this.nextToken(),this.lastMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}return y.prototype.throwError=function(m){for(var w=[],x=1;x0&&this.delegate)for(var w=0;w>="||m===">>>="||m==="&="||m==="^="||m==="|="},y.prototype.isolateCoverGrammar=function(m){var w=this.context.isBindingElement,x=this.context.isAssignmentTarget,C=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var S=m.call(this);return this.context.firstCoverInitializedNameError!==null&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=w,this.context.isAssignmentTarget=x,this.context.firstCoverInitializedNameError=C,S},y.prototype.inheritCoverGrammar=function(m){var w=this.context.isBindingElement,x=this.context.isAssignmentTarget,C=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var S=m.call(this);return this.context.isBindingElement=this.context.isBindingElement&&w,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&x,this.context.firstCoverInitializedNameError=C||this.context.firstCoverInitializedNameError,S},y.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(this.lookahead.type===2||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.line=this.startMarker.line,this.lastMarker.column=this.startMarker.column)},y.prototype.parsePrimaryExpression=function(){var m,w,x,C=this.createNode();switch(this.lookahead.type){case 3:(this.context.isModule||this.context.await)&&this.lookahead.value==="await"&&this.tolerateUnexpectedToken(this.lookahead),m=this.matchAsyncFunction()?this.parseFunctionExpression():this.finalize(C,new d.Identifier(this.nextToken().value));break;case 6:case 8:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,u.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(w.value,x));break;case 1:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(w.value==="true",x));break;case 5:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,w=this.nextToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.Literal(null,x));break;case 10:m=this.parseTemplateLiteral();break;case 7:switch(this.lookahead.value){case"(":this.context.isBindingElement=!1,m=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":m=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":m=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,w=this.nextRegexToken(),x=this.getTokenRaw(w),m=this.finalize(C,new d.RegexLiteral(w.regex,x,w.pattern,w.flags));break;default:m=this.throwUnexpectedToken(this.nextToken())}break;case 4:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?m=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?m=this.finalize(C,new d.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?m=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),m=this.finalize(C,new d.ThisExpression)):m=this.matchKeyword("class")?this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:m=this.throwUnexpectedToken(this.nextToken())}return m},y.prototype.parseSpreadElement=function(){var m=this.createNode();this.expect("...");var w=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(m,new d.SpreadElement(w))},y.prototype.parseArrayInitializer=function(){var m=this.createNode(),w=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),w.push(null);else if(this.match("...")){var x=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),w.push(x)}else w.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(m,new d.ArrayExpression(w))},y.prototype.parsePropertyMethod=function(m){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var w=this.context.strict,x=this.context.allowStrictDirective;this.context.allowStrictDirective=m.simple;var C=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&m.firstRestricted&&this.tolerateUnexpectedToken(m.firstRestricted,m.message),this.context.strict&&m.stricted&&this.tolerateUnexpectedToken(m.stricted,m.message),this.context.strict=w,this.context.allowStrictDirective=x,C},y.prototype.parsePropertyMethodFunction=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters(),C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parsePropertyMethodAsyncFunction=function(){var m=this.createNode(),w=this.context.allowYield,x=this.context.await;this.context.allowYield=!1,this.context.await=!0;var C=this.parseFormalParameters(),S=this.parsePropertyMethod(C);return this.context.allowYield=w,this.context.await=x,this.finalize(m,new d.AsyncFunctionExpression(null,C.params,S))},y.prototype.parseObjectPropertyKey=function(){var m,w=this.createNode(),x=this.nextToken();switch(x.type){case 8:case 6:this.context.strict&&x.octal&&this.tolerateUnexpectedToken(x,u.Messages.StrictOctalLiteral);var C=this.getTokenRaw(x);m=this.finalize(w,new d.Literal(x.value,C));break;case 3:case 1:case 5:case 4:m=this.finalize(w,new d.Identifier(x.value));break;case 7:x.value==="["?(m=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):m=this.throwUnexpectedToken(x);break;default:m=this.throwUnexpectedToken(x)}return m},y.prototype.isPropertyKey=function(m,w){return m.type===g.Syntax.Identifier&&m.name===w||m.type===g.Syntax.Literal&&m.value===w},y.prototype.parseObjectProperty=function(m){var w,x=this.createNode(),C=this.lookahead,S=null,_=null,T=!1,E=!1,D=!1,b=!1;if(C.type===3){var I=C.value;this.nextToken(),T=this.match("["),S=(b=!(this.hasLineTerminator||I!=="async"||this.match(":")||this.match("(")||this.match("*")||this.match(",")))?this.parseObjectPropertyKey():this.finalize(x,new d.Identifier(I))}else this.match("*")?this.nextToken():(T=this.match("["),S=this.parseObjectPropertyKey());var P=this.qualifiedPropertyName(this.lookahead);if(C.type===3&&!b&&C.value==="get"&&P)w="get",T=this.match("["),S=this.parseObjectPropertyKey(),this.context.allowYield=!1,_=this.parseGetterMethod();else if(C.type===3&&!b&&C.value==="set"&&P)w="set",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseSetterMethod();else if(C.type===7&&C.value==="*"&&P)w="init",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseGeneratorMethod(),E=!0;else if(S||this.throwUnexpectedToken(this.lookahead),w="init",this.match(":")&&!b)!T&&this.isPropertyKey(S,"__proto__")&&(m.value&&this.tolerateError(u.Messages.DuplicateProtoProperty),m.value=!0),this.nextToken(),_=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))_=b?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),E=!0;else if(C.type===3)if(I=this.finalize(x,new d.Identifier(C.value)),this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),D=!0;var M=this.isolateCoverGrammar(this.parseAssignmentExpression);_=this.finalize(x,new d.AssignmentPattern(I,M))}else D=!0,_=I;else this.throwUnexpectedToken(this.nextToken());return this.finalize(x,new d.Property(w,S,T,_,E,D))},y.prototype.parseObjectInitializer=function(){var m=this.createNode();this.expect("{");for(var w=[],x={value:!1};!this.match("}");)w.push(this.parseObjectProperty(x)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(m,new d.ObjectExpression(w))},y.prototype.parseTemplateHead=function(){l.assert(this.lookahead.head,"Template literal must start with a template head");var m=this.createNode(),w=this.nextToken(),x=w.value,C=w.cooked;return this.finalize(m,new d.TemplateElement({raw:x,cooked:C},w.tail))},y.prototype.parseTemplateElement=function(){this.lookahead.type!==10&&this.throwUnexpectedToken();var m=this.createNode(),w=this.nextToken(),x=w.value,C=w.cooked;return this.finalize(m,new d.TemplateElement({raw:x,cooked:C},w.tail))},y.prototype.parseTemplateLiteral=function(){var m=this.createNode(),w=[],x=[],C=this.parseTemplateHead();for(x.push(C);!C.tail;)w.push(this.parseExpression()),C=this.parseTemplateElement(),x.push(C);return this.finalize(m,new d.TemplateLiteral(x,w))},y.prototype.reinterpretExpressionAsPattern=function(m){switch(m.type){case g.Syntax.Identifier:case g.Syntax.MemberExpression:case g.Syntax.RestElement:case g.Syntax.AssignmentPattern:break;case g.Syntax.SpreadElement:m.type=g.Syntax.RestElement,this.reinterpretExpressionAsPattern(m.argument);break;case g.Syntax.ArrayExpression:m.type=g.Syntax.ArrayPattern;for(var w=0;w")||this.expect("=>"),m={type:"ArrowParameterPlaceHolder",params:[],async:!1};else{var w=this.lookahead,x=[];if(this.match("..."))m=this.parseRestElement(x),this.expect(")"),this.match("=>")||this.expect("=>"),m={type:"ArrowParameterPlaceHolder",params:[m],async:!1};else{var C=!1;if(this.context.isBindingElement=!0,m=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var S=[];for(this.context.isAssignmentTarget=!1,S.push(m);this.lookahead.type!==2&&this.match(",");){if(this.nextToken(),this.match(")")){this.nextToken();for(var _=0;_")||this.expect("=>"),this.context.isBindingElement=!1,_=0;_")&&(m.type===g.Syntax.Identifier&&m.name==="yield"&&(C=!0,m={type:"ArrowParameterPlaceHolder",params:[m],async:!1}),!C)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),m.type===g.Syntax.SequenceExpression)for(_=0;_")){for(var E=0;E0){this.nextToken(),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var S=[m,this.lookahead],_=w,T=this.isolateCoverGrammar(this.parseExponentiationExpression),E=[_,x.value,T],D=[C];!((C=this.binaryPrecedence(this.lookahead))<=0);){for(;E.length>2&&C<=D[D.length-1];){T=E.pop();var b=E.pop();D.pop(),_=E.pop(),S.pop();var I=this.startNode(S[S.length-1]);E.push(this.finalize(I,new d.BinaryExpression(b,_,T)))}E.push(this.nextToken().value),D.push(C),S.push(this.lookahead),E.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var P=E.length-1;w=E[P];for(var M=S.pop();P>1;){var L=S.pop(),V=M&&M.lineStart;I=this.startNode(L,V),b=E[P-1],w=this.finalize(I,new d.BinaryExpression(b,E[P-2],w)),P-=2,M=L}}return w},y.prototype.parseConditionalExpression=function(){var m=this.lookahead,w=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var x=this.context.allowIn;this.context.allowIn=!0;var C=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=x,this.expect(":");var S=this.isolateCoverGrammar(this.parseAssignmentExpression);w=this.finalize(this.startNode(m),new d.ConditionalExpression(w,C,S)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return w},y.prototype.checkPatternParam=function(m,w){switch(w.type){case g.Syntax.Identifier:this.validateParam(m,w,w.name);break;case g.Syntax.RestElement:this.checkPatternParam(m,w.argument);break;case g.Syntax.AssignmentPattern:this.checkPatternParam(m,w.left);break;case g.Syntax.ArrayPattern:for(var x=0;x")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var S=m.async,_=this.reinterpretAsCoverFormalsList(m);if(_){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var T=this.context.strict,E=this.context.allowStrictDirective;this.context.allowStrictDirective=_.simple;var D=this.context.allowYield,b=this.context.await;this.context.allowYield=!0,this.context.await=S;var I=this.startNode(w);this.expect("=>");var P=void 0;if(this.match("{")){var M=this.context.allowIn;this.context.allowIn=!0,P=this.parseFunctionSourceElements(),this.context.allowIn=M}else P=this.isolateCoverGrammar(this.parseAssignmentExpression);var L=P.type!==g.Syntax.BlockStatement;this.context.strict&&_.firstRestricted&&this.throwUnexpectedToken(_.firstRestricted,_.message),this.context.strict&&_.stricted&&this.tolerateUnexpectedToken(_.stricted,_.message),m=S?this.finalize(I,new d.AsyncArrowFunctionExpression(_.params,P,L)):this.finalize(I,new d.ArrowFunctionExpression(_.params,P,L)),this.context.strict=T,this.context.allowStrictDirective=E,this.context.allowYield=D,this.context.await=b}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(u.Messages.InvalidLHSInAssignment),this.context.strict&&m.type===g.Syntax.Identifier){var V=m;this.scanner.isRestrictedWord(V.name)&&this.tolerateUnexpectedToken(x,u.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(V.name)&&this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(m):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1);var G=(x=this.nextToken()).value,A=this.isolateCoverGrammar(this.parseAssignmentExpression);m=this.finalize(this.startNode(w),new d.AssignmentExpression(G,m,A)),this.context.firstCoverInitializedNameError=null}}return m},y.prototype.parseExpression=function(){var m=this.lookahead,w=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var x=[];for(x.push(w);this.lookahead.type!==2&&this.match(",");)this.nextToken(),x.push(this.isolateCoverGrammar(this.parseAssignmentExpression));w=this.finalize(this.startNode(m),new d.SequenceExpression(x))}return w},y.prototype.parseStatementListItem=function(){var m;if(this.context.isAssignmentTarget=!0,this.context.isBindingElement=!0,this.lookahead.type===4)switch(this.lookahead.value){case"export":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,u.Messages.IllegalExportDeclaration),m=this.parseExportDeclaration();break;case"import":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,u.Messages.IllegalImportDeclaration),m=this.parseImportDeclaration();break;case"const":m=this.parseLexicalDeclaration({inFor:!1});break;case"function":m=this.parseFunctionDeclaration();break;case"class":m=this.parseClassDeclaration();break;case"let":m=this.isLexicalDeclaration()?this.parseLexicalDeclaration({inFor:!1}):this.parseStatement();break;default:m=this.parseStatement()}else m=this.parseStatement();return m},y.prototype.parseBlock=function(){var m=this.createNode();this.expect("{");for(var w=[];!this.match("}");)w.push(this.parseStatementListItem());return this.expect("}"),this.finalize(m,new d.BlockStatement(w))},y.prototype.parseLexicalBinding=function(m,w){var x=this.createNode(),C=this.parsePattern([],m);this.context.strict&&C.type===g.Syntax.Identifier&&this.scanner.isRestrictedWord(C.name)&&this.tolerateError(u.Messages.StrictVarName);var S=null;return m==="const"?this.matchKeyword("in")||this.matchContextualKeyword("of")||(this.match("=")?(this.nextToken(),S=this.isolateCoverGrammar(this.parseAssignmentExpression)):this.throwError(u.Messages.DeclarationMissingInitializer,"const")):(!w.inFor&&C.type!==g.Syntax.Identifier||this.match("="))&&(this.expect("="),S=this.isolateCoverGrammar(this.parseAssignmentExpression)),this.finalize(x,new d.VariableDeclarator(C,S))},y.prototype.parseBindingList=function(m,w){for(var x=[this.parseLexicalBinding(m,w)];this.match(",");)this.nextToken(),x.push(this.parseLexicalBinding(m,w));return x},y.prototype.isLexicalDeclaration=function(){var m=this.scanner.saveState();this.scanner.scanComments();var w=this.scanner.lex();return this.scanner.restoreState(m),w.type===3||w.type===7&&w.value==="["||w.type===7&&w.value==="{"||w.type===4&&w.value==="let"||w.type===4&&w.value==="yield"},y.prototype.parseLexicalDeclaration=function(m){var w=this.createNode(),x=this.nextToken().value;l.assert(x==="let"||x==="const","Lexical declaration must be either let or const");var C=this.parseBindingList(x,m);return this.consumeSemicolon(),this.finalize(w,new d.VariableDeclaration(C,x))},y.prototype.parseBindingRestElement=function(m,w){var x=this.createNode();this.expect("...");var C=this.parsePattern(m,w);return this.finalize(x,new d.RestElement(C))},y.prototype.parseArrayPattern=function(m,w){var x=this.createNode();this.expect("[");for(var C=[];!this.match("]");)if(this.match(","))this.nextToken(),C.push(null);else{if(this.match("...")){C.push(this.parseBindingRestElement(m,w));break}C.push(this.parsePatternWithDefault(m,w)),this.match("]")||this.expect(",")}return this.expect("]"),this.finalize(x,new d.ArrayPattern(C))},y.prototype.parsePropertyPattern=function(m,w){var x,C,S=this.createNode(),_=!1,T=!1;if(this.lookahead.type===3){var E=this.lookahead;x=this.parseVariableIdentifier();var D=this.finalize(S,new d.Identifier(E.value));if(this.match("=")){m.push(E),T=!0,this.nextToken();var b=this.parseAssignmentExpression();C=this.finalize(this.startNode(E),new d.AssignmentPattern(D,b))}else this.match(":")?(this.expect(":"),C=this.parsePatternWithDefault(m,w)):(m.push(E),T=!0,C=D)}else _=this.match("["),x=this.parseObjectPropertyKey(),this.expect(":"),C=this.parsePatternWithDefault(m,w);return this.finalize(S,new d.Property("init",x,_,C,!1,T))},y.prototype.parseObjectPattern=function(m,w){var x=this.createNode(),C=[];for(this.expect("{");!this.match("}");)C.push(this.parsePropertyPattern(m,w)),this.match("}")||this.expect(",");return this.expect("}"),this.finalize(x,new d.ObjectPattern(C))},y.prototype.parsePattern=function(m,w){var x;return this.match("[")?x=this.parseArrayPattern(m,w):this.match("{")?x=this.parseObjectPattern(m,w):(!this.matchKeyword("let")||w!=="const"&&w!=="let"||this.tolerateUnexpectedToken(this.lookahead,u.Messages.LetInLexicalBinding),m.push(this.lookahead),x=this.parseVariableIdentifier(w)),x},y.prototype.parsePatternWithDefault=function(m,w){var x=this.lookahead,C=this.parsePattern(m,w);if(this.match("=")){this.nextToken();var S=this.context.allowYield;this.context.allowYield=!0;var _=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowYield=S,C=this.finalize(this.startNode(x),new d.AssignmentPattern(C,_))}return C},y.prototype.parseVariableIdentifier=function(m){var w=this.createNode(),x=this.nextToken();return x.type===4&&x.value==="yield"?this.context.strict?this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord):this.context.allowYield||this.throwUnexpectedToken(x):x.type!==3?this.context.strict&&x.type===4&&this.scanner.isStrictModeReservedWord(x.value)?this.tolerateUnexpectedToken(x,u.Messages.StrictReservedWord):(this.context.strict||x.value!=="let"||m!=="var")&&this.throwUnexpectedToken(x):(this.context.isModule||this.context.await)&&x.type===3&&x.value==="await"&&this.tolerateUnexpectedToken(x),this.finalize(w,new d.Identifier(x.value))},y.prototype.parseVariableDeclaration=function(m){var w=this.createNode(),x=this.parsePattern([],"var");this.context.strict&&x.type===g.Syntax.Identifier&&this.scanner.isRestrictedWord(x.name)&&this.tolerateError(u.Messages.StrictVarName);var C=null;return this.match("=")?(this.nextToken(),C=this.isolateCoverGrammar(this.parseAssignmentExpression)):x.type===g.Syntax.Identifier||m.inFor||this.expect("="),this.finalize(w,new d.VariableDeclarator(x,C))},y.prototype.parseVariableDeclarationList=function(m){var w={inFor:m.inFor},x=[];for(x.push(this.parseVariableDeclaration(w));this.match(",");)this.nextToken(),x.push(this.parseVariableDeclaration(w));return x},y.prototype.parseVariableStatement=function(){var m=this.createNode();this.expectKeyword("var");var w=this.parseVariableDeclarationList({inFor:!1});return this.consumeSemicolon(),this.finalize(m,new d.VariableDeclaration(w,"var"))},y.prototype.parseEmptyStatement=function(){var m=this.createNode();return this.expect(";"),this.finalize(m,new d.EmptyStatement)},y.prototype.parseExpressionStatement=function(){var m=this.createNode(),w=this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ExpressionStatement(w))},y.prototype.parseIfClause=function(){return this.context.strict&&this.matchKeyword("function")&&this.tolerateError(u.Messages.StrictFunction),this.parseStatement()},y.prototype.parseIfStatement=function(){var m,w=this.createNode(),x=null;this.expectKeyword("if"),this.expect("(");var C=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement)):(this.expect(")"),m=this.parseIfClause(),this.matchKeyword("else")&&(this.nextToken(),x=this.parseIfClause())),this.finalize(w,new d.IfStatement(C,m,x))},y.prototype.parseDoWhileStatement=function(){var m=this.createNode();this.expectKeyword("do");var w=this.context.inIteration;this.context.inIteration=!0;var x=this.parseStatement();this.context.inIteration=w,this.expectKeyword("while"),this.expect("(");var C=this.parseExpression();return!this.match(")")&&this.config.tolerant?this.tolerateUnexpectedToken(this.nextToken()):(this.expect(")"),this.match(";")&&this.nextToken()),this.finalize(m,new d.DoWhileStatement(x,C))},y.prototype.parseWhileStatement=function(){var m,w=this.createNode();this.expectKeyword("while"),this.expect("(");var x=this.parseExpression();if(!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement);else{this.expect(")");var C=this.context.inIteration;this.context.inIteration=!0,m=this.parseStatement(),this.context.inIteration=C}return this.finalize(w,new d.WhileStatement(x,m))},y.prototype.parseForStatement=function(){var m,w,x,C=null,S=null,_=null,T=!0,E=this.createNode();if(this.expectKeyword("for"),this.expect("("),this.match(";"))this.nextToken();else if(this.matchKeyword("var")){C=this.createNode(),this.nextToken();var D=this.context.allowIn;this.context.allowIn=!1;var b=this.parseVariableDeclarationList({inFor:!0});if(this.context.allowIn=D,b.length===1&&this.matchKeyword("in")){var I=b[0];I.init&&(I.id.type===g.Syntax.ArrayPattern||I.id.type===g.Syntax.ObjectPattern||this.context.strict)&&this.tolerateError(u.Messages.ForInOfLoopInitializer,"for-in"),C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.nextToken(),m=C,w=this.parseExpression(),C=null}else b.length===1&&b[0].init===null&&this.matchContextualKeyword("of")?(C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.nextToken(),m=C,w=this.parseAssignmentExpression(),C=null,T=!1):(C=this.finalize(C,new d.VariableDeclaration(b,"var")),this.expect(";"))}else if(this.matchKeyword("const")||this.matchKeyword("let")){C=this.createNode();var P=this.nextToken().value;this.context.strict||this.lookahead.value!=="in"?(D=this.context.allowIn,this.context.allowIn=!1,b=this.parseBindingList(P,{inFor:!0}),this.context.allowIn=D,b.length===1&&b[0].init===null&&this.matchKeyword("in")?(C=this.finalize(C,new d.VariableDeclaration(b,P)),this.nextToken(),m=C,w=this.parseExpression(),C=null):b.length===1&&b[0].init===null&&this.matchContextualKeyword("of")?(C=this.finalize(C,new d.VariableDeclaration(b,P)),this.nextToken(),m=C,w=this.parseAssignmentExpression(),C=null,T=!1):(this.consumeSemicolon(),C=this.finalize(C,new d.VariableDeclaration(b,P)))):(C=this.finalize(C,new d.Identifier(P)),this.nextToken(),m=C,w=this.parseExpression(),C=null)}else{var M=this.lookahead;if(D=this.context.allowIn,this.context.allowIn=!1,C=this.inheritCoverGrammar(this.parseAssignmentExpression),this.context.allowIn=D,this.matchKeyword("in"))this.context.isAssignmentTarget&&C.type!==g.Syntax.AssignmentExpression||this.tolerateError(u.Messages.InvalidLHSInForIn),this.nextToken(),this.reinterpretExpressionAsPattern(C),m=C,w=this.parseExpression(),C=null;else if(this.matchContextualKeyword("of"))this.context.isAssignmentTarget&&C.type!==g.Syntax.AssignmentExpression||this.tolerateError(u.Messages.InvalidLHSInForLoop),this.nextToken(),this.reinterpretExpressionAsPattern(C),m=C,w=this.parseAssignmentExpression(),C=null,T=!1;else{if(this.match(",")){for(var L=[C];this.match(",");)this.nextToken(),L.push(this.isolateCoverGrammar(this.parseAssignmentExpression));C=this.finalize(this.startNode(M),new d.SequenceExpression(L))}this.expect(";")}}if(m===void 0&&(this.match(";")||(S=this.parseExpression()),this.expect(";"),this.match(")")||(_=this.parseExpression())),!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),x=this.finalize(this.createNode(),new d.EmptyStatement);else{this.expect(")");var V=this.context.inIteration;this.context.inIteration=!0,x=this.isolateCoverGrammar(this.parseStatement),this.context.inIteration=V}return m===void 0?this.finalize(E,new d.ForStatement(C,S,_,x)):T?this.finalize(E,new d.ForInStatement(m,w,x)):this.finalize(E,new d.ForOfStatement(m,w,x))},y.prototype.parseContinueStatement=function(){var m=this.createNode();this.expectKeyword("continue");var w=null;if(this.lookahead.type===3&&!this.hasLineTerminator){var x=this.parseVariableIdentifier();w=x;var C="$"+x.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,C)||this.throwError(u.Messages.UnknownLabel,x.name)}return this.consumeSemicolon(),w!==null||this.context.inIteration||this.throwError(u.Messages.IllegalContinue),this.finalize(m,new d.ContinueStatement(w))},y.prototype.parseBreakStatement=function(){var m=this.createNode();this.expectKeyword("break");var w=null;if(this.lookahead.type===3&&!this.hasLineTerminator){var x=this.parseVariableIdentifier(),C="$"+x.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,C)||this.throwError(u.Messages.UnknownLabel,x.name),w=x}return this.consumeSemicolon(),w!==null||this.context.inIteration||this.context.inSwitch||this.throwError(u.Messages.IllegalBreak),this.finalize(m,new d.BreakStatement(w))},y.prototype.parseReturnStatement=function(){this.context.inFunctionBody||this.tolerateError(u.Messages.IllegalReturn);var m=this.createNode();this.expectKeyword("return");var w=(this.match(";")||this.match("}")||this.hasLineTerminator||this.lookahead.type===2)&&this.lookahead.type!==8&&this.lookahead.type!==10?null:this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ReturnStatement(w))},y.prototype.parseWithStatement=function(){this.context.strict&&this.tolerateError(u.Messages.StrictModeWith);var m,w=this.createNode();this.expectKeyword("with"),this.expect("(");var x=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),m=this.finalize(this.createNode(),new d.EmptyStatement)):(this.expect(")"),m=this.parseStatement()),this.finalize(w,new d.WithStatement(x,m))},y.prototype.parseSwitchCase=function(){var m,w=this.createNode();this.matchKeyword("default")?(this.nextToken(),m=null):(this.expectKeyword("case"),m=this.parseExpression()),this.expect(":");for(var x=[];!(this.match("}")||this.matchKeyword("default")||this.matchKeyword("case"));)x.push(this.parseStatementListItem());return this.finalize(w,new d.SwitchCase(m,x))},y.prototype.parseSwitchStatement=function(){var m=this.createNode();this.expectKeyword("switch"),this.expect("(");var w=this.parseExpression();this.expect(")");var x=this.context.inSwitch;this.context.inSwitch=!0;var C=[],S=!1;for(this.expect("{");!this.match("}");){var _=this.parseSwitchCase();_.test===null&&(S&&this.throwError(u.Messages.MultipleDefaultsInSwitch),S=!0),C.push(_)}return this.expect("}"),this.context.inSwitch=x,this.finalize(m,new d.SwitchStatement(w,C))},y.prototype.parseLabelledStatement=function(){var m,w=this.createNode(),x=this.parseExpression();if(x.type===g.Syntax.Identifier&&this.match(":")){this.nextToken();var C=x,S="$"+C.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,S)&&this.throwError(u.Messages.Redeclaration,"Label",C.name),this.context.labelSet[S]=!0;var _=void 0;if(this.matchKeyword("class"))this.tolerateUnexpectedToken(this.lookahead),_=this.parseClassDeclaration();else if(this.matchKeyword("function")){var T=this.lookahead,E=this.parseFunctionDeclaration();this.context.strict?this.tolerateUnexpectedToken(T,u.Messages.StrictFunction):E.generator&&this.tolerateUnexpectedToken(T,u.Messages.GeneratorInLegacyContext),_=E}else _=this.parseStatement();delete this.context.labelSet[S],m=new d.LabeledStatement(C,_)}else this.consumeSemicolon(),m=new d.ExpressionStatement(x);return this.finalize(w,m)},y.prototype.parseThrowStatement=function(){var m=this.createNode();this.expectKeyword("throw"),this.hasLineTerminator&&this.throwError(u.Messages.NewlineAfterThrow);var w=this.parseExpression();return this.consumeSemicolon(),this.finalize(m,new d.ThrowStatement(w))},y.prototype.parseCatchClause=function(){var m=this.createNode();this.expectKeyword("catch"),this.expect("("),this.match(")")&&this.throwUnexpectedToken(this.lookahead);for(var w=[],x=this.parsePattern(w),C={},S=0;S0&&this.tolerateError(u.Messages.BadGetterArity);var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parseSetterMethod=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters();x.params.length!==1?this.tolerateError(u.Messages.BadSetterArity):x.params[0]instanceof d.RestElement&&this.tolerateError(u.Messages.BadSetterRestParameter);var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!1))},y.prototype.parseGeneratorMethod=function(){var m=this.createNode(),w=this.context.allowYield;this.context.allowYield=!0;var x=this.parseFormalParameters();this.context.allowYield=!1;var C=this.parsePropertyMethod(x);return this.context.allowYield=w,this.finalize(m,new d.FunctionExpression(null,x.params,C,!0))},y.prototype.isStartOfExpression=function(){var m=!0,w=this.lookahead.value;switch(this.lookahead.type){case 7:m=w==="["||w==="("||w==="{"||w==="+"||w==="-"||w==="!"||w==="~"||w==="++"||w==="--"||w==="/"||w==="/=";break;case 4:m=w==="class"||w==="delete"||w==="function"||w==="let"||w==="new"||w==="super"||w==="this"||w==="typeof"||w==="void"||w==="yield"}return m},y.prototype.parseYieldExpression=function(){var m=this.createNode();this.expectKeyword("yield");var w=null,x=!1;if(!this.hasLineTerminator){var C=this.context.allowYield;this.context.allowYield=!1,(x=this.match("*"))?(this.nextToken(),w=this.parseAssignmentExpression()):this.isStartOfExpression()&&(w=this.parseAssignmentExpression()),this.context.allowYield=C}return this.finalize(m,new d.YieldExpression(w,x))},y.prototype.parseClassElement=function(m){var w=this.lookahead,x=this.createNode(),C="",S=null,_=null,T=!1,E=!1,D=!1,b=!1;if(this.match("*"))this.nextToken();else if(T=this.match("["),(S=this.parseObjectPropertyKey()).name==="static"&&(this.qualifiedPropertyName(this.lookahead)||this.match("*"))&&(w=this.lookahead,D=!0,T=this.match("["),this.match("*")?this.nextToken():S=this.parseObjectPropertyKey()),w.type===3&&!this.hasLineTerminator&&w.value==="async"){var I=this.lookahead.value;I!==":"&&I!=="("&&I!=="*"&&(b=!0,w=this.lookahead,S=this.parseObjectPropertyKey(),w.type===3&&w.value==="constructor"&&this.tolerateUnexpectedToken(w,u.Messages.ConstructorIsAsync))}var P=this.qualifiedPropertyName(this.lookahead);return w.type===3?w.value==="get"&&P?(C="get",T=this.match("["),S=this.parseObjectPropertyKey(),this.context.allowYield=!1,_=this.parseGetterMethod()):w.value==="set"&&P&&(C="set",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseSetterMethod()):w.type===7&&w.value==="*"&&P&&(C="init",T=this.match("["),S=this.parseObjectPropertyKey(),_=this.parseGeneratorMethod(),E=!0),!C&&S&&this.match("(")&&(C="init",_=b?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),E=!0),C||this.throwUnexpectedToken(this.lookahead),C==="init"&&(C="method"),T||(D&&this.isPropertyKey(S,"prototype")&&this.throwUnexpectedToken(w,u.Messages.StaticPrototype),!D&&this.isPropertyKey(S,"constructor")&&((C!=="method"||!E||_&&_.generator)&&this.throwUnexpectedToken(w,u.Messages.ConstructorSpecialMethod),m.value?this.throwUnexpectedToken(w,u.Messages.DuplicateConstructor):m.value=!0,C="constructor")),this.finalize(x,new d.MethodDefinition(S,T,_,C,D))},y.prototype.parseClassElementList=function(){var m=[],w={value:!1};for(this.expect("{");!this.match("}");)this.match(";")?this.nextToken():m.push(this.parseClassElement(w));return this.expect("}"),m},y.prototype.parseClassBody=function(){var m=this.createNode(),w=this.parseClassElementList();return this.finalize(m,new d.ClassBody(w))},y.prototype.parseClassDeclaration=function(m){var w=this.createNode(),x=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var C=m&&this.lookahead.type!==3?null:this.parseVariableIdentifier(),S=null;this.matchKeyword("extends")&&(this.nextToken(),S=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var _=this.parseClassBody();return this.context.strict=x,this.finalize(w,new d.ClassDeclaration(C,S,_))},y.prototype.parseClassExpression=function(){var m=this.createNode(),w=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var x=this.lookahead.type===3?this.parseVariableIdentifier():null,C=null;this.matchKeyword("extends")&&(this.nextToken(),C=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var S=this.parseClassBody();return this.context.strict=w,this.finalize(m,new d.ClassExpression(x,C,S))},y.prototype.parseModule=function(){this.context.strict=!0,this.context.isModule=!0,this.scanner.isModule=!0;for(var m=this.createNode(),w=this.parseDirectivePrologues();this.lookahead.type!==2;)w.push(this.parseStatementListItem());return this.finalize(m,new d.Module(w))},y.prototype.parseScript=function(){for(var m=this.createNode(),w=this.parseDirectivePrologues();this.lookahead.type!==2;)w.push(this.parseStatementListItem());return this.finalize(m,new d.Script(w))},y.prototype.parseModuleSpecifier=function(){var m=this.createNode();this.lookahead.type!==8&&this.throwError(u.Messages.InvalidModuleSpecifier);var w=this.nextToken(),x=this.getTokenRaw(w);return this.finalize(m,new d.Literal(w.value,x))},y.prototype.parseImportSpecifier=function(){var m,w,x=this.createNode();return this.lookahead.type===3?(w=m=this.parseVariableIdentifier(),this.matchContextualKeyword("as")&&(this.nextToken(),w=this.parseVariableIdentifier())):(w=m=this.parseIdentifierName(),this.matchContextualKeyword("as")?(this.nextToken(),w=this.parseVariableIdentifier()):this.throwUnexpectedToken(this.nextToken())),this.finalize(x,new d.ImportSpecifier(w,m))},y.prototype.parseNamedImports=function(){this.expect("{");for(var m=[];!this.match("}");)m.push(this.parseImportSpecifier()),this.match("}")||this.expect(",");return this.expect("}"),m},y.prototype.parseImportDefaultSpecifier=function(){var m=this.createNode(),w=this.parseIdentifierName();return this.finalize(m,new d.ImportDefaultSpecifier(w))},y.prototype.parseImportNamespaceSpecifier=function(){var m=this.createNode();this.expect("*"),this.matchContextualKeyword("as")||this.throwError(u.Messages.NoAsAfterImportNamespace),this.nextToken();var w=this.parseIdentifierName();return this.finalize(m,new d.ImportNamespaceSpecifier(w))},y.prototype.parseImportDeclaration=function(){this.context.inFunctionBody&&this.throwError(u.Messages.IllegalImportDeclaration);var m,w=this.createNode();this.expectKeyword("import");var x=[];if(this.lookahead.type===8)m=this.parseModuleSpecifier();else{if(this.match("{")?x=x.concat(this.parseNamedImports()):this.match("*")?x.push(this.parseImportNamespaceSpecifier()):this.isIdentifierName(this.lookahead)&&!this.matchKeyword("default")?(x.push(this.parseImportDefaultSpecifier()),this.match(",")&&(this.nextToken(),this.match("*")?x.push(this.parseImportNamespaceSpecifier()):this.match("{")?x=x.concat(this.parseNamedImports()):this.throwUnexpectedToken(this.lookahead))):this.throwUnexpectedToken(this.nextToken()),!this.matchContextualKeyword("from")){var C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause;this.throwError(C,this.lookahead.value)}this.nextToken(),m=this.parseModuleSpecifier()}return this.consumeSemicolon(),this.finalize(w,new d.ImportDeclaration(x,m))},y.prototype.parseExportSpecifier=function(){var m=this.createNode(),w=this.parseIdentifierName(),x=w;return this.matchContextualKeyword("as")&&(this.nextToken(),x=this.parseIdentifierName()),this.finalize(m,new d.ExportSpecifier(w,x))},y.prototype.parseExportDeclaration=function(){this.context.inFunctionBody&&this.throwError(u.Messages.IllegalExportDeclaration);var m,w=this.createNode();if(this.expectKeyword("export"),this.matchKeyword("default"))if(this.nextToken(),this.matchKeyword("function")){var x=this.parseFunctionDeclaration(!0);m=this.finalize(w,new d.ExportDefaultDeclaration(x))}else this.matchKeyword("class")?(x=this.parseClassDeclaration(!0),m=this.finalize(w,new d.ExportDefaultDeclaration(x))):this.matchContextualKeyword("async")?(x=this.matchAsyncFunction()?this.parseFunctionDeclaration(!0):this.parseAssignmentExpression(),m=this.finalize(w,new d.ExportDefaultDeclaration(x))):(this.matchContextualKeyword("from")&&this.throwError(u.Messages.UnexpectedToken,this.lookahead.value),x=this.match("{")?this.parseObjectInitializer():this.match("[")?this.parseArrayInitializer():this.parseAssignmentExpression(),this.consumeSemicolon(),m=this.finalize(w,new d.ExportDefaultDeclaration(x)));else if(this.match("*")){if(this.nextToken(),!this.matchContextualKeyword("from")){var C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause;this.throwError(C,this.lookahead.value)}this.nextToken();var S=this.parseModuleSpecifier();this.consumeSemicolon(),m=this.finalize(w,new d.ExportAllDeclaration(S))}else if(this.lookahead.type===4){switch(x=void 0,this.lookahead.value){case"let":case"const":x=this.parseLexicalDeclaration({inFor:!1});break;case"var":case"class":case"function":x=this.parseStatementListItem();break;default:this.throwUnexpectedToken(this.lookahead)}m=this.finalize(w,new d.ExportNamedDeclaration(x,[],null))}else if(this.matchAsyncFunction())x=this.parseFunctionDeclaration(),m=this.finalize(w,new d.ExportNamedDeclaration(x,[],null));else{var _=[],T=null,E=!1;for(this.expect("{");!this.match("}");)E=E||this.matchKeyword("default"),_.push(this.parseExportSpecifier()),this.match("}")||this.expect(",");this.expect("}"),this.matchContextualKeyword("from")?(this.nextToken(),T=this.parseModuleSpecifier(),this.consumeSemicolon()):E?(C=this.lookahead.value?u.Messages.UnexpectedToken:u.Messages.MissingFromClause,this.throwError(C,this.lookahead.value)):this.consumeSemicolon(),m=this.finalize(w,new d.ExportNamedDeclaration(null,_,T))}return m},y}();s.Parser=v},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.assert=function(c,l){if(!c)throw new Error("ASSERT: "+l)}},function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var c=function(){function l(){this.errors=[],this.tolerant=!1}return l.prototype.recordError=function(f){this.errors.push(f)},l.prototype.tolerate=function(f){if(!this.tolerant)throw f;this.recordError(f)},l.prototype.constructError=function(f,u){var d=new Error(f);try{throw d}catch(h){Object.create&&Object.defineProperty&&(d=Object.create(h),Object.defineProperty(d,"column",{value:u}))}return d},l.prototype.createError=function(f,u,d,h){var g="Line "+u+": "+h,p=this.constructError(g,d);return p.index=f,p.lineNumber=u,p.description=h,p},l.prototype.throwError=function(f,u,d,h){throw this.createError(f,u,d,h)},l.prototype.tolerateError=function(f,u,d,h){var g=this.createError(f,u,d,h);if(!this.tolerant)throw g;this.recordError(g)},l}();s.ErrorHandler=c},function(a,s){Object.defineProperty(s,"__esModule",{value:!0}),s.Messages={BadGetterArity:"Getter must not have any formal parameters",BadSetterArity:"Setter must have exactly one formal parameter",BadSetterRestParameter:"Setter function argument must not be a rest parameter",ConstructorIsAsync:"Class constructor may not be an async method",ConstructorSpecialMethod:"Class constructor may not be an accessor",DeclarationMissingInitializer:"Missing initializer in %0 declaration",DefaultRestParameter:"Unexpected token =",DuplicateBinding:"Duplicate binding %0",DuplicateConstructor:"A class may only have one constructor",DuplicateProtoProperty:"Duplicate __proto__ fields are not allowed in object literals",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInLegacyContext:"Generator declarations are not allowed in legacy contexts",IllegalBreak:"Illegal break statement",IllegalContinue:"Illegal continue statement",IllegalExportDeclaration:"Unexpected token",IllegalImportDeclaration:"Unexpected token",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"Illegal return statement",InvalidEscapedReservedWord:"Keyword must not contain escaped characters",InvalidHexEscapeSequence:"Invalid hexadecimal escape sequence",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",InvalidLHSInForLoop:"Invalid left-hand side in for-loop",InvalidModuleSpecifier:"Unexpected token",InvalidRegExp:"Invalid regular expression",LetInLexicalBinding:"let is disallowed as a lexically bound name",MissingFromClause:"Unexpected token",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NewlineAfterThrow:"Illegal newline after throw",NoAsAfterImportNamespace:"Unexpected token",NoCatchOrFinally:"Missing catch or finally after try",ParameterAfterRestParameter:"Rest parameter must be last formal parameter",Redeclaration:"%0 '%1' has already been declared",StaticPrototype:"Classes may not have static property named prototype",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictModeWith:"Strict mode code may not include a with statement",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",TemplateOctalLiteral:"Octal literals are not allowed in template strings.",UnexpectedEOS:"Unexpected end of input",UnexpectedIdentifier:"Unexpected identifier",UnexpectedNumber:"Unexpected number",UnexpectedReserved:"Unexpected reserved word",UnexpectedString:"Unexpected string",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedToken:"Unexpected token %0",UnexpectedTokenIllegal:"Unexpected token ILLEGAL",UnknownLabel:"Undefined label '%0'",UnterminatedRegExp:"Invalid regular expression: missing /"}},function(a,s,c){Object.defineProperty(s,"__esModule",{value:!0});var l=c(9),f=c(4),u=c(11);function d(p){return"0123456789abcdef".indexOf(p.toLowerCase())}function h(p){return"01234567".indexOf(p)}var g=function(){function p(v,y){this.source=v,this.errorHandler=y,this.trackComment=!1,this.isModule=!1,this.length=v.length,this.index=0,this.lineNumber=v.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return p.prototype.saveState=function(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart}},p.prototype.restoreState=function(v){this.index=v.index,this.lineNumber=v.lineNumber,this.lineStart=v.lineStart},p.prototype.eof=function(){return this.index>=this.length},p.prototype.throwUnexpectedToken=function(v){return v===void 0&&(v=u.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,v)},p.prototype.tolerateUnexpectedToken=function(v){v===void 0&&(v=u.Messages.UnexpectedTokenIllegal),this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,v)},p.prototype.skipSingleLineComment=function(v){var y,m,w=[];for(this.trackComment&&(w=[],y=this.index-v,m={start:{line:this.lineNumber,column:this.index-this.lineStart-v},end:{}});!this.eof();){var x=this.source.charCodeAt(this.index);if(++this.index,f.Character.isLineTerminator(x)){if(this.trackComment){m.end={line:this.lineNumber,column:this.index-this.lineStart-1};var C={multiLine:!1,slice:[y+v,this.index-1],range:[y,this.index-1],loc:m};w.push(C)}return x===13&&this.source.charCodeAt(this.index)===10&&++this.index,++this.lineNumber,this.lineStart=this.index,w}}return this.trackComment&&(m.end={line:this.lineNumber,column:this.index-this.lineStart},C={multiLine:!1,slice:[y+v,this.index],range:[y,this.index],loc:m},w.push(C)),w},p.prototype.skipMultiLineComment=function(){var v,y,m=[];for(this.trackComment&&(m=[],v=this.index-2,y={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var w=this.source.charCodeAt(this.index);if(f.Character.isLineTerminator(w))w===13&&this.source.charCodeAt(this.index+1)===10&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(w===42){if(this.source.charCodeAt(this.index+1)===47){if(this.index+=2,this.trackComment){y.end={line:this.lineNumber,column:this.index-this.lineStart};var x={multiLine:!0,slice:[v+2,this.index-2],range:[v,this.index],loc:y};m.push(x)}return m}++this.index}else++this.index}return this.trackComment&&(y.end={line:this.lineNumber,column:this.index-this.lineStart},x={multiLine:!0,slice:[v+2,this.index],range:[v,this.index],loc:y},m.push(x)),this.tolerateUnexpectedToken(),m},p.prototype.scanComments=function(){var v;this.trackComment&&(v=[]);for(var y=this.index===0;!this.eof();){var m=this.source.charCodeAt(this.index);if(f.Character.isWhiteSpace(m))++this.index;else if(f.Character.isLineTerminator(m))++this.index,m===13&&this.source.charCodeAt(this.index)===10&&++this.index,++this.lineNumber,this.lineStart=this.index,y=!0;else if(m===47)if((m=this.source.charCodeAt(this.index+1))===47){this.index+=2;var w=this.skipSingleLineComment(2);this.trackComment&&(v=v.concat(w)),y=!0}else{if(m!==42)break;this.index+=2,w=this.skipMultiLineComment(),this.trackComment&&(v=v.concat(w))}else if(y&&m===45){if(this.source.charCodeAt(this.index+1)!==45||this.source.charCodeAt(this.index+2)!==62)break;this.index+=3,w=this.skipSingleLineComment(3),this.trackComment&&(v=v.concat(w))}else{if(m!==60||this.isModule||this.source.slice(this.index+1,this.index+4)!=="!--")break;this.index+=4,w=this.skipSingleLineComment(4),this.trackComment&&(v=v.concat(w))}}return v},p.prototype.isFutureReservedWord=function(v){switch(v){case"enum":case"export":case"import":case"super":return!0;default:return!1}},p.prototype.isStrictModeReservedWord=function(v){switch(v){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},p.prototype.isRestrictedWord=function(v){return v==="eval"||v==="arguments"},p.prototype.isKeyword=function(v){switch(v.length){case 2:return v==="if"||v==="in"||v==="do";case 3:return v==="var"||v==="for"||v==="new"||v==="try"||v==="let";case 4:return v==="this"||v==="else"||v==="case"||v==="void"||v==="with"||v==="enum";case 5:return v==="while"||v==="break"||v==="catch"||v==="throw"||v==="const"||v==="yield"||v==="class"||v==="super";case 6:return v==="return"||v==="typeof"||v==="delete"||v==="switch"||v==="export"||v==="import";case 7:return v==="default"||v==="finally"||v==="extends";case 8:return v==="function"||v==="continue"||v==="debugger";case 10:return v==="instanceof";default:return!1}},p.prototype.codePointAt=function(v){var y=this.source.charCodeAt(v);if(y>=55296&&y<=56319){var m=this.source.charCodeAt(v+1);m>=56320&&m<=57343&&(y=1024*(y-55296)+m-56320+65536)}return y},p.prototype.scanHexEscape=function(v){for(var y=v==="u"?4:2,m=0,w=0;w1114111||v!=="}")&&this.throwUnexpectedToken(),f.Character.fromCodePoint(y)},p.prototype.getIdentifier=function(){for(var v=this.index++;!this.eof();){var y=this.source.charCodeAt(this.index);if(y===92)return this.index=v,this.getComplexIdentifier();if(y>=55296&&y<57343)return this.index=v,this.getComplexIdentifier();if(!f.Character.isIdentifierPart(y))break;++this.index}return this.source.slice(v,this.index)},p.prototype.getComplexIdentifier=function(){var v,y=this.codePointAt(this.index),m=f.Character.fromCodePoint(y);for(this.index+=m.length,y===92&&(this.source.charCodeAt(this.index)!==117&&this.throwUnexpectedToken(),++this.index,this.source[this.index]==="{"?(++this.index,v=this.scanUnicodeCodePointEscape()):(v=this.scanHexEscape("u"))!==null&&v!=="\\"&&f.Character.isIdentifierStart(v.charCodeAt(0))||this.throwUnexpectedToken(),m=v);!this.eof()&&(y=this.codePointAt(this.index),f.Character.isIdentifierPart(y));)m+=v=f.Character.fromCodePoint(y),this.index+=v.length,y===92&&(m=m.substr(0,m.length-1),this.source.charCodeAt(this.index)!==117&&this.throwUnexpectedToken(),++this.index,this.source[this.index]==="{"?(++this.index,v=this.scanUnicodeCodePointEscape()):(v=this.scanHexEscape("u"))!==null&&v!=="\\"&&f.Character.isIdentifierPart(v.charCodeAt(0))||this.throwUnexpectedToken(),m+=v);return m},p.prototype.octalToDecimal=function(v){var y=v!=="0",m=h(v);return!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(y=!0,m=8*m+h(this.source[this.index++]),"0123".indexOf(v)>=0&&!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(m=8*m+h(this.source[this.index++]))),{code:m,octal:y}},p.prototype.scanIdentifier=function(){var v,y=this.index,m=this.source.charCodeAt(y)===92?this.getComplexIdentifier():this.getIdentifier();if((v=m.length===1?3:this.isKeyword(m)?4:m==="null"?5:m==="true"||m==="false"?1:3)!=3&&y+m.length!==this.index){var w=this.index;this.index=y,this.tolerateUnexpectedToken(u.Messages.InvalidEscapedReservedWord),this.index=w}return{type:v,value:m,lineNumber:this.lineNumber,lineStart:this.lineStart,start:y,end:this.index}},p.prototype.scanPunctuator=function(){var v=this.index,y=this.source[this.index];switch(y){case"(":case"{":y==="{"&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,this.source[this.index]==="."&&this.source[this.index+1]==="."&&(this.index+=2,y="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:(y=this.source.substr(this.index,4))===">>>="?this.index+=4:(y=y.substr(0,3))==="==="||y==="!=="||y===">>>"||y==="<<="||y===">>="||y==="**="?this.index+=3:(y=y.substr(0,2))==="&&"||y==="||"||y==="=="||y==="!="||y==="+="||y==="-="||y==="*="||y==="/="||y==="++"||y==="--"||y==="<<"||y===">>"||y==="&="||y==="|="||y==="^="||y==="%="||y==="<="||y===">="||y==="=>"||y==="**"?this.index+=2:(y=this.source[this.index],"<>=!+-*%&|^/".indexOf(y)>=0&&++this.index)}return this.index===v&&this.throwUnexpectedToken(),{type:7,value:y,lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanHexLiteral=function(v){for(var y="";!this.eof()&&f.Character.isHexDigit(this.source.charCodeAt(this.index));)y+=this.source[this.index++];return y.length===0&&this.throwUnexpectedToken(),f.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:6,value:parseInt("0x"+y,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanBinaryLiteral=function(v){for(var y,m="";!this.eof()&&((y=this.source[this.index])==="0"||y==="1");)m+=this.source[this.index++];return m.length===0&&this.throwUnexpectedToken(),this.eof()||(y=this.source.charCodeAt(this.index),(f.Character.isIdentifierStart(y)||f.Character.isDecimalDigit(y))&&this.throwUnexpectedToken()),{type:6,value:parseInt(m,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:v,end:this.index}},p.prototype.scanOctalLiteral=function(v,y){var m="",w=!1;for(f.Character.isOctalDigit(v.charCodeAt(0))?(w=!0,m="0"+this.source[this.index++]):++this.index;!this.eof()&&f.Character.isOctalDigit(this.source.charCodeAt(this.index));)m+=this.source[this.index++];return w||m.length!==0||this.throwUnexpectedToken(),(f.Character.isIdentifierStart(this.source.charCodeAt(this.index))||f.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:6,value:parseInt(m,8),octal:w,lineNumber:this.lineNumber,lineStart:this.lineStart,start:y,end:this.index}},p.prototype.isImplicitOctalLiteral=function(){for(var v=this.index+1;v0?M.charCodeAt(k-1):null,Ee=Ee&&w(F,j)}else{for(k=0;kG&&M[pe+1]!==" ",pe=k);else if(!m(F))return 5;j=k>0?M.charCodeAt(k-1):null,Ee=Ee&&w(F,j)}ue=ue||ce&&k-pe-1>G&&M[pe+1]!==" "}return re||ue?V>9&&x(M)?5:ue?4:3:Ee&&!A(M)?1:2}function S(M,L,V,G){M.dump=function(){if(L.length===0)return"''";if(!M.noCompatMode&&d.indexOf(L)!==-1)return"'"+L+"'";var A=M.indent*Math.max(1,V),k=M.lineWidth===-1?-1:Math.max(Math.min(M.lineWidth,40),M.lineWidth-A),F=G||M.flowLevel>-1&&V>=M.flowLevel;switch(C(L,F,M.indent,k,function(j){return function(Y,re){var ue,ce;for(ue=0,ce=Y.implicitTypes.length;ue"+_(L,M.indent)+T(p(function(j,Y){for(var re,ue,ce=/(\n+)([^\n]*)/g,pe=(Oe=j.indexOf(` `),Oe=Oe!==-1?Oe:j.length,ce.lastIndex=Oe,E(j.slice(0,Oe),Y)),Ee=j[0]===` -`||j[0]===" ",Oe;ue=ce.exec(j);){var Se=ue[1],B=ue[2];re=B[0]===" ",pe+=Se+(Ee||re||B===""?"":` +`||j[0]===" ",Oe;ue=ce.exec(j);){var _e=ue[1],B=ue[2];re=B[0]===" ",pe+=_e+(Ee||re||B===""?"":` `)+E(B,Y),Ee=re}return pe}(L,k),A));case 5:return'"'+function(j){for(var Y,re,ue,ce="",pe=0;pe=55296&&Y<=56319&&(re=j.charCodeAt(pe+1))>=56320&&re<=57343?(ce+=h(1024*(Y-55296)+re-56320+65536),pe++):(ue=u[Y],ce+=!ue&&m(Y)?j[pe]:ue||h(Y));return ce}(L)+'"';default:throw new a("impossible error: invalid scalar style")}}()}function _(M,L){var V=x(M)?String(L):"",G=M[M.length-1]===` `;return V+(G&&(M[M.length-2]===` `||M===` @@ -3446,8 +3446,8 @@ Input: `+this.err.str)},c.prototype[Symbol.iterator]=function(){return this._ind `?M.slice(0,-1):M}function E(M,L){if(M===""||M[0]===" ")return M;for(var V,G,A=/ [^ ]/g,k=0,F=0,j=0,Y="";V=A.exec(M);)(j=V.index)-k>L&&(G=F>k?F:j,Y+=` `+M.slice(k,G),k=G+1),F=j;return Y+=` `,M.length-k>L&&F>k?Y+=M.slice(k,F)+` -`+M.slice(F+1):Y+=M.slice(k),Y.slice(1)}function D(M,L,V){var G,A,k,F,j,Y;for(k=0,F=(A=V?M.explicitTypes:M.implicitTypes).length;k tag resolver accepts not "'+Y+'" style');G=j.represent[Y](L,Y)}M.dump=G}return!0}return!1}function b(M,L,V,G,A,k){M.tag=null,M.dump=V,D(M,V,!1)||D(M,V,!0);var F=l.call(M.dump);G&&(G=M.flowLevel<0||M.flowLevel>L);var j,Y,re=F==="[object Object]"||F==="[object Array]";if(re&&(Y=(j=M.duplicates.indexOf(V))!==-1),(M.tag!==null&&M.tag!=="?"||Y||M.indent!==2&&L>0)&&(A=!1),Y&&M.usedDuplicates[j])M.dump="*ref_"+j;else{if(re&&Y&&!M.usedDuplicates[j]&&(M.usedDuplicates[j]=!0),F==="[object Object]")G&&Object.keys(M.dump).length!==0?(function(ce,pe,Ee,Oe){var Se,B,O,z,W,K,Z="",ee=ce.tag,xe=Object.keys(Ee);if(ce.sortKeys===!0)xe.sort();else if(typeof ce.sortKeys=="function")xe.sort(ce.sortKeys);else if(ce.sortKeys)throw new a("sortKeys must be a boolean or a function");for(Se=0,B=xe.length;Se1024)&&(ce.dump&&ce.dump.charCodeAt(0)===10?K+="?":K+="? "),K+=ce.dump,W&&(K+=v(ce,pe)),b(ce,pe+1,z,!0,W)&&(ce.dump&&ce.dump.charCodeAt(0)===10?K+=":":K+=": ",Z+=K+=ce.dump));ce.tag=ee,ce.dump=Z||"{}"}(M,L,M.dump,A),Y&&(M.dump="&ref_"+j+M.dump)):(function(ce,pe,Ee){var Oe,Se,B,O,z,W="",K=ce.tag,Z=Object.keys(Ee);for(Oe=0,Se=Z.length;Oe1024&&(z+="? "),z+=ce.dump+(ce.condenseFlow?'"':"")+":"+(ce.condenseFlow?"":" "),b(ce,pe,O,!1,!1)&&(W+=z+=ce.dump));ce.tag=K,ce.dump="{"+W+"}"}(M,L,M.dump),Y&&(M.dump="&ref_"+j+" "+M.dump));else if(F==="[object Array]"){var ue=M.noArrayIndent&&L>0?L-1:L;G&&M.dump.length!==0?(function(ce,pe,Ee,Oe){var Se,B,O="",z=ce.tag;for(Se=0,B=Ee.length;Se "+M.dump)}return!0}function I(M,L){var V,G,A=[],k=[];for(function F(j,Y,re){var ue,ce,pe;if(j!==null&&typeof j=="object")if((ce=Y.indexOf(j))!==-1)re.indexOf(ce)===-1&&re.push(ce);else if(Y.push(j),Array.isArray(j))for(ce=0,pe=j.length;ce=C.length&&(C=void 0),{value:C&&C[T++],done:!C}}};throw new TypeError(S?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(C,S){var _=typeof Symbol=="function"&&C[Symbol.iterator];if(!_)return C;var T,E,D=_.call(C),b=[];try{for(;(S===void 0||S-- >0)&&!(T=D.next()).done;)b.push(T.value)}catch(I){E={error:I}}finally{try{T&&!T.done&&(_=D.return)&&_.call(D)}finally{if(E)throw E.error}}return b};Object.defineProperty(n,"__esModule",{value:!0});var l=i(91),f=i(1),u=i(183),d=i(0),h=i(7),g=i(95),p=i(69),v=i(3),y=i(305),m=i(306),w=i(307),x=function(C){function S(_,T){T===void 0&&(T=!1);var E=C.call(this)||this;return E._hasDeclaration=!1,E._docTypeName="",E._hasDocumentElement=!1,E._currentElementSerialized=!1,E._openTags=[],E._ended=!1,E._fragment=T,E._options=f.applyDefaults(_||{},l.DefaultXMLBuilderCBOptions),E._builderOptions={defaultNamespace:E._options.defaultNamespace,namespaceAlias:E._options.namespaceAlias},E._options.format==="json"?E._writer=new m.JSONCBWriter(E._options):E._options.format==="yaml"?E._writer=new w.YAMLCBWriter(E._options):E._writer=new y.XMLCBWriter(E._options),E._options.data!==void 0&&E.on("data",E._options.data),E._options.end!==void 0&&E.on("end",E._options.end),E._options.error!==void 0&&E.on("error",E._options.error),E._prefixMap=new g.NamespacePrefixMap,E._prefixMap.set("xml",h.namespace.XML),E._prefixIndex={value:1},E._push(E._writer.frontMatter()),E}return a(S,C),S.prototype.ele=function(_,T,E){var D,b;if(f.isObject(_)||f.isString(_)&&(/^\s*/g,">");return this._push(this._writer.text(E)),this},S.prototype.ins=function(_,T){var E;T===void 0&&(T=""),this._serializeOpenTag(!0);try{E=u.fragment(this._builderOptions).ins(_,T).first().node}catch(D){return this.emit("error",D),this}return this._options.wellFormed&&(E.target.indexOf(":")!==-1||/^xml$/i.test(E.target))?(this.emit("error",new Error("Processing instruction target contains invalid characters (well-formed required).")),this):this._options.wellFormed&&!d.xml_isLegalChar(E.data)?(this.emit("error",Error("Processing instruction data contains invalid characters (well-formed required).")),this):(this._push(this._writer.instruction(E.target,E.data)),this)},S.prototype.dat=function(_){var T;this._serializeOpenTag(!0);try{T=u.fragment(this._builderOptions).dat(_).first().node}catch(E){return this.emit("error",E),this}return this._push(this._writer.cdata(T.data)),this},S.prototype.dec=function(_){return _===void 0&&(_={version:"1.0"}),this._fragment?(this.emit("error",Error("Cannot insert an XML declaration into a document fragment.")),this):this._hasDeclaration?(this.emit("error",Error("XML declaration is already inserted.")),this):(this._push(this._writer.declaration(_.version||"1.0",_.encoding,_.standalone)),this._hasDeclaration=!0,this)},S.prototype.dtd=function(_){if(this._fragment)return this.emit("error",Error("Cannot insert a DocType declaration into a document fragment.")),this;if(this._docTypeName!=="")return this.emit("error",new Error("DocType declaration is already inserted.")),this;if(this._hasDocumentElement)return this.emit("error",new Error("Cannot insert DocType declaration after document element.")),this;var T;try{T=u.create().dtd(_).first().node}catch(E){return this.emit("error",E),this}return this._options.wellFormed&&!d.xml_isPubidChar(T.publicId)?(this.emit("error",new Error("DocType public identifier does not match PubidChar construct (well-formed required).")),this):this._options.wellFormed&&(!d.xml_isLegalChar(T.systemId)||T.systemId.indexOf('"')!==-1&&T.systemId.indexOf("'")!==-1)?(this.emit("error",new Error("DocType system identifier contains invalid characters (well-formed required).")),this):(this._docTypeName=_.name,this._push(this._writer.docType(_.name,T.publicId,T.systemId)),this)},S.prototype.import=function(_){var T,E,D=u.fragment().set(this._options);try{D.import(_)}catch(M){return this.emit("error",M),this}try{for(var b=s(D.node.childNodes),I=b.next();!I.done;I=b.next()){var P=I.value;this._fromNode(P)}}catch(M){T={error:M}}finally{try{I&&!I.done&&(E=b.return)&&E.call(b)}finally{if(T)throw T.error}}return this},S.prototype.up=function(){return this._serializeOpenTag(!1),this._serializeCloseTag(),this},S.prototype.end=function(){for(this._serializeOpenTag(!1);this._openTags.length>0;)this._serializeCloseTag();return this._push(null),this},S.prototype._serializeOpenTag=function(_){if(!this._currentElementSerialized&&this._currentElement!==void 0){var T=this._currentElement.node;if(!this._options.wellFormed||T.localName.indexOf(":")===-1&&d.xml_isName(T.localName)){var E="",D=!1,b=this._prefixMap.copy(),I={},P=this._recordNamespaceInformation(T,b,I),M=this._openTags.length===0?null:this._openTags[this._openTags.length-1][1],L=T.namespaceURI;if(L===null&&(L=M),M===L)P!==null&&(D=!0),E=L===h.namespace.XML?"xml:"+T.localName:T.localName,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E));else{var V=T.prefix,G=null;if(V===null&&L===P||(G=b.get(V,L)),V==="xmlns"){if(this._options.wellFormed)return void this.emit("error",new Error("An element cannot have the 'xmlns' prefix (well-formed required)."));G=V}G!==null?(E=G+":"+T.localName,P!==null&&P!==h.namespace.XML&&(M=P||null),this._writer.beginElement(E),this._push(this._writer.openTagBegin(E))):V!==null?(V in I&&(V=this._generatePrefix(L,b,this._prefixIndex)),b.set(V,L),E+=V+":"+T.localName,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)),this._push(this._writer.attribute("xmlns:"+V,this._serializeAttributeValue(L,this._options.wellFormed))),P!==null&&(M=P||null)):P===null||P!==null&&P!==L?(D=!0,E+=T.localName,M=L,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)),this._push(this._writer.attribute("xmlns",this._serializeAttributeValue(L,this._options.wellFormed)))):(E+=T.localName,M=L,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)))}this._serializeAttributes(T,b,this._prefixIndex,I,D,this._options.wellFormed);var A=L===h.namespace.HTML;A&&!_&&S._VoidElementNames.has(T.localName)?(this._push(this._writer.openTagEnd(E,!0,!0)),this._writer.endElement(E)):A||_?this._push(this._writer.openTagEnd(E,!1,!1)):(this._push(this._writer.openTagEnd(E,!0,!1)),this._writer.endElement(E)),this._currentElementSerialized=!0,this._openTags.push([E,M,this._prefixMap,_]),this._isPrefixMapModified(this._prefixMap,b)&&(this._prefixMap=b),this._writer.level++}else this.emit("error",new Error("Node local name contains invalid characters (well-formed required)."))}},S.prototype._serializeCloseTag=function(){this._writer.level--;var _=this._openTags.pop();if(_!==void 0){var T=c(_,4),E=T[0],D=(T[1],T[2]),b=T[3];this._prefixMap=D,b&&(this._push(this._writer.closeTag(E)),this._writer.endElement(E))}else this.emit("error",new Error("Last element is undefined."))},S.prototype._push=function(_){_===null?(this._ended=!0,this.emit("end")):this._ended?this.emit("error",new Error("Cannot push to ended stream.")):_.length!==0&&(this._writer.hasData=!0,this.emit("data",_,this._writer.level))},S.prototype._fromNode=function(_){var T,E,D,b;if(v.Guard.isElementNode(_)){var I=_.prefix?_.prefix+":"+_.localName:_.localName;_.namespaceURI!==null?this.ele(_.namespaceURI,I):this.ele(I);try{for(var P=s(_.attributes),M=P.next();!M.done;M=P.next()){var L=M.value,V=L.prefix?L.prefix+":"+L.localName:L.localName;L.namespaceURI!==null?this.att(L.namespaceURI,V,L.value):this.att(V,L.value)}}catch(F){T={error:F}}finally{try{M&&!M.done&&(E=P.return)&&E.call(P)}finally{if(T)throw T.error}}try{for(var G=s(_.childNodes),A=G.next();!A.done;A=G.next()){var k=A.value;this._fromNode(k)}}catch(F){D={error:F}}finally{try{A&&!A.done&&(b=G.return)&&b.call(G)}finally{if(D)throw D.error}}this.up()}else v.Guard.isExclusiveTextNode(_)&&_.data?this.txt(_.data):v.Guard.isCommentNode(_)?this.com(_.data):v.Guard.isCDATASectionNode(_)?this.dat(_.data):v.Guard.isProcessingInstructionNode(_)&&this.ins(_.target,_.data)},S.prototype._serializeAttributes=function(_,T,E,D,b,I){var P,M,L=I?new p.LocalNameSet:void 0;try{for(var V=s(_.attributes),G=V.next();!G.done;G=V.next()){var A=G.value;if(I||b||A.namespaceURI!==null){if(I&&L&&L.has(A.namespaceURI,A.localName))return void this.emit("error",new Error("Element contains duplicate attributes (well-formed required)."));I&&L&&L.set(A.namespaceURI,A.localName);var k=A.namespaceURI,F=null;if(k!==null)if(F=T.get(A.prefix,k),k===h.namespace.XMLNS){if(A.value===h.namespace.XML||A.prefix===null&&b||A.prefix!==null&&(!(A.localName in D)||D[A.localName]!==A.value)&&T.has(A.localName,A.value))continue;if(I&&A.value===h.namespace.XMLNS)return void this.emit("error",new Error("XMLNS namespace is reserved (well-formed required)."));if(I&&A.value==="")return void this.emit("error",new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required)."));A.prefix==="xmlns"&&(F="xmlns")}else F===null&&(F=A.prefix===null||T.hasPrefix(A.prefix)&&!T.has(A.prefix,k)?this._generatePrefix(k,T,E):A.prefix,this._push(this._writer.attribute("xmlns:"+F,this._serializeAttributeValue(k,this._options.wellFormed))));if(I&&(A.localName.indexOf(":")!==-1||!d.xml_isName(A.localName)||A.localName==="xmlns"&&k===null))return void this.emit("error",new Error("Attribute local name contains invalid characters (well-formed required)."));this._push(this._writer.attribute((F!==null?F+":":"")+A.localName,this._serializeAttributeValue(A.value,this._options.wellFormed)))}else this._push(this._writer.attribute(A.localName,this._serializeAttributeValue(A.value,this._options.wellFormed)))}}catch(j){P={error:j}}finally{try{G&&!G.done&&(M=V.return)&&M.call(V)}finally{if(P)throw P.error}}},S.prototype._serializeAttributeValue=function(_,T){return T&&_!==null&&!d.xml_isLegalChar(_)?(this.emit("error",new Error("Invalid characters in attribute value.")),""):_===null?"":_.replace(/(?!&(lt|gt|amp|apos|quot);)&/g,"&").replace(//g,">").replace(/"/g,""")},S.prototype._recordNamespaceInformation=function(_,T,E){var D,b,I=null;try{for(var P=s(_.attributes),M=P.next();!M.done;M=P.next()){var L=M.value,V=L.namespaceURI,G=L.prefix;if(V===h.namespace.XMLNS){if(G===null){I=L.value;continue}var A=L.localName,k=L.value;if(k===h.namespace.XML||(k===""&&(k=null),T.has(A,k)))continue;T.set(A,k),E[A]=k||""}}}catch(F){D={error:F}}finally{try{M&&!M.done&&(b=P.return)&&b.call(P)}finally{if(D)throw D.error}}return I},S.prototype._generatePrefix=function(_,T,E){var D="ns"+E.value;return E.value++,T.set(D,_),D},S.prototype._isPrefixMapModified=function(_,T){var E=_._items,D=T._items,b=_._nullItems,I=T._nullItems;for(var P in D){var M=E[P];if(M===void 0)return!0;var L=D[P];if(M.length!==L.length)return!0;for(var V=0;V':u?"':d?"':""},l.prototype.comment=function(f){return this._beginLine()+""},l.prototype.text=function(f){return this._beginLine()+f},l.prototype.instruction=function(f,u){return u?this._beginLine()+"":this._beginLine()+""},l.prototype.cdata=function(f){return this._beginLine()+""},l.prototype.openTagBegin=function(f){return this._lineLength+=1+f.length,this._beginLine()+"<"+f},l.prototype.openTagEnd=function(f,u,d){return d?" />":u?this._writerOptions.allowEmptyTags?">":this._writerOptions.spaceBeforeSlash?" />":"/>":">"},l.prototype.closeTag=function(f){return this._beginLine()+""},l.prototype.attribute=function(f,u){var d=f+'="'+u+'"';return this._writerOptions.prettyPrint&&this._writerOptions.width>0&&this._lineLength+1+d.length>this._writerOptions.width?(d=this._beginLine()+this._indent(1)+d,this._lineLength=d.length,d):(this._lineLength+=1+d.length," "+d)},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){},l.prototype._beginLine=function(){if(this._writerOptions.prettyPrint){var f=(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level);return this._lineLength=f.length,f}return""},l.prototype._indent=function(f){return f<=0?"":this._writerOptions.indent.repeat(f)},l}(i(114).BaseCBWriter);n.XMLCBWriter=s},function(r,n,i){i(74);var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(f){var u=c.call(this,f)||this;return u._hasChildren=[],u._additionalLevel=0,u}return a(l,c),l.prototype.frontMatter=function(){return""},l.prototype.declaration=function(f,u,d){return""},l.prototype.docType=function(f,u,d){return""},l.prototype.comment=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.comment)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.text=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.text)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.instruction=function(f,u){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.ins)+this._sep()+this._val(u?f+" "+u:f)+this._sep()+"}"},l.prototype.cdata=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.cdata)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.attribute=function(f,u){return this._comma()+this._beginLine(1)+"{"+this._sep()+this._key(this._builderOptions.convert.att+f)+this._sep()+this._val(u)+this._sep()+"}"},l.prototype.openTagBegin=function(f){var u=this._comma()+this._beginLine()+"{"+this._sep()+this._key(f)+this._sep()+"{";return this._additionalLevel++,this.hasData=!0,u+=this._beginLine()+this._key(this._builderOptions.convert.text)+this._sep()+"[",this._hasChildren.push(!1),u},l.prototype.openTagEnd=function(f,u,d){if(u){var h=this._sep()+"]";return this._additionalLevel--,h+=this._beginLine()+"}"+this._sep()+"}"}return""},l.prototype.closeTag=function(f){var u=this._beginLine()+"]";return this._additionalLevel--,u+=this._beginLine()+"}"+this._sep()+"}"},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){this._hasChildren.pop()},l.prototype._beginLine=function(f){return f===void 0&&(f=0),this._writerOptions.prettyPrint?(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level+f):""},l.prototype._indent=function(f){return f+this._additionalLevel<=0?"":this._writerOptions.indent.repeat(f+this._additionalLevel)},l.prototype._comma=function(){var f=this._hasChildren[this._hasChildren.length-1]?",":"";return this._hasChildren.length>0&&(this._hasChildren[this._hasChildren.length-1]=!0),f},l.prototype._sep=function(){return this._writerOptions.prettyPrint?" ":""},l.prototype._key=function(f){return'"'+f+'":'},l.prototype._val=function(f){return JSON.stringify(f)},l}(i(114).BaseCBWriter);n.JSONCBWriter=s},function(r,n,i){i(74);var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(f){var u=c.call(this,f)||this;if(u._rootWritten=!1,u._additionalLevel=0,f.indent.length<2)throw new Error("YAML indententation string must be at least two characters long.");if(f.offset<0)throw new Error("YAML offset should be zero or a positive number.");return u}return a(l,c),l.prototype.frontMatter=function(){return this._beginLine()+"---"},l.prototype.declaration=function(f,u,d){return""},l.prototype.docType=function(f,u,d){return""},l.prototype.comment=function(f){return this._beginLine()+this._key(this._builderOptions.convert.comment)+" "+this._val(f)},l.prototype.text=function(f){return this._beginLine()+this._key(this._builderOptions.convert.text)+" "+this._val(f)},l.prototype.instruction=function(f,u){return this._beginLine()+this._key(this._builderOptions.convert.ins)+" "+this._val(u?f+" "+u:f)},l.prototype.cdata=function(f){return this._beginLine()+this._key(this._builderOptions.convert.cdata)+" "+this._val(f)},l.prototype.attribute=function(f,u){this._additionalLevel++;var d=this._beginLine()+this._key(this._builderOptions.convert.att+f)+" "+this._val(u);return this._additionalLevel--,d},l.prototype.openTagBegin=function(f){var u=this._beginLine()+this._key(f);return this._rootWritten||(this._rootWritten=!0),this.hasData=!0,this._additionalLevel++,u+=this._beginLine(!0)+this._key(this._builderOptions.convert.text)},l.prototype.openTagEnd=function(f,u,d){return u?" "+this._val(""):""},l.prototype.closeTag=function(f){return this._additionalLevel--,""},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){},l.prototype._beginLine=function(f){return f===void 0&&(f=!1),(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level,f)},l.prototype._indent=function(f,u){if(f+this._additionalLevel<=0)return"";var d=this._writerOptions.indent.repeat(f+this._additionalLevel);return!u&&this._rootWritten?d.substr(0,d.length-2)+"-"+d.substr(-1,1):d},l.prototype._key=function(f){return'"'+f+'":'},l.prototype._val=function(f){return JSON.stringify(f)},l}(i(114).BaseCBWriter);n.YAMLCBWriter=s},function(r,n,i){var o,a=typeof Reflect=="object"?Reflect:null,s=a&&typeof a.apply=="function"?a.apply:function(w,x,C){return Function.prototype.apply.call(w,x,C)};o=a&&typeof a.ownKeys=="function"?a.ownKeys:Object.getOwnPropertySymbols?function(w){return Object.getOwnPropertyNames(w).concat(Object.getOwnPropertySymbols(w))}:function(w){return Object.getOwnPropertyNames(w)};var c=Number.isNaN||function(w){return w!=w};function l(){l.init.call(this)}r.exports=l,l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var f=10;function u(w){if(typeof w!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof w)}function d(w){return w._maxListeners===void 0?l.defaultMaxListeners:w._maxListeners}function h(w,x,C,S){var _,T,E,D;if(u(C),(T=w._events)===void 0?(T=w._events=Object.create(null),w._eventsCount=0):(T.newListener!==void 0&&(w.emit("newListener",x,C.listener?C.listener:C),T=w._events),E=T[x]),E===void 0)E=T[x]=C,++w._eventsCount;else if(typeof E=="function"?E=T[x]=S?[C,E]:[E,C]:S?E.unshift(C):E.push(C),(_=d(w))>0&&E.length>_&&!E.warned){E.warned=!0;var b=new Error("Possible EventEmitter memory leak detected. "+E.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");b.name="MaxListenersExceededWarning",b.emitter=w,b.type=x,b.count=E.length,D=b,console&&console.warn&&console.warn(D)}return w}function g(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(w,x,C){var S={fired:!1,wrapFn:void 0,target:w,type:x,listener:C},_=g.bind(S);return _.listener=C,S.wrapFn=_,_}function v(w,x,C){var S=w._events;if(S===void 0)return[];var _=S[x];return _===void 0?[]:typeof _=="function"?C?[_.listener||_]:[_]:C?function(T){for(var E=new Array(T.length),D=0;D0&&(T=x[0]),T instanceof Error)throw T;var E=new Error("Unhandled error."+(T?" ("+T.message+")":""));throw E.context=T,E}var D=_[w];if(D===void 0)return!1;if(typeof D=="function")s(D,this,x);else{var b=D.length,I=m(D,b);for(C=0;C=0;T--)if(C[T]===x||C[T].listener===x){E=C[T].listener,_=T;break}if(_<0)return this;_===0?C.shift():function(D,b){for(;b+1=0;S--)this.removeListener(w,x[S]);return this},l.prototype.listeners=function(w){return v(this,w,!0)},l.prototype.rawListeners=function(w){return v(this,w,!1)},l.listenerCount=function(w,x){return typeof w.listenerCount=="function"?w.listenerCount(x):y.call(w,x)},l.prototype.listenerCount=y,l.prototype.eventNames=function(){return this._eventsCount>0?o(this._events):[]}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(77);n.createCB=function(a){return new o.XMLBuilderCBImpl(a)},n.fragmentCB=function(a){return new o.XMLBuilderCBImpl(a,!0)}}])})})(bA);var Wae=bA.exports,da=Uint8Array,Rf=Uint16Array,IA=Uint32Array,OA=new da([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),MA=new da([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zae=new da([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),PA=function(t,e){for(var r=new Rf(31),n=0;n<31;++n)r[n]=e+=1<>>1|(Nr&21845)<<1;Ml=(Ml&52428)>>>2|(Ml&13107)<<2,Ml=(Ml&61680)>>>4|(Ml&3855)<<4,dC[Nr]=((Ml&65280)>>>8|(Ml&255)<<8)>>>1}var Gg=function(t,e,r){for(var n=t.length,i=0,o=new Rf(e);i>>c]=l}else for(s=new Rf(n),i=0;i>>15-t[i]);return s},w1=new da(288);for(var Nr=0;Nr<144;++Nr)w1[Nr]=8;for(var Nr=144;Nr<256;++Nr)w1[Nr]=9;for(var Nr=256;Nr<280;++Nr)w1[Nr]=7;for(var Nr=280;Nr<288;++Nr)w1[Nr]=8;var AA=new da(32);for(var Nr=0;Nr<32;++Nr)AA[Nr]=5;var Kae=Gg(w1,9,1),qae=Gg(AA,5,1),Hw=function(t){for(var e=t[0],r=1;re&&(e=t[r]);return e},es=function(t,e,r){var n=e/8|0;return(t[n]|t[n+1]<<8)>>(e&7)&r},Kw=function(t,e){var r=e/8|0;return(t[r]|t[r+1]<<8|t[r+2]<<16)>>(e&7)},Xae=function(t){return(t+7)/8|0},Yae=function(t,e,r){(r==null||r>t.length)&&(r=t.length);var n=new(t.BYTES_PER_ELEMENT==2?Rf:t.BYTES_PER_ELEMENT==4?IA:da)(r-e);return n.set(t.subarray(e,r)),n},Jae=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ss=function(t,e,r){var n=new Error(e||Jae[t]);if(n.code=t,Error.captureStackTrace&&Error.captureStackTrace(n,ss),!r)throw n;return n},LT=function(t,e,r){var n=t.length;if(!n||r&&r.f&&!r.l)return e||new da(0);var i=!e||r,o=!r||r.i;r||(r={}),e||(e=new da(n*3));var a=function(pe){var Ee=e.length;if(pe>Ee){var Oe=new da(Math.max(Ee*2,pe));Oe.set(e),e=Oe}},s=r.f||0,c=r.p||0,l=r.b||0,f=r.l,u=r.d,d=r.m,h=r.n,g=n*8;do{if(!f){s=es(t,c,1);var p=es(t,c+1,3);if(c+=3,p)if(p==1)f=Kae,u=qae,d=9,h=5;else if(p==2){var w=es(t,c,31)+257,x=es(t,c+10,15)+4,C=w+es(t,c+5,31)+1;c+=14;for(var S=new da(C),_=new da(19),T=0;T>>4;if(v<16)S[T++]=v;else{var P=0,M=0;for(v==16?(M=3+es(t,c,3),c+=2,P=S[T-1]):v==17?(M=3+es(t,c,7),c+=3):v==18&&(M=11+es(t,c,127),c+=7);M--;)S[T++]=P}}var L=S.subarray(0,w),V=S.subarray(w);d=Hw(L),h=Hw(V),f=Gg(L,d,1),u=Gg(V,h,1)}else ss(1);else{var v=Xae(c)+4,y=t[v-4]|t[v-3]<<8,m=v+y;if(m>n){o&&ss(0);break}i&&a(l+y),e.set(t.subarray(v,m),l),r.b=l+=y,r.p=c=m*8,r.f=s;continue}if(c>g){o&&ss(0);break}}i&&a(l+131072);for(var G=(1<>>4;if(c+=P&15,c>g){o&&ss(0);break}if(P||ss(2),F<256)e[l++]=F;else if(F==256){k=c,f=null;break}else{var j=F-254;if(F>264){var T=F-257,Y=OA[T];j=es(t,c,(1<>>4;re||ss(3),c+=re&15;var V=Hae[ue];if(ue>3){var Y=MA[ue];V+=Kw(t,c)&(1<g){o&&ss(0);break}i&&a(l+131072);for(var ce=l+j;l>3&1)+(e>>4&1);n>0;n-=!t[r++]);return r+(e&2)},ese=function(t){var e=t.length;return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0},tse=function(t){((t[0]&15)!=8||t[0]>>>4>7||(t[0]<<8|t[1])%31)&&ss(6,"invalid zlib data"),t[1]&32&&ss(6,"invalid zlib data: preset dictionaries not supported")};function nse(t,e){return LT(t,e)}function rse(t,e){return LT(t.subarray(Qae(t),-8),new da(ese(t)))}function ise(t,e){return LT((tse(t),t.subarray(2,-4)),e)}function ose(t,e){return t[0]==31&&t[1]==139&&t[2]==8?rse(t):(t[0]&15)!=8||t[0]>>4>7||(t[0]<<8|t[1])%31?nse(t,e):ise(t,e)}var ase=typeof TextDecoder<"u"&&new TextDecoder,sse=0;try{ase.decode(Zae,{stream:!0}),sse=1}catch{}const ca=[];ca[45]=62;ca[95]=63;const Hd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t>16&255,n[f++]=l>>8&255,n[f++]=l&255}switch(a){case 3:for(;!Ls(t[c]);)c++;for(l=ca[t.charCodeAt(c++)]<<10;!Ls(t[c]);)c++;for(l|=ca[t.charCodeAt(c++)]<<4;!Ls(t[c]);)c++;l|=ca[t.charCodeAt(c++)]>>2,n[f++]=l>>8&255,n[f++]=l&255;break;case 2:for(;!Ls(t[c]);)c++;for(l=ca[t.charCodeAt(c++)]<<2;!Ls(t[c]);)c++;l|=ca[t.charCodeAt(c++)]>>4,n[f++]=l&255;break;case 1:throw new Error("BASE64: remain 1 should not happen")}return f}function use(t){const e=cse(t),r=e[e.length-1].end+1,n=(4-r%4)%4,i=(r+n)*3/4-n,o=new ArrayBuffer(i),a=new Uint8Array(o);let s=0;for(let c=0;c>18]+Hd[n>>12&63]+Hd[n>>6&63]+Hd[n&63]}function fse(t){const e=new Uint8Array(t),r=t.byteLength%3,n=t.byteLength-r,i=Array(n/3);for(let o=0;o0){const o=D9(e[n],e[n+1]||0,e[n+2]||0);r===1?i.push(`${o.substr(0,2)}==`):r===2&&i.push(`${o.substr(0,3)}=`)}return i.join("")}var AT={toArrayBuffer:use,fromArrayBuffer:fse};function dse(t,e){e.classHierarchy.push("vtkStringArray"),t.getComponent=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return e.values[r*e.numberOfComponents+n]},t.setComponent=(r,n,i)=>{i!==e.values[r*e.numberOfComponents+n]&&(e.values[r*e.numberOfComponents+n]=i,t.modified())},t.getData=()=>e.values,t.getTuple=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];const i=e.numberOfComponents||1;n.length&&(n.length=i);const o=r*i;for(let a=0;a0&&arguments[0]!==void 0?arguments[0]:1)*e.numberOfComponents},t.getNumberOfComponents=()=>e.numberOfComponents,t.getNumberOfValues=()=>e.values.length,t.getNumberOfTuples=()=>e.values.length/e.numberOfComponents,t.getDataType=()=>e.dataType,t.newClone=()=>kA({name:e.name,numberOfComponents:e.numberOfComponents,empty:!0}),t.getName=()=>(e.name||t.setName(`vtkStringArray${t.getMTime()}`),e.name),t.setData=(r,n)=>{e.values=r,e.size=r.length,n&&(e.numberOfComponents=n),e.size%e.numberOfComponents!==0&&(e.numberOfComponents=1),t.modified()}}const hse={name:"",numberOfComponents:1,size:0,dataType:"string"};function NA(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Object.assign(e,hse,r),!e.empty&&!e.values&&!e.size)throw new TypeError("Cannot create vtkStringArray object without: size > 0, values");e.values?Array.isArray(e.values)&&(e.values=[...e.values]):e.values=[],e.values&&(e.size=e.values.length),ne.obj(t,e),ne.set(t,e,["name"]),dse(t,e)}const kA=ne.newInstance(NA,"vtkStringArray");var gse={newInstance:kA,extend:NA};function pse(t,e){return[...t.getElementsByTagName(e)]}function b9(t,e){return pse(t,e)[0]}function mse(t){return Wae.create(t)}function vse(t){const e=/^\s*\s*_/m,r=/\n\s*<\/AppendedData>/m;return Mae.extractBinary(t,e,r)}const Ql={Int8:Int8Array,UInt8:Uint8Array,Int16:Int16Array,UInt16:Uint16Array,Int32:Int32Array,UInt32:Uint32Array,Int64:Int32Array,UInt64:Uint32Array,Float32:Float32Array,Float64:Float64Array},Lp={Int8:1,UInt8:1,Int16:2,UInt16:2,Int32:4,UInt32:4,Int64:8,UInt64:8,Float32:4,Float64:8};function hC(t){const e=t.length-1;return t.filter((r,n)=>n0&&(o===0?a=n*i:a=(n-1)*i+o);const s=new ArrayBuffer(a),c={offset:0,uint8:new Uint8Array(s)};let l=wse(r);for(;l{d.trim().length&&(f[u++]=Number(d))})}else if(c==="binary"){const u=new Uint8Array(AT.toArrayBuffer(e.firstChild.nodeValue.trim()));if(r==="vtkZLibDataCompressor"){const d=NT(u,i);f=new Ql[a](d.buffer),/^U?Int64$/.test(a)&&(f=hC(f))}else f=new Ql[a](u.buffer,Lp[i]),a.indexOf("Int64")!==-1&&(f=hC(f))}else if(c==="appended"){const u=Number(e.getAttribute("offset"));f=gC(new Uint8Array(o,u),a,i)}else console.error("Format not supported",c);return{name:s,values:f,numberOfComponents:l}}function qw(t){return new TextDecoder().decode(t).split("\0").slice(0,-1)}function Cse(t,e,r,n,i){const o=t.getAttribute("Name"),a=t.getAttribute("format"),s=Number(t.getAttribute("NumberOfComponents")||"1"),l=Number(t.getAttribute("NumberOfTuples")||"1")*s,f=[];if(a==="ascii"){const u=t.firstChild.nodeValue.trim().split(/\s+/);let d=0;const h=[];for(;f.length{const p=g-h;u[d++]=p;for(let v=0;v{const d=e.getAttribute(u);d&&(c[d]=r[`set${u}`])});const l=e.getElementsByTagName("DataArray"),f=l.length;for(let u=0;uYt.newInstance(Ap(Number(s.getAttribute("NumberOfTuples")),s,e,r,n,i))),a=[...t.getElementsByTagName("Array")].filter(s=>s.getAttribute("type")==="String").map(s=>gse.newInstance(Cse(s,e,r,n,i)));return[...o,...a]}function Ese(t,e){e.classHierarchy.push("vtkXMLReader"),e.dataAccessHelper||(e.dataAccessHelper=Rae.get("http"));function r(n){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return e.dataAccessHelper.fetchBinary(n,i)}t.setUrl=function(n){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};e.url=n;const o=n.split("/");return o.pop(),e.baseURL=o.join("/"),t.loadData(i)},t.loadData=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r(e.url,n).then(t.parseAsArrayBuffer)},t.parseAsArrayBuffer=n=>{if(!n)return!1;if(n!==e.rawDataBuffer)t.modified();else return!0;const{text:i,binaryBuffer:o}=vse(n);e.rawDataBuffer=n,e.binaryBuffer=o;const s=mse(i).root(),c=s.node,l=c.getAttribute("type"),f=c.getAttribute("compressor"),u=c.getAttribute("byte_order"),d=c.getAttribute("header_type")||"UInt32";if(f&&f!=="vtkZLibDataCompressor")return console.error("Invalid compressor",f),!1;if(u&&u!=="LittleEndian")return console.error("Only LittleEndian encoding is supported"),!1;if(l!==e.dataType)return console.error("Invalid data type",l,"expecting",e.dataType),!1;if(b9(c,"AppendedData")){const p=b9(c,"AppendedData"),v=p.getAttribute("encoding"),y=s.filter(_=>{const{node:T}=_;return T.nodeType===Node.ELEMENT_NODE&&T.getAttribute("format")==="appended"&&T.hasAttribute("offset")},!1,!0).map(_=>({node:_.node,offset:Number(_.node.getAttribute("offset"))}));y.sort((_,T)=>_.offset-T.offset);let m=e.binaryBuffer;v==="base64"&&(m=p.textContent.trim().substr(1));const w=[];for(let _=0;__+T.length,0),C=new ArrayBuffer(x),S=new Uint8Array(C);for(let _=0,T=0;_{t.parseAsArrayBuffer(e.rawDataBuffer)}}const Dse={};function bse(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Dse,r),ne.obj(t,e),ne.get(t,e,["url","baseURL"]),ne.setGet(t,e,["dataAccessHelper"]),ne.algo(t,e,0,1),Ese(t,e)}var Np={extend:bse,processDataArray:Ap,processFieldData:_se,processCells:Sse};function Ise(t,e,r,n,i,o,a){const s=Number(r.getAttribute(`NumberOf${e}`));if(s>0){const c=r.getElementsByTagName(e)[0].getElementsByTagName("DataArray")[0],{values:l,numberOfComponents:f}=Np.processDataArray(s,c,n,i,o,a);t[`get${e}`]().setData(l,f)}return s}function Ose(t,e,r,n,i,o,a){const s=Number(r.getAttribute(`NumberOf${e}`));if(s>0){const c=Np.processCells(s,r.getElementsByTagName(e)[0],n,i,o,a);t[`get${e}`]().setData(c)}return s}function Mse(t,e){e.classHierarchy.push("vtkXMLPolyDataReader"),t.parseXML=(r,n,i,o,a)=>{const c=r.getElementsByTagName(e.dataType)[0].getElementsByTagName("Piece"),l=c.length;for(let f=0;f{g+=Ose(u,p,d,i,o,a,e.binaryBuffer)}),Np.processFieldData(h,d.getElementsByTagName("PointData")[0],u.getPointData(),i,o,a,e.binaryBuffer),Np.processFieldData(g,d.getElementsByTagName("CellData")[0],u.getCellData(),i,o,a,e.binaryBuffer),e.output[f]=u}}}const Pse={dataType:"PolyData"};function VA(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Pse,r),Np.extend(t,e,r),Mse(t,e)}const Rse=ne.newInstance(VA,"vtkXMLPolyDataReader");var Lse={newInstance:Rse,extend:VA},is;(function(t){t[t.None=0]="None",t[t.Capture=1]="Capture",t[t.Bubble=2]="Bubble"})(is||(is={}));class u5{constructor(e){this._eventListeners=new Map,this._children=new Map,this._target=e}get isEmpty(){return this._eventListeners.size===0&&this._children.size===0}addEventListener(e,r,n){const i=e.indexOf(".");if(i!==-1){const a=e.substring(0,i);let s=this._children.get(a);s||(s=new u5(this._target),this._children.set(a,s)),e=e.substring(i+1),s.addEventListener(e,r,n)}else this._addEventListener(e,r,n)}removeEventListener(e,r,n){const i=e.indexOf(".");if(i!==-1){const a=e.substring(0,i),s=this._children.get(a);if(!s)return;e=e.substring(i+1),s.removeEventListener(e,r,n),s.isEmpty&&this._children.delete(a)}else this._removeEventListener(e,r,n)}reset(){Array.from(this._children.entries()).forEach(([e,r])=>{if(r.reset(),r.isEmpty)this._children.delete(e);else throw new Error("Child is not empty and cannot be removed")}),this._unregisterAllEvents()}_addEventListener(e,r,n){let i=this._eventListeners.get(e);i||(i=new Map,this._eventListeners.set(e,i));const a=(n==null?void 0:n.capture)??!1?is.Capture:is.Bubble,s=i.get(r)??is.None;if(s&a){console.warn("A listener is already registered for this phase");return}i.set(r,s|a),this._target.addEventListener(e,r,n)}_removeEventListener(e,r,n){const o=(n==null?void 0:n.capture)??!1?is.Capture:is.Bubble,a=this._eventListeners.get(e);if(!a)return;(r?[r]:Array.from(a.keys())).forEach(c=>{const l=a.get(c)??is.None;if(!!!(l&o))return;this._target.removeEventListener(e,c,n);const u=l^o;u===is.None?a.delete(c):a.set(c,u)}),a.size||this._eventListeners.delete(e)}_unregisterAllListeners(e,r){Array.from(r.entries()).forEach(([n,i])=>{const o=is.Capture;for(let a=o;i;a<<=1){if(!(i&a))continue;const s=a===is.Capture;this.removeEventListener(e,n,{capture:s}),i^=a}})}_unregisterAllEvents(){Array.from(this._eventListeners.entries()).forEach(([e,r])=>{this._unregisterAllListeners(e,r)})}}class FA{constructor(){this._targetsEventListeners=new Map}addEventListener(e,r,n,i){let o=this._targetsEventListeners.get(e);o||(o=new u5(e),this._targetsEventListeners.set(e,o)),o.addEventListener(r,n,i)}removeEventListener(e,r,n,i){const o=this._targetsEventListeners.get(e);o&&(o.removeEventListener(r,n,i),o.isEmpty&&this._targetsEventListeners.delete(e))}reset(){Array.from(this._targetsEventListeners.entries()).forEach(([e,r])=>{r.reset(),this._targetsEventListeners.delete(e)})}}const Ase=Object.freeze(Object.defineProperty({__proto__:null,MultiTargetEventListenerManager:FA,TargetEventListeners:u5},Symbol.toStringTag,{value:"Module"}));function Nse(t,e){const r=t.getSize();for(let n=0;n0?r:Fse)>>>0).join(typeof e=="string"?e:Use)}function Bse(t,e,r){let n=t[e];n instanceof Array||(n=[0],Object.defineProperty(t,e,{value:n}));for(let i=!0,o=0;i&&o{const r=Vr(t);I9[r]=e},get:(t,e)=>{if(t==="calibratedPixelSpacing"){const r=Vr(e);return I9[r]}}};function vg(t,e,r=1e-5){return Math.abs(t[0]+e[0])=e[0]||t[1]<0||t[1]>=e[1]||t[2]<0||t[2]>=e[2])}function Wse(t,e){let r;e?r=[Jr(e)]:r=Qo();const n=[];return r.forEach(i=>{const o=t.getActors(),a=i.getVolumeViewports();for(const s of a){const c=s.getActors();if(c.length!==o.length)continue;o.every(({uid:f})=>c.find(u=>f===u.uid))&&n.push(s)}}),n}const BA=t=>t.preScale.scaled&&t.preScale.scalingParameters.suvbw;function GA(t,e,r=void 0,n="_thumbnails",i={displayArea:{imageArea:[1,1]}}){if(!t||!(t instanceof HTMLCanvasElement))throw new Error("canvas element is required");const o=!e.imageId,a=!o&&e,s=o&&e,l=`renderGPUViewport-${a.imageId||s.volumeId}`,f=document.createElement("div"),u=window.devicePixelRatio||1;i.displayArea||(i.displayArea={imageArea:[1,1]});const d=t.width,h=t.height;f.style.width=`${d/u+Ug}px`,f.style.height=`${h/u+Ug}px`,f.style.visibility="hidden",f.style.position="absolute",document.body.appendChild(f);const g=l.split(":").join("-");f.setAttribute("viewport-id-for-remove",g);const p=Mc(f),v=Jr(n)||new CA(n);let y=v.getViewport(l);if(!y){const m={viewportId:l,type:o?mr.ORTHOGRAPHIC:mr.STACK,element:f,defaultOptions:{...i,suppressEvents:!0}};v.enableElement(m),y=v.getViewport(l)}return new Promise(m=>{let w=!1,{viewReference:x}=i;const C=S=>{if(w)return;if(x){const M=x;x=null,y.setViewReference(M),y.render();return}t.getContext("2d").drawImage(p,0,0,p.width,p.height,0,0,t.width,t.height);const T=y.canvasToWorld([0,0]),E=y.canvasToWorld([p.width/u,0]),D=y.canvasToWorld([0,p.height/u]),b=En([0,0,0],y.canvasToWorld([1/u,0]),T),I=En([0,0,0],y.canvasToWorld([0,1/u]),T),P=1;w=!0,f.removeEventListener(Xe.IMAGE_RENDERED,C),setTimeout(()=>{v.disableElement(l),document.querySelectorAll(`[viewport-id-for-remove="${g}"]`).forEach(L=>{L.remove()})},0),m({origin:T,bottomLeft:D,topRight:E,thicknessMm:P,rightVector:b,downVector:I})};f.addEventListener(Xe.IMAGE_RENDERED,C),o?y.setVolumes([s],!1,!0):y.renderImageObject(e),y.resetCamera(),r==="PT"&&!BA(a)&&y.setProperties({voiRange:{lower:a.minPixelValue,upper:a.maxPixelValue}}),y.render()})}function WA(t,e,r,n,i){if(e.volumeId)throw new Error("Unsupported volume rendering for CPU");const a=e,s=yA(t,a,r),c={canvas:t,viewport:s,image:a,renderingTools:{}};c.transform=Pp(c);const l=!0;return new Promise((f,u)=>{pA(c,l),f(null)})}function zse(t){const{canvas:e,imageId:r,viewReference:n,requestType:i=hn.Thumbnail,priority:o=-5,renderingEngineId:a="_thumbnails",useCPURendering:s=!1,thumbnail:c=!1,imageAspect:l=!1,viewportOptions:f}=t,u=n==null?void 0:n.volumeId,d=u&&!r,h=n&&f?{...f,viewReference:n}:f,g=s?WA:GA;return new Promise((p,v)=>{function y(C,S){var D;const{modality:_}=mt("generalSeriesModule",S)||{},T=!d&&C,E=d&&C;T&&(T.isPreScaled=T.isPreScaled||((D=T.preScale)==null?void 0:D.scaled)),c&&(e.height=256,e.width=256),l&&T&&(e.width=T&&e.height*T.width/T.height),e.style.width=`${e.width/devicePixelRatio}px`,e.style.height=`${e.height/devicePixelRatio}px`,E&&s&&v(new Error("CPU rendering of volume not supported")),g(e,C,_,a,h).then(p)}function m(C,S){console.error(C,S),v(C)}function w(C,S,_){return xu(C,_).then(T=>{y.call(this,T,C)},T=>{m.call(this,T,C)})}const x={useRGBA:!!s,requestType:i};if(u){const C=Le.getVolume(u);C||v(new Error(`Volume id ${u} not found in cache`));const S=C.imageIds[0];y(C,S)}else Ao.addRequest(w.bind(null,r,null,x),i,{imageId:r},o)})}const O9={HISTORY_UNDO:"CORNERSTONE_TOOLS_HISTORY_UNDO",HISTORY_REDO:"CORNERSTONE_TOOLS_HISTORY_REDO"};class zA{constructor(e="Tools",r=50){this.position=-1,this.redoAvailable=0,this.undoAvailable=0,this.ring=new Array,this.label=e,this._size=r}get size(){return this._size}set size(e){this.ring=new Array(e),this._size=e,this.position=-1,this.redoAvailable=0,this.undoAvailable=0}undo(e=1){for(;e>0&&this.undoAvailable>0;){const r=this.ring[this.position];r.restoreMemo(!0),r.id&&Ke.dispatchEvent(new CustomEvent(O9.HISTORY_UNDO,{detail:{isUndo:!0,id:r.id,operationType:r.operationType||"annotation",memo:r}})),e--,this.redoAvailable++,this.undoAvailable--,this.position=(this.position-1+this.size)%this.size}}undoIf(e){return this.undoAvailable>0&&e(this.ring[this.position])?(this.undo(),!0):!1}redo(e=1){for(;e>0&&this.redoAvailable>0;){const r=(this.position+1)%this.size,n=this.ring[r];n.restoreMemo(!1),n.id&&Ke.dispatchEvent(new CustomEvent(O9.HISTORY_REDO,{detail:{isUndo:!1,id:n.id,operationType:n.operationType||"annotation",memo:n}})),e--,this.position=r,this.undoAvailable++,this.redoAvailable--}}push(e){var n;if(!e)return;const r=e.restoreMemo?e:(n=e.createMemo)==null?void 0:n.call(e);if(r)return this.redoAvailable=0,this.undoAvailable{n.getViewports().forEach(o=>{o.hasImageURI(t)&&r.push(o)})}),r}function FT(t,e){const r=$se(t,e);return r?r.index:null}function $se(t,e){const r=e.getImageIds(),n=e.getCurrentImageIdIndex();if(r.length===0)return null;const i=c=>{const l=jse(c);if(!l)return null;const f=qs(l.planeNormal,l.imagePositionPatient);return Mp(f,t)},o={distance:i(r[n])??1/0,index:n},a=r.slice(n+1);for(let c=0;c=0;c--){const l=s[c],f=i(l);if(!(f===null||f===o.distance))if(f{const[r,n]=t,i=`${r}_${n}`;df[i]||(df[i]={}),df[i]=e},get:(t,e,r)=>{if(t!=="spatialRegistrationModule")return;const n=`${e}_${r}`;if(df[n])return df[n];const i=`${r}_${e}`;if(df[i])return oi(Zo(),df[i])}};ah(kp.get.bind(kp));const Hse=.05;function HA(t,e){const r=t.getSliceIndex(),n=e.getSliceIndex(),i=mt("imagePlaneModule",r.toString()),o=mt("imagePlaneModule",n.toString());if(!i||!o){console.log("Viewport spatial registration requires image plane module");return}const{imageOrientationPatient:a}=o;if(!i.imageOrientationPatient.every((d,h)=>Math.abs(d-a[h])0||t[0]0||t[1]0||t[2]{r.getViewports().forEach(({element:i})=>{t.push(Ce(i))})}),t}function Xse(t){const e=Ce(t);if(!e)return;const{viewport:r}=e;if(!(r instanceof lr))throw new Error(`An image can only be fetched for a stack viewport and not for a viewport of type: ${r.type}`);return r.getCornerstoneImage()}function Nu(t){if(t.length<=1)return!1;const e=t[0],{modality:r,seriesInstanceUID:n}=mt("generalSeriesModule",e),{imageOrientationPatient:i,pixelSpacing:o,frameOfReferenceUID:a,columns:s,rows:c,usingDefaultValues:l}=mt("imagePlaneModule",e);if(l)return!1;const f={modality:r,imageOrientationPatient:i,pixelSpacing:o,columns:s,rows:c,seriesInstanceUID:n};let u=!0;for(let d=0;dYse.has(r)):!1}async function Jse({viewport:t,options:e={}}){const r=t.getRenderingEngine();let n=e.volumeId||`${Dn()}`;n.split(":").length===0&&(n=`${Gie()}:${n}`);const{id:i,element:o}=t,a=e.viewportId||i,s=t.getImageIds(),c=t.getViewPresentation(),l=t.getViewReference();r.enableElement({viewportId:a,type:mr.ORTHOGRAPHIC,element:o,defaultOptions:{background:e.background,orientation:e.orientation}}),(await Vv(n,{imageIds:s})).load();const u=r.getViewport(a);await xae(r,[{volumeId:n}],[a]);const d=()=>{u.render(),o.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,d)};return(()=>{o.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,d)})(),u.setViewPresentation(c),u.setViewReference(l),u.render(),u}async function Zse({viewport:t,options:e}){const r=t,{id:n,element:i}=r,o=t.getRenderingEngine(),{background:a}=e,s=e.viewportId||n,c=Le.getVolume(r.getVolumeId());if(!(c instanceof lh))throw new Error("Currently, you cannot decache a volume that is not an ImageVolume. So, unfortunately, volumes such as nifti (which are basic Volume, without imageIds) cannot be decached.");const l={viewportId:s,type:mr.STACK,element:i,defaultOptions:{background:a}},f=r.getViewReference();o.enableElement(l);const u=o.getViewport(s);return await u.setStack(c.imageIds),u.setViewReference(f),u.render(),u}function an(t,e=2){if(Array.isArray(t))return t.map(i=>an(i,e)).join(", ");if(t==null||t==="")return"NaN";t=Number(t);const r=Math.abs(t);if(r<1e-4)return`${t}`;const n=r>=100?e-2:r>=10?e-1:r>=1?e:r>=.1?e+1:r>=.01?e+2:r>=.001?e+3:e+4;return t.toFixed(n)}function eu(t){return Math.round(t/wa)*wa}function qA(t,e,r){const n=t.length===e*r*4,i=t.length===e*r*3;if(n||i){const o=new Float32Array(e*r);let a=0,s=0;const c=n?4:3;for(let l=0;l=r.length?(M9(r),r):(M9(r),r.slice(0,e))}function M9(t){for(let e=t.length-1;e>0;e--){const r=Math.floor(Math.random()*(e+1));[t[e],t[r]]=[t[r],t[e]]}}function Xw(t){const e=t.toString(16);return e.length==1?"0"+e:e}function ece(t,e,r){return"#"+Xw(t)+Xw(e)+Xw(r)}function tce(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null}const nce=Object.freeze(Object.defineProperty({__proto__:null,hexToRgb:tce,rgbToHex:ece},Symbol.toStringTag,{value:"Module"}));function XA(t,e){if(t===e)return!0;if(t==null||e==null)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch(r){return console.debug("Error in JSON.stringify during deep comparison:",r),t===e}}function rce(t,e,r){if(!r)throw new Error("getVolume is required, use the utilities export instead ");if(t.modality)return t.modality;if(t.setVolumes)return e=e??t.getVolumeId(),!e||!r?void 0:r(e).metadata.Modality;throw new Error("Invalid viewport type")}const ice=(t,e)=>t.reduce((r,n)=>((r[n[e]]=r[n[e]]||[]).push(n),r),{});function oce(t){const e=t.map(a=>{const{imagePositionPatient:s}=mt("imagePlaneModule",a)||{};return{imageId:a,imagePositionPatient:s}});if(!e.every(a=>a.imagePositionPatient))return null;const r=ice(e,"imagePositionPatient"),n=Object.keys(r),i=r[n[0]].length;return i===1||!n.every(a=>r[a].length===i)?null:r}function ace(t,e){const r={};let n=[];const i=Object.keys(t);for(let o=0;ojh(i,r[0]),i=>jh(i,r[1]),i=>jh(i,r[2]),i=>jh(i,r[3]),i=>jh(i,r[4]),sce,cce,lce,fce];for(let i=0;ic-l).map(c=>o[c].map(l=>l.imageId)),splittingTag:r[i]}}return{imageIdGroups:[t],splittingTag:null}}function dce(t){const{imageIdGroups:e,splittingTag:r}=YA(t);return{isDynamicVolume:e.length>1,timePoints:e,splittingTag:r}}function hce(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o}=e;if(e.modality==="PT"&&typeof o=="number")for(let a=0;at.getImageIds().length-1||a+i<0){const s={imageIdIndex:a,direction:i};at(Ke,Xe.STACK_SCROLL_OUT_OF_BOUNDS,s)}t.scroll(i,e.debounceLoading,e.loop)}}function gce(t,e,r,n=!1){const i=n,{numScrollSteps:o,currentStepIndex:a,sliceRangeInfo:s}=Vf(t,e,i);if(!s)return;const{sliceRange:c,spacingInNormalDirection:l,camera:f}=s,{focalPoint:u,viewPlaneNormal:d,position:h}=f,{newFocalPoint:g,newPosition:p}=m0(u,h,c,d,l,r);t.setCamera({focalPoint:g,position:p}),t.render();const v=a+r,y={volumeId:e,viewport:t,delta:r,desiredStepIndex:v,currentStepIndex:a,numScrollSteps:o,currentImageId:t.getCurrentImageId()};(v>o||v<0)&&t.getCurrentImageId()?at(Ke,Xe.VOLUME_VIEWPORT_SCROLL_OUT_OF_BOUNDS,y):at(Ke,Xe.VOLUME_VIEWPORT_SCROLL,y)}async function Aa(t,e={}){const{imageIndex:r,debounceLoading:n,volumeId:i}=e,o=Ce(t);if(!o)throw new Error("Element has been disabled");const{viewport:a}=o,{imageIndex:s,numberOfSlices:c}=pce(a,n),f=mce(c,r)-s;ps(a,{delta:f,debounceLoading:n,volumeId:i})}function pce(t,e){return t instanceof lr?{numberOfSlices:t.getImageIds().length,imageIndex:e?t.getTargetImageIdIndex():t.getCurrentImageIdIndex()}:{numberOfSlices:t.getNumberOfSlices(),imageIndex:t.getSliceIndex()}}function mce(t,e){const r=t-1;return Wv(e,0,r)}function GT(t,e,r={}){const n=Le.getVolume(t);if(!n)throw new Error(`Referenced volume with id ${t} does not exist.`);const{metadata:i,spacing:o,direction:a,dimensions:s}=n,{minX:c,maxX:l,minY:f,maxY:u,minZ:d,maxZ:h}=e,g=[Math.min(c,l),Math.min(f,u),Math.min(d,h)],p=B0(n.imageData,g),v=[Math.abs(l-c)+1,Math.abs(u-f)+1,Math.abs(h-d)+1],{targetBuffer:y}=r,m={metadata:i,dimensions:v,spacing:o,origin:p,direction:a,targetBuffer:y,scalarData:(y==null?void 0:y.type)==="Float32Array"?new Float32Array(v[0]*v[1]*v[2]):void 0},w=TT(Dn(),m),x=w.voxelManager.getCompleteScalarDataArray(),C=v[0]*v[1],S=s[0]*s[1],_=n.voxelManager.getCompleteScalarDataArray();for(let T=0;T=a)){for(let m=d-n;m<=d+n;m++)if(!(m<0||m>=o))for(let w=u-n;w<=u+n;w++){if(w<0||w>=i)continue;const x=y*s+m*i+w,C=t[x];c+=C,l+=C*C,f++}}if(f===0){const y=h*s+d*i+u;return y>=0&&yc/n),type:ls.ERMF,isProjection:a}:(console.warn("EstimatedRadiographicMagnificationFactor was not present. Unable to correct ImagerPixelSpacing."),{PixelSpacing:r,type:ls.PROJECTION,isProjection:a}):{PixelSpacing:e,type:ls.UNKNOWN,isProjection:a}}function wce(t){const{SequenceOfUltrasoundRegions:e}=t,r=Array.isArray(e);if(r&&e.length>1){console.warn("Sequence of Ultrasound Regions > one entry. This is not yet implemented, all measurements will be shown in pixels.");return}const{PhysicalDeltaX:n,PhysicalDeltaY:i}=r?e[0]:e;return{PixelSpacing:[n*10,i*10]}}function xce(t){const{PixelSpacing:e,SOPClassUID:r,SequenceOfUltrasoundRegions:n}=t;return n?wce(t):vce.has(r)?yce(t):{PixelSpacing:e,type:ls.NOT_APPLICABLE,isProjection:!1}}const ZA=(t,e)=>rce(t,e,Le.getVolume),Mn=Object.freeze(Object.defineProperty({__proto__:null,FrameRange:v0,HistoryMemo:VT,PointsManager:D2,ProgressiveIterator:Nv,RLEVoxelMap:Pd,VoxelManager:tc,actorIsA:Yo,applyPreset:iA,autoLoad:oC,buildMetadata:lA,calculateNeighborhoodStats:JA,calculateSpacingBetweenImageIds:$L,calculateViewportsSpatialRegistration:HA,calibratedPixelSpacingMetadataProvider:Gse,clamp:uC,clip:Wv,color:nce,colormap:Lte,convertStackToVolumeViewport:Jse,convertToGrayscale:qA,convertVolumeToStackViewport:Zse,createLinearRGBTransferFunction:uA,createSigmoidRGBTransferFunction:xT,createSubVolume:GT,decimate:qL,deepClone:Fa,deepEqual:XA,deepMerge:Ei,eventListener:Ase,fnv1aHash:eL,generateVolumePropsFromImageIds:r5,genericMetadataProvider:Zl,getBufferConfiguration:rT,getClosestImageId:qc,getClosestStackImageIndexForPoint:FT,getCurrentVolumeViewportSlice:UT,getDynamicVolumeInfo:dce,getImageDataMetadata:a5,getImageLegacy:Xse,getImageSliceDataForVolumeViewport:Fv,getMinMax:kT,getPixelSpacingInformation:xce,getRandomSampleFromArray:BT,getRuntimeId:UA,getScalingParameters:HL,getSliceRange:t5,getSpacingInNormalDirection:Au,getTargetVolumeAndSpacingInNormalDir:uh,getViewportImageCornersInWorld:Gv,getViewportImageIds:Qse,getViewportModality:ZA,getViewportsWithImageURI:Bv,getViewportsWithVolumeId:y1,getVoiFromSigmoidRGBTransferFunction:rA,getVolumeActorCorners:sL,getVolumeDirectionVectors:f5,getVolumeId:sc,getVolumeSliceRangeInfo:nA,getVolumeViewportScrollInfo:Vf,getVolumeViewportsContainingSameVolumes:Wse,hasFloatScalingParameters:_T,hasNaNValues:sC,imageIdToURI:Vr,imageRetrieveMetadataProvider:Op,imageToWorldCoords:jA,indexWithinDimensions:sr,invertRgbTransferFunction:Vg,isEqual:$t,isEqualAbs:Mte,isEqualNegative:dL,isImageActor:fs,isNumber:Ar,isOpposite:vg,isPTPrescaledWithSUV:BA,isValidVolume:Nu,isVideoTransferSyntax:KA,jumpToSlice:Aa,loadImageToCanvas:zse,logger:ute,makeVolumeMetadata:zL,planar:toe,pointInShapeCallback:ST,renderToCanvasCPU:WA,renderToCanvasGPU:GA,roundNumber:an,roundToPrecision:eu,scaleArray:hce,scaleRgbTransferFunction:Nse,scroll:ps,snapFocalPointToSlice:m0,sortImageIdsAndGetSpacing:jL,spatialRegistrationMetadataProvider:kp,splitImageIdsBy4DTags:YA,transferFunctionUtils:Nte,transformIndexToWorld:B0,transformWorldToIndex:Ur,transformWorldToIndexContinuous:T2,triggerEvent:at,updateVTKImageDataWithCornerstoneImage:s5,uuidv4:Dn,windowLevel:Ate,worldToImageCoords:pC},Symbol.toStringTag,{value:"Module"})),x1=new oT("imageRetrievalPool");x1.setMaxSimultaneousRequests(hn.Interaction,200);x1.setMaxSimultaneousRequests(hn.Thumbnail,200);x1.setMaxSimultaneousRequests(hn.Prefetch,200);x1.grabDelay=0;const P9=Symbol("DefaultSettings"),R9=Symbol("RuntimeSettings"),L9=Symbol("ObjectSettingsMap"),Cc=Symbol("Dictionary");class Cr{constructor(e){const r=Object.create(e instanceof Cr&&Cc in e?e[Cc]:null);Object.seal(Object.defineProperty(this,Cc,{value:r}))}set(e,r){return zv(this[Cc],e,r,null)}get(e){return _ce(this[Cc],e)}unset(e){return Cce(this[Cc],e+"")}forEach(e){A9(this[Cc],e)}extend(){return new Cr(this)}import(e){QA(e)&&Object.keys(e).forEach(r=>{zv(this[Cc],r,e[r],null)})}dump(){const e={};return A9(this[Cc],(r,n)=>{typeof n<"u"&&eN(e,r,n)}),e}static assert(e){return e instanceof Cr?e:Cr.getRuntimeSettings()}static getDefaultSettings(e=null){let r=Cr[P9];if(r instanceof Cr||(r=new Cr,Cr[P9]=r),e){const n={};return r.forEach(i=>{if(i.startsWith(e)){const o=i.split(`${e}.`)[1];n[o]=r.get(i)}}),n}return r}static getRuntimeSettings(){let e=Cr[R9];return e instanceof Cr||(e=new Cr(Cr.getDefaultSettings()),Cr[R9]=e),e}static getObjectSettings(e,r){let n=null;if(e instanceof Cr)n=e;else if(typeof e=="object"&&e!==null){let i=Cr[L9];i instanceof WeakMap||(i=new WeakMap,Cr[L9]=i),n=i.get(e),n instanceof Cr||(n=new Cr(Cr.assert(Cr.getObjectSettings(r))),i.set(e,n))}return n}static extendRuntimeSettings(){return Cr.getRuntimeSettings().extend()}}function Cce(t,e){if(e.endsWith(".")){let r=0;const n=e,i=n.slice(0,-1),o=i.length===0;for(const a in t)Object.prototype.hasOwnProperty.call(t,a)&&(o||a.startsWith(n)||a===i)&&(delete t[a],++r);return r>0}return delete t[e]}function A9(t,e){for(const r in t)e(r,t[r])}function Sce(t,e,r,n){let i;if(n.has(r))return zv(t,e,null,n);n.add(r),i=0;for(const o in r)if(Object.prototype.hasOwnProperty.call(r,o)){const a=o.length===0?e:`${e}.${o}`;zv(t,a,r[o],n)||++i}return n.delete(r),i===0}function zv(t,e,r,n){return Tce(e)?QA(r)?Sce(t,e,r,n instanceof WeakSet?n:new WeakSet):(t[e]=r,!0):!1}function _ce(t,e){return t[e]}function Tce(t){let e,r,n;if(typeof t!="string"||(e=t.length-1)<0)return!1;for(n=-1;(r=t.indexOf(".",n+1))>=0;){if(r-n<2||r===e)return!1;n=r}return!0}function QA(t){if(typeof t=="object"&&t!==null){const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null)return!0}return!1}function eN(t,e,r){const n=e.indexOf(".");if(n>=0){const i=e.slice(0,n);let o=t[i];if(typeof o!="object"||o===null){const a=o;o={},typeof a<"u"&&(o[""]=a),t[i]=o}eN(o,e.slice(n+1,e.length),r)}else t[e]=r}Cr.getDefaultSettings().set("useCursors",!0);function Ece(t,e){let r;if(e===void 0)for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);else{let n=-1;for(let i of t)(i=e(i,++n,t))!=null&&(r>i||r===void 0&&i>=i)&&(r=i)}return r}function Dce(t){if(!(o=t.length))return[];for(var e=-1,r=Ece(t,bce),n=new Array(r);++e=1?(r=1,e-1):Math.floor(r*e),i=t[n],o=t[n+1],a=n>0?t[n-1]:2*i-o,s=n{e.image.removeEventListener("load",t.imageLoaded),e.imageLoaded=!0,t.modified()},t.setJsImageData=r=>{e.jsImageData!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.image=null,e.canvas=null),e.jsImageData=r,e.imageLoaded=!0,t.modified())},t.setCanvas=r=>{e.canvas!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.image=null,e.jsImageData=null),e.canvas=r,t.modified())},t.setImage=r=>{e.image!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.canvas=null,e.jsImageData=null),e.image=r,e.imageLoaded=!1,r.complete?t.imageLoaded():r.addEventListener("load",t.imageLoaded),t.modified())},t.getDimensionality=()=>{let r=0,n=0,i=1;if(t.getInputData()){const a=t.getInputData();r=a.getDimensions()[0],n=a.getDimensions()[1],i=a.getDimensions()[2]}return e.jsImageData&&(r=e.jsImageData.width,n=e.jsImageData.height),e.canvas&&(r=e.canvas.width,n=e.canvas.height),e.image&&(r=e.image.width,n=e.image.height),(r>1)+(n>1)+(i>1)},t.getInputAsJsImageData=()=>{if(!e.imageLoaded||t.getInputData())return null;if(e.jsImageData)return e.jsImageData();if(e.canvas)return e.canvas.getContext("2d").getImageData(0,0,e.canvas.width,e.canvas.height);if(e.image){const r=document.createElement("canvas");r.width=e.image.width,r.height=e.image.height;const n=r.getContext("2d");return n.translate(0,r.height),n.scale(1,-1),n.drawImage(e.image,0,0,e.image.width,e.image.height),n.getImageData(0,0,r.width,r.height)}return null}}const Mce=(t,e,r,n)=>{const i=[1,2,1],o=4,a=i,s=o,c=t.length/(e*r);let l=e,f=r,u=t;const d=[u];for(let h=0;hc&&(T+=p),E<-c&&(T-=p),y[T]?S+=y[T]*a[_]:C-=a[_],x+=1}u[m+w]=S/C}y=[...u];for(let m=0;m2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Pce,r),ne.obj(t,e),ne.algo(t,e,6,0),ne.get(t,e,["canvas","image","jsImageData","imageLoaded","resizable"]),ne.setGet(t,e,["repeat","edgeClamp","interpolate","mipLevel"]),Oce(t,e)}const Rce=ne.newInstance(tN,"vtkTexture"),Lce={generateMipmaps:Mce};var Ace={newInstance:Rce,extend:tN,...Lce},nc;(function(t){t[t.Primary=1]="Primary",t[t.Secondary=2]="Secondary",t[t.Primary_And_Secondary=3]="Primary_And_Secondary",t[t.Auxiliary=4]="Auxiliary",t[t.Primary_And_Auxiliary=5]="Primary_And_Auxiliary",t[t.Secondary_And_Auxiliary=6]="Secondary_And_Auxiliary",t[t.Primary_And_Secondary_And_Auxiliary=7]="Primary_And_Secondary_And_Auxiliary",t[t.Fourth_Button=8]="Fourth_Button",t[t.Fifth_Button=16]="Fifth_Button",t[t.Wheel=524288]="Wheel",t[t.Wheel_Primary=524289]="Wheel_Primary"})(nc||(nc={}));var Oi;(function(t){t[t.Shift=16]="Shift",t[t.Ctrl=17]="Ctrl",t[t.Alt=18]="Alt",t[t.Meta=91]="Meta",t[t.ShiftCtrl=1617]="ShiftCtrl",t[t.ShiftAlt=1618]="ShiftAlt",t[t.ShiftMeta=1691]="ShiftMeta",t[t.CtrlAlt=1718]="CtrlAlt",t[t.CtrlMeta=1791]="CtrlMeta",t[t.AltMeta=1891]="AltMeta"})(Oi||(Oi={}));var An;(function(t){t.Active="Active",t.Passive="Passive",t.Enabled="Enabled",t.Disabled="Disabled"})(An||(An={}));var ds;(function(t){t.Default="",t.Highlighted="Highlighted",t.Selected="Selected",t.Locked="Locked",t.AutoGenerated="AutoGenerated"})(ds||(ds={}));var N;(function(t){t.TOOL_ACTIVATED="CORNERSTONE_TOOLS_TOOL_ACTIVATED",t.TOOLGROUP_VIEWPORT_ADDED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_ADDED",t.TOOLGROUP_VIEWPORT_REMOVED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_REMOVED",t.TOOL_MODE_CHANGED="CORNERSTONE_TOOLS_TOOL_MODE_CHANGED",t.CROSSHAIR_TOOL_CENTER_CHANGED="CORNERSTONE_TOOLS_CROSSHAIR_TOOL_CENTER_CHANGED",t.ANNOTATION_ADDED="CORNERSTONE_TOOLS_ANNOTATION_ADDED",t.ANNOTATION_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_COMPLETED",t.ANNOTATION_MODIFIED="CORNERSTONE_TOOLS_ANNOTATION_MODIFIED",t.ANNOTATION_REMOVED="CORNERSTONE_TOOLS_ANNOTATION_REMOVED",t.ANNOTATION_SELECTION_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_SELECTION_CHANGE",t.ANNOTATION_LOCK_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_LOCK_CHANGE",t.ANNOTATION_VISIBILITY_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_VISIBILITY_CHANGE",t.ANNOTATION_RENDERED="CORNERSTONE_TOOLS_ANNOTATION_RENDERED",t.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED",t.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_INTERPOLATION_PROCESS_COMPLETED",t.INTERPOLATED_ANNOTATIONS_REMOVED="CORNERSTONE_TOOLS_INTERPOLATED_ANNOTATIONS_REMOVED",t.SEGMENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_MODIFIED",t.SEGMENTATION_RENDERED="CORNERSTONE_TOOLS_SEGMENTATION_RENDERED",t.SEGMENTATION_REPRESENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_ADDED",t.SEGMENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_ADDED",t.SEGMENTATION_REPRESENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_MODIFIED",t.SEGMENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REMOVED",t.SEGMENTATION_REPRESENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_REMOVED",t.SEGMENTATION_DATA_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_DATA_MODIFIED",t.HISTORY_UNDO="CORNERSTONE_TOOLS_HISTORY_UNDO",t.HISTORY_REDO="CORNERSTONE_TOOLS_HISTORY_REDO",t.KEY_DOWN="CORNERSTONE_TOOLS_KEY_DOWN",t.KEY_UP="CORNERSTONE_TOOLS_KEY_UP",t.MOUSE_DOWN="CORNERSTONE_TOOLS_MOUSE_DOWN",t.MOUSE_UP="CORNERSTONE_TOOLS_MOUSE_UP",t.MOUSE_DOWN_ACTIVATE="CORNERSTONE_TOOLS_MOUSE_DOWN_ACTIVATE",t.MOUSE_DRAG="CORNERSTONE_TOOLS_MOUSE_DRAG",t.MOUSE_MOVE="CORNERSTONE_TOOLS_MOUSE_MOVE",t.MOUSE_CLICK="CORNERSTONE_TOOLS_MOUSE_CLICK",t.MOUSE_DOUBLE_CLICK="CORNERSTONE_TOOLS_MOUSE_DOUBLE_CLICK",t.MOUSE_WHEEL="CORNERSTONE_TOOLS_MOUSE_WHEEL",t.TOUCH_START="CORNERSTONE_TOOLS_TOUCH_START",t.TOUCH_START_ACTIVATE="CORNERSTONE_TOOLS_TOUCH_START_ACTIVATE",t.TOUCH_PRESS="CORNERSTONE_TOOLS_TOUCH_PRESS",t.TOUCH_DRAG="CORNERSTONE_TOOLS_TOUCH_DRAG",t.TOUCH_END="CORNERSTONE_TOOLS_TOUCH_END",t.TOUCH_TAP="CORNERSTONE_TOOLS_TAP",t.TOUCH_SWIPE="CORNERSTONE_TOOLS_SWIPE"})(N||(N={}));var Dt;(function(t){t.Labelmap="Labelmap",t.Contour="Contour",t.Surface="Surface"})(Dt||(Dt={}));var Lf;(function(t){t.UP="UP",t.DOWN="DOWN",t.LEFT="LEFT",t.RIGHT="RIGHT"})(Lf||(Lf={}));var St;(function(t){t.OnInteractionStart="onInteractionStart",t.OnInteractionEnd="onInteractionEnd",t.Preview="preview",t.RejectPreview="rejectPreview",t.AcceptPreview="acceptPreview",t.Fill="fill",t.Interpolate="interpolate",t.StrategyFunction="strategyFunction",t.CreateIsInThreshold="createIsInThreshold",t.Initialize="initialize",t.INTERNAL_setValue="setValue",t.AddPreview="addPreview",t.ComputeInnerCircleRadius="computeInnerCircleRadius",t.GetStatistics="getStatistics",t.EnsureImageVolumeFor3DManipulation="ensureImageVolumeFor3DManipulation",t.EnsureSegmentationVolumeFor3DManipulation="ensureSegmentationVolumeFor3DManipulation"})(St||(St={}));var Ht;(function(t){t.Interaction="Interaction",t.HandlesUpdated="HandlesUpdated",t.StatsUpdated="StatsUpdated",t.InitialSetup="InitialSetup",t.Completed="Completed",t.InterpolationUpdated="InterpolationUpdated",t.History="History",t.MetadataReferenceModified="MetadataReferenceModified",t.LabelChange="LabelChange"})(Ht||(Ht={}));var xa;(function(t){t.POLYSEG_CONTOUR_TO_LABELMAP="Converting Contour to Labelmap",t.POLYSEG_SURFACE_TO_LABELMAP="Converting Surfaces to Labelmap",t.POLYSEG_CONTOUR_TO_SURFACE="Converting Contour to Surface",t.POLYSEG_LABELMAP_TO_SURFACE="Converting Labelmap to Surface",t.SURFACE_CLIPPING="Clipping Surfaces",t.COMPUTE_STATISTICS="Computing Statistics",t.INTERPOLATE_LABELMAP="Interpolating Labelmap",t.COMPUTE_LARGEST_BIDIRECTIONAL="Computing Largest Bidirectional",t.GENERATE_CONTOUR_SETS="Generating Contour Sets"})(xa||(xa={}));const nN=Object.freeze(Object.defineProperty({__proto__:null,AnnotationStyleStates:ds,ChangeTypes:Ht,Events:N,get KeyboardBindings(){return Oi},get MouseBindings(){return nc},SegmentationRepresentations:Dt,StrategyCallbacks:St,get Swipe(){return Lf},ToolModes:An,WorkerTypes:xa},Symbol.toStringTag,{value:"Module"}));let d5={};function Nce(){d5={}}const k9={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:d5,enabledElements:[],handleRadius:6};let Ge={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:d5,enabledElements:[],handleRadius:6};function kce(){Nce(),Ge={...structuredClone({...k9,svgNodeCache:{}}),svgNodeCache:{...k9.svgNodeCache}}}var Vce="Expected a function",rN="__lodash_hash_undefined__",Fce="[object Function]",Uce="[object GeneratorFunction]",Bce="[object Symbol]",Gce=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wce=/^\w*$/,zce=/^\./,$ce=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,jce=/[\\^$.*+?()[\]{}|]/g,Hce=/\\(\\)?/g,Kce=/^\[object .+?Constructor\]$/,qce=typeof Pi=="object"&&Pi&&Pi.Object===Object&&Pi,Xce=typeof self=="object"&&self&&self.Object===Object&&self,WT=qce||Xce||Function("return this")();function Yce(t,e){return t==null?void 0:t[e]}function Jce(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var Zce=Array.prototype,Qce=Function.prototype,iN=Object.prototype,Jw=WT["__core-js_shared__"],V9=function(){var t=/[^.]+$/.exec(Jw&&Jw.keys&&Jw.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),oN=Qce.toString,zT=iN.hasOwnProperty,aN=iN.toString,ele=RegExp("^"+oN.call(zT).replace(jce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),F9=WT.Symbol,tle=Zce.splice,nle=sN(WT,"Map"),Vp=sN(Object,"create"),U9=F9?F9.prototype:void 0,B9=U9?U9.toString:void 0;function Zf(t){var e=-1,r=t?t.length:0;for(this.clear();++e-1}function dle(t,e){var r=this.__data__,n=h5(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}dh.prototype.clear=cle;dh.prototype.delete=lle;dh.prototype.get=ule;dh.prototype.has=fle;dh.prototype.set=dle;function ud(t){var e=-1,r=t?t.length:0;for(this.clear();++e=0&&n>=0&&(r>0||n>0)&&(i+=` ${r} ${n}`),this.addFallbackStyleProperty(i)}static getUniqueInstanceName(e){return`${e}-${UA(Fp)}`}}const kn={iconContent:"",iconSize:16,viewBox:{x:16,y:16},mousePoint:{x:8,y:8},mousePointerGroupString:` +`+M.slice(F+1):Y+=M.slice(k),Y.slice(1)}function D(M,L,V){var G,A,k,F,j,Y;for(k=0,F=(A=V?M.explicitTypes:M.implicitTypes).length;k tag resolver accepts not "'+Y+'" style');G=j.represent[Y](L,Y)}M.dump=G}return!0}return!1}function b(M,L,V,G,A,k){M.tag=null,M.dump=V,D(M,V,!1)||D(M,V,!0);var F=l.call(M.dump);G&&(G=M.flowLevel<0||M.flowLevel>L);var j,Y,re=F==="[object Object]"||F==="[object Array]";if(re&&(Y=(j=M.duplicates.indexOf(V))!==-1),(M.tag!==null&&M.tag!=="?"||Y||M.indent!==2&&L>0)&&(A=!1),Y&&M.usedDuplicates[j])M.dump="*ref_"+j;else{if(re&&Y&&!M.usedDuplicates[j]&&(M.usedDuplicates[j]=!0),F==="[object Object]")G&&Object.keys(M.dump).length!==0?(function(ce,pe,Ee,Oe){var _e,B,O,z,W,K,Z="",ee=ce.tag,xe=Object.keys(Ee);if(ce.sortKeys===!0)xe.sort();else if(typeof ce.sortKeys=="function")xe.sort(ce.sortKeys);else if(ce.sortKeys)throw new a("sortKeys must be a boolean or a function");for(_e=0,B=xe.length;_e1024)&&(ce.dump&&ce.dump.charCodeAt(0)===10?K+="?":K+="? "),K+=ce.dump,W&&(K+=v(ce,pe)),b(ce,pe+1,z,!0,W)&&(ce.dump&&ce.dump.charCodeAt(0)===10?K+=":":K+=": ",Z+=K+=ce.dump));ce.tag=ee,ce.dump=Z||"{}"}(M,L,M.dump,A),Y&&(M.dump="&ref_"+j+M.dump)):(function(ce,pe,Ee){var Oe,_e,B,O,z,W="",K=ce.tag,Z=Object.keys(Ee);for(Oe=0,_e=Z.length;Oe<_e;Oe+=1)z="",Oe!==0&&(z+=", "),ce.condenseFlow&&(z+='"'),O=Ee[B=Z[Oe]],b(ce,pe,B,!1,!1)&&(ce.dump.length>1024&&(z+="? "),z+=ce.dump+(ce.condenseFlow?'"':"")+":"+(ce.condenseFlow?"":" "),b(ce,pe,O,!1,!1)&&(W+=z+=ce.dump));ce.tag=K,ce.dump="{"+W+"}"}(M,L,M.dump),Y&&(M.dump="&ref_"+j+" "+M.dump));else if(F==="[object Array]"){var ue=M.noArrayIndent&&L>0?L-1:L;G&&M.dump.length!==0?(function(ce,pe,Ee,Oe){var _e,B,O="",z=ce.tag;for(_e=0,B=Ee.length;_e "+M.dump)}return!0}function I(M,L){var V,G,A=[],k=[];for(function F(j,Y,re){var ue,ce,pe;if(j!==null&&typeof j=="object")if((ce=Y.indexOf(j))!==-1)re.indexOf(ce)===-1&&re.push(ce);else if(Y.push(j),Array.isArray(j))for(ce=0,pe=j.length;ce=C.length&&(C=void 0),{value:C&&C[T++],done:!C}}};throw new TypeError(S?"Object is not iterable.":"Symbol.iterator is not defined.")},c=this&&this.__read||function(C,S){var _=typeof Symbol=="function"&&C[Symbol.iterator];if(!_)return C;var T,E,D=_.call(C),b=[];try{for(;(S===void 0||S-- >0)&&!(T=D.next()).done;)b.push(T.value)}catch(I){E={error:I}}finally{try{T&&!T.done&&(_=D.return)&&_.call(D)}finally{if(E)throw E.error}}return b};Object.defineProperty(n,"__esModule",{value:!0});var l=i(91),f=i(1),u=i(183),d=i(0),h=i(7),g=i(95),p=i(69),v=i(3),y=i(305),m=i(306),w=i(307),x=function(C){function S(_,T){T===void 0&&(T=!1);var E=C.call(this)||this;return E._hasDeclaration=!1,E._docTypeName="",E._hasDocumentElement=!1,E._currentElementSerialized=!1,E._openTags=[],E._ended=!1,E._fragment=T,E._options=f.applyDefaults(_||{},l.DefaultXMLBuilderCBOptions),E._builderOptions={defaultNamespace:E._options.defaultNamespace,namespaceAlias:E._options.namespaceAlias},E._options.format==="json"?E._writer=new m.JSONCBWriter(E._options):E._options.format==="yaml"?E._writer=new w.YAMLCBWriter(E._options):E._writer=new y.XMLCBWriter(E._options),E._options.data!==void 0&&E.on("data",E._options.data),E._options.end!==void 0&&E.on("end",E._options.end),E._options.error!==void 0&&E.on("error",E._options.error),E._prefixMap=new g.NamespacePrefixMap,E._prefixMap.set("xml",h.namespace.XML),E._prefixIndex={value:1},E._push(E._writer.frontMatter()),E}return a(S,C),S.prototype.ele=function(_,T,E){var D,b;if(f.isObject(_)||f.isString(_)&&(/^\s*/g,">");return this._push(this._writer.text(E)),this},S.prototype.ins=function(_,T){var E;T===void 0&&(T=""),this._serializeOpenTag(!0);try{E=u.fragment(this._builderOptions).ins(_,T).first().node}catch(D){return this.emit("error",D),this}return this._options.wellFormed&&(E.target.indexOf(":")!==-1||/^xml$/i.test(E.target))?(this.emit("error",new Error("Processing instruction target contains invalid characters (well-formed required).")),this):this._options.wellFormed&&!d.xml_isLegalChar(E.data)?(this.emit("error",Error("Processing instruction data contains invalid characters (well-formed required).")),this):(this._push(this._writer.instruction(E.target,E.data)),this)},S.prototype.dat=function(_){var T;this._serializeOpenTag(!0);try{T=u.fragment(this._builderOptions).dat(_).first().node}catch(E){return this.emit("error",E),this}return this._push(this._writer.cdata(T.data)),this},S.prototype.dec=function(_){return _===void 0&&(_={version:"1.0"}),this._fragment?(this.emit("error",Error("Cannot insert an XML declaration into a document fragment.")),this):this._hasDeclaration?(this.emit("error",Error("XML declaration is already inserted.")),this):(this._push(this._writer.declaration(_.version||"1.0",_.encoding,_.standalone)),this._hasDeclaration=!0,this)},S.prototype.dtd=function(_){if(this._fragment)return this.emit("error",Error("Cannot insert a DocType declaration into a document fragment.")),this;if(this._docTypeName!=="")return this.emit("error",new Error("DocType declaration is already inserted.")),this;if(this._hasDocumentElement)return this.emit("error",new Error("Cannot insert DocType declaration after document element.")),this;var T;try{T=u.create().dtd(_).first().node}catch(E){return this.emit("error",E),this}return this._options.wellFormed&&!d.xml_isPubidChar(T.publicId)?(this.emit("error",new Error("DocType public identifier does not match PubidChar construct (well-formed required).")),this):this._options.wellFormed&&(!d.xml_isLegalChar(T.systemId)||T.systemId.indexOf('"')!==-1&&T.systemId.indexOf("'")!==-1)?(this.emit("error",new Error("DocType system identifier contains invalid characters (well-formed required).")),this):(this._docTypeName=_.name,this._push(this._writer.docType(_.name,T.publicId,T.systemId)),this)},S.prototype.import=function(_){var T,E,D=u.fragment().set(this._options);try{D.import(_)}catch(M){return this.emit("error",M),this}try{for(var b=s(D.node.childNodes),I=b.next();!I.done;I=b.next()){var P=I.value;this._fromNode(P)}}catch(M){T={error:M}}finally{try{I&&!I.done&&(E=b.return)&&E.call(b)}finally{if(T)throw T.error}}return this},S.prototype.up=function(){return this._serializeOpenTag(!1),this._serializeCloseTag(),this},S.prototype.end=function(){for(this._serializeOpenTag(!1);this._openTags.length>0;)this._serializeCloseTag();return this._push(null),this},S.prototype._serializeOpenTag=function(_){if(!this._currentElementSerialized&&this._currentElement!==void 0){var T=this._currentElement.node;if(!this._options.wellFormed||T.localName.indexOf(":")===-1&&d.xml_isName(T.localName)){var E="",D=!1,b=this._prefixMap.copy(),I={},P=this._recordNamespaceInformation(T,b,I),M=this._openTags.length===0?null:this._openTags[this._openTags.length-1][1],L=T.namespaceURI;if(L===null&&(L=M),M===L)P!==null&&(D=!0),E=L===h.namespace.XML?"xml:"+T.localName:T.localName,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E));else{var V=T.prefix,G=null;if(V===null&&L===P||(G=b.get(V,L)),V==="xmlns"){if(this._options.wellFormed)return void this.emit("error",new Error("An element cannot have the 'xmlns' prefix (well-formed required)."));G=V}G!==null?(E=G+":"+T.localName,P!==null&&P!==h.namespace.XML&&(M=P||null),this._writer.beginElement(E),this._push(this._writer.openTagBegin(E))):V!==null?(V in I&&(V=this._generatePrefix(L,b,this._prefixIndex)),b.set(V,L),E+=V+":"+T.localName,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)),this._push(this._writer.attribute("xmlns:"+V,this._serializeAttributeValue(L,this._options.wellFormed))),P!==null&&(M=P||null)):P===null||P!==null&&P!==L?(D=!0,E+=T.localName,M=L,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)),this._push(this._writer.attribute("xmlns",this._serializeAttributeValue(L,this._options.wellFormed)))):(E+=T.localName,M=L,this._writer.beginElement(E),this._push(this._writer.openTagBegin(E)))}this._serializeAttributes(T,b,this._prefixIndex,I,D,this._options.wellFormed);var A=L===h.namespace.HTML;A&&!_&&S._VoidElementNames.has(T.localName)?(this._push(this._writer.openTagEnd(E,!0,!0)),this._writer.endElement(E)):A||_?this._push(this._writer.openTagEnd(E,!1,!1)):(this._push(this._writer.openTagEnd(E,!0,!1)),this._writer.endElement(E)),this._currentElementSerialized=!0,this._openTags.push([E,M,this._prefixMap,_]),this._isPrefixMapModified(this._prefixMap,b)&&(this._prefixMap=b),this._writer.level++}else this.emit("error",new Error("Node local name contains invalid characters (well-formed required)."))}},S.prototype._serializeCloseTag=function(){this._writer.level--;var _=this._openTags.pop();if(_!==void 0){var T=c(_,4),E=T[0],D=(T[1],T[2]),b=T[3];this._prefixMap=D,b&&(this._push(this._writer.closeTag(E)),this._writer.endElement(E))}else this.emit("error",new Error("Last element is undefined."))},S.prototype._push=function(_){_===null?(this._ended=!0,this.emit("end")):this._ended?this.emit("error",new Error("Cannot push to ended stream.")):_.length!==0&&(this._writer.hasData=!0,this.emit("data",_,this._writer.level))},S.prototype._fromNode=function(_){var T,E,D,b;if(v.Guard.isElementNode(_)){var I=_.prefix?_.prefix+":"+_.localName:_.localName;_.namespaceURI!==null?this.ele(_.namespaceURI,I):this.ele(I);try{for(var P=s(_.attributes),M=P.next();!M.done;M=P.next()){var L=M.value,V=L.prefix?L.prefix+":"+L.localName:L.localName;L.namespaceURI!==null?this.att(L.namespaceURI,V,L.value):this.att(V,L.value)}}catch(F){T={error:F}}finally{try{M&&!M.done&&(E=P.return)&&E.call(P)}finally{if(T)throw T.error}}try{for(var G=s(_.childNodes),A=G.next();!A.done;A=G.next()){var k=A.value;this._fromNode(k)}}catch(F){D={error:F}}finally{try{A&&!A.done&&(b=G.return)&&b.call(G)}finally{if(D)throw D.error}}this.up()}else v.Guard.isExclusiveTextNode(_)&&_.data?this.txt(_.data):v.Guard.isCommentNode(_)?this.com(_.data):v.Guard.isCDATASectionNode(_)?this.dat(_.data):v.Guard.isProcessingInstructionNode(_)&&this.ins(_.target,_.data)},S.prototype._serializeAttributes=function(_,T,E,D,b,I){var P,M,L=I?new p.LocalNameSet:void 0;try{for(var V=s(_.attributes),G=V.next();!G.done;G=V.next()){var A=G.value;if(I||b||A.namespaceURI!==null){if(I&&L&&L.has(A.namespaceURI,A.localName))return void this.emit("error",new Error("Element contains duplicate attributes (well-formed required)."));I&&L&&L.set(A.namespaceURI,A.localName);var k=A.namespaceURI,F=null;if(k!==null)if(F=T.get(A.prefix,k),k===h.namespace.XMLNS){if(A.value===h.namespace.XML||A.prefix===null&&b||A.prefix!==null&&(!(A.localName in D)||D[A.localName]!==A.value)&&T.has(A.localName,A.value))continue;if(I&&A.value===h.namespace.XMLNS)return void this.emit("error",new Error("XMLNS namespace is reserved (well-formed required)."));if(I&&A.value==="")return void this.emit("error",new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required)."));A.prefix==="xmlns"&&(F="xmlns")}else F===null&&(F=A.prefix===null||T.hasPrefix(A.prefix)&&!T.has(A.prefix,k)?this._generatePrefix(k,T,E):A.prefix,this._push(this._writer.attribute("xmlns:"+F,this._serializeAttributeValue(k,this._options.wellFormed))));if(I&&(A.localName.indexOf(":")!==-1||!d.xml_isName(A.localName)||A.localName==="xmlns"&&k===null))return void this.emit("error",new Error("Attribute local name contains invalid characters (well-formed required)."));this._push(this._writer.attribute((F!==null?F+":":"")+A.localName,this._serializeAttributeValue(A.value,this._options.wellFormed)))}else this._push(this._writer.attribute(A.localName,this._serializeAttributeValue(A.value,this._options.wellFormed)))}}catch(j){P={error:j}}finally{try{G&&!G.done&&(M=V.return)&&M.call(V)}finally{if(P)throw P.error}}},S.prototype._serializeAttributeValue=function(_,T){return T&&_!==null&&!d.xml_isLegalChar(_)?(this.emit("error",new Error("Invalid characters in attribute value.")),""):_===null?"":_.replace(/(?!&(lt|gt|amp|apos|quot);)&/g,"&").replace(//g,">").replace(/"/g,""")},S.prototype._recordNamespaceInformation=function(_,T,E){var D,b,I=null;try{for(var P=s(_.attributes),M=P.next();!M.done;M=P.next()){var L=M.value,V=L.namespaceURI,G=L.prefix;if(V===h.namespace.XMLNS){if(G===null){I=L.value;continue}var A=L.localName,k=L.value;if(k===h.namespace.XML||(k===""&&(k=null),T.has(A,k)))continue;T.set(A,k),E[A]=k||""}}}catch(F){D={error:F}}finally{try{M&&!M.done&&(b=P.return)&&b.call(P)}finally{if(D)throw D.error}}return I},S.prototype._generatePrefix=function(_,T,E){var D="ns"+E.value;return E.value++,T.set(D,_),D},S.prototype._isPrefixMapModified=function(_,T){var E=_._items,D=T._items,b=_._nullItems,I=T._nullItems;for(var P in D){var M=E[P];if(M===void 0)return!0;var L=D[P];if(M.length!==L.length)return!0;for(var V=0;V':u?"':d?"':""},l.prototype.comment=function(f){return this._beginLine()+""},l.prototype.text=function(f){return this._beginLine()+f},l.prototype.instruction=function(f,u){return u?this._beginLine()+"":this._beginLine()+""},l.prototype.cdata=function(f){return this._beginLine()+""},l.prototype.openTagBegin=function(f){return this._lineLength+=1+f.length,this._beginLine()+"<"+f},l.prototype.openTagEnd=function(f,u,d){return d?" />":u?this._writerOptions.allowEmptyTags?">":this._writerOptions.spaceBeforeSlash?" />":"/>":">"},l.prototype.closeTag=function(f){return this._beginLine()+""},l.prototype.attribute=function(f,u){var d=f+'="'+u+'"';return this._writerOptions.prettyPrint&&this._writerOptions.width>0&&this._lineLength+1+d.length>this._writerOptions.width?(d=this._beginLine()+this._indent(1)+d,this._lineLength=d.length,d):(this._lineLength+=1+d.length," "+d)},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){},l.prototype._beginLine=function(){if(this._writerOptions.prettyPrint){var f=(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level);return this._lineLength=f.length,f}return""},l.prototype._indent=function(f){return f<=0?"":this._writerOptions.indent.repeat(f)},l}(i(114).BaseCBWriter);n.XMLCBWriter=s},function(r,n,i){i(74);var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(f){var u=c.call(this,f)||this;return u._hasChildren=[],u._additionalLevel=0,u}return a(l,c),l.prototype.frontMatter=function(){return""},l.prototype.declaration=function(f,u,d){return""},l.prototype.docType=function(f,u,d){return""},l.prototype.comment=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.comment)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.text=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.text)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.instruction=function(f,u){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.ins)+this._sep()+this._val(u?f+" "+u:f)+this._sep()+"}"},l.prototype.cdata=function(f){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.cdata)+this._sep()+this._val(f)+this._sep()+"}"},l.prototype.attribute=function(f,u){return this._comma()+this._beginLine(1)+"{"+this._sep()+this._key(this._builderOptions.convert.att+f)+this._sep()+this._val(u)+this._sep()+"}"},l.prototype.openTagBegin=function(f){var u=this._comma()+this._beginLine()+"{"+this._sep()+this._key(f)+this._sep()+"{";return this._additionalLevel++,this.hasData=!0,u+=this._beginLine()+this._key(this._builderOptions.convert.text)+this._sep()+"[",this._hasChildren.push(!1),u},l.prototype.openTagEnd=function(f,u,d){if(u){var h=this._sep()+"]";return this._additionalLevel--,h+=this._beginLine()+"}"+this._sep()+"}"}return""},l.prototype.closeTag=function(f){var u=this._beginLine()+"]";return this._additionalLevel--,u+=this._beginLine()+"}"+this._sep()+"}"},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){this._hasChildren.pop()},l.prototype._beginLine=function(f){return f===void 0&&(f=0),this._writerOptions.prettyPrint?(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level+f):""},l.prototype._indent=function(f){return f+this._additionalLevel<=0?"":this._writerOptions.indent.repeat(f+this._additionalLevel)},l.prototype._comma=function(){var f=this._hasChildren[this._hasChildren.length-1]?",":"";return this._hasChildren.length>0&&(this._hasChildren[this._hasChildren.length-1]=!0),f},l.prototype._sep=function(){return this._writerOptions.prettyPrint?" ":""},l.prototype._key=function(f){return'"'+f+'":'},l.prototype._val=function(f){return JSON.stringify(f)},l}(i(114).BaseCBWriter);n.JSONCBWriter=s},function(r,n,i){i(74);var o,a=this&&this.__extends||(o=function(c,l){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,u){f.__proto__=u}||function(f,u){for(var d in u)u.hasOwnProperty(d)&&(f[d]=u[d])})(c,l)},function(c,l){function f(){this.constructor=c}o(c,l),c.prototype=l===null?Object.create(l):(f.prototype=l.prototype,new f)});Object.defineProperty(n,"__esModule",{value:!0});var s=function(c){function l(f){var u=c.call(this,f)||this;if(u._rootWritten=!1,u._additionalLevel=0,f.indent.length<2)throw new Error("YAML indententation string must be at least two characters long.");if(f.offset<0)throw new Error("YAML offset should be zero or a positive number.");return u}return a(l,c),l.prototype.frontMatter=function(){return this._beginLine()+"---"},l.prototype.declaration=function(f,u,d){return""},l.prototype.docType=function(f,u,d){return""},l.prototype.comment=function(f){return this._beginLine()+this._key(this._builderOptions.convert.comment)+" "+this._val(f)},l.prototype.text=function(f){return this._beginLine()+this._key(this._builderOptions.convert.text)+" "+this._val(f)},l.prototype.instruction=function(f,u){return this._beginLine()+this._key(this._builderOptions.convert.ins)+" "+this._val(u?f+" "+u:f)},l.prototype.cdata=function(f){return this._beginLine()+this._key(this._builderOptions.convert.cdata)+" "+this._val(f)},l.prototype.attribute=function(f,u){this._additionalLevel++;var d=this._beginLine()+this._key(this._builderOptions.convert.att+f)+" "+this._val(u);return this._additionalLevel--,d},l.prototype.openTagBegin=function(f){var u=this._beginLine()+this._key(f);return this._rootWritten||(this._rootWritten=!0),this.hasData=!0,this._additionalLevel++,u+=this._beginLine(!0)+this._key(this._builderOptions.convert.text)},l.prototype.openTagEnd=function(f,u,d){return u?" "+this._val(""):""},l.prototype.closeTag=function(f){return this._additionalLevel--,""},l.prototype.beginElement=function(f){},l.prototype.endElement=function(f){},l.prototype._beginLine=function(f){return f===void 0&&(f=!1),(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level,f)},l.prototype._indent=function(f,u){if(f+this._additionalLevel<=0)return"";var d=this._writerOptions.indent.repeat(f+this._additionalLevel);return!u&&this._rootWritten?d.substr(0,d.length-2)+"-"+d.substr(-1,1):d},l.prototype._key=function(f){return'"'+f+'":'},l.prototype._val=function(f){return JSON.stringify(f)},l}(i(114).BaseCBWriter);n.YAMLCBWriter=s},function(r,n,i){var o,a=typeof Reflect=="object"?Reflect:null,s=a&&typeof a.apply=="function"?a.apply:function(w,x,C){return Function.prototype.apply.call(w,x,C)};o=a&&typeof a.ownKeys=="function"?a.ownKeys:Object.getOwnPropertySymbols?function(w){return Object.getOwnPropertyNames(w).concat(Object.getOwnPropertySymbols(w))}:function(w){return Object.getOwnPropertyNames(w)};var c=Number.isNaN||function(w){return w!=w};function l(){l.init.call(this)}r.exports=l,l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var f=10;function u(w){if(typeof w!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof w)}function d(w){return w._maxListeners===void 0?l.defaultMaxListeners:w._maxListeners}function h(w,x,C,S){var _,T,E,D;if(u(C),(T=w._events)===void 0?(T=w._events=Object.create(null),w._eventsCount=0):(T.newListener!==void 0&&(w.emit("newListener",x,C.listener?C.listener:C),T=w._events),E=T[x]),E===void 0)E=T[x]=C,++w._eventsCount;else if(typeof E=="function"?E=T[x]=S?[C,E]:[E,C]:S?E.unshift(C):E.push(C),(_=d(w))>0&&E.length>_&&!E.warned){E.warned=!0;var b=new Error("Possible EventEmitter memory leak detected. "+E.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");b.name="MaxListenersExceededWarning",b.emitter=w,b.type=x,b.count=E.length,D=b,console&&console.warn&&console.warn(D)}return w}function g(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(w,x,C){var S={fired:!1,wrapFn:void 0,target:w,type:x,listener:C},_=g.bind(S);return _.listener=C,S.wrapFn=_,_}function v(w,x,C){var S=w._events;if(S===void 0)return[];var _=S[x];return _===void 0?[]:typeof _=="function"?C?[_.listener||_]:[_]:C?function(T){for(var E=new Array(T.length),D=0;D0&&(T=x[0]),T instanceof Error)throw T;var E=new Error("Unhandled error."+(T?" ("+T.message+")":""));throw E.context=T,E}var D=_[w];if(D===void 0)return!1;if(typeof D=="function")s(D,this,x);else{var b=D.length,I=m(D,b);for(C=0;C=0;T--)if(C[T]===x||C[T].listener===x){E=C[T].listener,_=T;break}if(_<0)return this;_===0?C.shift():function(D,b){for(;b+1=0;S--)this.removeListener(w,x[S]);return this},l.prototype.listeners=function(w){return v(this,w,!0)},l.prototype.rawListeners=function(w){return v(this,w,!1)},l.listenerCount=function(w,x){return typeof w.listenerCount=="function"?w.listenerCount(x):y.call(w,x)},l.prototype.listenerCount=y,l.prototype.eventNames=function(){return this._eventsCount>0?o(this._events):[]}},function(r,n,i){Object.defineProperty(n,"__esModule",{value:!0});var o=i(77);n.createCB=function(a){return new o.XMLBuilderCBImpl(a)},n.fragmentCB=function(a){return new o.XMLBuilderCBImpl(a,!0)}}])})})(bA);var Wae=bA.exports,da=Uint8Array,Rf=Uint16Array,IA=Uint32Array,OA=new da([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),MA=new da([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zae=new da([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),PA=function(t,e){for(var r=new Rf(31),n=0;n<31;++n)r[n]=e+=1<>>1|(Nr&21845)<<1;Ml=(Ml&52428)>>>2|(Ml&13107)<<2,Ml=(Ml&61680)>>>4|(Ml&3855)<<4,dC[Nr]=((Ml&65280)>>>8|(Ml&255)<<8)>>>1}var Gg=function(t,e,r){for(var n=t.length,i=0,o=new Rf(e);i>>c]=l}else for(s=new Rf(n),i=0;i>>15-t[i]);return s},w1=new da(288);for(var Nr=0;Nr<144;++Nr)w1[Nr]=8;for(var Nr=144;Nr<256;++Nr)w1[Nr]=9;for(var Nr=256;Nr<280;++Nr)w1[Nr]=7;for(var Nr=280;Nr<288;++Nr)w1[Nr]=8;var AA=new da(32);for(var Nr=0;Nr<32;++Nr)AA[Nr]=5;var Kae=Gg(w1,9,1),qae=Gg(AA,5,1),Hw=function(t){for(var e=t[0],r=1;re&&(e=t[r]);return e},es=function(t,e,r){var n=e/8|0;return(t[n]|t[n+1]<<8)>>(e&7)&r},Kw=function(t,e){var r=e/8|0;return(t[r]|t[r+1]<<8|t[r+2]<<16)>>(e&7)},Xae=function(t){return(t+7)/8|0},Yae=function(t,e,r){(r==null||r>t.length)&&(r=t.length);var n=new(t.BYTES_PER_ELEMENT==2?Rf:t.BYTES_PER_ELEMENT==4?IA:da)(r-e);return n.set(t.subarray(e,r)),n},Jae=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ss=function(t,e,r){var n=new Error(e||Jae[t]);if(n.code=t,Error.captureStackTrace&&Error.captureStackTrace(n,ss),!r)throw n;return n},LT=function(t,e,r){var n=t.length;if(!n||r&&r.f&&!r.l)return e||new da(0);var i=!e||r,o=!r||r.i;r||(r={}),e||(e=new da(n*3));var a=function(pe){var Ee=e.length;if(pe>Ee){var Oe=new da(Math.max(Ee*2,pe));Oe.set(e),e=Oe}},s=r.f||0,c=r.p||0,l=r.b||0,f=r.l,u=r.d,d=r.m,h=r.n,g=n*8;do{if(!f){s=es(t,c,1);var p=es(t,c+1,3);if(c+=3,p)if(p==1)f=Kae,u=qae,d=9,h=5;else if(p==2){var w=es(t,c,31)+257,x=es(t,c+10,15)+4,C=w+es(t,c+5,31)+1;c+=14;for(var S=new da(C),_=new da(19),T=0;T>>4;if(v<16)S[T++]=v;else{var P=0,M=0;for(v==16?(M=3+es(t,c,3),c+=2,P=S[T-1]):v==17?(M=3+es(t,c,7),c+=3):v==18&&(M=11+es(t,c,127),c+=7);M--;)S[T++]=P}}var L=S.subarray(0,w),V=S.subarray(w);d=Hw(L),h=Hw(V),f=Gg(L,d,1),u=Gg(V,h,1)}else ss(1);else{var v=Xae(c)+4,y=t[v-4]|t[v-3]<<8,m=v+y;if(m>n){o&&ss(0);break}i&&a(l+y),e.set(t.subarray(v,m),l),r.b=l+=y,r.p=c=m*8,r.f=s;continue}if(c>g){o&&ss(0);break}}i&&a(l+131072);for(var G=(1<>>4;if(c+=P&15,c>g){o&&ss(0);break}if(P||ss(2),F<256)e[l++]=F;else if(F==256){k=c,f=null;break}else{var j=F-254;if(F>264){var T=F-257,Y=OA[T];j=es(t,c,(1<>>4;re||ss(3),c+=re&15;var V=Hae[ue];if(ue>3){var Y=MA[ue];V+=Kw(t,c)&(1<g){o&&ss(0);break}i&&a(l+131072);for(var ce=l+j;l>3&1)+(e>>4&1);n>0;n-=!t[r++]);return r+(e&2)},ese=function(t){var e=t.length;return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0},tse=function(t){((t[0]&15)!=8||t[0]>>>4>7||(t[0]<<8|t[1])%31)&&ss(6,"invalid zlib data"),t[1]&32&&ss(6,"invalid zlib data: preset dictionaries not supported")};function nse(t,e){return LT(t,e)}function rse(t,e){return LT(t.subarray(Qae(t),-8),new da(ese(t)))}function ise(t,e){return LT((tse(t),t.subarray(2,-4)),e)}function ose(t,e){return t[0]==31&&t[1]==139&&t[2]==8?rse(t):(t[0]&15)!=8||t[0]>>4>7||(t[0]<<8|t[1])%31?nse(t,e):ise(t,e)}var ase=typeof TextDecoder<"u"&&new TextDecoder,sse=0;try{ase.decode(Zae,{stream:!0}),sse=1}catch{}const ca=[];ca[45]=62;ca[95]=63;const Hd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t>16&255,n[f++]=l>>8&255,n[f++]=l&255}switch(a){case 3:for(;!Ls(t[c]);)c++;for(l=ca[t.charCodeAt(c++)]<<10;!Ls(t[c]);)c++;for(l|=ca[t.charCodeAt(c++)]<<4;!Ls(t[c]);)c++;l|=ca[t.charCodeAt(c++)]>>2,n[f++]=l>>8&255,n[f++]=l&255;break;case 2:for(;!Ls(t[c]);)c++;for(l=ca[t.charCodeAt(c++)]<<2;!Ls(t[c]);)c++;l|=ca[t.charCodeAt(c++)]>>4,n[f++]=l&255;break;case 1:throw new Error("BASE64: remain 1 should not happen")}return f}function use(t){const e=cse(t),r=e[e.length-1].end+1,n=(4-r%4)%4,i=(r+n)*3/4-n,o=new ArrayBuffer(i),a=new Uint8Array(o);let s=0;for(let c=0;c>18]+Hd[n>>12&63]+Hd[n>>6&63]+Hd[n&63]}function fse(t){const e=new Uint8Array(t),r=t.byteLength%3,n=t.byteLength-r,i=Array(n/3);for(let o=0;o0){const o=D9(e[n],e[n+1]||0,e[n+2]||0);r===1?i.push(`${o.substr(0,2)}==`):r===2&&i.push(`${o.substr(0,3)}=`)}return i.join("")}var AT={toArrayBuffer:use,fromArrayBuffer:fse};function dse(t,e){e.classHierarchy.push("vtkStringArray"),t.getComponent=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return e.values[r*e.numberOfComponents+n]},t.setComponent=(r,n,i)=>{i!==e.values[r*e.numberOfComponents+n]&&(e.values[r*e.numberOfComponents+n]=i,t.modified())},t.getData=()=>e.values,t.getTuple=function(r){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];const i=e.numberOfComponents||1;n.length&&(n.length=i);const o=r*i;for(let a=0;a0&&arguments[0]!==void 0?arguments[0]:1)*e.numberOfComponents},t.getNumberOfComponents=()=>e.numberOfComponents,t.getNumberOfValues=()=>e.values.length,t.getNumberOfTuples=()=>e.values.length/e.numberOfComponents,t.getDataType=()=>e.dataType,t.newClone=()=>kA({name:e.name,numberOfComponents:e.numberOfComponents,empty:!0}),t.getName=()=>(e.name||t.setName(`vtkStringArray${t.getMTime()}`),e.name),t.setData=(r,n)=>{e.values=r,e.size=r.length,n&&(e.numberOfComponents=n),e.size%e.numberOfComponents!==0&&(e.numberOfComponents=1),t.modified()}}const hse={name:"",numberOfComponents:1,size:0,dataType:"string"};function NA(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Object.assign(e,hse,r),!e.empty&&!e.values&&!e.size)throw new TypeError("Cannot create vtkStringArray object without: size > 0, values");e.values?Array.isArray(e.values)&&(e.values=[...e.values]):e.values=[],e.values&&(e.size=e.values.length),ne.obj(t,e),ne.set(t,e,["name"]),dse(t,e)}const kA=ne.newInstance(NA,"vtkStringArray");var gse={newInstance:kA,extend:NA};function pse(t,e){return[...t.getElementsByTagName(e)]}function b9(t,e){return pse(t,e)[0]}function mse(t){return Wae.create(t)}function vse(t){const e=/^\s*\s*_/m,r=/\n\s*<\/AppendedData>/m;return Mae.extractBinary(t,e,r)}const Ql={Int8:Int8Array,UInt8:Uint8Array,Int16:Int16Array,UInt16:Uint16Array,Int32:Int32Array,UInt32:Uint32Array,Int64:Int32Array,UInt64:Uint32Array,Float32:Float32Array,Float64:Float64Array},Lp={Int8:1,UInt8:1,Int16:2,UInt16:2,Int32:4,UInt32:4,Int64:8,UInt64:8,Float32:4,Float64:8};function hC(t){const e=t.length-1;return t.filter((r,n)=>n0&&(o===0?a=n*i:a=(n-1)*i+o);const s=new ArrayBuffer(a),c={offset:0,uint8:new Uint8Array(s)};let l=wse(r);for(;l{d.trim().length&&(f[u++]=Number(d))})}else if(c==="binary"){const u=new Uint8Array(AT.toArrayBuffer(e.firstChild.nodeValue.trim()));if(r==="vtkZLibDataCompressor"){const d=NT(u,i);f=new Ql[a](d.buffer),/^U?Int64$/.test(a)&&(f=hC(f))}else f=new Ql[a](u.buffer,Lp[i]),a.indexOf("Int64")!==-1&&(f=hC(f))}else if(c==="appended"){const u=Number(e.getAttribute("offset"));f=gC(new Uint8Array(o,u),a,i)}else console.error("Format not supported",c);return{name:s,values:f,numberOfComponents:l}}function qw(t){return new TextDecoder().decode(t).split("\0").slice(0,-1)}function Cse(t,e,r,n,i){const o=t.getAttribute("Name"),a=t.getAttribute("format"),s=Number(t.getAttribute("NumberOfComponents")||"1"),l=Number(t.getAttribute("NumberOfTuples")||"1")*s,f=[];if(a==="ascii"){const u=t.firstChild.nodeValue.trim().split(/\s+/);let d=0;const h=[];for(;f.length{const p=g-h;u[d++]=p;for(let v=0;v{const d=e.getAttribute(u);d&&(c[d]=r[`set${u}`])});const l=e.getElementsByTagName("DataArray"),f=l.length;for(let u=0;uYt.newInstance(Ap(Number(s.getAttribute("NumberOfTuples")),s,e,r,n,i))),a=[...t.getElementsByTagName("Array")].filter(s=>s.getAttribute("type")==="String").map(s=>gse.newInstance(Cse(s,e,r,n,i)));return[...o,...a]}function Ese(t,e){e.classHierarchy.push("vtkXMLReader"),e.dataAccessHelper||(e.dataAccessHelper=Rae.get("http"));function r(n){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return e.dataAccessHelper.fetchBinary(n,i)}t.setUrl=function(n){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};e.url=n;const o=n.split("/");return o.pop(),e.baseURL=o.join("/"),t.loadData(i)},t.loadData=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r(e.url,n).then(t.parseAsArrayBuffer)},t.parseAsArrayBuffer=n=>{if(!n)return!1;if(n!==e.rawDataBuffer)t.modified();else return!0;const{text:i,binaryBuffer:o}=vse(n);e.rawDataBuffer=n,e.binaryBuffer=o;const s=mse(i).root(),c=s.node,l=c.getAttribute("type"),f=c.getAttribute("compressor"),u=c.getAttribute("byte_order"),d=c.getAttribute("header_type")||"UInt32";if(f&&f!=="vtkZLibDataCompressor")return console.error("Invalid compressor",f),!1;if(u&&u!=="LittleEndian")return console.error("Only LittleEndian encoding is supported"),!1;if(l!==e.dataType)return console.error("Invalid data type",l,"expecting",e.dataType),!1;if(b9(c,"AppendedData")){const p=b9(c,"AppendedData"),v=p.getAttribute("encoding"),y=s.filter(_=>{const{node:T}=_;return T.nodeType===Node.ELEMENT_NODE&&T.getAttribute("format")==="appended"&&T.hasAttribute("offset")},!1,!0).map(_=>({node:_.node,offset:Number(_.node.getAttribute("offset"))}));y.sort((_,T)=>_.offset-T.offset);let m=e.binaryBuffer;v==="base64"&&(m=p.textContent.trim().substr(1));const w=[];for(let _=0;__+T.length,0),C=new ArrayBuffer(x),S=new Uint8Array(C);for(let _=0,T=0;_{t.parseAsArrayBuffer(e.rawDataBuffer)}}const Dse={};function bse(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Dse,r),ne.obj(t,e),ne.get(t,e,["url","baseURL"]),ne.setGet(t,e,["dataAccessHelper"]),ne.algo(t,e,0,1),Ese(t,e)}var Np={extend:bse,processDataArray:Ap,processFieldData:_se,processCells:Sse};function Ise(t,e,r,n,i,o,a){const s=Number(r.getAttribute(`NumberOf${e}`));if(s>0){const c=r.getElementsByTagName(e)[0].getElementsByTagName("DataArray")[0],{values:l,numberOfComponents:f}=Np.processDataArray(s,c,n,i,o,a);t[`get${e}`]().setData(l,f)}return s}function Ose(t,e,r,n,i,o,a){const s=Number(r.getAttribute(`NumberOf${e}`));if(s>0){const c=Np.processCells(s,r.getElementsByTagName(e)[0],n,i,o,a);t[`get${e}`]().setData(c)}return s}function Mse(t,e){e.classHierarchy.push("vtkXMLPolyDataReader"),t.parseXML=(r,n,i,o,a)=>{const c=r.getElementsByTagName(e.dataType)[0].getElementsByTagName("Piece"),l=c.length;for(let f=0;f{g+=Ose(u,p,d,i,o,a,e.binaryBuffer)}),Np.processFieldData(h,d.getElementsByTagName("PointData")[0],u.getPointData(),i,o,a,e.binaryBuffer),Np.processFieldData(g,d.getElementsByTagName("CellData")[0],u.getCellData(),i,o,a,e.binaryBuffer),e.output[f]=u}}}const Pse={dataType:"PolyData"};function VA(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Pse,r),Np.extend(t,e,r),Mse(t,e)}const Rse=ne.newInstance(VA,"vtkXMLPolyDataReader");var Lse={newInstance:Rse,extend:VA},is;(function(t){t[t.None=0]="None",t[t.Capture=1]="Capture",t[t.Bubble=2]="Bubble"})(is||(is={}));class u5{constructor(e){this._eventListeners=new Map,this._children=new Map,this._target=e}get isEmpty(){return this._eventListeners.size===0&&this._children.size===0}addEventListener(e,r,n){const i=e.indexOf(".");if(i!==-1){const a=e.substring(0,i);let s=this._children.get(a);s||(s=new u5(this._target),this._children.set(a,s)),e=e.substring(i+1),s.addEventListener(e,r,n)}else this._addEventListener(e,r,n)}removeEventListener(e,r,n){const i=e.indexOf(".");if(i!==-1){const a=e.substring(0,i),s=this._children.get(a);if(!s)return;e=e.substring(i+1),s.removeEventListener(e,r,n),s.isEmpty&&this._children.delete(a)}else this._removeEventListener(e,r,n)}reset(){Array.from(this._children.entries()).forEach(([e,r])=>{if(r.reset(),r.isEmpty)this._children.delete(e);else throw new Error("Child is not empty and cannot be removed")}),this._unregisterAllEvents()}_addEventListener(e,r,n){let i=this._eventListeners.get(e);i||(i=new Map,this._eventListeners.set(e,i));const a=(n==null?void 0:n.capture)??!1?is.Capture:is.Bubble,s=i.get(r)??is.None;if(s&a){console.warn("A listener is already registered for this phase");return}i.set(r,s|a),this._target.addEventListener(e,r,n)}_removeEventListener(e,r,n){const o=(n==null?void 0:n.capture)??!1?is.Capture:is.Bubble,a=this._eventListeners.get(e);if(!a)return;(r?[r]:Array.from(a.keys())).forEach(c=>{const l=a.get(c)??is.None;if(!!!(l&o))return;this._target.removeEventListener(e,c,n);const u=l^o;u===is.None?a.delete(c):a.set(c,u)}),a.size||this._eventListeners.delete(e)}_unregisterAllListeners(e,r){Array.from(r.entries()).forEach(([n,i])=>{const o=is.Capture;for(let a=o;i;a<<=1){if(!(i&a))continue;const s=a===is.Capture;this.removeEventListener(e,n,{capture:s}),i^=a}})}_unregisterAllEvents(){Array.from(this._eventListeners.entries()).forEach(([e,r])=>{this._unregisterAllListeners(e,r)})}}class FA{constructor(){this._targetsEventListeners=new Map}addEventListener(e,r,n,i){let o=this._targetsEventListeners.get(e);o||(o=new u5(e),this._targetsEventListeners.set(e,o)),o.addEventListener(r,n,i)}removeEventListener(e,r,n,i){const o=this._targetsEventListeners.get(e);o&&(o.removeEventListener(r,n,i),o.isEmpty&&this._targetsEventListeners.delete(e))}reset(){Array.from(this._targetsEventListeners.entries()).forEach(([e,r])=>{r.reset(),this._targetsEventListeners.delete(e)})}}const Ase=Object.freeze(Object.defineProperty({__proto__:null,MultiTargetEventListenerManager:FA,TargetEventListeners:u5},Symbol.toStringTag,{value:"Module"}));function Nse(t,e){const r=t.getSize();for(let n=0;n0?r:Fse)>>>0).join(typeof e=="string"?e:Use)}function Bse(t,e,r){let n=t[e];n instanceof Array||(n=[0],Object.defineProperty(t,e,{value:n}));for(let i=!0,o=0;i&&o{const r=Vr(t);I9[r]=e},get:(t,e)=>{if(t==="calibratedPixelSpacing"){const r=Vr(e);return I9[r]}}};function vg(t,e,r=1e-5){return Math.abs(t[0]+e[0])=e[0]||t[1]<0||t[1]>=e[1]||t[2]<0||t[2]>=e[2])}function Wse(t,e){let r;e?r=[Jr(e)]:r=Qo();const n=[];return r.forEach(i=>{const o=t.getActors(),a=i.getVolumeViewports();for(const s of a){const c=s.getActors();if(c.length!==o.length)continue;o.every(({uid:f})=>c.find(u=>f===u.uid))&&n.push(s)}}),n}const BA=t=>t.preScale.scaled&&t.preScale.scalingParameters.suvbw;function GA(t,e,r=void 0,n="_thumbnails",i={displayArea:{imageArea:[1,1]}}){if(!t||!(t instanceof HTMLCanvasElement))throw new Error("canvas element is required");const o=!e.imageId,a=!o&&e,s=o&&e,l=`renderGPUViewport-${a.imageId||s.volumeId}`,f=document.createElement("div"),u=window.devicePixelRatio||1;i.displayArea||(i.displayArea={imageArea:[1,1]});const d=t.width,h=t.height;f.style.width=`${d/u+Ug}px`,f.style.height=`${h/u+Ug}px`,f.style.visibility="hidden",f.style.position="absolute",document.body.appendChild(f);const g=l.split(":").join("-");f.setAttribute("viewport-id-for-remove",g);const p=Mc(f),v=Jr(n)||new CA(n);let y=v.getViewport(l);if(!y){const m={viewportId:l,type:o?mr.ORTHOGRAPHIC:mr.STACK,element:f,defaultOptions:{...i,suppressEvents:!0}};v.enableElement(m),y=v.getViewport(l)}return new Promise(m=>{let w=!1,{viewReference:x}=i;const C=S=>{if(w)return;if(x){const M=x;x=null,y.setViewReference(M),y.render();return}t.getContext("2d").drawImage(p,0,0,p.width,p.height,0,0,t.width,t.height);const T=y.canvasToWorld([0,0]),E=y.canvasToWorld([p.width/u,0]),D=y.canvasToWorld([0,p.height/u]),b=En([0,0,0],y.canvasToWorld([1/u,0]),T),I=En([0,0,0],y.canvasToWorld([0,1/u]),T),P=1;w=!0,f.removeEventListener(Xe.IMAGE_RENDERED,C),setTimeout(()=>{v.disableElement(l),document.querySelectorAll(`[viewport-id-for-remove="${g}"]`).forEach(L=>{L.remove()})},0),m({origin:T,bottomLeft:D,topRight:E,thicknessMm:P,rightVector:b,downVector:I})};f.addEventListener(Xe.IMAGE_RENDERED,C),o?y.setVolumes([s],!1,!0):y.renderImageObject(e),y.resetCamera(),r==="PT"&&!BA(a)&&y.setProperties({voiRange:{lower:a.minPixelValue,upper:a.maxPixelValue}}),y.render()})}function WA(t,e,r,n,i){if(e.volumeId)throw new Error("Unsupported volume rendering for CPU");const a=e,s=yA(t,a,r),c={canvas:t,viewport:s,image:a,renderingTools:{}};c.transform=Pp(c);const l=!0;return new Promise((f,u)=>{pA(c,l),f(null)})}function zse(t){const{canvas:e,imageId:r,viewReference:n,requestType:i=hn.Thumbnail,priority:o=-5,renderingEngineId:a="_thumbnails",useCPURendering:s=!1,thumbnail:c=!1,imageAspect:l=!1,viewportOptions:f}=t,u=n==null?void 0:n.volumeId,d=u&&!r,h=n&&f?{...f,viewReference:n}:f,g=s?WA:GA;return new Promise((p,v)=>{function y(C,S){var D;const{modality:_}=mt("generalSeriesModule",S)||{},T=!d&&C,E=d&&C;T&&(T.isPreScaled=T.isPreScaled||((D=T.preScale)==null?void 0:D.scaled)),c&&(e.height=256,e.width=256),l&&T&&(e.width=T&&e.height*T.width/T.height),e.style.width=`${e.width/devicePixelRatio}px`,e.style.height=`${e.height/devicePixelRatio}px`,E&&s&&v(new Error("CPU rendering of volume not supported")),g(e,C,_,a,h).then(p)}function m(C,S){console.error(C,S),v(C)}function w(C,S,_){return xu(C,_).then(T=>{y.call(this,T,C)},T=>{m.call(this,T,C)})}const x={useRGBA:!!s,requestType:i};if(u){const C=Le.getVolume(u);C||v(new Error(`Volume id ${u} not found in cache`));const S=C.imageIds[0];y(C,S)}else Ao.addRequest(w.bind(null,r,null,x),i,{imageId:r},o)})}const O9={HISTORY_UNDO:"CORNERSTONE_TOOLS_HISTORY_UNDO",HISTORY_REDO:"CORNERSTONE_TOOLS_HISTORY_REDO"};class zA{constructor(e="Tools",r=50){this.position=-1,this.redoAvailable=0,this.undoAvailable=0,this.ring=new Array,this.label=e,this._size=r}get size(){return this._size}set size(e){this.ring=new Array(e),this._size=e,this.position=-1,this.redoAvailable=0,this.undoAvailable=0}undo(e=1){for(;e>0&&this.undoAvailable>0;){const r=this.ring[this.position];r.restoreMemo(!0),r.id&&Ke.dispatchEvent(new CustomEvent(O9.HISTORY_UNDO,{detail:{isUndo:!0,id:r.id,operationType:r.operationType||"annotation",memo:r}})),e--,this.redoAvailable++,this.undoAvailable--,this.position=(this.position-1+this.size)%this.size}}undoIf(e){return this.undoAvailable>0&&e(this.ring[this.position])?(this.undo(),!0):!1}redo(e=1){for(;e>0&&this.redoAvailable>0;){const r=(this.position+1)%this.size,n=this.ring[r];n.restoreMemo(!1),n.id&&Ke.dispatchEvent(new CustomEvent(O9.HISTORY_REDO,{detail:{isUndo:!1,id:n.id,operationType:n.operationType||"annotation",memo:n}})),e--,this.position=r,this.undoAvailable++,this.redoAvailable--}}push(e){var n;if(!e)return;const r=e.restoreMemo?e:(n=e.createMemo)==null?void 0:n.call(e);if(r)return this.redoAvailable=0,this.undoAvailable{n.getViewports().forEach(o=>{o.hasImageURI(t)&&r.push(o)})}),r}function FT(t,e){const r=$se(t,e);return r?r.index:null}function $se(t,e){const r=e.getImageIds(),n=e.getCurrentImageIdIndex();if(r.length===0)return null;const i=c=>{const l=jse(c);if(!l)return null;const f=qs(l.planeNormal,l.imagePositionPatient);return Mp(f,t)},o={distance:i(r[n])??1/0,index:n},a=r.slice(n+1);for(let c=0;c=0;c--){const l=s[c],f=i(l);if(!(f===null||f===o.distance))if(f{const[r,n]=t,i=`${r}_${n}`;df[i]||(df[i]={}),df[i]=e},get:(t,e,r)=>{if(t!=="spatialRegistrationModule")return;const n=`${e}_${r}`;if(df[n])return df[n];const i=`${r}_${e}`;if(df[i])return oi(Zo(),df[i])}};ah(kp.get.bind(kp));const Hse=.05;function HA(t,e){const r=t.getSliceIndex(),n=e.getSliceIndex(),i=mt("imagePlaneModule",r.toString()),o=mt("imagePlaneModule",n.toString());if(!i||!o){console.log("Viewport spatial registration requires image plane module");return}const{imageOrientationPatient:a}=o;if(!i.imageOrientationPatient.every((d,h)=>Math.abs(d-a[h])0||t[0]0||t[1]0||t[2]{r.getViewports().forEach(({element:i})=>{t.push(Ce(i))})}),t}function Xse(t){const e=Ce(t);if(!e)return;const{viewport:r}=e;if(!(r instanceof lr))throw new Error(`An image can only be fetched for a stack viewport and not for a viewport of type: ${r.type}`);return r.getCornerstoneImage()}function Nu(t){if(t.length<=1)return!1;const e=t[0],{modality:r,seriesInstanceUID:n}=mt("generalSeriesModule",e),{imageOrientationPatient:i,pixelSpacing:o,frameOfReferenceUID:a,columns:s,rows:c,usingDefaultValues:l}=mt("imagePlaneModule",e);if(l)return!1;const f={modality:r,imageOrientationPatient:i,pixelSpacing:o,columns:s,rows:c,seriesInstanceUID:n};let u=!0;for(let d=0;dYse.has(r)):!1}async function Jse({viewport:t,options:e={}}){const r=t.getRenderingEngine();let n=e.volumeId||`${Dn()}`;n.split(":").length===0&&(n=`${Gie()}:${n}`);const{id:i,element:o}=t,a=e.viewportId||i,s=t.getImageIds(),c=t.getViewPresentation(),l=t.getViewReference();r.enableElement({viewportId:a,type:mr.ORTHOGRAPHIC,element:o,defaultOptions:{background:e.background,orientation:e.orientation}}),(await Vv(n,{imageIds:s})).load();const u=r.getViewport(a);await xae(r,[{volumeId:n}],[a]);const d=()=>{u.render(),o.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,d)};return(()=>{o.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,d)})(),u.setViewPresentation(c),u.setViewReference(l),u.render(),u}async function Zse({viewport:t,options:e}){const r=t,{id:n,element:i}=r,o=t.getRenderingEngine(),{background:a}=e,s=e.viewportId||n,c=Le.getVolume(r.getVolumeId());if(!(c instanceof lh))throw new Error("Currently, you cannot decache a volume that is not an ImageVolume. So, unfortunately, volumes such as nifti (which are basic Volume, without imageIds) cannot be decached.");const l={viewportId:s,type:mr.STACK,element:i,defaultOptions:{background:a}},f=r.getViewReference();o.enableElement(l);const u=o.getViewport(s);return await u.setStack(c.imageIds),u.setViewReference(f),u.render(),u}function an(t,e=2){if(Array.isArray(t))return t.map(i=>an(i,e)).join(", ");if(t==null||t==="")return"NaN";t=Number(t);const r=Math.abs(t);if(r<1e-4)return`${t}`;const n=r>=100?e-2:r>=10?e-1:r>=1?e:r>=.1?e+1:r>=.01?e+2:r>=.001?e+3:e+4;return t.toFixed(n)}function eu(t){return Math.round(t/wa)*wa}function qA(t,e,r){const n=t.length===e*r*4,i=t.length===e*r*3;if(n||i){const o=new Float32Array(e*r);let a=0,s=0;const c=n?4:3;for(let l=0;l=r.length?(M9(r),r):(M9(r),r.slice(0,e))}function M9(t){for(let e=t.length-1;e>0;e--){const r=Math.floor(Math.random()*(e+1));[t[e],t[r]]=[t[r],t[e]]}}function Xw(t){const e=t.toString(16);return e.length==1?"0"+e:e}function ece(t,e,r){return"#"+Xw(t)+Xw(e)+Xw(r)}function tce(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null}const nce=Object.freeze(Object.defineProperty({__proto__:null,hexToRgb:tce,rgbToHex:ece},Symbol.toStringTag,{value:"Module"}));function XA(t,e){if(t===e)return!0;if(t==null||e==null)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch(r){return console.debug("Error in JSON.stringify during deep comparison:",r),t===e}}function rce(t,e,r){if(!r)throw new Error("getVolume is required, use the utilities export instead ");if(t.modality)return t.modality;if(t.setVolumes)return e=e??t.getVolumeId(),!e||!r?void 0:r(e).metadata.Modality;throw new Error("Invalid viewport type")}const ice=(t,e)=>t.reduce((r,n)=>((r[n[e]]=r[n[e]]||[]).push(n),r),{});function oce(t){const e=t.map(a=>{const{imagePositionPatient:s}=mt("imagePlaneModule",a)||{};return{imageId:a,imagePositionPatient:s}});if(!e.every(a=>a.imagePositionPatient))return null;const r=ice(e,"imagePositionPatient"),n=Object.keys(r),i=r[n[0]].length;return i===1||!n.every(a=>r[a].length===i)?null:r}function ace(t,e){const r={};let n=[];const i=Object.keys(t);for(let o=0;ojh(i,r[0]),i=>jh(i,r[1]),i=>jh(i,r[2]),i=>jh(i,r[3]),i=>jh(i,r[4]),sce,cce,lce,fce];for(let i=0;ic-l).map(c=>o[c].map(l=>l.imageId)),splittingTag:r[i]}}return{imageIdGroups:[t],splittingTag:null}}function dce(t){const{imageIdGroups:e,splittingTag:r}=YA(t);return{isDynamicVolume:e.length>1,timePoints:e,splittingTag:r}}function hce(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o}=e;if(e.modality==="PT"&&typeof o=="number")for(let a=0;at.getImageIds().length-1||a+i<0){const s={imageIdIndex:a,direction:i};at(Ke,Xe.STACK_SCROLL_OUT_OF_BOUNDS,s)}t.scroll(i,e.debounceLoading,e.loop)}}function gce(t,e,r,n=!1){const i=n,{numScrollSteps:o,currentStepIndex:a,sliceRangeInfo:s}=Vf(t,e,i);if(!s)return;const{sliceRange:c,spacingInNormalDirection:l,camera:f}=s,{focalPoint:u,viewPlaneNormal:d,position:h}=f,{newFocalPoint:g,newPosition:p}=m0(u,h,c,d,l,r);t.setCamera({focalPoint:g,position:p}),t.render();const v=a+r,y={volumeId:e,viewport:t,delta:r,desiredStepIndex:v,currentStepIndex:a,numScrollSteps:o,currentImageId:t.getCurrentImageId()};(v>o||v<0)&&t.getCurrentImageId()?at(Ke,Xe.VOLUME_VIEWPORT_SCROLL_OUT_OF_BOUNDS,y):at(Ke,Xe.VOLUME_VIEWPORT_SCROLL,y)}async function Aa(t,e={}){const{imageIndex:r,debounceLoading:n,volumeId:i}=e,o=Ce(t);if(!o)throw new Error("Element has been disabled");const{viewport:a}=o,{imageIndex:s,numberOfSlices:c}=pce(a,n),f=mce(c,r)-s;ps(a,{delta:f,debounceLoading:n,volumeId:i})}function pce(t,e){return t instanceof lr?{numberOfSlices:t.getImageIds().length,imageIndex:e?t.getTargetImageIdIndex():t.getCurrentImageIdIndex()}:{numberOfSlices:t.getNumberOfSlices(),imageIndex:t.getSliceIndex()}}function mce(t,e){const r=t-1;return Wv(e,0,r)}function GT(t,e,r={}){const n=Le.getVolume(t);if(!n)throw new Error(`Referenced volume with id ${t} does not exist.`);const{metadata:i,spacing:o,direction:a,dimensions:s}=n,{minX:c,maxX:l,minY:f,maxY:u,minZ:d,maxZ:h}=e,g=[Math.min(c,l),Math.min(f,u),Math.min(d,h)],p=B0(n.imageData,g),v=[Math.abs(l-c)+1,Math.abs(u-f)+1,Math.abs(h-d)+1],{targetBuffer:y}=r,m={metadata:i,dimensions:v,spacing:o,origin:p,direction:a,targetBuffer:y,scalarData:(y==null?void 0:y.type)==="Float32Array"?new Float32Array(v[0]*v[1]*v[2]):void 0},w=TT(Dn(),m),x=w.voxelManager.getCompleteScalarDataArray(),C=v[0]*v[1],S=s[0]*s[1],_=n.voxelManager.getCompleteScalarDataArray();for(let T=0;T=a)){for(let m=d-n;m<=d+n;m++)if(!(m<0||m>=o))for(let w=u-n;w<=u+n;w++){if(w<0||w>=i)continue;const x=y*s+m*i+w,C=t[x];c+=C,l+=C*C,f++}}if(f===0){const y=h*s+d*i+u;return y>=0&&yc/n),type:ls.ERMF,isProjection:a}:(console.warn("EstimatedRadiographicMagnificationFactor was not present. Unable to correct ImagerPixelSpacing."),{PixelSpacing:r,type:ls.PROJECTION,isProjection:a}):{PixelSpacing:e,type:ls.UNKNOWN,isProjection:a}}function wce(t){const{SequenceOfUltrasoundRegions:e}=t,r=Array.isArray(e);if(r&&e.length>1){console.warn("Sequence of Ultrasound Regions > one entry. This is not yet implemented, all measurements will be shown in pixels.");return}const{PhysicalDeltaX:n,PhysicalDeltaY:i}=r?e[0]:e;return{PixelSpacing:[n*10,i*10]}}function xce(t){const{PixelSpacing:e,SOPClassUID:r,SequenceOfUltrasoundRegions:n}=t;return n?wce(t):vce.has(r)?yce(t):{PixelSpacing:e,type:ls.NOT_APPLICABLE,isProjection:!1}}const ZA=(t,e)=>rce(t,e,Le.getVolume),Mn=Object.freeze(Object.defineProperty({__proto__:null,FrameRange:v0,HistoryMemo:VT,PointsManager:D2,ProgressiveIterator:Nv,RLEVoxelMap:Pd,VoxelManager:tc,actorIsA:Yo,applyPreset:iA,autoLoad:oC,buildMetadata:lA,calculateNeighborhoodStats:JA,calculateSpacingBetweenImageIds:$L,calculateViewportsSpatialRegistration:HA,calibratedPixelSpacingMetadataProvider:Gse,clamp:uC,clip:Wv,color:nce,colormap:Lte,convertStackToVolumeViewport:Jse,convertToGrayscale:qA,convertVolumeToStackViewport:Zse,createLinearRGBTransferFunction:uA,createSigmoidRGBTransferFunction:xT,createSubVolume:GT,decimate:qL,deepClone:Fa,deepEqual:XA,deepMerge:Ei,eventListener:Ase,fnv1aHash:eL,generateVolumePropsFromImageIds:r5,genericMetadataProvider:Zl,getBufferConfiguration:rT,getClosestImageId:qc,getClosestStackImageIndexForPoint:FT,getCurrentVolumeViewportSlice:UT,getDynamicVolumeInfo:dce,getImageDataMetadata:a5,getImageLegacy:Xse,getImageSliceDataForVolumeViewport:Fv,getMinMax:kT,getPixelSpacingInformation:xce,getRandomSampleFromArray:BT,getRuntimeId:UA,getScalingParameters:HL,getSliceRange:t5,getSpacingInNormalDirection:Au,getTargetVolumeAndSpacingInNormalDir:uh,getViewportImageCornersInWorld:Gv,getViewportImageIds:Qse,getViewportModality:ZA,getViewportsWithImageURI:Bv,getViewportsWithVolumeId:y1,getVoiFromSigmoidRGBTransferFunction:rA,getVolumeActorCorners:sL,getVolumeDirectionVectors:f5,getVolumeId:sc,getVolumeSliceRangeInfo:nA,getVolumeViewportScrollInfo:Vf,getVolumeViewportsContainingSameVolumes:Wse,hasFloatScalingParameters:_T,hasNaNValues:sC,imageIdToURI:Vr,imageRetrieveMetadataProvider:Op,imageToWorldCoords:jA,indexWithinDimensions:sr,invertRgbTransferFunction:Vg,isEqual:$t,isEqualAbs:Mte,isEqualNegative:dL,isImageActor:fs,isNumber:Ar,isOpposite:vg,isPTPrescaledWithSUV:BA,isValidVolume:Nu,isVideoTransferSyntax:KA,jumpToSlice:Aa,loadImageToCanvas:zse,logger:ute,makeVolumeMetadata:zL,planar:toe,pointInShapeCallback:ST,renderToCanvasCPU:WA,renderToCanvasGPU:GA,roundNumber:an,roundToPrecision:eu,scaleArray:hce,scaleRgbTransferFunction:Nse,scroll:ps,snapFocalPointToSlice:m0,sortImageIdsAndGetSpacing:jL,spatialRegistrationMetadataProvider:kp,splitImageIdsBy4DTags:YA,transferFunctionUtils:Nte,transformIndexToWorld:B0,transformWorldToIndex:Ur,transformWorldToIndexContinuous:T2,triggerEvent:at,updateVTKImageDataWithCornerstoneImage:s5,uuidv4:Dn,windowLevel:Ate,worldToImageCoords:pC},Symbol.toStringTag,{value:"Module"})),x1=new oT("imageRetrievalPool");x1.setMaxSimultaneousRequests(hn.Interaction,200);x1.setMaxSimultaneousRequests(hn.Thumbnail,200);x1.setMaxSimultaneousRequests(hn.Prefetch,200);x1.grabDelay=0;const P9=Symbol("DefaultSettings"),R9=Symbol("RuntimeSettings"),L9=Symbol("ObjectSettingsMap"),Cc=Symbol("Dictionary");class Cr{constructor(e){const r=Object.create(e instanceof Cr&&Cc in e?e[Cc]:null);Object.seal(Object.defineProperty(this,Cc,{value:r}))}set(e,r){return zv(this[Cc],e,r,null)}get(e){return _ce(this[Cc],e)}unset(e){return Cce(this[Cc],e+"")}forEach(e){A9(this[Cc],e)}extend(){return new Cr(this)}import(e){QA(e)&&Object.keys(e).forEach(r=>{zv(this[Cc],r,e[r],null)})}dump(){const e={};return A9(this[Cc],(r,n)=>{typeof n<"u"&&eN(e,r,n)}),e}static assert(e){return e instanceof Cr?e:Cr.getRuntimeSettings()}static getDefaultSettings(e=null){let r=Cr[P9];if(r instanceof Cr||(r=new Cr,Cr[P9]=r),e){const n={};return r.forEach(i=>{if(i.startsWith(e)){const o=i.split(`${e}.`)[1];n[o]=r.get(i)}}),n}return r}static getRuntimeSettings(){let e=Cr[R9];return e instanceof Cr||(e=new Cr(Cr.getDefaultSettings()),Cr[R9]=e),e}static getObjectSettings(e,r){let n=null;if(e instanceof Cr)n=e;else if(typeof e=="object"&&e!==null){let i=Cr[L9];i instanceof WeakMap||(i=new WeakMap,Cr[L9]=i),n=i.get(e),n instanceof Cr||(n=new Cr(Cr.assert(Cr.getObjectSettings(r))),i.set(e,n))}return n}static extendRuntimeSettings(){return Cr.getRuntimeSettings().extend()}}function Cce(t,e){if(e.endsWith(".")){let r=0;const n=e,i=n.slice(0,-1),o=i.length===0;for(const a in t)Object.prototype.hasOwnProperty.call(t,a)&&(o||a.startsWith(n)||a===i)&&(delete t[a],++r);return r>0}return delete t[e]}function A9(t,e){for(const r in t)e(r,t[r])}function Sce(t,e,r,n){let i;if(n.has(r))return zv(t,e,null,n);n.add(r),i=0;for(const o in r)if(Object.prototype.hasOwnProperty.call(r,o)){const a=o.length===0?e:`${e}.${o}`;zv(t,a,r[o],n)||++i}return n.delete(r),i===0}function zv(t,e,r,n){return Tce(e)?QA(r)?Sce(t,e,r,n instanceof WeakSet?n:new WeakSet):(t[e]=r,!0):!1}function _ce(t,e){return t[e]}function Tce(t){let e,r,n;if(typeof t!="string"||(e=t.length-1)<0)return!1;for(n=-1;(r=t.indexOf(".",n+1))>=0;){if(r-n<2||r===e)return!1;n=r}return!0}function QA(t){if(typeof t=="object"&&t!==null){const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null)return!0}return!1}function eN(t,e,r){const n=e.indexOf(".");if(n>=0){const i=e.slice(0,n);let o=t[i];if(typeof o!="object"||o===null){const a=o;o={},typeof a<"u"&&(o[""]=a),t[i]=o}eN(o,e.slice(n+1,e.length),r)}else t[e]=r}Cr.getDefaultSettings().set("useCursors",!0);function Ece(t,e){let r;if(e===void 0)for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);else{let n=-1;for(let i of t)(i=e(i,++n,t))!=null&&(r>i||r===void 0&&i>=i)&&(r=i)}return r}function Dce(t){if(!(o=t.length))return[];for(var e=-1,r=Ece(t,bce),n=new Array(r);++e=1?(r=1,e-1):Math.floor(r*e),i=t[n],o=t[n+1],a=n>0?t[n-1]:2*i-o,s=n{e.image.removeEventListener("load",t.imageLoaded),e.imageLoaded=!0,t.modified()},t.setJsImageData=r=>{e.jsImageData!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.image=null,e.canvas=null),e.jsImageData=r,e.imageLoaded=!0,t.modified())},t.setCanvas=r=>{e.canvas!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.image=null,e.jsImageData=null),e.canvas=r,t.modified())},t.setImage=r=>{e.image!==r&&(r!==null&&(t.setInputData(null),t.setInputConnection(null),e.canvas=null,e.jsImageData=null),e.image=r,e.imageLoaded=!1,r.complete?t.imageLoaded():r.addEventListener("load",t.imageLoaded),t.modified())},t.getDimensionality=()=>{let r=0,n=0,i=1;if(t.getInputData()){const a=t.getInputData();r=a.getDimensions()[0],n=a.getDimensions()[1],i=a.getDimensions()[2]}return e.jsImageData&&(r=e.jsImageData.width,n=e.jsImageData.height),e.canvas&&(r=e.canvas.width,n=e.canvas.height),e.image&&(r=e.image.width,n=e.image.height),(r>1)+(n>1)+(i>1)},t.getInputAsJsImageData=()=>{if(!e.imageLoaded||t.getInputData())return null;if(e.jsImageData)return e.jsImageData();if(e.canvas)return e.canvas.getContext("2d").getImageData(0,0,e.canvas.width,e.canvas.height);if(e.image){const r=document.createElement("canvas");r.width=e.image.width,r.height=e.image.height;const n=r.getContext("2d");return n.translate(0,r.height),n.scale(1,-1),n.drawImage(e.image,0,0,e.image.width,e.image.height),n.getImageData(0,0,r.width,r.height)}return null}}const Mce=(t,e,r,n)=>{const i=[1,2,1],o=4,a=i,s=o,c=t.length/(e*r);let l=e,f=r,u=t;const d=[u];for(let h=0;hc&&(T+=p),E<-c&&(T-=p),y[T]?S+=y[T]*a[_]:C-=a[_],x+=1}u[m+w]=S/C}y=[...u];for(let m=0;m2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,Pce,r),ne.obj(t,e),ne.algo(t,e,6,0),ne.get(t,e,["canvas","image","jsImageData","imageLoaded","resizable"]),ne.setGet(t,e,["repeat","edgeClamp","interpolate","mipLevel"]),Oce(t,e)}const Rce=ne.newInstance(tN,"vtkTexture"),Lce={generateMipmaps:Mce};var Ace={newInstance:Rce,extend:tN,...Lce},nc;(function(t){t[t.Primary=1]="Primary",t[t.Secondary=2]="Secondary",t[t.Primary_And_Secondary=3]="Primary_And_Secondary",t[t.Auxiliary=4]="Auxiliary",t[t.Primary_And_Auxiliary=5]="Primary_And_Auxiliary",t[t.Secondary_And_Auxiliary=6]="Secondary_And_Auxiliary",t[t.Primary_And_Secondary_And_Auxiliary=7]="Primary_And_Secondary_And_Auxiliary",t[t.Fourth_Button=8]="Fourth_Button",t[t.Fifth_Button=16]="Fifth_Button",t[t.Wheel=524288]="Wheel",t[t.Wheel_Primary=524289]="Wheel_Primary"})(nc||(nc={}));var Oi;(function(t){t[t.Shift=16]="Shift",t[t.Ctrl=17]="Ctrl",t[t.Alt=18]="Alt",t[t.Meta=91]="Meta",t[t.ShiftCtrl=1617]="ShiftCtrl",t[t.ShiftAlt=1618]="ShiftAlt",t[t.ShiftMeta=1691]="ShiftMeta",t[t.CtrlAlt=1718]="CtrlAlt",t[t.CtrlMeta=1791]="CtrlMeta",t[t.AltMeta=1891]="AltMeta"})(Oi||(Oi={}));var An;(function(t){t.Active="Active",t.Passive="Passive",t.Enabled="Enabled",t.Disabled="Disabled"})(An||(An={}));var ds;(function(t){t.Default="",t.Highlighted="Highlighted",t.Selected="Selected",t.Locked="Locked",t.AutoGenerated="AutoGenerated"})(ds||(ds={}));var N;(function(t){t.TOOL_ACTIVATED="CORNERSTONE_TOOLS_TOOL_ACTIVATED",t.TOOLGROUP_VIEWPORT_ADDED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_ADDED",t.TOOLGROUP_VIEWPORT_REMOVED="CORNERSTONE_TOOLS_TOOLGROUP_VIEWPORT_REMOVED",t.TOOL_MODE_CHANGED="CORNERSTONE_TOOLS_TOOL_MODE_CHANGED",t.CROSSHAIR_TOOL_CENTER_CHANGED="CORNERSTONE_TOOLS_CROSSHAIR_TOOL_CENTER_CHANGED",t.ANNOTATION_ADDED="CORNERSTONE_TOOLS_ANNOTATION_ADDED",t.ANNOTATION_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_COMPLETED",t.ANNOTATION_MODIFIED="CORNERSTONE_TOOLS_ANNOTATION_MODIFIED",t.ANNOTATION_REMOVED="CORNERSTONE_TOOLS_ANNOTATION_REMOVED",t.ANNOTATION_SELECTION_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_SELECTION_CHANGE",t.ANNOTATION_LOCK_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_LOCK_CHANGE",t.ANNOTATION_VISIBILITY_CHANGE="CORNERSTONE_TOOLS_ANNOTATION_VISIBILITY_CHANGE",t.ANNOTATION_RENDERED="CORNERSTONE_TOOLS_ANNOTATION_RENDERED",t.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED",t.ANNOTATION_INTERPOLATION_PROCESS_COMPLETED="CORNERSTONE_TOOLS_ANNOTATION_INTERPOLATION_PROCESS_COMPLETED",t.INTERPOLATED_ANNOTATIONS_REMOVED="CORNERSTONE_TOOLS_INTERPOLATED_ANNOTATIONS_REMOVED",t.SEGMENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_MODIFIED",t.SEGMENTATION_RENDERED="CORNERSTONE_TOOLS_SEGMENTATION_RENDERED",t.SEGMENTATION_REPRESENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_ADDED",t.SEGMENTATION_ADDED="CORNERSTONE_TOOLS_SEGMENTATION_ADDED",t.SEGMENTATION_REPRESENTATION_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_MODIFIED",t.SEGMENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REMOVED",t.SEGMENTATION_REPRESENTATION_REMOVED="CORNERSTONE_TOOLS_SEGMENTATION_REPRESENTATION_REMOVED",t.SEGMENTATION_DATA_MODIFIED="CORNERSTONE_TOOLS_SEGMENTATION_DATA_MODIFIED",t.HISTORY_UNDO="CORNERSTONE_TOOLS_HISTORY_UNDO",t.HISTORY_REDO="CORNERSTONE_TOOLS_HISTORY_REDO",t.KEY_DOWN="CORNERSTONE_TOOLS_KEY_DOWN",t.KEY_UP="CORNERSTONE_TOOLS_KEY_UP",t.MOUSE_DOWN="CORNERSTONE_TOOLS_MOUSE_DOWN",t.MOUSE_UP="CORNERSTONE_TOOLS_MOUSE_UP",t.MOUSE_DOWN_ACTIVATE="CORNERSTONE_TOOLS_MOUSE_DOWN_ACTIVATE",t.MOUSE_DRAG="CORNERSTONE_TOOLS_MOUSE_DRAG",t.MOUSE_MOVE="CORNERSTONE_TOOLS_MOUSE_MOVE",t.MOUSE_CLICK="CORNERSTONE_TOOLS_MOUSE_CLICK",t.MOUSE_DOUBLE_CLICK="CORNERSTONE_TOOLS_MOUSE_DOUBLE_CLICK",t.MOUSE_WHEEL="CORNERSTONE_TOOLS_MOUSE_WHEEL",t.TOUCH_START="CORNERSTONE_TOOLS_TOUCH_START",t.TOUCH_START_ACTIVATE="CORNERSTONE_TOOLS_TOUCH_START_ACTIVATE",t.TOUCH_PRESS="CORNERSTONE_TOOLS_TOUCH_PRESS",t.TOUCH_DRAG="CORNERSTONE_TOOLS_TOUCH_DRAG",t.TOUCH_END="CORNERSTONE_TOOLS_TOUCH_END",t.TOUCH_TAP="CORNERSTONE_TOOLS_TAP",t.TOUCH_SWIPE="CORNERSTONE_TOOLS_SWIPE"})(N||(N={}));var Dt;(function(t){t.Labelmap="Labelmap",t.Contour="Contour",t.Surface="Surface"})(Dt||(Dt={}));var Lf;(function(t){t.UP="UP",t.DOWN="DOWN",t.LEFT="LEFT",t.RIGHT="RIGHT"})(Lf||(Lf={}));var St;(function(t){t.OnInteractionStart="onInteractionStart",t.OnInteractionEnd="onInteractionEnd",t.Preview="preview",t.RejectPreview="rejectPreview",t.AcceptPreview="acceptPreview",t.Fill="fill",t.Interpolate="interpolate",t.StrategyFunction="strategyFunction",t.CreateIsInThreshold="createIsInThreshold",t.Initialize="initialize",t.INTERNAL_setValue="setValue",t.AddPreview="addPreview",t.ComputeInnerCircleRadius="computeInnerCircleRadius",t.GetStatistics="getStatistics",t.EnsureImageVolumeFor3DManipulation="ensureImageVolumeFor3DManipulation",t.EnsureSegmentationVolumeFor3DManipulation="ensureSegmentationVolumeFor3DManipulation"})(St||(St={}));var Ht;(function(t){t.Interaction="Interaction",t.HandlesUpdated="HandlesUpdated",t.StatsUpdated="StatsUpdated",t.InitialSetup="InitialSetup",t.Completed="Completed",t.InterpolationUpdated="InterpolationUpdated",t.History="History",t.MetadataReferenceModified="MetadataReferenceModified",t.LabelChange="LabelChange"})(Ht||(Ht={}));var xa;(function(t){t.POLYSEG_CONTOUR_TO_LABELMAP="Converting Contour to Labelmap",t.POLYSEG_SURFACE_TO_LABELMAP="Converting Surfaces to Labelmap",t.POLYSEG_CONTOUR_TO_SURFACE="Converting Contour to Surface",t.POLYSEG_LABELMAP_TO_SURFACE="Converting Labelmap to Surface",t.SURFACE_CLIPPING="Clipping Surfaces",t.COMPUTE_STATISTICS="Computing Statistics",t.INTERPOLATE_LABELMAP="Interpolating Labelmap",t.COMPUTE_LARGEST_BIDIRECTIONAL="Computing Largest Bidirectional",t.GENERATE_CONTOUR_SETS="Generating Contour Sets"})(xa||(xa={}));const nN=Object.freeze(Object.defineProperty({__proto__:null,AnnotationStyleStates:ds,ChangeTypes:Ht,Events:N,get KeyboardBindings(){return Oi},get MouseBindings(){return nc},SegmentationRepresentations:Dt,StrategyCallbacks:St,get Swipe(){return Lf},ToolModes:An,WorkerTypes:xa},Symbol.toStringTag,{value:"Module"}));let d5={};function Nce(){d5={}}const k9={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:d5,enabledElements:[],handleRadius:6};let Be={isInteractingWithTool:!1,isMultiPartToolActive:!1,tools:{},toolGroups:[],synchronizers:[],svgNodeCache:d5,enabledElements:[],handleRadius:6};function kce(){Nce(),Be={...structuredClone({...k9,svgNodeCache:{}}),svgNodeCache:{...k9.svgNodeCache}}}var Vce="Expected a function",rN="__lodash_hash_undefined__",Fce="[object Function]",Uce="[object GeneratorFunction]",Bce="[object Symbol]",Gce=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wce=/^\w*$/,zce=/^\./,$ce=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,jce=/[\\^$.*+?()[\]{}|]/g,Hce=/\\(\\)?/g,Kce=/^\[object .+?Constructor\]$/,qce=typeof Pi=="object"&&Pi&&Pi.Object===Object&&Pi,Xce=typeof self=="object"&&self&&self.Object===Object&&self,WT=qce||Xce||Function("return this")();function Yce(t,e){return t==null?void 0:t[e]}function Jce(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch{}return e}var Zce=Array.prototype,Qce=Function.prototype,iN=Object.prototype,Jw=WT["__core-js_shared__"],V9=function(){var t=/[^.]+$/.exec(Jw&&Jw.keys&&Jw.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),oN=Qce.toString,zT=iN.hasOwnProperty,aN=iN.toString,ele=RegExp("^"+oN.call(zT).replace(jce,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),F9=WT.Symbol,tle=Zce.splice,nle=sN(WT,"Map"),Vp=sN(Object,"create"),U9=F9?F9.prototype:void 0,B9=U9?U9.toString:void 0;function Zf(t){var e=-1,r=t?t.length:0;for(this.clear();++e-1}function dle(t,e){var r=this.__data__,n=h5(r,t);return n<0?r.push([t,e]):r[n][1]=e,this}dh.prototype.clear=cle;dh.prototype.delete=lle;dh.prototype.get=ule;dh.prototype.has=fle;dh.prototype.set=dle;function ud(t){var e=-1,r=t?t.length:0;for(this.clear();++e=0&&n>=0&&(r>0||n>0)&&(i+=` ${r} ${n}`),this.addFallbackStyleProperty(i)}static getUniqueInstanceName(e){return`${e}-${UA(Fp)}`}}const kn={iconContent:"",iconSize:16,viewBox:{x:16,y:16},mousePoint:{x:8,y:8},mousePointerGroupString:` `},Wo={x:127,y:60},_d=` @@ -3612,8 +3612,8 @@ Input: `+this.err.str)},c.prototype[Symbol.iterator]=function(){return this._ind width="${s}" height="${s}" viewBox="0 0 ${s} ${s}"> ${o} ${r} - `;return fN(c,e)}const z9=Symbol("ElementCursorsMap");function dN(t,e){Up(t)[0]=e,C1(t,e)}function C1(t,e){const r=Up(t);r[1]=r[0],r[0]=e,t.style.cursor=(e instanceof vo?e:vo.getDefinedCursor("auto")).getStyleProperty()}function zt(t){C1(t,Up(t)[1])}function Ot(t){C1(t,vo.getDefinedCursor("none"))}function Up(t){let e=Up[z9];e instanceof WeakMap||(e=new WeakMap,Object.defineProperty(Up,z9,{value:e}));let r=e.get(t);return r||(r=[null,null],e.set(t,r)),r}const Jle=Object.freeze(Object.defineProperty({__proto__:null,hideElementCursor:Ot,initElementCursor:dN,resetElementCursor:zt,setElementCursor:C1},Symbol.toStringTag,{value:"Module"}));function Zle(t,e){let r=y0.getDefinedCursor(e,!0);r||(r=vo.getDefinedCursor(e)),r||(console.log(`Cursor ${e} is not defined either as SVG or as a standard cursor.`),r=vo.getDefinedCursor(e)),C1(t,r)}const Qle=[...Ule,...Nle],eue=Object.freeze(Object.defineProperty({__proto__:null,CursorNames:Qle,CursorSVG:p5,ImageMouseCursor:Fp,MouseCursor:vo,SVGMouseCursor:y0,elementCursor:Jle,registerCursor:Vle,setCursorForElement:Zle},Symbol.toStringTag,{value:"Module"}));function Kr(t){return Ge.toolGroups.find(e=>e.id===t)}const{Active:Kh,Passive:Zw,Enabled:Qw,Disabled:e3}=An,tue=[{mouseButton:nc.Primary}];class KT{constructor(e){this.viewportsInfo=[],this.toolOptions={},this.currentActivePrimaryToolName=null,this.prevActivePrimaryToolName=null,this.restoreToolOptions={},this._toolInstances={},this.id=e}getViewportIds(){return this.viewportsInfo.map(({viewportId:e})=>e)}getViewportsInfo(){return this.viewportsInfo.slice()}getToolInstance(e){const r=this._toolInstances[e];if(!r){console.warn(`'${e}' is not registered with this toolGroup (${this.id}).`);return}return r}getToolInstances(){return this._toolInstances}hasTool(e){return!!this._toolInstances[e]}addTool(e,r={}){const n=Ge.tools[e],i=typeof e<"u"&&e!=="",o=this.toolOptions[e];if(!i){console.warn("Tool with configuration did not produce a toolName: ",r);return}if(!n){console.warn(`'${e}' is not registered with the library. You need to use cornerstoneTools.addTool to register it.`);return}if(o){console.warn(`'${e}' is already registered for ToolGroup ${this.id}.`);return}const{toolClass:a}=n,s={name:e,toolGroupId:this.id,configuration:r},c=new a(s);this._toolInstances[e]=c}addToolInstance(e,r,n={}){var o;let i=(o=Ge.tools[e])==null?void 0:o.toolClass;if(!i){const a=Ge.tools[r].toolClass;class s extends a{}s.toolName=e,i=s,Ge.tools[e]={toolClass:s}}this.addTool(i.toolName,n)}addViewport(e,r){if(typeof e!="string")throw new Error("viewportId must be defined and be a string");const n=this._findRenderingEngine(e,r);this.viewportsInfo.some(({viewportId:s})=>s===e)||this.viewportsInfo.push({viewportId:e,renderingEngineId:n});const i=this.getActivePrimaryMouseButtonTool();Cr.getRuntimeSettings().get("useCursors")&&this.setViewportsCursorByToolName(i);const a={toolGroupId:this.id,viewportId:e,renderingEngineId:n};at(Ke,N.TOOLGROUP_VIEWPORT_ADDED,a)}removeViewports(e,r){const n=[];if(this.viewportsInfo.forEach((o,a)=>{let s=!1;o.renderingEngineId===e&&(s=!0,r&&o.viewportId!==r&&(s=!1)),s&&n.push(a)}),n.length)for(let o=n.length-1;o>=0;o--)this.viewportsInfo.splice(n[o],1);const i={toolGroupId:this.id,viewportId:r,renderingEngineId:e};at(Ke,N.TOOLGROUP_VIEWPORT_REMOVED,i)}setActiveStrategy(e,r){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool configuration.`);return}n.setActiveStrategy(r)}setToolMode(e,r,n={}){if(!e){console.warn("setToolMode: toolName must be defined");return}if(r===An.Active){this.setToolActive(e,n||this.restoreToolOptions[e]);return}if(r===An.Passive){this.setToolPassive(e);return}if(r===An.Enabled){this.setToolEnabled(e);return}if(r===An.Disabled){this.setToolDisabled(e);return}console.warn("setToolMode: mode must be defined")}setToolActive(e,r={}){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}if(!n){console.warn(`'${e}' instance ${n} is not registered with this toolGroup, can't set tool mode.`);return}const i=this.toolOptions[e]?this.toolOptions[e].bindings:[],o=r.bindings?r.bindings:[],s={bindings:[...i,...o].reduce((u,d)=>{const h=d.numTouchPoints!==void 0,g=d.mouseButton!==void 0;return!u.some(p=>t3(p,d))&&(h||g)&&u.push(d),u},[]),mode:Kh};this.toolOptions[e]=s,this._toolInstances[e].mode=Kh;const l=Cr.getRuntimeSettings().get("useCursors");if(this._hasMousePrimaryButtonBinding(r)&&l)this.setViewportsCursorByToolName(e);else if(!this.getActivePrimaryMouseButtonTool()&&l){const d=vo.getDefinedCursor("default");this._setCursorForViewports(d)}this._hasMousePrimaryButtonBinding(r)&&(this.prevActivePrimaryToolName===null?this.prevActivePrimaryToolName=e:this.prevActivePrimaryToolName=this.currentActivePrimaryToolName,this.currentActivePrimaryToolName=e),typeof n.onSetToolActive=="function"&&n.onSetToolActive(),this._renderViewports();const f={toolGroupId:this.id,toolName:e,toolBindingsOptions:r};at(Ke,N.TOOL_ACTIVATED,f),this._triggerToolModeChangedEvent(e,Kh,r)}setToolPassive(e,r){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const i=this.getToolOptions(e),o=Object.assign({bindings:i?i.bindings:[]},i,{mode:Zw}),a=Array.isArray(r==null?void 0:r.removeAllBindings)?r.removeAllBindings:this.getDefaultPrimaryBindings();o.bindings=o.bindings.filter(c=>(r==null?void 0:r.removeAllBindings)!==!0&&!a.some(l=>t3(c,l)));let s=Zw;o.bindings.length!==0&&(s=Kh,o.mode=s),this.toolOptions[e]=o,n.mode=s,typeof n.onSetToolPassive=="function"&&n.onSetToolPassive(),this._renderViewports(),this._triggerToolModeChangedEvent(e,Zw)}setToolEnabled(e){const r=this._toolInstances[e];if(r===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const n={bindings:[],mode:Qw};this.toolOptions[e]=n,r.mode=Qw,typeof r.onSetToolEnabled=="function"&&r.onSetToolEnabled(),this._renderViewports(),this._triggerToolModeChangedEvent(e,Qw)}setToolDisabled(e){const r=this._toolInstances[e];if(r===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const n={bindings:[],mode:e3};this.restoreToolOptions[e]=this.toolOptions[e],this.toolOptions[e]=n,r.mode=e3,typeof r.onSetToolDisabled=="function"&&r.onSetToolDisabled(),this._renderViewports(),this._triggerToolModeChangedEvent(e,e3)}getToolOptions(e){const r=this.toolOptions[e];if(r!==void 0)return r}getActivePrimaryMouseButtonTool(){return Object.keys(this.toolOptions).find(e=>{const r=this.toolOptions[e];return r.mode===Kh&&this._hasMousePrimaryButtonBinding(r)})}setViewportsCursorByToolName(e,r){const n=this._getCursor(e,r);this._setCursorForViewports(n)}_getCursor(e,r){let n,i;return r&&(n=`${e}.${r}`,i=y0.getDefinedCursor(n,!0),i)||(n=`${e}`,i=y0.getDefinedCursor(n,!0),i)||(n=e,i=y0.getDefinedCursor(n,!0),i)?i:vo.getDefinedCursor("default")}_setCursorForViewports(e){this.viewportsInfo.forEach(({renderingEngineId:r,viewportId:n})=>{const i=Ti(n,r);if(!i)return;const{viewport:o}=i;dN(o.element,e)})}setToolConfiguration(e,r,n){const i=this._toolInstances[e];if(i===void 0)return console.warn(`Tool ${e} not present, can't set tool configuration.`),!1;let o;return n?o=r:o=Object.assign(i.configuration,r),i.configuration=o,typeof i.onSetToolConfiguration=="function"&&i.onSetToolConfiguration(),this._renderViewports(),!0}getDefaultMousePrimary(){return nc.Primary}getDefaultPrimaryBindings(){return tue}getToolConfiguration(e,r){if(this._toolInstances[e]===void 0){console.warn(`Tool ${e} not present, can't set tool configuration.`);return}const n=Ale(this._toolInstances[e].configuration,r)||this._toolInstances[e].configuration;return Fa(n)}getPrevActivePrimaryToolName(){return this.prevActivePrimaryToolName}setActivePrimaryTool(e){const r=this.getCurrentActivePrimaryToolName();this.setToolDisabled(r),this.setToolActive(e,{bindings:[{mouseButton:nc.Primary}]})}getCurrentActivePrimaryToolName(){return this.currentActivePrimaryToolName}clone(e,r=null){let n=Kr(e);return n?(console.debug(`ToolGroup ${e} already exists`),n):(n=new KT(e),Ge.toolGroups.push(n),r=r??(()=>!0),Object.keys(this._toolInstances).filter(r).forEach(i=>{const o=this._toolInstances[i],a=this.toolOptions[i],s=o.mode;n.addTool(i),n.setToolMode(i,s,{bindings:a.bindings??[]})}),n)}_hasMousePrimaryButtonBinding(e){var n;const r=this.getDefaultPrimaryBindings();return(n=e==null?void 0:e.bindings)==null?void 0:n.some(i=>r.some(o=>t3(i,o)))}_renderViewports(){this.viewportsInfo.forEach(({renderingEngineId:e,viewportId:r})=>{Jr(e).renderViewport(r)})}_triggerToolModeChangedEvent(e,r,n){const i={toolGroupId:this.id,toolName:e,mode:r,toolBindingsOptions:n};at(Ke,N.TOOL_MODE_CHANGED,i)}_findRenderingEngine(e,r){const n=Qo();if((n==null?void 0:n.length)===0)throw new Error("No rendering engines found.");if(r)return r;const i=n.filter(o=>o.getViewport(e));if(i.length===0){if(n.length===1)return n[0].id;throw new Error("No rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.")}if(i.length>1)throw new Error("Multiple rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.");return i[0].id}}function t3(t,e){return t.mouseButton!==e.mouseButton||t.numTouchPoints!==e.numTouchPoints?!1:t.modifierKey===e.modifierKey}function hN(t){if(Ge.toolGroups.some(n=>n.id===t)){console.warn(`'${t}' already exists.`);return}const r=new KT(t);return Ge.toolGroups.push(r),r}function gN(t){const e=Ge.toolGroups.findIndex(r=>r.id===t);e>-1&&Ge.toolGroups.splice(e,1)}function pN(){const t=[...Ge.toolGroups];for(const e of t)gN(e.id);Ge.toolGroups=[]}function Or(t,e){var n;e||(e=(n=Qo().find(i=>i.getViewports().find(o=>o.id===t)))==null?void 0:n.id);const r=Ge.toolGroups.filter(i=>i.viewportsInfo.some(o=>o.renderingEngineId===e&&(!o.viewportId||o.viewportId===t)));if(r.length){if(r.length>1)throw new Error(`Multiple tool groups found for renderingEngineId: ${e} and viewportId: ${t}. You should only - have one tool group per viewport in a renderingEngine.`);return r[0]}}function nue(){return Ge.toolGroups}const rue=[An.Active,An.Passive,An.Enabled];function mN(t){return Ge.toolGroups.filter(({toolOptions:e})=>{const r=Object.keys(e);for(let n=0;n{a.viewportsInfo.forEach(s=>{const{renderingEngineId:c,viewportId:l}=s,{FrameOfReferenceUID:f}=Ti(l,c);t.metadata.FrameOfReferenceUID===f&&n.push(s)})});const i=N.ANNOTATION_ADDED,o={annotation:t};if(!n.length){at(Ke,i,o);return}n.forEach(({renderingEngineId:a,viewportId:s})=>{o.viewportId=s,o.renderingEngineId=a,at(Ke,i,o)})}function m5(t){const e=N.ANNOTATION_REMOVED;at(Ke,e,t)}function tn(t,e,r=Ht.HandlesUpdated){const n=e&&Ce(e),{viewportId:i,renderingEngineId:o}=n||{},a=N.ANNOTATION_MODIFIED;at(Ke,a,{annotation:t,viewportId:i,renderingEngineId:o,changeType:r})}function Nn(t){xN({annotation:t})}function v5(t,e=!1){xN({annotation:t,contourHoleProcessingEnabled:e})}function xN(t){const e=N.ANNOTATION_COMPLETED;at(Ke,e,t)}const iue=Object.freeze(Object.defineProperty({__proto__:null,triggerAnnotationAddedForElement:yN,triggerAnnotationAddedForFOR:wN,triggerAnnotationCompleted:Nn,triggerAnnotationModified:tn,triggerAnnotationRemoved:m5,triggerContourAnnotationCompleted:v5},Symbol.toStringTag,{value:"Module"}));let CN;function Es(){return CN}function qT(t){CN=t}function un(t,e){const r=Es(),n=r.getGroupKey(e);return r.getAnnotations(n,t)}function Br(t){return Es().getAnnotation(t)}function S1(){return Es().getAllAnnotations()}function y5(t){const{annotationUID:e,parentAnnotationUID:r}=t;if(!r)return;const n=Br(r),i=n.childAnnotationUIDs.indexOf(e);n.childAnnotationUIDs.splice(i,1),t.parentAnnotationUID=void 0}function _1(t,e){const{annotationUID:r}=t,{annotationUID:n}=e;y5(e),t.childAnnotationUIDs||(t.childAnnotationUIDs=[]),!t.childAnnotationUIDs.includes(n)&&(t.childAnnotationUIDs.push(n),e.parentAnnotationUID=r)}function SN(t){return t.parentAnnotationUID?Br(t.parentAnnotationUID):void 0}function T1(t){var e;return((e=t.childAnnotationUIDs)==null?void 0:e.map(r=>Br(r)))??[]}function nn(t,e){t.annotationUID||(t.annotationUID=Dn());const r=Es();if(e instanceof HTMLDivElement){const n=r.getGroupKey(e);r.addAnnotation(t,n),yN(t,e)}else r.addAnnotation(t,void 0),wN(t);return t.annotationUID}function oue(t,e){const r=Es(),n=r.getGroupKey(e);return r.getNumberOfAnnotations(n,t)}function gn(t){var n;if(!t)return;const e=Es(),r=e.getAnnotation(t);r&&((n=r.childAnnotationUIDs)==null||n.forEach(i=>gn(i)),e.removeAnnotation(t),m5({annotation:r,annotationManagerUID:e.uid}))}function aue(){const t=Es(),e=t.removeAllAnnotations();for(const r of e)m5({annotation:r,annotationManagerUID:t.uid})}function sue(t,e){const r=Es(),n=r.getGroupKey(e),i=r.removeAnnotations(n,t);for(const o of i)m5({annotation:o,annotationManagerUID:r.uid})}function _N(t){let e=t;for(;e;)e.invalidated=!0,e=e.parentAnnotationUID?Br(e.parentAnnotationUID):void 0}const cue=Object.freeze(Object.defineProperty({__proto__:null,addAnnotation:nn,addChildAnnotation:_1,clearParentAnnotation:y5,getAllAnnotations:S1,getAnnotation:Br,getAnnotationManager:Es,getAnnotations:un,getChildAnnotations:T1,getNumberOfAnnotations:oue,getParentAnnotation:SN,invalidateAnnotation:_N,removeAllAnnotations:aue,removeAnnotation:gn,removeAnnotations:sue,setAnnotationManager:qT},Symbol.toStringTag,{value:"Module"}));function Ci(t){const e=t.toolName;if(!e)throw new Error(`No Tool Found for the ToolClass ${t.name}`);Ge.tools[e]||(Ge.tools[e]={toolClass:t})}function lue(t){const e=t.toolName;return!!(e&&Ge.tools[e])}function w5(t){return!!(t&&Ge.tools[t])}function TN(t){const e=t.toolName;if(!e)throw new Error(`No tool found for: ${t.name}`);if(!Ge.tools[e]!==void 0)delete Ge.tools[e];else throw new Error(`${e} cannot be removed because it has not been added`)}function fd(t,e){const r=e||t.currentTarget,{viewport:n}=Ce(r)||{};if(!n)return;const i=due(t),o=fue(t),a=uue(r,o),s=n.canvasToWorld(a);return{page:o,client:i,canvas:a,world:s}}function uue(t,e){const r=t.getBoundingClientRect();return[e[0]-r.left-window.pageXOffset,e[1]-r.top-window.pageYOffset]}function fue(t){return[t.pageX,t.pageY]}function due(t){return[t.clientX,t.clientY]}function EN(t){const e=t.currentTarget,{viewportId:r,renderingEngineId:n}=Ce(e),i=fd(t,e),o={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},a={event:t,eventName:N.MOUSE_DOUBLE_CLICK,viewportId:r,renderingEngineId:n,camera:{},element:e,startPoints:i,lastPoints:i,currentPoints:i,deltaPoints:o};!at(e,N.MOUSE_DOUBLE_CLICK,a)&&(t.stopImmediatePropagation(),t.preventDefault())}const $9=N.MOUSE_MOVE;function E1(t){const e=t.currentTarget,r=Ce(e);if(!r)return;const{renderingEngineId:n,viewportId:i}=r,o=fd(t);!at(e,$9,{renderingEngineId:n,viewportId:i,camera:{},element:e,currentPoints:o,eventName:$9,event:t})&&(t.stopImmediatePropagation(),t.preventDefault())}const{MOUSE_DOWN:j9,MOUSE_DOWN_ACTIVATE:hue,MOUSE_CLICK:gue,MOUSE_UP:pue,MOUSE_DRAG:H9}=N,mue=400,vue=150,yue=3,wue={mouseButton:void 0,element:null,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};let Zt={mouseButton:void 0,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,element:null,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};const Si={doubleClickTimeout:null,mouseDownEvent:null,mouseUpEvent:null,ignoreDoubleClick:!1};function DN(t){if(Si.doubleClickTimeout){if(t.buttons===Si.mouseDownEvent.buttons)return;Si.mouseDownEvent=t,$v();return}Si.doubleClickTimeout=setTimeout($v,t.buttons===1?mue:vue),Si.mouseDownEvent=t,Si.ignoreDoubleClick=!1,Zt.element=t.currentTarget,Zt.mouseButton=t.buttons;const e=Ce(Zt.element),{renderingEngineId:r,viewportId:n}=e;Zt.renderingEngineId=r,Zt.viewportId=n,Zt.preventClickTimeout=setTimeout(Cue,Zt.clickDelay),Zt.element.removeEventListener("mousemove",E1);const i=fd(t,Zt.element);Zt.startPoints=uu(i),Zt.lastPoints=uu(i),document.addEventListener("mouseup",XT),document.addEventListener("mousemove",bN)}function xue(t){const e=x5(Zt.startPoints,Zt.startPoints),r={event:t,eventName:j9,element:Zt.element,mouseButton:Zt.mouseButton,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},startPoints:Zt.startPoints,lastPoints:Zt.startPoints,currentPoints:Zt.startPoints,deltaPoints:e};Zt.lastPoints=uu(r.lastPoints),at(r.element,j9,r)&&at(r.element,hue,r)}function bN(t){const e=Ce(Zt.element);if(!(e!=null&&e.viewport))return;const r=fd(t,Zt.element),n=PN(Zt.element,Zt.lastPoints),i=x5(r,n);if(Si.doubleClickTimeout)if(ON(i.canvas))$v();else return;const o={event:t,eventName:H9,mouseButton:Zt.mouseButton,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},element:Zt.element,startPoints:uu(Zt.startPoints),lastPoints:uu(n),currentPoints:r,deltaPoints:i};!at(Zt.element,H9,o)&&(t.stopImmediatePropagation(),t.preventDefault()),Zt.lastPoints=uu(r)}function XT(t){if(clearTimeout(Zt.preventClickTimeout),Si.doubleClickTimeout)Si.mouseUpEvent?mC():(Si.mouseUpEvent=t,Zt.element.addEventListener("mousemove",IN));else{const e=Zt.isClickEvent?gue:pue,r=fd(t,Zt.element),n=x5(r,Zt.lastPoints),i={event:t,eventName:e,mouseButton:Zt.mouseButton,element:Zt.element,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},startPoints:uu(Zt.startPoints),lastPoints:uu(Zt.lastPoints),currentPoints:r,deltaPoints:n};at(i.element,e,i),mC()}document.removeEventListener("mousemove",bN)}function IN(t){const e=fd(t,Zt.element),r=PN(Zt.element,Zt.lastPoints),n=x5(e,r);ON(n.canvas)&&($v(),E1(t))}function ON(t){return Math.abs(t[0])+Math.abs(t[1])>yue}function Cue(){Zt.isClickEvent=!1}function $v(){Si.ignoreDoubleClick=!0;const t=Si.mouseDownEvent,e=Si.mouseUpEvent;MN(),xue(t),e&&XT(e)}function MN(){Si.doubleClickTimeout&&(clearTimeout(Si.doubleClickTimeout),Si.doubleClickTimeout=null),Si.mouseDownEvent=null,Si.mouseUpEvent=null}function mC(){var t,e;document.removeEventListener("mouseup",XT),(t=Zt.element)==null||t.removeEventListener("mousemove",IN),(e=Zt.element)==null||e.addEventListener("mousemove",E1),MN(),Zt=JSON.parse(JSON.stringify(wue))}function uu(t){return JSON.parse(JSON.stringify(t))}function PN(t,e){const{viewport:r}=Ce(t)||{};if(!r)return e;const n=r.canvasToWorld(e.canvas);return{page:e.page,client:e.client,canvas:e.canvas,world:n}}function x5(t,e){return!t||!e?{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}:{page:n3(t.page,e.page),client:n3(t.client,e.client),canvas:n3(t.canvas,e.canvas),world:Sue(t.world,e.world)}}function n3(t,e){return[t[0]-e[0],t[1]-e[1]]}function Sue(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function _ue(){return Zt.mouseButton}function RN(t){Si.ignoreDoubleClick?(Si.ignoreDoubleClick=!1,t.stopImmediatePropagation(),t.preventDefault()):mC()}function LN(t){t.removeEventListener("dblclick",EN),t.removeEventListener("mousedown",DN),t.removeEventListener("mousemove",E1),t.removeEventListener("dblclick",RN,{capture:!0})}function Tue(t){LN(t),t.addEventListener("dblclick",EN),t.addEventListener("mousedown",DN),t.addEventListener("mousemove",E1),t.addEventListener("dblclick",RN,{capture:!0})}const AN={enable:Tue,disable:LN},Eue=2e3,z0={mouse:0,touch:1};let K9,q9;function NN(t,e){const r=Date.now();if(t!==K9){if(r-q9<=Eue)return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),!1;K9=t}q9=r}const kN=NN.bind(null,z0.mouse),VN=NN.bind(null,z0.touch);function X9(t,e,r){const n=r?kN:VN;e.forEach(function(i){t.addEventListener(i,n,{passive:!1})})}function Y9(t,e,r){const n=r?kN:VN;e.forEach(function(i){t.removeEventListener(i,n)})}const FN=["mousedown","mouseup","mousemove"],UN=["touchstart","touchend"];function BN(t){Y9(t,FN,z0.mouse),Y9(t,UN,z0.touch)}function Due(t){BN(t),X9(t,FN,z0.mouse),X9(t,UN,z0.touch)}const GN={enable:Due,disable:BN};function C5(t,e){const r=e||t.currentTarget,n=t.type==="touchend"?t.changedTouches:t.touches;return Object.keys(n).map(i=>{const o=Oue(n[i]),a=Iue(n[i]),s=bue(r,a),{viewport:c}=Ce(r),l=c.canvasToWorld(s);return{page:a,client:o,canvas:s,world:l,touch:{identifier:i,radiusX:n[i].radiusX,radiusY:n[i].radiusY,force:n[i].force,rotationAngle:n[i].rotationAngle}}})}function bue(t,e){const r=t.getBoundingClientRect();return[e[0]-r.left-window.pageXOffset,e[1]-r.top-window.pageYOffset]}function Iue(t){return[t.pageX,t.pageY]}function Oue(t){return[t.clientX,t.clientY]}function jv(t,e){const r=Bp(t),n=Bp(e);return{page:r3(r.page,n.page),client:r3(r.client,n.client),canvas:r3(r.canvas,n.canvas),world:Pue(r.world,n.world)}}function YT(t,e){const r=Bp(t),n=Bp(e);return{page:w0(r.page,n.page),client:w0(r.client,n.client),canvas:w0(r.canvas,n.canvas),world:WN(r.world,n.world)}}function Mue(t,e){}function Hv(t,e){const r=J9(t),n=J9(e);return{page:r.page-n.page,client:r.client-n.client,canvas:r.canvas-n.canvas,world:r.world-n.world}}function Xs(t){return JSON.parse(JSON.stringify(t))}function vC(t){return JSON.parse(JSON.stringify(t))}function Bp(t){return t.reduce((e,r)=>({page:[e.page[0]+r.page[0]/t.length,e.page[1]+r.page[1]/t.length],client:[e.client[0]+r.client[0]/t.length,e.client[1]+r.client[1]/t.length],canvas:[e.canvas[0]+r.canvas[0]/t.length,e.canvas[1]+r.canvas[1]/t.length],world:[e.world[0]+r.world[0]/t.length,e.world[1]+r.world[1]/t.length,e.world[2]+r.world[2]/t.length]}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]})}function ys(t){return t.reduce((e,r)=>({page:[e.page[0]+r.page[0]/t.length,e.page[1]+r.page[1]/t.length],client:[e.client[0]+r.client[0]/t.length,e.client[1]+r.client[1]/t.length],canvas:[e.canvas[0]+r.canvas[0]/t.length,e.canvas[1]+r.canvas[1]/t.length],world:[e.world[0]+r.world[0]/t.length,e.world[1]+r.world[1]/t.length,e.world[2]+r.world[2]/t.length],touch:{identifier:null,radiusX:e.touch.radiusX+r.touch.radiusX/t.length,radiusY:e.touch.radiusY+r.touch.radiusY/t.length,force:e.touch.force+r.touch.force/t.length,rotationAngle:e.touch.rotationAngle+r.touch.rotationAngle/t.length}}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0],touch:{identifier:null,radiusX:0,radiusY:0,force:0,rotationAngle:0}})}function r3(t,e){return[t[0]-e[0],t[1]-e[1]]}function Pue(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function J9(t){const e=[];for(let r=0;r({page:r.page+n.page/e.length,client:r.client+n.client/e.length,canvas:r.canvas+n.canvas/e.length,world:r.world+n.world/e.length}),{page:0,client:0,canvas:0,world:0})}function w0(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2))}function WN(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}const Rue=Object.freeze(Object.defineProperty({__proto__:null,copyPoints:vC,copyPointsList:Xs,getDeltaDistance:YT,getDeltaDistanceBetweenIPoints:Hv,getDeltaPoints:jv,getDeltaRotation:Mue,getMeanPoints:Bp,getMeanTouchPoints:ys},Symbol.toStringTag,{value:"Module"}));Cr.getRuntimeSettings();const{TOUCH_START:Z9,TOUCH_START_ACTIVATE:Lue,TOUCH_PRESS:Q9,TOUCH_DRAG:eD,TOUCH_END:tD,TOUCH_TAP:nD,TOUCH_SWIPE:i3}=N,Gp={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},Kv={page:0,client:0,canvas:0,world:0},zN={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Gp,touch:null}],lastPointsList:[{...Gp,touch:null}],isTouchStart:!1,startTime:null,pressTimeout:null,pressDelay:700,pressMaxDistance:5,accumulatedDistance:Kv,swipeDistanceThreshold:48,swiped:!1,swipeToleranceMs:300},$N={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Gp,touch:null}],taps:0,tapTimeout:null,tapMaxDistance:24,tapToleranceMs:300};let It=JSON.parse(JSON.stringify(zN)),ti=JSON.parse(JSON.stringify($N));function Cu(t,e,r){return at(t,e,r)}function jN(t){It.element=t.currentTarget;const e=Ce(It.element),{renderingEngineId:r,viewportId:n}=e;It.renderingEngineId=r,It.viewportId=n,!It.isTouchStart&&(clearTimeout(It.pressTimeout),It.pressTimeout=setTimeout(()=>Aue(t),It.pressDelay),Nue(t),document.addEventListener("touchmove",HN),document.addEventListener("touchend",KN))}function Aue(t){if(It.accumulatedDistance.canvas>It.pressMaxDistance)return;const r={event:t,eventName:Q9,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,startPointsList:Xs(It.startPointsList),lastPointsList:Xs(It.lastPointsList),startPoints:vC(ys(It.startPointsList)),lastPoints:vC(ys(It.lastPointsList))};Cu(r.element,Q9,r)}function Nue(t){It.isTouchStart=!0,It.startTime=new Date;const e=C5(t,It.element),r=ys(e),n=Gp,i=Kv,o={event:t,eventName:Z9,element:It.element,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},startPointsList:e,lastPointsList:e,currentPointsList:e,startPoints:r,lastPoints:r,currentPoints:r,deltaPoints:n,deltaDistance:i};It.startPointsList=Xs(o.startPointsList),It.lastPointsList=Xs(o.lastPointsList),Cu(o.element,Z9,o)&&Cu(o.element,Lue,o)}function HN(t){const e=C5(t,It.element),r=qN(It.element,It.lastPointsList),n=e.length===r.length?jv(e,r):Gp,i=e.length===r.length?Hv(e,r):Kv,o=e.length===r.length?YT(e,It.lastPointsList):Kv;It.accumulatedDistance={page:It.accumulatedDistance.page+o.page,client:It.accumulatedDistance.client+o.client,canvas:It.accumulatedDistance.canvas+o.canvas,world:It.accumulatedDistance.world+o.world};const a={event:t,eventName:eD,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,startPoints:ys(It.startPointsList),lastPoints:ys(r),currentPoints:ys(e),startPointsList:Xs(It.startPointsList),lastPointsList:Xs(r),currentPointsList:e,deltaPoints:n,deltaDistance:i};Cu(It.element,eD,a),Vue(t,n),It.lastPointsList=Xs(e)}function KN(t){clearTimeout(It.pressTimeout);const e=C5(t,It.element),r=qN(It.element,It.lastPointsList),n=e.length===r.length?jv(e,r):jv(e,e),i=e.length===r.length?Hv(e,r):Hv(e,e),o={event:t,eventName:tD,element:It.element,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},startPointsList:Xs(It.startPointsList),lastPointsList:Xs(r),currentPointsList:e,startPoints:ys(It.startPointsList),lastPoints:ys(r),currentPoints:ys(e),deltaPoints:n,deltaDistance:i};Cu(o.element,tD,o),kue(t),It=JSON.parse(JSON.stringify(zN)),document.removeEventListener("touchmove",HN),document.removeEventListener("touchend",KN)}function kue(t){const e=new Date().getTime(),r=It.startTime.getTime();if(e-r>ti.tapToleranceMs||(ti.taps===0&&(ti.element=It.element,ti.renderingEngineId=It.renderingEngineId,ti.viewportId=It.viewportId,ti.startPointsList=It.startPointsList),ti.taps>0&&!(ti.element==It.element&&ti.renderingEngineId==It.renderingEngineId&&ti.viewportId==It.viewportId)))return;const n=C5(t,ti.element);YT(n,ti.startPointsList).canvas>ti.tapMaxDistance||(clearTimeout(ti.tapTimeout),ti.taps+=1,ti.tapTimeout=setTimeout(()=>{const o={event:t,eventName:nD,element:ti.element,renderingEngineId:ti.renderingEngineId,viewportId:ti.viewportId,camera:{},currentPointsList:n,currentPoints:ys(n),taps:ti.taps};Cu(o.element,nD,o),ti=JSON.parse(JSON.stringify($N))},ti.tapToleranceMs))}function Vue(t,e){const r=new Date().getTime(),n=It.startTime.getTime();if(It.swiped||r-n>It.swipeToleranceMs)return;const[i,o]=e.canvas,a={event:t,eventName:i3,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,swipe:null};Math.abs(i)>It.swipeDistanceThreshold&&(a.swipe=i>0?Lf.RIGHT:Lf.LEFT,Cu(a.element,i3,a),It.swiped=!0),Math.abs(o)>It.swipeDistanceThreshold&&(a.swipe=o>0?Lf.DOWN:Lf.UP,Cu(a.element,i3,a),It.swiped=!0)}function qN(t,e){const{viewport:r}=Ce(t);return e.map(n=>{const i=r.canvasToWorld(n.canvas);return{page:n.page,client:n.client,canvas:n.canvas,world:i,touch:n.touch}})}function XN(t){GN.disable(t),t.removeEventListener("touchstart",jN)}function Fue(t){XN(t),GN.enable(t),t.addEventListener("touchstart",jN,{passive:!1})}const YN={enable:Fue,disable:XN},rD=10,iD=40,oD=800;function Uue(t){let e=0,r=0,n=0,i=0;return"detail"in t&&(r=t.detail),"wheelDelta"in t&&(r=-t.wheelDelta/120),"wheelDeltaY"in t&&(r=-t.wheelDeltaY/120),"wheelDeltaX"in t&&(e=-t.wheelDeltaX/120),n=e*rD,i=r*rD,"deltaY"in t&&(i=t.deltaY),"deltaX"in t&&(n=t.deltaX),(n||i)&&t.deltaMode&&(t.deltaMode===1?(n*=iD,i*=iD):(n*=oD,i*=oD)),n&&!e&&(e=n<1?-1:1),i&&!r&&(r=i<1?-1:1),{spinX:e,spinY:r,pixelX:n,pixelY:i}}function JN(t){const e=t.currentTarget,r=Ce(e),{renderingEngineId:n,viewportId:i}=r;if(t.deltaY>-1&&t.deltaY<1)return;t.preventDefault();const{spinX:o,spinY:a,pixelX:s,pixelY:c}=Uue(t),l=a<0?-1:1,f={event:t,eventName:N.MOUSE_WHEEL,renderingEngineId:n,viewportId:i,element:e,camera:{},detail:t,wheel:{spinX:o,spinY:a,pixelX:s,pixelY:c,direction:l},points:fd(t)};at(e,N.MOUSE_WHEEL,f)}function Bue(t){ZN(t),t.addEventListener("wheel",JN,{passive:!1})}function ZN(t){t.removeEventListener("wheel",JN)}const QN={enable:Bue,disable:ZN},Gue={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};let fi={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};function S5(t){fi.element=t.currentTarget;const e=Ce(fi.element),{renderingEngineId:r,viewportId:n}=e;fi.renderingEngineId=r,fi.viewportId=n,fi.key=t.key,fi.keyCode=t.keyCode,t.preventDefault();const i={renderingEngineId:fi.renderingEngineId,viewportId:fi.viewportId,element:fi.element,key:fi.key,keyCode:fi.keyCode};at(i.element,N.KEY_DOWN,i),document.addEventListener("keyup",ek),document.addEventListener("visibilitychange",JT),fi.element.removeEventListener("keydown",S5)}function JT(){document.removeEventListener("visibilitychange",JT),document.visibilityState==="hidden"&&tk()}function ek(t){const e={renderingEngineId:fi.renderingEngineId,viewportId:fi.viewportId,element:fi.element,key:fi.key,keyCode:fi.keyCode};document.removeEventListener("keyup",ek),document.removeEventListener("visibilitychange",JT),fi.element.addEventListener("keydown",S5),fi=structuredClone(Gue),at(e.element,N.KEY_UP,e)}function Wue(){return fi.keyCode}function tk(){fi.keyCode=void 0}function zue(t){nk(t),t.addEventListener("keydown",S5)}function nk(t){t.removeEventListener("keydown",S5)}const hh={enable:zue,disable:nk,getModifierKey:Wue},{EPSILON:Ed}=cd;function rk(t,e,r=!1){var f;let n=1/0,i=r?-1/0:0,o=1/0,a=r?-1/0:0,s=1/0,c=r?-1/0:0;const l=((f=t[0])==null?void 0:f.length)===3;for(let u=0;uJSON.stringify(t)===JSON.stringify(e);function ZT(t,e,r,n){const i=r[0]/2,o=r[1]/2,a=r[2]/2,s=new Array(8);s[0]=Ur(t,[n[0]-i,n[1]-o,n[2]-a]);const c=[[1,-1,-1],[-1,1,-1],[1,1,-1],[-1,-1,1],[1,-1,1],[-1,1,1],[1,1,1]];for(let l=0;l<7;l++){const[f,u,d]=c[l];s[l+1]=Ur(t,[n[0]+f*i,n[1]+u*o,n[2]+d*a])}return Su(s,e)}function ok(t,e){const{spacing:r}=t,n=t.voxelManager.getScalarDataLength(),i=[];let o=0;for(let a=0;a{const e=QT.get(t);e&&(e.isDirty=!0)},Hue=t=>{const e=QT.get(t);return e&&!e.isDirty?e.indices:null},Kue=(t,e)=>{QT.set(t,{indices:e,isDirty:!1})};function io(t,e,r){const n={segmentationId:t,modifiedSlicesToUse:e,segmentIndex:r};jue(t),at(Ke,N.SEGMENTATION_DATA_MODIFIED,n)}function Ta(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_MODIFIED,e)}function e4(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_REMOVED,e)}function Gs(t,e,r){const n={segmentationId:e,type:r,viewportId:t};at(Ke,N.SEGMENTATION_REPRESENTATION_MODIFIED,n)}function yC(t,e,r){const n={viewportId:t,segmentationId:e,type:r};at(Ke,N.SEGMENTATION_REPRESENTATION_REMOVED,n)}const que=Object.freeze(Object.defineProperty({__proto__:null,triggerSegmentationDataModified:io,triggerSegmentationModified:Ta,triggerSegmentationRemoved:e4,triggerSegmentationRepresentationModified:Gs,triggerSegmentationRepresentationRemoved:yC},Symbol.toStringTag,{value:"Module"})),Xue={renderOutline:!0,outlineWidthAutoGenerated:3,outlineWidth:1,outlineWidthInactive:1,outlineOpacity:1,outlineOpacityInactive:.85,outlineDash:void 0,outlineDashInactive:void 0,outlineDashAutoGenerated:"5,3",activeSegmentOutlineWidthDelta:0,renderFill:!0,fillAlpha:.5,fillAlphaInactive:.3,fillAlphaAutoGenerated:.3};function Yue(){return Xue}const Jue={renderOutline:!0,renderOutlineInactive:!0,outlineWidth:3,outlineWidthInactive:2,activeSegmentOutlineWidthDelta:0,renderFill:!0,renderFillInactive:!0,fillAlpha:.5,fillAlphaInactive:.4,outlineOpacity:1,outlineOpacityInactive:.85};function Zue(){return Jue}class Que{constructor(){this.config={global:{},segmentations:{},viewportsStyle:{}}}setStyle(e,r){const{viewportId:n,segmentationId:i,type:o,segmentIndex:a}=e,s=this.getStyle(e);let c;if(!n&&!i?c={...s,...r}:c=this.copyActiveToInactiveIfNotProvided({...s,...r},o),!o)throw new Error("Type is required to set a style");if(n){this.config.viewportsStyle[n]||(this.config.viewportsStyle[n]={renderInactiveSegmentations:!1,representations:{}});const l=this.config.viewportsStyle[n].representations;if(i){l[i]||(l[i]={}),l[i][o]||(l[i][o]={});const f=l[i][o];a!==void 0?(f.perSegment||(f.perSegment={}),f.perSegment[a]=c):f.allSegments=c}else{const f="__allSegmentations__";l[f]||(l[f]={}),l[f][o]||(l[f][o]={}),l[f][o].allSegments=c}}else if(i){this.config.segmentations[i]||(this.config.segmentations[i]={}),this.config.segmentations[i][o]||(this.config.segmentations[i][o]={});const l=this.config.segmentations[i][o];a!==void 0?(l.perSegment||(l.perSegment={}),l.perSegment[a]=c):l.allSegments=c}else this.config.global[o]=c}copyActiveToInactiveIfNotProvided(e,r){const n={...e};if(r===Dt.Labelmap){const i=n;i.renderOutlineInactive??(i.renderOutlineInactive=i.renderOutline),i.outlineWidthInactive??(i.outlineWidthInactive=i.outlineWidth),i.renderFillInactive??(i.renderFillInactive=i.renderFill),i.fillAlphaInactive??(i.fillAlphaInactive=i.fillAlpha),i.outlineOpacityInactive??(i.outlineOpacityInactive=i.outlineOpacity)}else if(r===Dt.Contour){const i=n;i.outlineWidthInactive??(i.outlineWidthInactive=i.outlineWidth),i.outlineOpacityInactive??(i.outlineOpacityInactive=i.outlineOpacity),i.outlineDashInactive??(i.outlineDashInactive=i.outlineDash),i.renderOutlineInactive??(i.renderOutlineInactive=i.renderOutline),i.renderFillInactive??(i.renderFillInactive=i.renderFill),i.fillAlphaInactive??(i.fillAlphaInactive=i.fillAlpha)}return n}getStyle(e){var s,c,l,f,u;const{viewportId:r,segmentationId:n,type:i,segmentIndex:o}=e;let a=this.getDefaultStyle(i);if(this.config.global[i]&&(a={...a,...this.config.global[i]}),(s=this.config.segmentations[n])!=null&&s[i]&&(a={...a,...this.config.segmentations[n][i].allSegments},o!==void 0&&((c=this.config.segmentations[n][i].perSegment)!=null&&c[o])&&(a={...a,...this.config.segmentations[n][i].perSegment[o]})),r&&this.config.viewportsStyle[r]){this.config.viewportsStyle[r].renderInactiveSegmentations;const d="__allSegmentations__";(l=this.config.viewportsStyle[r].representations[d])!=null&&l[i]&&(a={...a,...this.config.viewportsStyle[r].representations[d][i].allSegments}),n&&((f=this.config.viewportsStyle[r].representations[n])!=null&&f[i])&&(a={...a,...this.config.viewportsStyle[r].representations[n][i].allSegments},o!==void 0&&((u=this.config.viewportsStyle[r].representations[n][i].perSegment)!=null&&u[o])&&(a={...a,...this.config.viewportsStyle[r].representations[n][i].perSegment[o]}))}return a}getRenderInactiveSegmentations(e){var r;return(r=this.config.viewportsStyle[e])==null?void 0:r.renderInactiveSegmentations}setRenderInactiveSegmentations(e,r){this.config.viewportsStyle[e]||(this.config.viewportsStyle[e]={renderInactiveSegmentations:!1,representations:{}}),this.config.viewportsStyle[e].renderInactiveSegmentations=r}getDefaultStyle(e){switch(e){case Dt.Labelmap:return Zue();case Dt.Contour:return Yue();case Dt.Surface:return{};default:throw new Error(`Unknown representation type: ${e}`)}}clearSegmentationStyle(e){this.config.segmentations[e]&&delete this.config.segmentations[e]}clearAllSegmentationStyles(){this.config.segmentations={}}clearViewportStyle(e){this.config.viewportsStyle[e]&&delete this.config.viewportsStyle[e]}clearAllViewportStyles(){for(const e in this.config.viewportsStyle){const n=this.config.viewportsStyle[e].renderInactiveSegmentations;this.config.viewportsStyle[e]={renderInactiveSegmentations:n,representations:{}}}}resetToGlobalStyle(){this.clearAllSegmentationStyles(),this.clearAllViewportStyles()}hasCustomStyle(e){const{type:r}=e,n=this.getStyle(e),i=this.getDefaultStyle(r);return!XA(n,i)}}const va=new Que;function efe(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_ADDED,e)}const aD={colorLUT:[],segmentations:[],viewportSegRepresentations:{}};class tfe{constructor(e){this._stackLabelmapImageIdReferenceMap=new Map,this._labelmapImageIdReferenceMap=new Map,e||(e=Dn()),this.state=Object.freeze(Fa(aD)),this.uid=e}getState(){return this.state}updateState(e){const r=Fa(this.state);e(r),this.state=Object.freeze(r)}getColorLUT(e){return this.state.colorLUT[e]}getNextColorLUTIndex(){return this.state.colorLUT.length}resetState(){this._stackLabelmapImageIdReferenceMap.clear(),this._labelmapImageIdReferenceMap.clear(),this.state=Object.freeze(Fa(aD))}getSegmentation(e){return this.state.segmentations.find(r=>r.segmentationId===e)}updateSegmentation(e,r){this.updateState(n=>{const i=n.segmentations.find(o=>o.segmentationId===e);if(!i){console.warn(`Segmentation with id ${e} not found. Update aborted.`);return}Object.assign(i,r)}),Ta(e)}addSegmentation(e){if(this.getSegmentation(e.segmentationId))throw new Error(`Segmentation with id ${e.segmentationId} already exists`);this.updateState(r=>{const n=Fa(e);if(n.representationData.Labelmap&&"volumeId"in n.representationData.Labelmap&&!("imageIds"in n.representationData.Labelmap)){const i=this.getLabelmapImageIds(n.representationData);n.representationData.Labelmap.imageIds=i}r.segmentations.push(n)}),efe(e.segmentationId)}removeSegmentation(e){this.updateState(r=>{const n=r.segmentations.filter(i=>i.segmentationId!==e);r.segmentations.splice(0,r.segmentations.length,...n)}),e4(e)}addSegmentationRepresentation(e,r,n,i){if(!zn(e))return;if(this.getSegmentationRepresentations(e,{type:n,segmentationId:r}).length>0){console.debug("A segmentation representation of type",n,"already exists in viewport",e,"for segmentation",r);return}this.updateState(s=>{s.viewportSegRepresentations[e]||(s.viewportSegRepresentations[e]=[],va.setRenderInactiveSegmentations(e,!0)),n!==Dt.Labelmap?this.addDefaultSegmentationRepresentation(s,e,r,n,i):this.addLabelmapRepresentation(s,e,r,i)}),Gs(e,r,n)}addDefaultSegmentationRepresentation(e,r,n,i,o){const a=e.segmentations.find(c=>c.segmentationId===n);if(!a)return;const s={};Object.keys(a.segments).forEach(c=>{s[Number(c)]={visible:!0}}),e.viewportSegRepresentations[r].push({segmentationId:n,type:i,active:!0,visible:!0,colorLUTIndex:(o==null?void 0:o.colorLUTIndex)||0,segments:s,config:{...sD(i),...o}}),this._setActiveSegmentation(e,r,n)}addLabelmapRepresentation(e,r,n,i=sD(Dt.Labelmap)){if(!zn(r))return;const a=this.getSegmentation(n);if(!a)return;const{representationData:s}=a;if(!s.Labelmap)return this.addDefaultSegmentationRepresentation(e,r,n,Dt.Labelmap,i);this.processLabelmapRepresentationAddition(r,n),this.addDefaultSegmentationRepresentation(e,r,n,Dt.Labelmap,i)}async processLabelmapRepresentationAddition(e,r){const n=zn(e);if(!n)return;const i=this.getSegmentation(r);if(!i)return;const o=n.viewport instanceof Ir,{representationData:a}=i,s="volumeId"in a.Labelmap;n.viewport,!o&&!s&&this.updateLabelmapSegmentationImageReferences(e,i.segmentationId)}_updateLabelmapSegmentationReferences(e,r,n,i){const o=r.getCurrentImageId();let a=!1;for(const s of n)r.isReferenceViewable({referencedImageId:s},{asOverlay:!0})&&(a=!0,this._stackLabelmapImageIdReferenceMap.get(e).set(o,s),this._updateLabelmapImageIdReferenceMap({segmentationId:e,referenceImageId:o,labelmapImageId:s}));return i&&i(r,e,n),a?this._stackLabelmapImageIdReferenceMap.get(e).get(o):void 0}updateLabelmapSegmentationImageReferences(e,r){const n=this.getSegmentation(r);if(!n)return;this._stackLabelmapImageIdReferenceMap.has(r)||this._stackLabelmapImageIdReferenceMap.set(r,new Map);const{representationData:i}=n;if(!i.Labelmap)return;const o=this.getLabelmapImageIds(i),s=zn(e).viewport;return this._updateLabelmapSegmentationReferences(r,s,o,null)}_updateAllLabelmapSegmentationImageReferences(e,r){const n=this.getSegmentation(r);if(!n)return;this._stackLabelmapImageIdReferenceMap.has(r)||this._stackLabelmapImageIdReferenceMap.set(r,new Map);const{representationData:i}=n;if(!i.Labelmap)return;const o=this.getLabelmapImageIds(i),s=zn(e).viewport;this._updateLabelmapSegmentationReferences(r,s,o,(c,l,f)=>{c.getImageIds().forEach((d,h)=>{for(const g of f)c.isReferenceViewable({referencedImageId:g,sliceIndex:h},{asOverlay:!0,withNavigation:!0})&&(this._stackLabelmapImageIdReferenceMap.get(l).set(d,g),this._updateLabelmapImageIdReferenceMap({segmentationId:l,referenceImageId:d,labelmapImageId:g}))})})}getLabelmapImageIds(e){const r=e.Labelmap;let n;if(r.imageIds)n=r.imageIds;else if(!n&&r.volumeId){const i=r.volumeId;n=Le.getVolume(i).imageIds}return n}getLabelmapImageIdsForImageId(e,r){const n=this._generateMapKey({segmentationId:r,referenceImageId:e});return this._labelmapImageIdReferenceMap.get(n)}getCurrentLabelmapImageIdsForViewport(e,r){const n=zn(e);if(!n)return;const o=n.viewport.getCurrentImageId();return this.getLabelmapImageIdsForImageId(o,r)}getCurrentLabelmapImageIdForViewport(e,r){const n=zn(e);if(!n||!this._stackLabelmapImageIdReferenceMap.has(r))return;const o=n.viewport.getCurrentImageId();return this._stackLabelmapImageIdReferenceMap.get(r).get(o)}getStackSegmentationImageIdsForViewport(e,r){if(!this.getSegmentation(r))return[];this._updateAllLabelmapSegmentationImageReferences(e,r);const{viewport:i}=zn(e),o=i.getImageIds(),a=this._stackLabelmapImageIdReferenceMap.get(r);return o.map(s=>a.get(s))}removeSegmentationRepresentationsInternal(e,r){const n=[];return this.updateState(i=>{if(!i.viewportSegRepresentations[e])return;const o=i.viewportSegRepresentations[e];let a=!1;if(!r||Object.values(r).every(s=>s===void 0))n.push(...o),delete i.viewportSegRepresentations[e];else{const{segmentationId:s,type:c}=r;i.viewportSegRepresentations[e]=o.filter(l=>{const f=s&&c&&l.segmentationId===s&&l.type===c||s&&!c&&l.segmentationId===s||!s&&c&&l.type===c;return f&&(n.push(l),l.active&&(a=!0)),!f}),i.viewportSegRepresentations[e].length===0?delete i.viewportSegRepresentations[e]:a&&(i.viewportSegRepresentations[e][0].active=!0)}}),n}removeSegmentationRepresentations(e,r){const n=this.removeSegmentationRepresentationsInternal(e,r);n.forEach(o=>{yC(e,o.segmentationId,o.type)});const i=this.getSegmentationRepresentations(e);return i.length>0&&i[0].active&&Gs(e,i[0].segmentationId,i[0].type),n}removeSegmentationRepresentation(e,r,n){const i=this.removeSegmentationRepresentationsInternal(e,r);return n||i.forEach(({segmentationId:o,type:a})=>{yC(e,o,a)}),i}_updateLabelmapImageIdReferenceMap({segmentationId:e,referenceImageId:r,labelmapImageId:n}){const i=this._generateMapKey({segmentationId:e,referenceImageId:r});if(!this._labelmapImageIdReferenceMap.has(i)){this._labelmapImageIdReferenceMap.set(i,[n]);return}const o=this._labelmapImageIdReferenceMap.get(i),a=Array.from(new Set([...o,n]));this._labelmapImageIdReferenceMap.set(i,a)}_setActiveSegmentation(e,r,n){const i=e.viewportSegRepresentations[r];i&&i.forEach(o=>{o.active=o.segmentationId===n})}setActiveSegmentation(e,r){this.updateState(n=>{const i=n.viewportSegRepresentations[e];i&&i.forEach(o=>{o.active=o.segmentationId===r})}),Gs(e,r)}getActiveSegmentation(e){if(!this.state.viewportSegRepresentations[e])return;const r=this.state.viewportSegRepresentations[e].find(n=>n.active);if(r)return this.getSegmentation(r.segmentationId)}getSegmentationRepresentations(e,r={}){const n=this.state.viewportSegRepresentations[e];return n?!r.type&&!r.segmentationId?n:n.filter(i=>{const o=r.type?i.type===r.type:!0,a=r.segmentationId?i.segmentationId===r.segmentationId:!0;return o&&a}):[]}getSegmentationRepresentation(e,r){return this.getSegmentationRepresentations(e,r)[0]}getSegmentationRepresentationVisibility(e,r){const n=this.getSegmentationRepresentation(e,r);return n==null?void 0:n.visible}setSegmentationRepresentationVisibility(e,r,n){this.updateState(i=>{const o=this.getSegmentationRepresentations(e,r);o&&o.forEach(a=>{a.visible=n,Object.entries(a.segments).forEach(([s,c])=>{c.visible=n})})}),Gs(e,r.segmentationId,r.type)}addColorLUT(e,r){this.updateState(n=>{n.colorLUT[r]&&console.warn("Color LUT table already exists, overwriting"),n.colorLUT[r]=Fa(e)})}removeColorLUT(e){this.updateState(r=>{delete r.colorLUT[e]})}_getStackIdForImageIds(e){return e.map(r=>r.slice(-Math.round(r.length*.15))).join("_")}getAllViewportSegmentationRepresentations(){return Object.entries(this.state.viewportSegRepresentations).map(([e,r])=>({viewportId:e,representations:r}))}getSegmentationRepresentationsBySegmentationId(e){const r=[];return Object.entries(this.state.viewportSegRepresentations).forEach(([n,i])=>{const o=i.filter(a=>a.segmentationId===e);o.length>0&&r.push({viewportId:n,representations:o})}),r}_generateMapKey({segmentationId:e,referenceImageId:r}){return`${e}-${r}`}}async function ak({imageIds:t,options:e}){const r=t,n=(e==null?void 0:e.volumeId)||Dn();return await QL(n,r),{volumeId:n}}async function nfe({segmentationId:t,options:e}){const r=Zn.getSegmentation(t),n=r.representationData.Labelmap,{volumeId:i}=await ak({imageIds:n.imageIds,options:e});r.representationData.Labelmap.volumeId=i}function sD(t){const e=Xc.newInstance(),r=Jf.newInstance();return r.addPoint(0,0),t===Dt.Labelmap?{cfun:e,ofun:r}:{}}const Zn=new tfe("DEFAULT");function Jo(t,e={}){return Zn.getSegmentationRepresentations(t,e)}function t4(t,e){const r=Zn;if(!e.segmentationId||!e.type)throw new Error("getSegmentationRepresentation: No segmentationId or type provided, you need to provide at least one of them");const n=r.getSegmentationRepresentations(t,e);return n==null?void 0:n[0]}function sk(t){return Zn.getSegmentationRepresentationsBySegmentationId(t)}function rfe(t,e){const r=Ce(t),{viewport:n}=r,o=n.getActors().filter(a=>a.representationUID&&typeof a.representationUID=="string"&&a.representationUID.startsWith(e));n.removeActors(o.map(a=>a.uid))}function ck(t,e,r){const n=zn(t);if(!n)return;const{renderingEngine:i,viewport:o}=n;if(!i||!o)return;const s=o.getActors().filter(r);return s.length>0?s[0]:void 0}function ife(t,e){const r=zn(t);if(!r)return;const{renderingEngine:n,viewport:i}=r;if(!n||!i)return;const a=i.getActors().filter(e);return a.length>0?a:void 0}function ofe(t,e){const r=_5(t,e);return r==null?void 0:r.uid}function Wg(t,e){return ife(t,r=>{var n;return(n=r.representationUID)==null?void 0:n.startsWith(`${e}-${Dt.Labelmap}`)})}function _5(t,e){return ck(t,e,r=>{var n;return(n=r.representationUID)==null?void 0:n.startsWith(`${e}-${Dt.Labelmap}`)})}function afe(t,e,r){return ck(t,e,n=>n.representationUID===lk(e,r))}function lk(t,e){return`${t}-${Dt.Surface}-${e}`}function sfe(t,e,r){const n=Ce(t),{viewport:i}=n,o=afe(i.id,r,e.segmentIndex),a=o==null?void 0:o.actor,s=e.visible;if(a){if(a.setVisibility(s),!s)return;const y=a.getMapper(),m=y.getInputData(),w=e.points,x=e.polys,C=m.getPoints().getData(),S=m.getPolys().getData();if(w.length===C.length&&x.length===S.length)return;const _=Xo.newInstance();_.getPoints().setData(w,3);const T=Yf.newInstance({values:Float32Array.from(x)});_.setPolys(T),y.setInputData(_),y.modified(),i.getRenderer().resetCameraClippingRange();return}const c=e.points,l=e.polys,f=e.color,u=Xo.newInstance();u.getPoints().setData(c,3);const d=Yf.newInstance({values:Float32Array.from(l)});u.setPolys(d);const h=g1.newInstance({});let g;h.setInputData(u);const p=Qy.newInstance();p.setMapper(h),p.getProperty().setColor(f[0]/255,f[1]/255,f[2]/255),p.getProperty().setLineWidth(2);const v=lk(r,e.segmentIndex);i.addActor({uid:Dn(),actor:p,clippingFilter:g,representationUID:v}),i.resetCamera(),i.getRenderer().resetCameraClippingRange(),i.render()}function Ln(t){return Zn.getSegmentation(t)}function D1(t){return Zn.getColorLUT(t)}let qv={};function cfe(){return qv}function lfe(t){qv=t}let cD=!1;function Gc(){var e;if(!((e=qv.addons)!=null&&e.polySeg))return console.warn("PolySeg add-on not configured. This will prevent automatic conversion between segmentation representations (labelmap, contour, surface). To enable these features, install @cornerstonejs/polymorphic-segmentation and register it during initialization: cornerstoneTools.init({ addons: { polySeg } })."),null;const t=qv.addons.polySeg;return cD||(t.init(),cD=!0),t}function n4({segmentationId:t,type:e,data:r}){const n=Ln(t);if(!n)throw new Error(`Segmentation ${t} not found`);switch(n.representationData[e]&&console.warn(`Representation data of type ${e} already exists for segmentation ${t}, overwriting it.`),e){case Dt.Labelmap:r&&(n.representationData[e]=r);break;case Dt.Contour:r&&(n.representationData[e]=r);break;case Dt.Surface:r&&(n.representationData[e]=r);break;default:throw new Error(`Invalid representation type ${e}`)}}function r4(t){const e=typeof t;return t!==null&&(e==="object"||e==="function")}function gh(t,e,r){let n,i,o,a,s,c,l=0,f=!1,u=!1,d=!0;const h=!e&&e!==0&&typeof window.requestAnimationFrame=="function";if(typeof t!="function")throw new TypeError("Expected a function");e=Number(e)||0,r4(r)&&(f=!!r.leading,u="maxWait"in r,o=u?Math.max(Number(r.maxWait)||0,e):o,d="trailing"in r?!!r.trailing:d);function g(D){const b=n,I=i;return n=i=void 0,l=D,a=t.apply(I,b),a}function p(D,b){return h?window.requestAnimationFrame(D):setTimeout(D,b)}function v(D){if(h)return window.cancelAnimationFrame(D);clearTimeout(D)}function y(D){return l=D,s=p(x,e),f?g(D):a}function m(D){const b=D-c,I=D-l,P=e-b;return u?Math.min(P,o-I):P}function w(D){const b=D-c,I=D-l;return c===void 0||b>=e||b<0||u&&I>=o}function x(){const D=Date.now();if(w(D))return C(D);s=p(x,m(D))}function C(D){return s=void 0,d&&n?g(D):(n=i=void 0,a)}function S(){s!==void 0&&v(s),l=0,n=c=i=s=void 0}function _(){return s===void 0?a:C(Date.now())}function T(){return s!==void 0}function E(...D){const b=Date.now(),I=w(b);if(n=D,i=this,c=b,I){if(s===void 0)return y(c);if(u)return s=p(x,e),g(c)}return s===void 0&&(s=p(x,e)),a}return E.cancel=S,E.flush=_,E.pending=T,E}const P2=new Map;async function i4(t,e,r,n,i){const o=await r();n4({segmentationId:t,type:e,data:o}),i==null||i(),P2.has(t)||P2.set(t,[]);const a=P2.get(t);return a.includes(e)||a.push(e),ufe(n),Ta(t),o}function ufe(t){const e=r=>{ffe(r,t)};t._debouncedUpdateFunction=e,Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,t._debouncedUpdateFunction),Ke.addEventListener(N.SEGMENTATION_DATA_MODIFIED,t._debouncedUpdateFunction)}const ffe=gh((t,e)=>{const r=t.detail.segmentationId,n=P2.get(r);!n||!n.length||(e(r),n.length&&Ta(r))},300);function o4(t,e){const r=t4(t,e);return r?Object.entries(r.segments).reduce((i,[o,a])=>(a.visible||i.add(Number(o)),i),new Set):new Set}function dfe(t,e,r=!1){const n=zn(t);if(!n)return;const{viewport:i}=n;rfe(i.element,e),r&&i.render()}async function hfe(t,e){var l;const{segmentationId:r,type:n}=e,i=Ln(r);if(!i)return;let o=i.representationData[Dt.Surface];if(!o&&((l=Gc())!=null&&l.canComputeRequestedRepresentation(r,Dt.Surface))){const f=Gc();if(o=await i4(r,Dt.Surface,()=>f.computeSurfaceData(r,{viewport:t}),()=>f.updateSurfaceData(r,{viewport:t})),!o)throw new Error(`No Surface data found for segmentationId ${r} even we tried to compute it`)}else!o&&!Gc()&&console.debug(`No surface data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to surface. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(!o){console.warn(`No Surface data found for segmentationId ${r}. Skipping render.`);return}const{geometryIds:a}=o;a!=null&&a.size||console.warn(`No Surfaces found for segmentationId ${r}. Skipping render.`);const{colorLUTIndex:s}=e,c=D1(s);a.forEach(f=>{const u=Le.getGeometry(f);if(!(u!=null&&u.data)){console.warn(`No Surfaces found for geometryId ${f}. Skipping render.`);return}const{segmentIndex:d}=u.data,g=o4(t.id,{segmentationId:r,type:n}).has(d),p=u.data,v=c[d];p.color=v.slice(0,3),p.visible=!g,sfe(t.element,p,r)}),t.render()}const uk={render:hfe,removeRepresentation:dfe};function gfe(t,e,r,n){const i=t.getViewReference(),{viewPlaneNormal:o,FrameOfReferenceUID:a}=i,s={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:e,viewPlaneNormal:o,FrameOfReferenceUID:a,referencedImageId:pfe(t,r[0],o),...n}};return nn(s,t.element),s}function pfe(t,e,r){let n;if(t instanceof lr)n=a4(t,e,r);else if(t instanceof Ir){const i=mfe(t),o=sc(i),a=Le.getVolume(o);n=qc(a,e,r)}else throw new Error("getReferencedImageId: viewport must be a StackViewport or BaseVolumeViewport");return n}function mfe(t){var r;const e=(r=t.getViewReferenceId)==null?void 0:r.call(t);if(e)return e;if(t instanceof Ir)return`volumeId:${vfe(t)}`;throw new Error("getTargetId: viewport must have a getTargetId method")}function vfe(t){var r;const e=t.getActors();if(e)return(r=e.find(n=>n.actor.getClassName()==="vtkVolume"))==null?void 0:r.uid}function a4(t,e,r){const n=t.getImageIds();if(!n||!n.length)return;const i=n.map(o=>{const{imagePositionPatient:a}=mt("imagePlaneModule",o),s=yfe(e,a,r);return{imageId:o,distance:s}});return i.sort((o,a)=>o.distance-a.distance),i[0].imageId}function yfe(t,e,r){const n=Ve();En(n,t,e);const i=Et(n,r);return Math.abs(i)}function fk(t,e){const{segmentation:r}=t.data,{segmentation:n}=e.data;return r.segmentationId===n.segmentationId&&r.segmentIndex===n.segmentIndex}class dk{constructor(e){this.getGroupKey=r=>{if(typeof r=="string")return r;const i=Ce(r);if(!i)throw new Error("Element not enabled, you must have an enabled element if you are not providing a FrameOfReferenceUID");return i.FrameOfReferenceUID},this._imageVolumeModifiedHandler=r=>{const n=r.detail,{FrameOfReferenceUID:i}=n,a=this.annotations[i];a&&Object.keys(a).forEach(s=>{a[s].forEach(l=>{l.invalidated!==void 0&&(l.invalidated=!0)})})},this.getFramesOfReference=()=>Object.keys(this.annotations),this.getAnnotations=(r,n)=>{const i=this.annotations;return i[r]?n?i[r][n]?i[r][n]:[]:i[r]:[]},this.getAnnotation=r=>{const n=this.annotations;for(const i in n){const o=n[i];for(const a in o){const s=o[a];for(const c of s)if(r===c.annotationUID)return c}}},this.getNumberOfAnnotations=(r,n)=>{const i=this.getAnnotations(r,n);if(!i.length)return 0;if(n)return i.length;let o=0;for(const a in i)o+=i[a].length;return o},this.addAnnotation=(r,n)=>{const{metadata:i}=r,{FrameOfReferenceUID:o,toolName:a}=i;n=n||o;const s=this.annotations;let c=s[n];c||(s[n]={},c=s[n]);let l=c[a];l||(c[a]=[],l=c[a]),this.preprocessingFn&&(r=this.preprocessingFn(r)),l.push(r)},this.removeAnnotation=r=>{const{annotations:n}=this;for(const i in n){const o=n[i];for(const a in o){const s=o[a],c=s.findIndex(l=>l.annotationUID===r);c!==-1&&(s.splice(c,1),s.length===0&&delete o[a])}Object.keys(o).length===0&&delete n[i]}},this.removeAnnotations=(r,n)=>{const i=this.annotations,o=[];if(!i[r])return o;if(n){const a=i[r][n];for(const s of a)this.removeAnnotation(s.annotationUID),o.push(s)}else for(const a in i[r]){const s=i[r][a];for(const c of s)this.removeAnnotation(c.annotationUID),o.push(c)}return o},this.saveAnnotations=(r,n)=>{const i=this.annotations;if(r&&n){const o=i[r];if(!o)return;const a=o[n];return structuredClone(a)}else if(r){const o=i[r];return structuredClone(o)}return structuredClone(i)},this.restoreAnnotations=(r,n,i)=>{const o=this.annotations;if(n&&i){let a=o[n];a||(o[n]={},a=o[n]),a[i]=r}else n?o[n]=r:this.annotations=structuredClone(r)},this.getAllAnnotations=()=>Object.values(this.annotations).map(r=>Object.values(r)).flat(2),this.getNumberOfAllAnnotations=()=>{let r=0;const n=this.annotations;for(const i in n){const o=n[i];for(const a in o){const s=o[a];r+=s.length}}return r},this.removeAllAnnotations=()=>{const r=[];for(const n of this.getAllAnnotations())this.removeAnnotation(n.annotationUID),r.push(n);return r},e||(e=Dn()),this.annotations={},this.uid=e,Ke.addEventListener(Xe.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedHandler)}setPreprocessingFn(e){this.preprocessingFn=e}}const wfe=new dk("DEFAULT"),fu=new Set;function hk(t,e=!0){const r=pk();t&&(e?_fe(t,fu,r):mk(t,fu,r)),vk(r,fu)}function xfe(){const t=pk();Tfe(fu,t),vk(t,fu)}function Cfe(){return Array.from(fu)}function Zr(t){return fu.has(t)}function Sfe(){return fu.size}function gk(t){const e=Zr(t);return hk(t,e),e}function pk(){return Object.freeze({added:[],removed:[],locked:[]})}function _fe(t,e,r){if(!e.has(t)){e.add(t),r.added.push(t);const n=Br(t);n&&(n.isLocked=!0)}}function mk(t,e,r){if(e.delete(t)){r.removed.push(t);const n=Br(t);n&&(n.isLocked=!1)}}function Tfe(t,e){t.forEach(r=>{mk(r,t,e)})}function vk(t,e){(t.added.length>0||t.removed.length>0)&&(e.forEach(r=>void t.locked.push(r)),at(Ke,N.ANNOTATION_LOCK_CHANGE,t))}const Efe=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationLocked:gk,getAnnotationsLocked:Cfe,getAnnotationsLockedCount:Sfe,isAnnotationLocked:Zr,setAnnotationLocked:hk,unlockAllAnnotations:xfe},Symbol.toStringTag,{value:"Module"})),Ws=new Set;function Ro(t,e=!0,r=!1){e?Dfe(t,r):s4(t)}function Dfe(t,e=!1){const r=wk();if(!e){xk(Ws,r);const n=Br(t);n&&(n.isSelected=!0)}if(t&&!Ws.has(t)){Ws.add(t),r.added.push(t);const n=Br(t);n&&(n.isSelected=!0)}Ck(r,Ws)}function s4(t){const e=wk();if(t){if(Ws.delete(t)){e.removed.push(t);const r=Br(t);r.isSelected=!1}}else xk(Ws,e);Ck(e,Ws)}function yk(){return Array.from(Ws)}function bfe(t){return yk().filter(e=>{var n;const r=Br(e);return((n=r==null?void 0:r.metadata)==null?void 0:n.toolName)===t})}function b1(t){return Ws.has(t)}function Ife(){return Ws.size}function wk(){return Object.freeze({added:[],removed:[],selection:[]})}function xk(t,e){t.forEach(r=>{if(t.delete(r)){e.removed.push(r);const n=Br(r);n&&(n.isSelected=!1)}})}function Ck(t,e){(t.added.length>0||t.removed.length>0)&&(e.forEach(r=>void t.selection.push(r)),at(Ke,N.ANNOTATION_SELECTION_CHANGE,t))}const Ofe=Object.freeze(Object.defineProperty({__proto__:null,deselectAnnotation:s4,getAnnotationsSelected:yk,getAnnotationsSelectedByToolName:bfe,getAnnotationsSelectedCount:Ife,isAnnotationSelected:b1,setAnnotationSelected:Ro},Symbol.toStringTag,{value:"Module"})),Mfe=t=>(t.data||(t.data={}),t.data.handles||(t.data.handles={}),t.data.handles.textBox||(t.data.handles.textBox={}),t),Pfe=t=>(t.data||(t.data={}),t.data.cachedStats||(t.data.cachedStats={}),t),Qf=new Set;function Sk(t,e=!0){const r=_k();t&&(e?Tk(t,Qf,r):Lfe(t,Qf,r)),Ek(r)}function Rfe(){const t=_k();Qf.forEach(e=>{Tk(e,Qf,t)}),Ek(t)}function Gr(t){if(Br(t))return!Qf.has(t)}function _k(){return Object.freeze({lastVisible:[],lastHidden:[],hidden:[]})}function Tk(t,e,r){if(e.delete(t)){r.lastVisible.push(t);const n=Br(t);n.isVisible=!0}}function Lfe(t,e,r){e.has(t)||(e.add(t),b1(t)&&s4(t),r.lastHidden.push(t))}function Ek(t){(t.lastHidden.length>0||t.lastVisible.length>0)&&(Qf.forEach(e=>void t.hidden.push(e)),at(Ke,N.ANNOTATION_VISIBILITY_CHANGE,t))}function Dk(t){const e=!Qf.has(t);return Sk(t,e),e}const Afe=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationVisibility:Dk,isAnnotationVisible:Gr,setAnnotationVisibility:Sk,showAllAnnotations:Rfe},Symbol.toStringTag,{value:"Module"})),c4=wfe,Nfe=t=>{t=Mfe(t),t=Pfe(t);const e=t.annotationUID,r=gk(e);t.isLocked=r;const n=Dk(e);return t.isVisible=n,t};c4.setPreprocessingFn(Nfe);qT(c4);function kfe(){qT(c4)}function Yc(t){if(!t.data.segmentation)throw new Error("removeContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:e,segmentIndex:r}=t.data.segmentation,n=Ln(e),{annotationUIDsMap:i}=(n==null?void 0:n.representationData.Contour)||{},o=i==null?void 0:i.get(r);o&&(o.delete(t.annotationUID),o.size||i.delete(r))}function Jc(t){if(t.parentAnnotationUID)return;if(!t.data.segmentation)throw new Error("addContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:e,segmentIndex:r}=t.data.segmentation,n=Ln(e);n.representationData.Contour||(n.representationData.Contour={annotationUIDsMap:new Map});let{annotationUIDsMap:i}=n.representationData.Contour;i||(i=new Map);let o=i==null?void 0:i.get(r);o||(o=new Set,i.set(r,o)),i.set(r,o.add(t.annotationUID))}const Vfe="PlanarFreehandContourSegmentationTool";function l4(t){var o;const{polyline:e}=((o=t.data)==null?void 0:o.contour)||{};if(!e||e.length<3){console.warn("Skipping creation of new annotation due to invalid polyline:",e);return}gn(t.annotationUID),Yc(t);const r=e[0],n=e[e.length-1],i={metadata:{...t.metadata,toolName:Vfe,originalToolName:t.metadata.originalToolName||t.metadata.toolName},data:{cachedStats:{},handles:{points:[r,n],textBox:t.data.handles.textBox?{...t.data.handles.textBox}:void 0},contour:{...t.data.contour},spline:t.data.spline,segmentation:{...t.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:t.interpolationUID,interpolationCompleted:t.interpolationCompleted};return nn(i,t.metadata.FrameOfReferenceUID),Jc(i),i}var Lo;(function(t){t[t.CounterClockwise=-1]="CounterClockwise",t[t.Unknown=0]="Unknown",t[t.Clockwise=1]="Clockwise"})(Lo||(Lo={}));function u4(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Xv(t,e){const r=t.maxX-t.minX,n=t.maxY-t.minY,i=[r,n],o=[t.minX+r/2,t.minY+n/2],a=[Math.abs(e[0]-o[0]),Math.abs(e[1]-o[1])],s=a[0]-i[0]*.5,c=a[1]-i[1]*.5;if(s>0&&c>0)return s*s+c*c;const l=Math.max(s,0)+Math.max(c,0);return l*l}function Ffe(t,e){return Math.sqrt(Xv(t,e))}const Ufe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:Ffe,distanceToPointSquared:Xv,intersectAABB:u4},Symbol.toStringTag,{value:"Module"}));class bk{}class Ik{constructor(e){this.storePointData=e.storePointData}getStatistics(){console.debug("InstanceCalculator getStatistics called")}}const{PointsManager:Bfe}=Mn;function Wp(t){return{max:[-1/0],min:[1/0],sum:[0],count:0,maxIJK:null,maxLPS:null,minIJK:null,minLPS:null,runMean:[0],m2:[0],m3:[0],m4:[0],allValues:[[]],pointsInShape:t?Bfe.create3(1024):null,sumLPS:[0,0,0]}}function Ok(t,e,r=null,n=null){Array.isArray(e)&&e.length>1&&t.max.length===1&&(t.max.push(t.max[0],t.max[0]),t.min.push(t.min[0],t.min[0]),t.sum.push(t.sum[0],t.sum[0]),t.runMean.push(0,0),t.m2.push(t.m2[0],t.m2[0]),t.m3.push(t.m3[0],t.m3[0]),t.m4.push(t.m4[0],t.m4[0]),t.allValues.push([],[])),t!=null&&t.pointsInShape&&r&&t.pointsInShape.push(r);const i=Array.isArray(e)?e:[e];t.count+=1,r&&(t.sumLPS[0]+=r[0],t.sumLPS[1]+=r[1],t.sumLPS[2]+=r[2]),t.max.forEach((o,a)=>{const s=i[a];t.allValues[a].push(s);const c=t.count,l=s-t.runMean[a],f=l/c,u=l*f*(c-1);t.sum[a]+=s,t.runMean[a]+=f,t.m4[a]+=u*f*f*(c*c-3*c+3)+6*f*f*t.m2[a]-4*f*t.m3[a],t.m3[a]+=u*f*(c-2)-3*f*t.m2[a],t.m2[a]+=u,st.max[a]&&(t.max[a]=s,a===0&&(t.maxIJK=n?[...n]:null,t.maxLPS=r?[...r]:null))})}function Gfe(t){if(t.length===0)return 0;const e=[...t].sort((n,i)=>n-i),r=Math.floor(e.length/2);return e.length%2===0?(e[r-1]+e[r])/2:e[r]}function Mk(t,e){const r=t.sum.map(u=>u/t.count),n=t.m2.map(u=>Math.sqrt(u/t.count)),i=t.sumLPS.map(u=>u/t.count),o=t.m3.map((u,d)=>{const h=t.m2[d]/t.count;return h===0?0:u/(t.count*Math.pow(h,1.5))}),a=t.m4.map((u,d)=>{const h=t.m2[d]/t.count;return h===0?0:u/(t.count*h*h)-3}),s=t.allValues.map(u=>Gfe(u)),c={max:{name:"max",label:"Max Pixel",value:t.max.length===1?t.max[0]:t.max,unit:e,pointIJK:t.maxIJK?[...t.maxIJK]:null,pointLPS:t.maxLPS?[...t.maxLPS]:null},min:{name:"min",label:"Min Pixel",value:t.min.length===1?t.min[0]:t.min,unit:e,pointIJK:t.minIJK?[...t.minIJK]:null,pointLPS:t.minLPS?[...t.minLPS]:null},mean:{name:"mean",label:"Mean Pixel",value:r.length===1?r[0]:r,unit:e},stdDev:{name:"stdDev",label:"Standard Deviation",value:n.length===1?n[0]:n,unit:e},count:{name:"count",label:"Voxel Count",value:t.count,unit:null},median:{name:"median",label:"Median",value:s.length===1?s[0]:s,unit:e},skewness:{name:"skewness",label:"Skewness",value:o.length===1?o[0]:o,unit:null},kurtosis:{name:"kurtosis",label:"Kurtosis",value:a.length===1?a[0]:a,unit:null},maxLPS:{name:"maxLPS",label:"Max LPS",value:t.maxLPS?Array.from(t.maxLPS):null,unit:null},minLPS:{name:"minLPS",label:"Min LPS",value:t.minLPS?Array.from(t.minLPS):null,unit:null},pointsInShape:t.pointsInShape,center:{name:"center",label:"Center",value:i?[...i]:null,unit:null},array:[]};c.array.push(c.min,c.max,c.mean,c.stdDev,c.median,c.skewness,c.kurtosis,c.count,c.maxLPS,c.minLPS),c.center.value&&c.array.push(c.center);const l=t.pointsInShape!==null,f=Wp(l);return t.max=f.max,t.min=f.min,t.sum=f.sum,t.count=f.count,t.maxIJK=f.maxIJK,t.maxLPS=f.maxLPS,t.minIJK=f.minIJK,t.minLPS=f.minLPS,t.runMean=f.runMean,t.m2=f.m2,t.m3=f.m3,t.m4=f.m4,t.allValues=f.allValues,t.pointsInShape=f.pointsInShape,t.sumLPS=f.sumLPS,c}const Ef=class Ef extends bk{static statsInit(e){e.storePointData||(this.state.pointsInShape=null),this.state=Wp(e.storePointData)}};Ef.state=Wp(!0),Ef.statsCallback=({value:e,pointLPS:r=null,pointIJK:n=null})=>{Ok(Ef.state,e,r,n)},Ef.getStatistics=e=>Mk(Ef.state,e==null?void 0:e.unit);let rc=Ef;class Pk extends Ik{constructor(e){super(e),this.state=Wp(e.storePointData)}statsInit(e){this.state=Wp(e.storePointData)}statsCallback(e){Ok(this.state,e.value,e.pointLPS,e.pointIJK)}getStatistics(e){return Mk(this.state,e==null?void 0:e.unit)}}const Wfe=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:rc,Calculator:bk,InstanceBasicStatsCalculator:Pk,InstanceCalculator:Ik},Symbol.toStringTag,{value:"Module"}));function Zc(t,e){if(t.length!==e.length)throw Error("Both points should have the same dimensionality");const[r,n,i=0]=t,[o,a,s=0]=e,c=o-r,l=a-n,f=s-i;return c*c+l*l+f*f}function yo(t,e){return Math.sqrt(Zc(t,e))}function wC(t,e){const[r,n]=t,[i,o]=e,a=2*i-r,s=2*o-n;return[a,s]}const zfe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:yo,distanceToPointSquared:Zc,mirror:wC},Symbol.toStringTag,{value:"Module"}));function du(t){const[e,r]=t;return yo(e,r)}function x0(t){const[e,r]=t,n=yo(e,r),i=[e[0]-n,e[1]-n],o=[e[0]+n,e[1]+n];return[i,o]}const $fe=Object.freeze(Object.defineProperty({__proto__:null,getCanvasCircleCorners:x0,getCanvasCircleRadius:du},Symbol.toStringTag,{value:"Module"}));function T5(t,e,r={}){return r.precalculated||f4(t,r),r.precalculated(e)}const f4=(t,e={})=>{const{xRadius:r,yRadius:n,zRadius:i}=t;(e.invXRadiusSq===void 0||e.invYRadiusSq===void 0||e.invZRadiusSq===void 0)&&(e.invXRadiusSq=r!==0?1/r**2:0,e.invYRadiusSq=n!==0?1/n**2:0,e.invZRadiusSq=i!==0?1/i**2:0);const{invXRadiusSq:o,invYRadiusSq:a,invZRadiusSq:s}=e,{center:c}=t,[l,f,u]=c;return e.precalculated=d=>{const h=d[0]-l;let g=h*h*o;if(g>1)return!1;const p=d[1]-f;if(g+=p*p*a,g>1)return!1;const v=d[2]-u;return g+=v*v*s,g<=1},e};function Yv(t){const[e,r,n,i]=t,o=[n[0],r[1]],a=[i[0],e[1]];return[o,a]}const jfe=Object.freeze(Object.defineProperty({__proto__:null,getCanvasEllipseCorners:Yv,pointInEllipse:T5,precalculatePointInEllipse:f4},Symbol.toStringTag,{value:"Module"}));function Jv(t,e,r){let n;const i=Zc(t,e);if(t[0]===e[0]&&t[1]===e[1]&&(n=t),!n){const o=((r[0]-t[0])*(e[0]-t[0])+(r[1]-t[1])*(e[1]-t[1]))/i;o<0?n=t:o>1?n=e:n=[t[0]+o*(e[0]-t[0]),t[1]+o*(e[1]-t[1])]}return{point:[...n],distanceSquared:Zc(r,n)}}function I1(t,e,r){return Jv(t,e,r).distanceSquared}function hi(t,e,r){if(t.length!==2||e.length!==2||r.length!==2)throw Error("lineStart, lineEnd, and point should have 2 elements of [x, y]");return Math.sqrt(I1(t,e,r))}function Om(t){return typeof t=="number"?t?t<0?-1:1:t===t?0:NaN:NaN}function Zv(t,e,r,n,i=!1){const[o,a]=t,[s,c]=e,[l,f]=r,[u,d]=n;if(i){const I=(o-s)*(f-d)-(a-c)*(l-u);if(Math.abs(I)<1e-10)return;const P=((o-l)*(f-d)-(a-f)*(l-u))/I,M=o+P*(s-o),L=a+P*(c-a);return[M,L]}const h=c-a,g=o-s,p=s*a-o*c,v=h*l+g*f+p,y=h*u+g*d+p;if(v!==0&&y!==0&&Om(v)===Om(y))return;const m=d-f,w=l-u,x=u*f-l*d,C=m*o+w*a+x,S=m*s+w*c+x;if(C!==0&&S!==0&&Om(C)===Om(S))return;const _=h*w-m*g;let T;T=g*x-w*p;const E=T/_;T=m*p-h*x;const D=T/_;return[E,D]}const qh=.01;function R2(t,e,r){const n=t[0]<=e[0]?t[0]:e[0],i=t[0]>=e[0]?t[0]:e[0],o=t[1]<=e[1]?t[1]:e[1],a=t[1]>=e[1]?t[1]:e[1];if(!(r[0]>=n-qh&&r[0]<=i+qh&&r[1]>=o-qh&&r[1]<=a+qh))return!1;const c=(e[1]-t[1])*(r[0]-e[0])-(e[0]-t[0])*(r[1]-e[1]);return(c>=0?c:-c)<=qh}const Hfe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:hi,distanceToPointSquared:I1,distanceToPointSquaredInfo:Jv,intersectLine:Zv,isPointOnLineSegment:R2},Symbol.toStringTag,{value:"Module"}));function Rk(t){if(t.length<3)return!1;const e=t.length,r=t[0],n=t[e-1],i=Zc(r,n);return vu(0,i)}function _u(t,e,r={closed:void 0}){if(t.length<3)return!1;const n=t.length;let i=0;const{closed:o,holes:a}=r;if(a!=null&&a.length){for(const l of a)if(_u(l,e))return!1}const s=!(o===void 0?Rk(t):o),c=t.length-(s?1:2);for(let l=0;l<=c;l++){const f=t[l],u=l===n-1?0:l+1,d=t[u],h=f[0]>=d[0]?f[0]:d[0],g=f[1]>=d[1]?f[1]:d[1],p=f[1]<=d[1]?f[1]:d[1];if(e[0]<=h&&e[1]>=p&&e[1]h?s:h,c=c>g?c:g,i&&(l=lp?f:p)}return i?{minX:o,maxX:s,minY:a,maxY:c,minZ:l,maxZ:f}:{minX:o,maxX:s,minY:a,maxY:c}}function M1(t){const e=t.length;let r=0,n=e-1;for(let i=0;i=0?1:-1}function Kfe(t){const e=Ve(),r=t[0];for(let n=0,i=t.length;ne[0]?t[0]:e[0],c=t[1]>e[1]?t[1]:e[1],l=r[0]n[0]?r[0]:n[0],d=r[1]>n[1]?r[1]:n[1];if(o>u||sd||c0?1:2}function Pm(t,e,r){return e[0]<=Math.max(t[0],r[0])&&e[0]>=Math.min(t[0],r[0])&&e[1]<=Math.max(t[1],r[1])&&e[1]>=Math.min(t[1],r[1])}function g4(t,e,r,n=!0){const i=[],o=t.length,a=o-(n?1:2);for(let s=0;s<=a;s++){const c=t[s],l=s===o-1?0:s+1,f=t[l];h4(e,r,c,f)&&i.push([s,l])}return i}const Xfe=.01;function Lk(t,e,r,n){const i=[e[0]-t[0],e[1]-t[1]],o=[n[0]-r[0],n[1]-r[1]],a=o[1]*i[0]-o[0]*i[1];if((a>=0?a:-a)e[0]?t[0]:e[0],t[1]e[1]?t[1]:e[1]],p=[r[0]n[0]?r[0]:n[0],r[1]n[1]?r[1]:n[1]];if(!(g[0]<=p[1]&&g[1]>=p[0]&&g[2]<=p[3]&&g[3]>=p[2])||!(R2(t,e,r)||R2(t,e,n)||R2(r,n,t)))return;const m=g[0]>p[0]?g[0]:p[0],w=g[1]p[2]?g[2]:p[2],C=g[3]{const p=g[0],v=e[g[0]],y=e[g[1]],m=Lk(l,d,v,y),w=Zc(l,m);return{sourceLineSegmentId:p,coordinate:m,targetStartPointDistSquared:w}});h.sort((g,p)=>g.targetStartPointDistSquared-p.targetStartPointDistSquared),h.forEach(g=>{const{sourceLineSegmentId:p,coordinate:v}=g,y={type:Ff.Intersection,coordinates:v,position:C0.Edge,direction:a,visited:!1,next:null},m={...y,direction:Kd.Unknown,cloned:!0};a===Kd.Entering?y.next=m:m.next=y;let w=i.get(p);w||(w=[],i.set(p,w)),r.push(y),w.push(m),a*=-1})}for(let s=0,c=e.length;s({intersectionPoint:h,lineSegStartDistSquared:Zc(f,h.coordinates)})).sort((h,g)=>h.lineSegStartDistSquared-g.lineSegStartDistSquared).map(({intersectionPoint:h})=>h).forEach(h=>n.push(h))}return lD(r),lD(n),{targetPolylinePoints:r,sourcePolylinePoints:n}}function Nk(t){for(let e=0,r=t.length;e=f&&console.warn("Maximum iterations reached in mergePolylines, possible infinite loop detected"),s}function D5(t,e){const r=zp(t),n=zp(e),i=Et(n,r);vu(-1,i)||(e=e.slice().reverse());const{targetPolylinePoints:o}=Ak(t,e);let a=null;const s=[];let c=0;const l=t.length*2;for(;(a=Nk(o))&&c=h&&console.warn("Maximum inner iterations reached in subtractPolylines, possible infinite loop detected"),s.push(f)}return c>=l&&console.warn("Maximum outer iterations reached in subtractPolylines, possible infinite loop detected"),s}function kk(t,e,r,n=!0){let i,o;n?(o=t.length-1,i=0):(o=0,i=1);for(let a=i;ad&&(d=v,h=g)}d{const u=[t[f[0]],t[f[1]]],d=[(u[0][0]+u[1][0])/2,(u[0][1]+u[1][1])/2];s.push(yr(d,e))});const c=Math.min(...s),l=s.indexOf(c);return{segment:a[l],distance:c}}const Dd=.001,Zfe=(t,e)=>{let r,n,i;if(t instanceof lr){const a=t.getImageData();if(!a)return;n=a.direction.slice(0,3),i=a.direction.slice(3,6),r=a.spacing}else{const a=t.getImageData(),{direction:s,spacing:c}=a,{viewPlaneNormal:l,viewUp:f}=t.getCamera(),u=s.slice(0,3),d=s.slice(3,6),h=s.slice(6,9),g=Ve();Rn(g,f,l);const p=Math.abs(Et(g,u)),v=Math.abs(Et(g,d)),y=Math.abs(Et(g,h));let m;if(Math.abs(1-p)V_(t,e){const{xDir:i,yDir:o,spacing:a}=n,s=Ce(t),{viewport:c}=s;if(!e.length)return e.push(r),console.log(">>>>> !canvasPoints. :: RETURN"),1;const l=c.canvasToWorld(e[e.length-1]),f=c.canvasToWorld(r),u=Ve();rr(u,f,l);const d=Math.abs(Et(u,i)),h=Math.abs(Et(u,o)),g=Math.max(Math.floor(d/a[0]),Math.floor(h/a[0]));if(g>1){const p=e[e.length-1],v=V_(p,r),y=qt();Wr(y,r,p),Va(y,y[0]/v,y[1]/v);const m=v/g;for(let w=1;w<=g;w++)e.push([p[0]+m*y[0]*w,p[1]+m*y[1]*w])}else e.push(r);return g},tde=(t,e,r,n)=>{const i=[t[0]-e[0],t[1]-e[1]],o=[r[0]-e[0],r[1]-e[1]],a=i[0]*o[0]+i[1]*o[1];if(a<0)return!1;const s=Math.sqrt(o[0]*o[0]+o[1]*o[1]);if(s===0)return!1;const c=a/s,l=[o[0]/s,o[1]/s],f=[l[0]*c,l[1]*c],u=[e[0]+f[0],e[1]+f[1]];return!(yr(t,u)>n||yr(e,u)>yr(e,r))},nde=1e-6;function Fk(t){let e;const r=BT(t,50);for(let a=0;a<3;a++)if(r.every((s,c,l)=>Math.abs(s[a]-l[0][a])[o[0],o[1]]).sort((o,a)=>o[0]===a[0]?o[1]-a[1]:o[0]-a[0]);function r(o,a,s){return(a[0]-o[0])*(s[1]-o[1])-(a[1]-o[1])*(s[0]-o[0])}const n=[];for(const o of e){for(;n.length>=2&&r(n[n.length-2],n[n.length-1],o)<=0;)n.pop();n.push(o)}const i=[];for(let o=e.length-1;o>=0;o--){const a=e[o];for(;i.length>=2&&r(i[i.length-2],i[i.length-1],a)<=0;)i.pop();i.push(a)}return n.pop(),i.pop(),n.concat(i)}const ku=Object.freeze(Object.defineProperty({__proto__:null,addCanvasPointsToArray:ede,containsPoint:_u,containsPoints:O1,convexHull:Uk,decimate:m4,getAABB:Tu,getArea:M1,getClosestLineSegmentIntersection:Jfe,getFirstLineSegmentIntersectionIndexes:kk,getLineSegmentIntersectionsCoordinates:Vk,getLineSegmentIntersectionsIndexes:g4,getNormal2:zp,getNormal3:qfe,getSignedArea:d4,getSubPixelSpacingAndXYDirections:Zfe,getWindingDirection:L2,intersectPolyline:p4,isClosed:Rk,isPointInsidePolyline3D:v4,mergePolylines:E5,pointCanProjectOnLine:tde,pointsAreWithinCloseContourProximity:Qfe,projectTo2D:Fk,subtractPolylines:D5},Symbol.toStringTag,{value:"Module"}));function rde(t,e,r,n){const i=[t,e],o=[t+r,e],a=[t+r,e],s=[t+r,e+n],c=[t+r,e+n],l=[t,e+n],f=[t,e+n];return{top:[i,o],right:[a,s],bottom:[c,l],left:[f,[t,e]]}}function y4(t,e){if(t.length!==4||e.length!==2)throw Error("rectangle:[left, top, width, height] or point: [x,y] not defined correctly");const[r,n,i,o]=t;let a=655535;const s=rde(r,n,i,o);return Object.keys(s).forEach(c=>{const[l,f]=s[c],u=hi(l,f,e);u0){if(o>i)return 0;o>n&&(r[0]=o)}else{if(o=r[0]&&o<=r[2]&&a>=r[1]&&a<=r[3])return uD;const u=[0,1];if(Rm(r[0]-o,l,u)&&Rm(o-r[2],-l,u)&&Rm(r[1]-a,f,u)&&Rm(a-r[3],-f,u)){const[d,h]=u;return h<1&&(i[0]=o+h*l,i[1]=a+h*f),d>0&&(n[0]+=d*l,n[1]+=d*f),uD}return ade}const sde=Object.freeze(Object.defineProperty({__proto__:null,findClosestPoint:xC,liangBarksyClip:yg},Symbol.toStringTag,{value:"Module"}));function cde(t,e){const[r,n]=t,[i,o]=e,a=En(Ve(),n,r),s=En(Ve(),i,o),c=Et(a,s),l=Po(a),f=Po(s),u=c/(l*f);return Math.acos(u)*180/Math.PI}function lde(t,e){const[r,n]=t,[i,o]=e,a=Ga(qt(),n,r),s=Ga(qt(),i,o),c=k_(a,s),l=xv(a),f=xv(s),u=c/(l*f);return Math.acos(u)*(180/Math.PI)}function S0(t,e){return t[0].length===3?cde(t,e):lde(t,e)}const ude=Object.freeze(Object.defineProperty({__proto__:null,angleBetweenLines:S0},Symbol.toStringTag,{value:"Module"})),fde=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:Wfe,aabb:Ufe,angle:ude,circle:$fe,ellipse:jfe,lineSegment:Hfe,point:zfe,polyline:ku,rectangle:ide,vec2:sde},Symbol.toStringTag,{value:"Module"}));function Ds(t,e,r,n){var g,p,v;const{canvasToWorld:i,worldToCanvas:o}=r,{data:a}=t,{targetWindingDirection:s}=e;let{points:c}=e,l=L2(c);(g=n==null?void 0:n.decimate)!=null&&g.enabled&&(c=m4(e.points,(p=n==null?void 0:n.decimate)==null?void 0:p.epsilon));let{closed:f}=e;const u=c.length,d=new Array(u);L2(c);const h=SN(t);if(f===void 0){let y=!1;if(c.length>3){const m=Zc(c[0],c[u-1]);y=$t(0,m)}f=y}if((n==null?void 0:n.updateWindingDirection)!==!1){let y=h?h.data.contour.windingDirection*-1:s;y===void 0&&(y=l),y!==l&&c.reverse();const m=(((v=a.handles)==null?void 0:v.points)??[]).map(o);m.length>2&&L2(m)!==y&&a.handles.points.reverse(),l=y}for(let y=0;y{Ge.svgNodeCache[i][a].touched=!1}),{svgLayerElement:o,svgNodeCacheForCanvas:Ge.svgNodeCache,getSvgNode:pde.bind(this,i),appendNode:mde.bind(this,o,i),setNodeTouched:vde.bind(this,i),clearUntouched:yde.bind(this,o,i)}}function gde(t){const e=`.${dde}`,r=t.querySelector(e);return r==null?void 0:r.querySelector(":scope > .svg-layer")}function pde(t,e){if(Ge.svgNodeCache[t]&&Ge.svgNodeCache[t][e])return Ge.svgNodeCache[t][e].domRef}function mde(t,e,r,n){if(!Ge.svgNodeCache[e])return null;Ge.svgNodeCache[e][n]={touched:!0,domRef:r},t.appendChild(r)}function vde(t,e){Ge.svgNodeCache[t]&&Ge.svgNodeCache[t][e]&&(Ge.svgNodeCache[t][e].touched=!0)}function yde(t,e){Ge.svgNodeCache[e]&&Object.keys(Ge.svgNodeCache[e]).forEach(r=>{const n=Ge.svgNodeCache[e][r];!n.touched&&n.domRef&&(t.removeChild(n.domRef),delete Ge.svgNodeCache[e][r])})}function Bk(t,e){const r=hde(t);e(r),r.clearUntouched()}function cc(t,e,r){return`${t}::${e}::${r}`}function Ca(t,e){Object.keys(t).forEach(r=>{const n=e.getAttribute(r),i=t[r];i===void 0||i===""?e.removeAttribute(r):n!==i&&e.setAttribute(r,i)})}function lc(t,e){Object.keys(t).forEach(r=>{const n=t[r];n!==void 0&&n!==""&&e.setAttribute(r,n)})}function No(t,e,r,n,i,o={},a=""){const{color:s,fill:c,width:l,lineWidth:f,lineDash:u,fillOpacity:d,strokeOpacity:h}=Object.assign({color:"rgb(0, 255, 0)",fill:"transparent",width:"2",lineDash:void 0,lineWidth:void 0,strokeOpacity:1,fillOpacity:1},o),g=f||l,p="http://www.w3.org/2000/svg",v=cc(e,"circle",r),y=t.getSvgNode(v),m={cx:`${n[0]}`,cy:`${n[1]}`,r:`${i}`,stroke:s,fill:c,"stroke-width":g,"stroke-dasharray":u,"fill-opacity":d,"stroke-opacity":h};if(y)Ca(m,y),t.setNodeTouched(v);else{const w=document.createElementNS(p,"circle");a!==""&&w.setAttribute("data-id",a),lc(m,w),t.appendNode(w,v)}}function w4(t,e,r,n,i={},o=""){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},i),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"ellipse",r),h=t.getSvgNode(d),[g,p,v,y]=n,m=Math.hypot(v[0]-y[0],v[1]-y[1]),w=Math.hypot(p[0]-g[0],p[1]-g[1]),x=Math.atan2(v[1]-y[1],v[0]-y[0])*180/Math.PI,C=[(v[0]+y[0])/2,(p[1]+g[1])/2],S=m/2,_=w/2,T={cx:`${C[0]}`,cy:`${C[1]}`,rx:`${S}`,ry:`${_}`,stroke:a,fill:"transparent",transform:`rotate(${x} ${C[0]} ${C[1]})`,"stroke-width":f,"stroke-dasharray":l};if(h)Ca(T,h),t.setNodeTouched(d);else{const E=document.createElementNS(u,"ellipse");o!==""&&E.setAttribute("data-id",o),lc(T,E),t.appendNode(E,d)}}function wde(t,e,r,n,i,o={},a=""){const s=[(n[0]+i[0])/2,n[1]],c=[(n[0]+i[0])/2,i[1]],l=[n[0],(n[1]+i[1])/2],f=[i[0],(n[1]+i[1])/2];w4(t,e,r,[c,s,l,f],o={},a="")}function Qv(t,e,r,n,i={},o){const{color:a,handleRadius:s,width:c,lineWidth:l,fill:f,type:u,opacity:d}=Object.assign({color:"rgb(0, 255, 0)",handleRadius:"6",width:"2",lineWidth:void 0,fill:"transparent",type:"circle",opacity:1},i),h=l||c,g="http://www.w3.org/2000/svg",p=cc(e,"handle",`hg-${r}-index-${o}`);let v;if(u==="circle")v={cx:`${n[0]}`,cy:`${n[1]}`,r:s,stroke:a,fill:f,"stroke-width":h,opacity:d};else if(u==="rect"){const w=parseFloat(s)*1.5,x=n[0]-w*.5,C=n[1]-w*.5;v={x:`${x}`,y:`${C}`,width:`${w}`,height:`${w}`,stroke:a,fill:f,"stroke-width":h,rx:`${w*.1}`,opacity:d}}else throw new Error(`Unsupported handle type: ${u}`);const y=t.getSvgNode(p);if(y)Ca(v,y),t.setNodeTouched(p);else{const m=document.createElementNS(g,u);lc(v,m),t.appendNode(m,p)}}function ir(t,e,r,n,i={}){n.forEach((o,a)=>{Qv(t,e,r,o,i,a)})}function vn(t,e,r,n,i,o={},a=""){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{color:s="rgb(0, 255, 0)",width:c=10,lineWidth:l,lineDash:f,markerStartId:u=null,markerEndId:d=null,shadow:h=!1,strokeOpacity:g=1}=o,p=l||c,v="http://www.w3.org/2000/svg",y=cc(e,"line",r),m=t.getSvgNode(y),w=t.svgLayerElement.id,x=h?`filter:url(#shadow-${w});`:"",C={x1:`${n[0]}`,y1:`${n[1]}`,x2:`${i[0]}`,y2:`${i[1]}`,stroke:s,style:x,"stroke-width":p,"stroke-dasharray":f,"marker-start":u?`url(#${u})`:"","marker-end":d?`url(#${d})`:"","stroke-opacity":g};if(m)Ca(C,m),t.setNodeTouched(y);else{const S=document.createElementNS(v,"line");a!==""&&S.setAttribute("data-id",a),lc(C,S),t.appendNode(S,y)}}function Gk(t,e,r,n,i,o={}){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),f=i[0]+(n[0]-i[0])/2,u=[f,n[1]],d=[f,i[1]],h={start:n,end:u},g={start:u,end:d},p={start:d,end:i};vn(t,e,"1",h.start,h.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"2",g.start,g.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"3",p.start,p.end,{color:a,width:s,lineWidth:c,lineDash:l})}function Cs(t,e,r,n,i){if(n.length<2)return;const{color:o="rgb(0, 255, 0)",width:a=10,fillColor:s="none",fillOpacity:c=0,lineWidth:l,lineDash:f,closePath:u=!1,markerStartId:d=null,markerEndId:h=null}=i,g=l||a,p="http://www.w3.org/2000/svg",v=cc(e,"polyline",r),y=t.getSvgNode(v);let m="";for(const x of n)m+=`${x[0].toFixed(1)}, ${x[1].toFixed(1)} `;if(u){const x=n[0];m+=`${x[0]}, ${x[1]}`}const w={points:m,stroke:o,fill:s,"fill-opacity":c,"stroke-width":g,"stroke-dasharray":f,"marker-start":d?`url(#${d})`:"","marker-end":h?`url(#${h})`:""};if(y)Ca(w,y),t.setNodeTouched(v);else{const x=document.createElementNS(p,"polyline");lc(w,x),t.appendNode(x,v)}}function Wc(t,e,r,n,i){const a=n.length&&n[0].length&&Array.isArray(n[0][0])?n:[n],{color:s="rgb(0, 255, 0)",width:c=10,fillColor:l="none",fillOpacity:f=0,lineWidth:u,lineDash:d,closePath:h=!1}=i,g=u||c,p="http://www.w3.org/2000/svg",v=cc(e,"path",r),y=t.getSvgNode(v);let m="";for(let x=0,C=a.length;xm.length){for(let C=0;C0?xC(n,i):i,c=_de(o),l=xC(c,s),f=Object.assign({color:"rgb(255, 255, 0)",lineWidth:"1",lineDash:"2,3"},a);vn(t,e,`link-${r}`,s,l,f)}function _de(t){const{x:e,y:r,height:n,width:i}=t,o=i/2,a=n/2,s=[e+o,r],c=[e,r+a],l=[e+o,r+n],f=[e+i,r+a];return[s,c,l,f]}function qi(t,e,r,n,i,o,a,s={}){const c=Object.assign({handleRadius:"6",centering:{x:!1,y:!0}},s),l=Eu(t,e,r,n,i,c);return Sde(t,e,r,o,i,l,c),l}function x4(t,e,r,n,i={},o=""){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},i),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"rect",r),h=t.getSvgNode(d),[g,p,v,y]=n,m=Math.hypot(g[0]-p[0],g[1]-p[1]),w=Math.hypot(g[0]-v[0],g[1]-v[1]),x=[(y[0]+g[0])/2,(y[1]+g[1])/2],C=[(v[0]+g[0])/2,(v[1]+g[1])/2],S=Math.atan2(x[1]-C[1],x[0]-C[0])*180/Math.PI,_={x:`${x[0]-m/2}`,y:`${x[1]-w/2}`,width:`${m}`,height:`${w}`,stroke:a,fill:"transparent",transform:`rotate(${S} ${x[0]} ${x[1]})`,"stroke-width":f,"stroke-dasharray":l};if(h)Ca(_,h),t.setNodeTouched(d);else{const T=document.createElementNS(u,"rect");o!==""&&T.setAttribute("data-id",o),lc(_,T),t.appendNode(T,d)}}function P1(t,e,r,n,i,o={},a=""){const s=[n[0],n[1]],c=[i[0],n[1]],l=[n[0],i[1]],f=[i[0],i[1]];x4(t,e,r,[s,c,l,f],o,a)}const hD="http://www.w3.org/2000/svg";function ey(t,e,r,n,i,o={}){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{viaMarker:a=!1,color:s="rgb(0, 255, 0)",markerSize:c=10}=o;if(!a){Tde(t,e,r,n,i,o);return}const l=t.svgLayerElement.id,u=`${`arrow-${e}`}-${l}`,d=t.svgLayerElement.querySelector("defs");let h=d.querySelector(`#${u}`);if(h){h.setAttribute("markerWidth",`${c}`),h.setAttribute("markerHeight",`${c}`);const g=h.querySelector("path");g&&g.setAttribute("fill",s)}else{h=document.createElementNS(hD,"marker"),h.setAttribute("id",u),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX","8"),h.setAttribute("refY","5"),h.setAttribute("markerWidth",`${c}`),h.setAttribute("markerHeight",`${c}`),h.setAttribute("orient","auto");const g=document.createElementNS(hD,"path");g.setAttribute("d","M 0 0 L 10 5 L 0 10 z"),g.setAttribute("fill",s),h.appendChild(g),d.appendChild(h)}o.markerEndId=u,vn(t,e,r,n,i,o)}function Tde(t,e,r,n,i,o={}){const{color:a="rgb(0, 255, 0)",width:s=2,lineWidth:c,lineDash:l}=o,f=10,u=Math.atan2(i[1]-n[1],i[0]-n[0]),d={start:[i[0]-f*Math.cos(u-Math.PI/7),i[1]-f*Math.sin(u-Math.PI/7)],end:i},h={start:[i[0]-f*Math.cos(u+Math.PI/7),i[1]-f*Math.sin(u+Math.PI/7)],end:i};vn(t,e,r,n,i,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"2",d.start,d.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"3",h.start,h.end,{color:a,width:s,lineWidth:c,lineDash:l})}function Wk(t,e,r,n,i,o={}){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"rect",r),h=t.getSvgNode(d),g=[Math.min(n[0],i[0]),Math.min(n[1],i[1])],p=Math.abs(n[0]-i[0]),v=Math.abs(n[1]-i[1]),y={x:`${g[0]}`,y:`${g[1]}`,width:`${p}`,height:`${v}`,stroke:a,fill:"black","stroke-width":f,"stroke-dasharray":l};if(h)Ca(y,h),t.setNodeTouched(d);else{const m=document.createElementNS(u,"rect");lc(y,m),t.appendNode(m,d)}}const Ede=Object.freeze(Object.defineProperty({__proto__:null,draw:Bk,drawArrow:ey,drawCircle:No,drawEllipse:wde,drawEllipseByCoordinates:w4,drawFan:SC,drawHandle:Qv,drawHandles:ir,drawHeight:Gk,drawLine:vn,drawLinkedTextBox:qi,drawPath:Wc,drawPolyline:Cs,drawRect:P1,drawRectByCoordinates:x4,drawRedactionRect:Wk,drawTextBox:Eu,setAttributesIfNecessary:Ca,setNewAttributesIfValid:lc},Symbol.toStringTag,{value:"Module"}));function zk(t,e){const r=Ce(t),{renderingEngineId:n,viewportId:i}=r,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;c{this._throwIfDestroyed();const e=Array.from(this._viewportElements.values());for(let r=0;r{this._needsRender.add(r)}),this._renderFlaggedViewports()}_setViewportsToBeRenderedNextFrame(e){const r=[...this._viewportElements.values()];e.forEach(n=>{r.indexOf(n)!==-1&&this._needsRender.add(n)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedViewports),this._animationFrameSet=!0)}_triggerRender(e){const r=Ce(e);if(!r)return;if(!Jr(r.renderingEngineId)){console.warn("rendering Engine has been destroyed");return}const i=zk(e,[Dde,bde,Ide]),{renderingEngineId:o,viewportId:a}=r,s={element:e,renderingEngineId:o,viewportId:a};Bk(e,c=>{let l=!1;const f=u=>{if(u.renderAnnotation){const d=u.renderAnnotation(r,c);l=l||d}};i.forEach(f),l&&at(e,N.ANNOTATION_RENDERED,{...s})})}_reset(){window.cancelAnimationFrame(this._animationFrameHandle),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null,this._setAllViewportsToBeRenderedNextFrame()}}const C4=new Ode;function ph(t){C4.renderViewport(t)}function Pe(t){t.length&&t.forEach(e=>{const r=zn(e);if(!r){console.warn(`Viewport not available for ${e}`);return}const{viewport:n}=r;if(!n){console.warn(`Viewport not available for ${e}`);return}const i=n.element;ph(i)})}function $k(t,e){const r=t.length,n=[];for(let i=0;i{const i=n.getCamera();return Math.abs(Et(i.viewPlaneNormal,e.viewPlaneNormal))>r})}function _t(t,e,r=!0){const n=Ce(t),{renderingEngine:i,FrameOfReferenceUID:o}=n;let a=i.getViewports();a=$k(a,o),a=b5(a,e);const s=i.getViewport(n.viewportId);return r&&(a=jk(a,s.getCamera())),a.map(l=>l.id)}const Ade=Object.freeze(Object.defineProperty({__proto__:null,filterViewportsWithFrameOfReferenceUID:$k,filterViewportsWithParallelNormals:jk,filterViewportsWithToolEnabled:b5,getViewportIdsWithToolToRender:_t},Symbol.toStringTag,{value:"Module"})),ty="PlanarFreehandContourSegmentationTool";function Du(t,e){const r=t.length,n=new Array(r);for(let i=0;i{const n=r,i=Du(n.data.contour.polyline,t);return{annotation:n,polyline:i}})}function O5(t,e,r){_1(e,r),Yc(r);const{contour:n}=r.data,i=Du(n.polyline,t);Ds(r,{points:i,closed:n.closed,targetWindingDirection:e.data.contour.windingDirection===Lo.Clockwise?Lo.CounterClockwise:Lo.Clockwise},t);const{element:o}=t;T4(t,[e,r])}function _4(t,e,r,n,i){var m;if(!w5(ty)){console.warn(`${ty} is not registered in cornerstone. Cannot combine polylines.`);return}const o=i[0],a=_u(r,o),s=Hk(t,e),c=new Set(s),l=new Map,f=(w,x)=>{let C=l.get(w);C||(C=[],l.set(w,C)),C.push(x),c.delete(x)},u=[];if(a){const w=E5(r,i);u.push(w),Array.from(c.keys()).forEach(x=>f(w,x))}else D5(r,i).forEach(x=>{u.push(x),Array.from(c.keys()).forEach(C=>{O1(x,C.polyline)&&f(x,C)})});Array.from(l.values()).forEach(w=>w.forEach(x=>y5(x.annotation)));const{element:d}=t,{metadata:h,data:g}=e,{handles:p,segmentation:v}=g,{textBox:y}=p;gn(n.annotationUID),gn(e.annotationUID),Yc(n),Yc(e);for(let w=0;w_1(C,S.annotation))}T4(t,[e,n])}function Kk(t,e,r){const n=t.canvasToWorld(r[0]),i=t.canvasToWorld(r[r.length-1]),o={metadata:{...e.metadata,toolName:ty,originalToolName:e.metadata.originalToolName||e.metadata.toolName},data:{cachedStats:{},handles:{points:[n,i],textBox:e.data.handles.textBox?{...e.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:e.data.spline,segmentation:{...e.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:e.interpolationUID,interpolationCompleted:e.interpolationCompleted};return Ds(o,{points:r,closed:!0,targetWindingDirection:Lo.Clockwise},t),o}function T4(t,e){const{element:r}=t,n=new Set([ty]);e.forEach(i=>{n.add(i.metadata.toolName)});for(const i of n.values())if(w5(i)){const o=_t(r,i);Pe(o)}}function M5(t,e){const r=[],n=new Set,i=new Set;for(let o=0;o[...r]);let e=t[0].map(r=>[...r]);for(let r=1;rny(o.data.contour.polyline,r)),i=e.map(o=>ny(o.data.contour.polyline,r));return M5(n,i)}function ny(t,e){const r=t.length,n=new Array(r);for(let i=0;i[...n]);let r=t.map(n=>[...n]);for(let n=0;nny(o.data.contour.polyline,r)),i=e.map(o=>ny(o.data.contour.polyline,r));return P5(n,i)}const Ude="PlanarFreehandContourSegmentationTool";function qk(t,e,r,n){const i=new Map;return r.forEach(o=>{if(o.length<3)return;const a={annotationUID:Dn(),data:{contour:{closed:!0,polyline:o},segmentation:{segmentationId:e,segmentIndex:n},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:Ude,...t.getViewReference()}};nn(a,t.element);const s=(i==null?void 0:i.get(n))||new Set;s.add(a.annotationUID),i.set(n,s)}),i}function gD(t,e){const r=[],{annotationUIDsMap:n}=t,i=n.get(e);for(const o of i){const a=Br(o),{polyline:s}=a.data.contour;r.push(s)}return r}function Xk(t,e,r,n){if(!e||!e.representationData.Contour)return;const i=e.representationData.Contour,{annotationUIDsMap:o}=i;if(!o||!o.get(r)||!o.get(n))return;const a=gD(i,r),s=gD(i,n),c=a.map(f=>Du(f,t)),l=s.map(f=>Du(f,t));return{polyLinesCanvas1:c,polyLinesCanvas2:l}}function Bde(t,e,r,n,{name:i,segmentIndex:o,color:a}){const{polyLinesCanvas1:s,polyLinesCanvas2:c}=Xk(t,e,r,n)||{};if(!s||c)return;const f=M5(s,c).map(g=>S4(g,t)),u=qk(t,e.segmentationId,f,o),d=e.representationData.Contour,{annotationUIDsMap:h}=d;h&&h.set(o,u.get(o))}function Gde(t,e,r,n,{name:i,segmentIndex:o,color:a}){const{polyLinesCanvas1:s,polyLinesCanvas2:c}=Xk(t,e,r,n)||{};if(!s||c)return;const f=P5(s,c).map(g=>S4(g,t)),u=qk(t,e.segmentationId,f,o),d=e.representationData.Contour,{annotationUIDsMap:h}=d;h&&h.set(o,u.get(o))}function R1(t){var e;return!!((e=t.data)!=null&&e.segmentation)}function Yk(t,e,r){const n=[],i=Tu(e);for(let o=0;oa.isContourHole),o=n.filter(a=>!a.isContourHole);if(i.length>0){const a=i[0];Kde(t,a.targetAnnotation,e),Zk(t,[e,a.targetAnnotation]);return}if(o.length!==0){if(!w5(ry)){console.warn(`${ry} is not registered in cornerstone. Cannot process multiple intersections.`);return}zde(t,e,r,o)}}function zde(t,e,r,n){const{element:i}=t,o=[e],a=[],s=[];n.forEach(({targetAnnotation:d})=>{const h=Hde(t,d);s.push(...h),o.push(d)});const c=r[0];if(n.some(({targetPolyline:d})=>_u(d,c))){let d=r;n.forEach(({targetPolyline:h})=>{d=E5(d,h)}),a.push(d)}else n.forEach(({targetPolyline:d})=>{const h=D5(d,r);a.push(...h)});o.forEach(d=>{gn(d.annotationUID),Yc(d)}),s.forEach(d=>y5(d.annotation));const f=n[0].targetAnnotation,u=[];a.forEach(d=>{if(!d||d.length<3){console.warn("Skipping creation of new annotation due to invalid polyline:",d);return}const h=$de(t,f,d);nn(h,i),Jc(h),tn(h,t.element),u.push(h)}),jde(t,s,u),Zk(t,o)}function $de(t,e,r){const n=t.canvasToWorld(r[0]),i=t.canvasToWorld(r[r.length-1]),o={metadata:{...e.metadata,toolName:ry,originalToolName:e.metadata.originalToolName||e.metadata.toolName},data:{cachedStats:{},handles:{points:[n,i],textBox:e.data.handles.textBox?{...e.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:e.data.spline,segmentation:{...e.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:e.interpolationUID,interpolationCompleted:e.interpolationCompleted};return Ds(o,{points:r,closed:!0,targetWindingDirection:Lo.Clockwise},t),o}function jde(t,e,r){e.forEach(n=>{const i=r.find(o=>{const a=E4(o.data.contour.polyline,t);return O1(a,n.polyline)});i&&_1(i,n.annotation)})}function Hde(t,e){return T1(e).map(r=>{const n=r,i=E4(n.data.contour.polyline,t);return{annotation:n,polyline:i}})}function Kde(t,e,r){_1(e,r),Yc(r);const{contour:n}=r.data,i=E4(n.polyline,t);Ds(r,{points:i,closed:n.closed,targetWindingDirection:e.data.contour.windingDirection===Lo.Clockwise?Lo.CounterClockwise:Lo.Clockwise},t)}function E4(t,e){const r=t.length,n=new Array(r);for(let i=0;i{n.add(i.metadata.toolName)});for(const i of n.values())if(w5(i)){const o=_t(r,i);Pe(o)}}const{isEqual:pD}=Mn;function D4(t){const{metadata:e}=t;return qse().filter(r=>{if(r.FrameOfReferenceUID===e.FrameOfReferenceUID){const n=r.viewport,{viewPlaneNormal:i,viewUp:o}=n.getCamera();return pD(i,e.viewPlaneNormal)&&(!e.viewUp||pD(o,e.viewUp))}}).map(r=>r.viewport)}async function qde(t,e,r,n=!0){const i=typeof t=="string"?Br(t):t,o=typeof e=="string"?Br(e):e;if(!i||!o)throw new Error("Both source and target annotations must be valid");r||(r=Xde(i));const a=Du(i.data.contour.polyline,r),s=Du(o.data.contour.polyline,r),c=I5(a,s);if(!c.hasIntersection){console.warn("No intersection found between the two annotations");return}if(c.isContourHole){if(!n){console.warn("Hole processing is disabled");return}O5(r,o,i)}else _4(r,o,s,i,a)}function Xde(t){const e=D4(t);if(!e.length)throw new Error("No viewport found for the annotation");return e[0]}const Yde=Object.freeze(Object.defineProperty({__proto__:null,addContourSegmentationAnnotation:Jc,addition:Bde,areSameSegment:fk,checkIntersection:I5,combinePolylines:_4,contourSegmentationOperation:qde,convertContourPolylineToCanvasSpace:Du,convertContourPolylineToWorld:S4,convertContourSegmentationAnnotation:l4,createNewAnnotationFromPolyline:Kk,createPolylineHole:O5,findAllIntersectingContours:Yk,getContourHolesData:Hk,isContourSegmentationAnnotation:R1,processMultipleIntersections:Jk,removeContourSegmentationAnnotation:Yc,subtractAnnotationPolylines:Fde,subtractMultiplePolylineSets:Vde,subtractPolylineSets:P5,subtraction:Gde,unifyAnnotationPolylines:kde,unifyMultiplePolylineSets:Nde,unifyPolylineSets:M5,updateViewportsForAnnotations:T4},Symbol.toStringTag,{value:"Module"}));function Jde(t){if(!t)throw new Error(`No contours found for geometryId ${t.id}`);const e=t.id;if(t.type!==cv.CONTOUR)throw new Error(`Geometry type ${t.type} not supported for rendering.`);if(!t.data){console.warn(`No contours found for geometryId ${e}. Skipping render.`);return}}function Zde(t,e,r,n){r.size?t.render():Qde(t,e,n)}function Qde(t,e,r){const{segmentationId:n}=r,i=new Map;e.forEach(o=>{const a=Le.getGeometry(o);if(!a){console.warn(`No geometry found for geometryId ${o}. Skipping render.`);return}const s=a.data.segmentIndex;Jde(a);const c=va.getStyle({viewportId:t.id,segmentationId:n,type:Dt.Contour,segmentIndex:s}),l=a.data,f=t.getCamera().viewPlaneNormal;l.contours.forEach(u=>{const{points:d,color:h,id:g}=u,p=a4(t,d[0],f),v={annotationUID:Dn(),data:{contour:{closed:!0,polyline:d},segmentation:{segmentationId:n,segmentIndex:s,color:h,id:g},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!0,isVisible:!0,metadata:{referencedImageId:p,toolName:"PlanarFreehandContourSegmentationTool",FrameOfReferenceUID:t.getFrameOfReferenceUID(),viewPlaneNormal:t.getCamera().viewPlaneNormal}},y=t.element;nn(v,y),Jc(v)}),c&&i.set(s,c)}),t.render()}function e0e(t,e,r=!1){const n=Ln(e),{annotationUIDsMap:i}=n.representationData.Contour;i.forEach(o=>{o.forEach(a=>{gn(a)})})}function Qk(t){const e=Hue(t);if(e)return e;const r=Ln(t);if(!r)throw new Error(`No segmentation found for segmentationId ${t}`);let n;if(r.representationData.Labelmap)n=t0e(r,t);else if(r.representationData.Contour)n=i0e(r);else if(r.representationData.Surface)n=o0e(r);else throw new Error(`Unsupported segmentation type: ${r.representationData}`);return Kue(t,n),n}function t0e(t,e){const r=t.representationData[Dt.Labelmap],n=new Set;return r.imageIds?r0e(n,r.imageIds):n0e(n,e),Array.from(n).map(Number).sort((i,o)=>i-o)}function n0e(t,e){Le.getVolume(e).voxelManager.forEach(({value:n})=>{n!==0&&t.add(n)})}function r0e(t,e){e.forEach(r=>{Le.getImage(r).voxelManager.getScalarData().forEach(o=>{o!==0&&t.add(o)})})}function i0e(t){const{annotationUIDsMap:e,geometryIds:r}=t.representationData.Contour||{};if(!r)throw new Error(`No geometryIds found for segmentationId ${t.segmentationId}`);const n=new Set([...e.keys()]);return r.forEach(i=>{const o=Le.getGeometry(i);n.add(o.data.segmentIndex)}),Array.from(n).sort((i,o)=>i-o)}function o0e(t){var r;const e=((r=t.representationData.Surface)==null?void 0:r.geometryIds)??[];return Array.from(e.keys()).map(Number).sort((n,i)=>n-i)}const bd=new Map,mD=new Map;function a0e(t,e,r=!1){const n=zn(t);if(!n)return;const{viewport:i}=n;e0e(t,e),r&&i.render()}async function s0e(t,e){var l,f;const{segmentationId:r}=e,n=Ln(r);if(!n)return;let i=n.representationData[Dt.Contour];const o=Gc();if(!i&&((l=Gc())!=null&&l.canComputeRequestedRepresentation(r,Dt.Contour))&&!bd.get(t.id)?(bd.set(t.id,!0),i=await i4(r,Dt.Contour,()=>o.computeContourData(r,{viewport:t}),()=>{}),bd.set(t.id,!1)):!i&&!Gc()&&console.debug(`No contour data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to contour. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`),!i||!((f=i.geometryIds)!=null&&f.length))return;let a=!1;const s=t.getCamera().viewPlaneNormal;i.annotationUIDsMap&&(a=!l0e(i.annotationUIDsMap,s)),i.geometryIds.length>0&&(a=!c0e(i.geometryIds,s));const c=mD.get(t.id)||new Set;if(a&&!bd.get(t.id)&&!c.has(r)&&t.viewportStatus===po.RENDERED){bd.set(t.id,!0);const u=Qk(r),h=(await o.computeSurfaceData(r,{segmentIndices:u,viewport:t})).geometryIds,g=[];for(const m of h.values()){const x=Le.getGeometry(m).data;g.push({points:x.points,polys:x.polys,segmentIndex:x.segmentIndex,id:x.segmentIndex})}const p=await o.clipAndCacheSurfacesForViewport(g,t),v=o.extractContourData(p),y=o.createAndAddContourSegmentationsFromClippedSurfaces(v,t,r);i.annotationUIDsMap=new Map([...i.annotationUIDsMap,...y]),c.add(r),mD.set(t.id,c),bd.set(t.id,!1)}Zde(t,i.geometryIds,i.annotationUIDsMap,e)}function c0e(t,e){var u,d,h;let r=null,n=null;for(const g of t){const p=Le.getGeometry(g);if(!p)continue;const v=p.data;if(((h=(d=(u=v.contours)==null?void 0:u[0])==null?void 0:d.points)==null?void 0:h.length)>=3){r=p,n=v;break}}if(!r||!n)return!1;const o=n.contours[0].points,a=o[0],s=o[1],c=o[2];let l=Rn(Ve(),En(Ve(),s,a),En(Ve(),c,a));l=tr(Ve(),l);const f=Et(l,e);return Math.abs(f)>.9}function l0e(t,e){const r=Array.from(t.values()).flat().map(i=>Array.from(i)).flat(),n=BT(r,3);for(const i of n){const o=Br(i);if(o!=null&&o.metadata){if(!o.metadata.viewPlaneNormal)continue;const a=o.metadata.viewPlaneNormal,s=Math.abs(e[0]*a[0]+e[1]*a[1]+e[2]*a[2]);if(Math.abs(s-1)>.01)return!1}}return!0}const eV={render:s0e,removeRepresentation:a0e};function Vu(t,e){return Qc(t,e)[0]}function Qc(t,e){return Zn.getCurrentLabelmapImageIdsForViewport(t,e)}function u0e(t,e){return Zn.getLabelmapImageIdsForImageId(t,e)}const vD=new Map,f0e=({cfun:t,ofun:e,actor:r})=>{r.getProperty().setRGBTransferFunction(1,t),r.getProperty().setScalarOpacity(1,e)};async function d0e({viewport:t,volumeInputs:e,segmentationId:r}){var E;const n=t.getDefaultActor(),{actor:i}=n,{uid:o,callback:a}=n,s=t.getVolumeId();if((E=vD.get(o))!=null&&E.added)return{uid:o,actor:i};const c=e,l=Le.getVolume(c[0].volumeId);if(!l)throw new Error(`imageVolume with id: ${l.volumeId} does not exist`);const{volumeId:f}=c[0],u=await ZL(f);if(!u)throw new Error(`segImageVolume with id: ${u.volumeId} does not exist`);const h=u.voxelManager.getCompleteScalarDataArray(),{imageData:g}=u,p=Le.getVolume(s),y=p.voxelManager.getCompleteScalarDataArray(),m=2,w=new Float32Array(m*p.voxelManager.getScalarDataLength()),x=g.getDimensions();for(let D=0;Dre);for(const Y of j)for(let re=0;re{Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,T);const b=t.getActor(o),{element:I,id:P}=t;t.removeActors([o]);const M=await aC({volumeId:o,blendMode:js.MAXIMUM_INTENSITY_BLEND,callback:({volumeActor:L})=>{b.callback&&b.callback({volumeActor:L,volumeId:f})}},I,P);t.addActor({actor:M,uid:o}),t.render()}),{uid:o,actor:i}}const{uuidv4:tV}=Mn;async function h0e(t,e,r,n){const i=Ce(t),{renderingEngine:o,viewport:a}=i,{id:s}=a,c=!0,l=!1,f=!0;if(a instanceof Ir){const d=g0e(e,r);Le.getVolume(d)||await p0e(e);let h=(n==null?void 0:n.blendMode)??js.MAXIMUM_INTENSITY_BLEND,g=h===js.LABELMAP_EDGE_PROJECTION_BLEND;if(g){const v=a.getVolumeId(),y=Le.getVolume(v),w=Le.getVolume(d).dimensions,x=y.dimensions;(w[0]!==x[0]||w[1]!==x[1]||w[2]!==x[2])&&(g=!1,h=js.MAXIMUM_INTENSITY_BLEND,console.debug("Dimensions mismatch - falling back to regular volume addition"))}const p=[{volumeId:d,visibility:c,representationUID:`${r}-${Dt.Labelmap}`,useIndependentComponents:g,blendMode:h}];if(!p[0].useIndependentComponents)await Cae(o,p,[s],l,f);else return await d0e({viewport:a,volumeInputs:p,segmentationId:r})}else{const d=Qc(a.id,r).map(h=>({imageId:h,representationUID:`${r}-${Dt.Labelmap}-${h}`}));Sae(o,d,[s])}io(r)}function g0e(t,e){let{volumeId:r}=t;if(!r){r=tV();const n=Ln(e);n.representationData.Labelmap={...n.representationData.Labelmap,volumeId:r},t.volumeId=r,Ta(e)}return r}async function p0e(t){const e=t;if(!(e.imageIds.length>0))throw new Error("cannot create labelmap, no imageIds found for the volume labelmap");return await QL(t.volumeId||tV(),e.imageIds)}function m0e(t,e){const r=Ce(t),{viewport:n}=r;n.removeActors([ofe(n.id,e)])}function ed(t){return Zn.getActiveSegmentation(t)}function v0e(t,e){Zn.setActiveSegmentation(t,e)}function ol(t){return ed(t)}function y0e(t,e){v0e(t,e)}const w0e=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentation:ol,setActiveSegmentation:y0e},Symbol.toStringTag,{value:"Module"}));function ea(t){const e=Ln(t);if(e){const r=Object.keys(e.segments).find(n=>e.segments[n].active);return r?Number(r):void 0}}const o3=255,zg=new Map;let a3=!1;function x0e(t,e,r=!1){const n=zn(t);if(zg.forEach((o,a)=>{a.includes(e)&&zg.delete(a)}),!n)return;const{viewport:i}=n;m0e(i.element,e),r&&i.render()}async function C0e(t,e){var s;const{segmentationId:r,config:n}=e,i=Ln(r);if(!i){console.warn("No segmentation found for segmentationId: ",r);return}let o=i.representationData[Dt.Labelmap],a=Wg(t.id,r);if(!o&&((s=Gc())!=null&&s.canComputeRequestedRepresentation(r,Dt.Labelmap))&&!a3){a3=!0;const c=Gc();if(o=await i4(r,Dt.Labelmap,()=>c.computeLabelmapData(r,{viewport:t}),()=>null,()=>{Zn.processLabelmapRepresentationAddition(t.id,r),setTimeout(()=>{io(r)},0)}),!o)throw new Error(`No labelmap data found for segmentationId ${r}.`);a3=!1}else!o&&!Gc()&&console.debug(`No labelmap data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to labelmap. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(o){if(t instanceof ur)a!=null&&a.length||await wD(t,o,r,n),a=Wg(t.id,r);else{const c=Qc(t.id,r);if(!(c!=null&&c.length))return;a||await wD(t,o,r,n),a=Wg(t.id,r)}if(a!=null&&a.length)for(const c of a)S0e(t.id,c,e)}}function S0e(t,e,r){var C;const{segmentationId:n}=r,{cfun:i,ofun:o}=r.config,{colorLUTIndex:a}=r,s=ol(t),c=(s==null?void 0:s.segmentationId)===n,l=va.getStyle({viewportId:t,type:Dt.Labelmap,segmentationId:n}),f=va.getRenderInactiveSegmentations(t),u=D1(a),d=Math.min(256,u.length),{outlineWidth:h,renderOutline:g,outlineOpacity:p,activeSegmentOutlineWidthDelta:v}=yD(l,c),y=o4(t,{segmentationId:n,type:Dt.Labelmap});for(let S=0;So.getCurrentImageId()===r),!i||!i.length)?void 0:i[0].getImageData()}else if(e.startsWith("volumeId:")){const r=sc(e),n=y1(r);return!n||!n.length?void 0:n[0].getImageData()}else if(e.startsWith("videoId:")){const r=Vr(e),n=Bv(r);return!n||!n.length?void 0:n[0].getImageData()}else throw new Error('getTargetIdImage: targetId must start with "imageId:" or "volumeId:"')}getTargetId(e){var n;const r=(n=e.getViewReferenceId)==null?void 0:n.call(e);if(r)return r;throw new Error("getTargetId: viewport must have a getViewReferenceId method")}undo(){this.doneEditMemo(),Lm.undo()}redo(){Lm.redo()}static createZoomPanMemo(e){const r={pan:e.getPan(),zoom:e.getZoom()},n={restoreMemo:()=>{const i=e.getPan(),o=e.getZoom();e.setZoom(r.zoom),e.setPan(r.pan),e.render(),r.pan=i,r.zoom=o}};return Lm.push(n),n}doneEditMemo(){var e,r;(r=(e=this.memo)==null?void 0:e.commitMemo)!=null&&r.call(e)&&Lm.push(this.memo),this.memo=null}};Zg.defaults={configuration:{strategies:{},defaultStrategy:void 0,activeStrategy:void 0,strategyOptions:{}}};let ai=Zg;ai.toolName="BaseTool";const{isEqual:T0e}=Mn,{EPSILON:E0e}=cd,D0e=1-E0e;function b4(t,e,r){var c;const{viewPlaneNormal:n}=e,i=t.filter(l=>{let f=l.metadata.viewPlaneNormal;if(!l.metadata.referencedImageId&&!f&&l.metadata.FrameOfReferenceUID){for(const d of l.data.handles.points){const h=En(Ve(),d,e.focalPoint),g=Et(h,e.viewPlaneNormal);if(!T0e(g,0))return!1}return l.metadata.viewPlaneNormal=e.viewPlaneNormal,l.metadata.cameraFocalPoint=e.focalPoint,!0}if(!f){const{referencedImageId:d}=l.metadata,{imageOrientationPatient:h}=mt("imagePlaneModule",d),g=bt(h[0],h[1],h[2]),p=bt(h[3],h[4],h[5]);f=Ve(),Rn(f,g,p),l.metadata.viewPlaneNormal=f}const u=Math.abs(Et(n,f))>D0e;return f&&u});if(!i.length)return[];const o=r/2,{focalPoint:a}=e,s=[];for(const l of i){const f=l.data,u=f.handles.points[0]||((c=f.contour)==null?void 0:c.polyline[0]);if(!l.isVisible)continue;const d=Ve();if(!u){s.push(l);continue}En(d,a,u);const h=Et(d,n);Math.abs(h)n.isVisible?n.data.isCanvasAnnotation?!0:t.isReferenceViewable(n.metadata,r):!1)}function rV(t){if(t){if(t.data&&t.highlighted)return ds.Highlighted;if(b1(t.annotationUID))return ds.Selected;if(Zr(t.annotationUID))return ds.Locked;if(t.data&&t.autoGenerated)return ds.AutoGenerated}return ds.Default}function b0e(t,e,r){const n=W0("textBoxFontSize",t,e,r),i=W0("textBoxFontFamily",t,e,r);return`${n}px ${i}`}const I0e=Object.freeze(Object.defineProperty({__proto__:null,getFont:b0e,getState:rV,style:HT},Symbol.toStringTag,{value:"Module"}));class Fu extends ai{constructor(){super(...arguments),this.onImageSpacingCalibrated=e=>{const{element:r,imageId:n}=e.detail,i=Vr(n),o=Es();o.getFramesOfReference().forEach(s=>{const l=o.getAnnotations(s)[this.getToolName()];!l||!l.length||(l.forEach(f=>{var d;if(!((d=f.metadata)!=null&&d.referencedImageId))return;Vr(f.metadata.referencedImageId)===i&&(f.invalidated=!0,f.data.cachedStats={})}),ph(r))})}}filterInteractableAnnotationsForElement(e,r){if(!(r!=null&&r.length))return[];const n=Ce(e),{viewport:i}=n;return L1(i,r)}createAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n,a=Ce(i),{viewport:s}=a,c=s.getCamera(),{viewPlaneNormal:l,viewUp:f,position:u}=c,d=this.getReferencedImageId(s,o,l,f),h=s.getViewReference({points:[o]});return{highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),...h,referencedImageId:d,viewUp:f,cameraPosition:u},data:{cachedStats:{},handles:{points:[],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}}}getReferencedImageId(e,r,n,i){const o=this.getTargetId(e);let a=o.split(/^[a-zA-Z]+:/)[1];if(e instanceof Ir){const s=sc(o),c=Le.getVolume(s);a=qc(c,r,n)}return a}getStyle(e,r,n){return W0(e,r,rV(n),this.mode)}}Fu.toolName="AnnotationDisplayTool";const{DefaultHistoryMemo:O0e}=VT,{PointsManager:M0e}=Mn;class ar extends Fu{static createAnnotation(...e){let r={annotationUID:null,highlighted:!0,invalidated:!0,metadata:{toolName:this.toolName},data:{text:"",handles:{points:new Array,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:""}};for(const n of e)r=Ei(r,n);return r}static createAnnotationForViewport(e,...r){return this.createAnnotation({metadata:e.getViewReference()},...r)}static createAndAddAnnotation(e,...r){const n=this.createAnnotationForViewport(e,...r);nn(n,e.element),tn(n,e.element)}constructor(e,r){var n,i;super(e,r),this.mouseMoveCallback=(o,a)=>{if(!a)return!1;const{element:s,currentPoints:c}=o.detail,l=c.canvas;let f=!1;for(const u of a){if(Zr(u.annotationUID)||!Gr(u.annotationUID))continue;const{data:d}=u,h=d.handles?d.handles.activeHandleIndex:void 0,g=this._imagePointNearToolOrHandle(s,u,l,6),p=g&&!u.highlighted,v=!g&&u.highlighted;p||v?(u.highlighted=!u.highlighted,f=!0):d.handles&&d.handles.activeHandleIndex!==h&&(f=!0)}return f},this.isSuvScaled=ar.isSuvScaled,(n=e.configuration)!=null&&n.getTextLines&&(this.configuration.getTextLines=e.configuration.getTextLines),(i=e.configuration)!=null&&i.statsCalculator&&(this.configuration.statsCalculator=e.configuration.statsCalculator)}getHandleNearImagePoint(e,r,n,i){const o=Ce(e),{viewport:a}=o,{data:s}=r,{isCanvasAnnotation:c}=s,{points:l,textBox:f}=s.handles;if(f){const{worldBoundingBox:u}=f;if(u){const d={topLeft:a.worldToCanvas(u.topLeft),topRight:a.worldToCanvas(u.topRight),bottomLeft:a.worldToCanvas(u.bottomLeft),bottomRight:a.worldToCanvas(u.bottomRight)};if(n[0]>=d.topLeft[0]&&n[0]<=d.bottomRight[0]&&n[1]>=d.topLeft[1]&&n[1]<=d.bottomRight[1])return s.handles.activeHandleIndex=null,f}}for(let u=0;u<(l==null?void 0:l.length);u++){const d=l[u],h=c?d.slice(0,2):a.worldToCanvas(d);if(yr(n,h)this.getStyle(p,n,r),{annotationUID:o}=r,a=Gr(o),s=Zr(o),c=i("lineWidth"),l=i("lineDash"),f=i("angleArcLineDash"),u=i("color"),d=i("markerSize"),h=i("shadow"),g=this.getLinkedTextBoxStyle(n,r);return{visibility:a,locked:s,color:u,lineWidth:c,lineDash:l,lineOpacity:1,fillColor:u,fillOpacity:0,shadow:h,textbox:g,markerSize:d,angleArcLineDash:f}}_imagePointNearToolOrHandle(e,r,n,i){if(this.getHandleNearImagePoint(e,r,n,i)||this.isPointNearTool(e,r,n,i,"mouse"))return!0}static createAnnotationState(e,r){const{data:n,annotationUID:i}=e,o={...n,cachedStats:{}};delete o.contour,delete o.spline;const a={annotationUID:i,data:structuredClone(o),deleting:r},s=n.contour;return s&&(a.data.contour={...s,polyline:null,pointsManager:M0e.create3(s.polyline.length,s.polyline)}),a}static createAnnotationMemo(e,r,n){if(!r)return;const{newAnnotation:i,deleting:o=i?!1:void 0}=n||{},{annotationUID:a}=r,s=ar.createAnnotationState(r,o),c={restoreMemo:()=>{const l=ar.createAnnotationState(r,o),{viewport:f}=Ce(e)||{};if(f==null||f.setViewReference(r.metadata),s.deleting===!0){if(s.deleting=!1,Object.assign(r.data,s.data),r.data.contour){const d=r.data;d.contour.polyline=s.data.contour.pointsManager.points,delete s.data.contour.pointsManager,d.segmentation&&Jc(r)}s.data=l.data,nn(r,e),Ro(r.annotationUID,!0),f==null||f.render();return}if(s.deleting===!1){s.deleting=!0,s.data=l.data,Ro(r.annotationUID),gn(r.annotationUID),f==null||f.render();return}const u=Br(a);if(!u){console.warn("No current annotation");return}Object.assign(u.data,s.data),u.data.contour&&(u.data.contour.polyline=s.data.contour.pointsManager.points),s.data=l.data,u.invalidated=!0,tn(u,e,Ht.History)},id:a,operationType:"annotation"};return O0e.push(c),c}createMemo(e,r,n){this.memo||(this.memo=ar.createAnnotationMemo(e,r,n))}static hydrateBase(e,r,n,i={}){if(!r)return null;const{viewport:o}=r,a=o.getFrameOfReferenceUID(),s=o.getCamera(),c=i.viewplaneNormal??s.viewPlaneNormal,l=i.viewUp??s.viewUp,f=i.toolInstance||new e;let u,d=c,h=l;if(i.referencedImageId)u=i.referencedImageId,d=void 0,h=void 0;else if(o instanceof lr){const g=FT(n[0],o);g!==void 0&&(u=o.getImageIds()[g])}else if(o instanceof Ir)u=f.getReferencedImageId(o,n[0],c,l);else throw new Error("Unsupported viewport type");return{FrameOfReferenceUID:a,referencedImageId:u,viewPlaneNormal:d,viewUp:h,instance:f,viewport:o}}}ar.toolName="AnnotationTool";const{CalibrationTypes:hf}=ja,gf="px",Am="voxels",iV=[1,2,3,4],P0e=["3,3","4,7"],R0e=["4,3","4,7"],_C={0:"px",1:"percent",2:"dB",3:"cm",4:"seconds",5:"hertz",6:"dB/seconds",7:"cm/sec",8:"cm²",9:"cm²/s",12:"degrees"},L0e=.001,Xh="²",ta=(t,e)=>{const{calibration:r,hasPixelSpacing:n}=t;let i=n?"mm":gf;const o=n?"mm³":Am;let a=i+Xh,s=1,c="";if(!r||!r.type&&!r.sequenceOfUltrasoundRegions)return{unit:i,areaUnit:a,scale:s,volumeUnit:o};if(r.type===hf.UNCALIBRATED)return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am};if(r.sequenceOfUltrasoundRegions){let f,u;if(Array.isArray(e)&&e.length===2)[f,u]=e;else if(typeof e=="function"){const y=e();f=y[0],u=y[1]}let d=r.sequenceOfUltrasoundRegions.filter(y=>f[0]>=y.regionLocationMinX0&&f[0]<=y.regionLocationMaxX1&&f[1]>=y.regionLocationMinY0&&f[1]<=y.regionLocationMaxY1&&u[0]>=y.regionLocationMinX0&&u[0]<=y.regionLocationMaxX1&&u[1]>=y.regionLocationMinY0&&u[1]<=y.regionLocationMaxY1);if(!(d!=null&&d.length))return{unit:i,areaUnit:a,scale:s,volumeUnit:o};if(d=d.filter(y=>iV.includes(y.regionDataType)&&P0e.includes(`${y.physicalUnitsXDirection},${y.physicalUnitsYDirection}`)),!d.length)return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am};const h=d[0],g=Math.abs(h.physicalDeltaX),p=Math.abs(h.physicalDeltaY);if($t(g,p,L0e))s=1/g,c="US Region",i=_C[h.physicalUnitsXDirection]||"unknown",a=i+Xh;else return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am}}else r.scale&&(s=r.scale);return[hf.ERMF,hf.USER,hf.ERROR,hf.PROJECTION,hf.CALIBRATED,hf.UNKNOWN].includes(r==null?void 0:r.type)&&(c=r.type),{unit:i+(c?` ${c}`:""),areaUnit:a+(c?` ${c}`:""),scale:s,volumeUnit:o+(c?` ${c}`:"")}},iy=(t,e)=>{const[r]=e,{calibration:n}=t;let i=["raw"],o=[null],a="";if(!n||!n.type&&!n.sequenceOfUltrasoundRegions)return{units:i,values:o};if(n.sequenceOfUltrasoundRegions){const s=n.sequenceOfUltrasoundRegions.filter(p=>iV.includes(p.regionDataType)&&R0e.includes(`${p.physicalUnitsXDirection},${p.physicalUnitsYDirection}`));if(!(s!=null&&s.length))return{units:i,values:o};const c=s.find(p=>r[0]>=p.regionLocationMinX0&&r[0]<=p.regionLocationMaxX1&&r[1]>=p.regionLocationMinY0&&r[1]<=p.regionLocationMaxY1);if(!c)return{units:i,values:o};const{referencePixelX0:l=0,referencePixelY0:f=0}=c,{physicalDeltaX:u,physicalDeltaY:d}=c,h=(r[1]-c.regionLocationMinY0-f)*d,g=(r[0]-c.regionLocationMinX0-l)*u;a="US Region",o=[g,h],i=[_C[c.physicalUnitsXDirection],_C[c.physicalUnitsYDirection]]}return{units:i,values:o,calibrationType:a}},I4=t=>{var e;return((e=t.calibration)==null?void 0:e.aspect)||1};function R5(t,e,r,n){const i=Ve();Rn(i,e,t);const o=bt(...r),a=bt(...n),s=Ve();rr(s,o,a);const c=Po(s);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=Et(s,i)/(c*Po(i)),u=Math.sqrt(1-l*l)*c,d=l*c;return{worldWidth:u,worldHeight:d}}function mh(t,e,r,n){const i=Ve();Rn(i,e,t);const o=bt(...r),a=bt(...n),s=Ve();rr(s,o,a);const c=Po(s);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=Et(s,i)/(c*Po(i)),u=Math.sqrt(1-l*l)*c,d=l*c;return{worldWidth:u,worldHeight:d}}function O4(t,e,r,n,i=.25){const o=M4(t,e,{targetVolumeId:r,stepSize:i});let a;for(const s of o){const c=t.getIntensityFromWorld(s),l=n(c,s);l&&(a=l)}return a}function M4(t,e,{targetVolumeId:r,stepSize:n}){const i=t.getCamera(),{viewPlaneNormal:o}=i,{spacingInNormalDirection:a}=uh(t,i,r),s=a*n||1,c=t.getBounds(),l=[];let f=[...e];for(;xD(f,c);)l.push([...f]),f[0]+=o[0]*s,f[1]+=o[1]*s,f[2]+=o[2]*s;for(f=[...e];xD(f,c);)l.push([...f]),f[0]-=o[0]*s,f[1]-=o[1]*s,f[2]-=o[2]*s;return l}const xD=function(t,e){const[r,n,i,o,a,s]=e,c=10;return t[0]>r+c&&t[0]i+c&&t[1]a+c&&t[2]{const c=[bt(r,n,i),bt(o,n,i),bt(r,a,i),bt(o,a,i),bt(r,n,s),bt(o,n,s),bt(r,a,s),bt(o,a,s)],l=bt(e[0],e[1],e[2]),f=bt(t[0],t[1],t[2]),u=-Et(l,f);let d=null;for(const h of c){const g=Et(l,h)+u;if(d===null)d=Math.sign(g);else if(Math.sign(g)!==d)return!0}return!1},{EPSILON:A0e}=cd,N0e=1-A0e;function L5(t,e){const{viewPlaneNormal:r}=e,n=t.filter(i=>{let o=i.metadata.viewPlaneNormal;if(!o){const{referencedImageId:s}=i.metadata,{imageOrientationPatient:c}=mt("imagePlaneModule",s),l=bt(c[0],c[1],c[2]),f=bt(c[3],c[4],c[5]);o=Ve(),Rn(o,l,f),i.metadata.viewPlaneNormal=o}const a=Math.abs(Et(r,o))>N0e;return o&&a});return n.length?n:[]}const k0e={filterAnnotationsWithinSlice:b4,getWorldWidthAndHeightFromCorners:R5,getWorldWidthAndHeightFromTwoPoints:mh,filterAnnotationsForDisplay:L1,getPointInLineOfSightWithCriteria:O4,isPlaneIntersectingAABB:oV,filterAnnotationsWithinSamePlane:L5,getPointsInLineOfSight:M4},V0e=Object.freeze(Object.defineProperty({__proto__:null,default:k0e,filterAnnotationsForDisplay:L1,filterAnnotationsWithinSamePlane:L5,filterAnnotationsWithinSlice:b4,getPointInLineOfSightWithCriteria:O4,getPointsInLineOfSight:M4,getWorldWidthAndHeightFromCorners:R5,getWorldWidthAndHeightFromTwoPoints:mh,isPlaneIntersectingAABB:oV},Symbol.toStringTag,{value:"Module"}));function _o(t,e,r){let n=!0,i=!0;if(typeof t!="function")throw new TypeError("Expected a function");return r4(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),gh(t,e,{leading:n,trailing:i,maxWait:e})}function F0e(t){var e;return((e=t[0])==null?void 0:e.length)===3}function U0e(t,e){if(!e||e.length===0||e.length===t.length)return t;const r=e[e.length-1]-e[0]+1,n=Yw(e.map(o=>t[o][0])),i=Yw(e.map(o=>t[o][1]));if(F0e(t)){const o=Yw(e.map(a=>t[a][2]));return N9(Hh(n,r),Hh(i,r),Hh(o,r))}else return N9(Hh(n,r),Hh(i,r))}function B0e(t,e){const r=[],[n,i]=e,o=i-n+1,a=Math.floor(o/t);let s=0,c=Math.round((o-1)/(a-1)*s)+n;for(;c<=i;)r.push(c),s++,c=Math.round((o-1)/(a-1)*s)+n;return r}function TC(t,e,r,n){const i=r-e+1,o=Math.floor(n/100*i)??1,a=Math.floor(i/o)??1;if(isNaN(i)||!i||!a||i/a<2)return t;const s=Math.max(0,e),c=Math.min(t.length-1,r),l=t.slice(0,s),f=t.slice(c+1,t.length),u=B0e(a,[s,c]),d=U0e(t,u);return[...l,...d,...f]}function A5(t,e){var n,i;return e!=null&&e.autoGenerated?!1:((n=t==null?void 0:t.smoothing)==null?void 0:n.smoothOnAdd)===!0||((i=t==null?void 0:t.smoothing)==null?void 0:i.smoothOnEdit)===!0}function G0e(t,e){return yo(t,e)<.001}function W0e(t,e){return yo(t,e)===0}function z0e(t,e){for(let r=0;rG0e(c,l)===!1,[o,a]=CD([qd(r,t.length,1),r,t],[qd(n,e.length,1),n,e],i,1),[s]=CD([qd(o,t.length,-1),o,t],[qd(a,e.length,-1),a,e],i,-1);return[o,s]}function N5(t,e,r){const{interpolation:n,smoothing:i}=t,o=e;if(n){const{knotsRatioPercentageOnAdd:a,knotsRatioPercentageOnEdit:s,smoothOnAdd:c=!1,smoothOnEdit:l=!1}=i,f=r?s:a;if(r?l:c){const[d,h]=r?$0e(e,r):[0,e.length-1];return!e[d]||!e[h]?e:TC(e,d,h,f)}}return o}const vh=t=>{if(t.shiftKey)return t.ctrlKey?Oi.ShiftCtrl:t.altKey?Oi.ShiftAlt:t.metaKey?Oi.ShiftMeta:Oi.Shift;if(t.ctrlKey)return t.altKey?Oi.CtrlAlt:t.metaKey?Oi.CtrlMeta:Oi.Ctrl;if(t.altKey)return t.metaKey&&Oi.AltMeta||Oi.Alt;if(t.metaKey)return Oi.Meta};function P4(t,e){const r=t[0],n=t[t.length-1],i=qt();Va(i,n[0]-r[0],n[1]-r[1]),Nc(i,i);const o=qt(),a=qt();Va(o,-i[1],i[0]),Va(a,i[1],-i[0]);const s=[(r[0]+n[0])/2,(r[1]+n[1])/2],c={dist:0,index:null};for(let u=0;uc.dist&&(c.dist=h,c.index=u)}return[t[c.index],s].map(e.canvasToWorld)}function j0e(t,e){const{viewport:r}=t,n=e.data.contour.polyline.map(r.worldToCanvas);return P4(n,r)}const{addCanvasPointsToArray:R4,pointsAreWithinCloseContourProximity:aV,getFirstLineSegmentIntersectionIndexes:sV,getSubPixelSpacingAndXYDirections:H0e}=ku;function K0e(t,e,r){this.isDrawing=!0;const n=t.detail,{currentPoints:i,element:o}=n,a=i.canvas,s=Ce(o),{viewport:c}=s,l=vh(t.detail.event)===this.configuration.contourHoleAdditionModifierKey,{spacing:f,xDir:u,yDir:d}=H0e(c,this.configuration.subPixelResolution)||{};!f||!u||!d||(this.drawData={canvasPoints:[a],polylineIndex:0,contourHoleProcessingEnabled:l,newAnnotation:!0},this.commonData={annotation:e,viewportIdsToRender:r,spacing:f,xDir:u,yDir:d,movingTextBox:!1},Ge.isInteractingWithTool=!0,o.addEventListener(N.MOUSE_UP,this.mouseUpDrawCallback),o.addEventListener(N.MOUSE_DRAG,this.mouseDragDrawCallback),o.addEventListener(N.MOUSE_CLICK,this.mouseUpDrawCallback),o.addEventListener(N.TOUCH_END,this.mouseUpDrawCallback),o.addEventListener(N.TOUCH_DRAG,this.mouseDragDrawCallback),o.addEventListener(N.TOUCH_TAP,this.mouseUpDrawCallback),Ot(o))}function q0e(t){Ge.isInteractingWithTool=!1,t.removeEventListener(N.MOUSE_UP,this.mouseUpDrawCallback),t.removeEventListener(N.MOUSE_DRAG,this.mouseDragDrawCallback),t.removeEventListener(N.MOUSE_CLICK,this.mouseUpDrawCallback),t.removeEventListener(N.TOUCH_END,this.mouseUpDrawCallback),t.removeEventListener(N.TOUCH_DRAG,this.mouseDragDrawCallback),t.removeEventListener(N.TOUCH_TAP,this.mouseUpDrawCallback),zt(t)}function X0e(t){const e=t.detail,{currentPoints:r,element:n}=e,i=r.world,o=r.canvas,a=Ce(n),{viewport:s}=a,{annotation:c,viewportIdsToRender:l,xDir:f,yDir:u,spacing:d,movingTextBox:h}=this.commonData,{polylineIndex:g,canvasPoints:p,newAnnotation:v}=this.drawData;this.createMemo(n,c,{newAnnotation:v});const y=p[p.length-1],m=s.canvasToWorld(y),w=Ve();rr(w,i,m);const x=Math.abs(Et(w,f)),C=Math.abs(Et(w,u));if(!(x<=d[0]&&C<=d[1])){if(h){this.isDrawing=!1;const{deltaPoints:S}=e,_=S.world,{textBox:T}=c.data.handles,{worldPosition:E}=T;E[0]+=_[0],E[1]+=_[1],E[2]+=_[2],T.hasMoved=!0}else{const S=this.findCrossingIndexDuringCreate(t);if(S!==void 0)this.applyCreateOnCross(t,S);else{const _=R4(n,p,o,this.commonData);this.drawData.polylineIndex=g+_}c.invalidated=!0}Pe(l),c.invalidated&&tn(c,n,Ht.HandlesUpdated)}}function Y0e(t){const{allowOpenContours:e}=this.configuration,{canvasPoints:r,contourHoleProcessingEnabled:n}=this.drawData,i=r[0],o=r[r.length-1],a=t.detail,{element:s}=a;this.doneEditMemo(),this.drawData.newAnnotation=!1,e&&!aV(i,o,this.configuration.closeContourProximity)?this.completeDrawOpenContour(s,{contourHoleProcessingEnabled:n}):this.completeDrawClosedContour(s,{contourHoleProcessingEnabled:n})}function J0e(t,e){this.removeCrossedLinesOnCompleteDraw();const{canvasPoints:r}=this.drawData,{contourHoleProcessingEnabled:n,minPointsToSave:i}=e??{};if(i&&r.length=2)if(c.length>this.configuration.checkCanvasEditFallbackProximity){const u=c[0],d=[];for(let p=0;pp.distance-v.distance);const h=[d[0],d[1]],g=Math.min(h[0].index,h[1].index);this.editData.startCrossingIndex=g}else{const u=qt();Wr(u,c[1],c[0]),Nc(u,u);const d=6,h=[c[0][0]-u[0]*d,c[0][1]-u[1]*d],g=td(l,h,c[0],e);if(g){const p=[h];ahe(n,p,c[0],this.commonData),c.unshift(...p),this.removePointsUpUntilFirstCrossing(e),this.editData.editIndex=c.length-1,this.editData.startCrossingIndex=g[0]}}}function che(t){const{editCanvasPoints:e,prevCanvasPoints:r}=this.editData;let n=0;for(let i=0;i0;n--){const i=[r[n],r[n-1]],o=!!td(e,i[0],i[1],t);if(r.pop(),o)break}}function fhe(){const{editCanvasPoints:t,prevCanvasPoints:e,startCrossingIndex:r}=this.editData;if(r===void 0)return;const n=t[t.length-1],i=[];for(let a=0;aa.distance-s.distance);const o=t.slice(0,-1);for(let a=0;a1&&this.checkForFirstCrossing(t,!0),this.editData.snapIndex=this.findSnapIndex(),this.editData.snapIndex===-1){this.finishEditAndStartNewEdit(t);return}this.editData.fusedCanvasPoints=this.fuseEditPointsWithClosedContour(t),g!==void 0&&this.checkForSecondCrossing(t,!0)&&(this.removePointsAfterSecondCrossing(!0),this.finishEditAndStartNewEdit(t)),Pe(c)}function yhe(t){const e=t.detail,{element:r}=e,n=Ce(r),{viewport:i,renderingEngine:o}=n,{annotation:a,viewportIdsToRender:s}=this.commonData,{fusedCanvasPoints:c,editCanvasPoints:l}=this.editData;Ds(a,{points:c,closed:!0,targetWindingDirection:Lo.Clockwise},i),a.autoGenerated&&(a.autoGenerated=!1),tn(a,r);const f=l.pop();this.editData={prevCanvasPoints:c,editCanvasPoints:[f],startCrossingIndex:void 0,editIndex:0,snapIndex:void 0,annotation:a},Pe(s)}function whe(t){const{prevCanvasPoints:e,editCanvasPoints:r,startCrossingIndex:n,snapIndex:i}=this.editData;if(n===void 0||i===void 0)return;const o=t.detail,{element:a}=o,s=[...r];cV(a,s,e[i],this.commonData),s.length>r.length&&s.pop();let c,l;n>i?(c=i,l=n):(c=n,l=i);const f=yr(e[c],s[0]),u=yr(e[c],s[s.length-1]),d=yr(e[l],s[0]),h=yr(e[l],s[s.length-1]),g=[];for(let C=0;C=0;C--){const S=s[C];g.push([S[0],S[1]])}for(let C=l;C=0;C--){const S=s[C];y.push([S[0],S[1]])}const m=SD(g),w=SD(y);return m>w?g:y}function xhe(t){const e=t.detail,{element:r}=e;this.completeClosedContourEdit(r)}function Che(t){var s;const e=Ce(t),{viewport:r}=e,{annotation:n,viewportIdsToRender:i}=this.commonData;this.doneEditMemo();const{fusedCanvasPoints:o,prevCanvasPoints:a}=this.editData;if(o){const c=A5(this.configuration,n)?N5(this.configuration,o,a):o,l=((s=this.configuration)==null?void 0:s.decimate)||{};Ds(n,{points:c,closed:!0,targetWindingDirection:Lo.Clockwise},r,{decimate:{enabled:!!l.enabled,epsilon:l.epsilon}}),n.autoGenerated&&(n.autoGenerated=!1),tn(n,t)}this.isEditingClosed=!1,this.editData=void 0,this.commonData=void 0,Pe(i),this.deactivateClosedContourEdit(t)}function She(t){this.completeClosedContourEdit(t)}function _he(t){t.activateClosedContourEdit=phe.bind(t),t.deactivateClosedContourEdit=mhe.bind(t),t.mouseDragClosedContourEditCallback=vhe.bind(t),t.mouseUpClosedContourEditCallback=xhe.bind(t),t.finishEditAndStartNewEdit=yhe.bind(t),t.fuseEditPointsWithClosedContour=whe.bind(t),t.cancelClosedContourEdit=She.bind(t),t.completeClosedContourEdit=Che.bind(t)}const{addCanvasPointsToArray:lV,getSubPixelSpacingAndXYDirections:The}=ku;function Ehe(t,e,r){this.isEditingOpen=!0;const n=t.detail,{currentPoints:i,element:o}=n,a=i.canvas,s=Ce(o),{viewport:c}=s;this.doneEditMemo();const l=e.data.contour.polyline.map(c.worldToCanvas),{spacing:f,xDir:u,yDir:d}=The(c,this.configuration.subPixelResolution);this.editData={prevCanvasPoints:l,editCanvasPoints:[a],startCrossingIndex:void 0,editIndex:0},this.commonData={annotation:e,viewportIdsToRender:r,spacing:f,xDir:u,yDir:d,movingTextBox:!1},Ge.isInteractingWithTool=!0,o.addEventListener(N.MOUSE_UP,this.mouseUpOpenContourEditCallback),o.addEventListener(N.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),o.addEventListener(N.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),o.addEventListener(N.TOUCH_END,this.mouseUpOpenContourEditCallback),o.addEventListener(N.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),o.addEventListener(N.TOUCH_TAP,this.mouseUpOpenContourEditCallback),Ot(o)}function Dhe(t){Ge.isInteractingWithTool=!1,t.removeEventListener(N.MOUSE_UP,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),t.removeEventListener(N.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.TOUCH_END,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),t.removeEventListener(N.TOUCH_TAP,this.mouseUpOpenContourEditCallback),zt(t)}function bhe(t){const e=t.detail,{currentPoints:r,element:n}=e,i=r.world,o=r.canvas,a=Ce(n),{viewport:s}=a,{viewportIdsToRender:c,xDir:l,yDir:f,spacing:u}=this.commonData,{editIndex:d,editCanvasPoints:h,startCrossingIndex:g}=this.editData,p=h[h.length-1],v=s.canvasToWorld(p),y=Ve();this.createMemo(n,this.commonData.annotation),rr(y,i,v);const m=Math.abs(Et(y,l)),w=Math.abs(Et(y,f));if(m<=u[0]&&w<=u[1])return;g!==void 0&&this.checkAndRemoveCrossesOnEditLine(t);const x=lV(n,h,o,this.commonData),C=d+x;this.editData.editIndex=C,g===void 0&&h.length>1&&this.checkForFirstCrossing(t,!1),this.editData.snapIndex=this.findSnapIndex(),this.editData.fusedCanvasPoints=this.fuseEditPointsWithOpenContour(t),g!==void 0&&this.checkForSecondCrossing(t,!1)?(this.removePointsAfterSecondCrossing(!1),this.finishEditOpenOnSecondCrossing(t)):this.checkIfShouldOverwriteAnEnd(t)&&this.openContourEditOverwriteEnd(t),Pe(c)}function Ihe(t){const e=t.detail,{element:r}=e,n=Ce(r),{viewport:i}=n,{annotation:o,viewportIdsToRender:a}=this.commonData,s=this.fuseEditPointsForOpenContourEndEdit();Ds(o,{points:s,closed:!1},i);const c=o.data.contour.polyline;o.data.handles.points=[c[0],c[c.length-1]],o.data.handles.activeHandleIndex=1,tn(o,r),this.isEditingOpen=!1,this.editData=void 0,this.commonData=void 0,this.doneEditMemo(),this.deactivateOpenContourEdit(r),this.activateOpenContourEndEdit(t,o,a,null)}function Ohe(t){const e=t.detail,{currentPoints:r,lastPoints:n}=e,i=r.canvas,o=n.canvas,{snapIndex:a,prevCanvasPoints:s,startCrossingIndex:c}=this.editData;if(c===void 0||a===void 0)return!1;if(a===-1)return!0;if(a!==0&&a!==s.length-1)return!1;const l=i,f=o,u=s[a],d=qt(),h=qt();Va(d,l[0]-f[0],l[1]-f[1]),Va(h,l[0]-u[0],l[1]-u[1]);const g=k_(d,h),p=Math.sqrt(d[0]*d[0]+d[1]*d[1]),v=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(g/(p*v))=n;s--){const c=e[s];i.push([c[0],c[1]])}else for(let s=0;s=0;s--){const c=r[s];i.push([c[0],c[1]])}return i}function Phe(t){const{prevCanvasPoints:e,editCanvasPoints:r,startCrossingIndex:n,snapIndex:i}=this.editData;if(n===void 0||i===void 0)return;const o=t.detail,{element:a}=o,s=[...r];lV(a,s,e[i],this.commonData),s.length>r.length&&s.pop();let c,l;n>i?(c=i,l=n):(c=n,l=i);const f=yr(e[c],s[0]),u=yr(e[c],s[s.length-1]),d=yr(e[l],s[0]),h=yr(e[l],s[s.length-1]),g=[];for(let y=0;y=0;y--){const m=s[y];g.push([m[0],m[1]])}for(let y=l;yBr(r).data.contour.polyline)}function A1(t,e){const r=uV(t),n=[];return r.forEach(i=>{const o=i.length,a=new Array(o);for(let s=0;sn.worldToCanvas(l)),a=A1(r,n),s=[o,...a];Wc(e,r.annotationUID,"1",s,i)}function jhe(t,e,r){var c;const{viewport:n}=t,i=this._getRenderingOptions(t,r),o=r.data.contour.polyline.map(l=>n.worldToCanvas(l));Cs(e,r.annotationUID,"1",o,i);const s=r.data.handles.activeHandleIndex;if(((c=this.configuration.alwaysRenderOpenContourHandles)==null?void 0:c.enabled)===!0){const l=this.configuration.alwaysRenderOpenContourHandles.radius,f="0",u=[o[0],o[o.length-1]];s===0?u.shift():s===1&&u.pop(),ir(e,r.annotationUID,f,u,{color:i.color,handleRadius:l})}if(s!==null){const l="1",f=s===0?0:o.length-1,u=o[f];ir(e,r.annotationUID,l,[u],{color:i.color})}}function Hhe(t,e,r){const{viewport:n}=t,{openUShapeContourVectorToPeak:i}=r.data,{polyline:o}=r.data.contour;if(this.renderOpenContour(t,e,r),!i)return;const a=n.worldToCanvas(o[0]),s=n.worldToCanvas(o[o.length-1]),c=[n.worldToCanvas(i[0]),n.worldToCanvas(i[1])],l=this._getRenderingOptions(t,r);Cs(e,r.annotationUID,"first-to-last",[a,s],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"}),Cs(e,r.annotationUID,"midpoint-to-open-contour",[c[0],c[1]],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"})}function Khe(t,e,r){const n=this._getRenderingOptions(t,r),{allowOpenContours:i}=this.configuration,{canvasPoints:o}=this.drawData;if(n.closePath=!1,Cs(e,r.annotationUID,"1",o,n),i){const a=o[0],s=o[o.length-1];Bhe(a,s,this.configuration.closeContourProximity)?Cs(e,r.annotationUID,"2",[s,a],n):ir(e,r.annotationUID,"0",[a],{color:n.color,handleRadius:2})}}function qhe(t,e,r){const{viewport:n}=t,{fusedCanvasPoints:i}=this.editData;if(i===void 0){this.renderClosedContour(t,e,r);return}const o=A1(r,n),a=[i,...o],s=this._getRenderingOptions(t,r),c="preview-1";r.parentAnnotationUID&&s.fillOpacity&&(s.fillOpacity=0),Wc(e,r.annotationUID,c,a,s)}function Xhe(t,e,r){const{fusedCanvasPoints:n}=this.editData;if(n===void 0){this.renderOpenContour(t,e,r);return}const i=this._getRenderingOptions(t,r);Cs(e,r.annotationUID,"preview-1",n,i)}function Yhe(t,e,r){if(r.parentAnnotationUID)return;const{viewport:n}=t,i=this._getRenderingOptions(t,r),o=r.data.contour.polyline.map(g=>n.worldToCanvas(g)),a=A1(r,n),s="1",c=o[0],l=6,f=100,u=[];for(let g=0;g0}else if(t instanceof lr){const{preScale:r}=t.getImageData()||{};return!!(r!=null&&r.scaled)}else return!1}function EC(t,e){let r=0;for(let n=0;nthis.moveAnnotation(i,r))}updateContourPolyline(e,r,n,i){var a;const o=((a=this.configuration)==null?void 0:a.decimate)||{};Ds(e,r,n,{decimate:{enabled:!!o.enabled,epsilon:o.epsilon},updateWindingDirection:i==null?void 0:i.updateWindingDirection})}getPolylinePoints(e){var r;return((r=e.data.contour)==null?void 0:r.polyline)??e.data.polyline}renderAnnotationInstance(e){const{enabledElement:r,annotationStyle:n,svgDrawingHelper:i}=e,o=e.annotation;if(o.parentAnnotationUID)return;const{annotationUID:a}=o,{viewport:s}=r,{worldToCanvas:c}=s,l=this.getPolylinePoints(o).map(y=>c(y)),{lineWidth:f,lineDash:u,color:d,fillColor:h,fillOpacity:g}=n,p=A1(o,s),v=[l,...p];return Wc(i,a,"contourPolyline",v,{color:d,lineDash:u,lineWidth:Math.max(.1,f),fillColor:h,fillOpacity:g}),!0}}class tge{constructor(){this.annotationUIDs=new Set,this._isVisible=!0,this.visibleFilter=this.unboundVisibleFilter.bind(this)}unboundVisibleFilter(e){return!this._isVisible||!this.annotationUIDs.has(e)}has(e){return this.annotationUIDs.has(e)}setVisible(e=!0,r,n){this._isVisible!==e&&(this._isVisible=e,this.annotationUIDs.forEach(i=>{const o=Br(i);if(!o){this.annotationUIDs.delete(i);return}if(o.isVisible===e||!e&&(n==null?void 0:n(i))===!1)return;o.isVisible=e;const a={...r,annotation:o};at(Ke,N.ANNOTATION_MODIFIED,a)}))}get isVisible(){return this._isVisible}findNearby(e,r){const n=[...this.annotationUIDs];if(n.length===0)return null;if(!e)return n[r===1?0:n.length-1];const i=n.indexOf(e);return i===-1||i+r<0||i+r>=n.length?null:n[i+r]}add(...e){e.forEach(r=>this.annotationUIDs.add(r))}remove(...e){e.forEach(r=>this.annotationUIDs.delete(r))}clear(){this.annotationUIDs.clear()}}const Rr={...cue,...iue,resetAnnotationManager:kfe},nge=Object.freeze(Object.defineProperty({__proto__:null,AnnotationGroup:tge,FrameOfReferenceSpecificAnnotationManager:dk,config:I0e,locking:Efe,selection:Ofe,state:Rr,visibility:Afe},Symbol.toStringTag,{value:"Module"})),_D="PlanarFreehandContourSegmentationTool";function L4(t,e=[]){const{viewport:r,sliceData:n,annotation:i}=t,o=new Map,{toolName:a,originalToolName:s}=i.metadata,c=s||a,l=(un(c,r.element)||[]).filter(f=>!f.metadata.originalToolName||f.metadata.originalToolName===c);if(c!==_D){const f=un(_D,r.element);f!=null&&f.length&&f.forEach(u=>{const{metadata:d}=u;d.originalToolName===c&&d.originalToolName!==d.toolName&&l.push(u)})}if(!(l!=null&&l.length))return o;for(let f=0;fh.metadata.sliceIndex===f);if(!(u!=null&&u.length))continue;const d=u.filter(h=>e.every(g=>{const p=g.parentKey?g.parentKey(h):h,v=p==null?void 0:p[g.key];return Array.isArray(v)?v.every((y,m)=>y===g.value[m]):v===g.value}));d.length&&o.set(f,d)}return o}function rge(t,e){const r=L4(t,e),n=[];if(!(r!=null&&r.size))return n;for(const i of r.values())i.forEach(o=>{n.push(o)});return n}function fV(t,e,r){const n=Ei({data:{},metadata:{}},r);return Object.assign(n,{highlighted:!1,invalidated:!0,autoGenerated:!0,annotationUID:void 0,cachedStats:{},childAnnotationUIDs:[],parentAnnotationUID:void 0}),Object.assign(n.data,{handles:{points:e.points||e||[],interpolationSources:e.sources,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},contour:{...r.data.contour,polyline:t}}),n}function ige(t,e){const r=L4(e,[{key:"interpolationUID",value:e.interpolationUID}]),n=oge(r);if(!n){console.warn("No annotations found to interpolate",r);return}const i=age(r,t.annotationUID),o=[];for(let a=n[0]+1;a=e[0];o--){const a=r.get(o);if(a!=null&&a.length){if(a[0].autoGenerated)continue;a.length>1&&(i=!1),n.push(o);break}}if(!(!i||!n.length)){for(let o=t+1;o<=e[1];o++){const a=r.get(o);if(a!=null&&a.length){if(a[0].autoGenerated)continue;a.length>1&&(i=!1),n.push(o);break}}if(!(!i||n.length<2))return n}}const{PointsManager:TD}=Mn;function uge(t,e=12){const r=TD.create3(e);r.sources=[];const{sources:n}=r,{length:i,sources:o=[]}=t,a=5;if(in.push(TD.create3(e)));const c=fge(t,a),l=dge(c,e),f=[];if((l==null?void 0:l.length)>2){let u=-1;const d=s/3;l.forEach(p=>{const[v,,y]=p,m=Math.ceil((v+y)/2);y-u2*d?(Id(f,u,v,s,i),u=Id(f,v,m,s,i)):u=Id(f,u,m,s,i),y-u>d&&(u=Id(f,u,y,s,i)))});const h=f[0];DC(h+i-u,i)>2*d&&Id(f,u,h-d,s,i)}else{const u=Math.floor(i/e);Id(f,-1,i-u,u,i)}return f.forEach(u=>{const d=t.getPointArray(u);r.push(d),o.forEach((h,g)=>n[g].push(h.getPoint(u)))}),r}function fge(t,e=6){const{length:r}=t,n=Ve(),i=Ve(),o=new Float32Array(r);for(let a=0;a{try{e&&(r.isInterpolationUpdate=!0,r.autoGenerated=!1),pge(t)}finally{e&&(r.autoGenerated=!0)}})}function pge(t){const{annotation:e}=t;gge(e);const{interpolationData:r,interpolationList:n}=ige(e,t)||{};if(!r||!n)return;const i={toolName:e.metadata.toolName,toolType:e.metadata.toolName,viewport:t.viewport};for(let l=0;ls.x.length,n)})}function vge(t,e,r,n,i,o,a){const[s,c]=n,l=(r-s)/(c-s),f=i.get(s)[0],u=i.get(c)[0],d=xge(t,e,l,o),h=l>.5?u:f,g=uge(d);i.has(r)?wge(d,g,r,h,a):yge(d,g,r,h,a)}function yge(t,e,r,n,i){var f;const o=t.points,{viewport:a}=i,s=fV(o,e,n),c=a.getViewReference({sliceIndex:r});if(!c)throw new Error(`Can't find slice ${r}`);Object.assign(s.metadata,c),Rr.addAnnotation(s,a.element),(f=n.onInterpolationComplete)==null||f.call(n,s,n);const{parentAnnotationUID:l}=n;if(l){const u=Rr.getAnnotation(l),d=dV(u,r,i);O5(a,d,s)}}function dV(t,e,r){const{viewport:n}=r,i=Rr.getAnnotations(t.metadata.toolName,n.element);for(let o=0;o!f.autoGenerated)||(s=o||s===n||c.forEach(l=>{l.autoGenerated&&(Rr.removeAnnotation(l.annotationUID),a.push(l))});if(a.length){const s={annotations:a,element:t.viewport.element,viewportId:t.viewport.id,renderingEngineId:t.viewport.getRenderingEngine().id};at(t.viewport.element,N.INTERPOLATED_ANNOTATIONS_REMOVED,s)}if(i>=0&&o{var h;const r=e.detail.annotation;if(!(r!=null&&r.metadata))return;const{toolName:n,originalToolName:i}=r.metadata;if(!La.toolNames.includes(n)&&!La.toolNames.includes(i))return;const o=N2(r);if(!o){console.warn("Unable to find viewport for",r);return}const a=s3(o),s={viewport:o,sliceData:a,annotation:r,interpolationUID:r.interpolationUID},c=!!r.interpolationUID;if(r.autoGenerated=!1,c){LD(s),A2(s);return}const l=[{key:"segmentIndex",value:r.data.segmentation.segmentIndex,parentKey:g=>g.data.segmentation},{key:"viewPlaneNormal",value:r.metadata.viewPlaneNormal,parentKey:g=>g.metadata},{key:"viewUp",value:r.metadata.viewUp,parentKey:g=>g.metadata}];let f=rge(s,l);const{sliceIndex:u}=r.metadata,d=new Set;f.forEach(g=>{if(g.interpolationCompleted||g.metadata.sliceIndex===u){const{interpolationUID:p}=g;d.add(p)}}),f=f.filter(g=>!d.has(g.interpolationUID)),r.interpolationUID=((h=f[0])==null?void 0:h.interpolationUID)||Tge(),s.interpolationUID=r.interpolationUID,A2(s)},La.handleAnnotationUpdate=e=>{const r=e.detail.annotation,{changeType:n=Ht.HandlesUpdated}=e.detail;if(!(r!=null&&r.metadata))return;const{toolName:i,originalToolName:o}=r.metadata;if(!La.toolNames.includes(i)&&!La.toolNames.includes(o)||!Ege.includes(n))return;const a=N2(r);if(!a){console.warn("Unable to find matching viewport for annotation interpolation",r);return}r.autoGenerated&&(Jc(r),r.autoGenerated=!1);const s=s3(a),c={viewport:a,sliceData:s,annotation:r,interpolationUID:r.interpolationUID,isInterpolationUpdate:n===Ht.InterpolationUpdated};A2(c)},La.handleAnnotationDelete=e=>{const r=e.detail.annotation;if(!(r!=null&&r.metadata))return;const{toolName:n}=r.metadata;if(!La.toolNames.includes(n)||r.autoGenerated)return;const i=N2(r);if(!i){console.warn("No viewport, can't delete interpolated results",r);return}const o=s3(i),a={viewport:i,sliceData:o,annotation:r,interpolationUID:r.interpolationUID};r.autoGenerated=!1,LD(a)};let Ys=La;function s3(t){return{numberOfSlices:t.getNumberOfSlices(),imageIndex:t.getCurrentImageIdIndex()}}function hV(t){t.forEach(e=>{const r=Kr(e);if(!r){console.warn(`ToolGroup not available for ${e}`);return}r.getViewportsInfo().forEach(i=>{const{renderingEngineId:o,viewportId:a}=i,s=Jr(o);if(!s){console.warn(`RenderingEngine not available for ${o}`);return}const c=s.getViewport(a);ph(c.element)})})}function yh(t){const n=Zn.getState().viewportSegRepresentations;return Object.entries(n).filter(([,o])=>o.some(a=>a.segmentationId===t)).map(([o])=>o)}function Dge(t,e){const r=Ln(t);if(!r)throw new Error(`No segmentation state found for ${t}`);const{segments:n}=r;return n[e].locked}function bge(t,e,r=!0){const n=Ln(t);if(!n)throw new Error(`No segmentation state found for ${t}`);const{segments:i}=n;i[e].locked=r,Ta(t)}function dd(t){const e=Ln(t);if(!e)throw new Error(`No segmentation state found for ${t}`);const{segments:r}=e;return Object.keys(r).filter(i=>r[i].locked).map(i=>parseInt(i))}const Ige=Object.freeze(Object.defineProperty({__proto__:null,getLockedSegmentIndices:dd,isSegmentIndexLocked:Dge,setSegmentIndexLocked:bge},Symbol.toStringTag,{value:"Module"}));function gV(){return Zn.getNextColorLUTIndex()}const oy=[[0,0,0,0],[221,84,84,255],[77,228,121,255],[166,70,235,255],[189,180,116,255],[109,182,196,255],[204,101,157,255],[123,211,94,255],[93,87,218,255],[225,128,80,255],[73,232,172,255],[181,119,186,255],[176,193,112,255],[105,153,200,255],[208,97,120,255],[90,215,101,255],[135,83,222,255],[229,178,76,255],[122,183,181,255],[190,115,171,255],[149,197,108,255],[100,118,205,255],[212,108,93,255],[86,219,141,255],[183,79,226,255],[233,233,72,255],[118,167,187,255],[194,111,146,255],[116,201,104,255],[115,96,209,255],[216,147,89,255],[82,223,188,255],[230,75,224,255],[163,184,121,255],[114,143,191,255],[198,107,114,255],[99,206,122,255],[153,92,213,255],[220,192,85,255],[78,215,227,255],[234,71,173,255],[141,188,117,255],[110,113,195,255],[202,128,103,255],[95,210,157,255],[195,88,217,255],[206,224,81,255],[74,166,231,255],[185,120,139,255],[113,192,113,255],[133,106,199,255],[207,162,98,255],[91,214,198,255],[221,84,198,255],[159,228,77,255],[70,111,235,255],[189,119,116,255],[109,196,138,255],[165,101,204,255],[211,201,94,255],[87,191,218,255],[225,80,153,255],[106,232,73,255],[124,119,186,255],[193,142,112,255],[105,200,168,255],[203,97,208,255],[184,215,90,255],[83,147,222,255],[229,76,101,255],[122,183,130,255],[146,115,190,255],[197,171,108,255],[100,205,205,255],[212,93,177,255],[141,219,86,255],[79,97,226,255],[233,99,72,255],[118,187,150,255],[173,111,194,255],[197,201,104,255],[96,171,209,255],[216,89,137,255],[94,223,82,255],[107,75,230,255],[184,153,121,255],[114,191,175,255],[198,107,191,255],[166,206,99,255],[92,132,213,255],[220,85,91,255],[78,227,115,255],[159,71,234,255],[188,176,117,255],[110,185,195,255],[202,103,161,255],[129,210,95,255],[88,88,217,255],[224,123,81,255],[74,231,166,255],[177,120,185,255],[179,192,113,255],[106,156,199,255],[207,98,125,255],[91,214,96,255],[130,84,221,255],[228,171,77,255],[70,235,221,255],[189,116,174,255],[153,196,109,255],[101,123,204,255],[211,104,94,255],[87,218,136,255],[177,80,225,255],[232,225,73,255],[119,169,186,255],[193,112,149,255],[121,200,105,255],[111,97,208,255],[215,142,90,255],[83,222,181,255],[229,76,229,255],[165,183,122,255],[115,146,190,255],[197,108,119,255],[100,205,118,255],[148,93,212,255],[219,186,86,255],[79,220,226,255],[233,72,179,255],[144,187,118,255],[111,118,194,255],[201,124,104,255],[96,209,153,255],[189,89,216,255],[211,223,82,255],[75,172,230,255],[184,121,142,255],[117,191,114,255],[130,107,198,255],[206,157,99,255],[92,213,193,255],[220,85,203,255],[165,227,78,255],[71,118,234,255],[188,117,117,255],[110,195,135,255],[161,103,202,255],[210,195,95,255],[88,195,217,255],[224,81,158,255],[113,231,74,255],[123,120,185,255],[192,139,113,255],[106,199,164,255],[198,98,207,255],[188,214,91,255],[84,153,221,255],[228,77,108,255],[70,235,84,255],[143,116,189,255],[196,167,109,255],[101,204,199,255],[211,94,182,255],[147,218,87,255],[80,104,225,255],[232,93,73,255],[119,186,147,255],[170,112,193,255],[200,200,105,255],[97,175,208,255],[215,90,142,255],[100,222,83,255],[101,76,229,255],[183,150,122,255],[115,190,171,255],[197,108,194,255],[170,205,100,255],[93,138,212,255],[219,86,97,255],[79,226,110,255],[153,72,233,255],[187,173,118,255],[111,187,194,255],[201,104,165,255],[134,209,96,255],[89,95,216,255],[223,117,82,255],[75,230,159,255],[174,121,184,255],[182,191,114,255],[107,160,198,255],[206,99,130,255],[92,213,92,255],[124,85,220,255],[227,165,78,255],[71,234,214,255],[188,117,176,255],[156,195,110,255],[103,128,202,255],[210,100,95,255],[88,217,131,255],[170,81,224,255],[231,218,74,255],[120,172,185,255],[192,113,153,255],[125,199,106,255],[107,98,207,255],[214,137,91,255],[84,221,175,255],[222,77,228,255],[194,235,70,255],[116,149,189,255],[196,109,123,255],[101,204,114,255],[143,94,211,255],[218,180,87,255],[80,225,225,255],[232,73,186,255],[147,186,119,255],[112,122,193,255],[200,121,105,255],[97,208,148,255],[184,90,215,255],[216,222,83,255],[76,178,229,255],[183,122,145,255],[121,190,115,255],[126,108,197,255],[205,153,100,255],[93,212,187,255],[219,86,208,255],[171,226,79,255],[72,126,233,255],[187,118,121,255],[111,194,132,255],[157,104,201,255],[209,190,96,255],[89,200,216,255],[223,82,164,255],[120,230,75,255],[121,121,184,255],[191,136,114,255],[107,198,160,255],[192,99,206,255],[193,213,92,255],[85,158,220,255],[227,78,115,255],[71,234,78,255],[141,117,188,255],[195,163,110,255],[103,202,194,255],[210,95,186,255],[153,217,88,255],[81,111,224,255]];function $g(t,e){const r=Zn,n=e??gV();let i=[...t];if($t(i[0],[0,0,0,0])||(console.warn("addColorLUT: [0, 0, 0, 0] color is not provided for the background color (segmentIndex =0), automatically adding it"),i=[[0,0,0,0],...i]),i=i.map(o=>o.length===3?[o[0],o[1],o[2],255]:o),i.length<255){const o=oy.slice(i.length);i=[...i,...o]}return r.addColorLUT(i,n),n}function Oge(t,e){if(!t)throw new Error("addColorLUT: colorLUT is required");return $g(t,e)}function Mge(t,e,r){if(!D1(r))throw new Error(`setColorLUT: could not find colorLUT with index ${r}`);const n=Jo(t,{segmentationId:e});if(!n)throw new Error(`viewport specific state for viewport ${t} does not exist`);n.forEach(i=>{i.colorLUTIndex=r}),Gs(t,e)}function el(t,e,r){const n=Jo(t,{segmentationId:e});if(!n||n.length===0)return null;const i=n[0],{colorLUTIndex:o}=i,a=D1(o);let s=a[r];if(!s){if(typeof r!="number")return console.warn(`Can't create colour for LUT index ${r}`),null;s=a[r]=[0,0,0,0]}return s}function pV(t,e,r,n){const i=el(t,e,r);for(let o=0;oOr(c).id);hV(s)}return i}_getContourSegmentationStyle(e){const r=e.annotation,{segmentationId:n,segmentIndex:i}=r.data.segmentation,{viewportId:o}=e.styleSpecifier,a=Jo(o,{segmentationId:n});if(!(a!=null&&a.length))return{};a.length>1?a.find(v=>v.segmentationId===n&&v.type===Dt.Contour):a[0];const{autoGenerated:s}=r,l=dd(n).includes(i),{color:f,fillColor:u,lineWidth:d,fillOpacity:h,lineDash:g,visibility:p}=vV({segmentationId:n,segmentIndex:i,viewportId:o,autoGenerated:s});return{color:f,fillColor:u,lineWidth:d,fillOpacity:h,lineDash:g,textbox:{color:f},visibility:p,locked:l}}};wE.PreviewSegmentIndex=255;let $p=wE;function yV(t,e){const r=mt("generalSeriesModule",t);return sl(r.modality,t,e)}function sl(t,e,r){return t==="CT"?"HU":t==="PT"?Rge(e,r):""}function Rge(t,e){if(!e.isPreScaled)return"raw";if(e.isSuvScaled)return"SUV";const r=mt("generalSeriesModule",t);if((r==null?void 0:r.modality)==="PT"){const n=mt("petSeriesModule",t);return(n==null?void 0:n.units)||"unitless"}return"unknown"}const{pointCanProjectOnLine:AD}=ku,{EPSILON:Lge}=cd,Age=1-Lge,xE=class xE extends $p{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,shadow:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:Oi.Shift,alwaysRenderOpenContourHandles:{enabled:!1,radius:2},allowOpenContours:!0,closeContourProximity:10,checkCanvasEditFallbackProximity:6,makeClockWise:!0,subPixelResolution:4,smoothing:{smoothOnAdd:!1,smoothOnEdit:!1,knotsRatioPercentageOnAdd:40,knotsRatioPercentageOnEdit:40},interpolation:{enabled:!1,onInterpolationComplete:null},decimate:{enabled:!1,epsilon:.1},displayOnePointAsCrosshairs:!1,calculateStats:!0,getTextLines:Nge,statsCalculator:rc}}){super(e,r),this.isDrawing=!1,this.isEditingClosed=!1,this.isEditingOpen=!1,this.addNewAnnotation=n=>{const i=n.detail,{element:o}=i,a=this.createAnnotation(n);this.addAnnotation(a,o);const s=_t(o,this.getToolName());return this.activateDraw(n,a,s),n.preventDefault(),Pe(s),a},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,c=_t(s,this.getToolName());this.activateOpenContourEndEdit(n,i,c,o)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o,s=_t(a,this.getToolName());i.data.contour.closed?this.activateClosedContourEdit(n,i,s):this.activateOpenContourEdit(n,i,s),n.preventDefault()},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{polyline:l}=i.data.contour;let f=c.worldToCanvas(l[0]);for(let h=1;h{const i=this.isDrawing,o=this.isEditingOpen,a=this.isEditingClosed;i?this.cancelDrawing(n):o?this.cancelOpenContourEdit(n):a&&this.cancelClosedContourEdit(n)},this._calculateCachedStats=(n,i,o,a)=>{const{data:s}=n,{cachedStats:c}=s,{polyline:l,closed:f}=s.contour,u=Object.keys(c);for(let h=0;hi.worldToCanvas(I)),w={isPreScaled:al(i,g),isSuvScaled:this.isSuvScaled(i,g,n.metadata.referencedImageId)},x=sl(y.Modality,n.metadata.referencedImageId,w),C=ta(p,()=>{const I=s.contour.polyline,P=I.length,M=new Array(P);for(let re=0;re{const{data:s}=n,c=this.getTargetId(i),l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:o.viewport.id,annotationUID:n.annotationUID},f=this.getLinkedTextBoxStyle(l,n);if(!f.visibility)return;const u=this.configuration.getTextLines(s,c);if(!u||u.length===0)return;const d=s.contour.polyline.map(x=>i.worldToCanvas(x));if(!s.handles.textBox.hasMoved){const x=na(d);s.handles.textBox.worldPosition=i.canvasToWorld(x)}const h=i.worldToCanvas(s.handles.textBox.worldPosition),p=qi(a,n.annotationUID??"","1",u,h,d,{},f),{x:v,y,width:m,height:w}=p;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([v,y]),topRight:i.canvasToWorld([v+m,y]),bottomLeft:i.canvasToWorld([v,y+w]),bottomRight:i.canvasToWorld([v+m,y+w])}},ohe(this),hhe(this),_he(this),khe(this),Uhe(this),Jhe(this),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}filterInteractableAnnotationsForElement(e,r){if(!r||!r.length)return;const n=Ce(e),{viewport:i}=n;let o;if(i instanceof ur){const a=i.getCamera(),{spacingInNormalDirection:s}=uh(i,a);o=this.filterAnnotationsWithinSlice(r,a,s)}else o=L1(i,r);return o}filterAnnotationsWithinSlice(e,r,n){const{viewPlaneNormal:i}=r,o=e.filter(l=>{let f=l.metadata.viewPlaneNormal;if(!l.metadata.referencedImageId&&!f&&l.metadata.FrameOfReferenceUID){for(const d of l.data.contour.polyline){const h=En(Ve(),d,r.focalPoint),g=Et(h,r.viewPlaneNormal);if(!$t(g,0))return!1}return l.metadata.viewPlaneNormal=r.viewPlaneNormal,l.metadata.cameraFocalPoint=r.focalPoint,!0}if(!f){const{referencedImageId:d}=l.metadata,{imageOrientationPatient:h}=mt("imagePlaneModule",d),g=bt(h[0],h[1],h[2]),p=bt(h[3],h[4],h[5]);f=Ve(),Rn(f,g,p),l.metadata.viewPlaneNormal=f}const u=Math.abs(Et(i,f))>Age;return f&&u});if(!o.length)return[];const a=n/2,{focalPoint:s}=r,c=[];for(const l of o){const u=l.data.contour.polyline[0];if(!l.isVisible)continue;const d=Ve();En(d,s,u);const h=Et(d,i);Math.abs(h){a.data.handles.points.length=0};return Ei(n,{data:{contour:{polyline:[[...r]]},label:"",cachedStats:{}},onInterpolationComplete:i})}getAnnotationStyle(e){return super.getAnnotationStyle(e)}renderAnnotationInstance(e){const{enabledElement:r,targetId:n,svgDrawingHelper:i}=e,o=e.annotation;let a=!1;const{viewport:s,renderingEngine:c}=r,l=this.isDrawing,f=this.isEditingOpen,u=this.isEditingClosed;if(!(l||f||u))this.configuration.displayOnePointAsCrosshairs&&o.data.contour.polyline.length===1?this.renderPointContourWithMarker(r,i,o):this.renderContour(r,i,o);else{const d=this.commonData.annotation.annotationUID;if(o.annotationUID===d)if(l)this.renderContourBeingDrawn(r,i,o);else if(u)this.renderClosedContourBeingEdited(r,i,o);else if(f)this.renderOpenContourBeingEdited(r,i,o);else throw new Error(`Unknown ${this.getToolName()} annotation rendering state`);else this.configuration.displayOnePointAsCrosshairs&&o.data.contour.polyline.length===1?this.renderPointContourWithMarker(r,i,o):this.renderContour(r,i,o);a=!0}if(this.configuration.calculateStats)return this._calculateStatsIfActive(o,n,s,c,r),this._renderStats(o,s,r,i),a}_calculateStatsIfActive(e,r,n,i,o){var s,c,l,f;const a=(s=this.commonData)==null?void 0:s.annotation.annotationUID;if(!(e.annotationUID===a&&!((c=this.commonData)!=null&&c.movingTextBox))&&!((l=this.commonData)!=null&&l.movingTextBox)){const{data:u}=e;(f=u.cachedStats[r])!=null&&f.unit?e.invalidated&&this._throttledCalculateCachedStats(e,n,i,o):(u.cachedStats[r]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null,unit:null},this._calculateCachedStats(e,n,i,o))}}updateClosedCachedStats({viewport:e,points:r,imageData:n,metadata:i,cachedStats:o,targetId:a,modalityUnit:s,canvasCoordinates:c,calibratedScale:l,deltaInX:f,deltaInY:u}){var j,Y,re,ue;const{scale:d,areaUnit:h,unit:g}=l,{voxelManager:p}=e.getImageData(),v=Ur(n,r[0]);v[0]=Math.floor(v[0]),v[1]=Math.floor(v[1]),v[2]=Math.floor(v[2]);let y=v[0],m=v[0],w=v[1],x=v[1],C=v[2],S=v[2];for(let ce=1;ce{let Ee=!0;const Oe=e.worldToCanvas(ce);return Oe[1]!=V&&(A=0,V=Oe[1],G=Vk(c,Oe,[L[0],Oe[1]]),G.sort(function(Se){return function(B,O){return B[Se]===O[Se]?0:B[Se]G[0][0]&&(G.shift(),A++),A%2===0&&(Ee=!1),Ee},boundsIJK:P,returnPoints:this.configuration.storePointData}));const F=this.configuration.statsCalculator.getStatistics();o[a]={Modality:i.Modality,area:T,perimeter:E,mean:(j=F.mean)==null?void 0:j.value,max:(Y=F.max)==null?void 0:Y.value,min:(re=F.min)==null?void 0:re.value,stdDev:(ue=F.stdDev)==null?void 0:ue.value,statsArray:F.array,pointsInShape:k,areaUnit:h,modalityUnit:s,unit:g}}updateOpenCachedStats({targetId:e,metadata:r,canvasCoordinates:n,cachedStats:i,modalityUnit:o,calibratedScale:a,deltaInX:s,deltaInY:c}){const{scale:l,unit:f}=a;let u=EC(n,closed)/l;u*=Math.sqrt(Math.pow(s,2)+Math.pow(c,2)),i[e]={Modality:r.Modality,length:u,modalityUnit:o,unit:f}}};xE.toolName="PlanarFreehandROI";let bu=xE;function Nge(t,e){const r=t.cachedStats[e],{area:n,mean:i,stdDev:o,length:a,perimeter:s,max:c,min:l,isEmptyArea:f,unit:u,areaUnit:d,modalityUnit:h}=r||{},g=[];if(Ar(n)){const p=f?"Area: Oblique not supported":`Area: ${an(n)} ${d}`;g.push(p)}return Ar(i)&&g.push(`Mean: ${an(i)} ${h}`),Ar(c)&&g.push(`Max: ${an(c)} ${h}`),Ar(l)&&g.push(`Min: ${an(l)} ${h}`),Ar(o)&&g.push(`Std Dev: ${an(o)} ${h}`),Ar(s)&&g.push(`Perimeter: ${an(s)} ${u}`),Ar(a)&&g.push(`${an(a)} ${u}`),g}const CE=class CE extends bu{constructor(e){const r=Ei({configuration:{calculateStats:!1,allowOpenContours:!1}},e);super(r)}isContourSegmentationTool(){return!0}renderAnnotationInstance(e){const r=e.annotation,{invalidated:n}=r,i=super.renderAnnotationInstance(e);if(n){const{segmentationId:o}=r.data.segmentation;io(o)}return i}};CE.toolName="PlanarFreehandContourSegmentationTool";let ic=CE;const kge={[Dt.Labelmap]:nV,[Dt.Contour]:eV,[Dt.Surface]:uk},km=ic.toolName;class Vge{constructor(){this._needsRender=new Set,this._animationFrameSet=!1,this._animationFrameHandle=null,this._getAllViewports=()=>Qo().flatMap(r=>r.getViewports()),this._renderFlaggedSegmentations=()=>{this._throwIfDestroyed(),Array.from(this._needsRender).forEach(r=>{this._triggerRender(r)}),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null}}renderSegmentationsForViewport(e){const r=e?[e]:this._getViewportIdsForSegmentation();this._setViewportsToBeRenderedNextFrame(r)}renderSegmentation(e){const r=this._getViewportIdsForSegmentation(e);this._setViewportsToBeRenderedNextFrame(r)}_getViewportIdsForSegmentation(e){const r=this._getAllViewports(),n=[];for(const i of r){const o=i.id;if(e){const a=Jo(o,{segmentationId:e});(a==null?void 0:a.length)>0&&n.push(o)}else{const a=Jo(o);(a==null?void 0:a.length)>0&&n.push(o)}}return n}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_setViewportsToBeRenderedNextFrame(e){e.forEach(r=>{this._needsRender.add(r)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedSegmentations),this._animationFrameSet=!0)}_triggerRender(e){const r=Jo(e);if(!(r!=null&&r.length))return;const{viewport:n}=zn(e)||{};if(!n)return;const i=[],o=r.map(a=>{a.type===Dt.Contour&&this._addPlanarFreeHandToolIfAbsent(n);const s=kge[a.type];try{const c=s.render(n,a);i.push(c)}catch(c){console.error(c)}return Promise.resolve({segmentationId:a.segmentationId,type:a.type})});Promise.allSettled(o).then(a=>{const s=a.filter(f=>f.status==="fulfilled").map(f=>f.value);function c(f){const{element:u,viewportId:d}=f.detail;u.removeEventListener(Xe.IMAGE_RENDERED,c),s.forEach(h=>{const g={viewportId:d,segmentationId:h.segmentationId,type:h.type};at(Ke,N.SEGMENTATION_RENDERED,{...g})})}n.element.addEventListener(Xe.IMAGE_RENDERED,c),n.render()})}_addPlanarFreeHandToolIfAbsent(e){km in Ge.tools||Ci(ic);const r=Or(e.id);r.hasTool(km)||(r.addTool(km),r.setToolPassive(km))}}function wh(t){wV.renderSegmentationsForViewport(t)}function k5(t){wV.renderSegmentation(t)}const wV=new Vge;function Fge({modifiedSlicesToUse:t,representationData:e,type:r}){const n=Le.getVolume(e[r].volumeId);if(!n){console.warn("segmentation not found in cache");return}const{imageData:i,vtkOpenGLTexture:o}=n;let a;if((t==null?void 0:t.length)>0)a=t;else{const s=i.getDimensions()[2];a=[...Array(s).keys()]}a.forEach(s=>{o.setUpdatedFrame(s)}),i.modified()}function Uge({viewportIds:t,segmentationId:e}){t.forEach(r=>{let n=Jo(r,{segmentationId:e});n=n.filter(i=>i.type===Dt.Labelmap),n.forEach(i=>{if(i.segmentationId!==e)return;const o=zn(r);if(!o)return;const{viewport:a}=o;if(a instanceof ur)return;const s=Wg(r,e);s!=null&&s.length&&s.forEach((c,l)=>{const f=c.actor.getMapper().getInputData(),u=Qc(r,e),d=Le.getImage(u[l]);f.modified(),s5(f,d)})})})}const Bge=function(t){const{segmentationId:e,modifiedSlicesToUse:r}=t.detail,{representationData:n}=Ln(e),i=yh(e),o=i.some(c=>{const{viewport:l}=zn(c);return l instanceof ur}),a=i.some(c=>{const{viewport:l}=zn(c);return l instanceof lr}),s=o&&a;i.forEach(c=>{const{viewport:l}=zn(c);l instanceof ur&&Fge({modifiedSlicesToUse:s?[]:r,representationData:n,type:Dt.Labelmap}),l instanceof lr&&Uge({viewportIds:i,segmentationId:e})})},xV=function(t){const{segmentationId:e}=t.detail,{representationData:r}=Ln(e);r.Labelmap&&Bge(t),k5(e)},CV=function(t){const{segmentationId:e}=t.detail;k5(e)};function SV(t,e){return Zn.updateLabelmapSegmentationImageReferences(t,e)}const Gge=function(t){if(!t)return;const e=Ce(t);if(!e)return;const{viewport:r}=e;r instanceof Ir||(t.addEventListener(Xe.STACK_NEW_IMAGE,jp),t.addEventListener(Xe.IMAGE_RENDERED,jp))},Wge=function(t){t.removeEventListener(Xe.STACK_NEW_IMAGE,jp),t.removeEventListener(Xe.IMAGE_RENDERED,jp)};function jp(t){const e=t.detail,{viewportId:r,renderingEngineId:n}=e,{viewport:i}=Ti(r,n),o=Jo(r);if(!(o!=null&&o.length))return;const a=o.filter(l=>l.type===Dt.Labelmap),s=i.getActors();a.forEach(l=>{const{segmentationId:f}=l;SV(r,f)});const c=a.flatMap(l=>Wg(r,l.segmentationId)).filter(l=>l!==void 0);c.length&&(c.forEach(l=>{a.find(u=>{const d=Qc(r,u.segmentationId);return d==null?void 0:d.includes(l.referencedId)})||i.removeActors([l.uid])}),a.forEach(l=>{const{segmentationId:f}=l,u=i.getCurrentImageId(),d=Qc(r,f);if(!d)return;const h=g=>{const p=Le.getImage(g);if(!p){console.warn("No derived image found in the cache for segmentation representation",l);return}const v=s.find(y=>y.referencedId===g);if(v){const y=v.actor.getMapper().getInputData();y.setDerivedImage?y.setDerivedImage(p):s5(y,p)}else{const{dimensions:y,spacing:m,direction:w}=i.getImageDataMetadata(p),x=Le.getImage(u)||{imageId:u},{origin:C}=i.getImageDataMetadata(x),S=C,_=p.voxelManager.getConstructor(),T=p.voxelManager.getScalarData(),E=Yt.newInstance({name:"Pixels",numberOfComponents:1,values:new _(T)}),D=h1.newInstance();D.setDimensions(y[0],y[1],1),D.setSpacing(m),D.setDirection(w),D.setOrigin(S),D.getPointData().setScalars(E),D.modified(),i.addImages([{imageId:g,representationUID:`${f}-${Dt.Labelmap}-${p.imageId}`,callback:({imageActor:b})=>{b.getMapper().setInputData(D)}}]),wh(r);return}};d.forEach(h),i.render(),t.type===Xe.IMAGE_RENDERED&&i.element.removeEventListener(Xe.IMAGE_RENDERED,jp)}))}const _V={enable:Gge,disable:Wge};async function zge(t){const e=t.detail.annotation;if(!R1(e))return;const r=jge(e),n=Hge(r,e);if(!n.length){at(Ke,N.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,{element:r.element,sourceAnnotation:e});return}const i=Du(e.data.contour.polyline,r),o=Yk(r,i,n);if(!o.length){at(Ke,N.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,{element:r.element,sourceAnnotation:e});return}if(o.length>1){Jk(r,e,i,o);return}const{targetAnnotation:a,targetPolyline:s,isContourHole:c}=o[0];if(c){const{contourHoleProcessingEnabled:l=!1}=t.detail;if(!l)return;O5(r,a,e)}else _4(r,a,s,e,i)}function $ge(t,e=!1){const r="PlanarFreehandContourSegmentationTool",n=Or(t.id,t.renderingEngineId);let i;return n?n.hasTool(r)?n.getToolOptions(r)||(i=`Tool ${r} must be in active/passive state in ${n.id} toolGroup`):i=`Tool ${r} not added to ${n.id} toolGroup`:i=`ToolGroup not found for viewport ${t.id}`,i&&!e&&console.warn(i),!i}function jge(t){const e=D4(t);return e.find(n=>$ge(n,!0))??e[0]}function Hge(t,e){const{annotationUID:r}=e;return S1().filter(i=>i.annotationUID&&i.annotationUID!==r&&R1(i)&&fk(i,e)&&t.isReferenceViewable(i.metadata))}function Kge(t){const e=t.detail.annotation;Yc(e)}function TV(t){const e=t.detail.annotation;R1(e)&&zge(t)}function ay(t){if(!t.detail.removed.length)return;Qo().forEach(n=>{const o=n.getViewports().map(a=>a.id);Pe(o)})}function EV(t){const{viewportId:e}=t.detail;Pe([e])}function qge(t){const e=t.detail.annotation;R1(e)&&Kge(t)}const DV=function(t){ph(t.detail.element)},Xge=function(t){t.addEventListener(Xe.IMAGE_RENDERED,DV)},Yge=function(t){t.removeEventListener(Xe.IMAGE_RENDERED,DV)},bV={enable:Xge,disable:Yge},{Active:Jge}=An;function xh(t,e,r){if(Ge.isInteractingWithTool)return!1;const{renderingEngineId:n,viewportId:i}=r.detail,o=Or(i,n);if(!o)return!1;let a;const s=Object.keys(o.toolOptions);for(let c=0;c{for(const c of s){if(c.isLocked||!c.isVisible)continue;const l=a.getHandleNearImagePoint(t,c,r,i);if(l){o.push({tool:a,annotation:c,handle:l});break}}}),o}function N1(t,e){const r=[];for(let n=0;n0&&r.push({tool:i,annotations:o}))}return r}function A4(t,e,r,n="mouse"){const i=n==="touch"?36:6,o=[];return e.forEach(({tool:a,annotations:s})=>{for(const c of s){if(c.isLocked||!c.isVisible)continue;if(a.isPointNearTool(t,c,r,i,n)){o.push({tool:a,annotation:c});break}}}),o}const{Active:Zge}=An;function V5(t){const{renderingEngineId:e,viewportId:r,event:n}=t.detail,i=vh(n)||hh.getModifierKey(),o=Or(r,e);if(!o)return null;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary(),c=t.detail.buttons??(n==null?void 0:n.buttons)??s;for(let l=0;lh.mouseButton===c&&h.modifierKey===i);if(u.mode===Zge&&d)return o.getToolInstance(f)}}function $0(t,e,r){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;cd.mouseButton===r);if(e.includes(f.mode)&&(!r||u)){const d=o.getToolInstance(l);a.push(d)}}return a}function Qge(t,e){var u;const r=new Map,{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return r;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary(),c=t.detail.event,l=(c==null?void 0:c.buttons)??s,f=vh(c)||hh.getModifierKey();for(let d=0;d{var w;return((w=m.bindings)==null?void 0:w.length)&&m.bindings.some(x=>x.mouseButton===l&&x.modifierKey===f)});y&&r.set(g,y)}return r}const{Active:epe,Passive:tpe}=An;function npe(t){if(Ge.isInteractingWithTool)return!1;const e=t.detail,{element:r}=e,n=Ce(r),{canvas:i}=e.currentPoints;if(!n)return!1;const o=Qge(t,[epe,tpe]),a=Array.from(o.keys()),s=N1(r,a),c=A4(r,s,i);if(c.length>0){const{tool:l,annotation:f}=c[0],u=o.get(l);return(typeof u.method=="string"?l[u.method]:u.method).call(l,t,f),!0}return!1}const{Active:rpe,Passive:ipe}=An;function PV(t){if(Ge.isInteractingWithTool)return;const e=V5(t);if(e&&typeof e.preMouseDownCallback=="function"&&e.preMouseDownCallback(t))return;const r=t.detail.event.buttons===1,n=$0(t,[rpe],t.detail.event.buttons),i=r?$0(t,[ipe]):void 0,o=[...n||[],...i||[]];if(npe(t))return;const s=t.detail,{element:c}=s,l=N1(c,o),f=s.currentPoints.canvas,u=MV(c,l,f,"mouse"),d=!!t.detail.event.shiftKey;if(u.length>0){const{tool:g,annotation:p,handle:v}=ND(u);kD(p.annotationUID,d),g.handleSelectedCallback(t,p,v,"Mouse");return}const h=A4(c,l,f,"mouse");if(h.length>0){const{tool:g,annotation:p}=ND(h);kD(p.annotationUID,d),g.toolSelectedCallback(t,p,"Mouse",f);return}e&&typeof e.postMouseDownCallback=="function"&&e.postMouseDownCallback(t)}function ND(t){if(t.length>1){const e=t.find(r=>{const n=!Zr(r.annotation.annotationUID),i=Gr(r.annotation.annotationUID);return n&&i});if(e)return e}return t[0]}function kD(t,e=!1){e?b1(t)?Ro(t,!1):Ro(t,!0,!0):Ro(t,!0,!1)}function RV(t){if(Ge.isInteractingWithTool)return;const e=V5(t);if(e&&!Ge.isMultiPartToolActive&&e.addNewAnnotation){const r=e.addNewAnnotation(t,"mouse");Ro(r.annotationUID)}}function LV(t){if(Ge.isInteractingWithTool)return;const e=V5(t);!e||typeof e.mouseDragCallback!="function"||e.mouseDragCallback(t)}const{Active:ope,Passive:ape}=An;function AV(t){if(Ge.isInteractingWithTool||Ge.isMultiPartToolActive)return;const e=$0(t,[ope,ape]),r=t.detail,{element:n}=r,i=N1(n,e),o=e.filter(s=>!i.some(l=>l.tool.getToolName()===s.getToolName()));let a=!1;for(const{tool:s,annotations:c}of i)typeof s.mouseMoveCallback=="function"&&(a=s.mouseMoveCallback(t,c)||a);o.forEach(s=>{typeof s.mouseMoveCallback=="function"&&s.mouseMoveCallback(t)}),a===!0&&ph(n)}const NV=xh.bind(null,"Mouse","mouseUpCallback");function kV(t){if(Ge.isInteractingWithTool)return;t.detail.buttons=nc.Wheel|(t.detail.event.buttons||0);const e=V5(t);if(e)return e.mouseWheelCallback(t)}const spe=function(t){t.addEventListener(N.MOUSE_CLICK,IV),t.addEventListener(N.MOUSE_DOWN,PV),t.addEventListener(N.MOUSE_DOWN_ACTIVATE,RV),t.addEventListener(N.MOUSE_DOUBLE_CLICK,OV),t.addEventListener(N.MOUSE_DRAG,LV),t.addEventListener(N.MOUSE_MOVE,AV),t.addEventListener(N.MOUSE_UP,NV),t.addEventListener(N.MOUSE_WHEEL,kV)},cpe=function(t){t.removeEventListener(N.MOUSE_CLICK,IV),t.removeEventListener(N.MOUSE_DOWN,PV),t.removeEventListener(N.MOUSE_DOWN_ACTIVATE,RV),t.removeEventListener(N.MOUSE_DOUBLE_CLICK,OV),t.removeEventListener(N.MOUSE_DRAG,LV),t.removeEventListener(N.MOUSE_MOVE,AV),t.removeEventListener(N.MOUSE_UP,NV),t.removeEventListener(N.MOUSE_WHEEL,kV)},VV={enable:spe,disable:cpe},{Active:lpe}=An;function FV(t){const{renderingEngineId:e,viewportId:r}=t.detail,n=_ue(),i=hh.getModifierKey(),o=Or(r,e);if(!o)return null;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary();for(let c=0;cd.mouseButton===(n??s)&&d.modifierKey===i))return o.getToolInstance(l)}}function upe(t,e){var c;const r=new Map,{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return r;const a=Object.keys(o.toolOptions),s=t.detail.key;for(let l=0;l{var v;return(v=p.bindings)==null?void 0:v.some(y=>y.key===s)});g&&r.set(u,g)}return r}function UV(t){const e=FV(t);if(e){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n),a=e.getToolName();Object.keys(o.toolOptions).includes(a)&&o.setViewportsCursorByToolName(a)}const r=upe(t,[An.Active]);if(r!=null&&r.size){const{element:n}=t.detail;for(const[i,o]of[...r.entries()])(typeof o.method=="function"?o.method:i[o.method]).call(i,n,o,t)}}function BV(t){const e=FV(t);if(!e)return;const{renderingEngineId:r,viewportId:n}=t.detail,i=Or(n,r);tk();const o=e.getToolName();Object.keys(i.toolOptions).includes(o)&&i.setViewportsCursorByToolName(o)}const fpe=function(t){t.addEventListener(N.KEY_DOWN,UV),t.addEventListener(N.KEY_UP,BV)},dpe=function(t){t.removeEventListener(N.KEY_DOWN,UV),t.removeEventListener(N.KEY_UP,BV)},GV={enable:fpe,disable:dpe},{Active:hpe,Passive:gpe,Enabled:ppe}=An,WV=function(t){$0(t,[hpe,gpe,ppe]).forEach(r=>{r.onCameraModified&&r.onCameraModified(t)})},mpe=function(t){t.addEventListener(Xe.CAMERA_MODIFIED,WV)},vpe=function(t){t.removeEventListener(Xe.CAMERA_MODIFIED,WV)},zV={enable:mpe,disable:vpe},{Active:ype,Passive:wpe,Enabled:xpe}=An,$V=function(t){$0(t,[ype,wpe,xpe]).forEach(r=>{r.onImageSpacingCalibrated&&r.onImageSpacingCalibrated(t)})},Cpe=function(t){t.addEventListener(Xe.IMAGE_SPACING_CALIBRATED,$V)},Spe=function(t){t.removeEventListener(Xe.IMAGE_SPACING_CALIBRATED,$V)},jV={enable:Cpe,disable:Spe},{Active:_pe}=An;function N4(t){const{renderingEngineId:e,viewportId:r}=t.detail,n=t.detail.event,i=Or(r,e);if(!i)return null;const o=Object.keys(i.toolOptions),a=Object.keys(n.touches).length,s=vh(n)||hh.getModifierKey(),c=i.getDefaultMousePrimary();for(let l=0;l(h.numTouchPoints===a||a===1&&h.mouseButton===c)&&h.modifierKey===s);if(u.mode===_pe&&d)return i.getToolInstance(f)}}function VD(t,e,r){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;cd.numTouchPoints===r);if(e.includes(f.mode)&&(!r||u)){const d=o.getToolInstance(l);a.push(d)}}return a}const{Active:Tpe,Passive:Epe}=An;function HV(t){if(Ge.isInteractingWithTool)return;const e=N4(t);if(e&&typeof e.preTouchStartCallback=="function"&&e.preTouchStartCallback(t))return;const r=Object.keys(t.detail.event.touches).length===1,n=VD(t,[Tpe],Object.keys(t.detail.event.touches).length),i=r?VD(t,[Epe]):void 0,o=[...n||[],...i||[],e],a=t.detail,{element:s}=a,c=N1(s,o),l=a.currentPoints.canvas,f=MV(s,c,l,"touch"),u=!1;if(f.length>0){const{tool:h,annotation:g,handle:p}=FD(f);UD(g.annotationUID,u),h.handleSelectedCallback(t,g,p,"Touch");return}const d=A4(s,c,l,"touch");if(d.length>0){const{tool:h,annotation:g}=FD(d);UD(g.annotationUID,u),h.toolSelectedCallback(t,g,"Touch",l);return}e&&typeof e.postTouchStartCallback=="function"&&e.postTouchStartCallback(t)}function FD(t){return t.length>1&&t.find(e=>!Zr(e.annotation.annotationUID)&&Gr(e.annotation.annotationUID))||t[0]}function UD(t,e=!1){e?b1(t)?Ro(t,!1):Ro(t,!0,!0):Ro(t,!0,!1)}function KV(t){if(Ge.isInteractingWithTool)return;const e=N4(t);if(e&&!Ge.isMultiPartToolActive&&e.addNewAnnotation){const r=e.addNewAnnotation(t,"touch");Ro(r.annotationUID)}}function qV(t){if(Ge.isInteractingWithTool)return;const e=N4(t);!e||typeof e.touchDragCallback!="function"||e.touchDragCallback(t)}const XV=xh.bind(null,"Touch","touchEndCallback"),Dpe=xh.bind(null,"Touch","touchTapCallback"),YV=xh.bind(null,"Touch","touchPressCallback"),bpe=function(t){t.addEventListener(N.TOUCH_START,HV),t.addEventListener(N.TOUCH_START_ACTIVATE,KV),t.addEventListener(N.TOUCH_DRAG,qV),t.addEventListener(N.TOUCH_END,XV),t.addEventListener(N.TOUCH_TAP,Dpe),t.addEventListener(N.TOUCH_PRESS,YV)},Ipe=function(t){t.removeEventListener(N.TOUCH_START,HV),t.removeEventListener(N.TOUCH_START_ACTIVATE,KV),t.removeEventListener(N.TOUCH_DRAG,qV),t.removeEventListener(N.TOUCH_END,XV),t.removeEventListener(N.TOUCH_PRESS,YV)},JV={enable:bpe,disable:Ipe},Ope=function(){Ke.addEventListener(N.ANNOTATION_COMPLETED,Ys.handleAnnotationCompleted),Ke.addEventListener(N.ANNOTATION_MODIFIED,Ys.handleAnnotationUpdate),Ke.addEventListener(N.ANNOTATION_REMOVED,Ys.handleAnnotationDelete)},Mpe=function(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,Ys.handleAnnotationCompleted),Ke.removeEventListener(N.ANNOTATION_MODIFIED,Ys.handleAnnotationUpdate),Ke.removeEventListener(N.ANNOTATION_REMOVED,Ys.handleAnnotationDelete)},ZV={enable:Ope,disable:Mpe},{Active:Ppe,Passive:Rpe,Enabled:Lpe}=An,QV=function(t){$0(t,[Ppe,Rpe,Lpe]).forEach(r=>{r.onResetCamera&&r.onResetCamera(t)})},Ape=function(t){t.addEventListener(Xe.CAMERA_RESET,QV)},Npe=function(t){t.removeEventListener(Xe.CAMERA_RESET,QV)},eF={enable:Ape,disable:Npe};function k4(t){const{element:e,viewportId:r}=t.detail,n=kpe(r);Vpe(e),Fpe(n,e),C4.addViewportElement(r,e),AN.enable(e),QN.enable(e),YN.enable(e),hh.enable(e),_V.enable(e),bV.enable(e),zV.enable(e),jV.enable(e),eF.enable(e),VV.enable(e),GV.enable(e),JV.enable(e),Ge.enabledElements.push(e)}function kpe(t){const e="http://www.w3.org/2000/svg",r=document.createElementNS(e,"svg"),n=`svg-layer-${t}`;r.classList.add("svg-layer"),r.setAttribute("id",n),r.setAttribute("xmlns","http://www.w3.org/2000/svg"),r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.position="absolute";const i=document.createElementNS(e,"defs"),o=document.createElementNS(e,"filter"),a=document.createElementNS(e,"feOffset"),s=document.createElementNS(e,"feColorMatrix"),c=document.createElementNS(e,"feBlend");return o.setAttribute("id",`shadow-${n}`),o.setAttribute("filterUnits","userSpaceOnUse"),a.setAttribute("result","offOut"),a.setAttribute("in","SourceGraphic"),a.setAttribute("dx","0.5"),a.setAttribute("dy","0.5"),s.setAttribute("result","matrixOut"),s.setAttribute("in","offOut"),s.setAttribute("in2","matrix"),s.setAttribute("values","0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0"),c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","matrixOut"),c.setAttribute("mode","normal"),o.appendChild(a),o.appendChild(s),o.appendChild(c),i.appendChild(o),r.appendChild(i),r}function Vpe(t){const{viewportUid:e,renderingEngineUid:r}=t.dataset,n=`${e}:${r}`;Ge.svgNodeCache[n]={}}function Fpe(t,e){e.querySelector("div.viewport-element").appendChild(t)}function tF(t,e){const r=[];if(!e&&!t)throw new Error("At least one of renderingEngineId or viewportId should be given");for(let n=0;n{const e=Ce(t);if(!e)return;tF(e.viewportId,e.renderingEngineId).forEach(n=>{n.remove(e)})},Gpe=t=>{const e=Ce(t);if(!e)return;const{renderingEngineId:r,viewportId:n}=e,i=Or(n,r);i&&i.removeViewports(r,n)};function Wpe(t){const{viewportUid:e,renderingEngineUid:r}=t.dataset,n=`${e}:${r}`;delete Ge.svgNodeCache[n]}function zpe(t){const e=t.querySelector(`div.${Upe}`),r=e.querySelector("svg");r&&e.removeChild(r)}const $pe=function(t){const e=Ge.enabledElements.findIndex(r=>r===t);e>-1&&Ge.enabledElements.splice(e,1)};function nF(t){const e=zk(t,[An.Active,An.Passive]),r=N1(t,e);for(const{tool:n}of r){const i=n.cancel(t);if(i)return i}}class F4{constructor(e,r,n,i){this._viewportOptions={},this._onEvent=o=>{var l;if(this._ignoreFiredEvents===!0||!this._targetViewports.length)return;const a=this._eventSource==="element"?Ce(o.currentTarget):zn((l=o.detail)==null?void 0:l.viewportId);if(!a)return;const{renderingEngineId:s,viewportId:c}=a;this._sourceViewports.find(f=>f.viewportId===c)&&this.fireEvent({renderingEngineId:s,viewportId:c},o)},this._enabled=!0,this._eventName=r,this._eventHandler=n,this._ignoreFiredEvents=!1,this._sourceViewports=[],this._targetViewports=[],this._options=i||{},this._eventSource=this._options.eventSource||"element",this._auxiliaryEvents=this._options.auxiliaryEvents||[],this.id=e}isDisabled(){return!this._enabled||!this._hasSourceElements()}setOptions(e,r={}){this._viewportOptions[e]=r}setEnabled(e){this._enabled=e}getOptions(e){return this._viewportOptions[e]}add(e){this.addTarget(e),this.addSource(e)}addSource(e){if(Vm(this._sourceViewports,e))return;const{renderingEngineId:r,viewportId:n}=e,i=Jr(r).getViewport(n);if(!i){console.warn(`Synchronizer.addSource: No viewport for ${r} ${n}`);return}(this._eventSource==="element"?i.element:Ke).addEventListener(this._eventName,this._onEvent.bind(this)),this._auxiliaryEvents.forEach(({name:a,source:s})=>{(s==="element"?i.element:Ke).addEventListener(a,this._onEvent.bind(this))}),this._updateDisableHandlers(),this._sourceViewports.push(e)}addTarget(e){Vm(this._targetViewports,e)||(this._targetViewports.push(e),this._updateDisableHandlers())}getSourceViewports(){return this._sourceViewports}getTargetViewports(){return this._targetViewports}destroy(){this._sourceViewports.forEach(e=>this.removeSource(e)),this._targetViewports.forEach(e=>this.removeTarget(e))}remove(e){this.removeTarget(e),this.removeSource(e)}removeSource(e){const r=BD(this._sourceViewports,e);if(r===-1)return;const n=this._eventSource==="element"?this.getViewportElement(e):Ke;this._sourceViewports.splice(r,1),n.removeEventListener(this._eventName,this._eventHandler),this._auxiliaryEvents.forEach(({name:i,source:o})=>{(o==="element"?this.getViewportElement(e):Ke).removeEventListener(i,this._eventHandler)}),this._updateDisableHandlers()}removeTarget(e){const r=BD(this._targetViewports,e);r!==-1&&(this._targetViewports.splice(r,1),this._updateDisableHandlers())}hasSourceViewport(e,r){return Vm(this._sourceViewports,{renderingEngineId:e,viewportId:r})}hasTargetViewport(e,r){return Vm(this._targetViewports,{renderingEngineId:e,viewportId:r})}fireEvent(e,r){if(this.isDisabled()||this._ignoreFiredEvents)return;this._ignoreFiredEvents=!0;const n=[];try{for(let i=0;i{this._ignoreFiredEvents=!1}):this._ignoreFiredEvents=!1}}_hasSourceElements(){return this._sourceViewports.length!==0}_updateDisableHandlers(){const e=jpe(this._sourceViewports,this._targetViewports),r=this.remove.bind(this),n=i=>{r(i.detail.element)};e.forEach(i=>{const o=this.getEventSource(i);o&&(o.removeEventListener(Xe.ELEMENT_DISABLED,n),o.addEventListener(Xe.ELEMENT_DISABLED,n))})}getEventSource(e){return this._eventSource==="element"?this.getViewportElement(e):Ke}getViewportElement(e){const{renderingEngineId:r,viewportId:n}=e,i=Jr(r);if(!i)return null;const o=i.getViewport(n);return o?o.element:null}}function jpe(t,e){const r=[],n=t.concat(e);for(let i=0;io.renderingEngineId===a.renderingEngineId&&o.viewportId===a.viewportId)||r.push(o)}return r}function BD(t,e){return t.findIndex(r=>e.renderingEngineId===r.renderingEngineId&&e.viewportId===r.viewportId)}function Vm(t,e){return t.some(r=>r.renderingEngineId===e.renderingEngineId&&r.viewportId===e.viewportId)}function hd(t,e,r,n){if(Ge.synchronizers.some(a=>a.id===t))throw new Error(`Synchronizer with id '${t}' already exists.`);const o=new F4(t,e,r,n);return Ge.synchronizers.push(o),o}function Hpe(){for(;Ge.synchronizers.length>0;)Ge.synchronizers.pop().destroy()}function Kpe(t){return Ge.synchronizers.find(e=>e.id===t)}function qpe(){return Ge.synchronizers}function Xpe(t){const e=Ge.synchronizers.findIndex(r=>r.id===t);e>-1&&(Ge.synchronizers[e].destroy(),Ge.synchronizers.splice(e,1))}const rF=Object.freeze(Object.defineProperty({__proto__:null,createSynchronizer:hd,destroy:Hpe,destroySynchronizer:Xpe,getAllSynchronizers:qpe,getSynchronizer:Kpe,getSynchronizersForViewport:tF},Symbol.toStringTag,{value:"Module"})),Ype=Object.freeze(Object.defineProperty({__proto__:null,Synchronizer:F4,SynchronizerManager:rF,ToolGroupManager:vN,addEnabledElement:k4,addTool:Ci,cancelActiveManipulations:nF,hasTool:lue,removeEnabledElement:V4,removeTool:TN,get state(){return Ge},svgNodeCache:d5},Symbol.toStringTag,{value:"Module"})),sy=function(t){const{viewportId:e}=t.detail;wh(e)};let bC=!1;function iF(t={}){bC||(lfe(t),Zpe(),Qpe(),bC=!0)}function Jpe(){oF(),aF(),pN(),kce();const t=Es(),e=Zn;t.restoreAnnotations({}),e.resetState(),bC=!1}function Zpe(){oF();const t=Xe.ELEMENT_ENABLED,e=Xe.ELEMENT_DISABLED;Ke.addEventListener(t,k4),Ke.addEventListener(e,V4),ZV.enable()}function oF(){const t=Xe.ELEMENT_ENABLED,e=Xe.ELEMENT_DISABLED;Ke.removeEventListener(t,k4),Ke.removeEventListener(e,V4),ZV.disable()}function Qpe(){aF(),Ke.addEventListener(N.ANNOTATION_COMPLETED,TV),Ke.addEventListener(N.ANNOTATION_MODIFIED,EV),Ke.addEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.addEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.addEventListener(N.ANNOTATION_REMOVED,qge),Ke.addEventListener(N.SEGMENTATION_MODIFIED,CV),Ke.addEventListener(N.SEGMENTATION_DATA_MODIFIED,xV),Ke.addEventListener(N.SEGMENTATION_REPRESENTATION_MODIFIED,sy),Ke.addEventListener(N.SEGMENTATION_REPRESENTATION_ADDED,sy)}function aF(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,TV),Ke.removeEventListener(N.ANNOTATION_MODIFIED,EV),Ke.removeEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.removeEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.removeEventListener(N.SEGMENTATION_MODIFIED,CV),Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,xV),Ke.removeEventListener(N.SEGMENTATION_REPRESENTATION_MODIFIED,sy),Ke.removeEventListener(N.SEGMENTATION_REPRESENTATION_ADDED,sy)}const e1e=Object.freeze(Object.defineProperty({__proto__:null,COLOR_LUT:oy},Symbol.toStringTag,{value:"Module"})),t1e="3.20.0";function n1e(t,e,r,n){const{camera:i}=n.detail,o=Jr(r.renderingEngineId);if(!o)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const a=o.getViewport(r.viewportId);a.setCamera(i),a.render()}const{CAMERA_MODIFIED:r1e}=Xe;function i1e(t){return hd(t,r1e,n1e)}function o1e(t,e,r,n,i){const o=Jr(r.renderingEngineId);if(!o)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const a=o.getViewport(r.viewportId),c=o.getViewport(e.viewportId).getViewPresentation(i);a.setViewPresentation(c),a.render()}const{CAMERA_MODIFIED:a1e}=Xe;function s1e(t,e){return hd(t,a1e,o1e,{viewPresentation:e})}function c1e(t,e,r,n,i){const o=n.detail,{volumeId:a,range:s,invertStateChanged:c,invert:l,colormap:f}=o,u=Jr(r.renderingEngineId);if(!u)throw new Error(`Rendering Engine does not exist: ${r.renderingEngineId}`);const d=u.getViewport(r.viewportId),h={voiRange:s};if(i!=null&&i.syncInvertState&&c&&(h.invert=l),i!=null&&i.syncColormap&&f&&(h.colormap=f),d instanceof Ir)d._actors&&d._actors.size>1?d.setProperties(h,a):d.setProperties(h);else if(d instanceof lr)d.setProperties(h);else throw new Error("Viewport type not supported.");d.render()}function l1e(t,e){return e=Object.assign({syncInvertState:!0,syncColormap:!0},e),hd(t,Xe.VOI_MODIFIED,c1e,{auxiliaryEvents:[{name:Xe.COLORMAP_MODIFIED}],...e})}function u1e(t,e,r){const n=Jr(r.renderingEngineId);if(!n)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const i=t.getOptions(r.viewportId),o=n.getViewport(r.viewportId),a=n.getViewport(e.viewportId);if((i==null?void 0:i.syncZoom)!==!1){const s=a.getZoom();o.setZoom(s)}if((i==null?void 0:i.syncPan)!==!1){const s=a.getPan();o.setPan(s)}o.render()}const{CAMERA_MODIFIED:f1e}=Xe;function d1e(t){return hd(t,f1e,u1e)}function h1e(t,e){const{viewPlaneNormal:r}=t.getCamera(),{viewPlaneNormal:n}=e.getCamera(),i=Et(r,n);return Math.abs(i)>.9}const GD=(t,e)=>kp.get("spatialRegistrationModule",t,e);async function g1e(t,e,r){const n=Jr(r.renderingEngineId);if(!n)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const i=n.getViewport(e.viewportId),o=t.getOptions(r.viewportId);if(o!=null&&o.disabled)return;const a=n.getViewport(r.viewportId),s=i.getCurrentImageId(),l=mt("imagePlaneModule",s).imagePositionPatient,f=a.getImageIds();if(!h1e(i,a))return;let u=GD(r.viewportId,e.viewportId);if(!u){const p=i.getFrameOfReferenceUID(),v=a.getFrameOfReferenceUID();if(p===v&&(o==null?void 0:o.useInitialPosition)!==!1?u=Vt(Zo()):(HA(i,a),u=GD(r.viewportId,e.viewportId)),!u)return}const d=Jt(Ve(),l,u),h=p1e(d,f);let g=h.index;a instanceof ur&&(g=f.length-h.index-1),h.index!==-1&&a.getCurrentImageIdIndex()!==h.index&&await Aa(a.element,{imageIndex:g})}function p1e(t,e){return e.reduce((r,n,i)=>{const{imagePositionPatient:o}=mt("imagePlaneModule",n),a=ki(o,t);return a{i.getImageIds().includes(t)&&i.calibrateSpacing(t)})}function lF(t,e){const r=t.findIndex(([n,i])=>n===i);if(r===-1)throw new Error("3D bounding boxes not supported in an oblique plane");return t[r][0]-=e,t[r][1]+=e,t}const D1e=Object.freeze(Object.defineProperty({__proto__:null,extend2DBoundingBoxInViewAxis:lF,getBoundingBoxAroundShape:Su,getBoundingBoxAroundShapeIJK:Su,getBoundingBoxAroundShapeWorld:ik},Symbol.toStringTag,{value:"Module"})),{transformWorldToIndex:c3}=Mn;function uF(t,e,r){const[n,i]=t,o=bt((n[0]+i[0])/2,(n[1]+i[1])/2,(n[2]+i[2])/2),a=ki(n,i)/2,{boundsIJK:s,topLeftWorld:c,bottomRightWorld:l}=I1e(e,r,t,o,a);return{boundsIJK:s,centerWorld:o,radiusWorld:a,topLeftWorld:c,bottomRightWorld:l}}function fF(t,e){const r=e.getDirection(),n=bt(r[0],r[1],r[2]),i=bt(r[3],r[4],r[5]),o=bt(r[6],r[7],r[8]),a=Hs(Ve(),o);return uF(t,e,{row:n,column:i,normal:a})}function b1e(t,e,r){if(!r)throw new Error("viewport is required in order to calculate the sphere bounds");const n=r.getCamera(),i=bt(n.viewUp[0],n.viewUp[1],n.viewUp[2]),o=bt(n.viewPlaneNormal[0],n.viewPlaneNormal[1],n.viewPlaneNormal[2]),a=Ve();Rn(a,i,o);const s={row:a,normal:o,column:Hs(Ve(),i)};return uF(t,e,s)}function I1e(t,e,r,n,i){const o=t.getDimensions(),{row:a,column:s,normal:c}=e,l=Ve(),f=Ve();Tn(l,n,c,i),Tn(f,n,c,-i),Tn(l,l,s,-i),Tn(f,f,s,i),Tn(l,l,a,-i),Tn(f,f,a,i);const u=c3(t,l),d=c3(t,f),h=r.map(p=>c3(t,p));return{boundsIJK:Su([u,d,...h],o),topLeftWorld:l,bottomRightWorld:f}}function dF(t,e=5){return parseFloat(t[0]).toFixed(e)+","+parseFloat(t[1]).toFixed(e)+","+parseFloat(t[2]).toFixed(e)+","}class O1e{static setStartRange(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,n)}static setEndRange(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,void 0,n)}static setRange(e,r,n,i){var c;const{metadata:o}=r;n===void 0&&(n=o.sliceIndex=n?a:e.getNumberOfSlices()-1),i=Math.max(n,i),o.sliceIndex=Math.min(n,i),o.referencedImageId=e.getCurrentImageId(o.sliceIndex),o.referencedImageURI=void 0,i===o.sliceIndex?o.multiSliceReference=void 0:i!==((c=o.multiSliceReference)==null?void 0:c.sliceIndex)&&(o.multiSliceReference={referencedImageId:e.getCurrentImageId(i),sliceIndex:i});const s={viewportId:e.id,renderingEngineId:e.renderingEngineId,changeType:Ht.MetadataReferenceModified,annotation:r};at(Ke,N.ANNOTATION_MODIFIED,s),this.setViewportFrameRange(e,o)}static setSingle(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,n,n)}static getFrameRange(e){const{metadata:r}=e,{sliceIndex:n,multiSliceReference:i}=r,o=i==null?void 0:i.sliceIndex;return o?[n+1,o+1]:n+1}static getFrameRangeStr(e){const r=this.getFrameRange(e);return Array.isArray(r)?`${r[0]}-${r[1]}`:String(r)}static setViewportFrameRange(e,r){var n;e.setFrameRange&&((n=r.multiSliceReference)!=null&&n.sliceIndex)&&e.setFrameRange(r.sliceIndex+1,r.multiSliceReference.sliceIndex+1)}}function M1e(t,e){const{viewPlaneNormal:r}=t.metadata,{viewPlaneNormal:n}=e.metadata,i=Et(r,n);if(!vu(1,Math.abs(i)))return!1;const{polyline:a}=t.data.contour,{polyline:s}=e.data.contour,c=Et(r,a[0]),l=Et(r,s[0]);return vu(c,l)}function hF(t,e,r){let n=-1;if(e.forEach((i,o)=>{n>=0||i.a==t.b&&(n=o)}),n>=0){const i=e[n];return e.splice(n,1),r.push(i.b),r[0]==i.b?{remainingLines:e,contourPoints:r,type:"CLOSED_PLANAR"}:hF(i,e,r)}return{remainingLines:e,contourPoints:r,type:"OPEN_PLANAR"}}function U4(t){if(t.length==0)return[];const e=[],r=t.shift();e.push(r.a),e.push(r.b);const n=hF(r,t,e);if(n.remainingLines.length==0)return[{type:n.type,contourPoints:n.contourPoints}];{const i=U4(n.remainingLines);return i.push({type:n.type,contourPoints:n.contourPoints}),i}}function P1e(t){return U4(t)}const R1e={findContours:U4,findContoursFromReducedSet:P1e};function L1e(t,e=!1){const r=t.getPoints(),n=t.getLines(),i=new Array(r.getNumberOfPoints()).fill(0).map((c,l)=>r.getPoint(l).slice()),o=new Array(n.getNumberOfCells()).fill(0).map((c,l)=>{const f=n.getCell(l*3).slice();return{a:f[0],b:f[1]}});if(e)return{points:i,lines:o};const a=[];for(const[c,l]of i.entries()){const f=a.findIndex(u=>u[0]===l[0]&&u[1]===l[1]&&u[2]===l[2]);if(f>=0)o.map(u=>(u.a===c&&(u.a=f),u.b===c&&(u.b=f),u));else{const u=a.length;a.push(l),o.map(d=>(d.a===c&&(d.a=u),d.b===c&&(d.b=u),d))}}const s=o.filter(c=>c.a!==c.b);return{points:a,lines:s}}const A1e=(t,e)=>{const r=t[0],n=t[1];let i=!1;for(let o=0,a=e.length-1;on!=f>n&&r<(l-s)*(n-c)/(f-c)+s&&(i=!i)}return i};function N1e(t,e,r){const n=[];t.contourPoints.forEach(o=>{n.push([r[o][0],r[o][1]])});let i=0;return e.contourPoints.forEach(o=>{A1e([r[o][0],r[o][1]],n)||i++}),i===0}function k1e(t,e,r=!0){const n=t.filter(s=>s.type!=="CLOSED_PLANAR"),i=t.filter(s=>s.type==="CLOSED_PLANAR"),o=[];let a=[];return i.forEach((s,c)=>{const l=[];i.forEach((f,u)=>{c!=u&&N1e(s,f,e)&&l.push(u)}),l.length>0?o.push({contour:s,holes:l}):a.push(c)}),r&&(o.forEach(s=>{s.contour.type="CLOSEDPLANAR_XOR",n.push(s.contour),s.holes.forEach(c=>{i[c].type="CLOSEDPLANAR_XOR",n.push(i[c]),a=a.filter(l=>l!==c)})}),a.forEach(s=>{n.push(i[s])})),n}const V1e={processContourHoles:k1e};let WD=!1;function F5(){if(WD)return;WD=!0;const t=()=>new Worker(new URL("/static/dv3d/assets/computeWorker-FOqOvCDJ.js",import.meta.url),{name:"compute",type:"module"}),e=il(),n=cfe().computeWorker,i={maxWorkerInstances:1,autoTerminateOnIdle:(n==null?void 0:n.autoTerminateOnIdle)??{enabled:!0,idleTimeThreshold:2e3}};e.registerWorker("compute",t,i)}function U5(){return Zn.getState().segmentations}function F1e(t){const{segmentationId:e,representation:r,config:n}=t,{type:i,data:o}=r,a=o?{...o}:{};if(!a)throw new Error("Segmentation representation data may not be undefined");i===Dt.Contour&&U1e(a);const s=B1e(n==null?void 0:n.segments,i,a);return n==null||delete n.segments,{segmentationId:e,label:(n==null?void 0:n.label)??null,cachedStats:(n==null?void 0:n.cachedStats)??{},segments:s,representationData:{[i]:{...a}}}}function U1e(t){t.geometryIds=t.geometryIds??[],t.annotationUIDsMap=t.annotationUIDsMap??new Map}function B1e(t,e,r){const n={};return t?Object.entries(t).forEach(([i,o])=>{const{label:a,locked:s,cachedStats:c,active:l,...f}=o,u={segmentIndex:Number(i),label:a??`Segment ${i}`,locked:s??!1,cachedStats:c??{},active:l??!1,...f};n[i]=u}):e===Dt.Surface?G1e(n,r):n[1]=W1e(),n}function G1e(t,e){const{geometryIds:r}=e;r==null||r.forEach(n=>{const i=Le.getGeometry(n);if(i!=null&&i.data){const{segmentIndex:o}=i.data;t[o]={segmentIndex:o}}})}function W1e(){return{segmentIndex:1,label:"Segment 1",locked:!1,cachedStats:{},active:!0}}function gF(t,e){const r=Zn;t.forEach(n=>{const i=F1e(n);r.addSegmentation(i),e||Ta(i.segmentationId)})}function Ch(t,e,r){return mF(t,e,r)}function pF(t,e,r){return mF(t,e,r)}function mF(t,e,r){const{segmentationId:n,type:i}=e;return z1e(t,n,i,r),Zn.removeSegmentationRepresentations(t,{segmentationId:n,type:i})}function vF(){Zn.getAllViewportSegmentationRepresentations().forEach(({viewportId:e,representations:r})=>{r.forEach(({segmentationId:n,type:i})=>{Ch(e,{segmentationId:n,type:i})})}),Zn.resetState()}function yF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Labelmap},r)}function wF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Contour},r)}function xF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Surface},r)}function z1e(t,e,r,n){Jo(t,{segmentationId:e,type:r}).forEach(a=>{a.type===Dt.Labelmap?nV.removeRepresentation(t,a.segmentationId,n):a.type===Dt.Contour?eV.removeRepresentation(t,a.segmentationId,n):a.type===Dt.Surface&&uk.removeRepresentation(t,a.segmentationId,n)});const{viewport:o}=zn(t)||{};o&&o.render()}function B4(t){const e=Zn;e.getAllViewportSegmentationRepresentations().filter(({representations:n})=>n.some(i=>i.segmentationId===t)).map(({viewportId:n})=>n).forEach(n=>{pF(n,{segmentationId:t})}),e.removeSegmentation(t),e4(t)}function CF(){const t=Zn;t.getState().segmentations.map(n=>n.segmentationId).forEach(n=>{B4(n)}),t.resetState()}function $1e(t){Zn.removeColorLUT(t)}function SF(t,e){return _F(t).map(o=>(e&&o.type===e,Ln(o.segmentationId))).filter(o=>o!==void 0)}function _F(t){return Zn.getState().viewportSegRepresentations[t]}function j1e(t,e){return Zn.getStackSegmentationImageIdsForViewport(t,e)}function H1e(){Zn.resetState()}const K1e=Object.freeze(Object.defineProperty({__proto__:null,addColorLUT:$g,addSegmentations:gF,destroy:H1e,getColorLUT:D1,getCurrentLabelmapImageIdForViewport:Vu,getCurrentLabelmapImageIdsForViewport:Qc,getNextColorLUTIndex:gV,getSegmentation:Ln,getSegmentationRepresentation:t4,getSegmentationRepresentations:Jo,getSegmentationRepresentationsBySegmentationId:sk,getSegmentations:U5,getStackSegmentationImageIdsForViewport:j1e,getViewportIdsWithSegmentation:yh,getViewportSegmentationRepresentations:_F,getViewportSegmentations:SF,removeAllSegmentationRepresentations:vF,removeAllSegmentations:CF,removeColorLUT:$1e,removeContourRepresentation:wF,removeLabelmapRepresentation:yF,removeSegmentation:B4,removeSegmentationRepresentation:Ch,removeSurfaceRepresentation:xF,updateLabelmapSegmentationImageReferences:SV},Symbol.toStringTag,{value:"Module"}));function TF(t){if("volumeId"in t){if(t=t,!Le.getVolume(t.volumeId))throw new Error(`volumeId of ${t.volumeId} not found in cache, you should load and cache volume before adding segmentation`)}else if("imageIds"in t){if(t=t,!t.imageIds)throw new Error("The segmentationInput.representationData.imageIds is undefined, please provide a valid representationData.imageIds for stack data")}else throw new Error("The segmentationInput.representationData is undefined, please provide a valid representationData")}function q1e(t){if(!t.representation.data)throw new Error("The segmentationInput.representationData.data is undefined, please provide a valid representationData.data");const e=t.representation.data;TF(e)}function X1e(t){TF(t)}const Y1e=Object.freeze(Object.defineProperty({__proto__:null,validate:X1e,validatePublic:q1e},Symbol.toStringTag,{value:"Module"}));function EF(t){const e=Le.getVolume(t);if(!e)return null;const r=e.referencedVolumeId;let n;if(r)n=Le.getVolume(r);else{const i=e.imageIds,a=Le.getImage(i[0]).referencedImageId,s=Le.getVolumeContainingImageId(a);n=s==null?void 0:s.volume}return n}function J1e({operationData:t}){const{volumeId:e}=t;if(!e){const c=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"No volume id found for the segmentation"},cancelable:!0});return Ke.dispatchEvent(c),null}const r=Le.getVolume(e),n=EF(e);if(!r||!n)return null;const{imageData:i}=r,{voxelManager:o}=r,{voxelManager:a,imageData:s}=n;return{segmentationImageData:i,segmentationVoxelManager:o,segmentationScalarData:null,imageScalarData:null,imageVoxelManager:a,imageData:s}}function Z1e({operationData:t,viewport:e,strategy:r}){var f;const{segmentationId:n}=t;let i,o,a,s,c,l;if(r.ensureSegmentationVolumeFor3DManipulation)r.ensureSegmentationVolumeFor3DManipulation({operationData:t,viewport:e}),o=t.segmentationVoxelManager,i=t.segmentationImageData,a=null;else{const u=Vu(e.id,n);if(!u)return null;const d=_5(e.id,n);if(!d)return null;const h=Le.getImage(u);i=d.actor.getMapper().getInputData(),o=h.voxelManager;const g=t.imageId,p=Le.getImage(g);if(!p)return null;a=(f=p.getPixelData)==null?void 0:f.call(p)}if(r.ensureImageVolumeFor3DManipulation)r.ensureImageVolumeFor3DManipulation({operationData:t,viewport:e}),c=t.imageVoxelManager,s=t.imageScalarData,l=t.imageData;else{const u=e.getCurrentImageId();if(!u)return null;const d=Le.getImage(u);l=d?null:e.getImageData(),s=(d==null?void 0:d.getPixelData())||l.getScalarData(),c=d==null?void 0:d.voxelManager}return{segmentationImageData:i,segmentationScalarData:a,imageScalarData:s,segmentationVoxelManager:o,imageVoxelManager:c,imageData:l}}function G4({operationData:t,viewport:e,strategy:r}){return t?"volumeId"in t&&t.volumeId!=null||"referencedVolumeId"in t&&t.referencedVolumeId!=null?J1e({operationData:t}):Z1e({operationData:t,viewport:e,strategy:r}):null}function Sh(t){const{representationData:e}=Ln(t);let{volumeId:r}=e.Labelmap,n;if(r&&(n=Le.getVolume(r),n))return n;const{imageIds:i}=e.Labelmap;if(r=Le.generateVolumeId(i),!(!i||i.length===1||!Nu(i)))return n=i5(r,i),n}const DF={[St.EnsureSegmentationVolumeFor3DManipulation]:t=>{const{operationData:e,viewport:r}=t,{segmentationId:n,imageIds:i}=e,o=r?r.getImageIds():i.map(c=>Le.getImage(c).referencedImageId);if(!Nu(o))throw new Error("Volume is not reconstructable for sphere manipulation");const s=Sh(n);s&&(e.segmentationVoxelManager=s.voxelManager,e.segmentationImageData=s.imageData)}};function B5(t){if(!t||t.length<=1||!Nu(t))return;const r=Le.generateVolumeId(t);let n=Le.getVolume(r);return n||(n=i5(r,t),n)}const bF={[St.EnsureImageVolumeFor3DManipulation]:t=>{const{operationData:e,viewport:r}=t;let n;if(r){if(n=r.getImageIds(),!Nu(n))throw new Error("Volume is not reconstructable for sphere manipulation")}else n=Ln(e.segmentationId).representationData.Labelmap.imageIds.map(s=>Le.getImage(s).referencedImageId);const i=B5(n);if(!i)throw new Error("Failed to create or get image volume");e.imageVoxelManager=i.voxelManager,e.imageData=i.imageData}},oc=(t,e)=>{at(Ke,Xe.WEB_WORKER_PROGRESS,{progress:e,type:t})},IF=(t,e)=>{const r=Ln(t),{representationData:n}=r,{Labelmap:i}=n;if(!i)return console.debug("No labelmap found for segmentation",t),null;const o=i.volumeId,a=i.imageIds,s={segmentationId:t,volumeId:o,imageIds:a};let c=!1;if(a){const f=a.map(u=>Le.getImage(u).referencedImageId);c=Nu(f)}let l=e;return l?Array.isArray(l)||(l=[l,255]):l=[ea(t)],{operationData:s,segVolumeId:o,segImageIds:a,reconstructableVolume:c,indices:l}},OF=t=>G4({operationData:t,strategy:{ensureSegmentationVolumeFor3DManipulation:DF.ensureSegmentationVolumeFor3DManipulation,ensureImageVolumeFor3DManipulation:bF.ensureImageVolumeFor3DManipulation}}),MF=t=>{const e=[],r=[];for(const n of t){const i=Le.getImage(n),o=i.getPixelData(),{origin:a,direction:s,spacing:c,dimensions:l}=a5(i);e.push({scalarData:o,dimensions:l,spacing:c,origin:a,direction:s});const f=i.referencedImageId;if(f){const u=Le.getImage(f);if(!u)continue;const d=u.getPixelData(),h=u.voxelManager,g=[u.rowPixelSpacing,u.columnPixelSpacing];r.push({scalarData:d,dimensions:h?h.dimensions:[u.columns,u.rows,1],spacing:g})}}return{segmentationInfo:e,imageInfo:r}},Q1e=(t,e)=>{var a;let r;if(t){const c=Le.getVolume(t).imageIds,l=Le.getImage(c[0]);l&&(r=l.referencedImageId)}else e!=null&&e.length&&(r=Le.getImage(e[0]).referencedImageId);const n=Le.getImage(r),i=mt("scalingModule",r),o={isPreScaled:!!((a=n==null?void 0:n.preScale)!=null&&a.scaled),isSuvScaled:typeof(i==null?void 0:i.suvbw)=="number"};return{refImageId:r,modalityUnitOptions:o}},{Labelmap:eme}=Dt;async function PF({segmentations:t}){F5(),oc(xa.GENERATE_CONTOUR_SETS,0);const{representationData:e,segments:r=[0,1],segmentationId:n}=t;let{volumeId:i}=e[eme];if(!i){const g=Sh(n);g&&(i=g.volumeId)}const o=Le.getVolume(i);if(!o){console.warn(`No volume found for ${i}`);return}const c={scalarData:o.voxelManager.getCompleteScalarDataArray(),dimensions:o.dimensions,spacing:o.imageData.getSpacing(),origin:o.imageData.getOrigin(),direction:o.imageData.getDirection()},l=Array.isArray(r)?r.filter(g=>g!==null).map(g=>g.segmentIndex||g):Object.values(r).filter(g=>g!==null).map(g=>g.segmentIndex||g),f=await il().executeTask("compute","generateContourSetsFromLabelmapVolume",{segmentation:c,indices:l,mode:"individual"}),u=o.imageIds.map(g=>{var v;const p=(v=Le.getImage(g))==null?void 0:v.referencedImageId;return p?Le.getImage(p):void 0}),d=u.map(g=>a5(g)),h=f.map(g=>{const p=r[g.segment.segmentIndex]||{};if(!g.sliceContours.length)return null;const v=g.sliceContours[0].polyData.points[0];let y;if(v){const m=d.findIndex(w=>{const{scanAxisNormal:x,origin:C}=w,S=qs(x,C);return tA(v,S)});m!==-1&&(y=u[m].imageId)}return{label:p.label,color:p.color,metadata:{FrameOfReferenceUID:o.metadata.FrameOfReferenceUID,referencedImageId:y},sliceContours:g.sliceContours.map(m=>({contours:m.contours,polyData:m.polyData,FrameNumber:m.sliceIndex+1,sliceIndex:m.sliceIndex,FrameOfReferenceUID:o.metadata.FrameOfReferenceUID,referencedImageId:y}))}}).filter(g=>g!==null);return oc(xa.GENERATE_CONTOUR_SETS,100),h}class RF{constructor(){}static getContourSequence(e,r){const{data:n}=e,{projectionPoints:i,projectionPointsImageIds:o}=n.cachedStats;return i.map((a,s)=>{const c=tme(a),l=nme(o[s],r);return{NumberOfContourPoints:c.length/3,ContourImageSequence:l,ContourGeometricType:"CLOSED_PLANAR",ContourData:c}})}}RF.toolName="RectangleROIStartEndThreshold";function tme(t){return[...t[0],...t[1],...t[3],...t[2]].flat().map(i=>i.toFixed(2))}function nme(t,e){const r=e.get("sopCommonModule",t);return{ReferencedSOPClassUID:r.sopClassUID,ReferencedSOPInstanceUID:r.sopInstanceUID}}function rme(t){if(!(t!=null&&t.data))throw new Error("Tool data is empty");if(!t.metadata||t.metadata.referencedImageId)throw new Error("Tool data is not associated with any imageId")}const Qg=class Qg{constructor(){}static convert(e,r,n){rme(e);const{toolName:i}=e.metadata,o=Qg.TOOL_NAMES[i];if(!o)throw new Error(`Unknown tool type: ${i}, cannot convert to RTSSReport`);const a=o.getContourSequence(e,n),s=[Math.floor(Math.random()*255),Math.floor(Math.random()*255),Math.floor(Math.random()*255)];return{ReferencedROINumber:r+1,ROIDisplayColor:s,ContourSequence:a}}static register(e){Qg.TOOL_NAMES[e.toolName]=e}};Qg.TOOL_NAMES={};let cy=Qg;cy.register(RF);function ime(t,e){Ys.acceptAutoGenerated(t,e)}const{isEqual:ome}=Mn;function IC(t,e){const{polyline:r}=t.data.contour,{points:n}=t.data.handles,{length:i}=n;if(e===i)return r.length;if(e<0&&(e=(e+i)%i),e===0)return 0;const o=n[e],a=r.findIndex(c=>ome(o,c));if(a!==-1)return a;let s=1/0;return r.reduce((c,l,f)=>{const u=MM(l,o);return u{const S=({value:M})=>{h=h+1,M>=g.lower&&M<=g.upper&&(d=d+1)},{imageData:_,dimensions:T,lower:E,upper:D}=w,b=ZT(_,T,x,C);h=0,d=0,g={lower:E,upper:D};let I=!1;const{voxelManager:P}=_.get("voxelManager");return P.forEach(S,{imageData:_,boundsIJK:b}),s===0?I=d>0:s==1&&(I=d===h),I},v=(w,x)=>{const{imageData:C,lower:S,upper:_}=w,T=C.get("voxelManager").voxelManager,E=T.toIndex(x),D=T.getAtIndex(E);return!(D<=S||D>=_)},y=({index:w,pointIJK:x,pointLPS:C})=>{let S=u.length>0;for(let _=0;_{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...s],[...s],[...s],[...s]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}}});nn(f,a);const u=_t(a,this.getToolName());return this.editData={annotation:f,viewportIdsToRender:u,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(u),f},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=c.worldToCanvas(f[0]),d=c.worldToCanvas(f[3]),h=this._getRectangleImageCoordinates([u,d]),g=[o[0],o[1]],{left:p,top:v,width:y,height:m}=h;return y4([p,v,y,m],g)<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;o.worldPosition?l=!0:f=c.handles.points.findIndex(g=>g===o);const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Ot(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.doneEditMemo(),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a))},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world,{points:g}=u.handles;g.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=Ce(o),{worldToCanvas:g,canvasToWorld:p}=h.viewport,v=d.world,{points:y}=u.handles;y[c]=[...v];let m,w,x,C,S,_,T,E;switch(c){case 0:case 3:m=g(y[0]),C=g(y[3]),w=[C[0],m[1]],x=[m[0],C[1]],_=p(w),T=p(x),y[1]=_,y[2]=T;break;case 1:case 2:w=g(y[1]),x=g(y[2]),m=[x[0],w[1]],C=[w[0],x[1]],S=p(m),E=p(C),y[0]=S,y[3]=E;break}a.invalidated=!0}this.editData.hasMoved=!0,Ce(o),Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(F));u.annotationUID=g;const{color:w,lineWidth:x,lineDash:C}=this.getAnnotationStyle({annotation:h,styleSpecifier:u}),{viewPlaneNormal:S,viewUp:_}=a.getCamera();if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null},this._calculateCachedStats(h,S,_,f,n);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,S,_,f,n),a instanceof ur)){const{referencedImageId:F}=h.metadata;for(const j in p.cachedStats)j.startsWith("imageId")&&f.getStackViewports().find(ue=>{const ce=Vr(F),pe=ue.hasImageURI(ce),Ee=Vr(ue.getCurrentImageId());return pe&&Ee!==ce})&&delete p.cachedStats[j]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let T;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(T=[m[y]]),T&&ir(i,g,"0",T,{color:w});const E=`${g}-rect`;x4(i,g,"0",m,{color:w,lineDash:C,lineWidth:x},E),o=!0;const b=this.getLinkedTextBoxStyle(u,h);if(!b.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const I=this.configuration.getTextLines(p,l);if(!I||I.length===0)continue;if(!p.handles.textBox.hasMoved){const F=na(m);p.handles.textBox.worldPosition=a.canvasToWorld(F)}const P=a.worldToCanvas(p.handles.textBox.worldPosition),L=qi(i,g,"1",I,P,m,{},b),{x:V,y:G,width:A,height:k}=L;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([V,G]),topRight:a.canvasToWorld([V+A,G]),bottomLeft:a.canvasToWorld([V,G+k]),bottomRight:a.canvasToWorld([V+A,G+k])}}return o},this._getRectangleImageCoordinates=n=>{const[i,o]=n;return{left:Math.min(i[0],o[0]),top:Math.min(i[1],o[1]),width:Math.abs(i[0]-o[0]),height:Math.abs(i[1]-o[1])}},this._calculateCachedStats=(n,i,o,a,s)=>{var v,y,m,w;if(!this.configuration.calculateStats)return;const{data:c}=n,{viewport:l}=s,{element:f}=l,u=c.handles.points[0],d=c.handles.points[3],{cachedStats:h}=c,g=Object.keys(h);for(let x=0;xsr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}};e0.toolName="RectangleROI",e0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=e0.hydrateBase(e0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let tl=e0;function sme(t,e){const r=t.cachedStats[e],{area:n,mean:i,max:o,stdDev:a,areaUnit:s,modalityUnit:c,min:l}=r;if(i==null)return;const f=[];return Ar(n)&&f.push(`Area: ${an(n)} ${s}`),Ar(i)&&f.push(`Mean: ${an(i)} ${c}`),Ar(o)&&f.push(`Max: ${an(o)} ${c}`),Ar(l)&&f.push(`Max: ${an(l)} ${c}`),Ar(a)&&f.push(`Std Dev: ${an(a)} ${c}`),f}const{transformWorldToIndex:Jh}=Mn;class W4 extends tl{constructor(e={},r={configuration:{storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:cme,statsCalculator:rc,showTextBox:!1,throttleTimeout:100}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u;let g,p,v;if(l instanceof lr)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);v=sc(_),p=Le.getVolume(v),g=qc(p,s,d)}const y=Au(p,d),m=this._getStartCoordinate(s,d),w=this._getEndCoordinate(s,y,d),x=l.getFrameOfReferenceUID(),C={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...d],enabledElement:c,viewUp:[...h],FrameOfReferenceUID:x,referencedImageId:g,toolName:this.getToolName(),volumeId:v,spacingInNormal:y},data:{label:"",startCoordinate:m,endCoordinate:w,cachedStats:{pointsInVolume:[],projectionPoints:[],projectionPointsImageIds:[g],statistics:[]},handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},labelmapUID:null}};this._computeProjectionPoints(C,p),nn(C,a);const S=_t(a,this.getToolName());return this.editData={annotation:C,viewportIdsToRender:S,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),C},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const d=this.getTargetId(u.viewport),h=Le.getVolume(d.split(/volumeId:|\?/)[1]);this._computePointsInsideVolume(a,d,h,u),Pe(s),c?Nn(a):tn(a,o)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;let s=un(this.getToolName(),a.element);if(!(s!=null&&s.length))return o;s=L5(s,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let l=0;la.worldToCanvas(A));c.annotationUID=u;const w=this.getStyle("lineWidth",c,f),x=this.getStyle("lineDash",c,f),C=this.getStyle("color",c,f),S=a.getCamera().focalPoint,_=a.getCamera().viewPlaneNormal;let T=g,E=p;if(Array.isArray(g)){T=this._getCoordinateForViewplaneNormal(T,_);const A=this._getIndexOfCoordinatesForViewplaneNormal(_);d.handles.points.forEach(k=>{k[A]=T}),d.startCoordinate=T}Array.isArray(p)&&(E=this._getCoordinateForViewplaneNormal(E,_),d.endCoordinate=E,d.endCoordinate=E);const D=eu(T),b=eu(E),I=this._getCoordinateForViewplaneNormal(S,_),P=eu(I);if(PMath.max(D,b))continue;f.invalidated&&this._throttledCalculateCachedStats(f,n);let M=!1;if((P===D||P===b)&&(M=!0),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let L;if(!Gr(u))continue;!Zr(u)&&!this.editData&&y!==null&&M&&(L=[m[y]]),L&&ir(i,u,"0",L,{color:C});let V=x;if(M||(V=2),P1(i,u,"0",m[0],m[3],{color:C,lineDash:V,lineWidth:w}),o=!0,this.configuration.showTextBox){const A=this.getLinkedTextBoxStyle(c,f);if(!A.visibility){d.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const k=this.configuration.getTextLines(d,{metadata:h});if(!k||k.length===0)continue;if(!d.handles.textBox.hasMoved){const Ee=na(m);d.handles.textBox.worldPosition=a.canvasToWorld(Ee)}const F=a.worldToCanvas(d.handles.textBox.worldPosition),Y=qi(i,u,"1",k,F,m,{},A),{x:re,y:ue,width:ce,height:pe}=Y;d.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([re,ue]),topRight:a.canvasToWorld([re+ce,ue]),bottomLeft:a.canvasToWorld([re,ue+pe]),bottomRight:a.canvasToWorld([re+ce,ue+pe])}}}return o},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=_o(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=gh(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(e,r){const{data:n,metadata:i}=e,{viewPlaneNormal:o,spacingInNormal:a}=i,{imageData:s}=r,{startCoordinate:c,endCoordinate:l}=n,{points:f}=n.handles,u=Jh(s,f[0]),d=Jh(s,f[0]),h=Ve();s.indexToWorldVec3(u,h);const g=Ve();s.indexToWorldVec3(d,g),this._getIndexOfCoordinatesForViewplaneNormal(o)==2?(h[2]=c,g[2]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==0?(h[0]=c,g[0]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==1&&(h[1]=c,g[1]=l);const p=ki(h,g),v=[];for(let y=0;y{const w=Ve();return Tn(w,m,o,y),Array.from(w)}));n.cachedStats.projectionPoints=v}_computePointsInsideVolume(e,r,n,i){var S,_,T;const{data:o,metadata:a}=e,{viewPlaneNormal:s,viewUp:c}=a,{viewport:l}=i,f=o.cachedStats.projectionPoints,u=[[]],d=this.getTargetImageData(r),h=o.handles.points[0],g=o.handles.points[3],{worldWidth:p,worldHeight:v}=R5(s,c,h,g),y=ta(d,o.habdles),m=Math.abs(p*v)/(y.scale*y.scale),w={isPreScaled:al(l,r),isSuvScaled:this.isSuvScaled(l,r,e.metadata.referencedImageId)},x=sl(a.Modality,e.metadata.referencedImageId,w);for(let E=0;E{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getTargetId(l);let p,v;if(l instanceof lr)p=g.split("imageId:")[1];else{v=sc(g);const x=Le.getVolume(v);p=qc(x,s,d)}const y=l.getFrameOfReferenceUID(),m={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...d],enabledElement:c,viewUp:[...h],FrameOfReferenceUID:y,referencedImageId:p,toolName:this.getToolName(),volumeId:v},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:null,worldBoundingBox:null},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},segmentationId:null}};nn(m,a);const w=_t(a,this.getToolName());return this.editData={annotation:m,viewportIdsToRender:w,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(w),m},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(S));l.annotationUID=d;const y=this.getStyle("lineWidth",l,u),m=this.getStyle("lineDash",l,u),w=this.getStyle("color",l,u);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;tn(u,s);let x;if(!Gr(d))continue;!Zr(d)&&!this.editData&&p!==null&&(x=[v[p]]),x&&ir(i,d,"0",x,{color:w}),P1(i,d,"0",v[0],v[3],{color:w,lineDash:m,lineWidth:y}),o=!0}return o}}}z4.toolName="RectangleROIThreshold";function AF(t,e,r={}){const n=[];return t.forEach(o=>{var h,g;const{data:a}=o,{points:s}=a.handles,{imageData:c,dimensions:l}=e;let f=s;if((h=a.cachedStats)!=null&&h.projectionPoints){const{projectionPoints:p}=a.cachedStats;f=[].concat(...p)}const u=f.map(p=>Ur(c,p));let d=Su(u,l);r.numSlicesToProject&&!((g=a.cachedStats)!=null&&g.projectionPoints)&&(d=lF(d,r.numSlicesToProject)),n.push(d)}),n.length===1?n[0]:n.reduce((o,a)=>({iMin:Math.min(o.iMin,a.iMin),jMin:Math.min(o.jMin,a.jMin),kMin:Math.min(o.kMin,a.kMin),iMax:Math.max(o.iMax,a.iMax),jMax:Math.max(o.jMax,a.jMax),kMax:Math.max(o.kMax,a.kMax)}),{iMin:1/0,jMin:1/0,kMin:1/0,iMax:-1/0,jMax:-1/0,kMax:-1/0})}function lme(t,e,r,n){const i=t.map(s=>Rr.getAnnotation(s));ume(i);let o;for(let s=0;s{if(!$t(f,t[0].dimensions)||!$t(l,t[0].direction)||!$t(d,t[0].spacing)||!$t(u,t[0].origin))throw new Error("labelmaps must have the same size and shape")});const n=t[0],i=n.voxelManager.getConstructor(),o=new i(n.voxelManager.getScalarDataLength());t.forEach(l=>{const f=l.voxelManager,u=f.getScalarDataLength();for(let d=0;d0;)g(f.pop());return{flooded:u};function g(T){const E=T.currentArgs,D=T.previousArgs;p(E)||(v(E),y(E)?(m(E),x(E)):w(D))}function p(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));return d.has(I)}function v(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));d.add(I)}function y(T){const E=C(T);return o?o(E,c):E===c}function m(T){u.push(T),n&&n(...T)}function w(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));h==null||h.set(I,T),i&&i(...T)}function x(T){for(let E=0;E{const{segmentIndex:e,previewSegmentIndex:r,segmentationVoxelManager:n,centerIJK:i,viewPlaneNormal:o,segmentationImageData:a,configuration:s}=t;if(!(s!=null&&s.useCenterSegmentIndex))return;let c=!1,l=!1;const f=[...n.getBoundsIJK()];Math.abs(o[0])>.8?f[0]=[i[0],i[0]]:Math.abs(o[1])>.8?f[1]=[i[1],i[1]]:Math.abs(o[2])>.8&&(f[2]=[i[2],i[2]]);const u=({value:h})=>{c||(c=h===e),l||(l=h===r)};if(n.forEach(u,{imageData:a,isInObject:t.isInObject,boundsIJK:f}),!c&&!l){t.centerSegmentIndexInfo.segmentIndex=null;return}const d=n.getAtIJKPoint(i);t.centerSegmentIndexInfo.segmentIndex=d,t.centerSegmentIndexInfo.hasSegmentIndex=c,t.centerSegmentIndexInfo.hasPreviewIndex=l}},pme={[St.Initialize]:t=>{var y;const{operationName:e,centerIJK:r,segmentationVoxelManager:n,imageVoxelManager:i,configuration:o,segmentIndex:a,viewport:s}=t;if(!((y=o==null?void 0:o.threshold)!=null&&y.isDynamic)||!r||!a||e===St.RejectPreview||e===St.OnInteractionEnd)return;const c=n.getBoundsIJK(),{range:l,dynamicRadius:f=0}=o.threshold,u=l?0:f,{viewPlaneNormal:d}=s.getCamera(),h=c.map((m,w)=>{const[x,C]=m;return[Math.max(x,r[w]-u),Math.min(C,r[w]+u)]});Math.abs(d[0])>.8?h[0]=[r[0],r[0]]:Math.abs(d[1])>.8?h[1]=[r[1],r[1]]:Math.abs(d[2])>.8&&(h[2]=[r[2],r[2]]);const g=l||[1/0,-1/0],p=u*u,v=({value:m,pointIJK:w})=>{if(Gx(r,w)>p)return;const C=Array.isArray(m)?N0(m):m;g[0]=Math.min(C,g[0]),g[1]=Math.max(C,g[1])};i.forEach(v,{boundsIJK:h}),o.threshold.range=g},[St.OnInteractionStart]:t=>{var r;const{configuration:e}=t;(r=e==null?void 0:e.threshold)!=null&&r.isDynamic&&(e.threshold.range=null)},[St.ComputeInnerCircleRadius]:t=>{const{configuration:e,viewport:r}=t,{dynamicRadius:n=0,isDynamic:i}=e.threshold;if(!i){e.threshold.dynamicRadiusInCanvas=0;return}if(n===0)return;const o=r.getImageData();if(!o)return;const{spacing:a}=o,s=[r.element.clientWidth/2,r.element.clientHeight/2],c=n*a[0],f=r.canvasToWorld(s).map(h=>h+c),u=r.worldToCanvas(f),d=Math.abs(s[0]-u[0]);e.threshold.dynamicRadiusInCanvas||(e.threshold.dynamicRadiusInCanvas=0),e.threshold.dynamicRadiusInCanvas=3+d}},mme={[St.Initialize]:t=>{t.segmentIndex=0}},{isEqual:l3}=Mn,$D={toIJK:t=>t,fromIJK:t=>t,type:"acquistion"},vme={toIJK:([t,e,r])=>[r,t,e],fromIJK:([t,e,r])=>[e,r,t],type:"jk"},yme={toIJK:([t,e,r])=>[t,r,e],fromIJK:([t,e,r])=>[t,r,e],type:"ik"};function kF(t,e){if(!(t instanceof Ir))return{...$D,boundsIJKPrime:e};const{viewPlaneNormal:r}=t.getCamera(),n=l3(Math.abs(r[0]),1)&&vme||l3(Math.abs(r[1]),1)&&yme||l3(Math.abs(r[2]),1)&&$D;return n?{...n,boundsIJKPrime:n.fromIJK(e)}:{toIJK:null,boundsIJKPrime:null,fromIJK:null,error:`Only mappings orthogonal to acquisition plane are permitted, but requested ${r}`}}const{RLEVoxelMap:wme,VoxelManager:xme}=Mn,Cme=65535;var Zi;(function(t){t[t.SEGMENT=-1]="SEGMENT",t[t.ISLAND=-2]="ISLAND",t[t.INTERIOR=-3]="INTERIOR",t[t.EXTERIOR=-4]="EXTERIOR",t[t.INTERIOR_SMALL=-5]="INTERIOR_SMALL",t[t.INTERIOR_TEST=-6]="INTERIOR_TEST"})(Zi||(Zi={}));class nd{constructor(e){this.fillInternalEdge=!1,this.maxInternalRemove=128,this.maxInternalRemove=(e==null?void 0:e.maxInternalRemove)??this.maxInternalRemove,this.fillInternalEdge=(e==null?void 0:e.fillInternalEdge)??this.fillInternalEdge}initialize(e,r,n){const i=!!r.sourceVoxelManager,o=i?r.sourceVoxelManager:r,a=i?r:xme.createRLEHistoryVoxelManager(o),{segmentIndex:s=1,previewSegmentIndex:c=1}=n,l=n.points||o.getPoints();if(!(l!=null&&l.length))return;const f=o.getBoundsIJK().map((x,C)=>[Math.min(x[0],...l.map(S=>S[C])),Math.max(x[1],...l.map(S=>S[C]))]);if(f.find(x=>x[0]<0||x[1]>Cme))return;const{toIJK:u,fromIJK:d,boundsIJKPrime:h,error:g}=kF(e,f);if(g){console.warn("Not performing island removal for planes not orthogonal to acquisition plane",g);return}const[p,v,y]=d(o.dimensions),m=new wme(p,v,y),w=(x,C,S)=>{const _=o.toIndex(u([x,C,S])),T=o.getAtIndex(_);if(T===c||T===s)return Zi.SEGMENT};return m.fillFrom(w,h),m.normalizer={toIJK:u,fromIJK:d,boundsIJKPrime:h},this.segmentSet=m,this.previewVoxelManager=a,this.segmentIndex=s,this.previewSegmentIndex=c??s,this.selectedPoints=l,!0}floodFillSegmentIsland(){const{selectedPoints:e,segmentSet:r}=this;let n=0;const{fromIJK:i}=r.normalizer;return e.forEach(o=>{const a=i(o),s=r.toIndex(a),[c,l,f]=a;r.get(s)===Zi.SEGMENT&&(n+=r.floodFill(c,l,f,Zi.ISLAND))}),n}removeExternalIslands(){const{previewVoxelManager:e,segmentSet:r}=this,{toIJK:n}=r.normalizer,i=(o,a)=>{const[,s,c]=r.toIJK(o);if(a.value!==Zi.ISLAND)for(let l=a.start;l{let f;for(const u of[...l])if(u.value===Zi.ISLAND){if(!f){if(this.fillInternalEdge&&u.start>0)for(let d=0;d{if(l.value!==Zi.INTERIOR)return;const[,f,u]=e.toIJK(c),d=f>0?e.getRun(f-1,u):null,h=f+12&&(!v||!y)&&e.floodFill(l.start,f,u,Zi.EXTERIOR,{singlePlane:!0})}),e.forEach((c,l)=>{if(l.value!==Zi.INTERIOR)return;const[,f,u]=e.toIJK(c),g=e.floodFill(l.start,f,u,Zi.INTERIOR_TEST)>this.maxInternalRemove?Zi.EXTERIOR:Zi.INTERIOR_SMALL;e.floodFill(l.start,f,u,g)}),e.forEach((c,l)=>{if(l.value===Zi.INTERIOR_SMALL)for(let f=l.start;f=o.start&&n=i))return!0;return!1}}const Sme={[St.OnInteractionEnd]:t=>{const{previewSegmentIndex:e,segmentIndex:r,viewport:n,segmentationVoxelManager:i,activeStrategy:o,memo:a}=t;if(o!=="THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL"||r===null)return;const s=new nd,c=(a==null?void 0:a.voxelManager)||i;if(!s.initialize(n,c,{previewSegmentIndex:e,segmentIndex:r}))return;s.floodFillSegmentIsland(),s.removeExternalIslands(),s.removeInternalIslands();const l=c.getArrayOfModifiedSlices();l&&io(t.segmentationId,l,e)}},_me={[St.Preview]:function(t){var o,a;const{previewSegmentIndex:e,configuration:r,enabledElement:n}=t;if(!e||!r)return;(o=this.onInteractionStart)==null||o.call(this,n,t);const i=this.fill(n,t);return i&&((a=this.onInteractionEnd)==null||a.call(this,n,t)),i},[St.Initialize]:t=>{const{segmentIndex:e,previewColor:r,previewSegmentIndex:n}=t;if(n==null||e==null)return;const i=yh(t.segmentationId);i==null||i.forEach(o=>{pV(o,t.segmentationId,n,r)})},[St.AcceptPreview]:t=>{const{previewSegmentIndex:e,segmentationVoxelManager:r,memo:n,segmentIndex:i,centerSegmentIndexInfo:o}=t||{},{changedIndices:a}=o||{},s=n,c=({index:l})=>{const f=r.getAtIndex(l);(a==null?void 0:a.length)>0?a.includes(l)&&s.voxelManager.setAtIndex(l,0):f===e&&s.voxelManager.setAtIndex(l,i)};r.forEach(c),io(t.segmentationId,r.getArrayOfModifiedSlices(),i),t.centerSegmentIndexInfo.changedIndices=[]},[St.RejectPreview]:t=>{t&&$A.undoIf(e=>{const r=e;if(!(r!=null&&r.voxelManager))return!1;const{segmentationVoxelManager:n}=r;let i=!1;const o=({value:a})=>{a===t.previewSegmentIndex&&(i=!0)};return n.forEach(o),i})}},Tme={[St.Fill]:t=>{var l;const{segmentsLocked:e,segmentationImageData:r,segmentationVoxelManager:n,brushStrategy:i,centerIJK:o}=t,a=(l=i.createIsInThreshold)==null?void 0:l.call(i,t),{setValue:s}=i,c=a?f=>{const{value:u,index:d}=f;e.includes(u)||!a(d)||s(t,f)}:f=>s(t,f);n.forEach(c,{imageData:r,isInObject:t.isInObject,boundsIJK:t.isInObjectBoundsIJK}),n.addPoint(o)}};function Eme({operationData:t,existingValue:e,index:r}){const{previewSegmentIndex:n,memo:i,centerSegmentIndexInfo:o,previewOnHover:a,segmentIndex:s}=t,{hasPreviewIndex:c,hasSegmentIndex:l,segmentIndex:f}=o;if(f===0&&l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&l&&!c){if(e===0||e!==s)return;i.voxelManager.setAtIndex(r,n),o.changedIndices.push(r);return}if(f===0&&!l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&!l&&!c){if(e===s)return;if(e===n){i.voxelManager.setAtIndex(r,n);return}return}if(f===n&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===n&&!l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&!c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}}const Dme={[St.INTERNAL_setValue]:(t,{value:e,index:r})=>{const{segmentsLocked:n,previewSegmentIndex:i,memo:o,segmentationVoxelManager:a,centerSegmentIndexInfo:s,segmentIndex:c}=t,l=a.getAtIndex(r);if(!n.includes(e)&&!(!s&&l===c)&&!((s==null?void 0:s.segmentIndex)!==0&&l===c)){if((s==null?void 0:s.segmentIndex)===null){o.voxelManager.setAtIndex(r,i??c);return}if(!i){let f=c;s&&(f=s.segmentIndex),o.voxelManager.setAtIndex(r,f);return}Eme({operationData:t,existingValue:l,index:r})}}},bme={[St.CreateIsInThreshold]:t=>{const{imageVoxelManager:e,segmentIndex:r,configuration:n}=t;if(!(!n||!r))return i=>{var c;const o=e.getAtIndex(i),a=Array.isArray(o)?Po(o):o,{threshold:s}=n||{};return(c=s==null?void 0:s.range)!=null&&c.length?s.range[0]<=a&&a<=s.range[1]:!0}}},jD=10;function ly(){return{maxIJKs:[]}}function VF(t,e){const{value:r}=e,{maxIJKs:n}=t,i=n.length;if(typeof r!="number"||i>=jD&&r=n[i-1].value)n.push(o);else for(let a=0;a=jD&&n.splice(0,1)}function FF(t,e,r){const{spacing:n,calibration:i}=r,{volumeUnit:o}=ta({calibration:i,hasPixelSpacing:!0},[]),a=n?n[0]*n[1]*n[2]:1;return e.volume={value:Array.isArray(e.count.value)?e.count.value.map(s=>s*a):e.count.value*a,unit:o,name:"volume",label:"Volume"},e.maxIJKs=t.maxIJKs.filter(s=>s.pointIJK!==void 0),e.array.push(e.volume),t.maxIJKs=[],e}const SE=class SE extends rc{static statsInit(e){super.statsInit(e),this.volumetricState=ly()}static statsCallback(e){super.statsCallback(e),VF(this.volumetricState,e)}static getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return FF(this.volumetricState,n,r)}};SE.volumetricState=ly();let Uf=SE;class HD extends Pk{constructor(e){super(e),this.volumetricState=ly()}statsInit(e){super.statsInit(e),this.volumetricState=ly()}statsCallback(e){super.statsCallback(e),VF(this.volumetricState,e)}getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return FF(this.volumetricState,n,r)}}const Ime=Math.pow(3*1e3/(4*Math.PI),1/3);async function UF({segmentationId:t,segmentIndices:e,mode:r="collective"}){F5(),oc(xa.COMPUTE_STATISTICS,0);const n=IF(t,e);if(!n)return;const{operationData:i,segVolumeId:o,segImageIds:a,reconstructableVolume:s,indices:c}=n,{refImageId:l,modalityUnitOptions:f}=Q1e(o,a),u=yV(l,f);return s?await Ome({operationData:i,indices:c,unit:u,mode:r}):await Mme({segImageIds:a,indices:c,unit:u,mode:r})}async function Ome({operationData:t,indices:e,unit:r,mode:n}){var p;const i=OF(t),{segmentationVoxelManager:o,imageVoxelManager:a,segmentationImageData:s,imageData:c}=i;if(!o||!s)return;const l=s.getSpacing(),{boundsIJK:f}=o;if(!f)return Uf.getStatistics({spacing:l});const d={scalarData:o.getCompleteScalarDataArray(),dimensions:s.getDimensions(),spacing:s.getSpacing(),origin:s.getOrigin(),direction:s.getDirection()},h={scalarData:a.getCompleteScalarDataArray(),dimensions:c.getDimensions(),spacing:c.getSpacing(),origin:c.getOrigin(),direction:c.getDirection()};if(!((p=h.scalarData)!=null&&p.length))return;const g=await il().executeTask("compute","calculateSegmentsStatisticsVolume",{segmentationInfo:d,imageInfo:h,indices:e,unit:r,mode:n});if(oc(xa.COMPUTE_STATISTICS,100),n==="collective")return uy({stats:g,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a});{const v={};return Object.entries(g).forEach(([y,m])=>{v[y]=uy({stats:m,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a})}),v}}const u3=(t,e)=>{if(!t.array)return;const r=t.array.findIndex(n=>n.name===e.name);r!==-1?t.array[r]=e:t.array.push(e)},uy=({stats:t,unit:e,spacing:r,segmentationImageData:n,imageVoxelManager:i})=>{if(t.mean.unit=e,t.max.unit=e,t.min.unit=e,e!=="SUV")return t;const o=r.map(a=>Math.max(1,Math.round(1.1*Ime/a)));for(const a of t.maxIJKs){const s=Pme(a,o,n,i,r);if(!s)continue;const{mean:c}=s;(!t.peakValue||t.peakValue.value<=c.value)&&(t.peakValue={name:"peakValue",label:"Peak Value",value:c.value,unit:e},t.peakPoint={name:"peakLPS",label:"Peak SUV Point",value:a.pointLPS?[...a.pointLPS]:null,unit:null},u3(t,t.peakValue),u3(t,t.peakPoint))}if(t.volume&&t.mean){const a=t.volume.value,s=t.mean.value;t.lesionGlycolysis={name:"lesionGlycolysis",label:"Lesion Glycolysis",value:a*s,unit:`${t.volume.unit}·${e}`},u3(t,t.lesionGlycolysis)}return t};async function Mme({segImageIds:t,indices:e,unit:r,mode:n}){oc(xa.COMPUTE_STATISTICS,0);const{segmentationInfo:i,imageInfo:o}=MF(t),a=await il().executeTask("compute","calculateSegmentsStatisticsStack",{segmentationInfo:i,imageInfo:o,indices:e,mode:n});oc(xa.COMPUTE_STATISTICS,100);const s=i[0].spacing,c=i[0],l=o[0].voxelManager;if(n==="collective")return uy({stats:a,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l});{const f={};return Object.entries(a).forEach(([u,d])=>{f[u]=uy({stats:d,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l})}),f}}function Pme(t,e,r,n,i){const{pointIJK:o,pointLPS:a}=t;if(!o)return;const s=o.map((f,u)=>[f-e[u],f+e[u]]),c=(f,u)=>{const d=(u[0]-o[0])/e[0],h=(u[1]-o[1])/e[1],g=(u[2]-o[2])/e[2];return d*d+h*h+g*g<=1},l=({pointIJK:f,pointLPS:u})=>{const d=n.getAtIJKPoint(f);d!==void 0&&Uf.statsCallback({value:d,pointLPS:u,pointIJK:f})};return Uf.statsInit({storePointData:!1}),ST(r,{pointInShapeFn:c,callback:l,boundsIJK:s}),Uf.getStatistics({spacing:i})}const Rme={[St.GetStatistics]:function(t,e,r){const{indices:n}=r,{segmentationId:i,viewport:o}=e;UF({segmentationId:i,segmentIndices:n})}},mn={determineSegmentIndex:gme,dynamicThreshold:pme,erase:mme,islandRemoval:Sme,preview:_me,regionFill:Tme,setValue:Dme,threshold:bme,labelmapStatistics:Rme,ensureSegmentationVolumeFor3DManipulation:DF,ensureImageVolumeFor3DManipulation:bF},Df=class Df{constructor(e,...r){this._initialize=[],this._fill=[],this._onInteractionStart=[],this.fill=(n,i)=>{const o=this.initialize(n,i,St.Fill);if(!o)return;this._fill.forEach(c=>c(o));const{segmentationVoxelManager:a,segmentIndex:s}=o;return io(o.segmentationId,a.getArrayOfModifiedSlices(),s),o},this.onInteractionStart=(n,i)=>{const o=this.initialize(n,i);o&&this._onInteractionStart.forEach(a=>a.call(this,o))},this.addPreview=(n,i)=>{const o=this.initialize(n,i,St.AddPreview);if(o)return o},this.configurationName=e,this.compositions=r,r.forEach(n=>{const i=typeof n=="function"?n():n;if(i)for(const o in i){if(!Df.childFunctions[o])throw new Error(`Didn't find ${o} as a brush strategy`);Df.childFunctions[o](this,i[o])}}),this.strategyFunction=(n,i)=>this.fill(n,i);for(const n of Object.keys(Df.childFunctions))this.strategyFunction[n]=this[n]}initialize(e,r,n){const{viewport:i}=e,o=G4({operationData:r,viewport:i,strategy:this});if(!o)return null;const{imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c}=o,l=r.createMemo(r.segmentationId,s),f={operationName:n,...r,segmentIndex:r.segmentIndex,enabledElement:e,imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c,viewport:i,centerWorld:null,isInObject:null,isInObjectBoundsIJK:null,brushStrategy:this,memo:l};return this._initialize.forEach(u=>u(f)),f}};Df.COMPOSITIONS=mn,Df.childFunctions={[St.OnInteractionStart]:ts(St.OnInteractionStart,St.Initialize),[St.OnInteractionEnd]:ts(St.OnInteractionEnd,St.Initialize),[St.Fill]:ts(St.Fill),[St.Initialize]:ts(St.Initialize),[St.CreateIsInThreshold]:Fm(St.CreateIsInThreshold),[St.Interpolate]:ts(St.Interpolate,St.Initialize),[St.AcceptPreview]:ts(St.AcceptPreview,St.Initialize),[St.RejectPreview]:ts(St.RejectPreview,St.Initialize),[St.INTERNAL_setValue]:Fm(St.INTERNAL_setValue),[St.Preview]:Fm(St.Preview,!1),[St.ComputeInnerCircleRadius]:ts(St.ComputeInnerCircleRadius),[St.EnsureSegmentationVolumeFor3DManipulation]:ts(St.EnsureSegmentationVolumeFor3DManipulation),[St.EnsureImageVolumeFor3DManipulation]:ts(St.EnsureImageVolumeFor3DManipulation),[St.AddPreview]:ts(St.AddPreview),[St.GetStatistics]:Fm(St.GetStatistics),compositions:null};let Ss=Df;function ts(t,e){const r=`_${t}`;return(n,i)=>{n[r]||(n[r]=[]),n[r].push(i),n[t]||(n[t]=e?(o,a,...s)=>{const c=n[e](o,a,t);let l;return n[r].forEach(f=>{const u=f.call(n,c,...s);l||(l=u)}),l}:(o,...a)=>{n[r].forEach(s=>s.call(n,o,...a))})}}function Fm(t,e=!0){return(r,n)=>{if(r[t])throw new Error(`The singleton method ${t} already exists`);r[t]=e?n:(i,o,...a)=>(o.enabledElement=i,n.call(r,o,...a))}}function BF(t,e){const{center:r,radius:n}=t,i=t.radius2||n*n;return(e[0]-r[0])*(e[0]-r[0])+(e[1]-r[1])*(e[1]-r[1])+(e[2]-r[2])*(e[2]-r[2])<=i}const{transformWorldToIndex:KD,isEqual:f3}=Mn,GF={[St.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=bt(0,0,0);e.forEach(d=>{Ai(i,i,d)}),Ni(i,i,1/e.length),t.centerWorld=i,t.centerIJK=KD(n,i);const o=e.map(d=>r.worldToCanvas(d)),[a,s]=Yv(o),c=r.canvasToWorld(a),l=r.canvasToWorld(s),f=e.map(d=>KD(n,d)),u=Su(f,n.getDimensions());t.isInObject=WF({topLeftWorld:c,bottomRightWorld:l,center:i}),t.isInObjectBoundsIJK=u}};function WF(t){const{topLeftWorld:e,bottomRightWorld:r,center:n}=t,i=Math.abs(e[0]-r[0])/2,o=Math.abs(e[1]-r[1])/2,a=Math.abs(e[2]-r[2])/2,s=Math.max(i,o,a);if(f3(i,s)&&f3(o,s)&&f3(a,s)){const f={center:n,radius:s,radius2:s*s};return u=>BF(f,u)}const c={center:n,xRadius:i,yRadius:o,zRadius:a},{precalculated:l}=f4(c,{});return l}const zF=new Ss("Circle",mn.regionFill,mn.setValue,GF,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics),Lme=new Ss("CircleThreshold",mn.regionFill,mn.setValue,GF,mn.determineSegmentIndex,mn.dynamicThreshold,mn.threshold,mn.preview,mn.islandRemoval,mn.labelmapStatistics),G5=zF.strategyFunction,Ame=Lme.strategyFunction;function Nme(){throw new Error("Not yet implemented")}const{transformWorldToIndex:kme}=Mn,Vme={[St.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=bt(0,0,0);e.forEach(c=>{Ai(i,i,c)}),Ni(i,i,1/e.length),t.centerWorld=i,t.centerIJK=kme(n,i);const{boundsIJK:o,topLeftWorld:a,bottomRightWorld:s}=b1e(e.slice(0,2),n,r);t.isInObjectBoundsIJK=o,t.isInObject=WF({topLeftWorld:a,bottomRightWorld:s,center:i})}},W5=new Ss("Sphere",mn.regionFill,mn.setValue,Vme,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics,mn.ensureSegmentationVolumeFor3DManipulation),$F=W5.strategyFunction,Fme=new Ss("SphereThreshold",...W5.compositions,mn.dynamicThreshold,mn.threshold,mn.ensureSegmentationVolumeFor3DManipulation,mn.ensureImageVolumeFor3DManipulation),Ume=new Ss("SphereThreshold",...W5.compositions,mn.dynamicThreshold,mn.threshold,mn.islandRemoval,mn.ensureSegmentationVolumeFor3DManipulation,mn.ensureImageVolumeFor3DManipulation),Bme=Fme.strategyFunction,Gme=Ume.strategyFunction,Wme=new Ss("EraseSphere",mn.erase,...W5.compositions),jF=Wme.strategyFunction,zme=new Ss("EraseCircle",mn.erase,...zF.compositions),HF=zme.strategyFunction,{VoxelManager:OC,RLEVoxelMap:$me}=Mn;function MC(t,e){return qF(t,e)}function KF(t){const{segmentationVoxelManager:e,undoVoxelManager:r,redoVoxelManager:n}=this,i=t===!1?n:r;i.forEach(({value:a,pointIJK:s})=>{e.setAtIJKPoint(s,a)});const o=i.getArrayOfModifiedSlices();io(this.segmentationId,o)}function qF(t,e){const r=OC.createRLEHistoryVoxelManager(e);return{segmentationId:t,restoreMemo:KF,commitMemo:jme,segmentationVoxelManager:e,voxelManager:r,id:Dn(),operationType:"labelmap"}}function jme(){if(this.redoVoxelManager)return!0;if(!this.voxelManager.modifiedSlices.size)return!1;const{segmentationVoxelManager:t}=this,e=OC.createRLEHistoryVoxelManager(t);$me.copyMap(e.map,this.voxelManager.map);for(const n of this.voxelManager.modifiedSlices.keys())e.modifiedSlices.add(n);this.undoVoxelManager=e;const r=OC.createRLEVolumeVoxelManager({dimensions:this.segmentationVoxelManager.dimensions});return this.redoVoxelManager=r,e.forEach(({index:n,pointIJK:i,value:o})=>{const a=t.getAtIJKPoint(i);a!==o&&r.setAtIndex(n,a)}),!0}const Hme=Object.freeze(Object.defineProperty({__proto__:null,createLabelmapMemo:MC,createRleMemo:qF,restoreMemo:KF},Symbol.toStringTag,{value:"Module"})),{isEqual:Um}=Mn,Kme=bt(1,0,0),qme=bt(0,1,0),Xme=bt(0,0,1),qD=[Kme,qme,Xme];function XF(t){const e=rr(Ve(),t[0],t[1]),r=rr(Ve(),t[0],t[2]),n=XD(e,qD),i=XD(r,qD);return[...n,...i].every(a=>Um(a,0)||Um(a,90)||Um(a,180)||Um(a,270))}function XD(t,e){return e.map(r=>N_(t,r)*180/Math.PI)}const{transformWorldToIndex:YF}=Mn,JF={[St.Initialize]:t=>{const{points:e,imageVoxelManager:r,viewport:n,segmentationImageData:i,segmentationVoxelManager:o}=t;if(!e)return;const a=bt(0,0,0);e.forEach(l=>{Ai(a,a,l)}),Ni(a,a,1/e.length),t.centerWorld=a,t.centerIJK=YF(i,a);const{boundsIJK:s,pointInShapeFn:c}=Yme(n,e,i);t.isInObject=c,t.isInObjectBoundsIJK=s}};function Yme(t,e,r){let n=e.map(w=>YF(r,w));n=n.map(w=>w.map(x=>Math.round(x)));const i=Su(n,r.getDimensions()),a=t instanceof lr||XF(n),s=r.getDirection(),c=r.getSpacing(),{viewPlaneNormal:l}=t.getCamera(),f=Au({direction:s,spacing:c},l),u=ik(e);let[[d,h],[g,p],[v,y]]=u;return d-=f,h+=f,g-=f,p+=f,v-=f,y+=f,{boundsIJK:i,pointInShapeFn:a?()=>!0:w=>{const[x,C,S]=w,_=x>=d&&x<=h,T=C>=g&&C<=p,E=S>=v&&S<=y;return _&&T&&E}}}const Jme=new Ss("Rectangle",mn.regionFill,mn.setValue,JF,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics),Zme=new Ss("RectangleThreshold",mn.regionFill,mn.setValue,JF,mn.determineSegmentIndex,mn.dynamicThreshold,mn.threshold,mn.preview,mn.islandRemoval,mn.labelmapStatistics),j4=Jme.strategyFunction,Qme=Zme.strategyFunction,e2e=Object.freeze(Object.defineProperty({__proto__:null,fillInsideCircle:G5,fillInsideRectangle:j4,fillOutsideCircle:Nme,thresholdInsideRectangle:Qme},Symbol.toStringTag,{value:"Module"})),ep=class ep extends ai{constructor(e,r){super(e,r),this.memoMap=new Map,this.acceptedMemoIds=new Map,this.centerSegmentIndexInfo={segmentIndex:null,hasSegmentIndex:!1,hasPreviewIndex:!1,changedIndices:[]}}_historyRedoHandler(e){const{id:r,operationType:n}=e.detail;if(n==="labelmap"){if(this.acceptedMemoIds.has(r)){this._hoverData=null;const i=this.acceptedMemoIds.get(r),o=i==null?void 0:i.element,a=this.getOperationData(o);a.segmentIndex=i==null?void 0:i.segmentIndex,o&&this.applyActiveStrategyCallback(Ce(o),a,St.AcceptPreview)}this._previewData.isDrag=!0}}get _previewData(){return ep.previewData}createMemo(e,r){const n=r.id;if(this.memo&&this.memo.segmentationVoxelManager===r)return this.memo;let i=this.memoMap.get(n);return i?i.redoVoxelManager&&(i=MC(e,r),this.memoMap.set(n,i)):(i=MC(e,r),this.memoMap.set(n,i)),this.memo=i,i}createEditData(e){const r=Ce(e),{viewport:n}=r,i=ed(n.id);if(!i){const l=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"No active segmentation detected, create a segmentation representation before using the brush tool"},cancelable:!0});return Ke.dispatchEvent(l),null}const{segmentationId:o}=i,a=dd(o),{representationData:s}=Ln(o);return this.getEditData({viewport:n,representationData:s,segmentsLocked:a,segmentationId:o})}getEditData({viewport:e,representationData:r,segmentsLocked:n,segmentationId:i}){var o,a,s;if(e instanceof Ir){const{volumeId:c}=r[Dt.Labelmap],l=e.getActors();if(e instanceof lr){const g=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"Cannot perform brush operation on the selected viewport"},cancelable:!0});return Ke.dispatchEvent(g),null}const u=l.map(g=>Le.getVolume(g.referencedId)),d=Le.getVolume(c),h=((o=u.find(g=>$t(g.dimensions,d.dimensions)))==null?void 0:o.volumeId)||((a=u[0])==null?void 0:a.volumeId);return{volumeId:c,referencedVolumeId:((s=this.configuration.threshold)==null?void 0:s.volumeId)??h,segmentsLocked:n}}else{const c=Vu(e.id,i);return c?{imageId:c,segmentsLocked:n}:void 0}}createHoverData(e,r){const n=Ce(e),{viewport:i}=n,o=i.getCamera(),{viewPlaneNormal:a,viewUp:s}=o,c=[i.id],{segmentIndex:l,segmentationId:f,segmentColor:u}=this.getActiveSegmentationData(i)||{};return{brushCursor:{metadata:{viewPlaneNormal:[...a],viewUp:[...s],FrameOfReferenceUID:i.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:u},data:{}},centerCanvas:r,segmentIndex:l,viewport:i,segmentationId:f,segmentColor:u,viewportIdsToRender:c}}getActiveSegmentationData(e){const r=e.id,n=ed(r);if(!n)return;const{segmentationId:i}=n,o=ea(i);if(!o)return;const a=el(r,i,o);return{segmentIndex:o,segmentationId:i,segmentColor:a}}getOperationData(e){var v,y,m,w;const r=this._editData||this.createEditData(e),{segmentIndex:n,segmentationId:i,brushCursor:o}=this._hoverData||this.createHoverData(e),{data:a,metadata:s={}}=o||{},{viewPlaneNormal:c,viewUp:l}=s,f=(y=(v=this.configuration.preview)==null?void 0:v.previewColors)==null?void 0:y[n],{viewport:u}=Ce(e),d=el(u.id,i,n);if(!f&&!d)return;let h=null,g=null;return(m=this.configuration.preview)!=null&&m.enabled&&(h=f||t2e(...d),g=255),{...r,points:(w=a==null?void 0:a.handles)==null?void 0:w.points,segmentIndex:n,viewPlaneNormal:c,previewOnHover:!this._previewData.isDrag,toolGroupId:this.toolGroupId,segmentationId:i,viewUp:l,centerSegmentIndexInfo:this.centerSegmentIndexInfo,activeStrategy:this.configuration.activeStrategy,configuration:this.configuration,previewColor:h,previewSegmentIndex:g,createMemo:this.createMemo.bind(this)}}addPreview(e=this._previewData.element,r){const{_previewData:n}=this,i=r==null?void 0:r.acceptReject;i===!0?this.acceptPreview(e):i===!1&&this.rejectPreview(e);const o=Ce(e),a=this.applyActiveStrategyCallback(o,this.getOperationData(e),St.AddPreview);return n.isDrag=!0,a}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Ce(e);this.applyActiveStrategyCallback(r,this.getOperationData(e),St.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1}acceptPreview(e=this._previewData.element){if(!e)return;const r=this.getOperationData(e);this.memo&&this.memo.id&&this.acceptedMemoIds.set(this.memo.id,{element:e,segmentIndex:r.segmentIndex});const n=Ce(e);this.applyActiveStrategyCallback(n,r,St.AcceptPreview),this.doneEditMemo(),this._previewData.preview=null,this._previewData.isDrag=!1}static viewportContoursToLabelmap(e,r){var v;const n=(r==null?void 0:r.removeContours)??!0,i=S1(),o=L1(e,i);if(!(o!=null&&o.length))return;const a=o.filter(y=>{var m,w;return(w=(m=y.data.contour)==null?void 0:m.polyline)==null?void 0:w.length});if(!a.length)return;const c=new ep({},{configuration:{strategies:{FILL_INSIDE_CIRCLE:G5},activeStrategy:"FILL_INSIDE_CIRCLE"}}).addPreview(e.element),{memo:l,segmentationId:f}=c,u=l==null?void 0:l.voxelManager,d=u.sourceVoxelManager||u,{dimensions:h}=u,g=e.getDefaultActor().actor.getMapper().getInputData();for(const y of a){const m=[[1/0,-1/0],[1/0,-1/0],[1/0,-1/0]],{polyline:w}=y.data.contour;for(const I of w)g.worldToIndex(I).forEach((M,L)=>{m[L][0]=Math.min(m[L][0],M),m[L][1]=Math.max(m[L][1],M)});m.forEach((I,P)=>{I[0]=Math.round(Math.max(0,I[0])),I[1]=Math.round(Math.min(h[P]-1,I[1]))});const x=ea(f),C=((v=y.data.handles)==null?void 0:v[0])||w[0],S=g.worldToIndex(C).map(Math.round),_=d.getAtIJKPoint(S)||0;let T=!1,E=!1;for(const I of w){const P=g.worldToIndex(I).map(Math.round),M=d.getAtIJKPoint(P);M===_?T=!0:M>=0&&(E=!0)}const b=T&&E?_:_===0?x:0;for(let I=m[0][0];I<=m[0][1];I++)for(let P=m[1][0];P<=m[1][1];P++)for(let M=m[2][0];M<=m[2][1];M++){const L=g.indexToWorld([I,P,M]);v4(L,w)&&u.setAtIJK(I,P,M,b)}n&&gn(y.annotationUID)}const p=u.getArrayOfModifiedSlices();io(f,p)}};ep.previewData={preview:null,element:null,timerStart:0,timer:null,startPoint:[NaN,NaN],isDrag:!1};let rd=ep;function t2e(t,e,r,n,i=.4){return[Math.round(t+(255-t)*i),Math.round(e+(255-e)*i),Math.round(r+(255-r)*i),n]}class z5 extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE_CIRCLE:G5,ERASE_INSIDE_CIRCLE:HF,FILL_INSIDE_SPHERE:$F,ERASE_INSIDE_SPHERE:jF,THRESHOLD_INSIDE_CIRCLE:Ame,THRESHOLD_INSIDE_SPHERE:Bme,THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL:Gme},defaultStrategy:"FILL_INSIDE_CIRCLE",activeStrategy:"FILL_INSIDE_CIRCLE",brushSize:25,useCenterSegmentIndex:!1,preview:{enabled:!1,previewColors:{0:[255,255,255,128]},previewTimeMs:250,previewMoveDistance:8,dragMoveDistance:4,dragTimeMs:500},actions:{[St.AcceptPreview]:{method:St.AcceptPreview,bindings:[{key:"Enter"}]},[St.RejectPreview]:{method:St.RejectPreview,bindings:[{key:"Escape"}]},[St.Interpolate]:{method:St.Interpolate,bindings:[{key:"i"}],configuration:{useBallStructuringElement:!0,noUseDistanceTransform:!0,noUseExtrapolation:!0}},interpolateExtrapolation:{method:St.Interpolate,bindings:[{key:"e"}],configuration:{}}}}}){super(e,r),this.onSetToolPassive=n=>{this.disableCursor()},this.onSetToolEnabled=()=>{this.disableCursor()},this.onSetToolDisabled=n=>{this.disableCursor()},this.preMouseDownCallback=n=>{const i=n.detail,{element:o}=i,a=Ce(o);this._editData=this.createEditData(o),this._activateDraw(o),Ot(o),n.preventDefault(),this._previewData.isDrag=!1,this._previewData.timerStart=Date.now();const s=this._hoverData||this.createHoverData(o);Pe(s.viewportIdsToRender);const c=this.getOperationData(o);return this.applyActiveStrategyCallback(a,c,St.OnInteractionStart),!0},this.mouseMoveCallback=n=>{if(this.mode===An.Active){if(this.updateCursor(n),!this.configuration.preview.enabled)return;const{previewTimeMs:i,previewMoveDistance:o,dragMoveDistance:a}=this.configuration.preview,{currentPoints:s,element:c}=n.detail,{canvas:l}=s,{startPoint:f,timer:u,timerStart:d,isDrag:h}=this._previewData;if(h)return;const g=yr(l,f),p=Date.now()-d;if((g>o||p>i&&g>a)&&(u&&(window.clearTimeout(u),this._previewData.timer=null),h||this.rejectPreview(c)),!this._previewData.timer){const v=window.setTimeout(this.previewCallback,250);Object.assign(this._previewData,{timerStart:Date.now(),timer:v,startPoint:l,element:c})}}},this.previewCallback=()=>{if(this._previewData.isDrag){this._previewData.timer=null;return}this._previewData.timer=null;const n=this.getOperationData(this._previewData.element),i=Ce(this._previewData.element);if(!i)return;const{viewport:o}=i,a=this.configuration.activeStrategy,s=G4({operationData:n,viewport:o,strategy:a});if(!n)return;const c=this.createMemo(n.segmentationId,s.segmentationVoxelManager);this._previewData.preview=this.applyActiveStrategyCallback(Ce(this._previewData.element),{...n,...s,memo:c},St.Preview)},this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o);this.updateCursor(n);const{viewportIdsToRender:c}=this._hoverData;Pe(c);const l=yr(a.canvas,this._previewData.startPoint),{dragTimeMs:f,dragMoveDistance:u}=this.configuration.preview;!this._previewData.isDrag&&Date.now()-this._previewData.timerStart{const i=n.detail,{element:o}=i,a=Ce(o),s=this.getOperationData(o);!this._previewData.preview&&!this._previewData.isDrag&&this.applyActiveStrategy(a,s),this.doneEditMemo(),this._deactivateDraw(o),zt(o),this.updateCursor(n),this._editData=null,this.applyActiveStrategyCallback(a,s,St.OnInteractionEnd),this._previewData.isDrag||this.acceptPreview(o)},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}disableCursor(){this._hoverData=void 0,this.rejectPreview()}updateCursor(e){const r=e.detail,{element:n}=r,{currentPoints:i}=r,o=i.canvas;this._hoverData=this.createHoverData(n,o),this._calculateCursor(n,o),this._hoverData&&Pe(this._hoverData.viewportIdsToRender)}_calculateCursor(e,r){const n=Ce(e),{viewport:i}=n,{canvasToWorld:o}=i,a=i.getCamera(),{brushSize:s}=this.configuration,c=bt(a.viewUp[0],a.viewUp[1],a.viewUp[2]),l=bt(a.viewPlaneNormal[0],a.viewPlaneNormal[1],a.viewPlaneNormal[2]),f=Ve();Rn(f,c,l);const u=o([r[0],r[1]]),d=Ve(),h=Ve(),g=Ve(),p=Ve();for(let x=0;x<=2;x++)d[x]=u[x]-c[x]*s,h[x]=u[x]+c[x]*s,g[x]=u[x]-f[x]*s,p[x]=u[x]+f[x]*s;if(!this._hoverData)return;const{brushCursor:v}=this._hoverData,{data:y}=v;y.handles===void 0&&(y.handles={}),y.handles.points=[d,h,g,p];const m=this.configuration.activeStrategy,w=this.configuration.strategies[m];typeof(w==null?void 0:w.computeInnerCircleRadius)=="function"&&w.computeInnerCircleRadius({configuration:this.configuration,viewport:i}),y.invalidated=!1}getStatistics(e,r){if(!e)return;const n=Ce(e);return this.applyActiveStrategyCallback(n,this.getOperationData(e),St.GetStatistics,r)}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Ce(e);r&&(this.applyActiveStrategyCallback(r,this.getOperationData(e),St.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1)}acceptPreview(e=this._previewData.element){e&&super.acceptPreview(e)}interpolate(e,r){if(!e)return;const n=Ce(e);this._previewData.preview=this.applyActiveStrategyCallback(n,this.getOperationData(e),St.Interpolate,r.configuration),this._previewData.isDrag=!0}invalidateBrushCursor(){if(this._hoverData===void 0)return;const{data:e}=this._hoverData.brushCursor,{viewport:r}=this._hoverData;e.invalidated=!0;const{segmentColor:n}=this.getActiveSegmentationData(r)||{};this._hoverData.brushCursor.metadata.segmentColor=n}renderAnnotation(e,r){var m,w;if(!this._hoverData)return;const{viewport:n}=e;if(!this._hoverData.viewportIdsToRender.includes(n.id))return;const o=this._hoverData.brushCursor;if(o.data.invalidated===!0){const{centerCanvas:x}=this._hoverData,{element:C}=n;this._calculateCursor(C,x)}const a=o.metadata;if(!a)return;const s=a.brushCursorUID,c=o.data,{points:l}=c.handles,f=l.map(x=>n.worldToCanvas(x)),u=f[0],d=f[1],h=[Math.floor((u[0]+d[0])/2),Math.floor((u[1]+d[1])/2)],g=Math.abs(u[1]-Math.floor((u[1]+d[1])/2)),p=`rgb(${((m=a.segmentColor)==null?void 0:m.slice(0,3))||[0,0,0]})`;if(!n.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}No(r,s,"0",h,g,{color:p,lineDash:this.centerSegmentIndexInfo.segmentIndex===0?[1,2]:null});const{dynamicRadiusInCanvas:y}=((w=this.configuration)==null?void 0:w.threshold)||{dynamicRadiusInCanvas:0};y&&No(r,s,"1",h,y,{color:p})}}z5.toolName="Brush";function _h(t,e){const r=Kr(t);if(r===void 0)return;const n=r._toolInstances;return Object.keys(n).length?e&&n[e]?[n[e]]:Object.values(n).filter(o=>o instanceof z5):void 0}function n2e(t,e,r){const n=Kr(t);if(n===void 0)return;_h(t,r).forEach(l=>{l.configuration.brushSize=e,l.invalidateBrushCursor()});const o=n.getViewportsInfo(),a=Object.keys(o).map(l=>o[l]);if(!a.length)return;const{renderingEngineId:s}=a[0],c=n.getViewportIds();Jr(s),Pe(c)}function r2e(t,e){const r=Kr(t);if(r===void 0)return;const n=r._toolInstances;if(!Object.keys(n).length)return;const o=_h(t,e)[0];if(o)return o.configuration.brushSize}function i2e(t,e){const r=Kr(t);if(r===void 0||(_h(t).forEach(a=>{a.configuration.activeStrategy.toLowerCase().includes("threshold")&&(a.configuration={...a.configuration,threshold:{...a.configuration.threshold,...e}})}),!r.getViewportsInfo().length))return;const o=r.getViewportIds();Pe(o)}function o2e(t){const e=Kr(t);if(e===void 0)return;const r=e._toolInstances;if(!Object.keys(r).length)return;const i=_h(t)[0];if(i)return i.configuration.threshold.range}const tp=class tp{static statsInit(e){const{storePointData:r,indices:n,mode:i}=e;this.mode=i,this.indices=n,this.calculators.clear(),this.mode==="individual"?n.forEach(o=>{this.calculators.set(o,new HD({storePointData:r}))}):this.calculators.set(n,new HD({storePointData:r}))}static statsCallback(e){const{segmentIndex:r,...n}=e;if(!r)throw new Error("Segment index is required for stats calculation");const i=this.mode==="individual"?this.calculators.get(r):this.calculators.get(this.indices);if(!i)throw new Error(`No calculator found for segment ${r}`);i.statsCallback(n)}static getStatistics(e){if(this.mode==="individual"){const n={};return this.calculators.forEach((i,o)=>{n[o]=i.getStatistics(e)}),n}return this.calculators.get(this.indices).getStatistics(e)}};tp.calculators=new Map,tp.indices=[],tp.mode="collective";let PC=tp;function a2e(t,e,r,n,i){if(!i)throw new Error("Segmentation ID is required to be passed inside thresholdSegmentationByRange");const{baseVolumeIdx:o,volumeInfoList:a}=ok(t,r),{voxelManager:s}=a[o],c=s,l=t.voxelManager.getScalarDataLength(),f=t.voxelManager;return a.forEach(u=>{const{volumeSize:d}=u;d===l?c2e(f,c,e,u):s2e(f,c,e,u,a,o,n)}),io(i),t}function s2e(t,e,r,n,i,o,a){const{imageData:s,lower:c,upper:l,dimensions:f}=n;let u,d,h;const g=t.getScalarDataLength();for(let p=0;p{u=u+1,w>=h.lower&&w<=h.upper&&(d=d+1)};u=0,d=0,h={lower:c,upper:l};let m=!1;t.forEach(y,{imageData:s,boundsIJK:v}),m=a===0?d>0:d===u,t.setAtIndex(p,m?r:0)}return{total:u,range:h,overlaps:d}}function c2e(t,e,r,n){const{lower:i,upper:o}=n,a=t.getScalarDataLength();for(let s=0;s=i&&c<=o?r:0)}}function YD(t,e,r){const n=r.toIJK(t),i=r.toIJK(e),o=Ve(),{testIJK:a}=r,s=En(Ve(),n,i),c=Math.round(Math.max(...s.map(Math.abs)));if(c<2)return!0;const l=Ni(Ve(),s,1/c);for(let f=1;f{const l=Ai(Ve(),s,c).map(v=>v/2),f=e.worldToIndex(l).map(Math.round),[u,d,h]=f,g=u+d*o+h*a,p=r.getAtIndex(g);return p===n||(i==null?void 0:i.has(p))},toIJK:s=>e.worldToIndex(s),testIJK:s=>{const[c,l,f]=s,u=Math.round(c)+Math.round(l)*o+Math.round(f)*a,d=r.getAtIndex(u);return d===n||(i==null?void 0:i.has(d))}}}function u2e(t,e,r){const n=Le.getVolume(t);if(!n){console.warn(`No volume found for ${t}`);return}return l2e({dimensions:n.dimensions,imageData:n.imageData,voxelManager:n.voxelManager,segmentIndex:e,containedSegmentIndices:r})}const Zh=.01;function f2e(t,e,r){const{sliceContours:n}=t,{segmentIndex:i,containedSegmentIndices:o}=r;let a;const s=u2e(e,i,o);for(const c of n){const l=d2e(c,s,a);l&&(a=l)}return a&&Object.assign(a,r),a}function d2e(t,e,r={maxMajor:0,maxMinor:0}){const{points:n}=t.polyData,{maxMinor:i,maxMajor:o}=r;let a=o*o,s=i*i,c;for(let v=0;vZh||e.testCenter(m,w)&&YD(m,w,e)&&(s=x,d=[v,y])}if(!d)return;s=Math.sqrt(s);const h=n[d[0]],g=n[d[1]];return{majorAxis:[l,f],minorAxis:[h,g],maxMajor:a,maxMinor:s,...t}}async function ZF(t){const e=await PF({segmentations:t});if(!(e!=null&&e.length)||!e[0].sliceContours.length)return;const{segments:r=[null,{label:"Unspecified",color:null,containedSegmentIndices:null}]}=t,n=Sh(t.segmentationId);if(!n)return;const i=r.findIndex(o=>!!o);if(i!==-1)return r[i].segmentIndex=i,f2e(e[0],n.volumeId,r[i])}function QF(t,e){const{majorAxis:r,minorAxis:n,label:i="",sliceIndex:o}=t,[a,s]=r,[c,l]=n,f=[a,s,c,l];return{highlighted:!0,invalidated:!0,metadata:{toolName:"Bidirectional",...e.getViewReference({sliceIndex:o})},data:{handles:{points:f,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:i,cachedStats:{}},isLocked:!1,isVisible:!0}}const{transformWorldToIndex:Bm}=Mn,t0=class t0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:h2e}}){super(e,r),this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles;let u=c.worldToCanvas(f[0]),d=c.worldToCanvas(f[1]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=hi([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]);return g<=a||(u=c.worldToCanvas(f[2]),d=c.worldToCanvas(f[3]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=hi([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]),g<=a)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),Ot(a),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,c=i.data;i.highlighted=!0;let l=!1,f;o.worldPosition?l=!0:f=c.handles.points.findIndex(g=>g===o);const u=_t(s,this.getToolName());Ot(s),this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;this.doneEditMemo(),f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);if(this.editData.handleIndex!==void 0){const{points:d}=f.handles,h=ki(d[0],d[1]);if(ki(d[2],d[3])>h){const p=[[...d[2]],[...d[3]]],v=[...d[0]],y=[...d[1]],m=qt();Va(m,p[1][0]-p[0][0],p[1][1]-p[1][0]);const w=qt();Va(w,-m[1],m[0]);const x=qt();Va(x,y[0]-v[0],y[1]-v[0]);let C;k_(x,w)>0?C=[v,y]:C=[y,v],f.handles.points=[p[0],p[1],C[0],C[1]]}}this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c}=s,{worldToCanvas:l}=c,{annotation:f,viewportIdsToRender:u,handleIndex:d,newAnnotation:h}=this.editData;this.createMemo(a,f,{newAnnotation:h});const{data:g}=f,p=o.world;g.handles.points[d]=[...p];const v=g.handles.points.map(l),y={longLineSegment:{start:{x:v[0][0],y:v[0][1]},end:{x:v[1][0],y:v[1][1]}},shortLineSegment:{start:{x:v[2][0],y:v[2][1]},end:{x:v[3][0],y:v[3][1]}}},w=yr(v[0],v[1])/3,x=y.longLineSegment.start.x-y.longLineSegment.end.x,C=y.longLineSegment.start.y-y.longLineSegment.end.y,S=Math.sqrt(x*x+C*C),_=x/S,T=C/S,E=(y.longLineSegment.start.x+y.longLineSegment.end.x)/2,D=(y.longLineSegment.start.y+y.longLineSegment.end.y)/2,b=E+w*T,I=D-w*_,P=E-w*T,M=D+w*_;g.handles.points[2]=c.canvasToWorld([b,I]),g.handles.points[3]=c.canvasToWorld([P,M]),f.invalidated=!0,Pe(u),tn(f,a,Ht.HandlesUpdated),this.editData.hasMoved=!0},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else this._dragModifyHandle(n),a.invalidated=!0;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragModifyHandle=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c}=s,{annotation:l,handleIndex:f}=this.editData,{data:u}=l,d=o.world,h=[c.worldToCanvas(u.handles.points[0]),c.worldToCanvas(u.handles.points[1]),c.worldToCanvas(u.handles.points[2]),c.worldToCanvas(u.handles.points[3])],g={start:{x:h[0][0],y:h[0][1]},end:{x:h[1][0],y:h[1][1]}},p={start:{x:h[2][0],y:h[2][1]},end:{x:h[3][0],y:h[3][1]}},v=[...d],y=c.worldToCanvas(v);if(f===0||f===1){const w=h[f===0?1:0],x=Va(qt(),y[0]-w[0],y[1]-w[1]),C=Va(qt(),h[f][0]-w[0],h[f][1]-w[1]);Nc(x,x),Nc(C,C);const S={start:{x:w[0],y:w[1]},end:{x:y[0],y:y[1]}};if(this._movingLongAxisWouldPutItThroughShortAxis(S,p))return;const _=w,T=this._getSignedAngle(C,x);let E=h[2][0],D=h[2][1],b=h[3][0],I=h[3][1];E-=_[0],D-=_[1],b-=_[0],I-=_[1];const P=E*Math.cos(T)-D*Math.sin(T),M=E*Math.sin(T)+D*Math.cos(T),L=b*Math.cos(T)-I*Math.sin(T),V=b*Math.sin(T)+I*Math.cos(T);E=P+_[0],D=M+_[1],b=L+_[0],I=V+_[1];const G=c.canvasToWorld([E,D]),A=c.canvasToWorld([b,I]);u.handles.points[f]=v,u.handles.points[2]=G,u.handles.points[3]=A}else{const m=f===2?3:2,w={longLineSegment:{start:g.start,end:g.end},shortLineSegment:{start:p.start,end:p.end}},x=Wr(qt(),[w.longLineSegment.end.x,w.longLineSegment.end.y],[w.longLineSegment.start.x,w.longLineSegment.start.y]),C=Nc(qt(),x),S=Wr(qt(),[y[0],y[1]],[h[f][0],h[f][1]]),_=xv(S),T=this._getSignedAngle(C,S),E=Math.cos(T)*_,D=jK(qt(),[h[m][0],h[m][1]],C,E);if(this._movingLongAxisWouldPutItThroughShortAxis({start:{x:y[0],y:y[1]},end:{x:D[0],y:D[1]}},{start:{x:w.longLineSegment.start.x,y:w.longLineSegment.start.y},end:{x:w.longLineSegment.end.x,y:w.longLineSegment.end.y}})||!Zv([y[0],y[1]],[D[0],D[1]],[g.start.x,g.start.y],[g.end.x,g.end.y]))return;u.handles.points[m]=c.canvasToWorld(D),u.handles.points[f]=v}},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback)},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!0;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(Y));u.annotationUID=g;const{color:w,lineWidth:x,lineDash:C,shadow:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:u});if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let _;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(_=[m[y]]),_&&ir(i,g,"0",_,{color:w});const T=`${g}-line-1`,E=`${g}-line-2`;vn(i,g,"0",m[0],m[1],{color:w,lineDash:C,lineWidth:x,shadow:S},T),vn(i,g,"1",m[2],m[3],{color:w,lineDash:C,lineWidth:x,shadow:S},E),o=!0;const I=this.getLinkedTextBoxStyle(u,h);if(!I.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const P=this.configuration.getTextLines(p,l);if(!P||P.length===0)continue;let M;p.handles.textBox.hasMoved||(M=na(m),p.handles.textBox.worldPosition=a.canvasToWorld(M));const L=a.worldToCanvas(p.handles.textBox.worldPosition),G=qi(i,g,"1",P,L,m,{},I),{x:A,y:k,width:F,height:j}=G;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([A,k]),topRight:a.canvasToWorld([A+F,k]),bottomLeft:a.canvasToWorld([A,k+j]),bottomRight:a.canvasToWorld([A+F,k+j])}}return o},this._movingLongAxisWouldPutItThroughShortAxis=(n,i)=>{const o=qt();Va(o,i.end.x-i.start.x,i.end.y-i.start.y),Nc(o,o);const a={start:{x:i.start.x-o[0]*10,y:i.start.y-o[1]*10},end:{x:i.end.x+o[0]*10,y:i.end.y+o[1]*10}};return!Zv([a.start.x,a.start.y],[a.end.x,a.end.y],[n.start.x,n.start.y],[n.end.x,n.end.y])},this._calculateCachedStats=(n,i,o)=>{const{data:a}=n,{element:s}=o.viewport,c=a.handles.points[0],l=a.handles.points[1],f=a.handles.points[2],u=a.handles.points[3],{cachedStats:d}=a,h=Object.keys(d);for(let p=0;pL?M:L,G=M>L?L:M,A=M>L?b:P,k=M>L?P:b;this._isInsideVolume(x,C,S,_,w)?this.isHandleOutsideImage=!1:this.isHandleOutsideImage=!0,d[v]={length:V,width:G,unit:A,widthUnit:k}}const g=n.invalidated;return n.invalidated=!1,g&&tn(n,s,Ht.StatsUpdated),d},this._isInsideVolume=(n,i,o,a,s)=>sr(n,s)&&sr(i,s)&&sr(o,s)&&sr(a,s),this._getSignedAngle=(n,i)=>Math.atan2(n[0]*i[1]-n[1]*i[0],n[0]*i[0]+n[1]*i[1]),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,o=n.world,a=Ce(i),{viewport:s,renderingEngine:c}=a;this.isDrawing=!0;const l=s.getCamera(),{viewPlaneNormal:f,viewUp:u}=l,d=this.getReferencedImageId(s,o,f,u),h=s.getFrameOfReferenceUID(),g={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...f],viewUp:[...u],FrameOfReferenceUID:h,referencedImageId:d,...s.getViewReference({points:[o]})},data:{handles:{points:[[...o],[...o],[...o],[...o]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};nn(g,i);const p=_t(i,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(i),Ot(i),e.preventDefault(),Pe(p),g}_calculateLength(e,r){const n=e[0]-r[0],i=e[1]-r[1],o=e[2]-r[2];return Math.sqrt(n*n+i*i+o*o)}};t0.toolName="Bidirectional",t0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=t0.hydrateBase(t0,i,r[0],n),[f,u]=r,[d,h]=f,[g,p]=u,v=[d,h,g,p],{toolInstance:y,...m}=n||{},w={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:v,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...m}};return nn(w,l.element),Pe([l.id]),w};let Hp=t0;function h2e(t,e){const{cachedStats:r,label:n}=t,{length:i,width:o,unit:a}=r[e],s=[];return n&&s.push(n),i===void 0||s.push(`L: ${an(i)} ${a||a}`,`W: ${an(o)} ${a}`),s}async function g2e(t,e){console.warn("Deprecation Alert: There is a new getSegmentLargestBidirectional function that handles volume, stack and individual segment cases properly. This function is deprecated and will be removed in a future version.");const{data:r}=e,n=Ce(t),i=(r.getSegment||p2e)(n,r);if(!i)return;const o=n.viewport.getFrameOfReferenceUID(),a=U5(),{segmentIndex:s,segmentationId:c}=i,l=Rr.getAnnotations(this.toolName||Hp.toolName,o);let f=!1;const u=l.filter(h=>{const g=h.data.segment;return g?(g.segmentationId===c&&g.segmentIndex===s&&(f=!0,h.data.segment=g),!0):!1});f||u.push({data:{segment:i}});let d;if(u.forEach(async h=>{const g=[],p=h.data.segment,{segmentIndex:v,segmentationId:y}=p;g[v]=p,Rr.removeAnnotation(h.annotationUID);const m=await ZF({...a.find(C=>C.segmentationId===y),segments:g});if(!m)return;const w=QF(m,n.viewport);w.annotationUID=h.annotationUID,w.data.segment=p;const x=Rr.addAnnotation(w,o);if(p.segmentIndex===i.segmentIndex&&p.segmentationId===i.segmentationId){d=m;const{style:C}=i;C&&HT.setAnnotationStyles(x,C)}}),d){const{sliceIndex:h}=d,g=n.viewport.getImageIds();Aa(t,{imageIndex:g.length-1-h}),n.viewport.render()}else console.warn("No bidirectional found");return d}function p2e(t,e){var a;const r=U5();if(!r.length)return;const n=e.segmentationId||r[0].segmentationId,i=e.segmentIndex??ea(n);if(!i)return;const o=(a=e.segmentData)==null?void 0:a.get(i);return{label:`Segment ${i}`,segmentIndex:i,segmentationId:n,...o}}function eU(t){const e=Kr(t);if(e===void 0)return;_h(t).forEach(a=>{a.invalidateBrushCursor()});const n=e.getViewportsInfo();if(!Object.keys(n).map(a=>n[a]).length)return;const o=e.getViewportIds();Pe(o)}function H4(t,e,r={}){const n=Ln(t),i=n.representationData,o=(r==null?void 0:r.representationType)??Object.keys(i)[0];if(!o)throw new Error(`Segmentation ${t} does not have any representations`);switch(o){case Dt.Labelmap:return m2e(n,e,r);case Dt.Contour:return v2e(n,e,r);default:return}}function m2e(t,e,{viewport:r}){const n=t.representationData.Labelmap;if(r instanceof Ir){const{volumeId:h}=n,g=Le.getVolume(h);return g?g.imageData.getScalarValueFromWorld(e):void 0}const i=Qc(r.id,t.segmentationId);if(i.length>1){console.warn("Segment selection for labelmaps with multiple imageIds in stack viewports is not supported yet.");return}const o=i[0];if(!Le.getImage(o))return;const s=_5(r.id,t.segmentationId),c=s==null?void 0:s.actor.getMapper().getInputData(),l=Ur(c,e),f=c.getDimensions();return(c.voxelManager||tc.createScalarVolumeVoxelManager({dimensions:f,scalarData:c.getPointData().getScalars().getData()})).getAtIJKPoint(l)}function v2e(t,e,{viewport:r}){const n=t.representationData.Contour,i=Array.from(n.annotationUIDsMap.keys()),{viewPlaneNormal:o}=r.getCamera();for(const a of i){const s=n.annotationUIDsMap.get(a);if(s)for(const c of s){const l=Br(c);if(!l)continue;const{polyline:f}=l.data.contour;if($t(o,l.metadata.viewPlaneNormal)&&v4(e,f))return Number(a)}}}function tU(t,e,{viewport:r,searchRadius:n}){const o=Ln(t).representationData.Labelmap;if(r instanceof Ir){const{volumeId:p}=o,v=Le.getVolume(p);if(!v)return;const y=v.voxelManager,m=v.imageData,w=Ur(m,e),x=y.getAtIJK(w[0],w[1],w[2]),C=r.worldToCanvas(e);return w2e(C,x,r,m,n)?x:void 0}const a=Vu(r.id,t);if(!Le.getImage(a))return;const c=_5(r.id,t),l=c==null?void 0:c.actor.getMapper().getInputData(),f=Ur(l,e),u=l.getDimensions(),d=l.voxelManager||tc.createScalarVolumeVoxelManager({dimensions:u,scalarData:l.getPointData().getScalars().getData()}),h=d.getAtIJKPoint(f);return y2e(f,u,d,h)?h:void 0}function nU(t,e,r=1){const n=Array.from({length:2*r+1},(i,o)=>o-r);for(const i of n)for(const o of n)for(const a of n){if(i===0&&o===0&&a===0)continue;const s=t(i,o,a);if(s!==void 0&&e!==s)return!0}return!1}function y2e(t,e,r,n,i){return nU((a,s,c)=>{const l=[t[0]+a,t[1]+s,t[2]+c];return r.getAtIJK(l[0],l[1],l[2])},n,i)}function w2e(t,e,r,n,i){return nU((a,s)=>{const c=[t[0]+a,t[1]+s],l=r.canvasToWorld(c),f=n.get("voxelManager").voxelManager,u=Ur(n,l);return f.getAtIJK(u[0],u[1],u[2])},e,i)}function rU(t){const e=Ln(t),{annotationUIDsMap:r}=e.representationData.Contour;for(const[n,i]of r.entries())if(Array.from(i).find(a=>Br(a).highlighted))return n}const x2e=` + `;return fN(c,e)}const z9=Symbol("ElementCursorsMap");function dN(t,e){Up(t)[0]=e,C1(t,e)}function C1(t,e){const r=Up(t);r[1]=r[0],r[0]=e,t.style.cursor=(e instanceof vo?e:vo.getDefinedCursor("auto")).getStyleProperty()}function zt(t){C1(t,Up(t)[1])}function Ot(t){C1(t,vo.getDefinedCursor("none"))}function Up(t){let e=Up[z9];e instanceof WeakMap||(e=new WeakMap,Object.defineProperty(Up,z9,{value:e}));let r=e.get(t);return r||(r=[null,null],e.set(t,r)),r}const Jle=Object.freeze(Object.defineProperty({__proto__:null,hideElementCursor:Ot,initElementCursor:dN,resetElementCursor:zt,setElementCursor:C1},Symbol.toStringTag,{value:"Module"}));function Zle(t,e){let r=y0.getDefinedCursor(e,!0);r||(r=vo.getDefinedCursor(e)),r||(console.log(`Cursor ${e} is not defined either as SVG or as a standard cursor.`),r=vo.getDefinedCursor(e)),C1(t,r)}const Qle=[...Ule,...Nle],eue=Object.freeze(Object.defineProperty({__proto__:null,CursorNames:Qle,CursorSVG:p5,ImageMouseCursor:Fp,MouseCursor:vo,SVGMouseCursor:y0,elementCursor:Jle,registerCursor:Vle,setCursorForElement:Zle},Symbol.toStringTag,{value:"Module"}));function Kr(t){return Be.toolGroups.find(e=>e.id===t)}const{Active:Kh,Passive:Zw,Enabled:Qw,Disabled:e3}=An,tue=[{mouseButton:nc.Primary}];class KT{constructor(e){this.viewportsInfo=[],this.toolOptions={},this.currentActivePrimaryToolName=null,this.prevActivePrimaryToolName=null,this.restoreToolOptions={},this._toolInstances={},this.id=e}getViewportIds(){return this.viewportsInfo.map(({viewportId:e})=>e)}getViewportsInfo(){return this.viewportsInfo.slice()}getToolInstance(e){const r=this._toolInstances[e];if(!r){console.warn(`'${e}' is not registered with this toolGroup (${this.id}).`);return}return r}getToolInstances(){return this._toolInstances}hasTool(e){return!!this._toolInstances[e]}addTool(e,r={}){const n=Be.tools[e],i=typeof e<"u"&&e!=="",o=this.toolOptions[e];if(!i){console.warn("Tool with configuration did not produce a toolName: ",r);return}if(!n){console.warn(`'${e}' is not registered with the library. You need to use cornerstoneTools.addTool to register it.`);return}if(o){console.warn(`'${e}' is already registered for ToolGroup ${this.id}.`);return}const{toolClass:a}=n,s={name:e,toolGroupId:this.id,configuration:r},c=new a(s);this._toolInstances[e]=c}addToolInstance(e,r,n={}){var o;let i=(o=Be.tools[e])==null?void 0:o.toolClass;if(!i){const a=Be.tools[r].toolClass;class s extends a{}s.toolName=e,i=s,Be.tools[e]={toolClass:s}}this.addTool(i.toolName,n)}addViewport(e,r){if(typeof e!="string")throw new Error("viewportId must be defined and be a string");const n=this._findRenderingEngine(e,r);this.viewportsInfo.some(({viewportId:s})=>s===e)||this.viewportsInfo.push({viewportId:e,renderingEngineId:n});const i=this.getActivePrimaryMouseButtonTool();Cr.getRuntimeSettings().get("useCursors")&&this.setViewportsCursorByToolName(i);const a={toolGroupId:this.id,viewportId:e,renderingEngineId:n};at(Ke,N.TOOLGROUP_VIEWPORT_ADDED,a)}removeViewports(e,r){const n=[];if(this.viewportsInfo.forEach((o,a)=>{let s=!1;o.renderingEngineId===e&&(s=!0,r&&o.viewportId!==r&&(s=!1)),s&&n.push(a)}),n.length)for(let o=n.length-1;o>=0;o--)this.viewportsInfo.splice(n[o],1);const i={toolGroupId:this.id,viewportId:r,renderingEngineId:e};at(Ke,N.TOOLGROUP_VIEWPORT_REMOVED,i)}setActiveStrategy(e,r){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool configuration.`);return}n.setActiveStrategy(r)}setToolMode(e,r,n={}){if(!e){console.warn("setToolMode: toolName must be defined");return}if(r===An.Active){this.setToolActive(e,n||this.restoreToolOptions[e]);return}if(r===An.Passive){this.setToolPassive(e);return}if(r===An.Enabled){this.setToolEnabled(e);return}if(r===An.Disabled){this.setToolDisabled(e);return}console.warn("setToolMode: mode must be defined")}setToolActive(e,r={}){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}if(!n){console.warn(`'${e}' instance ${n} is not registered with this toolGroup, can't set tool mode.`);return}const i=this.toolOptions[e]?this.toolOptions[e].bindings:[],o=r.bindings?r.bindings:[],s={bindings:[...i,...o].reduce((u,d)=>{const h=d.numTouchPoints!==void 0,g=d.mouseButton!==void 0;return!u.some(p=>t3(p,d))&&(h||g)&&u.push(d),u},[]),mode:Kh};this.toolOptions[e]=s,this._toolInstances[e].mode=Kh;const l=Cr.getRuntimeSettings().get("useCursors");if(this._hasMousePrimaryButtonBinding(r)&&l)this.setViewportsCursorByToolName(e);else if(!this.getActivePrimaryMouseButtonTool()&&l){const d=vo.getDefinedCursor("default");this._setCursorForViewports(d)}this._hasMousePrimaryButtonBinding(r)&&(this.prevActivePrimaryToolName===null?this.prevActivePrimaryToolName=e:this.prevActivePrimaryToolName=this.currentActivePrimaryToolName,this.currentActivePrimaryToolName=e),typeof n.onSetToolActive=="function"&&n.onSetToolActive(),this._renderViewports();const f={toolGroupId:this.id,toolName:e,toolBindingsOptions:r};at(Ke,N.TOOL_ACTIVATED,f),this._triggerToolModeChangedEvent(e,Kh,r)}setToolPassive(e,r){const n=this._toolInstances[e];if(n===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const i=this.getToolOptions(e),o=Object.assign({bindings:i?i.bindings:[]},i,{mode:Zw}),a=Array.isArray(r==null?void 0:r.removeAllBindings)?r.removeAllBindings:this.getDefaultPrimaryBindings();o.bindings=o.bindings.filter(c=>(r==null?void 0:r.removeAllBindings)!==!0&&!a.some(l=>t3(c,l)));let s=Zw;o.bindings.length!==0&&(s=Kh,o.mode=s),this.toolOptions[e]=o,n.mode=s,typeof n.onSetToolPassive=="function"&&n.onSetToolPassive(),this._renderViewports(),this._triggerToolModeChangedEvent(e,Zw)}setToolEnabled(e){const r=this._toolInstances[e];if(r===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const n={bindings:[],mode:Qw};this.toolOptions[e]=n,r.mode=Qw,typeof r.onSetToolEnabled=="function"&&r.onSetToolEnabled(),this._renderViewports(),this._triggerToolModeChangedEvent(e,Qw)}setToolDisabled(e){const r=this._toolInstances[e];if(r===void 0){console.warn(`Tool ${e} not added to toolGroup, can't set tool mode.`);return}const n={bindings:[],mode:e3};this.restoreToolOptions[e]=this.toolOptions[e],this.toolOptions[e]=n,r.mode=e3,typeof r.onSetToolDisabled=="function"&&r.onSetToolDisabled(),this._renderViewports(),this._triggerToolModeChangedEvent(e,e3)}getToolOptions(e){const r=this.toolOptions[e];if(r!==void 0)return r}getActivePrimaryMouseButtonTool(){return Object.keys(this.toolOptions).find(e=>{const r=this.toolOptions[e];return r.mode===Kh&&this._hasMousePrimaryButtonBinding(r)})}setViewportsCursorByToolName(e,r){const n=this._getCursor(e,r);this._setCursorForViewports(n)}_getCursor(e,r){let n,i;return r&&(n=`${e}.${r}`,i=y0.getDefinedCursor(n,!0),i)||(n=`${e}`,i=y0.getDefinedCursor(n,!0),i)||(n=e,i=y0.getDefinedCursor(n,!0),i)?i:vo.getDefinedCursor("default")}_setCursorForViewports(e){this.viewportsInfo.forEach(({renderingEngineId:r,viewportId:n})=>{const i=Ti(n,r);if(!i)return;const{viewport:o}=i;dN(o.element,e)})}setToolConfiguration(e,r,n){const i=this._toolInstances[e];if(i===void 0)return console.warn(`Tool ${e} not present, can't set tool configuration.`),!1;let o;return n?o=r:o=Object.assign(i.configuration,r),i.configuration=o,typeof i.onSetToolConfiguration=="function"&&i.onSetToolConfiguration(),this._renderViewports(),!0}getDefaultMousePrimary(){return nc.Primary}getDefaultPrimaryBindings(){return tue}getToolConfiguration(e,r){if(this._toolInstances[e]===void 0){console.warn(`Tool ${e} not present, can't set tool configuration.`);return}const n=Ale(this._toolInstances[e].configuration,r)||this._toolInstances[e].configuration;return Fa(n)}getPrevActivePrimaryToolName(){return this.prevActivePrimaryToolName}setActivePrimaryTool(e){const r=this.getCurrentActivePrimaryToolName();this.setToolDisabled(r),this.setToolActive(e,{bindings:[{mouseButton:nc.Primary}]})}getCurrentActivePrimaryToolName(){return this.currentActivePrimaryToolName}clone(e,r=null){let n=Kr(e);return n?(console.debug(`ToolGroup ${e} already exists`),n):(n=new KT(e),Be.toolGroups.push(n),r=r??(()=>!0),Object.keys(this._toolInstances).filter(r).forEach(i=>{const o=this._toolInstances[i],a=this.toolOptions[i],s=o.mode;n.addTool(i),n.setToolMode(i,s,{bindings:a.bindings??[]})}),n)}_hasMousePrimaryButtonBinding(e){var n;const r=this.getDefaultPrimaryBindings();return(n=e==null?void 0:e.bindings)==null?void 0:n.some(i=>r.some(o=>t3(i,o)))}_renderViewports(){this.viewportsInfo.forEach(({renderingEngineId:e,viewportId:r})=>{Jr(e).renderViewport(r)})}_triggerToolModeChangedEvent(e,r,n){const i={toolGroupId:this.id,toolName:e,mode:r,toolBindingsOptions:n};at(Ke,N.TOOL_MODE_CHANGED,i)}_findRenderingEngine(e,r){const n=Qo();if((n==null?void 0:n.length)===0)throw new Error("No rendering engines found.");if(r)return r;const i=n.filter(o=>o.getViewport(e));if(i.length===0){if(n.length===1)return n[0].id;throw new Error("No rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.")}if(i.length>1)throw new Error("Multiple rendering engines found that contain the viewport with the same viewportId, you must specify a renderingEngineId.");return i[0].id}}function t3(t,e){return t.mouseButton!==e.mouseButton||t.numTouchPoints!==e.numTouchPoints?!1:t.modifierKey===e.modifierKey}function hN(t){if(Be.toolGroups.some(n=>n.id===t)){console.warn(`'${t}' already exists.`);return}const r=new KT(t);return Be.toolGroups.push(r),r}function gN(t){const e=Be.toolGroups.findIndex(r=>r.id===t);e>-1&&Be.toolGroups.splice(e,1)}function pN(){const t=[...Be.toolGroups];for(const e of t)gN(e.id);Be.toolGroups=[]}function Or(t,e){var n;e||(e=(n=Qo().find(i=>i.getViewports().find(o=>o.id===t)))==null?void 0:n.id);const r=Be.toolGroups.filter(i=>i.viewportsInfo.some(o=>o.renderingEngineId===e&&(!o.viewportId||o.viewportId===t)));if(r.length){if(r.length>1)throw new Error(`Multiple tool groups found for renderingEngineId: ${e} and viewportId: ${t}. You should only + have one tool group per viewport in a renderingEngine.`);return r[0]}}function nue(){return Be.toolGroups}const rue=[An.Active,An.Passive,An.Enabled];function mN(t){return Be.toolGroups.filter(({toolOptions:e})=>{const r=Object.keys(e);for(let n=0;n{a.viewportsInfo.forEach(s=>{const{renderingEngineId:c,viewportId:l}=s,{FrameOfReferenceUID:f}=Ti(l,c);t.metadata.FrameOfReferenceUID===f&&n.push(s)})});const i=N.ANNOTATION_ADDED,o={annotation:t};if(!n.length){at(Ke,i,o);return}n.forEach(({renderingEngineId:a,viewportId:s})=>{o.viewportId=s,o.renderingEngineId=a,at(Ke,i,o)})}function m5(t){const e=N.ANNOTATION_REMOVED;at(Ke,e,t)}function tn(t,e,r=Ht.HandlesUpdated){const n=e&&Ce(e),{viewportId:i,renderingEngineId:o}=n||{},a=N.ANNOTATION_MODIFIED;at(Ke,a,{annotation:t,viewportId:i,renderingEngineId:o,changeType:r})}function Nn(t){xN({annotation:t})}function v5(t,e=!1){xN({annotation:t,contourHoleProcessingEnabled:e})}function xN(t){const e=N.ANNOTATION_COMPLETED;at(Ke,e,t)}const iue=Object.freeze(Object.defineProperty({__proto__:null,triggerAnnotationAddedForElement:yN,triggerAnnotationAddedForFOR:wN,triggerAnnotationCompleted:Nn,triggerAnnotationModified:tn,triggerAnnotationRemoved:m5,triggerContourAnnotationCompleted:v5},Symbol.toStringTag,{value:"Module"}));let CN;function Es(){return CN}function qT(t){CN=t}function un(t,e){const r=Es(),n=r.getGroupKey(e);return r.getAnnotations(n,t)}function Br(t){return Es().getAnnotation(t)}function S1(){return Es().getAllAnnotations()}function y5(t){const{annotationUID:e,parentAnnotationUID:r}=t;if(!r)return;const n=Br(r),i=n.childAnnotationUIDs.indexOf(e);n.childAnnotationUIDs.splice(i,1),t.parentAnnotationUID=void 0}function _1(t,e){const{annotationUID:r}=t,{annotationUID:n}=e;y5(e),t.childAnnotationUIDs||(t.childAnnotationUIDs=[]),!t.childAnnotationUIDs.includes(n)&&(t.childAnnotationUIDs.push(n),e.parentAnnotationUID=r)}function SN(t){return t.parentAnnotationUID?Br(t.parentAnnotationUID):void 0}function T1(t){var e;return((e=t.childAnnotationUIDs)==null?void 0:e.map(r=>Br(r)))??[]}function nn(t,e){t.annotationUID||(t.annotationUID=Dn());const r=Es();if(e instanceof HTMLDivElement){const n=r.getGroupKey(e);r.addAnnotation(t,n),yN(t,e)}else r.addAnnotation(t,void 0),wN(t);return t.annotationUID}function oue(t,e){const r=Es(),n=r.getGroupKey(e);return r.getNumberOfAnnotations(n,t)}function gn(t){var n;if(!t)return;const e=Es(),r=e.getAnnotation(t);r&&((n=r.childAnnotationUIDs)==null||n.forEach(i=>gn(i)),e.removeAnnotation(t),m5({annotation:r,annotationManagerUID:e.uid}))}function aue(){const t=Es(),e=t.removeAllAnnotations();for(const r of e)m5({annotation:r,annotationManagerUID:t.uid})}function sue(t,e){const r=Es(),n=r.getGroupKey(e),i=r.removeAnnotations(n,t);for(const o of i)m5({annotation:o,annotationManagerUID:r.uid})}function _N(t){let e=t;for(;e;)e.invalidated=!0,e=e.parentAnnotationUID?Br(e.parentAnnotationUID):void 0}const cue=Object.freeze(Object.defineProperty({__proto__:null,addAnnotation:nn,addChildAnnotation:_1,clearParentAnnotation:y5,getAllAnnotations:S1,getAnnotation:Br,getAnnotationManager:Es,getAnnotations:un,getChildAnnotations:T1,getNumberOfAnnotations:oue,getParentAnnotation:SN,invalidateAnnotation:_N,removeAllAnnotations:aue,removeAnnotation:gn,removeAnnotations:sue,setAnnotationManager:qT},Symbol.toStringTag,{value:"Module"}));function Ci(t){const e=t.toolName;if(!e)throw new Error(`No Tool Found for the ToolClass ${t.name}`);Be.tools[e]||(Be.tools[e]={toolClass:t})}function lue(t){const e=t.toolName;return!!(e&&Be.tools[e])}function w5(t){return!!(t&&Be.tools[t])}function TN(t){const e=t.toolName;if(!e)throw new Error(`No tool found for: ${t.name}`);if(!Be.tools[e]!==void 0)delete Be.tools[e];else throw new Error(`${e} cannot be removed because it has not been added`)}function fd(t,e){const r=e||t.currentTarget,{viewport:n}=Ce(r)||{};if(!n)return;const i=due(t),o=fue(t),a=uue(r,o),s=n.canvasToWorld(a);return{page:o,client:i,canvas:a,world:s}}function uue(t,e){const r=t.getBoundingClientRect();return[e[0]-r.left-window.pageXOffset,e[1]-r.top-window.pageYOffset]}function fue(t){return[t.pageX,t.pageY]}function due(t){return[t.clientX,t.clientY]}function EN(t){const e=t.currentTarget,{viewportId:r,renderingEngineId:n}=Ce(e),i=fd(t,e),o={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},a={event:t,eventName:N.MOUSE_DOUBLE_CLICK,viewportId:r,renderingEngineId:n,camera:{},element:e,startPoints:i,lastPoints:i,currentPoints:i,deltaPoints:o};!at(e,N.MOUSE_DOUBLE_CLICK,a)&&(t.stopImmediatePropagation(),t.preventDefault())}const $9=N.MOUSE_MOVE;function E1(t){const e=t.currentTarget,r=Ce(e);if(!r)return;const{renderingEngineId:n,viewportId:i}=r,o=fd(t);!at(e,$9,{renderingEngineId:n,viewportId:i,camera:{},element:e,currentPoints:o,eventName:$9,event:t})&&(t.stopImmediatePropagation(),t.preventDefault())}const{MOUSE_DOWN:j9,MOUSE_DOWN_ACTIVATE:hue,MOUSE_CLICK:gue,MOUSE_UP:pue,MOUSE_DRAG:H9}=N,mue=400,vue=150,yue=3,wue={mouseButton:void 0,element:null,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};let Zt={mouseButton:void 0,renderingEngineId:void 0,viewportId:void 0,isClickEvent:!0,clickDelay:200,element:null,preventClickTimeout:null,startPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},lastPoints:{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}};const Si={doubleClickTimeout:null,mouseDownEvent:null,mouseUpEvent:null,ignoreDoubleClick:!1};function DN(t){if(Si.doubleClickTimeout){if(t.buttons===Si.mouseDownEvent.buttons)return;Si.mouseDownEvent=t,$v();return}Si.doubleClickTimeout=setTimeout($v,t.buttons===1?mue:vue),Si.mouseDownEvent=t,Si.ignoreDoubleClick=!1,Zt.element=t.currentTarget,Zt.mouseButton=t.buttons;const e=Ce(Zt.element),{renderingEngineId:r,viewportId:n}=e;Zt.renderingEngineId=r,Zt.viewportId=n,Zt.preventClickTimeout=setTimeout(Cue,Zt.clickDelay),Zt.element.removeEventListener("mousemove",E1);const i=fd(t,Zt.element);Zt.startPoints=uu(i),Zt.lastPoints=uu(i),document.addEventListener("mouseup",XT),document.addEventListener("mousemove",bN)}function xue(t){const e=x5(Zt.startPoints,Zt.startPoints),r={event:t,eventName:j9,element:Zt.element,mouseButton:Zt.mouseButton,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},startPoints:Zt.startPoints,lastPoints:Zt.startPoints,currentPoints:Zt.startPoints,deltaPoints:e};Zt.lastPoints=uu(r.lastPoints),at(r.element,j9,r)&&at(r.element,hue,r)}function bN(t){const e=Ce(Zt.element);if(!(e!=null&&e.viewport))return;const r=fd(t,Zt.element),n=PN(Zt.element,Zt.lastPoints),i=x5(r,n);if(Si.doubleClickTimeout)if(ON(i.canvas))$v();else return;const o={event:t,eventName:H9,mouseButton:Zt.mouseButton,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},element:Zt.element,startPoints:uu(Zt.startPoints),lastPoints:uu(n),currentPoints:r,deltaPoints:i};!at(Zt.element,H9,o)&&(t.stopImmediatePropagation(),t.preventDefault()),Zt.lastPoints=uu(r)}function XT(t){if(clearTimeout(Zt.preventClickTimeout),Si.doubleClickTimeout)Si.mouseUpEvent?mC():(Si.mouseUpEvent=t,Zt.element.addEventListener("mousemove",IN));else{const e=Zt.isClickEvent?gue:pue,r=fd(t,Zt.element),n=x5(r,Zt.lastPoints),i={event:t,eventName:e,mouseButton:Zt.mouseButton,element:Zt.element,renderingEngineId:Zt.renderingEngineId,viewportId:Zt.viewportId,camera:{},startPoints:uu(Zt.startPoints),lastPoints:uu(Zt.lastPoints),currentPoints:r,deltaPoints:n};at(i.element,e,i),mC()}document.removeEventListener("mousemove",bN)}function IN(t){const e=fd(t,Zt.element),r=PN(Zt.element,Zt.lastPoints),n=x5(e,r);ON(n.canvas)&&($v(),E1(t))}function ON(t){return Math.abs(t[0])+Math.abs(t[1])>yue}function Cue(){Zt.isClickEvent=!1}function $v(){Si.ignoreDoubleClick=!0;const t=Si.mouseDownEvent,e=Si.mouseUpEvent;MN(),xue(t),e&&XT(e)}function MN(){Si.doubleClickTimeout&&(clearTimeout(Si.doubleClickTimeout),Si.doubleClickTimeout=null),Si.mouseDownEvent=null,Si.mouseUpEvent=null}function mC(){var t,e;document.removeEventListener("mouseup",XT),(t=Zt.element)==null||t.removeEventListener("mousemove",IN),(e=Zt.element)==null||e.addEventListener("mousemove",E1),MN(),Zt=JSON.parse(JSON.stringify(wue))}function uu(t){return JSON.parse(JSON.stringify(t))}function PN(t,e){const{viewport:r}=Ce(t)||{};if(!r)return e;const n=r.canvasToWorld(e.canvas);return{page:e.page,client:e.client,canvas:e.canvas,world:n}}function x5(t,e){return!t||!e?{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]}:{page:n3(t.page,e.page),client:n3(t.client,e.client),canvas:n3(t.canvas,e.canvas),world:Sue(t.world,e.world)}}function n3(t,e){return[t[0]-e[0],t[1]-e[1]]}function Sue(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function _ue(){return Zt.mouseButton}function RN(t){Si.ignoreDoubleClick?(Si.ignoreDoubleClick=!1,t.stopImmediatePropagation(),t.preventDefault()):mC()}function LN(t){t.removeEventListener("dblclick",EN),t.removeEventListener("mousedown",DN),t.removeEventListener("mousemove",E1),t.removeEventListener("dblclick",RN,{capture:!0})}function Tue(t){LN(t),t.addEventListener("dblclick",EN),t.addEventListener("mousedown",DN),t.addEventListener("mousemove",E1),t.addEventListener("dblclick",RN,{capture:!0})}const AN={enable:Tue,disable:LN},Eue=2e3,z0={mouse:0,touch:1};let K9,q9;function NN(t,e){const r=Date.now();if(t!==K9){if(r-q9<=Eue)return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),!1;K9=t}q9=r}const kN=NN.bind(null,z0.mouse),VN=NN.bind(null,z0.touch);function X9(t,e,r){const n=r?kN:VN;e.forEach(function(i){t.addEventListener(i,n,{passive:!1})})}function Y9(t,e,r){const n=r?kN:VN;e.forEach(function(i){t.removeEventListener(i,n)})}const FN=["mousedown","mouseup","mousemove"],UN=["touchstart","touchend"];function BN(t){Y9(t,FN,z0.mouse),Y9(t,UN,z0.touch)}function Due(t){BN(t),X9(t,FN,z0.mouse),X9(t,UN,z0.touch)}const GN={enable:Due,disable:BN};function C5(t,e){const r=e||t.currentTarget,n=t.type==="touchend"?t.changedTouches:t.touches;return Object.keys(n).map(i=>{const o=Oue(n[i]),a=Iue(n[i]),s=bue(r,a),{viewport:c}=Ce(r),l=c.canvasToWorld(s);return{page:a,client:o,canvas:s,world:l,touch:{identifier:i,radiusX:n[i].radiusX,radiusY:n[i].radiusY,force:n[i].force,rotationAngle:n[i].rotationAngle}}})}function bue(t,e){const r=t.getBoundingClientRect();return[e[0]-r.left-window.pageXOffset,e[1]-r.top-window.pageYOffset]}function Iue(t){return[t.pageX,t.pageY]}function Oue(t){return[t.clientX,t.clientY]}function jv(t,e){const r=Bp(t),n=Bp(e);return{page:r3(r.page,n.page),client:r3(r.client,n.client),canvas:r3(r.canvas,n.canvas),world:Pue(r.world,n.world)}}function YT(t,e){const r=Bp(t),n=Bp(e);return{page:w0(r.page,n.page),client:w0(r.client,n.client),canvas:w0(r.canvas,n.canvas),world:WN(r.world,n.world)}}function Mue(t,e){}function Hv(t,e){const r=J9(t),n=J9(e);return{page:r.page-n.page,client:r.client-n.client,canvas:r.canvas-n.canvas,world:r.world-n.world}}function Xs(t){return JSON.parse(JSON.stringify(t))}function vC(t){return JSON.parse(JSON.stringify(t))}function Bp(t){return t.reduce((e,r)=>({page:[e.page[0]+r.page[0]/t.length,e.page[1]+r.page[1]/t.length],client:[e.client[0]+r.client[0]/t.length,e.client[1]+r.client[1]/t.length],canvas:[e.canvas[0]+r.canvas[0]/t.length,e.canvas[1]+r.canvas[1]/t.length],world:[e.world[0]+r.world[0]/t.length,e.world[1]+r.world[1]/t.length,e.world[2]+r.world[2]/t.length]}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]})}function ys(t){return t.reduce((e,r)=>({page:[e.page[0]+r.page[0]/t.length,e.page[1]+r.page[1]/t.length],client:[e.client[0]+r.client[0]/t.length,e.client[1]+r.client[1]/t.length],canvas:[e.canvas[0]+r.canvas[0]/t.length,e.canvas[1]+r.canvas[1]/t.length],world:[e.world[0]+r.world[0]/t.length,e.world[1]+r.world[1]/t.length,e.world[2]+r.world[2]/t.length],touch:{identifier:null,radiusX:e.touch.radiusX+r.touch.radiusX/t.length,radiusY:e.touch.radiusY+r.touch.radiusY/t.length,force:e.touch.force+r.touch.force/t.length,rotationAngle:e.touch.rotationAngle+r.touch.rotationAngle/t.length}}),{page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0],touch:{identifier:null,radiusX:0,radiusY:0,force:0,rotationAngle:0}})}function r3(t,e){return[t[0]-e[0],t[1]-e[1]]}function Pue(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function J9(t){const e=[];for(let r=0;r({page:r.page+n.page/e.length,client:r.client+n.client/e.length,canvas:r.canvas+n.canvas/e.length,world:r.world+n.world/e.length}),{page:0,client:0,canvas:0,world:0})}function w0(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2))}function WN(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}const Rue=Object.freeze(Object.defineProperty({__proto__:null,copyPoints:vC,copyPointsList:Xs,getDeltaDistance:YT,getDeltaDistanceBetweenIPoints:Hv,getDeltaPoints:jv,getDeltaRotation:Mue,getMeanPoints:Bp,getMeanTouchPoints:ys},Symbol.toStringTag,{value:"Module"}));Cr.getRuntimeSettings();const{TOUCH_START:Z9,TOUCH_START_ACTIVATE:Lue,TOUCH_PRESS:Q9,TOUCH_DRAG:eD,TOUCH_END:tD,TOUCH_TAP:nD,TOUCH_SWIPE:i3}=N,Gp={page:[0,0],client:[0,0],canvas:[0,0],world:[0,0,0]},Kv={page:0,client:0,canvas:0,world:0},zN={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Gp,touch:null}],lastPointsList:[{...Gp,touch:null}],isTouchStart:!1,startTime:null,pressTimeout:null,pressDelay:700,pressMaxDistance:5,accumulatedDistance:Kv,swipeDistanceThreshold:48,swiped:!1,swipeToleranceMs:300},$N={renderingEngineId:void 0,viewportId:void 0,element:null,startPointsList:[{...Gp,touch:null}],taps:0,tapTimeout:null,tapMaxDistance:24,tapToleranceMs:300};let It=JSON.parse(JSON.stringify(zN)),ti=JSON.parse(JSON.stringify($N));function Cu(t,e,r){return at(t,e,r)}function jN(t){It.element=t.currentTarget;const e=Ce(It.element),{renderingEngineId:r,viewportId:n}=e;It.renderingEngineId=r,It.viewportId=n,!It.isTouchStart&&(clearTimeout(It.pressTimeout),It.pressTimeout=setTimeout(()=>Aue(t),It.pressDelay),Nue(t),document.addEventListener("touchmove",HN),document.addEventListener("touchend",KN))}function Aue(t){if(It.accumulatedDistance.canvas>It.pressMaxDistance)return;const r={event:t,eventName:Q9,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,startPointsList:Xs(It.startPointsList),lastPointsList:Xs(It.lastPointsList),startPoints:vC(ys(It.startPointsList)),lastPoints:vC(ys(It.lastPointsList))};Cu(r.element,Q9,r)}function Nue(t){It.isTouchStart=!0,It.startTime=new Date;const e=C5(t,It.element),r=ys(e),n=Gp,i=Kv,o={event:t,eventName:Z9,element:It.element,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},startPointsList:e,lastPointsList:e,currentPointsList:e,startPoints:r,lastPoints:r,currentPoints:r,deltaPoints:n,deltaDistance:i};It.startPointsList=Xs(o.startPointsList),It.lastPointsList=Xs(o.lastPointsList),Cu(o.element,Z9,o)&&Cu(o.element,Lue,o)}function HN(t){const e=C5(t,It.element),r=qN(It.element,It.lastPointsList),n=e.length===r.length?jv(e,r):Gp,i=e.length===r.length?Hv(e,r):Kv,o=e.length===r.length?YT(e,It.lastPointsList):Kv;It.accumulatedDistance={page:It.accumulatedDistance.page+o.page,client:It.accumulatedDistance.client+o.client,canvas:It.accumulatedDistance.canvas+o.canvas,world:It.accumulatedDistance.world+o.world};const a={event:t,eventName:eD,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,startPoints:ys(It.startPointsList),lastPoints:ys(r),currentPoints:ys(e),startPointsList:Xs(It.startPointsList),lastPointsList:Xs(r),currentPointsList:e,deltaPoints:n,deltaDistance:i};Cu(It.element,eD,a),Vue(t,n),It.lastPointsList=Xs(e)}function KN(t){clearTimeout(It.pressTimeout);const e=C5(t,It.element),r=qN(It.element,It.lastPointsList),n=e.length===r.length?jv(e,r):jv(e,e),i=e.length===r.length?Hv(e,r):Hv(e,e),o={event:t,eventName:tD,element:It.element,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},startPointsList:Xs(It.startPointsList),lastPointsList:Xs(r),currentPointsList:e,startPoints:ys(It.startPointsList),lastPoints:ys(r),currentPoints:ys(e),deltaPoints:n,deltaDistance:i};Cu(o.element,tD,o),kue(t),It=JSON.parse(JSON.stringify(zN)),document.removeEventListener("touchmove",HN),document.removeEventListener("touchend",KN)}function kue(t){const e=new Date().getTime(),r=It.startTime.getTime();if(e-r>ti.tapToleranceMs||(ti.taps===0&&(ti.element=It.element,ti.renderingEngineId=It.renderingEngineId,ti.viewportId=It.viewportId,ti.startPointsList=It.startPointsList),ti.taps>0&&!(ti.element==It.element&&ti.renderingEngineId==It.renderingEngineId&&ti.viewportId==It.viewportId)))return;const n=C5(t,ti.element);YT(n,ti.startPointsList).canvas>ti.tapMaxDistance||(clearTimeout(ti.tapTimeout),ti.taps+=1,ti.tapTimeout=setTimeout(()=>{const o={event:t,eventName:nD,element:ti.element,renderingEngineId:ti.renderingEngineId,viewportId:ti.viewportId,camera:{},currentPointsList:n,currentPoints:ys(n),taps:ti.taps};Cu(o.element,nD,o),ti=JSON.parse(JSON.stringify($N))},ti.tapToleranceMs))}function Vue(t,e){const r=new Date().getTime(),n=It.startTime.getTime();if(It.swiped||r-n>It.swipeToleranceMs)return;const[i,o]=e.canvas,a={event:t,eventName:i3,renderingEngineId:It.renderingEngineId,viewportId:It.viewportId,camera:{},element:It.element,swipe:null};Math.abs(i)>It.swipeDistanceThreshold&&(a.swipe=i>0?Lf.RIGHT:Lf.LEFT,Cu(a.element,i3,a),It.swiped=!0),Math.abs(o)>It.swipeDistanceThreshold&&(a.swipe=o>0?Lf.DOWN:Lf.UP,Cu(a.element,i3,a),It.swiped=!0)}function qN(t,e){const{viewport:r}=Ce(t);return e.map(n=>{const i=r.canvasToWorld(n.canvas);return{page:n.page,client:n.client,canvas:n.canvas,world:i,touch:n.touch}})}function XN(t){GN.disable(t),t.removeEventListener("touchstart",jN)}function Fue(t){XN(t),GN.enable(t),t.addEventListener("touchstart",jN,{passive:!1})}const YN={enable:Fue,disable:XN},rD=10,iD=40,oD=800;function Uue(t){let e=0,r=0,n=0,i=0;return"detail"in t&&(r=t.detail),"wheelDelta"in t&&(r=-t.wheelDelta/120),"wheelDeltaY"in t&&(r=-t.wheelDeltaY/120),"wheelDeltaX"in t&&(e=-t.wheelDeltaX/120),n=e*rD,i=r*rD,"deltaY"in t&&(i=t.deltaY),"deltaX"in t&&(n=t.deltaX),(n||i)&&t.deltaMode&&(t.deltaMode===1?(n*=iD,i*=iD):(n*=oD,i*=oD)),n&&!e&&(e=n<1?-1:1),i&&!r&&(r=i<1?-1:1),{spinX:e,spinY:r,pixelX:n,pixelY:i}}function JN(t){const e=t.currentTarget,r=Ce(e),{renderingEngineId:n,viewportId:i}=r;if(t.deltaY>-1&&t.deltaY<1)return;t.preventDefault();const{spinX:o,spinY:a,pixelX:s,pixelY:c}=Uue(t),l=a<0?-1:1,f={event:t,eventName:N.MOUSE_WHEEL,renderingEngineId:n,viewportId:i,element:e,camera:{},detail:t,wheel:{spinX:o,spinY:a,pixelX:s,pixelY:c,direction:l},points:fd(t)};at(e,N.MOUSE_WHEEL,f)}function Bue(t){ZN(t),t.addEventListener("wheel",JN,{passive:!1})}function ZN(t){t.removeEventListener("wheel",JN)}const QN={enable:Bue,disable:ZN},Gue={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};let fi={renderingEngineId:void 0,viewportId:void 0,key:void 0,keyCode:void 0,element:null};function S5(t){fi.element=t.currentTarget;const e=Ce(fi.element),{renderingEngineId:r,viewportId:n}=e;fi.renderingEngineId=r,fi.viewportId=n,fi.key=t.key,fi.keyCode=t.keyCode,t.preventDefault();const i={renderingEngineId:fi.renderingEngineId,viewportId:fi.viewportId,element:fi.element,key:fi.key,keyCode:fi.keyCode};at(i.element,N.KEY_DOWN,i),document.addEventListener("keyup",ek),document.addEventListener("visibilitychange",JT),fi.element.removeEventListener("keydown",S5)}function JT(){document.removeEventListener("visibilitychange",JT),document.visibilityState==="hidden"&&tk()}function ek(t){const e={renderingEngineId:fi.renderingEngineId,viewportId:fi.viewportId,element:fi.element,key:fi.key,keyCode:fi.keyCode};document.removeEventListener("keyup",ek),document.removeEventListener("visibilitychange",JT),fi.element.addEventListener("keydown",S5),fi=structuredClone(Gue),at(e.element,N.KEY_UP,e)}function Wue(){return fi.keyCode}function tk(){fi.keyCode=void 0}function zue(t){nk(t),t.addEventListener("keydown",S5)}function nk(t){t.removeEventListener("keydown",S5)}const hh={enable:zue,disable:nk,getModifierKey:Wue},{EPSILON:Ed}=cd;function rk(t,e,r=!1){var f;let n=1/0,i=r?-1/0:0,o=1/0,a=r?-1/0:0,s=1/0,c=r?-1/0:0;const l=((f=t[0])==null?void 0:f.length)===3;for(let u=0;uJSON.stringify(t)===JSON.stringify(e);function ZT(t,e,r,n){const i=r[0]/2,o=r[1]/2,a=r[2]/2,s=new Array(8);s[0]=Ur(t,[n[0]-i,n[1]-o,n[2]-a]);const c=[[1,-1,-1],[-1,1,-1],[1,1,-1],[-1,-1,1],[1,-1,1],[-1,1,1],[1,1,1]];for(let l=0;l<7;l++){const[f,u,d]=c[l];s[l+1]=Ur(t,[n[0]+f*i,n[1]+u*o,n[2]+d*a])}return Su(s,e)}function ok(t,e){const{spacing:r}=t,n=t.voxelManager.getScalarDataLength(),i=[];let o=0;for(let a=0;a{const e=QT.get(t);e&&(e.isDirty=!0)},Hue=t=>{const e=QT.get(t);return e&&!e.isDirty?e.indices:null},Kue=(t,e)=>{QT.set(t,{indices:e,isDirty:!1})};function io(t,e,r){const n={segmentationId:t,modifiedSlicesToUse:e,segmentIndex:r};jue(t),at(Ke,N.SEGMENTATION_DATA_MODIFIED,n)}function Ta(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_MODIFIED,e)}function e4(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_REMOVED,e)}function Gs(t,e,r){const n={segmentationId:e,type:r,viewportId:t};at(Ke,N.SEGMENTATION_REPRESENTATION_MODIFIED,n)}function yC(t,e,r){const n={viewportId:t,segmentationId:e,type:r};at(Ke,N.SEGMENTATION_REPRESENTATION_REMOVED,n)}const que=Object.freeze(Object.defineProperty({__proto__:null,triggerSegmentationDataModified:io,triggerSegmentationModified:Ta,triggerSegmentationRemoved:e4,triggerSegmentationRepresentationModified:Gs,triggerSegmentationRepresentationRemoved:yC},Symbol.toStringTag,{value:"Module"})),Xue={renderOutline:!0,outlineWidthAutoGenerated:3,outlineWidth:1,outlineWidthInactive:1,outlineOpacity:1,outlineOpacityInactive:.85,outlineDash:void 0,outlineDashInactive:void 0,outlineDashAutoGenerated:"5,3",activeSegmentOutlineWidthDelta:0,renderFill:!0,fillAlpha:.5,fillAlphaInactive:.3,fillAlphaAutoGenerated:.3};function Yue(){return Xue}const Jue={renderOutline:!0,renderOutlineInactive:!0,outlineWidth:3,outlineWidthInactive:2,activeSegmentOutlineWidthDelta:0,renderFill:!0,renderFillInactive:!0,fillAlpha:.5,fillAlphaInactive:.4,outlineOpacity:1,outlineOpacityInactive:.85};function Zue(){return Jue}class Que{constructor(){this.config={global:{},segmentations:{},viewportsStyle:{}}}setStyle(e,r){const{viewportId:n,segmentationId:i,type:o,segmentIndex:a}=e,s=this.getStyle(e);let c;if(!n&&!i?c={...s,...r}:c=this.copyActiveToInactiveIfNotProvided({...s,...r},o),!o)throw new Error("Type is required to set a style");if(n){this.config.viewportsStyle[n]||(this.config.viewportsStyle[n]={renderInactiveSegmentations:!1,representations:{}});const l=this.config.viewportsStyle[n].representations;if(i){l[i]||(l[i]={}),l[i][o]||(l[i][o]={});const f=l[i][o];a!==void 0?(f.perSegment||(f.perSegment={}),f.perSegment[a]=c):f.allSegments=c}else{const f="__allSegmentations__";l[f]||(l[f]={}),l[f][o]||(l[f][o]={}),l[f][o].allSegments=c}}else if(i){this.config.segmentations[i]||(this.config.segmentations[i]={}),this.config.segmentations[i][o]||(this.config.segmentations[i][o]={});const l=this.config.segmentations[i][o];a!==void 0?(l.perSegment||(l.perSegment={}),l.perSegment[a]=c):l.allSegments=c}else this.config.global[o]=c}copyActiveToInactiveIfNotProvided(e,r){const n={...e};if(r===Dt.Labelmap){const i=n;i.renderOutlineInactive??(i.renderOutlineInactive=i.renderOutline),i.outlineWidthInactive??(i.outlineWidthInactive=i.outlineWidth),i.renderFillInactive??(i.renderFillInactive=i.renderFill),i.fillAlphaInactive??(i.fillAlphaInactive=i.fillAlpha),i.outlineOpacityInactive??(i.outlineOpacityInactive=i.outlineOpacity)}else if(r===Dt.Contour){const i=n;i.outlineWidthInactive??(i.outlineWidthInactive=i.outlineWidth),i.outlineOpacityInactive??(i.outlineOpacityInactive=i.outlineOpacity),i.outlineDashInactive??(i.outlineDashInactive=i.outlineDash),i.renderOutlineInactive??(i.renderOutlineInactive=i.renderOutline),i.renderFillInactive??(i.renderFillInactive=i.renderFill),i.fillAlphaInactive??(i.fillAlphaInactive=i.fillAlpha)}return n}getStyle(e){var s,c,l,f,u;const{viewportId:r,segmentationId:n,type:i,segmentIndex:o}=e;let a=this.getDefaultStyle(i);if(this.config.global[i]&&(a={...a,...this.config.global[i]}),(s=this.config.segmentations[n])!=null&&s[i]&&(a={...a,...this.config.segmentations[n][i].allSegments},o!==void 0&&((c=this.config.segmentations[n][i].perSegment)!=null&&c[o])&&(a={...a,...this.config.segmentations[n][i].perSegment[o]})),r&&this.config.viewportsStyle[r]){this.config.viewportsStyle[r].renderInactiveSegmentations;const d="__allSegmentations__";(l=this.config.viewportsStyle[r].representations[d])!=null&&l[i]&&(a={...a,...this.config.viewportsStyle[r].representations[d][i].allSegments}),n&&((f=this.config.viewportsStyle[r].representations[n])!=null&&f[i])&&(a={...a,...this.config.viewportsStyle[r].representations[n][i].allSegments},o!==void 0&&((u=this.config.viewportsStyle[r].representations[n][i].perSegment)!=null&&u[o])&&(a={...a,...this.config.viewportsStyle[r].representations[n][i].perSegment[o]}))}return a}getRenderInactiveSegmentations(e){var r;return(r=this.config.viewportsStyle[e])==null?void 0:r.renderInactiveSegmentations}setRenderInactiveSegmentations(e,r){this.config.viewportsStyle[e]||(this.config.viewportsStyle[e]={renderInactiveSegmentations:!1,representations:{}}),this.config.viewportsStyle[e].renderInactiveSegmentations=r}getDefaultStyle(e){switch(e){case Dt.Labelmap:return Zue();case Dt.Contour:return Yue();case Dt.Surface:return{};default:throw new Error(`Unknown representation type: ${e}`)}}clearSegmentationStyle(e){this.config.segmentations[e]&&delete this.config.segmentations[e]}clearAllSegmentationStyles(){this.config.segmentations={}}clearViewportStyle(e){this.config.viewportsStyle[e]&&delete this.config.viewportsStyle[e]}clearAllViewportStyles(){for(const e in this.config.viewportsStyle){const n=this.config.viewportsStyle[e].renderInactiveSegmentations;this.config.viewportsStyle[e]={renderInactiveSegmentations:n,representations:{}}}}resetToGlobalStyle(){this.clearAllSegmentationStyles(),this.clearAllViewportStyles()}hasCustomStyle(e){const{type:r}=e,n=this.getStyle(e),i=this.getDefaultStyle(r);return!XA(n,i)}}const va=new Que;function efe(t){const e={segmentationId:t};at(Ke,N.SEGMENTATION_ADDED,e)}const aD={colorLUT:[],segmentations:[],viewportSegRepresentations:{}};class tfe{constructor(e){this._stackLabelmapImageIdReferenceMap=new Map,this._labelmapImageIdReferenceMap=new Map,e||(e=Dn()),this.state=Object.freeze(Fa(aD)),this.uid=e}getState(){return this.state}updateState(e){const r=Fa(this.state);e(r),this.state=Object.freeze(r)}getColorLUT(e){return this.state.colorLUT[e]}getNextColorLUTIndex(){return this.state.colorLUT.length}resetState(){this._stackLabelmapImageIdReferenceMap.clear(),this._labelmapImageIdReferenceMap.clear(),this.state=Object.freeze(Fa(aD))}getSegmentation(e){return this.state.segmentations.find(r=>r.segmentationId===e)}updateSegmentation(e,r){this.updateState(n=>{const i=n.segmentations.find(o=>o.segmentationId===e);if(!i){console.warn(`Segmentation with id ${e} not found. Update aborted.`);return}Object.assign(i,r)}),Ta(e)}addSegmentation(e){if(this.getSegmentation(e.segmentationId))throw new Error(`Segmentation with id ${e.segmentationId} already exists`);this.updateState(r=>{const n=Fa(e);if(n.representationData.Labelmap&&"volumeId"in n.representationData.Labelmap&&!("imageIds"in n.representationData.Labelmap)){const i=this.getLabelmapImageIds(n.representationData);n.representationData.Labelmap.imageIds=i}r.segmentations.push(n)}),efe(e.segmentationId)}removeSegmentation(e){this.updateState(r=>{const n=r.segmentations.filter(i=>i.segmentationId!==e);r.segmentations.splice(0,r.segmentations.length,...n)}),e4(e)}addSegmentationRepresentation(e,r,n,i){if(!zn(e))return;if(this.getSegmentationRepresentations(e,{type:n,segmentationId:r}).length>0){console.debug("A segmentation representation of type",n,"already exists in viewport",e,"for segmentation",r);return}this.updateState(s=>{s.viewportSegRepresentations[e]||(s.viewportSegRepresentations[e]=[],va.setRenderInactiveSegmentations(e,!0)),n!==Dt.Labelmap?this.addDefaultSegmentationRepresentation(s,e,r,n,i):this.addLabelmapRepresentation(s,e,r,i)}),Gs(e,r,n)}addDefaultSegmentationRepresentation(e,r,n,i,o){const a=e.segmentations.find(c=>c.segmentationId===n);if(!a)return;const s={};Object.keys(a.segments).forEach(c=>{s[Number(c)]={visible:!0}}),e.viewportSegRepresentations[r].push({segmentationId:n,type:i,active:!0,visible:!0,colorLUTIndex:(o==null?void 0:o.colorLUTIndex)||0,segments:s,config:{...sD(i),...o}}),this._setActiveSegmentation(e,r,n)}addLabelmapRepresentation(e,r,n,i=sD(Dt.Labelmap)){if(!zn(r))return;const a=this.getSegmentation(n);if(!a)return;const{representationData:s}=a;if(!s.Labelmap)return this.addDefaultSegmentationRepresentation(e,r,n,Dt.Labelmap,i);this.processLabelmapRepresentationAddition(r,n),this.addDefaultSegmentationRepresentation(e,r,n,Dt.Labelmap,i)}async processLabelmapRepresentationAddition(e,r){const n=zn(e);if(!n)return;const i=this.getSegmentation(r);if(!i)return;const o=n.viewport instanceof Ir,{representationData:a}=i,s="volumeId"in a.Labelmap;n.viewport,!o&&!s&&this.updateLabelmapSegmentationImageReferences(e,i.segmentationId)}_updateLabelmapSegmentationReferences(e,r,n,i){const o=r.getCurrentImageId();let a=!1;for(const s of n)r.isReferenceViewable({referencedImageId:s},{asOverlay:!0})&&(a=!0,this._stackLabelmapImageIdReferenceMap.get(e).set(o,s),this._updateLabelmapImageIdReferenceMap({segmentationId:e,referenceImageId:o,labelmapImageId:s}));return i&&i(r,e,n),a?this._stackLabelmapImageIdReferenceMap.get(e).get(o):void 0}updateLabelmapSegmentationImageReferences(e,r){const n=this.getSegmentation(r);if(!n)return;this._stackLabelmapImageIdReferenceMap.has(r)||this._stackLabelmapImageIdReferenceMap.set(r,new Map);const{representationData:i}=n;if(!i.Labelmap)return;const o=this.getLabelmapImageIds(i),s=zn(e).viewport;return this._updateLabelmapSegmentationReferences(r,s,o,null)}_updateAllLabelmapSegmentationImageReferences(e,r){const n=this.getSegmentation(r);if(!n)return;this._stackLabelmapImageIdReferenceMap.has(r)||this._stackLabelmapImageIdReferenceMap.set(r,new Map);const{representationData:i}=n;if(!i.Labelmap)return;const o=this.getLabelmapImageIds(i),s=zn(e).viewport;this._updateLabelmapSegmentationReferences(r,s,o,(c,l,f)=>{c.getImageIds().forEach((d,h)=>{for(const g of f)c.isReferenceViewable({referencedImageId:g,sliceIndex:h},{asOverlay:!0,withNavigation:!0})&&(this._stackLabelmapImageIdReferenceMap.get(l).set(d,g),this._updateLabelmapImageIdReferenceMap({segmentationId:l,referenceImageId:d,labelmapImageId:g}))})})}getLabelmapImageIds(e){const r=e.Labelmap;let n;if(r.imageIds)n=r.imageIds;else if(!n&&r.volumeId){const i=r.volumeId;n=Le.getVolume(i).imageIds}return n}getLabelmapImageIdsForImageId(e,r){const n=this._generateMapKey({segmentationId:r,referenceImageId:e});return this._labelmapImageIdReferenceMap.get(n)}getCurrentLabelmapImageIdsForViewport(e,r){const n=zn(e);if(!n)return;const o=n.viewport.getCurrentImageId();return this.getLabelmapImageIdsForImageId(o,r)}getCurrentLabelmapImageIdForViewport(e,r){const n=zn(e);if(!n||!this._stackLabelmapImageIdReferenceMap.has(r))return;const o=n.viewport.getCurrentImageId();return this._stackLabelmapImageIdReferenceMap.get(r).get(o)}getStackSegmentationImageIdsForViewport(e,r){if(!this.getSegmentation(r))return[];this._updateAllLabelmapSegmentationImageReferences(e,r);const{viewport:i}=zn(e),o=i.getImageIds(),a=this._stackLabelmapImageIdReferenceMap.get(r);return o.map(s=>a.get(s))}removeSegmentationRepresentationsInternal(e,r){const n=[];return this.updateState(i=>{if(!i.viewportSegRepresentations[e])return;const o=i.viewportSegRepresentations[e];let a=!1;if(!r||Object.values(r).every(s=>s===void 0))n.push(...o),delete i.viewportSegRepresentations[e];else{const{segmentationId:s,type:c}=r;i.viewportSegRepresentations[e]=o.filter(l=>{const f=s&&c&&l.segmentationId===s&&l.type===c||s&&!c&&l.segmentationId===s||!s&&c&&l.type===c;return f&&(n.push(l),l.active&&(a=!0)),!f}),i.viewportSegRepresentations[e].length===0?delete i.viewportSegRepresentations[e]:a&&(i.viewportSegRepresentations[e][0].active=!0)}}),n}removeSegmentationRepresentations(e,r){const n=this.removeSegmentationRepresentationsInternal(e,r);n.forEach(o=>{yC(e,o.segmentationId,o.type)});const i=this.getSegmentationRepresentations(e);return i.length>0&&i[0].active&&Gs(e,i[0].segmentationId,i[0].type),n}removeSegmentationRepresentation(e,r,n){const i=this.removeSegmentationRepresentationsInternal(e,r);return n||i.forEach(({segmentationId:o,type:a})=>{yC(e,o,a)}),i}_updateLabelmapImageIdReferenceMap({segmentationId:e,referenceImageId:r,labelmapImageId:n}){const i=this._generateMapKey({segmentationId:e,referenceImageId:r});if(!this._labelmapImageIdReferenceMap.has(i)){this._labelmapImageIdReferenceMap.set(i,[n]);return}const o=this._labelmapImageIdReferenceMap.get(i),a=Array.from(new Set([...o,n]));this._labelmapImageIdReferenceMap.set(i,a)}_setActiveSegmentation(e,r,n){const i=e.viewportSegRepresentations[r];i&&i.forEach(o=>{o.active=o.segmentationId===n})}setActiveSegmentation(e,r){this.updateState(n=>{const i=n.viewportSegRepresentations[e];i&&i.forEach(o=>{o.active=o.segmentationId===r})}),Gs(e,r)}getActiveSegmentation(e){if(!this.state.viewportSegRepresentations[e])return;const r=this.state.viewportSegRepresentations[e].find(n=>n.active);if(r)return this.getSegmentation(r.segmentationId)}getSegmentationRepresentations(e,r={}){const n=this.state.viewportSegRepresentations[e];return n?!r.type&&!r.segmentationId?n:n.filter(i=>{const o=r.type?i.type===r.type:!0,a=r.segmentationId?i.segmentationId===r.segmentationId:!0;return o&&a}):[]}getSegmentationRepresentation(e,r){return this.getSegmentationRepresentations(e,r)[0]}getSegmentationRepresentationVisibility(e,r){const n=this.getSegmentationRepresentation(e,r);return n==null?void 0:n.visible}setSegmentationRepresentationVisibility(e,r,n){this.updateState(i=>{const o=this.getSegmentationRepresentations(e,r);o&&o.forEach(a=>{a.visible=n,Object.entries(a.segments).forEach(([s,c])=>{c.visible=n})})}),Gs(e,r.segmentationId,r.type)}addColorLUT(e,r){this.updateState(n=>{n.colorLUT[r]&&console.warn("Color LUT table already exists, overwriting"),n.colorLUT[r]=Fa(e)})}removeColorLUT(e){this.updateState(r=>{delete r.colorLUT[e]})}_getStackIdForImageIds(e){return e.map(r=>r.slice(-Math.round(r.length*.15))).join("_")}getAllViewportSegmentationRepresentations(){return Object.entries(this.state.viewportSegRepresentations).map(([e,r])=>({viewportId:e,representations:r}))}getSegmentationRepresentationsBySegmentationId(e){const r=[];return Object.entries(this.state.viewportSegRepresentations).forEach(([n,i])=>{const o=i.filter(a=>a.segmentationId===e);o.length>0&&r.push({viewportId:n,representations:o})}),r}_generateMapKey({segmentationId:e,referenceImageId:r}){return`${e}-${r}`}}async function ak({imageIds:t,options:e}){const r=t,n=(e==null?void 0:e.volumeId)||Dn();return await QL(n,r),{volumeId:n}}async function nfe({segmentationId:t,options:e}){const r=Zn.getSegmentation(t),n=r.representationData.Labelmap,{volumeId:i}=await ak({imageIds:n.imageIds,options:e});r.representationData.Labelmap.volumeId=i}function sD(t){const e=Xc.newInstance(),r=Jf.newInstance();return r.addPoint(0,0),t===Dt.Labelmap?{cfun:e,ofun:r}:{}}const Zn=new tfe("DEFAULT");function Jo(t,e={}){return Zn.getSegmentationRepresentations(t,e)}function t4(t,e){const r=Zn;if(!e.segmentationId||!e.type)throw new Error("getSegmentationRepresentation: No segmentationId or type provided, you need to provide at least one of them");const n=r.getSegmentationRepresentations(t,e);return n==null?void 0:n[0]}function sk(t){return Zn.getSegmentationRepresentationsBySegmentationId(t)}function rfe(t,e){const r=Ce(t),{viewport:n}=r,o=n.getActors().filter(a=>a.representationUID&&typeof a.representationUID=="string"&&a.representationUID.startsWith(e));n.removeActors(o.map(a=>a.uid))}function ck(t,e,r){const n=zn(t);if(!n)return;const{renderingEngine:i,viewport:o}=n;if(!i||!o)return;const s=o.getActors().filter(r);return s.length>0?s[0]:void 0}function ife(t,e){const r=zn(t);if(!r)return;const{renderingEngine:n,viewport:i}=r;if(!n||!i)return;const a=i.getActors().filter(e);return a.length>0?a:void 0}function ofe(t,e){const r=_5(t,e);return r==null?void 0:r.uid}function Wg(t,e){return ife(t,r=>{var n;return(n=r.representationUID)==null?void 0:n.startsWith(`${e}-${Dt.Labelmap}`)})}function _5(t,e){return ck(t,e,r=>{var n;return(n=r.representationUID)==null?void 0:n.startsWith(`${e}-${Dt.Labelmap}`)})}function afe(t,e,r){return ck(t,e,n=>n.representationUID===lk(e,r))}function lk(t,e){return`${t}-${Dt.Surface}-${e}`}function sfe(t,e,r){const n=Ce(t),{viewport:i}=n,o=afe(i.id,r,e.segmentIndex),a=o==null?void 0:o.actor,s=e.visible;if(a){if(a.setVisibility(s),!s)return;const y=a.getMapper(),m=y.getInputData(),w=e.points,x=e.polys,C=m.getPoints().getData(),S=m.getPolys().getData();if(w.length===C.length&&x.length===S.length)return;const _=Xo.newInstance();_.getPoints().setData(w,3);const T=Yf.newInstance({values:Float32Array.from(x)});_.setPolys(T),y.setInputData(_),y.modified(),i.getRenderer().resetCameraClippingRange();return}const c=e.points,l=e.polys,f=e.color,u=Xo.newInstance();u.getPoints().setData(c,3);const d=Yf.newInstance({values:Float32Array.from(l)});u.setPolys(d);const h=g1.newInstance({});let g;h.setInputData(u);const p=Qy.newInstance();p.setMapper(h),p.getProperty().setColor(f[0]/255,f[1]/255,f[2]/255),p.getProperty().setLineWidth(2);const v=lk(r,e.segmentIndex);i.addActor({uid:Dn(),actor:p,clippingFilter:g,representationUID:v}),i.resetCamera(),i.getRenderer().resetCameraClippingRange(),i.render()}function Ln(t){return Zn.getSegmentation(t)}function D1(t){return Zn.getColorLUT(t)}let qv={};function cfe(){return qv}function lfe(t){qv=t}let cD=!1;function Gc(){var e;if(!((e=qv.addons)!=null&&e.polySeg))return console.warn("PolySeg add-on not configured. This will prevent automatic conversion between segmentation representations (labelmap, contour, surface). To enable these features, install @cornerstonejs/polymorphic-segmentation and register it during initialization: cornerstoneTools.init({ addons: { polySeg } })."),null;const t=qv.addons.polySeg;return cD||(t.init(),cD=!0),t}function n4({segmentationId:t,type:e,data:r}){const n=Ln(t);if(!n)throw new Error(`Segmentation ${t} not found`);switch(n.representationData[e]&&console.warn(`Representation data of type ${e} already exists for segmentation ${t}, overwriting it.`),e){case Dt.Labelmap:r&&(n.representationData[e]=r);break;case Dt.Contour:r&&(n.representationData[e]=r);break;case Dt.Surface:r&&(n.representationData[e]=r);break;default:throw new Error(`Invalid representation type ${e}`)}}function r4(t){const e=typeof t;return t!==null&&(e==="object"||e==="function")}function gh(t,e,r){let n,i,o,a,s,c,l=0,f=!1,u=!1,d=!0;const h=!e&&e!==0&&typeof window.requestAnimationFrame=="function";if(typeof t!="function")throw new TypeError("Expected a function");e=Number(e)||0,r4(r)&&(f=!!r.leading,u="maxWait"in r,o=u?Math.max(Number(r.maxWait)||0,e):o,d="trailing"in r?!!r.trailing:d);function g(D){const b=n,I=i;return n=i=void 0,l=D,a=t.apply(I,b),a}function p(D,b){return h?window.requestAnimationFrame(D):setTimeout(D,b)}function v(D){if(h)return window.cancelAnimationFrame(D);clearTimeout(D)}function y(D){return l=D,s=p(x,e),f?g(D):a}function m(D){const b=D-c,I=D-l,P=e-b;return u?Math.min(P,o-I):P}function w(D){const b=D-c,I=D-l;return c===void 0||b>=e||b<0||u&&I>=o}function x(){const D=Date.now();if(w(D))return C(D);s=p(x,m(D))}function C(D){return s=void 0,d&&n?g(D):(n=i=void 0,a)}function S(){s!==void 0&&v(s),l=0,n=c=i=s=void 0}function _(){return s===void 0?a:C(Date.now())}function T(){return s!==void 0}function E(...D){const b=Date.now(),I=w(b);if(n=D,i=this,c=b,I){if(s===void 0)return y(c);if(u)return s=p(x,e),g(c)}return s===void 0&&(s=p(x,e)),a}return E.cancel=S,E.flush=_,E.pending=T,E}const P2=new Map;async function i4(t,e,r,n,i){const o=await r();n4({segmentationId:t,type:e,data:o}),i==null||i(),P2.has(t)||P2.set(t,[]);const a=P2.get(t);return a.includes(e)||a.push(e),ufe(n),Ta(t),o}function ufe(t){const e=r=>{ffe(r,t)};t._debouncedUpdateFunction=e,Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,t._debouncedUpdateFunction),Ke.addEventListener(N.SEGMENTATION_DATA_MODIFIED,t._debouncedUpdateFunction)}const ffe=gh((t,e)=>{const r=t.detail.segmentationId,n=P2.get(r);!n||!n.length||(e(r),n.length&&Ta(r))},300);function o4(t,e){const r=t4(t,e);return r?Object.entries(r.segments).reduce((i,[o,a])=>(a.visible||i.add(Number(o)),i),new Set):new Set}function dfe(t,e,r=!1){const n=zn(t);if(!n)return;const{viewport:i}=n;rfe(i.element,e),r&&i.render()}async function hfe(t,e){var l;const{segmentationId:r,type:n}=e,i=Ln(r);if(!i)return;let o=i.representationData[Dt.Surface];if(!o&&((l=Gc())!=null&&l.canComputeRequestedRepresentation(r,Dt.Surface))){const f=Gc();if(o=await i4(r,Dt.Surface,()=>f.computeSurfaceData(r,{viewport:t}),()=>f.updateSurfaceData(r,{viewport:t})),!o)throw new Error(`No Surface data found for segmentationId ${r} even we tried to compute it`)}else!o&&!Gc()&&console.debug(`No surface data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to surface. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(!o){console.warn(`No Surface data found for segmentationId ${r}. Skipping render.`);return}const{geometryIds:a}=o;a!=null&&a.size||console.warn(`No Surfaces found for segmentationId ${r}. Skipping render.`);const{colorLUTIndex:s}=e,c=D1(s);a.forEach(f=>{const u=Le.getGeometry(f);if(!(u!=null&&u.data)){console.warn(`No Surfaces found for geometryId ${f}. Skipping render.`);return}const{segmentIndex:d}=u.data,g=o4(t.id,{segmentationId:r,type:n}).has(d),p=u.data,v=c[d];p.color=v.slice(0,3),p.visible=!g,sfe(t.element,p,r)}),t.render()}const uk={render:hfe,removeRepresentation:dfe};function gfe(t,e,r,n){const i=t.getViewReference(),{viewPlaneNormal:o,FrameOfReferenceUID:a}=i,s={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:e,viewPlaneNormal:o,FrameOfReferenceUID:a,referencedImageId:pfe(t,r[0],o),...n}};return nn(s,t.element),s}function pfe(t,e,r){let n;if(t instanceof lr)n=a4(t,e,r);else if(t instanceof Ir){const i=mfe(t),o=sc(i),a=Le.getVolume(o);n=qc(a,e,r)}else throw new Error("getReferencedImageId: viewport must be a StackViewport or BaseVolumeViewport");return n}function mfe(t){var r;const e=(r=t.getViewReferenceId)==null?void 0:r.call(t);if(e)return e;if(t instanceof Ir)return`volumeId:${vfe(t)}`;throw new Error("getTargetId: viewport must have a getTargetId method")}function vfe(t){var r;const e=t.getActors();if(e)return(r=e.find(n=>n.actor.getClassName()==="vtkVolume"))==null?void 0:r.uid}function a4(t,e,r){const n=t.getImageIds();if(!n||!n.length)return;const i=n.map(o=>{const{imagePositionPatient:a}=mt("imagePlaneModule",o),s=yfe(e,a,r);return{imageId:o,distance:s}});return i.sort((o,a)=>o.distance-a.distance),i[0].imageId}function yfe(t,e,r){const n=Ve();En(n,t,e);const i=Et(n,r);return Math.abs(i)}function fk(t,e){const{segmentation:r}=t.data,{segmentation:n}=e.data;return r.segmentationId===n.segmentationId&&r.segmentIndex===n.segmentIndex}class dk{constructor(e){this.getGroupKey=r=>{if(typeof r=="string")return r;const i=Ce(r);if(!i)throw new Error("Element not enabled, you must have an enabled element if you are not providing a FrameOfReferenceUID");return i.FrameOfReferenceUID},this._imageVolumeModifiedHandler=r=>{const n=r.detail,{FrameOfReferenceUID:i}=n,a=this.annotations[i];a&&Object.keys(a).forEach(s=>{a[s].forEach(l=>{l.invalidated!==void 0&&(l.invalidated=!0)})})},this.getFramesOfReference=()=>Object.keys(this.annotations),this.getAnnotations=(r,n)=>{const i=this.annotations;return i[r]?n?i[r][n]?i[r][n]:[]:i[r]:[]},this.getAnnotation=r=>{const n=this.annotations;for(const i in n){const o=n[i];for(const a in o){const s=o[a];for(const c of s)if(r===c.annotationUID)return c}}},this.getNumberOfAnnotations=(r,n)=>{const i=this.getAnnotations(r,n);if(!i.length)return 0;if(n)return i.length;let o=0;for(const a in i)o+=i[a].length;return o},this.addAnnotation=(r,n)=>{const{metadata:i}=r,{FrameOfReferenceUID:o,toolName:a}=i;n=n||o;const s=this.annotations;let c=s[n];c||(s[n]={},c=s[n]);let l=c[a];l||(c[a]=[],l=c[a]),this.preprocessingFn&&(r=this.preprocessingFn(r)),l.push(r)},this.removeAnnotation=r=>{const{annotations:n}=this;for(const i in n){const o=n[i];for(const a in o){const s=o[a],c=s.findIndex(l=>l.annotationUID===r);c!==-1&&(s.splice(c,1),s.length===0&&delete o[a])}Object.keys(o).length===0&&delete n[i]}},this.removeAnnotations=(r,n)=>{const i=this.annotations,o=[];if(!i[r])return o;if(n){const a=i[r][n];for(const s of a)this.removeAnnotation(s.annotationUID),o.push(s)}else for(const a in i[r]){const s=i[r][a];for(const c of s)this.removeAnnotation(c.annotationUID),o.push(c)}return o},this.saveAnnotations=(r,n)=>{const i=this.annotations;if(r&&n){const o=i[r];if(!o)return;const a=o[n];return structuredClone(a)}else if(r){const o=i[r];return structuredClone(o)}return structuredClone(i)},this.restoreAnnotations=(r,n,i)=>{const o=this.annotations;if(n&&i){let a=o[n];a||(o[n]={},a=o[n]),a[i]=r}else n?o[n]=r:this.annotations=structuredClone(r)},this.getAllAnnotations=()=>Object.values(this.annotations).map(r=>Object.values(r)).flat(2),this.getNumberOfAllAnnotations=()=>{let r=0;const n=this.annotations;for(const i in n){const o=n[i];for(const a in o){const s=o[a];r+=s.length}}return r},this.removeAllAnnotations=()=>{const r=[];for(const n of this.getAllAnnotations())this.removeAnnotation(n.annotationUID),r.push(n);return r},e||(e=Dn()),this.annotations={},this.uid=e,Ke.addEventListener(Xe.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedHandler)}setPreprocessingFn(e){this.preprocessingFn=e}}const wfe=new dk("DEFAULT"),fu=new Set;function hk(t,e=!0){const r=pk();t&&(e?_fe(t,fu,r):mk(t,fu,r)),vk(r,fu)}function xfe(){const t=pk();Tfe(fu,t),vk(t,fu)}function Cfe(){return Array.from(fu)}function Zr(t){return fu.has(t)}function Sfe(){return fu.size}function gk(t){const e=Zr(t);return hk(t,e),e}function pk(){return Object.freeze({added:[],removed:[],locked:[]})}function _fe(t,e,r){if(!e.has(t)){e.add(t),r.added.push(t);const n=Br(t);n&&(n.isLocked=!0)}}function mk(t,e,r){if(e.delete(t)){r.removed.push(t);const n=Br(t);n&&(n.isLocked=!1)}}function Tfe(t,e){t.forEach(r=>{mk(r,t,e)})}function vk(t,e){(t.added.length>0||t.removed.length>0)&&(e.forEach(r=>void t.locked.push(r)),at(Ke,N.ANNOTATION_LOCK_CHANGE,t))}const Efe=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationLocked:gk,getAnnotationsLocked:Cfe,getAnnotationsLockedCount:Sfe,isAnnotationLocked:Zr,setAnnotationLocked:hk,unlockAllAnnotations:xfe},Symbol.toStringTag,{value:"Module"})),Ws=new Set;function Ro(t,e=!0,r=!1){e?Dfe(t,r):s4(t)}function Dfe(t,e=!1){const r=wk();if(!e){xk(Ws,r);const n=Br(t);n&&(n.isSelected=!0)}if(t&&!Ws.has(t)){Ws.add(t),r.added.push(t);const n=Br(t);n&&(n.isSelected=!0)}Ck(r,Ws)}function s4(t){const e=wk();if(t){if(Ws.delete(t)){e.removed.push(t);const r=Br(t);r.isSelected=!1}}else xk(Ws,e);Ck(e,Ws)}function yk(){return Array.from(Ws)}function bfe(t){return yk().filter(e=>{var n;const r=Br(e);return((n=r==null?void 0:r.metadata)==null?void 0:n.toolName)===t})}function b1(t){return Ws.has(t)}function Ife(){return Ws.size}function wk(){return Object.freeze({added:[],removed:[],selection:[]})}function xk(t,e){t.forEach(r=>{if(t.delete(r)){e.removed.push(r);const n=Br(r);n&&(n.isSelected=!1)}})}function Ck(t,e){(t.added.length>0||t.removed.length>0)&&(e.forEach(r=>void t.selection.push(r)),at(Ke,N.ANNOTATION_SELECTION_CHANGE,t))}const Ofe=Object.freeze(Object.defineProperty({__proto__:null,deselectAnnotation:s4,getAnnotationsSelected:yk,getAnnotationsSelectedByToolName:bfe,getAnnotationsSelectedCount:Ife,isAnnotationSelected:b1,setAnnotationSelected:Ro},Symbol.toStringTag,{value:"Module"})),Mfe=t=>(t.data||(t.data={}),t.data.handles||(t.data.handles={}),t.data.handles.textBox||(t.data.handles.textBox={}),t),Pfe=t=>(t.data||(t.data={}),t.data.cachedStats||(t.data.cachedStats={}),t),Qf=new Set;function Sk(t,e=!0){const r=_k();t&&(e?Tk(t,Qf,r):Lfe(t,Qf,r)),Ek(r)}function Rfe(){const t=_k();Qf.forEach(e=>{Tk(e,Qf,t)}),Ek(t)}function Gr(t){if(Br(t))return!Qf.has(t)}function _k(){return Object.freeze({lastVisible:[],lastHidden:[],hidden:[]})}function Tk(t,e,r){if(e.delete(t)){r.lastVisible.push(t);const n=Br(t);n.isVisible=!0}}function Lfe(t,e,r){e.has(t)||(e.add(t),b1(t)&&s4(t),r.lastHidden.push(t))}function Ek(t){(t.lastHidden.length>0||t.lastVisible.length>0)&&(Qf.forEach(e=>void t.hidden.push(e)),at(Ke,N.ANNOTATION_VISIBILITY_CHANGE,t))}function Dk(t){const e=!Qf.has(t);return Sk(t,e),e}const Afe=Object.freeze(Object.defineProperty({__proto__:null,checkAndSetAnnotationVisibility:Dk,isAnnotationVisible:Gr,setAnnotationVisibility:Sk,showAllAnnotations:Rfe},Symbol.toStringTag,{value:"Module"})),c4=wfe,Nfe=t=>{t=Mfe(t),t=Pfe(t);const e=t.annotationUID,r=gk(e);t.isLocked=r;const n=Dk(e);return t.isVisible=n,t};c4.setPreprocessingFn(Nfe);qT(c4);function kfe(){qT(c4)}function Yc(t){if(!t.data.segmentation)throw new Error("removeContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:e,segmentIndex:r}=t.data.segmentation,n=Ln(e),{annotationUIDsMap:i}=(n==null?void 0:n.representationData.Contour)||{},o=i==null?void 0:i.get(r);o&&(o.delete(t.annotationUID),o.size||i.delete(r))}function Jc(t){if(t.parentAnnotationUID)return;if(!t.data.segmentation)throw new Error("addContourSegmentationAnnotation: annotation does not have a segmentation data");const{segmentationId:e,segmentIndex:r}=t.data.segmentation,n=Ln(e);n.representationData.Contour||(n.representationData.Contour={annotationUIDsMap:new Map});let{annotationUIDsMap:i}=n.representationData.Contour;i||(i=new Map);let o=i==null?void 0:i.get(r);o||(o=new Set,i.set(r,o)),i.set(r,o.add(t.annotationUID))}const Vfe="PlanarFreehandContourSegmentationTool";function l4(t){var o;const{polyline:e}=((o=t.data)==null?void 0:o.contour)||{};if(!e||e.length<3){console.warn("Skipping creation of new annotation due to invalid polyline:",e);return}gn(t.annotationUID),Yc(t);const r=e[0],n=e[e.length-1],i={metadata:{...t.metadata,toolName:Vfe,originalToolName:t.metadata.originalToolName||t.metadata.toolName},data:{cachedStats:{},handles:{points:[r,n],textBox:t.data.handles.textBox?{...t.data.handles.textBox}:void 0},contour:{...t.data.contour},spline:t.data.spline,segmentation:{...t.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:t.interpolationUID,interpolationCompleted:t.interpolationCompleted};return nn(i,t.metadata.FrameOfReferenceUID),Jc(i),i}var Lo;(function(t){t[t.CounterClockwise=-1]="CounterClockwise",t[t.Unknown=0]="Unknown",t[t.Clockwise=1]="Clockwise"})(Lo||(Lo={}));function u4(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Xv(t,e){const r=t.maxX-t.minX,n=t.maxY-t.minY,i=[r,n],o=[t.minX+r/2,t.minY+n/2],a=[Math.abs(e[0]-o[0]),Math.abs(e[1]-o[1])],s=a[0]-i[0]*.5,c=a[1]-i[1]*.5;if(s>0&&c>0)return s*s+c*c;const l=Math.max(s,0)+Math.max(c,0);return l*l}function Ffe(t,e){return Math.sqrt(Xv(t,e))}const Ufe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:Ffe,distanceToPointSquared:Xv,intersectAABB:u4},Symbol.toStringTag,{value:"Module"}));class bk{}class Ik{constructor(e){this.storePointData=e.storePointData}getStatistics(){console.debug("InstanceCalculator getStatistics called")}}const{PointsManager:Bfe}=Mn;function Wp(t){return{max:[-1/0],min:[1/0],sum:[0],count:0,maxIJK:null,maxLPS:null,minIJK:null,minLPS:null,runMean:[0],m2:[0],m3:[0],m4:[0],allValues:[[]],pointsInShape:t?Bfe.create3(1024):null,sumLPS:[0,0,0]}}function Ok(t,e,r=null,n=null){Array.isArray(e)&&e.length>1&&t.max.length===1&&(t.max.push(t.max[0],t.max[0]),t.min.push(t.min[0],t.min[0]),t.sum.push(t.sum[0],t.sum[0]),t.runMean.push(0,0),t.m2.push(t.m2[0],t.m2[0]),t.m3.push(t.m3[0],t.m3[0]),t.m4.push(t.m4[0],t.m4[0]),t.allValues.push([],[])),t!=null&&t.pointsInShape&&r&&t.pointsInShape.push(r);const i=Array.isArray(e)?e:[e];t.count+=1,r&&(t.sumLPS[0]+=r[0],t.sumLPS[1]+=r[1],t.sumLPS[2]+=r[2]),t.max.forEach((o,a)=>{const s=i[a];t.allValues[a].push(s);const c=t.count,l=s-t.runMean[a],f=l/c,u=l*f*(c-1);t.sum[a]+=s,t.runMean[a]+=f,t.m4[a]+=u*f*f*(c*c-3*c+3)+6*f*f*t.m2[a]-4*f*t.m3[a],t.m3[a]+=u*f*(c-2)-3*f*t.m2[a],t.m2[a]+=u,st.max[a]&&(t.max[a]=s,a===0&&(t.maxIJK=n?[...n]:null,t.maxLPS=r?[...r]:null))})}function Gfe(t){if(t.length===0)return 0;const e=[...t].sort((n,i)=>n-i),r=Math.floor(e.length/2);return e.length%2===0?(e[r-1]+e[r])/2:e[r]}function Mk(t,e){const r=t.sum.map(u=>u/t.count),n=t.m2.map(u=>Math.sqrt(u/t.count)),i=t.sumLPS.map(u=>u/t.count),o=t.m3.map((u,d)=>{const h=t.m2[d]/t.count;return h===0?0:u/(t.count*Math.pow(h,1.5))}),a=t.m4.map((u,d)=>{const h=t.m2[d]/t.count;return h===0?0:u/(t.count*h*h)-3}),s=t.allValues.map(u=>Gfe(u)),c={max:{name:"max",label:"Max Pixel",value:t.max.length===1?t.max[0]:t.max,unit:e,pointIJK:t.maxIJK?[...t.maxIJK]:null,pointLPS:t.maxLPS?[...t.maxLPS]:null},min:{name:"min",label:"Min Pixel",value:t.min.length===1?t.min[0]:t.min,unit:e,pointIJK:t.minIJK?[...t.minIJK]:null,pointLPS:t.minLPS?[...t.minLPS]:null},mean:{name:"mean",label:"Mean Pixel",value:r.length===1?r[0]:r,unit:e},stdDev:{name:"stdDev",label:"Standard Deviation",value:n.length===1?n[0]:n,unit:e},count:{name:"count",label:"Voxel Count",value:t.count,unit:null},median:{name:"median",label:"Median",value:s.length===1?s[0]:s,unit:e},skewness:{name:"skewness",label:"Skewness",value:o.length===1?o[0]:o,unit:null},kurtosis:{name:"kurtosis",label:"Kurtosis",value:a.length===1?a[0]:a,unit:null},maxLPS:{name:"maxLPS",label:"Max LPS",value:t.maxLPS?Array.from(t.maxLPS):null,unit:null},minLPS:{name:"minLPS",label:"Min LPS",value:t.minLPS?Array.from(t.minLPS):null,unit:null},pointsInShape:t.pointsInShape,center:{name:"center",label:"Center",value:i?[...i]:null,unit:null},array:[]};c.array.push(c.min,c.max,c.mean,c.stdDev,c.median,c.skewness,c.kurtosis,c.count,c.maxLPS,c.minLPS),c.center.value&&c.array.push(c.center);const l=t.pointsInShape!==null,f=Wp(l);return t.max=f.max,t.min=f.min,t.sum=f.sum,t.count=f.count,t.maxIJK=f.maxIJK,t.maxLPS=f.maxLPS,t.minIJK=f.minIJK,t.minLPS=f.minLPS,t.runMean=f.runMean,t.m2=f.m2,t.m3=f.m3,t.m4=f.m4,t.allValues=f.allValues,t.pointsInShape=f.pointsInShape,t.sumLPS=f.sumLPS,c}const Ef=class Ef extends bk{static statsInit(e){e.storePointData||(this.state.pointsInShape=null),this.state=Wp(e.storePointData)}};Ef.state=Wp(!0),Ef.statsCallback=({value:e,pointLPS:r=null,pointIJK:n=null})=>{Ok(Ef.state,e,r,n)},Ef.getStatistics=e=>Mk(Ef.state,e==null?void 0:e.unit);let rc=Ef;class Pk extends Ik{constructor(e){super(e),this.state=Wp(e.storePointData)}statsInit(e){this.state=Wp(e.storePointData)}statsCallback(e){Ok(this.state,e.value,e.pointLPS,e.pointIJK)}getStatistics(e){return Mk(this.state,e==null?void 0:e.unit)}}const Wfe=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:rc,Calculator:bk,InstanceBasicStatsCalculator:Pk,InstanceCalculator:Ik},Symbol.toStringTag,{value:"Module"}));function Zc(t,e){if(t.length!==e.length)throw Error("Both points should have the same dimensionality");const[r,n,i=0]=t,[o,a,s=0]=e,c=o-r,l=a-n,f=s-i;return c*c+l*l+f*f}function yo(t,e){return Math.sqrt(Zc(t,e))}function wC(t,e){const[r,n]=t,[i,o]=e,a=2*i-r,s=2*o-n;return[a,s]}const zfe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:yo,distanceToPointSquared:Zc,mirror:wC},Symbol.toStringTag,{value:"Module"}));function du(t){const[e,r]=t;return yo(e,r)}function x0(t){const[e,r]=t,n=yo(e,r),i=[e[0]-n,e[1]-n],o=[e[0]+n,e[1]+n];return[i,o]}const $fe=Object.freeze(Object.defineProperty({__proto__:null,getCanvasCircleCorners:x0,getCanvasCircleRadius:du},Symbol.toStringTag,{value:"Module"}));function T5(t,e,r={}){return r.precalculated||f4(t,r),r.precalculated(e)}const f4=(t,e={})=>{const{xRadius:r,yRadius:n,zRadius:i}=t;(e.invXRadiusSq===void 0||e.invYRadiusSq===void 0||e.invZRadiusSq===void 0)&&(e.invXRadiusSq=r!==0?1/r**2:0,e.invYRadiusSq=n!==0?1/n**2:0,e.invZRadiusSq=i!==0?1/i**2:0);const{invXRadiusSq:o,invYRadiusSq:a,invZRadiusSq:s}=e,{center:c}=t,[l,f,u]=c;return e.precalculated=d=>{const h=d[0]-l;let g=h*h*o;if(g>1)return!1;const p=d[1]-f;if(g+=p*p*a,g>1)return!1;const v=d[2]-u;return g+=v*v*s,g<=1},e};function Yv(t){const[e,r,n,i]=t,o=[n[0],r[1]],a=[i[0],e[1]];return[o,a]}const jfe=Object.freeze(Object.defineProperty({__proto__:null,getCanvasEllipseCorners:Yv,pointInEllipse:T5,precalculatePointInEllipse:f4},Symbol.toStringTag,{value:"Module"}));function Jv(t,e,r){let n;const i=Zc(t,e);if(t[0]===e[0]&&t[1]===e[1]&&(n=t),!n){const o=((r[0]-t[0])*(e[0]-t[0])+(r[1]-t[1])*(e[1]-t[1]))/i;o<0?n=t:o>1?n=e:n=[t[0]+o*(e[0]-t[0]),t[1]+o*(e[1]-t[1])]}return{point:[...n],distanceSquared:Zc(r,n)}}function I1(t,e,r){return Jv(t,e,r).distanceSquared}function hi(t,e,r){if(t.length!==2||e.length!==2||r.length!==2)throw Error("lineStart, lineEnd, and point should have 2 elements of [x, y]");return Math.sqrt(I1(t,e,r))}function Om(t){return typeof t=="number"?t?t<0?-1:1:t===t?0:NaN:NaN}function Zv(t,e,r,n,i=!1){const[o,a]=t,[s,c]=e,[l,f]=r,[u,d]=n;if(i){const I=(o-s)*(f-d)-(a-c)*(l-u);if(Math.abs(I)<1e-10)return;const P=((o-l)*(f-d)-(a-f)*(l-u))/I,M=o+P*(s-o),L=a+P*(c-a);return[M,L]}const h=c-a,g=o-s,p=s*a-o*c,v=h*l+g*f+p,y=h*u+g*d+p;if(v!==0&&y!==0&&Om(v)===Om(y))return;const m=d-f,w=l-u,x=u*f-l*d,C=m*o+w*a+x,S=m*s+w*c+x;if(C!==0&&S!==0&&Om(C)===Om(S))return;const _=h*w-m*g;let T;T=g*x-w*p;const E=T/_;T=m*p-h*x;const D=T/_;return[E,D]}const qh=.01;function R2(t,e,r){const n=t[0]<=e[0]?t[0]:e[0],i=t[0]>=e[0]?t[0]:e[0],o=t[1]<=e[1]?t[1]:e[1],a=t[1]>=e[1]?t[1]:e[1];if(!(r[0]>=n-qh&&r[0]<=i+qh&&r[1]>=o-qh&&r[1]<=a+qh))return!1;const c=(e[1]-t[1])*(r[0]-e[0])-(e[0]-t[0])*(r[1]-e[1]);return(c>=0?c:-c)<=qh}const Hfe=Object.freeze(Object.defineProperty({__proto__:null,distanceToPoint:hi,distanceToPointSquared:I1,distanceToPointSquaredInfo:Jv,intersectLine:Zv,isPointOnLineSegment:R2},Symbol.toStringTag,{value:"Module"}));function Rk(t){if(t.length<3)return!1;const e=t.length,r=t[0],n=t[e-1],i=Zc(r,n);return vu(0,i)}function _u(t,e,r={closed:void 0}){if(t.length<3)return!1;const n=t.length;let i=0;const{closed:o,holes:a}=r;if(a!=null&&a.length){for(const l of a)if(_u(l,e))return!1}const s=!(o===void 0?Rk(t):o),c=t.length-(s?1:2);for(let l=0;l<=c;l++){const f=t[l],u=l===n-1?0:l+1,d=t[u],h=f[0]>=d[0]?f[0]:d[0],g=f[1]>=d[1]?f[1]:d[1],p=f[1]<=d[1]?f[1]:d[1];if(e[0]<=h&&e[1]>=p&&e[1]h?s:h,c=c>g?c:g,i&&(l=lp?f:p)}return i?{minX:o,maxX:s,minY:a,maxY:c,minZ:l,maxZ:f}:{minX:o,maxX:s,minY:a,maxY:c}}function M1(t){const e=t.length;let r=0,n=e-1;for(let i=0;i=0?1:-1}function Kfe(t){const e=Ve(),r=t[0];for(let n=0,i=t.length;ne[0]?t[0]:e[0],c=t[1]>e[1]?t[1]:e[1],l=r[0]n[0]?r[0]:n[0],d=r[1]>n[1]?r[1]:n[1];if(o>u||sd||c0?1:2}function Pm(t,e,r){return e[0]<=Math.max(t[0],r[0])&&e[0]>=Math.min(t[0],r[0])&&e[1]<=Math.max(t[1],r[1])&&e[1]>=Math.min(t[1],r[1])}function g4(t,e,r,n=!0){const i=[],o=t.length,a=o-(n?1:2);for(let s=0;s<=a;s++){const c=t[s],l=s===o-1?0:s+1,f=t[l];h4(e,r,c,f)&&i.push([s,l])}return i}const Xfe=.01;function Lk(t,e,r,n){const i=[e[0]-t[0],e[1]-t[1]],o=[n[0]-r[0],n[1]-r[1]],a=o[1]*i[0]-o[0]*i[1];if((a>=0?a:-a)e[0]?t[0]:e[0],t[1]e[1]?t[1]:e[1]],p=[r[0]n[0]?r[0]:n[0],r[1]n[1]?r[1]:n[1]];if(!(g[0]<=p[1]&&g[1]>=p[0]&&g[2]<=p[3]&&g[3]>=p[2])||!(R2(t,e,r)||R2(t,e,n)||R2(r,n,t)))return;const m=g[0]>p[0]?g[0]:p[0],w=g[1]p[2]?g[2]:p[2],C=g[3]{const p=g[0],v=e[g[0]],y=e[g[1]],m=Lk(l,d,v,y),w=Zc(l,m);return{sourceLineSegmentId:p,coordinate:m,targetStartPointDistSquared:w}});h.sort((g,p)=>g.targetStartPointDistSquared-p.targetStartPointDistSquared),h.forEach(g=>{const{sourceLineSegmentId:p,coordinate:v}=g,y={type:Ff.Intersection,coordinates:v,position:C0.Edge,direction:a,visited:!1,next:null},m={...y,direction:Kd.Unknown,cloned:!0};a===Kd.Entering?y.next=m:m.next=y;let w=i.get(p);w||(w=[],i.set(p,w)),r.push(y),w.push(m),a*=-1})}for(let s=0,c=e.length;s({intersectionPoint:h,lineSegStartDistSquared:Zc(f,h.coordinates)})).sort((h,g)=>h.lineSegStartDistSquared-g.lineSegStartDistSquared).map(({intersectionPoint:h})=>h).forEach(h=>n.push(h))}return lD(r),lD(n),{targetPolylinePoints:r,sourcePolylinePoints:n}}function Nk(t){for(let e=0,r=t.length;e=f&&console.warn("Maximum iterations reached in mergePolylines, possible infinite loop detected"),s}function D5(t,e){const r=zp(t),n=zp(e),i=Et(n,r);vu(-1,i)||(e=e.slice().reverse());const{targetPolylinePoints:o}=Ak(t,e);let a=null;const s=[];let c=0;const l=t.length*2;for(;(a=Nk(o))&&c=h&&console.warn("Maximum inner iterations reached in subtractPolylines, possible infinite loop detected"),s.push(f)}return c>=l&&console.warn("Maximum outer iterations reached in subtractPolylines, possible infinite loop detected"),s}function kk(t,e,r,n=!0){let i,o;n?(o=t.length-1,i=0):(o=0,i=1);for(let a=i;ad&&(d=v,h=g)}d{const u=[t[f[0]],t[f[1]]],d=[(u[0][0]+u[1][0])/2,(u[0][1]+u[1][1])/2];s.push(yr(d,e))});const c=Math.min(...s),l=s.indexOf(c);return{segment:a[l],distance:c}}const Dd=.001,Zfe=(t,e)=>{let r,n,i;if(t instanceof lr){const a=t.getImageData();if(!a)return;n=a.direction.slice(0,3),i=a.direction.slice(3,6),r=a.spacing}else{const a=t.getImageData(),{direction:s,spacing:c}=a,{viewPlaneNormal:l,viewUp:f}=t.getCamera(),u=s.slice(0,3),d=s.slice(3,6),h=s.slice(6,9),g=Ve();Rn(g,f,l);const p=Math.abs(Et(g,u)),v=Math.abs(Et(g,d)),y=Math.abs(Et(g,h));let m;if(Math.abs(1-p)V_(t,e){const{xDir:i,yDir:o,spacing:a}=n,s=Ce(t),{viewport:c}=s;if(!e.length)return e.push(r),console.log(">>>>> !canvasPoints. :: RETURN"),1;const l=c.canvasToWorld(e[e.length-1]),f=c.canvasToWorld(r),u=Ve();rr(u,f,l);const d=Math.abs(Et(u,i)),h=Math.abs(Et(u,o)),g=Math.max(Math.floor(d/a[0]),Math.floor(h/a[0]));if(g>1){const p=e[e.length-1],v=V_(p,r),y=qt();Wr(y,r,p),Va(y,y[0]/v,y[1]/v);const m=v/g;for(let w=1;w<=g;w++)e.push([p[0]+m*y[0]*w,p[1]+m*y[1]*w])}else e.push(r);return g},tde=(t,e,r,n)=>{const i=[t[0]-e[0],t[1]-e[1]],o=[r[0]-e[0],r[1]-e[1]],a=i[0]*o[0]+i[1]*o[1];if(a<0)return!1;const s=Math.sqrt(o[0]*o[0]+o[1]*o[1]);if(s===0)return!1;const c=a/s,l=[o[0]/s,o[1]/s],f=[l[0]*c,l[1]*c],u=[e[0]+f[0],e[1]+f[1]];return!(yr(t,u)>n||yr(e,u)>yr(e,r))},nde=1e-6;function Fk(t){let e;const r=BT(t,50);for(let a=0;a<3;a++)if(r.every((s,c,l)=>Math.abs(s[a]-l[0][a])[o[0],o[1]]).sort((o,a)=>o[0]===a[0]?o[1]-a[1]:o[0]-a[0]);function r(o,a,s){return(a[0]-o[0])*(s[1]-o[1])-(a[1]-o[1])*(s[0]-o[0])}const n=[];for(const o of e){for(;n.length>=2&&r(n[n.length-2],n[n.length-1],o)<=0;)n.pop();n.push(o)}const i=[];for(let o=e.length-1;o>=0;o--){const a=e[o];for(;i.length>=2&&r(i[i.length-2],i[i.length-1],a)<=0;)i.pop();i.push(a)}return n.pop(),i.pop(),n.concat(i)}const ku=Object.freeze(Object.defineProperty({__proto__:null,addCanvasPointsToArray:ede,containsPoint:_u,containsPoints:O1,convexHull:Uk,decimate:m4,getAABB:Tu,getArea:M1,getClosestLineSegmentIntersection:Jfe,getFirstLineSegmentIntersectionIndexes:kk,getLineSegmentIntersectionsCoordinates:Vk,getLineSegmentIntersectionsIndexes:g4,getNormal2:zp,getNormal3:qfe,getSignedArea:d4,getSubPixelSpacingAndXYDirections:Zfe,getWindingDirection:L2,intersectPolyline:p4,isClosed:Rk,isPointInsidePolyline3D:v4,mergePolylines:E5,pointCanProjectOnLine:tde,pointsAreWithinCloseContourProximity:Qfe,projectTo2D:Fk,subtractPolylines:D5},Symbol.toStringTag,{value:"Module"}));function rde(t,e,r,n){const i=[t,e],o=[t+r,e],a=[t+r,e],s=[t+r,e+n],c=[t+r,e+n],l=[t,e+n],f=[t,e+n];return{top:[i,o],right:[a,s],bottom:[c,l],left:[f,[t,e]]}}function y4(t,e){if(t.length!==4||e.length!==2)throw Error("rectangle:[left, top, width, height] or point: [x,y] not defined correctly");const[r,n,i,o]=t;let a=655535;const s=rde(r,n,i,o);return Object.keys(s).forEach(c=>{const[l,f]=s[c],u=hi(l,f,e);u0){if(o>i)return 0;o>n&&(r[0]=o)}else{if(o=r[0]&&o<=r[2]&&a>=r[1]&&a<=r[3])return uD;const u=[0,1];if(Rm(r[0]-o,l,u)&&Rm(o-r[2],-l,u)&&Rm(r[1]-a,f,u)&&Rm(a-r[3],-f,u)){const[d,h]=u;return h<1&&(i[0]=o+h*l,i[1]=a+h*f),d>0&&(n[0]+=d*l,n[1]+=d*f),uD}return ade}const sde=Object.freeze(Object.defineProperty({__proto__:null,findClosestPoint:xC,liangBarksyClip:yg},Symbol.toStringTag,{value:"Module"}));function cde(t,e){const[r,n]=t,[i,o]=e,a=En(Ve(),n,r),s=En(Ve(),i,o),c=Et(a,s),l=Po(a),f=Po(s),u=c/(l*f);return Math.acos(u)*180/Math.PI}function lde(t,e){const[r,n]=t,[i,o]=e,a=Ga(qt(),n,r),s=Ga(qt(),i,o),c=k_(a,s),l=xv(a),f=xv(s),u=c/(l*f);return Math.acos(u)*(180/Math.PI)}function S0(t,e){return t[0].length===3?cde(t,e):lde(t,e)}const ude=Object.freeze(Object.defineProperty({__proto__:null,angleBetweenLines:S0},Symbol.toStringTag,{value:"Module"})),fde=Object.freeze(Object.defineProperty({__proto__:null,BasicStatsCalculator:Wfe,aabb:Ufe,angle:ude,circle:$fe,ellipse:jfe,lineSegment:Hfe,point:zfe,polyline:ku,rectangle:ide,vec2:sde},Symbol.toStringTag,{value:"Module"}));function Ds(t,e,r,n){var g,p,v;const{canvasToWorld:i,worldToCanvas:o}=r,{data:a}=t,{targetWindingDirection:s}=e;let{points:c}=e,l=L2(c);(g=n==null?void 0:n.decimate)!=null&&g.enabled&&(c=m4(e.points,(p=n==null?void 0:n.decimate)==null?void 0:p.epsilon));let{closed:f}=e;const u=c.length,d=new Array(u);L2(c);const h=SN(t);if(f===void 0){let y=!1;if(c.length>3){const m=Zc(c[0],c[u-1]);y=$t(0,m)}f=y}if((n==null?void 0:n.updateWindingDirection)!==!1){let y=h?h.data.contour.windingDirection*-1:s;y===void 0&&(y=l),y!==l&&c.reverse();const m=(((v=a.handles)==null?void 0:v.points)??[]).map(o);m.length>2&&L2(m)!==y&&a.handles.points.reverse(),l=y}for(let y=0;y{Be.svgNodeCache[i][a].touched=!1}),{svgLayerElement:o,svgNodeCacheForCanvas:Be.svgNodeCache,getSvgNode:pde.bind(this,i),appendNode:mde.bind(this,o,i),setNodeTouched:vde.bind(this,i),clearUntouched:yde.bind(this,o,i)}}function gde(t){const e=`.${dde}`,r=t.querySelector(e);return r==null?void 0:r.querySelector(":scope > .svg-layer")}function pde(t,e){if(Be.svgNodeCache[t]&&Be.svgNodeCache[t][e])return Be.svgNodeCache[t][e].domRef}function mde(t,e,r,n){if(!Be.svgNodeCache[e])return null;Be.svgNodeCache[e][n]={touched:!0,domRef:r},t.appendChild(r)}function vde(t,e){Be.svgNodeCache[t]&&Be.svgNodeCache[t][e]&&(Be.svgNodeCache[t][e].touched=!0)}function yde(t,e){Be.svgNodeCache[e]&&Object.keys(Be.svgNodeCache[e]).forEach(r=>{const n=Be.svgNodeCache[e][r];!n.touched&&n.domRef&&(t.removeChild(n.domRef),delete Be.svgNodeCache[e][r])})}function Bk(t,e){const r=hde(t);e(r),r.clearUntouched()}function cc(t,e,r){return`${t}::${e}::${r}`}function Ca(t,e){Object.keys(t).forEach(r=>{const n=e.getAttribute(r),i=t[r];i===void 0||i===""?e.removeAttribute(r):n!==i&&e.setAttribute(r,i)})}function lc(t,e){Object.keys(t).forEach(r=>{const n=t[r];n!==void 0&&n!==""&&e.setAttribute(r,n)})}function No(t,e,r,n,i,o={},a=""){const{color:s,fill:c,width:l,lineWidth:f,lineDash:u,fillOpacity:d,strokeOpacity:h}=Object.assign({color:"rgb(0, 255, 0)",fill:"transparent",width:"2",lineDash:void 0,lineWidth:void 0,strokeOpacity:1,fillOpacity:1},o),g=f||l,p="http://www.w3.org/2000/svg",v=cc(e,"circle",r),y=t.getSvgNode(v),m={cx:`${n[0]}`,cy:`${n[1]}`,r:`${i}`,stroke:s,fill:c,"stroke-width":g,"stroke-dasharray":u,"fill-opacity":d,"stroke-opacity":h};if(y)Ca(m,y),t.setNodeTouched(v);else{const w=document.createElementNS(p,"circle");a!==""&&w.setAttribute("data-id",a),lc(m,w),t.appendNode(w,v)}}function w4(t,e,r,n,i={},o=""){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},i),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"ellipse",r),h=t.getSvgNode(d),[g,p,v,y]=n,m=Math.hypot(v[0]-y[0],v[1]-y[1]),w=Math.hypot(p[0]-g[0],p[1]-g[1]),x=Math.atan2(v[1]-y[1],v[0]-y[0])*180/Math.PI,C=[(v[0]+y[0])/2,(p[1]+g[1])/2],S=m/2,_=w/2,T={cx:`${C[0]}`,cy:`${C[1]}`,rx:`${S}`,ry:`${_}`,stroke:a,fill:"transparent",transform:`rotate(${x} ${C[0]} ${C[1]})`,"stroke-width":f,"stroke-dasharray":l};if(h)Ca(T,h),t.setNodeTouched(d);else{const E=document.createElementNS(u,"ellipse");o!==""&&E.setAttribute("data-id",o),lc(T,E),t.appendNode(E,d)}}function wde(t,e,r,n,i,o={},a=""){const s=[(n[0]+i[0])/2,n[1]],c=[(n[0]+i[0])/2,i[1]],l=[n[0],(n[1]+i[1])/2],f=[i[0],(n[1]+i[1])/2];w4(t,e,r,[c,s,l,f],o={},a="")}function Qv(t,e,r,n,i={},o){const{color:a,handleRadius:s,width:c,lineWidth:l,fill:f,type:u,opacity:d}=Object.assign({color:"rgb(0, 255, 0)",handleRadius:"6",width:"2",lineWidth:void 0,fill:"transparent",type:"circle",opacity:1},i),h=l||c,g="http://www.w3.org/2000/svg",p=cc(e,"handle",`hg-${r}-index-${o}`);let v;if(u==="circle")v={cx:`${n[0]}`,cy:`${n[1]}`,r:s,stroke:a,fill:f,"stroke-width":h,opacity:d};else if(u==="rect"){const w=parseFloat(s)*1.5,x=n[0]-w*.5,C=n[1]-w*.5;v={x:`${x}`,y:`${C}`,width:`${w}`,height:`${w}`,stroke:a,fill:f,"stroke-width":h,rx:`${w*.1}`,opacity:d}}else throw new Error(`Unsupported handle type: ${u}`);const y=t.getSvgNode(p);if(y)Ca(v,y),t.setNodeTouched(p);else{const m=document.createElementNS(g,u);lc(v,m),t.appendNode(m,p)}}function ir(t,e,r,n,i={}){n.forEach((o,a)=>{Qv(t,e,r,o,i,a)})}function vn(t,e,r,n,i,o={},a=""){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{color:s="rgb(0, 255, 0)",width:c=10,lineWidth:l,lineDash:f,markerStartId:u=null,markerEndId:d=null,shadow:h=!1,strokeOpacity:g=1}=o,p=l||c,v="http://www.w3.org/2000/svg",y=cc(e,"line",r),m=t.getSvgNode(y),w=t.svgLayerElement.id,x=h?`filter:url(#shadow-${w});`:"",C={x1:`${n[0]}`,y1:`${n[1]}`,x2:`${i[0]}`,y2:`${i[1]}`,stroke:s,style:x,"stroke-width":p,"stroke-dasharray":f,"marker-start":u?`url(#${u})`:"","marker-end":d?`url(#${d})`:"","stroke-opacity":g};if(m)Ca(C,m),t.setNodeTouched(y);else{const S=document.createElementNS(v,"line");a!==""&&S.setAttribute("data-id",a),lc(C,S),t.appendNode(S,y)}}function Gk(t,e,r,n,i,o={}){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),f=i[0]+(n[0]-i[0])/2,u=[f,n[1]],d=[f,i[1]],h={start:n,end:u},g={start:u,end:d},p={start:d,end:i};vn(t,e,"1",h.start,h.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"2",g.start,g.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"3",p.start,p.end,{color:a,width:s,lineWidth:c,lineDash:l})}function Cs(t,e,r,n,i){if(n.length<2)return;const{color:o="rgb(0, 255, 0)",width:a=10,fillColor:s="none",fillOpacity:c=0,lineWidth:l,lineDash:f,closePath:u=!1,markerStartId:d=null,markerEndId:h=null}=i,g=l||a,p="http://www.w3.org/2000/svg",v=cc(e,"polyline",r),y=t.getSvgNode(v);let m="";for(const x of n)m+=`${x[0].toFixed(1)}, ${x[1].toFixed(1)} `;if(u){const x=n[0];m+=`${x[0]}, ${x[1]}`}const w={points:m,stroke:o,fill:s,"fill-opacity":c,"stroke-width":g,"stroke-dasharray":f,"marker-start":d?`url(#${d})`:"","marker-end":h?`url(#${h})`:""};if(y)Ca(w,y),t.setNodeTouched(v);else{const x=document.createElementNS(p,"polyline");lc(w,x),t.appendNode(x,v)}}function Wc(t,e,r,n,i){const a=n.length&&n[0].length&&Array.isArray(n[0][0])?n:[n],{color:s="rgb(0, 255, 0)",width:c=10,fillColor:l="none",fillOpacity:f=0,lineWidth:u,lineDash:d,closePath:h=!1}=i,g=u||c,p="http://www.w3.org/2000/svg",v=cc(e,"path",r),y=t.getSvgNode(v);let m="";for(let x=0,C=a.length;xm.length){for(let C=0;C0?xC(n,i):i,c=_de(o),l=xC(c,s),f=Object.assign({color:"rgb(255, 255, 0)",lineWidth:"1",lineDash:"2,3"},a);vn(t,e,`link-${r}`,s,l,f)}function _de(t){const{x:e,y:r,height:n,width:i}=t,o=i/2,a=n/2,s=[e+o,r],c=[e,r+a],l=[e+o,r+n],f=[e+i,r+a];return[s,c,l,f]}function qi(t,e,r,n,i,o,a,s={}){const c=Object.assign({handleRadius:"6",centering:{x:!1,y:!0}},s),l=Eu(t,e,r,n,i,c);return Sde(t,e,r,o,i,l,c),l}function x4(t,e,r,n,i={},o=""){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},i),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"rect",r),h=t.getSvgNode(d),[g,p,v,y]=n,m=Math.hypot(g[0]-p[0],g[1]-p[1]),w=Math.hypot(g[0]-v[0],g[1]-v[1]),x=[(y[0]+g[0])/2,(y[1]+g[1])/2],C=[(v[0]+g[0])/2,(v[1]+g[1])/2],S=Math.atan2(x[1]-C[1],x[0]-C[0])*180/Math.PI,_={x:`${x[0]-m/2}`,y:`${x[1]-w/2}`,width:`${m}`,height:`${w}`,stroke:a,fill:"transparent",transform:`rotate(${S} ${x[0]} ${x[1]})`,"stroke-width":f,"stroke-dasharray":l};if(h)Ca(_,h),t.setNodeTouched(d);else{const T=document.createElementNS(u,"rect");o!==""&&T.setAttribute("data-id",o),lc(_,T),t.appendNode(T,d)}}function P1(t,e,r,n,i,o={},a=""){const s=[n[0],n[1]],c=[i[0],n[1]],l=[n[0],i[1]],f=[i[0],i[1]];x4(t,e,r,[s,c,l,f],o,a)}const hD="http://www.w3.org/2000/svg";function ey(t,e,r,n,i,o={}){if(isNaN(n[0])||isNaN(n[1])||isNaN(i[0])||isNaN(i[1]))return;const{viaMarker:a=!1,color:s="rgb(0, 255, 0)",markerSize:c=10}=o;if(!a){Tde(t,e,r,n,i,o);return}const l=t.svgLayerElement.id,u=`${`arrow-${e}`}-${l}`,d=t.svgLayerElement.querySelector("defs");let h=d.querySelector(`#${u}`);if(h){h.setAttribute("markerWidth",`${c}`),h.setAttribute("markerHeight",`${c}`);const g=h.querySelector("path");g&&g.setAttribute("fill",s)}else{h=document.createElementNS(hD,"marker"),h.setAttribute("id",u),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX","8"),h.setAttribute("refY","5"),h.setAttribute("markerWidth",`${c}`),h.setAttribute("markerHeight",`${c}`),h.setAttribute("orient","auto");const g=document.createElementNS(hD,"path");g.setAttribute("d","M 0 0 L 10 5 L 0 10 z"),g.setAttribute("fill",s),h.appendChild(g),d.appendChild(h)}o.markerEndId=u,vn(t,e,r,n,i,o)}function Tde(t,e,r,n,i,o={}){const{color:a="rgb(0, 255, 0)",width:s=2,lineWidth:c,lineDash:l}=o,f=10,u=Math.atan2(i[1]-n[1],i[0]-n[0]),d={start:[i[0]-f*Math.cos(u-Math.PI/7),i[1]-f*Math.sin(u-Math.PI/7)],end:i},h={start:[i[0]-f*Math.cos(u+Math.PI/7),i[1]-f*Math.sin(u+Math.PI/7)],end:i};vn(t,e,r,n,i,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"2",d.start,d.end,{color:a,width:s,lineWidth:c,lineDash:l}),vn(t,e,"3",h.start,h.end,{color:a,width:s,lineWidth:c,lineDash:l})}function Wk(t,e,r,n,i,o={}){const{color:a,width:s,lineWidth:c,lineDash:l}=Object.assign({color:"rgb(0, 255, 0)",width:"2",lineWidth:void 0,lineDash:void 0},o),f=c||s,u="http://www.w3.org/2000/svg",d=cc(e,"rect",r),h=t.getSvgNode(d),g=[Math.min(n[0],i[0]),Math.min(n[1],i[1])],p=Math.abs(n[0]-i[0]),v=Math.abs(n[1]-i[1]),y={x:`${g[0]}`,y:`${g[1]}`,width:`${p}`,height:`${v}`,stroke:a,fill:"black","stroke-width":f,"stroke-dasharray":l};if(h)Ca(y,h),t.setNodeTouched(d);else{const m=document.createElementNS(u,"rect");lc(y,m),t.appendNode(m,d)}}const Ede=Object.freeze(Object.defineProperty({__proto__:null,draw:Bk,drawArrow:ey,drawCircle:No,drawEllipse:wde,drawEllipseByCoordinates:w4,drawFan:SC,drawHandle:Qv,drawHandles:ir,drawHeight:Gk,drawLine:vn,drawLinkedTextBox:qi,drawPath:Wc,drawPolyline:Cs,drawRect:P1,drawRectByCoordinates:x4,drawRedactionRect:Wk,drawTextBox:Eu,setAttributesIfNecessary:Ca,setNewAttributesIfValid:lc},Symbol.toStringTag,{value:"Module"}));function zk(t,e){const r=Ce(t),{renderingEngineId:n,viewportId:i}=r,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;c{this._throwIfDestroyed();const e=Array.from(this._viewportElements.values());for(let r=0;r{this._needsRender.add(r)}),this._renderFlaggedViewports()}_setViewportsToBeRenderedNextFrame(e){const r=[...this._viewportElements.values()];e.forEach(n=>{r.indexOf(n)!==-1&&this._needsRender.add(n)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedViewports),this._animationFrameSet=!0)}_triggerRender(e){const r=Ce(e);if(!r)return;if(!Jr(r.renderingEngineId)){console.warn("rendering Engine has been destroyed");return}const i=zk(e,[Dde,bde,Ide]),{renderingEngineId:o,viewportId:a}=r,s={element:e,renderingEngineId:o,viewportId:a};Bk(e,c=>{let l=!1;const f=u=>{if(u.renderAnnotation){const d=u.renderAnnotation(r,c);l=l||d}};i.forEach(f),l&&at(e,N.ANNOTATION_RENDERED,{...s})})}_reset(){window.cancelAnimationFrame(this._animationFrameHandle),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null,this._setAllViewportsToBeRenderedNextFrame()}}const C4=new Ode;function ph(t){C4.renderViewport(t)}function Pe(t){t.length&&t.forEach(e=>{const r=zn(e);if(!r){console.warn(`Viewport not available for ${e}`);return}const{viewport:n}=r;if(!n){console.warn(`Viewport not available for ${e}`);return}const i=n.element;ph(i)})}function $k(t,e){const r=t.length,n=[];for(let i=0;i{const i=n.getCamera();return Math.abs(Et(i.viewPlaneNormal,e.viewPlaneNormal))>r})}function _t(t,e,r=!0){const n=Ce(t),{renderingEngine:i,FrameOfReferenceUID:o}=n;let a=i.getViewports();a=$k(a,o),a=b5(a,e);const s=i.getViewport(n.viewportId);return r&&(a=jk(a,s.getCamera())),a.map(l=>l.id)}const Ade=Object.freeze(Object.defineProperty({__proto__:null,filterViewportsWithFrameOfReferenceUID:$k,filterViewportsWithParallelNormals:jk,filterViewportsWithToolEnabled:b5,getViewportIdsWithToolToRender:_t},Symbol.toStringTag,{value:"Module"})),ty="PlanarFreehandContourSegmentationTool";function Du(t,e){const r=t.length,n=new Array(r);for(let i=0;i{const n=r,i=Du(n.data.contour.polyline,t);return{annotation:n,polyline:i}})}function O5(t,e,r){_1(e,r),Yc(r);const{contour:n}=r.data,i=Du(n.polyline,t);Ds(r,{points:i,closed:n.closed,targetWindingDirection:e.data.contour.windingDirection===Lo.Clockwise?Lo.CounterClockwise:Lo.Clockwise},t);const{element:o}=t;T4(t,[e,r])}function _4(t,e,r,n,i){var m;if(!w5(ty)){console.warn(`${ty} is not registered in cornerstone. Cannot combine polylines.`);return}const o=i[0],a=_u(r,o),s=Hk(t,e),c=new Set(s),l=new Map,f=(w,x)=>{let C=l.get(w);C||(C=[],l.set(w,C)),C.push(x),c.delete(x)},u=[];if(a){const w=E5(r,i);u.push(w),Array.from(c.keys()).forEach(x=>f(w,x))}else D5(r,i).forEach(x=>{u.push(x),Array.from(c.keys()).forEach(C=>{O1(x,C.polyline)&&f(x,C)})});Array.from(l.values()).forEach(w=>w.forEach(x=>y5(x.annotation)));const{element:d}=t,{metadata:h,data:g}=e,{handles:p,segmentation:v}=g,{textBox:y}=p;gn(n.annotationUID),gn(e.annotationUID),Yc(n),Yc(e);for(let w=0;w_1(C,S.annotation))}T4(t,[e,n])}function Kk(t,e,r){const n=t.canvasToWorld(r[0]),i=t.canvasToWorld(r[r.length-1]),o={metadata:{...e.metadata,toolName:ty,originalToolName:e.metadata.originalToolName||e.metadata.toolName},data:{cachedStats:{},handles:{points:[n,i],textBox:e.data.handles.textBox?{...e.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:e.data.spline,segmentation:{...e.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:e.interpolationUID,interpolationCompleted:e.interpolationCompleted};return Ds(o,{points:r,closed:!0,targetWindingDirection:Lo.Clockwise},t),o}function T4(t,e){const{element:r}=t,n=new Set([ty]);e.forEach(i=>{n.add(i.metadata.toolName)});for(const i of n.values())if(w5(i)){const o=_t(r,i);Pe(o)}}function M5(t,e){const r=[],n=new Set,i=new Set;for(let o=0;o[...r]);let e=t[0].map(r=>[...r]);for(let r=1;rny(o.data.contour.polyline,r)),i=e.map(o=>ny(o.data.contour.polyline,r));return M5(n,i)}function ny(t,e){const r=t.length,n=new Array(r);for(let i=0;i[...n]);let r=t.map(n=>[...n]);for(let n=0;nny(o.data.contour.polyline,r)),i=e.map(o=>ny(o.data.contour.polyline,r));return P5(n,i)}const Ude="PlanarFreehandContourSegmentationTool";function qk(t,e,r,n){const i=new Map;return r.forEach(o=>{if(o.length<3)return;const a={annotationUID:Dn(),data:{contour:{closed:!0,polyline:o},segmentation:{segmentationId:e,segmentIndex:n},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:Ude,...t.getViewReference()}};nn(a,t.element);const s=(i==null?void 0:i.get(n))||new Set;s.add(a.annotationUID),i.set(n,s)}),i}function gD(t,e){const r=[],{annotationUIDsMap:n}=t,i=n.get(e);for(const o of i){const a=Br(o),{polyline:s}=a.data.contour;r.push(s)}return r}function Xk(t,e,r,n){if(!e||!e.representationData.Contour)return;const i=e.representationData.Contour,{annotationUIDsMap:o}=i;if(!o||!o.get(r)||!o.get(n))return;const a=gD(i,r),s=gD(i,n),c=a.map(f=>Du(f,t)),l=s.map(f=>Du(f,t));return{polyLinesCanvas1:c,polyLinesCanvas2:l}}function Bde(t,e,r,n,{name:i,segmentIndex:o,color:a}){const{polyLinesCanvas1:s,polyLinesCanvas2:c}=Xk(t,e,r,n)||{};if(!s||c)return;const f=M5(s,c).map(g=>S4(g,t)),u=qk(t,e.segmentationId,f,o),d=e.representationData.Contour,{annotationUIDsMap:h}=d;h&&h.set(o,u.get(o))}function Gde(t,e,r,n,{name:i,segmentIndex:o,color:a}){const{polyLinesCanvas1:s,polyLinesCanvas2:c}=Xk(t,e,r,n)||{};if(!s||c)return;const f=P5(s,c).map(g=>S4(g,t)),u=qk(t,e.segmentationId,f,o),d=e.representationData.Contour,{annotationUIDsMap:h}=d;h&&h.set(o,u.get(o))}function R1(t){var e;return!!((e=t.data)!=null&&e.segmentation)}function Yk(t,e,r){const n=[],i=Tu(e);for(let o=0;oa.isContourHole),o=n.filter(a=>!a.isContourHole);if(i.length>0){const a=i[0];Kde(t,a.targetAnnotation,e),Zk(t,[e,a.targetAnnotation]);return}if(o.length!==0){if(!w5(ry)){console.warn(`${ry} is not registered in cornerstone. Cannot process multiple intersections.`);return}zde(t,e,r,o)}}function zde(t,e,r,n){const{element:i}=t,o=[e],a=[],s=[];n.forEach(({targetAnnotation:d})=>{const h=Hde(t,d);s.push(...h),o.push(d)});const c=r[0];if(n.some(({targetPolyline:d})=>_u(d,c))){let d=r;n.forEach(({targetPolyline:h})=>{d=E5(d,h)}),a.push(d)}else n.forEach(({targetPolyline:d})=>{const h=D5(d,r);a.push(...h)});o.forEach(d=>{gn(d.annotationUID),Yc(d)}),s.forEach(d=>y5(d.annotation));const f=n[0].targetAnnotation,u=[];a.forEach(d=>{if(!d||d.length<3){console.warn("Skipping creation of new annotation due to invalid polyline:",d);return}const h=$de(t,f,d);nn(h,i),Jc(h),tn(h,t.element),u.push(h)}),jde(t,s,u),Zk(t,o)}function $de(t,e,r){const n=t.canvasToWorld(r[0]),i=t.canvasToWorld(r[r.length-1]),o={metadata:{...e.metadata,toolName:ry,originalToolName:e.metadata.originalToolName||e.metadata.toolName},data:{cachedStats:{},handles:{points:[n,i],textBox:e.data.handles.textBox?{...e.data.handles.textBox}:void 0},contour:{polyline:[],closed:!0},spline:e.data.spline,segmentation:{...e.data.segmentation}},annotationUID:Dn(),highlighted:!0,invalidated:!0,isLocked:!1,isVisible:void 0,interpolationUID:e.interpolationUID,interpolationCompleted:e.interpolationCompleted};return Ds(o,{points:r,closed:!0,targetWindingDirection:Lo.Clockwise},t),o}function jde(t,e,r){e.forEach(n=>{const i=r.find(o=>{const a=E4(o.data.contour.polyline,t);return O1(a,n.polyline)});i&&_1(i,n.annotation)})}function Hde(t,e){return T1(e).map(r=>{const n=r,i=E4(n.data.contour.polyline,t);return{annotation:n,polyline:i}})}function Kde(t,e,r){_1(e,r),Yc(r);const{contour:n}=r.data,i=E4(n.polyline,t);Ds(r,{points:i,closed:n.closed,targetWindingDirection:e.data.contour.windingDirection===Lo.Clockwise?Lo.CounterClockwise:Lo.Clockwise},t)}function E4(t,e){const r=t.length,n=new Array(r);for(let i=0;i{n.add(i.metadata.toolName)});for(const i of n.values())if(w5(i)){const o=_t(r,i);Pe(o)}}const{isEqual:pD}=Mn;function D4(t){const{metadata:e}=t;return qse().filter(r=>{if(r.FrameOfReferenceUID===e.FrameOfReferenceUID){const n=r.viewport,{viewPlaneNormal:i,viewUp:o}=n.getCamera();return pD(i,e.viewPlaneNormal)&&(!e.viewUp||pD(o,e.viewUp))}}).map(r=>r.viewport)}async function qde(t,e,r,n=!0){const i=typeof t=="string"?Br(t):t,o=typeof e=="string"?Br(e):e;if(!i||!o)throw new Error("Both source and target annotations must be valid");r||(r=Xde(i));const a=Du(i.data.contour.polyline,r),s=Du(o.data.contour.polyline,r),c=I5(a,s);if(!c.hasIntersection){console.warn("No intersection found between the two annotations");return}if(c.isContourHole){if(!n){console.warn("Hole processing is disabled");return}O5(r,o,i)}else _4(r,o,s,i,a)}function Xde(t){const e=D4(t);if(!e.length)throw new Error("No viewport found for the annotation");return e[0]}const Yde=Object.freeze(Object.defineProperty({__proto__:null,addContourSegmentationAnnotation:Jc,addition:Bde,areSameSegment:fk,checkIntersection:I5,combinePolylines:_4,contourSegmentationOperation:qde,convertContourPolylineToCanvasSpace:Du,convertContourPolylineToWorld:S4,convertContourSegmentationAnnotation:l4,createNewAnnotationFromPolyline:Kk,createPolylineHole:O5,findAllIntersectingContours:Yk,getContourHolesData:Hk,isContourSegmentationAnnotation:R1,processMultipleIntersections:Jk,removeContourSegmentationAnnotation:Yc,subtractAnnotationPolylines:Fde,subtractMultiplePolylineSets:Vde,subtractPolylineSets:P5,subtraction:Gde,unifyAnnotationPolylines:kde,unifyMultiplePolylineSets:Nde,unifyPolylineSets:M5,updateViewportsForAnnotations:T4},Symbol.toStringTag,{value:"Module"}));function Jde(t){if(!t)throw new Error(`No contours found for geometryId ${t.id}`);const e=t.id;if(t.type!==cv.CONTOUR)throw new Error(`Geometry type ${t.type} not supported for rendering.`);if(!t.data){console.warn(`No contours found for geometryId ${e}. Skipping render.`);return}}function Zde(t,e,r,n){r.size?t.render():Qde(t,e,n)}function Qde(t,e,r){const{segmentationId:n}=r,i=new Map;e.forEach(o=>{const a=Le.getGeometry(o);if(!a){console.warn(`No geometry found for geometryId ${o}. Skipping render.`);return}const s=a.data.segmentIndex;Jde(a);const c=va.getStyle({viewportId:t.id,segmentationId:n,type:Dt.Contour,segmentIndex:s}),l=a.data,f=t.getCamera().viewPlaneNormal;l.contours.forEach(u=>{const{points:d,color:h,id:g}=u,p=a4(t,d[0],f),v={annotationUID:Dn(),data:{contour:{closed:!0,polyline:d},segmentation:{segmentationId:n,segmentIndex:s,color:h,id:g},handles:{}},handles:{},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!0,isVisible:!0,metadata:{referencedImageId:p,toolName:"PlanarFreehandContourSegmentationTool",FrameOfReferenceUID:t.getFrameOfReferenceUID(),viewPlaneNormal:t.getCamera().viewPlaneNormal}},y=t.element;nn(v,y),Jc(v)}),c&&i.set(s,c)}),t.render()}function e0e(t,e,r=!1){const n=Ln(e),{annotationUIDsMap:i}=n.representationData.Contour;i.forEach(o=>{o.forEach(a=>{gn(a)})})}function Qk(t){const e=Hue(t);if(e)return e;const r=Ln(t);if(!r)throw new Error(`No segmentation found for segmentationId ${t}`);let n;if(r.representationData.Labelmap)n=t0e(r,t);else if(r.representationData.Contour)n=i0e(r);else if(r.representationData.Surface)n=o0e(r);else throw new Error(`Unsupported segmentation type: ${r.representationData}`);return Kue(t,n),n}function t0e(t,e){const r=t.representationData[Dt.Labelmap],n=new Set;return r.imageIds?r0e(n,r.imageIds):n0e(n,e),Array.from(n).map(Number).sort((i,o)=>i-o)}function n0e(t,e){Le.getVolume(e).voxelManager.forEach(({value:n})=>{n!==0&&t.add(n)})}function r0e(t,e){e.forEach(r=>{Le.getImage(r).voxelManager.getScalarData().forEach(o=>{o!==0&&t.add(o)})})}function i0e(t){const{annotationUIDsMap:e,geometryIds:r}=t.representationData.Contour||{};if(!r)throw new Error(`No geometryIds found for segmentationId ${t.segmentationId}`);const n=new Set([...e.keys()]);return r.forEach(i=>{const o=Le.getGeometry(i);n.add(o.data.segmentIndex)}),Array.from(n).sort((i,o)=>i-o)}function o0e(t){var r;const e=((r=t.representationData.Surface)==null?void 0:r.geometryIds)??[];return Array.from(e.keys()).map(Number).sort((n,i)=>n-i)}const bd=new Map,mD=new Map;function a0e(t,e,r=!1){const n=zn(t);if(!n)return;const{viewport:i}=n;e0e(t,e),r&&i.render()}async function s0e(t,e){var l,f;const{segmentationId:r}=e,n=Ln(r);if(!n)return;let i=n.representationData[Dt.Contour];const o=Gc();if(!i&&((l=Gc())!=null&&l.canComputeRequestedRepresentation(r,Dt.Contour))&&!bd.get(t.id)?(bd.set(t.id,!0),i=await i4(r,Dt.Contour,()=>o.computeContourData(r,{viewport:t}),()=>{}),bd.set(t.id,!1)):!i&&!Gc()&&console.debug(`No contour data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to contour. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`),!i||!((f=i.geometryIds)!=null&&f.length))return;let a=!1;const s=t.getCamera().viewPlaneNormal;i.annotationUIDsMap&&(a=!l0e(i.annotationUIDsMap,s)),i.geometryIds.length>0&&(a=!c0e(i.geometryIds,s));const c=mD.get(t.id)||new Set;if(a&&!bd.get(t.id)&&!c.has(r)&&t.viewportStatus===po.RENDERED){bd.set(t.id,!0);const u=Qk(r),h=(await o.computeSurfaceData(r,{segmentIndices:u,viewport:t})).geometryIds,g=[];for(const m of h.values()){const x=Le.getGeometry(m).data;g.push({points:x.points,polys:x.polys,segmentIndex:x.segmentIndex,id:x.segmentIndex})}const p=await o.clipAndCacheSurfacesForViewport(g,t),v=o.extractContourData(p),y=o.createAndAddContourSegmentationsFromClippedSurfaces(v,t,r);i.annotationUIDsMap=new Map([...i.annotationUIDsMap,...y]),c.add(r),mD.set(t.id,c),bd.set(t.id,!1)}Zde(t,i.geometryIds,i.annotationUIDsMap,e)}function c0e(t,e){var u,d,h;let r=null,n=null;for(const g of t){const p=Le.getGeometry(g);if(!p)continue;const v=p.data;if(((h=(d=(u=v.contours)==null?void 0:u[0])==null?void 0:d.points)==null?void 0:h.length)>=3){r=p,n=v;break}}if(!r||!n)return!1;const o=n.contours[0].points,a=o[0],s=o[1],c=o[2];let l=Rn(Ve(),En(Ve(),s,a),En(Ve(),c,a));l=tr(Ve(),l);const f=Et(l,e);return Math.abs(f)>.9}function l0e(t,e){const r=Array.from(t.values()).flat().map(i=>Array.from(i)).flat(),n=BT(r,3);for(const i of n){const o=Br(i);if(o!=null&&o.metadata){if(!o.metadata.viewPlaneNormal)continue;const a=o.metadata.viewPlaneNormal,s=Math.abs(e[0]*a[0]+e[1]*a[1]+e[2]*a[2]);if(Math.abs(s-1)>.01)return!1}}return!0}const eV={render:s0e,removeRepresentation:a0e};function Vu(t,e){return Qc(t,e)[0]}function Qc(t,e){return Zn.getCurrentLabelmapImageIdsForViewport(t,e)}function u0e(t,e){return Zn.getLabelmapImageIdsForImageId(t,e)}const vD=new Map,f0e=({cfun:t,ofun:e,actor:r})=>{r.getProperty().setRGBTransferFunction(1,t),r.getProperty().setScalarOpacity(1,e)};async function d0e({viewport:t,volumeInputs:e,segmentationId:r}){var E;const n=t.getDefaultActor(),{actor:i}=n,{uid:o,callback:a}=n,s=t.getVolumeId();if((E=vD.get(o))!=null&&E.added)return{uid:o,actor:i};const c=e,l=Le.getVolume(c[0].volumeId);if(!l)throw new Error(`imageVolume with id: ${l.volumeId} does not exist`);const{volumeId:f}=c[0],u=await ZL(f);if(!u)throw new Error(`segImageVolume with id: ${u.volumeId} does not exist`);const h=u.voxelManager.getCompleteScalarDataArray(),{imageData:g}=u,p=Le.getVolume(s),y=p.voxelManager.getCompleteScalarDataArray(),m=2,w=new Float32Array(m*p.voxelManager.getScalarDataLength()),x=g.getDimensions();for(let D=0;Dre);for(const Y of j)for(let re=0;re{Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,T);const b=t.getActor(o),{element:I,id:P}=t;t.removeActors([o]);const M=await aC({volumeId:o,blendMode:js.MAXIMUM_INTENSITY_BLEND,callback:({volumeActor:L})=>{b.callback&&b.callback({volumeActor:L,volumeId:f})}},I,P);t.addActor({actor:M,uid:o}),t.render()}),{uid:o,actor:i}}const{uuidv4:tV}=Mn;async function h0e(t,e,r,n){const i=Ce(t),{renderingEngine:o,viewport:a}=i,{id:s}=a,c=!0,l=!1,f=!0;if(a instanceof Ir){const d=g0e(e,r);Le.getVolume(d)||await p0e(e);let h=(n==null?void 0:n.blendMode)??js.MAXIMUM_INTENSITY_BLEND,g=h===js.LABELMAP_EDGE_PROJECTION_BLEND;if(g){const v=a.getVolumeId(),y=Le.getVolume(v),w=Le.getVolume(d).dimensions,x=y.dimensions;(w[0]!==x[0]||w[1]!==x[1]||w[2]!==x[2])&&(g=!1,h=js.MAXIMUM_INTENSITY_BLEND,console.debug("Dimensions mismatch - falling back to regular volume addition"))}const p=[{volumeId:d,visibility:c,representationUID:`${r}-${Dt.Labelmap}`,useIndependentComponents:g,blendMode:h}];if(!p[0].useIndependentComponents)await Cae(o,p,[s],l,f);else return await d0e({viewport:a,volumeInputs:p,segmentationId:r})}else{const d=Qc(a.id,r).map(h=>({imageId:h,representationUID:`${r}-${Dt.Labelmap}-${h}`}));Sae(o,d,[s])}io(r)}function g0e(t,e){let{volumeId:r}=t;if(!r){r=tV();const n=Ln(e);n.representationData.Labelmap={...n.representationData.Labelmap,volumeId:r},t.volumeId=r,Ta(e)}return r}async function p0e(t){const e=t;if(!(e.imageIds.length>0))throw new Error("cannot create labelmap, no imageIds found for the volume labelmap");return await QL(t.volumeId||tV(),e.imageIds)}function m0e(t,e){const r=Ce(t),{viewport:n}=r;n.removeActors([ofe(n.id,e)])}function ed(t){return Zn.getActiveSegmentation(t)}function v0e(t,e){Zn.setActiveSegmentation(t,e)}function ol(t){return ed(t)}function y0e(t,e){v0e(t,e)}const w0e=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentation:ol,setActiveSegmentation:y0e},Symbol.toStringTag,{value:"Module"}));function ea(t){const e=Ln(t);if(e){const r=Object.keys(e.segments).find(n=>e.segments[n].active);return r?Number(r):void 0}}const o3=255,zg=new Map;let a3=!1;function x0e(t,e,r=!1){const n=zn(t);if(zg.forEach((o,a)=>{a.includes(e)&&zg.delete(a)}),!n)return;const{viewport:i}=n;m0e(i.element,e),r&&i.render()}async function C0e(t,e){var s;const{segmentationId:r,config:n}=e,i=Ln(r);if(!i){console.warn("No segmentation found for segmentationId: ",r);return}let o=i.representationData[Dt.Labelmap],a=Wg(t.id,r);if(!o&&((s=Gc())!=null&&s.canComputeRequestedRepresentation(r,Dt.Labelmap))&&!a3){a3=!0;const c=Gc();if(o=await i4(r,Dt.Labelmap,()=>c.computeLabelmapData(r,{viewport:t}),()=>null,()=>{Zn.processLabelmapRepresentationAddition(t.id,r),setTimeout(()=>{io(r)},0)}),!o)throw new Error(`No labelmap data found for segmentationId ${r}.`);a3=!1}else!o&&!Gc()&&console.debug(`No labelmap data found for segmentationId ${r} and PolySeg add-on is not configured. Unable to convert from other representations to labelmap. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);if(o){if(t instanceof ur)a!=null&&a.length||await wD(t,o,r,n),a=Wg(t.id,r);else{const c=Qc(t.id,r);if(!(c!=null&&c.length))return;a||await wD(t,o,r,n),a=Wg(t.id,r)}if(a!=null&&a.length)for(const c of a)S0e(t.id,c,e)}}function S0e(t,e,r){var C;const{segmentationId:n}=r,{cfun:i,ofun:o}=r.config,{colorLUTIndex:a}=r,s=ol(t),c=(s==null?void 0:s.segmentationId)===n,l=va.getStyle({viewportId:t,type:Dt.Labelmap,segmentationId:n}),f=va.getRenderInactiveSegmentations(t),u=D1(a),d=Math.min(256,u.length),{outlineWidth:h,renderOutline:g,outlineOpacity:p,activeSegmentOutlineWidthDelta:v}=yD(l,c),y=o4(t,{segmentationId:n,type:Dt.Labelmap});for(let S=0;So.getCurrentImageId()===r),!i||!i.length)?void 0:i[0].getImageData()}else if(e.startsWith("volumeId:")){const r=sc(e),n=y1(r);return!n||!n.length?void 0:n[0].getImageData()}else if(e.startsWith("videoId:")){const r=Vr(e),n=Bv(r);return!n||!n.length?void 0:n[0].getImageData()}else throw new Error('getTargetIdImage: targetId must start with "imageId:" or "volumeId:"')}getTargetId(e){var n;const r=(n=e.getViewReferenceId)==null?void 0:n.call(e);if(r)return r;throw new Error("getTargetId: viewport must have a getViewReferenceId method")}undo(){this.doneEditMemo(),Lm.undo()}redo(){Lm.redo()}static createZoomPanMemo(e){const r={pan:e.getPan(),zoom:e.getZoom()},n={restoreMemo:()=>{const i=e.getPan(),o=e.getZoom();e.setZoom(r.zoom),e.setPan(r.pan),e.render(),r.pan=i,r.zoom=o}};return Lm.push(n),n}doneEditMemo(){var e,r;(r=(e=this.memo)==null?void 0:e.commitMemo)!=null&&r.call(e)&&Lm.push(this.memo),this.memo=null}};Zg.defaults={configuration:{strategies:{},defaultStrategy:void 0,activeStrategy:void 0,strategyOptions:{}}};let ai=Zg;ai.toolName="BaseTool";const{isEqual:T0e}=Mn,{EPSILON:E0e}=cd,D0e=1-E0e;function b4(t,e,r){var c;const{viewPlaneNormal:n}=e,i=t.filter(l=>{let f=l.metadata.viewPlaneNormal;if(!l.metadata.referencedImageId&&!f&&l.metadata.FrameOfReferenceUID){for(const d of l.data.handles.points){const h=En(Ve(),d,e.focalPoint),g=Et(h,e.viewPlaneNormal);if(!T0e(g,0))return!1}return l.metadata.viewPlaneNormal=e.viewPlaneNormal,l.metadata.cameraFocalPoint=e.focalPoint,!0}if(!f){const{referencedImageId:d}=l.metadata,{imageOrientationPatient:h}=mt("imagePlaneModule",d),g=bt(h[0],h[1],h[2]),p=bt(h[3],h[4],h[5]);f=Ve(),Rn(f,g,p),l.metadata.viewPlaneNormal=f}const u=Math.abs(Et(n,f))>D0e;return f&&u});if(!i.length)return[];const o=r/2,{focalPoint:a}=e,s=[];for(const l of i){const f=l.data,u=f.handles.points[0]||((c=f.contour)==null?void 0:c.polyline[0]);if(!l.isVisible)continue;const d=Ve();if(!u){s.push(l);continue}En(d,a,u);const h=Et(d,n);Math.abs(h)n.isVisible?n.data.isCanvasAnnotation?!0:t.isReferenceViewable(n.metadata,r):!1)}function rV(t){if(t){if(t.data&&t.highlighted)return ds.Highlighted;if(b1(t.annotationUID))return ds.Selected;if(Zr(t.annotationUID))return ds.Locked;if(t.data&&t.autoGenerated)return ds.AutoGenerated}return ds.Default}function b0e(t,e,r){const n=W0("textBoxFontSize",t,e,r),i=W0("textBoxFontFamily",t,e,r);return`${n}px ${i}`}const I0e=Object.freeze(Object.defineProperty({__proto__:null,getFont:b0e,getState:rV,style:HT},Symbol.toStringTag,{value:"Module"}));class Fu extends ai{constructor(){super(...arguments),this.onImageSpacingCalibrated=e=>{const{element:r,imageId:n}=e.detail,i=Vr(n),o=Es();o.getFramesOfReference().forEach(s=>{const l=o.getAnnotations(s)[this.getToolName()];!l||!l.length||(l.forEach(f=>{var d;if(!((d=f.metadata)!=null&&d.referencedImageId))return;Vr(f.metadata.referencedImageId)===i&&(f.invalidated=!0,f.data.cachedStats={})}),ph(r))})}}filterInteractableAnnotationsForElement(e,r){if(!(r!=null&&r.length))return[];const n=Ce(e),{viewport:i}=n;return L1(i,r)}createAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n,a=Ce(i),{viewport:s}=a,c=s.getCamera(),{viewPlaneNormal:l,viewUp:f,position:u}=c,d=this.getReferencedImageId(s,o,l,f),h=s.getViewReference({points:[o]});return{highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),...h,referencedImageId:d,viewUp:f,cameraPosition:u},data:{cachedStats:{},handles:{points:[],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}}}getReferencedImageId(e,r,n,i){const o=this.getTargetId(e);let a=o.split(/^[a-zA-Z]+:/)[1];if(e instanceof Ir){const s=sc(o),c=Le.getVolume(s);a=qc(c,r,n)}return a}getStyle(e,r,n){return W0(e,r,rV(n),this.mode)}}Fu.toolName="AnnotationDisplayTool";const{DefaultHistoryMemo:O0e}=VT,{PointsManager:M0e}=Mn;class ar extends Fu{static createAnnotation(...e){let r={annotationUID:null,highlighted:!0,invalidated:!0,metadata:{toolName:this.toolName},data:{text:"",handles:{points:new Array,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:""}};for(const n of e)r=Ei(r,n);return r}static createAnnotationForViewport(e,...r){return this.createAnnotation({metadata:e.getViewReference()},...r)}static createAndAddAnnotation(e,...r){const n=this.createAnnotationForViewport(e,...r);nn(n,e.element),tn(n,e.element)}constructor(e,r){var n,i;super(e,r),this.mouseMoveCallback=(o,a)=>{if(!a)return!1;const{element:s,currentPoints:c}=o.detail,l=c.canvas;let f=!1;for(const u of a){if(Zr(u.annotationUID)||!Gr(u.annotationUID))continue;const{data:d}=u,h=d.handles?d.handles.activeHandleIndex:void 0,g=this._imagePointNearToolOrHandle(s,u,l,6),p=g&&!u.highlighted,v=!g&&u.highlighted;p||v?(u.highlighted=!u.highlighted,f=!0):d.handles&&d.handles.activeHandleIndex!==h&&(f=!0)}return f},this.isSuvScaled=ar.isSuvScaled,(n=e.configuration)!=null&&n.getTextLines&&(this.configuration.getTextLines=e.configuration.getTextLines),(i=e.configuration)!=null&&i.statsCalculator&&(this.configuration.statsCalculator=e.configuration.statsCalculator)}getHandleNearImagePoint(e,r,n,i){const o=Ce(e),{viewport:a}=o,{data:s}=r,{isCanvasAnnotation:c}=s,{points:l,textBox:f}=s.handles;if(f){const{worldBoundingBox:u}=f;if(u){const d={topLeft:a.worldToCanvas(u.topLeft),topRight:a.worldToCanvas(u.topRight),bottomLeft:a.worldToCanvas(u.bottomLeft),bottomRight:a.worldToCanvas(u.bottomRight)};if(n[0]>=d.topLeft[0]&&n[0]<=d.bottomRight[0]&&n[1]>=d.topLeft[1]&&n[1]<=d.bottomRight[1])return s.handles.activeHandleIndex=null,f}}for(let u=0;u<(l==null?void 0:l.length);u++){const d=l[u],h=c?d.slice(0,2):a.worldToCanvas(d);if(yr(n,h)this.getStyle(p,n,r),{annotationUID:o}=r,a=Gr(o),s=Zr(o),c=i("lineWidth"),l=i("lineDash"),f=i("angleArcLineDash"),u=i("color"),d=i("markerSize"),h=i("shadow"),g=this.getLinkedTextBoxStyle(n,r);return{visibility:a,locked:s,color:u,lineWidth:c,lineDash:l,lineOpacity:1,fillColor:u,fillOpacity:0,shadow:h,textbox:g,markerSize:d,angleArcLineDash:f}}_imagePointNearToolOrHandle(e,r,n,i){if(this.getHandleNearImagePoint(e,r,n,i)||this.isPointNearTool(e,r,n,i,"mouse"))return!0}static createAnnotationState(e,r){const{data:n,annotationUID:i}=e,o={...n,cachedStats:{}};delete o.contour,delete o.spline;const a={annotationUID:i,data:structuredClone(o),deleting:r},s=n.contour;return s&&(a.data.contour={...s,polyline:null,pointsManager:M0e.create3(s.polyline.length,s.polyline)}),a}static createAnnotationMemo(e,r,n){if(!r)return;const{newAnnotation:i,deleting:o=i?!1:void 0}=n||{},{annotationUID:a}=r,s=ar.createAnnotationState(r,o),c={restoreMemo:()=>{const l=ar.createAnnotationState(r,o),{viewport:f}=Ce(e)||{};if(f==null||f.setViewReference(r.metadata),s.deleting===!0){if(s.deleting=!1,Object.assign(r.data,s.data),r.data.contour){const d=r.data;d.contour.polyline=s.data.contour.pointsManager.points,delete s.data.contour.pointsManager,d.segmentation&&Jc(r)}s.data=l.data,nn(r,e),Ro(r.annotationUID,!0),f==null||f.render();return}if(s.deleting===!1){s.deleting=!0,s.data=l.data,Ro(r.annotationUID),gn(r.annotationUID),f==null||f.render();return}const u=Br(a);if(!u){console.warn("No current annotation");return}Object.assign(u.data,s.data),u.data.contour&&(u.data.contour.polyline=s.data.contour.pointsManager.points),s.data=l.data,u.invalidated=!0,tn(u,e,Ht.History)},id:a,operationType:"annotation"};return O0e.push(c),c}createMemo(e,r,n){this.memo||(this.memo=ar.createAnnotationMemo(e,r,n))}static hydrateBase(e,r,n,i={}){if(!r)return null;const{viewport:o}=r,a=o.getFrameOfReferenceUID(),s=o.getCamera(),c=i.viewplaneNormal??s.viewPlaneNormal,l=i.viewUp??s.viewUp,f=i.toolInstance||new e;let u,d=c,h=l;if(i.referencedImageId)u=i.referencedImageId,d=void 0,h=void 0;else if(o instanceof lr){const g=FT(n[0],o);g!==void 0&&(u=o.getImageIds()[g])}else if(o instanceof Ir)u=f.getReferencedImageId(o,n[0],c,l);else throw new Error("Unsupported viewport type");return{FrameOfReferenceUID:a,referencedImageId:u,viewPlaneNormal:d,viewUp:h,instance:f,viewport:o}}}ar.toolName="AnnotationTool";const{CalibrationTypes:hf}=ja,gf="px",Am="voxels",iV=[1,2,3,4],P0e=["3,3","4,7"],R0e=["4,3","4,7"],_C={0:"px",1:"percent",2:"dB",3:"cm",4:"seconds",5:"hertz",6:"dB/seconds",7:"cm/sec",8:"cm²",9:"cm²/s",12:"degrees"},L0e=.001,Xh="²",ta=(t,e)=>{const{calibration:r,hasPixelSpacing:n}=t;let i=n?"mm":gf;const o=n?"mm³":Am;let a=i+Xh,s=1,c="";if(!r||!r.type&&!r.sequenceOfUltrasoundRegions)return{unit:i,areaUnit:a,scale:s,volumeUnit:o};if(r.type===hf.UNCALIBRATED)return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am};if(r.sequenceOfUltrasoundRegions){let f,u;if(Array.isArray(e)&&e.length===2)[f,u]=e;else if(typeof e=="function"){const y=e();f=y[0],u=y[1]}let d=r.sequenceOfUltrasoundRegions.filter(y=>f[0]>=y.regionLocationMinX0&&f[0]<=y.regionLocationMaxX1&&f[1]>=y.regionLocationMinY0&&f[1]<=y.regionLocationMaxY1&&u[0]>=y.regionLocationMinX0&&u[0]<=y.regionLocationMaxX1&&u[1]>=y.regionLocationMinY0&&u[1]<=y.regionLocationMaxY1);if(!(d!=null&&d.length))return{unit:i,areaUnit:a,scale:s,volumeUnit:o};if(d=d.filter(y=>iV.includes(y.regionDataType)&&P0e.includes(`${y.physicalUnitsXDirection},${y.physicalUnitsYDirection}`)),!d.length)return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am};const h=d[0],g=Math.abs(h.physicalDeltaX),p=Math.abs(h.physicalDeltaY);if($t(g,p,L0e))s=1/g,c="US Region",i=_C[h.physicalUnitsXDirection]||"unknown",a=i+Xh;else return{unit:gf,areaUnit:gf+Xh,scale:s,volumeUnit:Am}}else r.scale&&(s=r.scale);return[hf.ERMF,hf.USER,hf.ERROR,hf.PROJECTION,hf.CALIBRATED,hf.UNKNOWN].includes(r==null?void 0:r.type)&&(c=r.type),{unit:i+(c?` ${c}`:""),areaUnit:a+(c?` ${c}`:""),scale:s,volumeUnit:o+(c?` ${c}`:"")}},iy=(t,e)=>{const[r]=e,{calibration:n}=t;let i=["raw"],o=[null],a="";if(!n||!n.type&&!n.sequenceOfUltrasoundRegions)return{units:i,values:o};if(n.sequenceOfUltrasoundRegions){const s=n.sequenceOfUltrasoundRegions.filter(p=>iV.includes(p.regionDataType)&&R0e.includes(`${p.physicalUnitsXDirection},${p.physicalUnitsYDirection}`));if(!(s!=null&&s.length))return{units:i,values:o};const c=s.find(p=>r[0]>=p.regionLocationMinX0&&r[0]<=p.regionLocationMaxX1&&r[1]>=p.regionLocationMinY0&&r[1]<=p.regionLocationMaxY1);if(!c)return{units:i,values:o};const{referencePixelX0:l=0,referencePixelY0:f=0}=c,{physicalDeltaX:u,physicalDeltaY:d}=c,h=(r[1]-c.regionLocationMinY0-f)*d,g=(r[0]-c.regionLocationMinX0-l)*u;a="US Region",o=[g,h],i=[_C[c.physicalUnitsXDirection],_C[c.physicalUnitsYDirection]]}return{units:i,values:o,calibrationType:a}},I4=t=>{var e;return((e=t.calibration)==null?void 0:e.aspect)||1};function R5(t,e,r,n){const i=Ve();Rn(i,e,t);const o=bt(...r),a=bt(...n),s=Ve();rr(s,o,a);const c=Po(s);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=Et(s,i)/(c*Po(i)),u=Math.sqrt(1-l*l)*c,d=l*c;return{worldWidth:u,worldHeight:d}}function mh(t,e,r,n){const i=Ve();Rn(i,e,t);const o=bt(...r),a=bt(...n),s=Ve();rr(s,o,a);const c=Po(s);if(c<1e-4)return{worldWidth:0,worldHeight:0};const l=Et(s,i)/(c*Po(i)),u=Math.sqrt(1-l*l)*c,d=l*c;return{worldWidth:u,worldHeight:d}}function O4(t,e,r,n,i=.25){const o=M4(t,e,{targetVolumeId:r,stepSize:i});let a;for(const s of o){const c=t.getIntensityFromWorld(s),l=n(c,s);l&&(a=l)}return a}function M4(t,e,{targetVolumeId:r,stepSize:n}){const i=t.getCamera(),{viewPlaneNormal:o}=i,{spacingInNormalDirection:a}=uh(t,i,r),s=a*n||1,c=t.getBounds(),l=[];let f=[...e];for(;xD(f,c);)l.push([...f]),f[0]+=o[0]*s,f[1]+=o[1]*s,f[2]+=o[2]*s;for(f=[...e];xD(f,c);)l.push([...f]),f[0]-=o[0]*s,f[1]-=o[1]*s,f[2]-=o[2]*s;return l}const xD=function(t,e){const[r,n,i,o,a,s]=e,c=10;return t[0]>r+c&&t[0]i+c&&t[1]a+c&&t[2]{const c=[bt(r,n,i),bt(o,n,i),bt(r,a,i),bt(o,a,i),bt(r,n,s),bt(o,n,s),bt(r,a,s),bt(o,a,s)],l=bt(e[0],e[1],e[2]),f=bt(t[0],t[1],t[2]),u=-Et(l,f);let d=null;for(const h of c){const g=Et(l,h)+u;if(d===null)d=Math.sign(g);else if(Math.sign(g)!==d)return!0}return!1},{EPSILON:A0e}=cd,N0e=1-A0e;function L5(t,e){const{viewPlaneNormal:r}=e,n=t.filter(i=>{let o=i.metadata.viewPlaneNormal;if(!o){const{referencedImageId:s}=i.metadata,{imageOrientationPatient:c}=mt("imagePlaneModule",s),l=bt(c[0],c[1],c[2]),f=bt(c[3],c[4],c[5]);o=Ve(),Rn(o,l,f),i.metadata.viewPlaneNormal=o}const a=Math.abs(Et(r,o))>N0e;return o&&a});return n.length?n:[]}const k0e={filterAnnotationsWithinSlice:b4,getWorldWidthAndHeightFromCorners:R5,getWorldWidthAndHeightFromTwoPoints:mh,filterAnnotationsForDisplay:L1,getPointInLineOfSightWithCriteria:O4,isPlaneIntersectingAABB:oV,filterAnnotationsWithinSamePlane:L5,getPointsInLineOfSight:M4},V0e=Object.freeze(Object.defineProperty({__proto__:null,default:k0e,filterAnnotationsForDisplay:L1,filterAnnotationsWithinSamePlane:L5,filterAnnotationsWithinSlice:b4,getPointInLineOfSightWithCriteria:O4,getPointsInLineOfSight:M4,getWorldWidthAndHeightFromCorners:R5,getWorldWidthAndHeightFromTwoPoints:mh,isPlaneIntersectingAABB:oV},Symbol.toStringTag,{value:"Module"}));function _o(t,e,r){let n=!0,i=!0;if(typeof t!="function")throw new TypeError("Expected a function");return r4(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),gh(t,e,{leading:n,trailing:i,maxWait:e})}function F0e(t){var e;return((e=t[0])==null?void 0:e.length)===3}function U0e(t,e){if(!e||e.length===0||e.length===t.length)return t;const r=e[e.length-1]-e[0]+1,n=Yw(e.map(o=>t[o][0])),i=Yw(e.map(o=>t[o][1]));if(F0e(t)){const o=Yw(e.map(a=>t[a][2]));return N9(Hh(n,r),Hh(i,r),Hh(o,r))}else return N9(Hh(n,r),Hh(i,r))}function B0e(t,e){const r=[],[n,i]=e,o=i-n+1,a=Math.floor(o/t);let s=0,c=Math.round((o-1)/(a-1)*s)+n;for(;c<=i;)r.push(c),s++,c=Math.round((o-1)/(a-1)*s)+n;return r}function TC(t,e,r,n){const i=r-e+1,o=Math.floor(n/100*i)??1,a=Math.floor(i/o)??1;if(isNaN(i)||!i||!a||i/a<2)return t;const s=Math.max(0,e),c=Math.min(t.length-1,r),l=t.slice(0,s),f=t.slice(c+1,t.length),u=B0e(a,[s,c]),d=U0e(t,u);return[...l,...d,...f]}function A5(t,e){var n,i;return e!=null&&e.autoGenerated?!1:((n=t==null?void 0:t.smoothing)==null?void 0:n.smoothOnAdd)===!0||((i=t==null?void 0:t.smoothing)==null?void 0:i.smoothOnEdit)===!0}function G0e(t,e){return yo(t,e)<.001}function W0e(t,e){return yo(t,e)===0}function z0e(t,e){for(let r=0;rG0e(c,l)===!1,[o,a]=CD([qd(r,t.length,1),r,t],[qd(n,e.length,1),n,e],i,1),[s]=CD([qd(o,t.length,-1),o,t],[qd(a,e.length,-1),a,e],i,-1);return[o,s]}function N5(t,e,r){const{interpolation:n,smoothing:i}=t,o=e;if(n){const{knotsRatioPercentageOnAdd:a,knotsRatioPercentageOnEdit:s,smoothOnAdd:c=!1,smoothOnEdit:l=!1}=i,f=r?s:a;if(r?l:c){const[d,h]=r?$0e(e,r):[0,e.length-1];return!e[d]||!e[h]?e:TC(e,d,h,f)}}return o}const vh=t=>{if(t.shiftKey)return t.ctrlKey?Oi.ShiftCtrl:t.altKey?Oi.ShiftAlt:t.metaKey?Oi.ShiftMeta:Oi.Shift;if(t.ctrlKey)return t.altKey?Oi.CtrlAlt:t.metaKey?Oi.CtrlMeta:Oi.Ctrl;if(t.altKey)return t.metaKey&&Oi.AltMeta||Oi.Alt;if(t.metaKey)return Oi.Meta};function P4(t,e){const r=t[0],n=t[t.length-1],i=qt();Va(i,n[0]-r[0],n[1]-r[1]),Nc(i,i);const o=qt(),a=qt();Va(o,-i[1],i[0]),Va(a,i[1],-i[0]);const s=[(r[0]+n[0])/2,(r[1]+n[1])/2],c={dist:0,index:null};for(let u=0;uc.dist&&(c.dist=h,c.index=u)}return[t[c.index],s].map(e.canvasToWorld)}function j0e(t,e){const{viewport:r}=t,n=e.data.contour.polyline.map(r.worldToCanvas);return P4(n,r)}const{addCanvasPointsToArray:R4,pointsAreWithinCloseContourProximity:aV,getFirstLineSegmentIntersectionIndexes:sV,getSubPixelSpacingAndXYDirections:H0e}=ku;function K0e(t,e,r){this.isDrawing=!0;const n=t.detail,{currentPoints:i,element:o}=n,a=i.canvas,s=Ce(o),{viewport:c}=s,l=vh(t.detail.event)===this.configuration.contourHoleAdditionModifierKey,{spacing:f,xDir:u,yDir:d}=H0e(c,this.configuration.subPixelResolution)||{};!f||!u||!d||(this.drawData={canvasPoints:[a],polylineIndex:0,contourHoleProcessingEnabled:l,newAnnotation:!0},this.commonData={annotation:e,viewportIdsToRender:r,spacing:f,xDir:u,yDir:d,movingTextBox:!1},Be.isInteractingWithTool=!0,o.addEventListener(N.MOUSE_UP,this.mouseUpDrawCallback),o.addEventListener(N.MOUSE_DRAG,this.mouseDragDrawCallback),o.addEventListener(N.MOUSE_CLICK,this.mouseUpDrawCallback),o.addEventListener(N.TOUCH_END,this.mouseUpDrawCallback),o.addEventListener(N.TOUCH_DRAG,this.mouseDragDrawCallback),o.addEventListener(N.TOUCH_TAP,this.mouseUpDrawCallback),Ot(o))}function q0e(t){Be.isInteractingWithTool=!1,t.removeEventListener(N.MOUSE_UP,this.mouseUpDrawCallback),t.removeEventListener(N.MOUSE_DRAG,this.mouseDragDrawCallback),t.removeEventListener(N.MOUSE_CLICK,this.mouseUpDrawCallback),t.removeEventListener(N.TOUCH_END,this.mouseUpDrawCallback),t.removeEventListener(N.TOUCH_DRAG,this.mouseDragDrawCallback),t.removeEventListener(N.TOUCH_TAP,this.mouseUpDrawCallback),zt(t)}function X0e(t){const e=t.detail,{currentPoints:r,element:n}=e,i=r.world,o=r.canvas,a=Ce(n),{viewport:s}=a,{annotation:c,viewportIdsToRender:l,xDir:f,yDir:u,spacing:d,movingTextBox:h}=this.commonData,{polylineIndex:g,canvasPoints:p,newAnnotation:v}=this.drawData;this.createMemo(n,c,{newAnnotation:v});const y=p[p.length-1],m=s.canvasToWorld(y),w=Ve();rr(w,i,m);const x=Math.abs(Et(w,f)),C=Math.abs(Et(w,u));if(!(x<=d[0]&&C<=d[1])){if(h){this.isDrawing=!1;const{deltaPoints:S}=e,_=S.world,{textBox:T}=c.data.handles,{worldPosition:E}=T;E[0]+=_[0],E[1]+=_[1],E[2]+=_[2],T.hasMoved=!0}else{const S=this.findCrossingIndexDuringCreate(t);if(S!==void 0)this.applyCreateOnCross(t,S);else{const _=R4(n,p,o,this.commonData);this.drawData.polylineIndex=g+_}c.invalidated=!0}Pe(l),c.invalidated&&tn(c,n,Ht.HandlesUpdated)}}function Y0e(t){const{allowOpenContours:e}=this.configuration,{canvasPoints:r,contourHoleProcessingEnabled:n}=this.drawData,i=r[0],o=r[r.length-1],a=t.detail,{element:s}=a;this.doneEditMemo(),this.drawData.newAnnotation=!1,e&&!aV(i,o,this.configuration.closeContourProximity)?this.completeDrawOpenContour(s,{contourHoleProcessingEnabled:n}):this.completeDrawClosedContour(s,{contourHoleProcessingEnabled:n})}function J0e(t,e){this.removeCrossedLinesOnCompleteDraw();const{canvasPoints:r}=this.drawData,{contourHoleProcessingEnabled:n,minPointsToSave:i}=e??{};if(i&&r.length=2)if(c.length>this.configuration.checkCanvasEditFallbackProximity){const u=c[0],d=[];for(let p=0;pp.distance-v.distance);const h=[d[0],d[1]],g=Math.min(h[0].index,h[1].index);this.editData.startCrossingIndex=g}else{const u=qt();Wr(u,c[1],c[0]),Nc(u,u);const d=6,h=[c[0][0]-u[0]*d,c[0][1]-u[1]*d],g=td(l,h,c[0],e);if(g){const p=[h];ahe(n,p,c[0],this.commonData),c.unshift(...p),this.removePointsUpUntilFirstCrossing(e),this.editData.editIndex=c.length-1,this.editData.startCrossingIndex=g[0]}}}function che(t){const{editCanvasPoints:e,prevCanvasPoints:r}=this.editData;let n=0;for(let i=0;i0;n--){const i=[r[n],r[n-1]],o=!!td(e,i[0],i[1],t);if(r.pop(),o)break}}function fhe(){const{editCanvasPoints:t,prevCanvasPoints:e,startCrossingIndex:r}=this.editData;if(r===void 0)return;const n=t[t.length-1],i=[];for(let a=0;aa.distance-s.distance);const o=t.slice(0,-1);for(let a=0;a1&&this.checkForFirstCrossing(t,!0),this.editData.snapIndex=this.findSnapIndex(),this.editData.snapIndex===-1){this.finishEditAndStartNewEdit(t);return}this.editData.fusedCanvasPoints=this.fuseEditPointsWithClosedContour(t),g!==void 0&&this.checkForSecondCrossing(t,!0)&&(this.removePointsAfterSecondCrossing(!0),this.finishEditAndStartNewEdit(t)),Pe(c)}function yhe(t){const e=t.detail,{element:r}=e,n=Ce(r),{viewport:i,renderingEngine:o}=n,{annotation:a,viewportIdsToRender:s}=this.commonData,{fusedCanvasPoints:c,editCanvasPoints:l}=this.editData;Ds(a,{points:c,closed:!0,targetWindingDirection:Lo.Clockwise},i),a.autoGenerated&&(a.autoGenerated=!1),tn(a,r);const f=l.pop();this.editData={prevCanvasPoints:c,editCanvasPoints:[f],startCrossingIndex:void 0,editIndex:0,snapIndex:void 0,annotation:a},Pe(s)}function whe(t){const{prevCanvasPoints:e,editCanvasPoints:r,startCrossingIndex:n,snapIndex:i}=this.editData;if(n===void 0||i===void 0)return;const o=t.detail,{element:a}=o,s=[...r];cV(a,s,e[i],this.commonData),s.length>r.length&&s.pop();let c,l;n>i?(c=i,l=n):(c=n,l=i);const f=yr(e[c],s[0]),u=yr(e[c],s[s.length-1]),d=yr(e[l],s[0]),h=yr(e[l],s[s.length-1]),g=[];for(let C=0;C=0;C--){const S=s[C];g.push([S[0],S[1]])}for(let C=l;C=0;C--){const S=s[C];y.push([S[0],S[1]])}const m=SD(g),w=SD(y);return m>w?g:y}function xhe(t){const e=t.detail,{element:r}=e;this.completeClosedContourEdit(r)}function Che(t){var s;const e=Ce(t),{viewport:r}=e,{annotation:n,viewportIdsToRender:i}=this.commonData;this.doneEditMemo();const{fusedCanvasPoints:o,prevCanvasPoints:a}=this.editData;if(o){const c=A5(this.configuration,n)?N5(this.configuration,o,a):o,l=((s=this.configuration)==null?void 0:s.decimate)||{};Ds(n,{points:c,closed:!0,targetWindingDirection:Lo.Clockwise},r,{decimate:{enabled:!!l.enabled,epsilon:l.epsilon}}),n.autoGenerated&&(n.autoGenerated=!1),tn(n,t)}this.isEditingClosed=!1,this.editData=void 0,this.commonData=void 0,Pe(i),this.deactivateClosedContourEdit(t)}function She(t){this.completeClosedContourEdit(t)}function _he(t){t.activateClosedContourEdit=phe.bind(t),t.deactivateClosedContourEdit=mhe.bind(t),t.mouseDragClosedContourEditCallback=vhe.bind(t),t.mouseUpClosedContourEditCallback=xhe.bind(t),t.finishEditAndStartNewEdit=yhe.bind(t),t.fuseEditPointsWithClosedContour=whe.bind(t),t.cancelClosedContourEdit=She.bind(t),t.completeClosedContourEdit=Che.bind(t)}const{addCanvasPointsToArray:lV,getSubPixelSpacingAndXYDirections:The}=ku;function Ehe(t,e,r){this.isEditingOpen=!0;const n=t.detail,{currentPoints:i,element:o}=n,a=i.canvas,s=Ce(o),{viewport:c}=s;this.doneEditMemo();const l=e.data.contour.polyline.map(c.worldToCanvas),{spacing:f,xDir:u,yDir:d}=The(c,this.configuration.subPixelResolution);this.editData={prevCanvasPoints:l,editCanvasPoints:[a],startCrossingIndex:void 0,editIndex:0},this.commonData={annotation:e,viewportIdsToRender:r,spacing:f,xDir:u,yDir:d,movingTextBox:!1},Be.isInteractingWithTool=!0,o.addEventListener(N.MOUSE_UP,this.mouseUpOpenContourEditCallback),o.addEventListener(N.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),o.addEventListener(N.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),o.addEventListener(N.TOUCH_END,this.mouseUpOpenContourEditCallback),o.addEventListener(N.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),o.addEventListener(N.TOUCH_TAP,this.mouseUpOpenContourEditCallback),Ot(o)}function Dhe(t){Be.isInteractingWithTool=!1,t.removeEventListener(N.MOUSE_UP,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.MOUSE_DRAG,this.mouseDragOpenContourEditCallback),t.removeEventListener(N.MOUSE_CLICK,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.TOUCH_END,this.mouseUpOpenContourEditCallback),t.removeEventListener(N.TOUCH_DRAG,this.mouseDragOpenContourEditCallback),t.removeEventListener(N.TOUCH_TAP,this.mouseUpOpenContourEditCallback),zt(t)}function bhe(t){const e=t.detail,{currentPoints:r,element:n}=e,i=r.world,o=r.canvas,a=Ce(n),{viewport:s}=a,{viewportIdsToRender:c,xDir:l,yDir:f,spacing:u}=this.commonData,{editIndex:d,editCanvasPoints:h,startCrossingIndex:g}=this.editData,p=h[h.length-1],v=s.canvasToWorld(p),y=Ve();this.createMemo(n,this.commonData.annotation),rr(y,i,v);const m=Math.abs(Et(y,l)),w=Math.abs(Et(y,f));if(m<=u[0]&&w<=u[1])return;g!==void 0&&this.checkAndRemoveCrossesOnEditLine(t);const x=lV(n,h,o,this.commonData),C=d+x;this.editData.editIndex=C,g===void 0&&h.length>1&&this.checkForFirstCrossing(t,!1),this.editData.snapIndex=this.findSnapIndex(),this.editData.fusedCanvasPoints=this.fuseEditPointsWithOpenContour(t),g!==void 0&&this.checkForSecondCrossing(t,!1)?(this.removePointsAfterSecondCrossing(!1),this.finishEditOpenOnSecondCrossing(t)):this.checkIfShouldOverwriteAnEnd(t)&&this.openContourEditOverwriteEnd(t),Pe(c)}function Ihe(t){const e=t.detail,{element:r}=e,n=Ce(r),{viewport:i}=n,{annotation:o,viewportIdsToRender:a}=this.commonData,s=this.fuseEditPointsForOpenContourEndEdit();Ds(o,{points:s,closed:!1},i);const c=o.data.contour.polyline;o.data.handles.points=[c[0],c[c.length-1]],o.data.handles.activeHandleIndex=1,tn(o,r),this.isEditingOpen=!1,this.editData=void 0,this.commonData=void 0,this.doneEditMemo(),this.deactivateOpenContourEdit(r),this.activateOpenContourEndEdit(t,o,a,null)}function Ohe(t){const e=t.detail,{currentPoints:r,lastPoints:n}=e,i=r.canvas,o=n.canvas,{snapIndex:a,prevCanvasPoints:s,startCrossingIndex:c}=this.editData;if(c===void 0||a===void 0)return!1;if(a===-1)return!0;if(a!==0&&a!==s.length-1)return!1;const l=i,f=o,u=s[a],d=qt(),h=qt();Va(d,l[0]-f[0],l[1]-f[1]),Va(h,l[0]-u[0],l[1]-u[1]);const g=k_(d,h),p=Math.sqrt(d[0]*d[0]+d[1]*d[1]),v=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(g/(p*v))=n;s--){const c=e[s];i.push([c[0],c[1]])}else for(let s=0;s=0;s--){const c=r[s];i.push([c[0],c[1]])}return i}function Phe(t){const{prevCanvasPoints:e,editCanvasPoints:r,startCrossingIndex:n,snapIndex:i}=this.editData;if(n===void 0||i===void 0)return;const o=t.detail,{element:a}=o,s=[...r];lV(a,s,e[i],this.commonData),s.length>r.length&&s.pop();let c,l;n>i?(c=i,l=n):(c=n,l=i);const f=yr(e[c],s[0]),u=yr(e[c],s[s.length-1]),d=yr(e[l],s[0]),h=yr(e[l],s[s.length-1]),g=[];for(let y=0;y=0;y--){const m=s[y];g.push([m[0],m[1]])}for(let y=l;yBr(r).data.contour.polyline)}function A1(t,e){const r=uV(t),n=[];return r.forEach(i=>{const o=i.length,a=new Array(o);for(let s=0;sn.worldToCanvas(l)),a=A1(r,n),s=[o,...a];Wc(e,r.annotationUID,"1",s,i)}function jhe(t,e,r){var c;const{viewport:n}=t,i=this._getRenderingOptions(t,r),o=r.data.contour.polyline.map(l=>n.worldToCanvas(l));Cs(e,r.annotationUID,"1",o,i);const s=r.data.handles.activeHandleIndex;if(((c=this.configuration.alwaysRenderOpenContourHandles)==null?void 0:c.enabled)===!0){const l=this.configuration.alwaysRenderOpenContourHandles.radius,f="0",u=[o[0],o[o.length-1]];s===0?u.shift():s===1&&u.pop(),ir(e,r.annotationUID,f,u,{color:i.color,handleRadius:l})}if(s!==null){const l="1",f=s===0?0:o.length-1,u=o[f];ir(e,r.annotationUID,l,[u],{color:i.color})}}function Hhe(t,e,r){const{viewport:n}=t,{openUShapeContourVectorToPeak:i}=r.data,{polyline:o}=r.data.contour;if(this.renderOpenContour(t,e,r),!i)return;const a=n.worldToCanvas(o[0]),s=n.worldToCanvas(o[o.length-1]),c=[n.worldToCanvas(i[0]),n.worldToCanvas(i[1])],l=this._getRenderingOptions(t,r);Cs(e,r.annotationUID,"first-to-last",[a,s],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"}),Cs(e,r.annotationUID,"midpoint-to-open-contour",[c[0],c[1]],{color:l.color,width:l.width,closePath:!1,lineDash:"2,2"})}function Khe(t,e,r){const n=this._getRenderingOptions(t,r),{allowOpenContours:i}=this.configuration,{canvasPoints:o}=this.drawData;if(n.closePath=!1,Cs(e,r.annotationUID,"1",o,n),i){const a=o[0],s=o[o.length-1];Bhe(a,s,this.configuration.closeContourProximity)?Cs(e,r.annotationUID,"2",[s,a],n):ir(e,r.annotationUID,"0",[a],{color:n.color,handleRadius:2})}}function qhe(t,e,r){const{viewport:n}=t,{fusedCanvasPoints:i}=this.editData;if(i===void 0){this.renderClosedContour(t,e,r);return}const o=A1(r,n),a=[i,...o],s=this._getRenderingOptions(t,r),c="preview-1";r.parentAnnotationUID&&s.fillOpacity&&(s.fillOpacity=0),Wc(e,r.annotationUID,c,a,s)}function Xhe(t,e,r){const{fusedCanvasPoints:n}=this.editData;if(n===void 0){this.renderOpenContour(t,e,r);return}const i=this._getRenderingOptions(t,r);Cs(e,r.annotationUID,"preview-1",n,i)}function Yhe(t,e,r){if(r.parentAnnotationUID)return;const{viewport:n}=t,i=this._getRenderingOptions(t,r),o=r.data.contour.polyline.map(g=>n.worldToCanvas(g)),a=A1(r,n),s="1",c=o[0],l=6,f=100,u=[];for(let g=0;g0}else if(t instanceof lr){const{preScale:r}=t.getImageData()||{};return!!(r!=null&&r.scaled)}else return!1}function EC(t,e){let r=0;for(let n=0;nthis.moveAnnotation(i,r))}updateContourPolyline(e,r,n,i){var a;const o=((a=this.configuration)==null?void 0:a.decimate)||{};Ds(e,r,n,{decimate:{enabled:!!o.enabled,epsilon:o.epsilon},updateWindingDirection:i==null?void 0:i.updateWindingDirection})}getPolylinePoints(e){var r;return((r=e.data.contour)==null?void 0:r.polyline)??e.data.polyline}renderAnnotationInstance(e){const{enabledElement:r,annotationStyle:n,svgDrawingHelper:i}=e,o=e.annotation;if(o.parentAnnotationUID)return;const{annotationUID:a}=o,{viewport:s}=r,{worldToCanvas:c}=s,l=this.getPolylinePoints(o).map(y=>c(y)),{lineWidth:f,lineDash:u,color:d,fillColor:h,fillOpacity:g}=n,p=A1(o,s),v=[l,...p];return Wc(i,a,"contourPolyline",v,{color:d,lineDash:u,lineWidth:Math.max(.1,f),fillColor:h,fillOpacity:g}),!0}}class tge{constructor(){this.annotationUIDs=new Set,this._isVisible=!0,this.visibleFilter=this.unboundVisibleFilter.bind(this)}unboundVisibleFilter(e){return!this._isVisible||!this.annotationUIDs.has(e)}has(e){return this.annotationUIDs.has(e)}setVisible(e=!0,r,n){this._isVisible!==e&&(this._isVisible=e,this.annotationUIDs.forEach(i=>{const o=Br(i);if(!o){this.annotationUIDs.delete(i);return}if(o.isVisible===e||!e&&(n==null?void 0:n(i))===!1)return;o.isVisible=e;const a={...r,annotation:o};at(Ke,N.ANNOTATION_MODIFIED,a)}))}get isVisible(){return this._isVisible}findNearby(e,r){const n=[...this.annotationUIDs];if(n.length===0)return null;if(!e)return n[r===1?0:n.length-1];const i=n.indexOf(e);return i===-1||i+r<0||i+r>=n.length?null:n[i+r]}add(...e){e.forEach(r=>this.annotationUIDs.add(r))}remove(...e){e.forEach(r=>this.annotationUIDs.delete(r))}clear(){this.annotationUIDs.clear()}}const Rr={...cue,...iue,resetAnnotationManager:kfe},nge=Object.freeze(Object.defineProperty({__proto__:null,AnnotationGroup:tge,FrameOfReferenceSpecificAnnotationManager:dk,config:I0e,locking:Efe,selection:Ofe,state:Rr,visibility:Afe},Symbol.toStringTag,{value:"Module"})),_D="PlanarFreehandContourSegmentationTool";function L4(t,e=[]){const{viewport:r,sliceData:n,annotation:i}=t,o=new Map,{toolName:a,originalToolName:s}=i.metadata,c=s||a,l=(un(c,r.element)||[]).filter(f=>!f.metadata.originalToolName||f.metadata.originalToolName===c);if(c!==_D){const f=un(_D,r.element);f!=null&&f.length&&f.forEach(u=>{const{metadata:d}=u;d.originalToolName===c&&d.originalToolName!==d.toolName&&l.push(u)})}if(!(l!=null&&l.length))return o;for(let f=0;fh.metadata.sliceIndex===f);if(!(u!=null&&u.length))continue;const d=u.filter(h=>e.every(g=>{const p=g.parentKey?g.parentKey(h):h,v=p==null?void 0:p[g.key];return Array.isArray(v)?v.every((y,m)=>y===g.value[m]):v===g.value}));d.length&&o.set(f,d)}return o}function rge(t,e){const r=L4(t,e),n=[];if(!(r!=null&&r.size))return n;for(const i of r.values())i.forEach(o=>{n.push(o)});return n}function fV(t,e,r){const n=Ei({data:{},metadata:{}},r);return Object.assign(n,{highlighted:!1,invalidated:!0,autoGenerated:!0,annotationUID:void 0,cachedStats:{},childAnnotationUIDs:[],parentAnnotationUID:void 0}),Object.assign(n.data,{handles:{points:e.points||e||[],interpolationSources:e.sources,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},contour:{...r.data.contour,polyline:t}}),n}function ige(t,e){const r=L4(e,[{key:"interpolationUID",value:e.interpolationUID}]),n=oge(r);if(!n){console.warn("No annotations found to interpolate",r);return}const i=age(r,t.annotationUID),o=[];for(let a=n[0]+1;a=e[0];o--){const a=r.get(o);if(a!=null&&a.length){if(a[0].autoGenerated)continue;a.length>1&&(i=!1),n.push(o);break}}if(!(!i||!n.length)){for(let o=t+1;o<=e[1];o++){const a=r.get(o);if(a!=null&&a.length){if(a[0].autoGenerated)continue;a.length>1&&(i=!1),n.push(o);break}}if(!(!i||n.length<2))return n}}const{PointsManager:TD}=Mn;function uge(t,e=12){const r=TD.create3(e);r.sources=[];const{sources:n}=r,{length:i,sources:o=[]}=t,a=5;if(in.push(TD.create3(e)));const c=fge(t,a),l=dge(c,e),f=[];if((l==null?void 0:l.length)>2){let u=-1;const d=s/3;l.forEach(p=>{const[v,,y]=p,m=Math.ceil((v+y)/2);y-u2*d?(Id(f,u,v,s,i),u=Id(f,v,m,s,i)):u=Id(f,u,m,s,i),y-u>d&&(u=Id(f,u,y,s,i)))});const h=f[0];DC(h+i-u,i)>2*d&&Id(f,u,h-d,s,i)}else{const u=Math.floor(i/e);Id(f,-1,i-u,u,i)}return f.forEach(u=>{const d=t.getPointArray(u);r.push(d),o.forEach((h,g)=>n[g].push(h.getPoint(u)))}),r}function fge(t,e=6){const{length:r}=t,n=Ve(),i=Ve(),o=new Float32Array(r);for(let a=0;a{try{e&&(r.isInterpolationUpdate=!0,r.autoGenerated=!1),pge(t)}finally{e&&(r.autoGenerated=!0)}})}function pge(t){const{annotation:e}=t;gge(e);const{interpolationData:r,interpolationList:n}=ige(e,t)||{};if(!r||!n)return;const i={toolName:e.metadata.toolName,toolType:e.metadata.toolName,viewport:t.viewport};for(let l=0;ls.x.length,n)})}function vge(t,e,r,n,i,o,a){const[s,c]=n,l=(r-s)/(c-s),f=i.get(s)[0],u=i.get(c)[0],d=xge(t,e,l,o),h=l>.5?u:f,g=uge(d);i.has(r)?wge(d,g,r,h,a):yge(d,g,r,h,a)}function yge(t,e,r,n,i){var f;const o=t.points,{viewport:a}=i,s=fV(o,e,n),c=a.getViewReference({sliceIndex:r});if(!c)throw new Error(`Can't find slice ${r}`);Object.assign(s.metadata,c),Rr.addAnnotation(s,a.element),(f=n.onInterpolationComplete)==null||f.call(n,s,n);const{parentAnnotationUID:l}=n;if(l){const u=Rr.getAnnotation(l),d=dV(u,r,i);O5(a,d,s)}}function dV(t,e,r){const{viewport:n}=r,i=Rr.getAnnotations(t.metadata.toolName,n.element);for(let o=0;o!f.autoGenerated)||(s=o||s===n||c.forEach(l=>{l.autoGenerated&&(Rr.removeAnnotation(l.annotationUID),a.push(l))});if(a.length){const s={annotations:a,element:t.viewport.element,viewportId:t.viewport.id,renderingEngineId:t.viewport.getRenderingEngine().id};at(t.viewport.element,N.INTERPOLATED_ANNOTATIONS_REMOVED,s)}if(i>=0&&o{var h;const r=e.detail.annotation;if(!(r!=null&&r.metadata))return;const{toolName:n,originalToolName:i}=r.metadata;if(!La.toolNames.includes(n)&&!La.toolNames.includes(i))return;const o=N2(r);if(!o){console.warn("Unable to find viewport for",r);return}const a=s3(o),s={viewport:o,sliceData:a,annotation:r,interpolationUID:r.interpolationUID},c=!!r.interpolationUID;if(r.autoGenerated=!1,c){LD(s),A2(s);return}const l=[{key:"segmentIndex",value:r.data.segmentation.segmentIndex,parentKey:g=>g.data.segmentation},{key:"viewPlaneNormal",value:r.metadata.viewPlaneNormal,parentKey:g=>g.metadata},{key:"viewUp",value:r.metadata.viewUp,parentKey:g=>g.metadata}];let f=rge(s,l);const{sliceIndex:u}=r.metadata,d=new Set;f.forEach(g=>{if(g.interpolationCompleted||g.metadata.sliceIndex===u){const{interpolationUID:p}=g;d.add(p)}}),f=f.filter(g=>!d.has(g.interpolationUID)),r.interpolationUID=((h=f[0])==null?void 0:h.interpolationUID)||Tge(),s.interpolationUID=r.interpolationUID,A2(s)},La.handleAnnotationUpdate=e=>{const r=e.detail.annotation,{changeType:n=Ht.HandlesUpdated}=e.detail;if(!(r!=null&&r.metadata))return;const{toolName:i,originalToolName:o}=r.metadata;if(!La.toolNames.includes(i)&&!La.toolNames.includes(o)||!Ege.includes(n))return;const a=N2(r);if(!a){console.warn("Unable to find matching viewport for annotation interpolation",r);return}r.autoGenerated&&(Jc(r),r.autoGenerated=!1);const s=s3(a),c={viewport:a,sliceData:s,annotation:r,interpolationUID:r.interpolationUID,isInterpolationUpdate:n===Ht.InterpolationUpdated};A2(c)},La.handleAnnotationDelete=e=>{const r=e.detail.annotation;if(!(r!=null&&r.metadata))return;const{toolName:n}=r.metadata;if(!La.toolNames.includes(n)||r.autoGenerated)return;const i=N2(r);if(!i){console.warn("No viewport, can't delete interpolated results",r);return}const o=s3(i),a={viewport:i,sliceData:o,annotation:r,interpolationUID:r.interpolationUID};r.autoGenerated=!1,LD(a)};let Ys=La;function s3(t){return{numberOfSlices:t.getNumberOfSlices(),imageIndex:t.getCurrentImageIdIndex()}}function hV(t){t.forEach(e=>{const r=Kr(e);if(!r){console.warn(`ToolGroup not available for ${e}`);return}r.getViewportsInfo().forEach(i=>{const{renderingEngineId:o,viewportId:a}=i,s=Jr(o);if(!s){console.warn(`RenderingEngine not available for ${o}`);return}const c=s.getViewport(a);ph(c.element)})})}function yh(t){const n=Zn.getState().viewportSegRepresentations;return Object.entries(n).filter(([,o])=>o.some(a=>a.segmentationId===t)).map(([o])=>o)}function Dge(t,e){const r=Ln(t);if(!r)throw new Error(`No segmentation state found for ${t}`);const{segments:n}=r;return n[e].locked}function bge(t,e,r=!0){const n=Ln(t);if(!n)throw new Error(`No segmentation state found for ${t}`);const{segments:i}=n;i[e].locked=r,Ta(t)}function dd(t){const e=Ln(t);if(!e)throw new Error(`No segmentation state found for ${t}`);const{segments:r}=e;return Object.keys(r).filter(i=>r[i].locked).map(i=>parseInt(i))}const Ige=Object.freeze(Object.defineProperty({__proto__:null,getLockedSegmentIndices:dd,isSegmentIndexLocked:Dge,setSegmentIndexLocked:bge},Symbol.toStringTag,{value:"Module"}));function gV(){return Zn.getNextColorLUTIndex()}const oy=[[0,0,0,0],[221,84,84,255],[77,228,121,255],[166,70,235,255],[189,180,116,255],[109,182,196,255],[204,101,157,255],[123,211,94,255],[93,87,218,255],[225,128,80,255],[73,232,172,255],[181,119,186,255],[176,193,112,255],[105,153,200,255],[208,97,120,255],[90,215,101,255],[135,83,222,255],[229,178,76,255],[122,183,181,255],[190,115,171,255],[149,197,108,255],[100,118,205,255],[212,108,93,255],[86,219,141,255],[183,79,226,255],[233,233,72,255],[118,167,187,255],[194,111,146,255],[116,201,104,255],[115,96,209,255],[216,147,89,255],[82,223,188,255],[230,75,224,255],[163,184,121,255],[114,143,191,255],[198,107,114,255],[99,206,122,255],[153,92,213,255],[220,192,85,255],[78,215,227,255],[234,71,173,255],[141,188,117,255],[110,113,195,255],[202,128,103,255],[95,210,157,255],[195,88,217,255],[206,224,81,255],[74,166,231,255],[185,120,139,255],[113,192,113,255],[133,106,199,255],[207,162,98,255],[91,214,198,255],[221,84,198,255],[159,228,77,255],[70,111,235,255],[189,119,116,255],[109,196,138,255],[165,101,204,255],[211,201,94,255],[87,191,218,255],[225,80,153,255],[106,232,73,255],[124,119,186,255],[193,142,112,255],[105,200,168,255],[203,97,208,255],[184,215,90,255],[83,147,222,255],[229,76,101,255],[122,183,130,255],[146,115,190,255],[197,171,108,255],[100,205,205,255],[212,93,177,255],[141,219,86,255],[79,97,226,255],[233,99,72,255],[118,187,150,255],[173,111,194,255],[197,201,104,255],[96,171,209,255],[216,89,137,255],[94,223,82,255],[107,75,230,255],[184,153,121,255],[114,191,175,255],[198,107,191,255],[166,206,99,255],[92,132,213,255],[220,85,91,255],[78,227,115,255],[159,71,234,255],[188,176,117,255],[110,185,195,255],[202,103,161,255],[129,210,95,255],[88,88,217,255],[224,123,81,255],[74,231,166,255],[177,120,185,255],[179,192,113,255],[106,156,199,255],[207,98,125,255],[91,214,96,255],[130,84,221,255],[228,171,77,255],[70,235,221,255],[189,116,174,255],[153,196,109,255],[101,123,204,255],[211,104,94,255],[87,218,136,255],[177,80,225,255],[232,225,73,255],[119,169,186,255],[193,112,149,255],[121,200,105,255],[111,97,208,255],[215,142,90,255],[83,222,181,255],[229,76,229,255],[165,183,122,255],[115,146,190,255],[197,108,119,255],[100,205,118,255],[148,93,212,255],[219,186,86,255],[79,220,226,255],[233,72,179,255],[144,187,118,255],[111,118,194,255],[201,124,104,255],[96,209,153,255],[189,89,216,255],[211,223,82,255],[75,172,230,255],[184,121,142,255],[117,191,114,255],[130,107,198,255],[206,157,99,255],[92,213,193,255],[220,85,203,255],[165,227,78,255],[71,118,234,255],[188,117,117,255],[110,195,135,255],[161,103,202,255],[210,195,95,255],[88,195,217,255],[224,81,158,255],[113,231,74,255],[123,120,185,255],[192,139,113,255],[106,199,164,255],[198,98,207,255],[188,214,91,255],[84,153,221,255],[228,77,108,255],[70,235,84,255],[143,116,189,255],[196,167,109,255],[101,204,199,255],[211,94,182,255],[147,218,87,255],[80,104,225,255],[232,93,73,255],[119,186,147,255],[170,112,193,255],[200,200,105,255],[97,175,208,255],[215,90,142,255],[100,222,83,255],[101,76,229,255],[183,150,122,255],[115,190,171,255],[197,108,194,255],[170,205,100,255],[93,138,212,255],[219,86,97,255],[79,226,110,255],[153,72,233,255],[187,173,118,255],[111,187,194,255],[201,104,165,255],[134,209,96,255],[89,95,216,255],[223,117,82,255],[75,230,159,255],[174,121,184,255],[182,191,114,255],[107,160,198,255],[206,99,130,255],[92,213,92,255],[124,85,220,255],[227,165,78,255],[71,234,214,255],[188,117,176,255],[156,195,110,255],[103,128,202,255],[210,100,95,255],[88,217,131,255],[170,81,224,255],[231,218,74,255],[120,172,185,255],[192,113,153,255],[125,199,106,255],[107,98,207,255],[214,137,91,255],[84,221,175,255],[222,77,228,255],[194,235,70,255],[116,149,189,255],[196,109,123,255],[101,204,114,255],[143,94,211,255],[218,180,87,255],[80,225,225,255],[232,73,186,255],[147,186,119,255],[112,122,193,255],[200,121,105,255],[97,208,148,255],[184,90,215,255],[216,222,83,255],[76,178,229,255],[183,122,145,255],[121,190,115,255],[126,108,197,255],[205,153,100,255],[93,212,187,255],[219,86,208,255],[171,226,79,255],[72,126,233,255],[187,118,121,255],[111,194,132,255],[157,104,201,255],[209,190,96,255],[89,200,216,255],[223,82,164,255],[120,230,75,255],[121,121,184,255],[191,136,114,255],[107,198,160,255],[192,99,206,255],[193,213,92,255],[85,158,220,255],[227,78,115,255],[71,234,78,255],[141,117,188,255],[195,163,110,255],[103,202,194,255],[210,95,186,255],[153,217,88,255],[81,111,224,255]];function $g(t,e){const r=Zn,n=e??gV();let i=[...t];if($t(i[0],[0,0,0,0])||(console.warn("addColorLUT: [0, 0, 0, 0] color is not provided for the background color (segmentIndex =0), automatically adding it"),i=[[0,0,0,0],...i]),i=i.map(o=>o.length===3?[o[0],o[1],o[2],255]:o),i.length<255){const o=oy.slice(i.length);i=[...i,...o]}return r.addColorLUT(i,n),n}function Oge(t,e){if(!t)throw new Error("addColorLUT: colorLUT is required");return $g(t,e)}function Mge(t,e,r){if(!D1(r))throw new Error(`setColorLUT: could not find colorLUT with index ${r}`);const n=Jo(t,{segmentationId:e});if(!n)throw new Error(`viewport specific state for viewport ${t} does not exist`);n.forEach(i=>{i.colorLUTIndex=r}),Gs(t,e)}function el(t,e,r){const n=Jo(t,{segmentationId:e});if(!n||n.length===0)return null;const i=n[0],{colorLUTIndex:o}=i,a=D1(o);let s=a[r];if(!s){if(typeof r!="number")return console.warn(`Can't create colour for LUT index ${r}`),null;s=a[r]=[0,0,0,0]}return s}function pV(t,e,r,n){const i=el(t,e,r);for(let o=0;oOr(c).id);hV(s)}return i}_getContourSegmentationStyle(e){const r=e.annotation,{segmentationId:n,segmentIndex:i}=r.data.segmentation,{viewportId:o}=e.styleSpecifier,a=Jo(o,{segmentationId:n});if(!(a!=null&&a.length))return{};a.length>1?a.find(v=>v.segmentationId===n&&v.type===Dt.Contour):a[0];const{autoGenerated:s}=r,l=dd(n).includes(i),{color:f,fillColor:u,lineWidth:d,fillOpacity:h,lineDash:g,visibility:p}=vV({segmentationId:n,segmentIndex:i,viewportId:o,autoGenerated:s});return{color:f,fillColor:u,lineWidth:d,fillOpacity:h,lineDash:g,textbox:{color:f},visibility:p,locked:l}}};wE.PreviewSegmentIndex=255;let $p=wE;function yV(t,e){const r=mt("generalSeriesModule",t);return sl(r.modality,t,e)}function sl(t,e,r){return t==="CT"?"HU":t==="PT"?Rge(e,r):""}function Rge(t,e){if(!e.isPreScaled)return"raw";if(e.isSuvScaled)return"SUV";const r=mt("generalSeriesModule",t);if((r==null?void 0:r.modality)==="PT"){const n=mt("petSeriesModule",t);return(n==null?void 0:n.units)||"unitless"}return"unknown"}const{pointCanProjectOnLine:AD}=ku,{EPSILON:Lge}=cd,Age=1-Lge,xE=class xE extends $p{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,shadow:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:Oi.Shift,alwaysRenderOpenContourHandles:{enabled:!1,radius:2},allowOpenContours:!0,closeContourProximity:10,checkCanvasEditFallbackProximity:6,makeClockWise:!0,subPixelResolution:4,smoothing:{smoothOnAdd:!1,smoothOnEdit:!1,knotsRatioPercentageOnAdd:40,knotsRatioPercentageOnEdit:40},interpolation:{enabled:!1,onInterpolationComplete:null},decimate:{enabled:!1,epsilon:.1},displayOnePointAsCrosshairs:!1,calculateStats:!0,getTextLines:Nge,statsCalculator:rc}}){super(e,r),this.isDrawing=!1,this.isEditingClosed=!1,this.isEditingOpen=!1,this.addNewAnnotation=n=>{const i=n.detail,{element:o}=i,a=this.createAnnotation(n);this.addAnnotation(a,o);const s=_t(o,this.getToolName());return this.activateDraw(n,a,s),n.preventDefault(),Pe(s),a},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,c=_t(s,this.getToolName());this.activateOpenContourEndEdit(n,i,c,o)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o,s=_t(a,this.getToolName());i.data.contour.closed?this.activateClosedContourEdit(n,i,s):this.activateOpenContourEdit(n,i,s),n.preventDefault()},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{polyline:l}=i.data.contour;let f=c.worldToCanvas(l[0]);for(let h=1;h{const i=this.isDrawing,o=this.isEditingOpen,a=this.isEditingClosed;i?this.cancelDrawing(n):o?this.cancelOpenContourEdit(n):a&&this.cancelClosedContourEdit(n)},this._calculateCachedStats=(n,i,o,a)=>{const{data:s}=n,{cachedStats:c}=s,{polyline:l,closed:f}=s.contour,u=Object.keys(c);for(let h=0;hi.worldToCanvas(I)),w={isPreScaled:al(i,g),isSuvScaled:this.isSuvScaled(i,g,n.metadata.referencedImageId)},x=sl(y.Modality,n.metadata.referencedImageId,w),C=ta(p,()=>{const I=s.contour.polyline,P=I.length,M=new Array(P);for(let re=0;re{const{data:s}=n,c=this.getTargetId(i),l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:o.viewport.id,annotationUID:n.annotationUID},f=this.getLinkedTextBoxStyle(l,n);if(!f.visibility)return;const u=this.configuration.getTextLines(s,c);if(!u||u.length===0)return;const d=s.contour.polyline.map(x=>i.worldToCanvas(x));if(!s.handles.textBox.hasMoved){const x=na(d);s.handles.textBox.worldPosition=i.canvasToWorld(x)}const h=i.worldToCanvas(s.handles.textBox.worldPosition),p=qi(a,n.annotationUID??"","1",u,h,d,{},f),{x:v,y,width:m,height:w}=p;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([v,y]),topRight:i.canvasToWorld([v+m,y]),bottomLeft:i.canvasToWorld([v,y+w]),bottomRight:i.canvasToWorld([v+m,y+w])}},ohe(this),hhe(this),_he(this),khe(this),Uhe(this),Jhe(this),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}filterInteractableAnnotationsForElement(e,r){if(!r||!r.length)return;const n=Ce(e),{viewport:i}=n;let o;if(i instanceof ur){const a=i.getCamera(),{spacingInNormalDirection:s}=uh(i,a);o=this.filterAnnotationsWithinSlice(r,a,s)}else o=L1(i,r);return o}filterAnnotationsWithinSlice(e,r,n){const{viewPlaneNormal:i}=r,o=e.filter(l=>{let f=l.metadata.viewPlaneNormal;if(!l.metadata.referencedImageId&&!f&&l.metadata.FrameOfReferenceUID){for(const d of l.data.contour.polyline){const h=En(Ve(),d,r.focalPoint),g=Et(h,r.viewPlaneNormal);if(!$t(g,0))return!1}return l.metadata.viewPlaneNormal=r.viewPlaneNormal,l.metadata.cameraFocalPoint=r.focalPoint,!0}if(!f){const{referencedImageId:d}=l.metadata,{imageOrientationPatient:h}=mt("imagePlaneModule",d),g=bt(h[0],h[1],h[2]),p=bt(h[3],h[4],h[5]);f=Ve(),Rn(f,g,p),l.metadata.viewPlaneNormal=f}const u=Math.abs(Et(i,f))>Age;return f&&u});if(!o.length)return[];const a=n/2,{focalPoint:s}=r,c=[];for(const l of o){const u=l.data.contour.polyline[0];if(!l.isVisible)continue;const d=Ve();En(d,s,u);const h=Et(d,i);Math.abs(h){a.data.handles.points.length=0};return Ei(n,{data:{contour:{polyline:[[...r]]},label:"",cachedStats:{}},onInterpolationComplete:i})}getAnnotationStyle(e){return super.getAnnotationStyle(e)}renderAnnotationInstance(e){const{enabledElement:r,targetId:n,svgDrawingHelper:i}=e,o=e.annotation;let a=!1;const{viewport:s,renderingEngine:c}=r,l=this.isDrawing,f=this.isEditingOpen,u=this.isEditingClosed;if(!(l||f||u))this.configuration.displayOnePointAsCrosshairs&&o.data.contour.polyline.length===1?this.renderPointContourWithMarker(r,i,o):this.renderContour(r,i,o);else{const d=this.commonData.annotation.annotationUID;if(o.annotationUID===d)if(l)this.renderContourBeingDrawn(r,i,o);else if(u)this.renderClosedContourBeingEdited(r,i,o);else if(f)this.renderOpenContourBeingEdited(r,i,o);else throw new Error(`Unknown ${this.getToolName()} annotation rendering state`);else this.configuration.displayOnePointAsCrosshairs&&o.data.contour.polyline.length===1?this.renderPointContourWithMarker(r,i,o):this.renderContour(r,i,o);a=!0}if(this.configuration.calculateStats)return this._calculateStatsIfActive(o,n,s,c,r),this._renderStats(o,s,r,i),a}_calculateStatsIfActive(e,r,n,i,o){var s,c,l,f;const a=(s=this.commonData)==null?void 0:s.annotation.annotationUID;if(!(e.annotationUID===a&&!((c=this.commonData)!=null&&c.movingTextBox))&&!((l=this.commonData)!=null&&l.movingTextBox)){const{data:u}=e;(f=u.cachedStats[r])!=null&&f.unit?e.invalidated&&this._throttledCalculateCachedStats(e,n,i,o):(u.cachedStats[r]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null,unit:null},this._calculateCachedStats(e,n,i,o))}}updateClosedCachedStats({viewport:e,points:r,imageData:n,metadata:i,cachedStats:o,targetId:a,modalityUnit:s,canvasCoordinates:c,calibratedScale:l,deltaInX:f,deltaInY:u}){var j,Y,re,ue;const{scale:d,areaUnit:h,unit:g}=l,{voxelManager:p}=e.getImageData(),v=Ur(n,r[0]);v[0]=Math.floor(v[0]),v[1]=Math.floor(v[1]),v[2]=Math.floor(v[2]);let y=v[0],m=v[0],w=v[1],x=v[1],C=v[2],S=v[2];for(let ce=1;ce{let Ee=!0;const Oe=e.worldToCanvas(ce);return Oe[1]!=V&&(A=0,V=Oe[1],G=Vk(c,Oe,[L[0],Oe[1]]),G.sort(function(_e){return function(B,O){return B[_e]===O[_e]?0:B[_e]G[0][0]&&(G.shift(),A++),A%2===0&&(Ee=!1),Ee},boundsIJK:P,returnPoints:this.configuration.storePointData}));const F=this.configuration.statsCalculator.getStatistics();o[a]={Modality:i.Modality,area:T,perimeter:E,mean:(j=F.mean)==null?void 0:j.value,max:(Y=F.max)==null?void 0:Y.value,min:(re=F.min)==null?void 0:re.value,stdDev:(ue=F.stdDev)==null?void 0:ue.value,statsArray:F.array,pointsInShape:k,areaUnit:h,modalityUnit:s,unit:g}}updateOpenCachedStats({targetId:e,metadata:r,canvasCoordinates:n,cachedStats:i,modalityUnit:o,calibratedScale:a,deltaInX:s,deltaInY:c}){const{scale:l,unit:f}=a;let u=EC(n,closed)/l;u*=Math.sqrt(Math.pow(s,2)+Math.pow(c,2)),i[e]={Modality:r.Modality,length:u,modalityUnit:o,unit:f}}};xE.toolName="PlanarFreehandROI";let bu=xE;function Nge(t,e){const r=t.cachedStats[e],{area:n,mean:i,stdDev:o,length:a,perimeter:s,max:c,min:l,isEmptyArea:f,unit:u,areaUnit:d,modalityUnit:h}=r||{},g=[];if(Ar(n)){const p=f?"Area: Oblique not supported":`Area: ${an(n)} ${d}`;g.push(p)}return Ar(i)&&g.push(`Mean: ${an(i)} ${h}`),Ar(c)&&g.push(`Max: ${an(c)} ${h}`),Ar(l)&&g.push(`Min: ${an(l)} ${h}`),Ar(o)&&g.push(`Std Dev: ${an(o)} ${h}`),Ar(s)&&g.push(`Perimeter: ${an(s)} ${u}`),Ar(a)&&g.push(`${an(a)} ${u}`),g}const CE=class CE extends bu{constructor(e){const r=Ei({configuration:{calculateStats:!1,allowOpenContours:!1}},e);super(r)}isContourSegmentationTool(){return!0}renderAnnotationInstance(e){const r=e.annotation,{invalidated:n}=r,i=super.renderAnnotationInstance(e);if(n){const{segmentationId:o}=r.data.segmentation;io(o)}return i}};CE.toolName="PlanarFreehandContourSegmentationTool";let ic=CE;const kge={[Dt.Labelmap]:nV,[Dt.Contour]:eV,[Dt.Surface]:uk},km=ic.toolName;class Vge{constructor(){this._needsRender=new Set,this._animationFrameSet=!1,this._animationFrameHandle=null,this._getAllViewports=()=>Qo().flatMap(r=>r.getViewports()),this._renderFlaggedSegmentations=()=>{this._throwIfDestroyed(),Array.from(this._needsRender).forEach(r=>{this._triggerRender(r)}),this._needsRender.clear(),this._animationFrameSet=!1,this._animationFrameHandle=null}}renderSegmentationsForViewport(e){const r=e?[e]:this._getViewportIdsForSegmentation();this._setViewportsToBeRenderedNextFrame(r)}renderSegmentation(e){const r=this._getViewportIdsForSegmentation(e);this._setViewportsToBeRenderedNextFrame(r)}_getViewportIdsForSegmentation(e){const r=this._getAllViewports(),n=[];for(const i of r){const o=i.id;if(e){const a=Jo(o,{segmentationId:e});(a==null?void 0:a.length)>0&&n.push(o)}else{const a=Jo(o);(a==null?void 0:a.length)>0&&n.push(o)}}return n}_throwIfDestroyed(){if(this.hasBeenDestroyed)throw new Error("this.destroy() has been manually called to free up memory, can not longer use this instance. Instead make a new one.")}_setViewportsToBeRenderedNextFrame(e){e.forEach(r=>{this._needsRender.add(r)}),this._render()}_render(){this._needsRender.size>0&&this._animationFrameSet===!1&&(this._animationFrameHandle=window.requestAnimationFrame(this._renderFlaggedSegmentations),this._animationFrameSet=!0)}_triggerRender(e){const r=Jo(e);if(!(r!=null&&r.length))return;const{viewport:n}=zn(e)||{};if(!n)return;const i=[],o=r.map(a=>{a.type===Dt.Contour&&this._addPlanarFreeHandToolIfAbsent(n);const s=kge[a.type];try{const c=s.render(n,a);i.push(c)}catch(c){console.error(c)}return Promise.resolve({segmentationId:a.segmentationId,type:a.type})});Promise.allSettled(o).then(a=>{const s=a.filter(f=>f.status==="fulfilled").map(f=>f.value);function c(f){const{element:u,viewportId:d}=f.detail;u.removeEventListener(Xe.IMAGE_RENDERED,c),s.forEach(h=>{const g={viewportId:d,segmentationId:h.segmentationId,type:h.type};at(Ke,N.SEGMENTATION_RENDERED,{...g})})}n.element.addEventListener(Xe.IMAGE_RENDERED,c),n.render()})}_addPlanarFreeHandToolIfAbsent(e){km in Be.tools||Ci(ic);const r=Or(e.id);r.hasTool(km)||(r.addTool(km),r.setToolPassive(km))}}function wh(t){wV.renderSegmentationsForViewport(t)}function k5(t){wV.renderSegmentation(t)}const wV=new Vge;function Fge({modifiedSlicesToUse:t,representationData:e,type:r}){const n=Le.getVolume(e[r].volumeId);if(!n){console.warn("segmentation not found in cache");return}const{imageData:i,vtkOpenGLTexture:o}=n;let a;if((t==null?void 0:t.length)>0)a=t;else{const s=i.getDimensions()[2];a=[...Array(s).keys()]}a.forEach(s=>{o.setUpdatedFrame(s)}),i.modified()}function Uge({viewportIds:t,segmentationId:e}){t.forEach(r=>{let n=Jo(r,{segmentationId:e});n=n.filter(i=>i.type===Dt.Labelmap),n.forEach(i=>{if(i.segmentationId!==e)return;const o=zn(r);if(!o)return;const{viewport:a}=o;if(a instanceof ur)return;const s=Wg(r,e);s!=null&&s.length&&s.forEach((c,l)=>{const f=c.actor.getMapper().getInputData(),u=Qc(r,e),d=Le.getImage(u[l]);f.modified(),s5(f,d)})})})}const Bge=function(t){const{segmentationId:e,modifiedSlicesToUse:r}=t.detail,{representationData:n}=Ln(e),i=yh(e),o=i.some(c=>{const{viewport:l}=zn(c);return l instanceof ur}),a=i.some(c=>{const{viewport:l}=zn(c);return l instanceof lr}),s=o&&a;i.forEach(c=>{const{viewport:l}=zn(c);l instanceof ur&&Fge({modifiedSlicesToUse:s?[]:r,representationData:n,type:Dt.Labelmap}),l instanceof lr&&Uge({viewportIds:i,segmentationId:e})})},xV=function(t){const{segmentationId:e}=t.detail,{representationData:r}=Ln(e);r.Labelmap&&Bge(t),k5(e)},CV=function(t){const{segmentationId:e}=t.detail;k5(e)};function SV(t,e){return Zn.updateLabelmapSegmentationImageReferences(t,e)}const Gge=function(t){if(!t)return;const e=Ce(t);if(!e)return;const{viewport:r}=e;r instanceof Ir||(t.addEventListener(Xe.STACK_NEW_IMAGE,jp),t.addEventListener(Xe.IMAGE_RENDERED,jp))},Wge=function(t){t.removeEventListener(Xe.STACK_NEW_IMAGE,jp),t.removeEventListener(Xe.IMAGE_RENDERED,jp)};function jp(t){const e=t.detail,{viewportId:r,renderingEngineId:n}=e,{viewport:i}=Ti(r,n),o=Jo(r);if(!(o!=null&&o.length))return;const a=o.filter(l=>l.type===Dt.Labelmap),s=i.getActors();a.forEach(l=>{const{segmentationId:f}=l;SV(r,f)});const c=a.flatMap(l=>Wg(r,l.segmentationId)).filter(l=>l!==void 0);c.length&&(c.forEach(l=>{a.find(u=>{const d=Qc(r,u.segmentationId);return d==null?void 0:d.includes(l.referencedId)})||i.removeActors([l.uid])}),a.forEach(l=>{const{segmentationId:f}=l,u=i.getCurrentImageId(),d=Qc(r,f);if(!d)return;const h=g=>{const p=Le.getImage(g);if(!p){console.warn("No derived image found in the cache for segmentation representation",l);return}const v=s.find(y=>y.referencedId===g);if(v){const y=v.actor.getMapper().getInputData();y.setDerivedImage?y.setDerivedImage(p):s5(y,p)}else{const{dimensions:y,spacing:m,direction:w}=i.getImageDataMetadata(p),x=Le.getImage(u)||{imageId:u},{origin:C}=i.getImageDataMetadata(x),S=C,_=p.voxelManager.getConstructor(),T=p.voxelManager.getScalarData(),E=Yt.newInstance({name:"Pixels",numberOfComponents:1,values:new _(T)}),D=h1.newInstance();D.setDimensions(y[0],y[1],1),D.setSpacing(m),D.setDirection(w),D.setOrigin(S),D.getPointData().setScalars(E),D.modified(),i.addImages([{imageId:g,representationUID:`${f}-${Dt.Labelmap}-${p.imageId}`,callback:({imageActor:b})=>{b.getMapper().setInputData(D)}}]),wh(r);return}};d.forEach(h),i.render(),t.type===Xe.IMAGE_RENDERED&&i.element.removeEventListener(Xe.IMAGE_RENDERED,jp)}))}const _V={enable:Gge,disable:Wge};async function zge(t){const e=t.detail.annotation;if(!R1(e))return;const r=jge(e),n=Hge(r,e);if(!n.length){at(Ke,N.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,{element:r.element,sourceAnnotation:e});return}const i=Du(e.data.contour.polyline,r),o=Yk(r,i,n);if(!o.length){at(Ke,N.ANNOTATION_CUT_MERGE_PROCESS_COMPLETED,{element:r.element,sourceAnnotation:e});return}if(o.length>1){Jk(r,e,i,o);return}const{targetAnnotation:a,targetPolyline:s,isContourHole:c}=o[0];if(c){const{contourHoleProcessingEnabled:l=!1}=t.detail;if(!l)return;O5(r,a,e)}else _4(r,a,s,e,i)}function $ge(t,e=!1){const r="PlanarFreehandContourSegmentationTool",n=Or(t.id,t.renderingEngineId);let i;return n?n.hasTool(r)?n.getToolOptions(r)||(i=`Tool ${r} must be in active/passive state in ${n.id} toolGroup`):i=`Tool ${r} not added to ${n.id} toolGroup`:i=`ToolGroup not found for viewport ${t.id}`,i&&!e&&console.warn(i),!i}function jge(t){const e=D4(t);return e.find(n=>$ge(n,!0))??e[0]}function Hge(t,e){const{annotationUID:r}=e;return S1().filter(i=>i.annotationUID&&i.annotationUID!==r&&R1(i)&&fk(i,e)&&t.isReferenceViewable(i.metadata))}function Kge(t){const e=t.detail.annotation;Yc(e)}function TV(t){const e=t.detail.annotation;R1(e)&&zge(t)}function ay(t){if(!t.detail.removed.length)return;Qo().forEach(n=>{const o=n.getViewports().map(a=>a.id);Pe(o)})}function EV(t){const{viewportId:e}=t.detail;Pe([e])}function qge(t){const e=t.detail.annotation;R1(e)&&Kge(t)}const DV=function(t){ph(t.detail.element)},Xge=function(t){t.addEventListener(Xe.IMAGE_RENDERED,DV)},Yge=function(t){t.removeEventListener(Xe.IMAGE_RENDERED,DV)},bV={enable:Xge,disable:Yge},{Active:Jge}=An;function xh(t,e,r){if(Be.isInteractingWithTool)return!1;const{renderingEngineId:n,viewportId:i}=r.detail,o=Or(i,n);if(!o)return!1;let a;const s=Object.keys(o.toolOptions);for(let c=0;c{for(const c of s){if(c.isLocked||!c.isVisible)continue;const l=a.getHandleNearImagePoint(t,c,r,i);if(l){o.push({tool:a,annotation:c,handle:l});break}}}),o}function N1(t,e){const r=[];for(let n=0;n0&&r.push({tool:i,annotations:o}))}return r}function A4(t,e,r,n="mouse"){const i=n==="touch"?36:6,o=[];return e.forEach(({tool:a,annotations:s})=>{for(const c of s){if(c.isLocked||!c.isVisible)continue;if(a.isPointNearTool(t,c,r,i,n)){o.push({tool:a,annotation:c});break}}}),o}const{Active:Zge}=An;function V5(t){const{renderingEngineId:e,viewportId:r,event:n}=t.detail,i=vh(n)||hh.getModifierKey(),o=Or(r,e);if(!o)return null;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary(),c=t.detail.buttons??(n==null?void 0:n.buttons)??s;for(let l=0;lh.mouseButton===c&&h.modifierKey===i);if(u.mode===Zge&&d)return o.getToolInstance(f)}}function $0(t,e,r){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;cd.mouseButton===r);if(e.includes(f.mode)&&(!r||u)){const d=o.getToolInstance(l);a.push(d)}}return a}function Qge(t,e){var u;const r=new Map,{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return r;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary(),c=t.detail.event,l=(c==null?void 0:c.buttons)??s,f=vh(c)||hh.getModifierKey();for(let d=0;d{var w;return((w=m.bindings)==null?void 0:w.length)&&m.bindings.some(x=>x.mouseButton===l&&x.modifierKey===f)});y&&r.set(g,y)}return r}const{Active:epe,Passive:tpe}=An;function npe(t){if(Be.isInteractingWithTool)return!1;const e=t.detail,{element:r}=e,n=Ce(r),{canvas:i}=e.currentPoints;if(!n)return!1;const o=Qge(t,[epe,tpe]),a=Array.from(o.keys()),s=N1(r,a),c=A4(r,s,i);if(c.length>0){const{tool:l,annotation:f}=c[0],u=o.get(l);return(typeof u.method=="string"?l[u.method]:u.method).call(l,t,f),!0}return!1}const{Active:rpe,Passive:ipe}=An;function PV(t){if(Be.isInteractingWithTool)return;const e=V5(t);if(e&&typeof e.preMouseDownCallback=="function"&&e.preMouseDownCallback(t))return;const r=t.detail.event.buttons===1,n=$0(t,[rpe],t.detail.event.buttons),i=r?$0(t,[ipe]):void 0,o=[...n||[],...i||[]];if(npe(t))return;const s=t.detail,{element:c}=s,l=N1(c,o),f=s.currentPoints.canvas,u=MV(c,l,f,"mouse"),d=!!t.detail.event.shiftKey;if(u.length>0){const{tool:g,annotation:p,handle:v}=ND(u);kD(p.annotationUID,d),g.handleSelectedCallback(t,p,v,"Mouse");return}const h=A4(c,l,f,"mouse");if(h.length>0){const{tool:g,annotation:p}=ND(h);kD(p.annotationUID,d),g.toolSelectedCallback(t,p,"Mouse",f);return}e&&typeof e.postMouseDownCallback=="function"&&e.postMouseDownCallback(t)}function ND(t){if(t.length>1){const e=t.find(r=>{const n=!Zr(r.annotation.annotationUID),i=Gr(r.annotation.annotationUID);return n&&i});if(e)return e}return t[0]}function kD(t,e=!1){e?b1(t)?Ro(t,!1):Ro(t,!0,!0):Ro(t,!0,!1)}function RV(t){if(Be.isInteractingWithTool)return;const e=V5(t);if(e&&!Be.isMultiPartToolActive&&e.addNewAnnotation){const r=e.addNewAnnotation(t,"mouse");Ro(r.annotationUID)}}function LV(t){if(Be.isInteractingWithTool)return;const e=V5(t);!e||typeof e.mouseDragCallback!="function"||e.mouseDragCallback(t)}const{Active:ope,Passive:ape}=An;function AV(t){if(Be.isInteractingWithTool||Be.isMultiPartToolActive)return;const e=$0(t,[ope,ape]),r=t.detail,{element:n}=r,i=N1(n,e),o=e.filter(s=>!i.some(l=>l.tool.getToolName()===s.getToolName()));let a=!1;for(const{tool:s,annotations:c}of i)typeof s.mouseMoveCallback=="function"&&(a=s.mouseMoveCallback(t,c)||a);o.forEach(s=>{typeof s.mouseMoveCallback=="function"&&s.mouseMoveCallback(t)}),a===!0&&ph(n)}const NV=xh.bind(null,"Mouse","mouseUpCallback");function kV(t){if(Be.isInteractingWithTool)return;t.detail.buttons=nc.Wheel|(t.detail.event.buttons||0);const e=V5(t);if(e)return e.mouseWheelCallback(t)}const spe=function(t){t.addEventListener(N.MOUSE_CLICK,IV),t.addEventListener(N.MOUSE_DOWN,PV),t.addEventListener(N.MOUSE_DOWN_ACTIVATE,RV),t.addEventListener(N.MOUSE_DOUBLE_CLICK,OV),t.addEventListener(N.MOUSE_DRAG,LV),t.addEventListener(N.MOUSE_MOVE,AV),t.addEventListener(N.MOUSE_UP,NV),t.addEventListener(N.MOUSE_WHEEL,kV)},cpe=function(t){t.removeEventListener(N.MOUSE_CLICK,IV),t.removeEventListener(N.MOUSE_DOWN,PV),t.removeEventListener(N.MOUSE_DOWN_ACTIVATE,RV),t.removeEventListener(N.MOUSE_DOUBLE_CLICK,OV),t.removeEventListener(N.MOUSE_DRAG,LV),t.removeEventListener(N.MOUSE_MOVE,AV),t.removeEventListener(N.MOUSE_UP,NV),t.removeEventListener(N.MOUSE_WHEEL,kV)},VV={enable:spe,disable:cpe},{Active:lpe}=An;function FV(t){const{renderingEngineId:e,viewportId:r}=t.detail,n=_ue(),i=hh.getModifierKey(),o=Or(r,e);if(!o)return null;const a=Object.keys(o.toolOptions),s=o.getDefaultMousePrimary();for(let c=0;cd.mouseButton===(n??s)&&d.modifierKey===i))return o.getToolInstance(l)}}function upe(t,e){var c;const r=new Map,{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return r;const a=Object.keys(o.toolOptions),s=t.detail.key;for(let l=0;l{var v;return(v=p.bindings)==null?void 0:v.some(y=>y.key===s)});g&&r.set(u,g)}return r}function UV(t){const e=FV(t);if(e){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n),a=e.getToolName();Object.keys(o.toolOptions).includes(a)&&o.setViewportsCursorByToolName(a)}const r=upe(t,[An.Active]);if(r!=null&&r.size){const{element:n}=t.detail;for(const[i,o]of[...r.entries()])(typeof o.method=="function"?o.method:i[o.method]).call(i,n,o,t)}}function BV(t){const e=FV(t);if(!e)return;const{renderingEngineId:r,viewportId:n}=t.detail,i=Or(n,r);tk();const o=e.getToolName();Object.keys(i.toolOptions).includes(o)&&i.setViewportsCursorByToolName(o)}const fpe=function(t){t.addEventListener(N.KEY_DOWN,UV),t.addEventListener(N.KEY_UP,BV)},dpe=function(t){t.removeEventListener(N.KEY_DOWN,UV),t.removeEventListener(N.KEY_UP,BV)},GV={enable:fpe,disable:dpe},{Active:hpe,Passive:gpe,Enabled:ppe}=An,WV=function(t){$0(t,[hpe,gpe,ppe]).forEach(r=>{r.onCameraModified&&r.onCameraModified(t)})},mpe=function(t){t.addEventListener(Xe.CAMERA_MODIFIED,WV)},vpe=function(t){t.removeEventListener(Xe.CAMERA_MODIFIED,WV)},zV={enable:mpe,disable:vpe},{Active:ype,Passive:wpe,Enabled:xpe}=An,$V=function(t){$0(t,[ype,wpe,xpe]).forEach(r=>{r.onImageSpacingCalibrated&&r.onImageSpacingCalibrated(t)})},Cpe=function(t){t.addEventListener(Xe.IMAGE_SPACING_CALIBRATED,$V)},Spe=function(t){t.removeEventListener(Xe.IMAGE_SPACING_CALIBRATED,$V)},jV={enable:Cpe,disable:Spe},{Active:_pe}=An;function N4(t){const{renderingEngineId:e,viewportId:r}=t.detail,n=t.detail.event,i=Or(r,e);if(!i)return null;const o=Object.keys(i.toolOptions),a=Object.keys(n.touches).length,s=vh(n)||hh.getModifierKey(),c=i.getDefaultMousePrimary();for(let l=0;l(h.numTouchPoints===a||a===1&&h.mouseButton===c)&&h.modifierKey===s);if(u.mode===_pe&&d)return i.getToolInstance(f)}}function VD(t,e,r){const{renderingEngineId:n,viewportId:i}=t.detail,o=Or(i,n);if(!o)return[];const a=[],s=Object.keys(o.toolOptions);for(let c=0;cd.numTouchPoints===r);if(e.includes(f.mode)&&(!r||u)){const d=o.getToolInstance(l);a.push(d)}}return a}const{Active:Tpe,Passive:Epe}=An;function HV(t){if(Be.isInteractingWithTool)return;const e=N4(t);if(e&&typeof e.preTouchStartCallback=="function"&&e.preTouchStartCallback(t))return;const r=Object.keys(t.detail.event.touches).length===1,n=VD(t,[Tpe],Object.keys(t.detail.event.touches).length),i=r?VD(t,[Epe]):void 0,o=[...n||[],...i||[],e],a=t.detail,{element:s}=a,c=N1(s,o),l=a.currentPoints.canvas,f=MV(s,c,l,"touch"),u=!1;if(f.length>0){const{tool:h,annotation:g,handle:p}=FD(f);UD(g.annotationUID,u),h.handleSelectedCallback(t,g,p,"Touch");return}const d=A4(s,c,l,"touch");if(d.length>0){const{tool:h,annotation:g}=FD(d);UD(g.annotationUID,u),h.toolSelectedCallback(t,g,"Touch",l);return}e&&typeof e.postTouchStartCallback=="function"&&e.postTouchStartCallback(t)}function FD(t){return t.length>1&&t.find(e=>!Zr(e.annotation.annotationUID)&&Gr(e.annotation.annotationUID))||t[0]}function UD(t,e=!1){e?b1(t)?Ro(t,!1):Ro(t,!0,!0):Ro(t,!0,!1)}function KV(t){if(Be.isInteractingWithTool)return;const e=N4(t);if(e&&!Be.isMultiPartToolActive&&e.addNewAnnotation){const r=e.addNewAnnotation(t,"touch");Ro(r.annotationUID)}}function qV(t){if(Be.isInteractingWithTool)return;const e=N4(t);!e||typeof e.touchDragCallback!="function"||e.touchDragCallback(t)}const XV=xh.bind(null,"Touch","touchEndCallback"),Dpe=xh.bind(null,"Touch","touchTapCallback"),YV=xh.bind(null,"Touch","touchPressCallback"),bpe=function(t){t.addEventListener(N.TOUCH_START,HV),t.addEventListener(N.TOUCH_START_ACTIVATE,KV),t.addEventListener(N.TOUCH_DRAG,qV),t.addEventListener(N.TOUCH_END,XV),t.addEventListener(N.TOUCH_TAP,Dpe),t.addEventListener(N.TOUCH_PRESS,YV)},Ipe=function(t){t.removeEventListener(N.TOUCH_START,HV),t.removeEventListener(N.TOUCH_START_ACTIVATE,KV),t.removeEventListener(N.TOUCH_DRAG,qV),t.removeEventListener(N.TOUCH_END,XV),t.removeEventListener(N.TOUCH_PRESS,YV)},JV={enable:bpe,disable:Ipe},Ope=function(){Ke.addEventListener(N.ANNOTATION_COMPLETED,Ys.handleAnnotationCompleted),Ke.addEventListener(N.ANNOTATION_MODIFIED,Ys.handleAnnotationUpdate),Ke.addEventListener(N.ANNOTATION_REMOVED,Ys.handleAnnotationDelete)},Mpe=function(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,Ys.handleAnnotationCompleted),Ke.removeEventListener(N.ANNOTATION_MODIFIED,Ys.handleAnnotationUpdate),Ke.removeEventListener(N.ANNOTATION_REMOVED,Ys.handleAnnotationDelete)},ZV={enable:Ope,disable:Mpe},{Active:Ppe,Passive:Rpe,Enabled:Lpe}=An,QV=function(t){$0(t,[Ppe,Rpe,Lpe]).forEach(r=>{r.onResetCamera&&r.onResetCamera(t)})},Ape=function(t){t.addEventListener(Xe.CAMERA_RESET,QV)},Npe=function(t){t.removeEventListener(Xe.CAMERA_RESET,QV)},eF={enable:Ape,disable:Npe};function k4(t){const{element:e,viewportId:r}=t.detail,n=kpe(r);Vpe(e),Fpe(n,e),C4.addViewportElement(r,e),AN.enable(e),QN.enable(e),YN.enable(e),hh.enable(e),_V.enable(e),bV.enable(e),zV.enable(e),jV.enable(e),eF.enable(e),VV.enable(e),GV.enable(e),JV.enable(e),Be.enabledElements.push(e)}function kpe(t){const e="http://www.w3.org/2000/svg",r=document.createElementNS(e,"svg"),n=`svg-layer-${t}`;r.classList.add("svg-layer"),r.setAttribute("id",n),r.setAttribute("xmlns","http://www.w3.org/2000/svg"),r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.position="absolute";const i=document.createElementNS(e,"defs"),o=document.createElementNS(e,"filter"),a=document.createElementNS(e,"feOffset"),s=document.createElementNS(e,"feColorMatrix"),c=document.createElementNS(e,"feBlend");return o.setAttribute("id",`shadow-${n}`),o.setAttribute("filterUnits","userSpaceOnUse"),a.setAttribute("result","offOut"),a.setAttribute("in","SourceGraphic"),a.setAttribute("dx","0.5"),a.setAttribute("dy","0.5"),s.setAttribute("result","matrixOut"),s.setAttribute("in","offOut"),s.setAttribute("in2","matrix"),s.setAttribute("values","0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0"),c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","matrixOut"),c.setAttribute("mode","normal"),o.appendChild(a),o.appendChild(s),o.appendChild(c),i.appendChild(o),r.appendChild(i),r}function Vpe(t){const{viewportUid:e,renderingEngineUid:r}=t.dataset,n=`${e}:${r}`;Be.svgNodeCache[n]={}}function Fpe(t,e){e.querySelector("div.viewport-element").appendChild(t)}function tF(t,e){const r=[];if(!e&&!t)throw new Error("At least one of renderingEngineId or viewportId should be given");for(let n=0;n{const e=Ce(t);if(!e)return;tF(e.viewportId,e.renderingEngineId).forEach(n=>{n.remove(e)})},Gpe=t=>{const e=Ce(t);if(!e)return;const{renderingEngineId:r,viewportId:n}=e,i=Or(n,r);i&&i.removeViewports(r,n)};function Wpe(t){const{viewportUid:e,renderingEngineUid:r}=t.dataset,n=`${e}:${r}`;delete Be.svgNodeCache[n]}function zpe(t){const e=t.querySelector(`div.${Upe}`),r=e.querySelector("svg");r&&e.removeChild(r)}const $pe=function(t){const e=Be.enabledElements.findIndex(r=>r===t);e>-1&&Be.enabledElements.splice(e,1)};function nF(t){const e=zk(t,[An.Active,An.Passive]),r=N1(t,e);for(const{tool:n}of r){const i=n.cancel(t);if(i)return i}}class F4{constructor(e,r,n,i){this._viewportOptions={},this._onEvent=o=>{var l;if(this._ignoreFiredEvents===!0||!this._targetViewports.length)return;const a=this._eventSource==="element"?Ce(o.currentTarget):zn((l=o.detail)==null?void 0:l.viewportId);if(!a)return;const{renderingEngineId:s,viewportId:c}=a;this._sourceViewports.find(f=>f.viewportId===c)&&this.fireEvent({renderingEngineId:s,viewportId:c},o)},this._enabled=!0,this._eventName=r,this._eventHandler=n,this._ignoreFiredEvents=!1,this._sourceViewports=[],this._targetViewports=[],this._options=i||{},this._eventSource=this._options.eventSource||"element",this._auxiliaryEvents=this._options.auxiliaryEvents||[],this.id=e}isDisabled(){return!this._enabled||!this._hasSourceElements()}setOptions(e,r={}){this._viewportOptions[e]=r}setEnabled(e){this._enabled=e}getOptions(e){return this._viewportOptions[e]}add(e){this.addTarget(e),this.addSource(e)}addSource(e){if(Vm(this._sourceViewports,e))return;const{renderingEngineId:r,viewportId:n}=e,i=Jr(r).getViewport(n);if(!i){console.warn(`Synchronizer.addSource: No viewport for ${r} ${n}`);return}(this._eventSource==="element"?i.element:Ke).addEventListener(this._eventName,this._onEvent.bind(this)),this._auxiliaryEvents.forEach(({name:a,source:s})=>{(s==="element"?i.element:Ke).addEventListener(a,this._onEvent.bind(this))}),this._updateDisableHandlers(),this._sourceViewports.push(e)}addTarget(e){Vm(this._targetViewports,e)||(this._targetViewports.push(e),this._updateDisableHandlers())}getSourceViewports(){return this._sourceViewports}getTargetViewports(){return this._targetViewports}destroy(){this._sourceViewports.forEach(e=>this.removeSource(e)),this._targetViewports.forEach(e=>this.removeTarget(e))}remove(e){this.removeTarget(e),this.removeSource(e)}removeSource(e){const r=BD(this._sourceViewports,e);if(r===-1)return;const n=this._eventSource==="element"?this.getViewportElement(e):Ke;this._sourceViewports.splice(r,1),n.removeEventListener(this._eventName,this._eventHandler),this._auxiliaryEvents.forEach(({name:i,source:o})=>{(o==="element"?this.getViewportElement(e):Ke).removeEventListener(i,this._eventHandler)}),this._updateDisableHandlers()}removeTarget(e){const r=BD(this._targetViewports,e);r!==-1&&(this._targetViewports.splice(r,1),this._updateDisableHandlers())}hasSourceViewport(e,r){return Vm(this._sourceViewports,{renderingEngineId:e,viewportId:r})}hasTargetViewport(e,r){return Vm(this._targetViewports,{renderingEngineId:e,viewportId:r})}fireEvent(e,r){if(this.isDisabled()||this._ignoreFiredEvents)return;this._ignoreFiredEvents=!0;const n=[];try{for(let i=0;i{this._ignoreFiredEvents=!1}):this._ignoreFiredEvents=!1}}_hasSourceElements(){return this._sourceViewports.length!==0}_updateDisableHandlers(){const e=jpe(this._sourceViewports,this._targetViewports),r=this.remove.bind(this),n=i=>{r(i.detail.element)};e.forEach(i=>{const o=this.getEventSource(i);o&&(o.removeEventListener(Xe.ELEMENT_DISABLED,n),o.addEventListener(Xe.ELEMENT_DISABLED,n))})}getEventSource(e){return this._eventSource==="element"?this.getViewportElement(e):Ke}getViewportElement(e){const{renderingEngineId:r,viewportId:n}=e,i=Jr(r);if(!i)return null;const o=i.getViewport(n);return o?o.element:null}}function jpe(t,e){const r=[],n=t.concat(e);for(let i=0;io.renderingEngineId===a.renderingEngineId&&o.viewportId===a.viewportId)||r.push(o)}return r}function BD(t,e){return t.findIndex(r=>e.renderingEngineId===r.renderingEngineId&&e.viewportId===r.viewportId)}function Vm(t,e){return t.some(r=>r.renderingEngineId===e.renderingEngineId&&r.viewportId===e.viewportId)}function hd(t,e,r,n){if(Be.synchronizers.some(a=>a.id===t))throw new Error(`Synchronizer with id '${t}' already exists.`);const o=new F4(t,e,r,n);return Be.synchronizers.push(o),o}function Hpe(){for(;Be.synchronizers.length>0;)Be.synchronizers.pop().destroy()}function Kpe(t){return Be.synchronizers.find(e=>e.id===t)}function qpe(){return Be.synchronizers}function Xpe(t){const e=Be.synchronizers.findIndex(r=>r.id===t);e>-1&&(Be.synchronizers[e].destroy(),Be.synchronizers.splice(e,1))}const rF=Object.freeze(Object.defineProperty({__proto__:null,createSynchronizer:hd,destroy:Hpe,destroySynchronizer:Xpe,getAllSynchronizers:qpe,getSynchronizer:Kpe,getSynchronizersForViewport:tF},Symbol.toStringTag,{value:"Module"})),Ype=Object.freeze(Object.defineProperty({__proto__:null,Synchronizer:F4,SynchronizerManager:rF,ToolGroupManager:vN,addEnabledElement:k4,addTool:Ci,cancelActiveManipulations:nF,hasTool:lue,removeEnabledElement:V4,removeTool:TN,get state(){return Be},svgNodeCache:d5},Symbol.toStringTag,{value:"Module"})),sy=function(t){const{viewportId:e}=t.detail;wh(e)};let bC=!1;function iF(t={}){bC||(lfe(t),Zpe(),Qpe(),bC=!0)}function Jpe(){oF(),aF(),pN(),kce();const t=Es(),e=Zn;t.restoreAnnotations({}),e.resetState(),bC=!1}function Zpe(){oF();const t=Xe.ELEMENT_ENABLED,e=Xe.ELEMENT_DISABLED;Ke.addEventListener(t,k4),Ke.addEventListener(e,V4),ZV.enable()}function oF(){const t=Xe.ELEMENT_ENABLED,e=Xe.ELEMENT_DISABLED;Ke.removeEventListener(t,k4),Ke.removeEventListener(e,V4),ZV.disable()}function Qpe(){aF(),Ke.addEventListener(N.ANNOTATION_COMPLETED,TV),Ke.addEventListener(N.ANNOTATION_MODIFIED,EV),Ke.addEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.addEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.addEventListener(N.ANNOTATION_REMOVED,qge),Ke.addEventListener(N.SEGMENTATION_MODIFIED,CV),Ke.addEventListener(N.SEGMENTATION_DATA_MODIFIED,xV),Ke.addEventListener(N.SEGMENTATION_REPRESENTATION_MODIFIED,sy),Ke.addEventListener(N.SEGMENTATION_REPRESENTATION_ADDED,sy)}function aF(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,TV),Ke.removeEventListener(N.ANNOTATION_MODIFIED,EV),Ke.removeEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.removeEventListener(N.ANNOTATION_SELECTION_CHANGE,ay),Ke.removeEventListener(N.SEGMENTATION_MODIFIED,CV),Ke.removeEventListener(N.SEGMENTATION_DATA_MODIFIED,xV),Ke.removeEventListener(N.SEGMENTATION_REPRESENTATION_MODIFIED,sy),Ke.removeEventListener(N.SEGMENTATION_REPRESENTATION_ADDED,sy)}const e1e=Object.freeze(Object.defineProperty({__proto__:null,COLOR_LUT:oy},Symbol.toStringTag,{value:"Module"})),t1e="3.20.0";function n1e(t,e,r,n){const{camera:i}=n.detail,o=Jr(r.renderingEngineId);if(!o)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const a=o.getViewport(r.viewportId);a.setCamera(i),a.render()}const{CAMERA_MODIFIED:r1e}=Xe;function i1e(t){return hd(t,r1e,n1e)}function o1e(t,e,r,n,i){const o=Jr(r.renderingEngineId);if(!o)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const a=o.getViewport(r.viewportId),c=o.getViewport(e.viewportId).getViewPresentation(i);a.setViewPresentation(c),a.render()}const{CAMERA_MODIFIED:a1e}=Xe;function s1e(t,e){return hd(t,a1e,o1e,{viewPresentation:e})}function c1e(t,e,r,n,i){const o=n.detail,{volumeId:a,range:s,invertStateChanged:c,invert:l,colormap:f}=o,u=Jr(r.renderingEngineId);if(!u)throw new Error(`Rendering Engine does not exist: ${r.renderingEngineId}`);const d=u.getViewport(r.viewportId),h={voiRange:s};if(i!=null&&i.syncInvertState&&c&&(h.invert=l),i!=null&&i.syncColormap&&f&&(h.colormap=f),d instanceof Ir)d._actors&&d._actors.size>1?d.setProperties(h,a):d.setProperties(h);else if(d instanceof lr)d.setProperties(h);else throw new Error("Viewport type not supported.");d.render()}function l1e(t,e){return e=Object.assign({syncInvertState:!0,syncColormap:!0},e),hd(t,Xe.VOI_MODIFIED,c1e,{auxiliaryEvents:[{name:Xe.COLORMAP_MODIFIED}],...e})}function u1e(t,e,r){const n=Jr(r.renderingEngineId);if(!n)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const i=t.getOptions(r.viewportId),o=n.getViewport(r.viewportId),a=n.getViewport(e.viewportId);if((i==null?void 0:i.syncZoom)!==!1){const s=a.getZoom();o.setZoom(s)}if((i==null?void 0:i.syncPan)!==!1){const s=a.getPan();o.setPan(s)}o.render()}const{CAMERA_MODIFIED:f1e}=Xe;function d1e(t){return hd(t,f1e,u1e)}function h1e(t,e){const{viewPlaneNormal:r}=t.getCamera(),{viewPlaneNormal:n}=e.getCamera(),i=Et(r,n);return Math.abs(i)>.9}const GD=(t,e)=>kp.get("spatialRegistrationModule",t,e);async function g1e(t,e,r){const n=Jr(r.renderingEngineId);if(!n)throw new Error(`No RenderingEngine for Id: ${r.renderingEngineId}`);const i=n.getViewport(e.viewportId),o=t.getOptions(r.viewportId);if(o!=null&&o.disabled)return;const a=n.getViewport(r.viewportId),s=i.getCurrentImageId(),l=mt("imagePlaneModule",s).imagePositionPatient,f=a.getImageIds();if(!h1e(i,a))return;let u=GD(r.viewportId,e.viewportId);if(!u){const p=i.getFrameOfReferenceUID(),v=a.getFrameOfReferenceUID();if(p===v&&(o==null?void 0:o.useInitialPosition)!==!1?u=Vt(Zo()):(HA(i,a),u=GD(r.viewportId,e.viewportId)),!u)return}const d=Jt(Ve(),l,u),h=p1e(d,f);let g=h.index;a instanceof ur&&(g=f.length-h.index-1),h.index!==-1&&a.getCurrentImageIdIndex()!==h.index&&await Aa(a.element,{imageIndex:g})}function p1e(t,e){return e.reduce((r,n,i)=>{const{imagePositionPatient:o}=mt("imagePlaneModule",n),a=ki(o,t);return a{i.getImageIds().includes(t)&&i.calibrateSpacing(t)})}function lF(t,e){const r=t.findIndex(([n,i])=>n===i);if(r===-1)throw new Error("3D bounding boxes not supported in an oblique plane");return t[r][0]-=e,t[r][1]+=e,t}const D1e=Object.freeze(Object.defineProperty({__proto__:null,extend2DBoundingBoxInViewAxis:lF,getBoundingBoxAroundShape:Su,getBoundingBoxAroundShapeIJK:Su,getBoundingBoxAroundShapeWorld:ik},Symbol.toStringTag,{value:"Module"})),{transformWorldToIndex:c3}=Mn;function uF(t,e,r){const[n,i]=t,o=bt((n[0]+i[0])/2,(n[1]+i[1])/2,(n[2]+i[2])/2),a=ki(n,i)/2,{boundsIJK:s,topLeftWorld:c,bottomRightWorld:l}=I1e(e,r,t,o,a);return{boundsIJK:s,centerWorld:o,radiusWorld:a,topLeftWorld:c,bottomRightWorld:l}}function fF(t,e){const r=e.getDirection(),n=bt(r[0],r[1],r[2]),i=bt(r[3],r[4],r[5]),o=bt(r[6],r[7],r[8]),a=Hs(Ve(),o);return uF(t,e,{row:n,column:i,normal:a})}function b1e(t,e,r){if(!r)throw new Error("viewport is required in order to calculate the sphere bounds");const n=r.getCamera(),i=bt(n.viewUp[0],n.viewUp[1],n.viewUp[2]),o=bt(n.viewPlaneNormal[0],n.viewPlaneNormal[1],n.viewPlaneNormal[2]),a=Ve();Rn(a,i,o);const s={row:a,normal:o,column:Hs(Ve(),i)};return uF(t,e,s)}function I1e(t,e,r,n,i){const o=t.getDimensions(),{row:a,column:s,normal:c}=e,l=Ve(),f=Ve();Tn(l,n,c,i),Tn(f,n,c,-i),Tn(l,l,s,-i),Tn(f,f,s,i),Tn(l,l,a,-i),Tn(f,f,a,i);const u=c3(t,l),d=c3(t,f),h=r.map(p=>c3(t,p));return{boundsIJK:Su([u,d,...h],o),topLeftWorld:l,bottomRightWorld:f}}function dF(t,e=5){return parseFloat(t[0]).toFixed(e)+","+parseFloat(t[1]).toFixed(e)+","+parseFloat(t[2]).toFixed(e)+","}class O1e{static setStartRange(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,n)}static setEndRange(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,void 0,n)}static setRange(e,r,n,i){var c;const{metadata:o}=r;n===void 0&&(n=o.sliceIndex=n?a:e.getNumberOfSlices()-1),i=Math.max(n,i),o.sliceIndex=Math.min(n,i),o.referencedImageId=e.getCurrentImageId(o.sliceIndex),o.referencedImageURI=void 0,i===o.sliceIndex?o.multiSliceReference=void 0:i!==((c=o.multiSliceReference)==null?void 0:c.sliceIndex)&&(o.multiSliceReference={referencedImageId:e.getCurrentImageId(i),sliceIndex:i});const s={viewportId:e.id,renderingEngineId:e.renderingEngineId,changeType:Ht.MetadataReferenceModified,annotation:r};at(Ke,N.ANNOTATION_MODIFIED,s),this.setViewportFrameRange(e,o)}static setSingle(e,r,n=e.getCurrentImageIdIndex()){this.setRange(e,r,n,n)}static getFrameRange(e){const{metadata:r}=e,{sliceIndex:n,multiSliceReference:i}=r,o=i==null?void 0:i.sliceIndex;return o?[n+1,o+1]:n+1}static getFrameRangeStr(e){const r=this.getFrameRange(e);return Array.isArray(r)?`${r[0]}-${r[1]}`:String(r)}static setViewportFrameRange(e,r){var n;e.setFrameRange&&((n=r.multiSliceReference)!=null&&n.sliceIndex)&&e.setFrameRange(r.sliceIndex+1,r.multiSliceReference.sliceIndex+1)}}function M1e(t,e){const{viewPlaneNormal:r}=t.metadata,{viewPlaneNormal:n}=e.metadata,i=Et(r,n);if(!vu(1,Math.abs(i)))return!1;const{polyline:a}=t.data.contour,{polyline:s}=e.data.contour,c=Et(r,a[0]),l=Et(r,s[0]);return vu(c,l)}function hF(t,e,r){let n=-1;if(e.forEach((i,o)=>{n>=0||i.a==t.b&&(n=o)}),n>=0){const i=e[n];return e.splice(n,1),r.push(i.b),r[0]==i.b?{remainingLines:e,contourPoints:r,type:"CLOSED_PLANAR"}:hF(i,e,r)}return{remainingLines:e,contourPoints:r,type:"OPEN_PLANAR"}}function U4(t){if(t.length==0)return[];const e=[],r=t.shift();e.push(r.a),e.push(r.b);const n=hF(r,t,e);if(n.remainingLines.length==0)return[{type:n.type,contourPoints:n.contourPoints}];{const i=U4(n.remainingLines);return i.push({type:n.type,contourPoints:n.contourPoints}),i}}function P1e(t){return U4(t)}const R1e={findContours:U4,findContoursFromReducedSet:P1e};function L1e(t,e=!1){const r=t.getPoints(),n=t.getLines(),i=new Array(r.getNumberOfPoints()).fill(0).map((c,l)=>r.getPoint(l).slice()),o=new Array(n.getNumberOfCells()).fill(0).map((c,l)=>{const f=n.getCell(l*3).slice();return{a:f[0],b:f[1]}});if(e)return{points:i,lines:o};const a=[];for(const[c,l]of i.entries()){const f=a.findIndex(u=>u[0]===l[0]&&u[1]===l[1]&&u[2]===l[2]);if(f>=0)o.map(u=>(u.a===c&&(u.a=f),u.b===c&&(u.b=f),u));else{const u=a.length;a.push(l),o.map(d=>(d.a===c&&(d.a=u),d.b===c&&(d.b=u),d))}}const s=o.filter(c=>c.a!==c.b);return{points:a,lines:s}}const A1e=(t,e)=>{const r=t[0],n=t[1];let i=!1;for(let o=0,a=e.length-1;on!=f>n&&r<(l-s)*(n-c)/(f-c)+s&&(i=!i)}return i};function N1e(t,e,r){const n=[];t.contourPoints.forEach(o=>{n.push([r[o][0],r[o][1]])});let i=0;return e.contourPoints.forEach(o=>{A1e([r[o][0],r[o][1]],n)||i++}),i===0}function k1e(t,e,r=!0){const n=t.filter(s=>s.type!=="CLOSED_PLANAR"),i=t.filter(s=>s.type==="CLOSED_PLANAR"),o=[];let a=[];return i.forEach((s,c)=>{const l=[];i.forEach((f,u)=>{c!=u&&N1e(s,f,e)&&l.push(u)}),l.length>0?o.push({contour:s,holes:l}):a.push(c)}),r&&(o.forEach(s=>{s.contour.type="CLOSEDPLANAR_XOR",n.push(s.contour),s.holes.forEach(c=>{i[c].type="CLOSEDPLANAR_XOR",n.push(i[c]),a=a.filter(l=>l!==c)})}),a.forEach(s=>{n.push(i[s])})),n}const V1e={processContourHoles:k1e};let WD=!1;function F5(){if(WD)return;WD=!0;const t=()=>new Worker(new URL("/static/dv3d/assets/computeWorker-FOqOvCDJ.js",import.meta.url),{name:"compute",type:"module"}),e=il(),n=cfe().computeWorker,i={maxWorkerInstances:1,autoTerminateOnIdle:(n==null?void 0:n.autoTerminateOnIdle)??{enabled:!0,idleTimeThreshold:2e3}};e.registerWorker("compute",t,i)}function U5(){return Zn.getState().segmentations}function F1e(t){const{segmentationId:e,representation:r,config:n}=t,{type:i,data:o}=r,a=o?{...o}:{};if(!a)throw new Error("Segmentation representation data may not be undefined");i===Dt.Contour&&U1e(a);const s=B1e(n==null?void 0:n.segments,i,a);return n==null||delete n.segments,{segmentationId:e,label:(n==null?void 0:n.label)??null,cachedStats:(n==null?void 0:n.cachedStats)??{},segments:s,representationData:{[i]:{...a}}}}function U1e(t){t.geometryIds=t.geometryIds??[],t.annotationUIDsMap=t.annotationUIDsMap??new Map}function B1e(t,e,r){const n={};return t?Object.entries(t).forEach(([i,o])=>{const{label:a,locked:s,cachedStats:c,active:l,...f}=o,u={segmentIndex:Number(i),label:a??`Segment ${i}`,locked:s??!1,cachedStats:c??{},active:l??!1,...f};n[i]=u}):e===Dt.Surface?G1e(n,r):n[1]=W1e(),n}function G1e(t,e){const{geometryIds:r}=e;r==null||r.forEach(n=>{const i=Le.getGeometry(n);if(i!=null&&i.data){const{segmentIndex:o}=i.data;t[o]={segmentIndex:o}}})}function W1e(){return{segmentIndex:1,label:"Segment 1",locked:!1,cachedStats:{},active:!0}}function gF(t,e){const r=Zn;t.forEach(n=>{const i=F1e(n);r.addSegmentation(i),e||Ta(i.segmentationId)})}function Ch(t,e,r){return mF(t,e,r)}function pF(t,e,r){return mF(t,e,r)}function mF(t,e,r){const{segmentationId:n,type:i}=e;return z1e(t,n,i,r),Zn.removeSegmentationRepresentations(t,{segmentationId:n,type:i})}function vF(){Zn.getAllViewportSegmentationRepresentations().forEach(({viewportId:e,representations:r})=>{r.forEach(({segmentationId:n,type:i})=>{Ch(e,{segmentationId:n,type:i})})}),Zn.resetState()}function yF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Labelmap},r)}function wF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Contour},r)}function xF(t,e,r){Ch(t,{segmentationId:e,type:Dt.Surface},r)}function z1e(t,e,r,n){Jo(t,{segmentationId:e,type:r}).forEach(a=>{a.type===Dt.Labelmap?nV.removeRepresentation(t,a.segmentationId,n):a.type===Dt.Contour?eV.removeRepresentation(t,a.segmentationId,n):a.type===Dt.Surface&&uk.removeRepresentation(t,a.segmentationId,n)});const{viewport:o}=zn(t)||{};o&&o.render()}function B4(t){const e=Zn;e.getAllViewportSegmentationRepresentations().filter(({representations:n})=>n.some(i=>i.segmentationId===t)).map(({viewportId:n})=>n).forEach(n=>{pF(n,{segmentationId:t})}),e.removeSegmentation(t),e4(t)}function CF(){const t=Zn;t.getState().segmentations.map(n=>n.segmentationId).forEach(n=>{B4(n)}),t.resetState()}function $1e(t){Zn.removeColorLUT(t)}function SF(t,e){return _F(t).map(o=>(e&&o.type===e,Ln(o.segmentationId))).filter(o=>o!==void 0)}function _F(t){return Zn.getState().viewportSegRepresentations[t]}function j1e(t,e){return Zn.getStackSegmentationImageIdsForViewport(t,e)}function H1e(){Zn.resetState()}const K1e=Object.freeze(Object.defineProperty({__proto__:null,addColorLUT:$g,addSegmentations:gF,destroy:H1e,getColorLUT:D1,getCurrentLabelmapImageIdForViewport:Vu,getCurrentLabelmapImageIdsForViewport:Qc,getNextColorLUTIndex:gV,getSegmentation:Ln,getSegmentationRepresentation:t4,getSegmentationRepresentations:Jo,getSegmentationRepresentationsBySegmentationId:sk,getSegmentations:U5,getStackSegmentationImageIdsForViewport:j1e,getViewportIdsWithSegmentation:yh,getViewportSegmentationRepresentations:_F,getViewportSegmentations:SF,removeAllSegmentationRepresentations:vF,removeAllSegmentations:CF,removeColorLUT:$1e,removeContourRepresentation:wF,removeLabelmapRepresentation:yF,removeSegmentation:B4,removeSegmentationRepresentation:Ch,removeSurfaceRepresentation:xF,updateLabelmapSegmentationImageReferences:SV},Symbol.toStringTag,{value:"Module"}));function TF(t){if("volumeId"in t){if(t=t,!Le.getVolume(t.volumeId))throw new Error(`volumeId of ${t.volumeId} not found in cache, you should load and cache volume before adding segmentation`)}else if("imageIds"in t){if(t=t,!t.imageIds)throw new Error("The segmentationInput.representationData.imageIds is undefined, please provide a valid representationData.imageIds for stack data")}else throw new Error("The segmentationInput.representationData is undefined, please provide a valid representationData")}function q1e(t){if(!t.representation.data)throw new Error("The segmentationInput.representationData.data is undefined, please provide a valid representationData.data");const e=t.representation.data;TF(e)}function X1e(t){TF(t)}const Y1e=Object.freeze(Object.defineProperty({__proto__:null,validate:X1e,validatePublic:q1e},Symbol.toStringTag,{value:"Module"}));function EF(t){const e=Le.getVolume(t);if(!e)return null;const r=e.referencedVolumeId;let n;if(r)n=Le.getVolume(r);else{const i=e.imageIds,a=Le.getImage(i[0]).referencedImageId,s=Le.getVolumeContainingImageId(a);n=s==null?void 0:s.volume}return n}function J1e({operationData:t}){const{volumeId:e}=t;if(!e){const c=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"No volume id found for the segmentation"},cancelable:!0});return Ke.dispatchEvent(c),null}const r=Le.getVolume(e),n=EF(e);if(!r||!n)return null;const{imageData:i}=r,{voxelManager:o}=r,{voxelManager:a,imageData:s}=n;return{segmentationImageData:i,segmentationVoxelManager:o,segmentationScalarData:null,imageScalarData:null,imageVoxelManager:a,imageData:s}}function Z1e({operationData:t,viewport:e,strategy:r}){var f;const{segmentationId:n}=t;let i,o,a,s,c,l;if(r.ensureSegmentationVolumeFor3DManipulation)r.ensureSegmentationVolumeFor3DManipulation({operationData:t,viewport:e}),o=t.segmentationVoxelManager,i=t.segmentationImageData,a=null;else{const u=Vu(e.id,n);if(!u)return null;const d=_5(e.id,n);if(!d)return null;const h=Le.getImage(u);i=d.actor.getMapper().getInputData(),o=h.voxelManager;const g=t.imageId,p=Le.getImage(g);if(!p)return null;a=(f=p.getPixelData)==null?void 0:f.call(p)}if(r.ensureImageVolumeFor3DManipulation)r.ensureImageVolumeFor3DManipulation({operationData:t,viewport:e}),c=t.imageVoxelManager,s=t.imageScalarData,l=t.imageData;else{const u=e.getCurrentImageId();if(!u)return null;const d=Le.getImage(u);l=d?null:e.getImageData(),s=(d==null?void 0:d.getPixelData())||l.getScalarData(),c=d==null?void 0:d.voxelManager}return{segmentationImageData:i,segmentationScalarData:a,imageScalarData:s,segmentationVoxelManager:o,imageVoxelManager:c,imageData:l}}function G4({operationData:t,viewport:e,strategy:r}){return t?"volumeId"in t&&t.volumeId!=null||"referencedVolumeId"in t&&t.referencedVolumeId!=null?J1e({operationData:t}):Z1e({operationData:t,viewport:e,strategy:r}):null}function Sh(t){const{representationData:e}=Ln(t);let{volumeId:r}=e.Labelmap,n;if(r&&(n=Le.getVolume(r),n))return n;const{imageIds:i}=e.Labelmap;if(r=Le.generateVolumeId(i),!(!i||i.length===1||!Nu(i)))return n=i5(r,i),n}const DF={[St.EnsureSegmentationVolumeFor3DManipulation]:t=>{const{operationData:e,viewport:r}=t,{segmentationId:n,imageIds:i}=e,o=r?r.getImageIds():i.map(c=>Le.getImage(c).referencedImageId);if(!Nu(o))throw new Error("Volume is not reconstructable for sphere manipulation");const s=Sh(n);s&&(e.segmentationVoxelManager=s.voxelManager,e.segmentationImageData=s.imageData)}};function B5(t){if(!t||t.length<=1||!Nu(t))return;const r=Le.generateVolumeId(t);let n=Le.getVolume(r);return n||(n=i5(r,t),n)}const bF={[St.EnsureImageVolumeFor3DManipulation]:t=>{const{operationData:e,viewport:r}=t;let n;if(r){if(n=r.getImageIds(),!Nu(n))throw new Error("Volume is not reconstructable for sphere manipulation")}else n=Ln(e.segmentationId).representationData.Labelmap.imageIds.map(s=>Le.getImage(s).referencedImageId);const i=B5(n);if(!i)throw new Error("Failed to create or get image volume");e.imageVoxelManager=i.voxelManager,e.imageData=i.imageData}},oc=(t,e)=>{at(Ke,Xe.WEB_WORKER_PROGRESS,{progress:e,type:t})},IF=(t,e)=>{const r=Ln(t),{representationData:n}=r,{Labelmap:i}=n;if(!i)return console.debug("No labelmap found for segmentation",t),null;const o=i.volumeId,a=i.imageIds,s={segmentationId:t,volumeId:o,imageIds:a};let c=!1;if(a){const f=a.map(u=>Le.getImage(u).referencedImageId);c=Nu(f)}let l=e;return l?Array.isArray(l)||(l=[l,255]):l=[ea(t)],{operationData:s,segVolumeId:o,segImageIds:a,reconstructableVolume:c,indices:l}},OF=t=>G4({operationData:t,strategy:{ensureSegmentationVolumeFor3DManipulation:DF.ensureSegmentationVolumeFor3DManipulation,ensureImageVolumeFor3DManipulation:bF.ensureImageVolumeFor3DManipulation}}),MF=t=>{const e=[],r=[];for(const n of t){const i=Le.getImage(n),o=i.getPixelData(),{origin:a,direction:s,spacing:c,dimensions:l}=a5(i);e.push({scalarData:o,dimensions:l,spacing:c,origin:a,direction:s});const f=i.referencedImageId;if(f){const u=Le.getImage(f);if(!u)continue;const d=u.getPixelData(),h=u.voxelManager,g=[u.rowPixelSpacing,u.columnPixelSpacing];r.push({scalarData:d,dimensions:h?h.dimensions:[u.columns,u.rows,1],spacing:g})}}return{segmentationInfo:e,imageInfo:r}},Q1e=(t,e)=>{var a;let r;if(t){const c=Le.getVolume(t).imageIds,l=Le.getImage(c[0]);l&&(r=l.referencedImageId)}else e!=null&&e.length&&(r=Le.getImage(e[0]).referencedImageId);const n=Le.getImage(r),i=mt("scalingModule",r),o={isPreScaled:!!((a=n==null?void 0:n.preScale)!=null&&a.scaled),isSuvScaled:typeof(i==null?void 0:i.suvbw)=="number"};return{refImageId:r,modalityUnitOptions:o}},{Labelmap:eme}=Dt;async function PF({segmentations:t}){F5(),oc(xa.GENERATE_CONTOUR_SETS,0);const{representationData:e,segments:r=[0,1],segmentationId:n}=t;let{volumeId:i}=e[eme];if(!i){const g=Sh(n);g&&(i=g.volumeId)}const o=Le.getVolume(i);if(!o){console.warn(`No volume found for ${i}`);return}const c={scalarData:o.voxelManager.getCompleteScalarDataArray(),dimensions:o.dimensions,spacing:o.imageData.getSpacing(),origin:o.imageData.getOrigin(),direction:o.imageData.getDirection()},l=Array.isArray(r)?r.filter(g=>g!==null).map(g=>g.segmentIndex||g):Object.values(r).filter(g=>g!==null).map(g=>g.segmentIndex||g),f=await il().executeTask("compute","generateContourSetsFromLabelmapVolume",{segmentation:c,indices:l,mode:"individual"}),u=o.imageIds.map(g=>{var v;const p=(v=Le.getImage(g))==null?void 0:v.referencedImageId;return p?Le.getImage(p):void 0}),d=u.map(g=>a5(g)),h=f.map(g=>{const p=r[g.segment.segmentIndex]||{};if(!g.sliceContours.length)return null;const v=g.sliceContours[0].polyData.points[0];let y;if(v){const m=d.findIndex(w=>{const{scanAxisNormal:x,origin:C}=w,S=qs(x,C);return tA(v,S)});m!==-1&&(y=u[m].imageId)}return{label:p.label,color:p.color,metadata:{FrameOfReferenceUID:o.metadata.FrameOfReferenceUID,referencedImageId:y},sliceContours:g.sliceContours.map(m=>({contours:m.contours,polyData:m.polyData,FrameNumber:m.sliceIndex+1,sliceIndex:m.sliceIndex,FrameOfReferenceUID:o.metadata.FrameOfReferenceUID,referencedImageId:y}))}}).filter(g=>g!==null);return oc(xa.GENERATE_CONTOUR_SETS,100),h}class RF{constructor(){}static getContourSequence(e,r){const{data:n}=e,{projectionPoints:i,projectionPointsImageIds:o}=n.cachedStats;return i.map((a,s)=>{const c=tme(a),l=nme(o[s],r);return{NumberOfContourPoints:c.length/3,ContourImageSequence:l,ContourGeometricType:"CLOSED_PLANAR",ContourData:c}})}}RF.toolName="RectangleROIStartEndThreshold";function tme(t){return[...t[0],...t[1],...t[3],...t[2]].flat().map(i=>i.toFixed(2))}function nme(t,e){const r=e.get("sopCommonModule",t);return{ReferencedSOPClassUID:r.sopClassUID,ReferencedSOPInstanceUID:r.sopInstanceUID}}function rme(t){if(!(t!=null&&t.data))throw new Error("Tool data is empty");if(!t.metadata||t.metadata.referencedImageId)throw new Error("Tool data is not associated with any imageId")}const Qg=class Qg{constructor(){}static convert(e,r,n){rme(e);const{toolName:i}=e.metadata,o=Qg.TOOL_NAMES[i];if(!o)throw new Error(`Unknown tool type: ${i}, cannot convert to RTSSReport`);const a=o.getContourSequence(e,n),s=[Math.floor(Math.random()*255),Math.floor(Math.random()*255),Math.floor(Math.random()*255)];return{ReferencedROINumber:r+1,ROIDisplayColor:s,ContourSequence:a}}static register(e){Qg.TOOL_NAMES[e.toolName]=e}};Qg.TOOL_NAMES={};let cy=Qg;cy.register(RF);function ime(t,e){Ys.acceptAutoGenerated(t,e)}const{isEqual:ome}=Mn;function IC(t,e){const{polyline:r}=t.data.contour,{points:n}=t.data.handles,{length:i}=n;if(e===i)return r.length;if(e<0&&(e=(e+i)%i),e===0)return 0;const o=n[e],a=r.findIndex(c=>ome(o,c));if(a!==-1)return a;let s=1/0;return r.reduce((c,l,f)=>{const u=MM(l,o);return u{const S=({value:M})=>{h=h+1,M>=g.lower&&M<=g.upper&&(d=d+1)},{imageData:_,dimensions:T,lower:E,upper:D}=w,b=ZT(_,T,x,C);h=0,d=0,g={lower:E,upper:D};let I=!1;const{voxelManager:P}=_.get("voxelManager");return P.forEach(S,{imageData:_,boundsIJK:b}),s===0?I=d>0:s==1&&(I=d===h),I},v=(w,x)=>{const{imageData:C,lower:S,upper:_}=w,T=C.get("voxelManager").voxelManager,E=T.toIndex(x),D=T.getAtIndex(E);return!(D<=S||D>=_)},y=({index:w,pointIJK:x,pointLPS:C})=>{let S=u.length>0;for(let _=0;_{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...s],[...s],[...s],[...s]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}}});nn(f,a);const u=_t(a,this.getToolName());return this.editData={annotation:f,viewportIdsToRender:u,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(u),f},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=c.worldToCanvas(f[0]),d=c.worldToCanvas(f[3]),h=this._getRectangleImageCoordinates([u,d]),g=[o[0],o[1]],{left:p,top:v,width:y,height:m}=h;return y4([p,v,y,m],g)<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;o.worldPosition?l=!0:f=c.handles.points.findIndex(g=>g===o);const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Ot(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.doneEditMemo(),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a))},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world,{points:g}=u.handles;g.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=Ce(o),{worldToCanvas:g,canvasToWorld:p}=h.viewport,v=d.world,{points:y}=u.handles;y[c]=[...v];let m,w,x,C,S,_,T,E;switch(c){case 0:case 3:m=g(y[0]),C=g(y[3]),w=[C[0],m[1]],x=[m[0],C[1]],_=p(w),T=p(x),y[1]=_,y[2]=T;break;case 1:case 2:w=g(y[1]),x=g(y[2]),m=[x[0],w[1]],C=[w[0],x[1]],S=p(m),E=p(C),y[0]=S,y[3]=E;break}a.invalidated=!0}this.editData.hasMoved=!0,Ce(o),Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(F));u.annotationUID=g;const{color:w,lineWidth:x,lineDash:C}=this.getAnnotationStyle({annotation:h,styleSpecifier:u}),{viewPlaneNormal:S,viewUp:_}=a.getCamera();if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null},this._calculateCachedStats(h,S,_,f,n);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,S,_,f,n),a instanceof ur)){const{referencedImageId:F}=h.metadata;for(const j in p.cachedStats)j.startsWith("imageId")&&f.getStackViewports().find(ue=>{const ce=Vr(F),pe=ue.hasImageURI(ce),Ee=Vr(ue.getCurrentImageId());return pe&&Ee!==ce})&&delete p.cachedStats[j]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let T;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(T=[m[y]]),T&&ir(i,g,"0",T,{color:w});const E=`${g}-rect`;x4(i,g,"0",m,{color:w,lineDash:C,lineWidth:x},E),o=!0;const b=this.getLinkedTextBoxStyle(u,h);if(!b.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const I=this.configuration.getTextLines(p,l);if(!I||I.length===0)continue;if(!p.handles.textBox.hasMoved){const F=na(m);p.handles.textBox.worldPosition=a.canvasToWorld(F)}const P=a.worldToCanvas(p.handles.textBox.worldPosition),L=qi(i,g,"1",I,P,m,{},b),{x:V,y:G,width:A,height:k}=L;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([V,G]),topRight:a.canvasToWorld([V+A,G]),bottomLeft:a.canvasToWorld([V,G+k]),bottomRight:a.canvasToWorld([V+A,G+k])}}return o},this._getRectangleImageCoordinates=n=>{const[i,o]=n;return{left:Math.min(i[0],o[0]),top:Math.min(i[1],o[1]),width:Math.abs(i[0]-o[0]),height:Math.abs(i[1]-o[1])}},this._calculateCachedStats=(n,i,o,a,s)=>{var v,y,m,w;if(!this.configuration.calculateStats)return;const{data:c}=n,{viewport:l}=s,{element:f}=l,u=c.handles.points[0],d=c.handles.points[3],{cachedStats:h}=c,g=Object.keys(h);for(let x=0;xsr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}};e0.toolName="RectangleROI",e0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=e0.hydrateBase(e0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let tl=e0;function sme(t,e){const r=t.cachedStats[e],{area:n,mean:i,max:o,stdDev:a,areaUnit:s,modalityUnit:c,min:l}=r;if(i==null)return;const f=[];return Ar(n)&&f.push(`Area: ${an(n)} ${s}`),Ar(i)&&f.push(`Mean: ${an(i)} ${c}`),Ar(o)&&f.push(`Max: ${an(o)} ${c}`),Ar(l)&&f.push(`Max: ${an(l)} ${c}`),Ar(a)&&f.push(`Std Dev: ${an(a)} ${c}`),f}const{transformWorldToIndex:Jh}=Mn;class W4 extends tl{constructor(e={},r={configuration:{storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:cme,statsCalculator:rc,showTextBox:!1,throttleTimeout:100}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u;let g,p,v;if(l instanceof lr)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);v=sc(_),p=Le.getVolume(v),g=qc(p,s,d)}const y=Au(p,d),m=this._getStartCoordinate(s,d),w=this._getEndCoordinate(s,y,d),x=l.getFrameOfReferenceUID(),C={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...d],enabledElement:c,viewUp:[...h],FrameOfReferenceUID:x,referencedImageId:g,toolName:this.getToolName(),volumeId:v,spacingInNormal:y},data:{label:"",startCoordinate:m,endCoordinate:w,cachedStats:{pointsInVolume:[],projectionPoints:[],projectionPointsImageIds:[g],statistics:[]},handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},labelmapUID:null}};this._computeProjectionPoints(C,p),nn(C,a);const S=_t(a,this.getToolName());return this.editData={annotation:C,viewportIdsToRender:S,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),C},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const d=this.getTargetId(u.viewport),h=Le.getVolume(d.split(/volumeId:|\?/)[1]);this._computePointsInsideVolume(a,d,h,u),Pe(s),c?Nn(a):tn(a,o)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;let s=un(this.getToolName(),a.element);if(!(s!=null&&s.length))return o;s=L5(s,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let l=0;la.worldToCanvas(A));c.annotationUID=u;const w=this.getStyle("lineWidth",c,f),x=this.getStyle("lineDash",c,f),C=this.getStyle("color",c,f),S=a.getCamera().focalPoint,_=a.getCamera().viewPlaneNormal;let T=g,E=p;if(Array.isArray(g)){T=this._getCoordinateForViewplaneNormal(T,_);const A=this._getIndexOfCoordinatesForViewplaneNormal(_);d.handles.points.forEach(k=>{k[A]=T}),d.startCoordinate=T}Array.isArray(p)&&(E=this._getCoordinateForViewplaneNormal(E,_),d.endCoordinate=E,d.endCoordinate=E);const D=eu(T),b=eu(E),I=this._getCoordinateForViewplaneNormal(S,_),P=eu(I);if(PMath.max(D,b))continue;f.invalidated&&this._throttledCalculateCachedStats(f,n);let M=!1;if((P===D||P===b)&&(M=!0),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let L;if(!Gr(u))continue;!Zr(u)&&!this.editData&&y!==null&&M&&(L=[m[y]]),L&&ir(i,u,"0",L,{color:C});let V=x;if(M||(V=2),P1(i,u,"0",m[0],m[3],{color:C,lineDash:V,lineWidth:w}),o=!0,this.configuration.showTextBox){const A=this.getLinkedTextBoxStyle(c,f);if(!A.visibility){d.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const k=this.configuration.getTextLines(d,{metadata:h});if(!k||k.length===0)continue;if(!d.handles.textBox.hasMoved){const Ee=na(m);d.handles.textBox.worldPosition=a.canvasToWorld(Ee)}const F=a.worldToCanvas(d.handles.textBox.worldPosition),Y=qi(i,u,"1",k,F,m,{},A),{x:re,y:ue,width:ce,height:pe}=Y;d.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([re,ue]),topRight:a.canvasToWorld([re+ce,ue]),bottomLeft:a.canvasToWorld([re,ue+pe]),bottomRight:a.canvasToWorld([re+ce,ue+pe])}}}return o},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=_o(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=gh(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(e,r){const{data:n,metadata:i}=e,{viewPlaneNormal:o,spacingInNormal:a}=i,{imageData:s}=r,{startCoordinate:c,endCoordinate:l}=n,{points:f}=n.handles,u=Jh(s,f[0]),d=Jh(s,f[0]),h=Ve();s.indexToWorldVec3(u,h);const g=Ve();s.indexToWorldVec3(d,g),this._getIndexOfCoordinatesForViewplaneNormal(o)==2?(h[2]=c,g[2]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==0?(h[0]=c,g[0]=l):this._getIndexOfCoordinatesForViewplaneNormal(o)==1&&(h[1]=c,g[1]=l);const p=ki(h,g),v=[];for(let y=0;y{const w=Ve();return Tn(w,m,o,y),Array.from(w)}));n.cachedStats.projectionPoints=v}_computePointsInsideVolume(e,r,n,i){var S,_,T;const{data:o,metadata:a}=e,{viewPlaneNormal:s,viewUp:c}=a,{viewport:l}=i,f=o.cachedStats.projectionPoints,u=[[]],d=this.getTargetImageData(r),h=o.handles.points[0],g=o.handles.points[3],{worldWidth:p,worldHeight:v}=R5(s,c,h,g),y=ta(d,o.habdles),m=Math.abs(p*v)/(y.scale*y.scale),w={isPreScaled:al(l,r),isSuvScaled:this.isSuvScaled(l,r,e.metadata.referencedImageId)},x=sl(a.Modality,e.metadata.referencedImageId,w);for(let E=0;E{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getTargetId(l);let p,v;if(l instanceof lr)p=g.split("imageId:")[1];else{v=sc(g);const x=Le.getVolume(v);p=qc(x,s,d)}const y=l.getFrameOfReferenceUID(),m={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...d],enabledElement:c,viewUp:[...h],FrameOfReferenceUID:y,referencedImageId:p,toolName:this.getToolName(),volumeId:v},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:null,worldBoundingBox:null},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},segmentationId:null}};nn(m,a);const w=_t(a,this.getToolName());return this.editData={annotation:m,viewportIdsToRender:w,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(w),m},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(S));l.annotationUID=d;const y=this.getStyle("lineWidth",l,u),m=this.getStyle("lineDash",l,u),w=this.getStyle("color",l,u);if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;tn(u,s);let x;if(!Gr(d))continue;!Zr(d)&&!this.editData&&p!==null&&(x=[v[p]]),x&&ir(i,d,"0",x,{color:w}),P1(i,d,"0",v[0],v[3],{color:w,lineDash:m,lineWidth:y}),o=!0}return o}}}z4.toolName="RectangleROIThreshold";function AF(t,e,r={}){const n=[];return t.forEach(o=>{var h,g;const{data:a}=o,{points:s}=a.handles,{imageData:c,dimensions:l}=e;let f=s;if((h=a.cachedStats)!=null&&h.projectionPoints){const{projectionPoints:p}=a.cachedStats;f=[].concat(...p)}const u=f.map(p=>Ur(c,p));let d=Su(u,l);r.numSlicesToProject&&!((g=a.cachedStats)!=null&&g.projectionPoints)&&(d=lF(d,r.numSlicesToProject)),n.push(d)}),n.length===1?n[0]:n.reduce((o,a)=>({iMin:Math.min(o.iMin,a.iMin),jMin:Math.min(o.jMin,a.jMin),kMin:Math.min(o.kMin,a.kMin),iMax:Math.max(o.iMax,a.iMax),jMax:Math.max(o.jMax,a.jMax),kMax:Math.max(o.kMax,a.kMax)}),{iMin:1/0,jMin:1/0,kMin:1/0,iMax:-1/0,jMax:-1/0,kMax:-1/0})}function lme(t,e,r,n){const i=t.map(s=>Rr.getAnnotation(s));ume(i);let o;for(let s=0;s{if(!$t(f,t[0].dimensions)||!$t(l,t[0].direction)||!$t(d,t[0].spacing)||!$t(u,t[0].origin))throw new Error("labelmaps must have the same size and shape")});const n=t[0],i=n.voxelManager.getConstructor(),o=new i(n.voxelManager.getScalarDataLength());t.forEach(l=>{const f=l.voxelManager,u=f.getScalarDataLength();for(let d=0;d0;)g(f.pop());return{flooded:u};function g(T){const E=T.currentArgs,D=T.previousArgs;p(E)||(v(E),y(E)?(m(E),x(E)):w(D))}function p(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));return d.has(I)}function v(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));d.add(I)}function y(T){const E=C(T);return o?o(E,c):E===c}function m(T){u.push(T),n&&n(...T)}function w(T){const[E,D,b=0]=T,I=E+32768+65536*(D+32768+65536*(b+32768));h==null||h.set(I,T),i&&i(...T)}function x(T){for(let E=0;E{const{segmentIndex:e,previewSegmentIndex:r,segmentationVoxelManager:n,centerIJK:i,viewPlaneNormal:o,segmentationImageData:a,configuration:s}=t;if(!(s!=null&&s.useCenterSegmentIndex))return;let c=!1,l=!1;const f=[...n.getBoundsIJK()];Math.abs(o[0])>.8?f[0]=[i[0],i[0]]:Math.abs(o[1])>.8?f[1]=[i[1],i[1]]:Math.abs(o[2])>.8&&(f[2]=[i[2],i[2]]);const u=({value:h})=>{c||(c=h===e),l||(l=h===r)};if(n.forEach(u,{imageData:a,isInObject:t.isInObject,boundsIJK:f}),!c&&!l){t.centerSegmentIndexInfo.segmentIndex=null;return}const d=n.getAtIJKPoint(i);t.centerSegmentIndexInfo.segmentIndex=d,t.centerSegmentIndexInfo.hasSegmentIndex=c,t.centerSegmentIndexInfo.hasPreviewIndex=l}},pme={[St.Initialize]:t=>{var y;const{operationName:e,centerIJK:r,segmentationVoxelManager:n,imageVoxelManager:i,configuration:o,segmentIndex:a,viewport:s}=t;if(!((y=o==null?void 0:o.threshold)!=null&&y.isDynamic)||!r||!a||e===St.RejectPreview||e===St.OnInteractionEnd)return;const c=n.getBoundsIJK(),{range:l,dynamicRadius:f=0}=o.threshold,u=l?0:f,{viewPlaneNormal:d}=s.getCamera(),h=c.map((m,w)=>{const[x,C]=m;return[Math.max(x,r[w]-u),Math.min(C,r[w]+u)]});Math.abs(d[0])>.8?h[0]=[r[0],r[0]]:Math.abs(d[1])>.8?h[1]=[r[1],r[1]]:Math.abs(d[2])>.8&&(h[2]=[r[2],r[2]]);const g=l||[1/0,-1/0],p=u*u,v=({value:m,pointIJK:w})=>{if(Gx(r,w)>p)return;const C=Array.isArray(m)?N0(m):m;g[0]=Math.min(C,g[0]),g[1]=Math.max(C,g[1])};i.forEach(v,{boundsIJK:h}),o.threshold.range=g},[St.OnInteractionStart]:t=>{var r;const{configuration:e}=t;(r=e==null?void 0:e.threshold)!=null&&r.isDynamic&&(e.threshold.range=null)},[St.ComputeInnerCircleRadius]:t=>{const{configuration:e,viewport:r}=t,{dynamicRadius:n=0,isDynamic:i}=e.threshold;if(!i){e.threshold.dynamicRadiusInCanvas=0;return}if(n===0)return;const o=r.getImageData();if(!o)return;const{spacing:a}=o,s=[r.element.clientWidth/2,r.element.clientHeight/2],c=n*a[0],f=r.canvasToWorld(s).map(h=>h+c),u=r.worldToCanvas(f),d=Math.abs(s[0]-u[0]);e.threshold.dynamicRadiusInCanvas||(e.threshold.dynamicRadiusInCanvas=0),e.threshold.dynamicRadiusInCanvas=3+d}},mme={[St.Initialize]:t=>{t.segmentIndex=0}},{isEqual:l3}=Mn,$D={toIJK:t=>t,fromIJK:t=>t,type:"acquistion"},vme={toIJK:([t,e,r])=>[r,t,e],fromIJK:([t,e,r])=>[e,r,t],type:"jk"},yme={toIJK:([t,e,r])=>[t,r,e],fromIJK:([t,e,r])=>[t,r,e],type:"ik"};function kF(t,e){if(!(t instanceof Ir))return{...$D,boundsIJKPrime:e};const{viewPlaneNormal:r}=t.getCamera(),n=l3(Math.abs(r[0]),1)&&vme||l3(Math.abs(r[1]),1)&&yme||l3(Math.abs(r[2]),1)&&$D;return n?{...n,boundsIJKPrime:n.fromIJK(e)}:{toIJK:null,boundsIJKPrime:null,fromIJK:null,error:`Only mappings orthogonal to acquisition plane are permitted, but requested ${r}`}}const{RLEVoxelMap:wme,VoxelManager:xme}=Mn,Cme=65535;var Zi;(function(t){t[t.SEGMENT=-1]="SEGMENT",t[t.ISLAND=-2]="ISLAND",t[t.INTERIOR=-3]="INTERIOR",t[t.EXTERIOR=-4]="EXTERIOR",t[t.INTERIOR_SMALL=-5]="INTERIOR_SMALL",t[t.INTERIOR_TEST=-6]="INTERIOR_TEST"})(Zi||(Zi={}));class nd{constructor(e){this.fillInternalEdge=!1,this.maxInternalRemove=128,this.maxInternalRemove=(e==null?void 0:e.maxInternalRemove)??this.maxInternalRemove,this.fillInternalEdge=(e==null?void 0:e.fillInternalEdge)??this.fillInternalEdge}initialize(e,r,n){const i=!!r.sourceVoxelManager,o=i?r.sourceVoxelManager:r,a=i?r:xme.createRLEHistoryVoxelManager(o),{segmentIndex:s=1,previewSegmentIndex:c=1}=n,l=n.points||o.getPoints();if(!(l!=null&&l.length))return;const f=o.getBoundsIJK().map((x,C)=>[Math.min(x[0],...l.map(S=>S[C])),Math.max(x[1],...l.map(S=>S[C]))]);if(f.find(x=>x[0]<0||x[1]>Cme))return;const{toIJK:u,fromIJK:d,boundsIJKPrime:h,error:g}=kF(e,f);if(g){console.warn("Not performing island removal for planes not orthogonal to acquisition plane",g);return}const[p,v,y]=d(o.dimensions),m=new wme(p,v,y),w=(x,C,S)=>{const _=o.toIndex(u([x,C,S])),T=o.getAtIndex(_);if(T===c||T===s)return Zi.SEGMENT};return m.fillFrom(w,h),m.normalizer={toIJK:u,fromIJK:d,boundsIJKPrime:h},this.segmentSet=m,this.previewVoxelManager=a,this.segmentIndex=s,this.previewSegmentIndex=c??s,this.selectedPoints=l,!0}floodFillSegmentIsland(){const{selectedPoints:e,segmentSet:r}=this;let n=0;const{fromIJK:i}=r.normalizer;return e.forEach(o=>{const a=i(o),s=r.toIndex(a),[c,l,f]=a;r.get(s)===Zi.SEGMENT&&(n+=r.floodFill(c,l,f,Zi.ISLAND))}),n}removeExternalIslands(){const{previewVoxelManager:e,segmentSet:r}=this,{toIJK:n}=r.normalizer,i=(o,a)=>{const[,s,c]=r.toIJK(o);if(a.value!==Zi.ISLAND)for(let l=a.start;l{let f;for(const u of[...l])if(u.value===Zi.ISLAND){if(!f){if(this.fillInternalEdge&&u.start>0)for(let d=0;d{if(l.value!==Zi.INTERIOR)return;const[,f,u]=e.toIJK(c),d=f>0?e.getRun(f-1,u):null,h=f+12&&(!v||!y)&&e.floodFill(l.start,f,u,Zi.EXTERIOR,{singlePlane:!0})}),e.forEach((c,l)=>{if(l.value!==Zi.INTERIOR)return;const[,f,u]=e.toIJK(c),g=e.floodFill(l.start,f,u,Zi.INTERIOR_TEST)>this.maxInternalRemove?Zi.EXTERIOR:Zi.INTERIOR_SMALL;e.floodFill(l.start,f,u,g)}),e.forEach((c,l)=>{if(l.value===Zi.INTERIOR_SMALL)for(let f=l.start;f=o.start&&n=i))return!0;return!1}}const Sme={[St.OnInteractionEnd]:t=>{const{previewSegmentIndex:e,segmentIndex:r,viewport:n,segmentationVoxelManager:i,activeStrategy:o,memo:a}=t;if(o!=="THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL"||r===null)return;const s=new nd,c=(a==null?void 0:a.voxelManager)||i;if(!s.initialize(n,c,{previewSegmentIndex:e,segmentIndex:r}))return;s.floodFillSegmentIsland(),s.removeExternalIslands(),s.removeInternalIslands();const l=c.getArrayOfModifiedSlices();l&&io(t.segmentationId,l,e)}},_me={[St.Preview]:function(t){var o,a;const{previewSegmentIndex:e,configuration:r,enabledElement:n}=t;if(!e||!r)return;(o=this.onInteractionStart)==null||o.call(this,n,t);const i=this.fill(n,t);return i&&((a=this.onInteractionEnd)==null||a.call(this,n,t)),i},[St.Initialize]:t=>{const{segmentIndex:e,previewColor:r,previewSegmentIndex:n}=t;if(n==null||e==null)return;const i=yh(t.segmentationId);i==null||i.forEach(o=>{pV(o,t.segmentationId,n,r)})},[St.AcceptPreview]:t=>{const{previewSegmentIndex:e,segmentationVoxelManager:r,memo:n,segmentIndex:i,centerSegmentIndexInfo:o}=t||{},{changedIndices:a}=o||{},s=n,c=({index:l})=>{const f=r.getAtIndex(l);(a==null?void 0:a.length)>0?a.includes(l)&&s.voxelManager.setAtIndex(l,0):f===e&&s.voxelManager.setAtIndex(l,i)};r.forEach(c),io(t.segmentationId,r.getArrayOfModifiedSlices(),i),t.centerSegmentIndexInfo.changedIndices=[]},[St.RejectPreview]:t=>{t&&$A.undoIf(e=>{const r=e;if(!(r!=null&&r.voxelManager))return!1;const{segmentationVoxelManager:n}=r;let i=!1;const o=({value:a})=>{a===t.previewSegmentIndex&&(i=!0)};return n.forEach(o),i})}},Tme={[St.Fill]:t=>{var l;const{segmentsLocked:e,segmentationImageData:r,segmentationVoxelManager:n,brushStrategy:i,centerIJK:o}=t,a=(l=i.createIsInThreshold)==null?void 0:l.call(i,t),{setValue:s}=i,c=a?f=>{const{value:u,index:d}=f;e.includes(u)||!a(d)||s(t,f)}:f=>s(t,f);n.forEach(c,{imageData:r,isInObject:t.isInObject,boundsIJK:t.isInObjectBoundsIJK}),n.addPoint(o)}};function Eme({operationData:t,existingValue:e,index:r}){const{previewSegmentIndex:n,memo:i,centerSegmentIndexInfo:o,previewOnHover:a,segmentIndex:s}=t,{hasPreviewIndex:c,hasSegmentIndex:l,segmentIndex:f}=o;if(f===0&&l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&l&&!c){if(e===0||e!==s)return;i.voxelManager.setAtIndex(r,n),o.changedIndices.push(r);return}if(f===0&&!l&&c){if(e===s||a)return;if(e===n){i.voxelManager.setAtIndex(r,0);return}return}if(f===0&&!l&&!c){if(e===s)return;if(e===n){i.voxelManager.setAtIndex(r,n);return}return}if(f===n&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===n&&!l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}if(f===s&&l&&!c){if(e===s)return;i.voxelManager.setAtIndex(r,n);return}}const Dme={[St.INTERNAL_setValue]:(t,{value:e,index:r})=>{const{segmentsLocked:n,previewSegmentIndex:i,memo:o,segmentationVoxelManager:a,centerSegmentIndexInfo:s,segmentIndex:c}=t,l=a.getAtIndex(r);if(!n.includes(e)&&!(!s&&l===c)&&!((s==null?void 0:s.segmentIndex)!==0&&l===c)){if((s==null?void 0:s.segmentIndex)===null){o.voxelManager.setAtIndex(r,i??c);return}if(!i){let f=c;s&&(f=s.segmentIndex),o.voxelManager.setAtIndex(r,f);return}Eme({operationData:t,existingValue:l,index:r})}}},bme={[St.CreateIsInThreshold]:t=>{const{imageVoxelManager:e,segmentIndex:r,configuration:n}=t;if(!(!n||!r))return i=>{var c;const o=e.getAtIndex(i),a=Array.isArray(o)?Po(o):o,{threshold:s}=n||{};return(c=s==null?void 0:s.range)!=null&&c.length?s.range[0]<=a&&a<=s.range[1]:!0}}},jD=10;function ly(){return{maxIJKs:[]}}function VF(t,e){const{value:r}=e,{maxIJKs:n}=t,i=n.length;if(typeof r!="number"||i>=jD&&r=n[i-1].value)n.push(o);else for(let a=0;a=jD&&n.splice(0,1)}function FF(t,e,r){const{spacing:n,calibration:i}=r,{volumeUnit:o}=ta({calibration:i,hasPixelSpacing:!0},[]),a=n?n[0]*n[1]*n[2]:1;return e.volume={value:Array.isArray(e.count.value)?e.count.value.map(s=>s*a):e.count.value*a,unit:o,name:"volume",label:"Volume"},e.maxIJKs=t.maxIJKs.filter(s=>s.pointIJK!==void 0),e.array.push(e.volume),t.maxIJKs=[],e}const SE=class SE extends rc{static statsInit(e){super.statsInit(e),this.volumetricState=ly()}static statsCallback(e){super.statsCallback(e),VF(this.volumetricState,e)}static getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return FF(this.volumetricState,n,r)}};SE.volumetricState=ly();let Uf=SE;class HD extends Pk{constructor(e){super(e),this.volumetricState=ly()}statsInit(e){super.statsInit(e),this.volumetricState=ly()}statsCallback(e){super.statsCallback(e),VF(this.volumetricState,e)}getStatistics(e){const r={...e,unit:(e==null?void 0:e.unit)||"none",calibration:e==null?void 0:e.calibration,hasPixelSpacing:e==null?void 0:e.hasPixelSpacing},n=super.getStatistics(r);return FF(this.volumetricState,n,r)}}const Ime=Math.pow(3*1e3/(4*Math.PI),1/3);async function UF({segmentationId:t,segmentIndices:e,mode:r="collective"}){F5(),oc(xa.COMPUTE_STATISTICS,0);const n=IF(t,e);if(!n)return;const{operationData:i,segVolumeId:o,segImageIds:a,reconstructableVolume:s,indices:c}=n,{refImageId:l,modalityUnitOptions:f}=Q1e(o,a),u=yV(l,f);return s?await Ome({operationData:i,indices:c,unit:u,mode:r}):await Mme({segImageIds:a,indices:c,unit:u,mode:r})}async function Ome({operationData:t,indices:e,unit:r,mode:n}){var p;const i=OF(t),{segmentationVoxelManager:o,imageVoxelManager:a,segmentationImageData:s,imageData:c}=i;if(!o||!s)return;const l=s.getSpacing(),{boundsIJK:f}=o;if(!f)return Uf.getStatistics({spacing:l});const d={scalarData:o.getCompleteScalarDataArray(),dimensions:s.getDimensions(),spacing:s.getSpacing(),origin:s.getOrigin(),direction:s.getDirection()},h={scalarData:a.getCompleteScalarDataArray(),dimensions:c.getDimensions(),spacing:c.getSpacing(),origin:c.getOrigin(),direction:c.getDirection()};if(!((p=h.scalarData)!=null&&p.length))return;const g=await il().executeTask("compute","calculateSegmentsStatisticsVolume",{segmentationInfo:d,imageInfo:h,indices:e,unit:r,mode:n});if(oc(xa.COMPUTE_STATISTICS,100),n==="collective")return uy({stats:g,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a});{const v={};return Object.entries(g).forEach(([y,m])=>{v[y]=uy({stats:m,unit:r,spacing:l,segmentationImageData:s,imageVoxelManager:a})}),v}}const u3=(t,e)=>{if(!t.array)return;const r=t.array.findIndex(n=>n.name===e.name);r!==-1?t.array[r]=e:t.array.push(e)},uy=({stats:t,unit:e,spacing:r,segmentationImageData:n,imageVoxelManager:i})=>{if(t.mean.unit=e,t.max.unit=e,t.min.unit=e,e!=="SUV")return t;const o=r.map(a=>Math.max(1,Math.round(1.1*Ime/a)));for(const a of t.maxIJKs){const s=Pme(a,o,n,i,r);if(!s)continue;const{mean:c}=s;(!t.peakValue||t.peakValue.value<=c.value)&&(t.peakValue={name:"peakValue",label:"Peak Value",value:c.value,unit:e},t.peakPoint={name:"peakLPS",label:"Peak SUV Point",value:a.pointLPS?[...a.pointLPS]:null,unit:null},u3(t,t.peakValue),u3(t,t.peakPoint))}if(t.volume&&t.mean){const a=t.volume.value,s=t.mean.value;t.lesionGlycolysis={name:"lesionGlycolysis",label:"Lesion Glycolysis",value:a*s,unit:`${t.volume.unit}·${e}`},u3(t,t.lesionGlycolysis)}return t};async function Mme({segImageIds:t,indices:e,unit:r,mode:n}){oc(xa.COMPUTE_STATISTICS,0);const{segmentationInfo:i,imageInfo:o}=MF(t),a=await il().executeTask("compute","calculateSegmentsStatisticsStack",{segmentationInfo:i,imageInfo:o,indices:e,mode:n});oc(xa.COMPUTE_STATISTICS,100);const s=i[0].spacing,c=i[0],l=o[0].voxelManager;if(n==="collective")return uy({stats:a,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l});{const f={};return Object.entries(a).forEach(([u,d])=>{f[u]=uy({stats:d,unit:r,spacing:s,segmentationImageData:c,imageVoxelManager:l})}),f}}function Pme(t,e,r,n,i){const{pointIJK:o,pointLPS:a}=t;if(!o)return;const s=o.map((f,u)=>[f-e[u],f+e[u]]),c=(f,u)=>{const d=(u[0]-o[0])/e[0],h=(u[1]-o[1])/e[1],g=(u[2]-o[2])/e[2];return d*d+h*h+g*g<=1},l=({pointIJK:f,pointLPS:u})=>{const d=n.getAtIJKPoint(f);d!==void 0&&Uf.statsCallback({value:d,pointLPS:u,pointIJK:f})};return Uf.statsInit({storePointData:!1}),ST(r,{pointInShapeFn:c,callback:l,boundsIJK:s}),Uf.getStatistics({spacing:i})}const Rme={[St.GetStatistics]:function(t,e,r){const{indices:n}=r,{segmentationId:i,viewport:o}=e;UF({segmentationId:i,segmentIndices:n})}},mn={determineSegmentIndex:gme,dynamicThreshold:pme,erase:mme,islandRemoval:Sme,preview:_me,regionFill:Tme,setValue:Dme,threshold:bme,labelmapStatistics:Rme,ensureSegmentationVolumeFor3DManipulation:DF,ensureImageVolumeFor3DManipulation:bF},Df=class Df{constructor(e,...r){this._initialize=[],this._fill=[],this._onInteractionStart=[],this.fill=(n,i)=>{const o=this.initialize(n,i,St.Fill);if(!o)return;this._fill.forEach(c=>c(o));const{segmentationVoxelManager:a,segmentIndex:s}=o;return io(o.segmentationId,a.getArrayOfModifiedSlices(),s),o},this.onInteractionStart=(n,i)=>{const o=this.initialize(n,i);o&&this._onInteractionStart.forEach(a=>a.call(this,o))},this.addPreview=(n,i)=>{const o=this.initialize(n,i,St.AddPreview);if(o)return o},this.configurationName=e,this.compositions=r,r.forEach(n=>{const i=typeof n=="function"?n():n;if(i)for(const o in i){if(!Df.childFunctions[o])throw new Error(`Didn't find ${o} as a brush strategy`);Df.childFunctions[o](this,i[o])}}),this.strategyFunction=(n,i)=>this.fill(n,i);for(const n of Object.keys(Df.childFunctions))this.strategyFunction[n]=this[n]}initialize(e,r,n){const{viewport:i}=e,o=G4({operationData:r,viewport:i,strategy:this});if(!o)return null;const{imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c}=o,l=r.createMemo(r.segmentationId,s),f={operationName:n,...r,segmentIndex:r.segmentIndex,enabledElement:e,imageVoxelManager:a,segmentationVoxelManager:s,segmentationImageData:c,viewport:i,centerWorld:null,isInObject:null,isInObjectBoundsIJK:null,brushStrategy:this,memo:l};return this._initialize.forEach(u=>u(f)),f}};Df.COMPOSITIONS=mn,Df.childFunctions={[St.OnInteractionStart]:ts(St.OnInteractionStart,St.Initialize),[St.OnInteractionEnd]:ts(St.OnInteractionEnd,St.Initialize),[St.Fill]:ts(St.Fill),[St.Initialize]:ts(St.Initialize),[St.CreateIsInThreshold]:Fm(St.CreateIsInThreshold),[St.Interpolate]:ts(St.Interpolate,St.Initialize),[St.AcceptPreview]:ts(St.AcceptPreview,St.Initialize),[St.RejectPreview]:ts(St.RejectPreview,St.Initialize),[St.INTERNAL_setValue]:Fm(St.INTERNAL_setValue),[St.Preview]:Fm(St.Preview,!1),[St.ComputeInnerCircleRadius]:ts(St.ComputeInnerCircleRadius),[St.EnsureSegmentationVolumeFor3DManipulation]:ts(St.EnsureSegmentationVolumeFor3DManipulation),[St.EnsureImageVolumeFor3DManipulation]:ts(St.EnsureImageVolumeFor3DManipulation),[St.AddPreview]:ts(St.AddPreview),[St.GetStatistics]:Fm(St.GetStatistics),compositions:null};let Ss=Df;function ts(t,e){const r=`_${t}`;return(n,i)=>{n[r]||(n[r]=[]),n[r].push(i),n[t]||(n[t]=e?(o,a,...s)=>{const c=n[e](o,a,t);let l;return n[r].forEach(f=>{const u=f.call(n,c,...s);l||(l=u)}),l}:(o,...a)=>{n[r].forEach(s=>s.call(n,o,...a))})}}function Fm(t,e=!0){return(r,n)=>{if(r[t])throw new Error(`The singleton method ${t} already exists`);r[t]=e?n:(i,o,...a)=>(o.enabledElement=i,n.call(r,o,...a))}}function BF(t,e){const{center:r,radius:n}=t,i=t.radius2||n*n;return(e[0]-r[0])*(e[0]-r[0])+(e[1]-r[1])*(e[1]-r[1])+(e[2]-r[2])*(e[2]-r[2])<=i}const{transformWorldToIndex:KD,isEqual:f3}=Mn,GF={[St.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=bt(0,0,0);e.forEach(d=>{Ai(i,i,d)}),Ni(i,i,1/e.length),t.centerWorld=i,t.centerIJK=KD(n,i);const o=e.map(d=>r.worldToCanvas(d)),[a,s]=Yv(o),c=r.canvasToWorld(a),l=r.canvasToWorld(s),f=e.map(d=>KD(n,d)),u=Su(f,n.getDimensions());t.isInObject=WF({topLeftWorld:c,bottomRightWorld:l,center:i}),t.isInObjectBoundsIJK=u}};function WF(t){const{topLeftWorld:e,bottomRightWorld:r,center:n}=t,i=Math.abs(e[0]-r[0])/2,o=Math.abs(e[1]-r[1])/2,a=Math.abs(e[2]-r[2])/2,s=Math.max(i,o,a);if(f3(i,s)&&f3(o,s)&&f3(a,s)){const f={center:n,radius:s,radius2:s*s};return u=>BF(f,u)}const c={center:n,xRadius:i,yRadius:o,zRadius:a},{precalculated:l}=f4(c,{});return l}const zF=new Ss("Circle",mn.regionFill,mn.setValue,GF,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics),Lme=new Ss("CircleThreshold",mn.regionFill,mn.setValue,GF,mn.determineSegmentIndex,mn.dynamicThreshold,mn.threshold,mn.preview,mn.islandRemoval,mn.labelmapStatistics),G5=zF.strategyFunction,Ame=Lme.strategyFunction;function Nme(){throw new Error("Not yet implemented")}const{transformWorldToIndex:kme}=Mn,Vme={[St.Initialize]:t=>{const{points:e,viewport:r,segmentationImageData:n}=t;if(!e)return;const i=bt(0,0,0);e.forEach(c=>{Ai(i,i,c)}),Ni(i,i,1/e.length),t.centerWorld=i,t.centerIJK=kme(n,i);const{boundsIJK:o,topLeftWorld:a,bottomRightWorld:s}=b1e(e.slice(0,2),n,r);t.isInObjectBoundsIJK=o,t.isInObject=WF({topLeftWorld:a,bottomRightWorld:s,center:i})}},W5=new Ss("Sphere",mn.regionFill,mn.setValue,Vme,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics,mn.ensureSegmentationVolumeFor3DManipulation),$F=W5.strategyFunction,Fme=new Ss("SphereThreshold",...W5.compositions,mn.dynamicThreshold,mn.threshold,mn.ensureSegmentationVolumeFor3DManipulation,mn.ensureImageVolumeFor3DManipulation),Ume=new Ss("SphereThreshold",...W5.compositions,mn.dynamicThreshold,mn.threshold,mn.islandRemoval,mn.ensureSegmentationVolumeFor3DManipulation,mn.ensureImageVolumeFor3DManipulation),Bme=Fme.strategyFunction,Gme=Ume.strategyFunction,Wme=new Ss("EraseSphere",mn.erase,...W5.compositions),jF=Wme.strategyFunction,zme=new Ss("EraseCircle",mn.erase,...zF.compositions),HF=zme.strategyFunction,{VoxelManager:OC,RLEVoxelMap:$me}=Mn;function MC(t,e){return qF(t,e)}function KF(t){const{segmentationVoxelManager:e,undoVoxelManager:r,redoVoxelManager:n}=this,i=t===!1?n:r;i.forEach(({value:a,pointIJK:s})=>{e.setAtIJKPoint(s,a)});const o=i.getArrayOfModifiedSlices();io(this.segmentationId,o)}function qF(t,e){const r=OC.createRLEHistoryVoxelManager(e);return{segmentationId:t,restoreMemo:KF,commitMemo:jme,segmentationVoxelManager:e,voxelManager:r,id:Dn(),operationType:"labelmap"}}function jme(){if(this.redoVoxelManager)return!0;if(!this.voxelManager.modifiedSlices.size)return!1;const{segmentationVoxelManager:t}=this,e=OC.createRLEHistoryVoxelManager(t);$me.copyMap(e.map,this.voxelManager.map);for(const n of this.voxelManager.modifiedSlices.keys())e.modifiedSlices.add(n);this.undoVoxelManager=e;const r=OC.createRLEVolumeVoxelManager({dimensions:this.segmentationVoxelManager.dimensions});return this.redoVoxelManager=r,e.forEach(({index:n,pointIJK:i,value:o})=>{const a=t.getAtIJKPoint(i);a!==o&&r.setAtIndex(n,a)}),!0}const Hme=Object.freeze(Object.defineProperty({__proto__:null,createLabelmapMemo:MC,createRleMemo:qF,restoreMemo:KF},Symbol.toStringTag,{value:"Module"})),{isEqual:Um}=Mn,Kme=bt(1,0,0),qme=bt(0,1,0),Xme=bt(0,0,1),qD=[Kme,qme,Xme];function XF(t){const e=rr(Ve(),t[0],t[1]),r=rr(Ve(),t[0],t[2]),n=XD(e,qD),i=XD(r,qD);return[...n,...i].every(a=>Um(a,0)||Um(a,90)||Um(a,180)||Um(a,270))}function XD(t,e){return e.map(r=>N_(t,r)*180/Math.PI)}const{transformWorldToIndex:YF}=Mn,JF={[St.Initialize]:t=>{const{points:e,imageVoxelManager:r,viewport:n,segmentationImageData:i,segmentationVoxelManager:o}=t;if(!e)return;const a=bt(0,0,0);e.forEach(l=>{Ai(a,a,l)}),Ni(a,a,1/e.length),t.centerWorld=a,t.centerIJK=YF(i,a);const{boundsIJK:s,pointInShapeFn:c}=Yme(n,e,i);t.isInObject=c,t.isInObjectBoundsIJK=s}};function Yme(t,e,r){let n=e.map(w=>YF(r,w));n=n.map(w=>w.map(x=>Math.round(x)));const i=Su(n,r.getDimensions()),a=t instanceof lr||XF(n),s=r.getDirection(),c=r.getSpacing(),{viewPlaneNormal:l}=t.getCamera(),f=Au({direction:s,spacing:c},l),u=ik(e);let[[d,h],[g,p],[v,y]]=u;return d-=f,h+=f,g-=f,p+=f,v-=f,y+=f,{boundsIJK:i,pointInShapeFn:a?()=>!0:w=>{const[x,C,S]=w,_=x>=d&&x<=h,T=C>=g&&C<=p,E=S>=v&&S<=y;return _&&T&&E}}}const Jme=new Ss("Rectangle",mn.regionFill,mn.setValue,JF,mn.determineSegmentIndex,mn.preview,mn.labelmapStatistics),Zme=new Ss("RectangleThreshold",mn.regionFill,mn.setValue,JF,mn.determineSegmentIndex,mn.dynamicThreshold,mn.threshold,mn.preview,mn.islandRemoval,mn.labelmapStatistics),j4=Jme.strategyFunction,Qme=Zme.strategyFunction,e2e=Object.freeze(Object.defineProperty({__proto__:null,fillInsideCircle:G5,fillInsideRectangle:j4,fillOutsideCircle:Nme,thresholdInsideRectangle:Qme},Symbol.toStringTag,{value:"Module"})),ep=class ep extends ai{constructor(e,r){super(e,r),this.memoMap=new Map,this.acceptedMemoIds=new Map,this.centerSegmentIndexInfo={segmentIndex:null,hasSegmentIndex:!1,hasPreviewIndex:!1,changedIndices:[]}}_historyRedoHandler(e){const{id:r,operationType:n}=e.detail;if(n==="labelmap"){if(this.acceptedMemoIds.has(r)){this._hoverData=null;const i=this.acceptedMemoIds.get(r),o=i==null?void 0:i.element,a=this.getOperationData(o);a.segmentIndex=i==null?void 0:i.segmentIndex,o&&this.applyActiveStrategyCallback(Ce(o),a,St.AcceptPreview)}this._previewData.isDrag=!0}}get _previewData(){return ep.previewData}createMemo(e,r){const n=r.id;if(this.memo&&this.memo.segmentationVoxelManager===r)return this.memo;let i=this.memoMap.get(n);return i?i.redoVoxelManager&&(i=MC(e,r),this.memoMap.set(n,i)):(i=MC(e,r),this.memoMap.set(n,i)),this.memo=i,i}createEditData(e){const r=Ce(e),{viewport:n}=r,i=ed(n.id);if(!i){const l=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"No active segmentation detected, create a segmentation representation before using the brush tool"},cancelable:!0});return Ke.dispatchEvent(l),null}const{segmentationId:o}=i,a=dd(o),{representationData:s}=Ln(o);return this.getEditData({viewport:n,representationData:s,segmentsLocked:a,segmentationId:o})}getEditData({viewport:e,representationData:r,segmentsLocked:n,segmentationId:i}){var o,a,s;if(e instanceof Ir){const{volumeId:c}=r[Dt.Labelmap],l=e.getActors();if(e instanceof lr){const g=new CustomEvent(Xe.ERROR_EVENT,{detail:{type:"Segmentation",message:"Cannot perform brush operation on the selected viewport"},cancelable:!0});return Ke.dispatchEvent(g),null}const u=l.map(g=>Le.getVolume(g.referencedId)),d=Le.getVolume(c),h=((o=u.find(g=>$t(g.dimensions,d.dimensions)))==null?void 0:o.volumeId)||((a=u[0])==null?void 0:a.volumeId);return{volumeId:c,referencedVolumeId:((s=this.configuration.threshold)==null?void 0:s.volumeId)??h,segmentsLocked:n}}else{const c=Vu(e.id,i);return c?{imageId:c,segmentsLocked:n}:void 0}}createHoverData(e,r){const n=Ce(e),{viewport:i}=n,o=i.getCamera(),{viewPlaneNormal:a,viewUp:s}=o,c=[i.id],{segmentIndex:l,segmentationId:f,segmentColor:u}=this.getActiveSegmentationData(i)||{};return{brushCursor:{metadata:{viewPlaneNormal:[...a],viewUp:[...s],FrameOfReferenceUID:i.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:u},data:{}},centerCanvas:r,segmentIndex:l,viewport:i,segmentationId:f,segmentColor:u,viewportIdsToRender:c}}getActiveSegmentationData(e){const r=e.id,n=ed(r);if(!n)return;const{segmentationId:i}=n,o=ea(i);if(!o)return;const a=el(r,i,o);return{segmentIndex:o,segmentationId:i,segmentColor:a}}getOperationData(e){var v,y,m,w;const r=this._editData||this.createEditData(e),{segmentIndex:n,segmentationId:i,brushCursor:o}=this._hoverData||this.createHoverData(e),{data:a,metadata:s={}}=o||{},{viewPlaneNormal:c,viewUp:l}=s,f=(y=(v=this.configuration.preview)==null?void 0:v.previewColors)==null?void 0:y[n],{viewport:u}=Ce(e),d=el(u.id,i,n);if(!f&&!d)return;let h=null,g=null;return(m=this.configuration.preview)!=null&&m.enabled&&(h=f||t2e(...d),g=255),{...r,points:(w=a==null?void 0:a.handles)==null?void 0:w.points,segmentIndex:n,viewPlaneNormal:c,previewOnHover:!this._previewData.isDrag,toolGroupId:this.toolGroupId,segmentationId:i,viewUp:l,centerSegmentIndexInfo:this.centerSegmentIndexInfo,activeStrategy:this.configuration.activeStrategy,configuration:this.configuration,previewColor:h,previewSegmentIndex:g,createMemo:this.createMemo.bind(this)}}addPreview(e=this._previewData.element,r){const{_previewData:n}=this,i=r==null?void 0:r.acceptReject;i===!0?this.acceptPreview(e):i===!1&&this.rejectPreview(e);const o=Ce(e),a=this.applyActiveStrategyCallback(o,this.getOperationData(e),St.AddPreview);return n.isDrag=!0,a}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Ce(e);this.applyActiveStrategyCallback(r,this.getOperationData(e),St.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1}acceptPreview(e=this._previewData.element){if(!e)return;const r=this.getOperationData(e);this.memo&&this.memo.id&&this.acceptedMemoIds.set(this.memo.id,{element:e,segmentIndex:r.segmentIndex});const n=Ce(e);this.applyActiveStrategyCallback(n,r,St.AcceptPreview),this.doneEditMemo(),this._previewData.preview=null,this._previewData.isDrag=!1}static viewportContoursToLabelmap(e,r){var v;const n=(r==null?void 0:r.removeContours)??!0,i=S1(),o=L1(e,i);if(!(o!=null&&o.length))return;const a=o.filter(y=>{var m,w;return(w=(m=y.data.contour)==null?void 0:m.polyline)==null?void 0:w.length});if(!a.length)return;const c=new ep({},{configuration:{strategies:{FILL_INSIDE_CIRCLE:G5},activeStrategy:"FILL_INSIDE_CIRCLE"}}).addPreview(e.element),{memo:l,segmentationId:f}=c,u=l==null?void 0:l.voxelManager,d=u.sourceVoxelManager||u,{dimensions:h}=u,g=e.getDefaultActor().actor.getMapper().getInputData();for(const y of a){const m=[[1/0,-1/0],[1/0,-1/0],[1/0,-1/0]],{polyline:w}=y.data.contour;for(const I of w)g.worldToIndex(I).forEach((M,L)=>{m[L][0]=Math.min(m[L][0],M),m[L][1]=Math.max(m[L][1],M)});m.forEach((I,P)=>{I[0]=Math.round(Math.max(0,I[0])),I[1]=Math.round(Math.min(h[P]-1,I[1]))});const x=ea(f),C=((v=y.data.handles)==null?void 0:v[0])||w[0],S=g.worldToIndex(C).map(Math.round),_=d.getAtIJKPoint(S)||0;let T=!1,E=!1;for(const I of w){const P=g.worldToIndex(I).map(Math.round),M=d.getAtIJKPoint(P);M===_?T=!0:M>=0&&(E=!0)}const b=T&&E?_:_===0?x:0;for(let I=m[0][0];I<=m[0][1];I++)for(let P=m[1][0];P<=m[1][1];P++)for(let M=m[2][0];M<=m[2][1];M++){const L=g.indexToWorld([I,P,M]);v4(L,w)&&u.setAtIJK(I,P,M,b)}n&&gn(y.annotationUID)}const p=u.getArrayOfModifiedSlices();io(f,p)}};ep.previewData={preview:null,element:null,timerStart:0,timer:null,startPoint:[NaN,NaN],isDrag:!1};let rd=ep;function t2e(t,e,r,n,i=.4){return[Math.round(t+(255-t)*i),Math.round(e+(255-e)*i),Math.round(r+(255-r)*i),n]}class z5 extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE_CIRCLE:G5,ERASE_INSIDE_CIRCLE:HF,FILL_INSIDE_SPHERE:$F,ERASE_INSIDE_SPHERE:jF,THRESHOLD_INSIDE_CIRCLE:Ame,THRESHOLD_INSIDE_SPHERE:Bme,THRESHOLD_INSIDE_SPHERE_WITH_ISLAND_REMOVAL:Gme},defaultStrategy:"FILL_INSIDE_CIRCLE",activeStrategy:"FILL_INSIDE_CIRCLE",brushSize:25,useCenterSegmentIndex:!1,preview:{enabled:!1,previewColors:{0:[255,255,255,128]},previewTimeMs:250,previewMoveDistance:8,dragMoveDistance:4,dragTimeMs:500},actions:{[St.AcceptPreview]:{method:St.AcceptPreview,bindings:[{key:"Enter"}]},[St.RejectPreview]:{method:St.RejectPreview,bindings:[{key:"Escape"}]},[St.Interpolate]:{method:St.Interpolate,bindings:[{key:"i"}],configuration:{useBallStructuringElement:!0,noUseDistanceTransform:!0,noUseExtrapolation:!0}},interpolateExtrapolation:{method:St.Interpolate,bindings:[{key:"e"}],configuration:{}}}}}){super(e,r),this.onSetToolPassive=n=>{this.disableCursor()},this.onSetToolEnabled=()=>{this.disableCursor()},this.onSetToolDisabled=n=>{this.disableCursor()},this.preMouseDownCallback=n=>{const i=n.detail,{element:o}=i,a=Ce(o);this._editData=this.createEditData(o),this._activateDraw(o),Ot(o),n.preventDefault(),this._previewData.isDrag=!1,this._previewData.timerStart=Date.now();const s=this._hoverData||this.createHoverData(o);Pe(s.viewportIdsToRender);const c=this.getOperationData(o);return this.applyActiveStrategyCallback(a,c,St.OnInteractionStart),!0},this.mouseMoveCallback=n=>{if(this.mode===An.Active){if(this.updateCursor(n),!this.configuration.preview.enabled)return;const{previewTimeMs:i,previewMoveDistance:o,dragMoveDistance:a}=this.configuration.preview,{currentPoints:s,element:c}=n.detail,{canvas:l}=s,{startPoint:f,timer:u,timerStart:d,isDrag:h}=this._previewData;if(h)return;const g=yr(l,f),p=Date.now()-d;if((g>o||p>i&&g>a)&&(u&&(window.clearTimeout(u),this._previewData.timer=null),h||this.rejectPreview(c)),!this._previewData.timer){const v=window.setTimeout(this.previewCallback,250);Object.assign(this._previewData,{timerStart:Date.now(),timer:v,startPoint:l,element:c})}}},this.previewCallback=()=>{if(this._previewData.isDrag){this._previewData.timer=null;return}this._previewData.timer=null;const n=this.getOperationData(this._previewData.element),i=Ce(this._previewData.element);if(!i)return;const{viewport:o}=i,a=this.configuration.activeStrategy,s=G4({operationData:n,viewport:o,strategy:a});if(!n)return;const c=this.createMemo(n.segmentationId,s.segmentationVoxelManager);this._previewData.preview=this.applyActiveStrategyCallback(Ce(this._previewData.element),{...n,...s,memo:c},St.Preview)},this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o);this.updateCursor(n);const{viewportIdsToRender:c}=this._hoverData;Pe(c);const l=yr(a.canvas,this._previewData.startPoint),{dragTimeMs:f,dragMoveDistance:u}=this.configuration.preview;!this._previewData.isDrag&&Date.now()-this._previewData.timerStart{const i=n.detail,{element:o}=i,a=Ce(o),s=this.getOperationData(o);!this._previewData.preview&&!this._previewData.isDrag&&this.applyActiveStrategy(a,s),this.doneEditMemo(),this._deactivateDraw(o),zt(o),this.updateCursor(n),this._editData=null,this.applyActiveStrategyCallback(a,s,St.OnInteractionEnd),this._previewData.isDrag||this.acceptPreview(o)},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}disableCursor(){this._hoverData=void 0,this.rejectPreview()}updateCursor(e){const r=e.detail,{element:n}=r,{currentPoints:i}=r,o=i.canvas;this._hoverData=this.createHoverData(n,o),this._calculateCursor(n,o),this._hoverData&&Pe(this._hoverData.viewportIdsToRender)}_calculateCursor(e,r){const n=Ce(e),{viewport:i}=n,{canvasToWorld:o}=i,a=i.getCamera(),{brushSize:s}=this.configuration,c=bt(a.viewUp[0],a.viewUp[1],a.viewUp[2]),l=bt(a.viewPlaneNormal[0],a.viewPlaneNormal[1],a.viewPlaneNormal[2]),f=Ve();Rn(f,c,l);const u=o([r[0],r[1]]),d=Ve(),h=Ve(),g=Ve(),p=Ve();for(let x=0;x<=2;x++)d[x]=u[x]-c[x]*s,h[x]=u[x]+c[x]*s,g[x]=u[x]-f[x]*s,p[x]=u[x]+f[x]*s;if(!this._hoverData)return;const{brushCursor:v}=this._hoverData,{data:y}=v;y.handles===void 0&&(y.handles={}),y.handles.points=[d,h,g,p];const m=this.configuration.activeStrategy,w=this.configuration.strategies[m];typeof(w==null?void 0:w.computeInnerCircleRadius)=="function"&&w.computeInnerCircleRadius({configuration:this.configuration,viewport:i}),y.invalidated=!1}getStatistics(e,r){if(!e)return;const n=Ce(e);return this.applyActiveStrategyCallback(n,this.getOperationData(e),St.GetStatistics,r)}rejectPreview(e=this._previewData.element){if(!e)return;this.doneEditMemo();const r=Ce(e);r&&(this.applyActiveStrategyCallback(r,this.getOperationData(e),St.RejectPreview),this._previewData.preview=null,this._previewData.isDrag=!1)}acceptPreview(e=this._previewData.element){e&&super.acceptPreview(e)}interpolate(e,r){if(!e)return;const n=Ce(e);this._previewData.preview=this.applyActiveStrategyCallback(n,this.getOperationData(e),St.Interpolate,r.configuration),this._previewData.isDrag=!0}invalidateBrushCursor(){if(this._hoverData===void 0)return;const{data:e}=this._hoverData.brushCursor,{viewport:r}=this._hoverData;e.invalidated=!0;const{segmentColor:n}=this.getActiveSegmentationData(r)||{};this._hoverData.brushCursor.metadata.segmentColor=n}renderAnnotation(e,r){var m,w;if(!this._hoverData)return;const{viewport:n}=e;if(!this._hoverData.viewportIdsToRender.includes(n.id))return;const o=this._hoverData.brushCursor;if(o.data.invalidated===!0){const{centerCanvas:x}=this._hoverData,{element:C}=n;this._calculateCursor(C,x)}const a=o.metadata;if(!a)return;const s=a.brushCursorUID,c=o.data,{points:l}=c.handles,f=l.map(x=>n.worldToCanvas(x)),u=f[0],d=f[1],h=[Math.floor((u[0]+d[0])/2),Math.floor((u[1]+d[1])/2)],g=Math.abs(u[1]-Math.floor((u[1]+d[1])/2)),p=`rgb(${((m=a.segmentColor)==null?void 0:m.slice(0,3))||[0,0,0]})`;if(!n.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}No(r,s,"0",h,g,{color:p,lineDash:this.centerSegmentIndexInfo.segmentIndex===0?[1,2]:null});const{dynamicRadiusInCanvas:y}=((w=this.configuration)==null?void 0:w.threshold)||{dynamicRadiusInCanvas:0};y&&No(r,s,"1",h,y,{color:p})}}z5.toolName="Brush";function _h(t,e){const r=Kr(t);if(r===void 0)return;const n=r._toolInstances;return Object.keys(n).length?e&&n[e]?[n[e]]:Object.values(n).filter(o=>o instanceof z5):void 0}function n2e(t,e,r){const n=Kr(t);if(n===void 0)return;_h(t,r).forEach(l=>{l.configuration.brushSize=e,l.invalidateBrushCursor()});const o=n.getViewportsInfo(),a=Object.keys(o).map(l=>o[l]);if(!a.length)return;const{renderingEngineId:s}=a[0],c=n.getViewportIds();Jr(s),Pe(c)}function r2e(t,e){const r=Kr(t);if(r===void 0)return;const n=r._toolInstances;if(!Object.keys(n).length)return;const o=_h(t,e)[0];if(o)return o.configuration.brushSize}function i2e(t,e){const r=Kr(t);if(r===void 0||(_h(t).forEach(a=>{a.configuration.activeStrategy.toLowerCase().includes("threshold")&&(a.configuration={...a.configuration,threshold:{...a.configuration.threshold,...e}})}),!r.getViewportsInfo().length))return;const o=r.getViewportIds();Pe(o)}function o2e(t){const e=Kr(t);if(e===void 0)return;const r=e._toolInstances;if(!Object.keys(r).length)return;const i=_h(t)[0];if(i)return i.configuration.threshold.range}const tp=class tp{static statsInit(e){const{storePointData:r,indices:n,mode:i}=e;this.mode=i,this.indices=n,this.calculators.clear(),this.mode==="individual"?n.forEach(o=>{this.calculators.set(o,new HD({storePointData:r}))}):this.calculators.set(n,new HD({storePointData:r}))}static statsCallback(e){const{segmentIndex:r,...n}=e;if(!r)throw new Error("Segment index is required for stats calculation");const i=this.mode==="individual"?this.calculators.get(r):this.calculators.get(this.indices);if(!i)throw new Error(`No calculator found for segment ${r}`);i.statsCallback(n)}static getStatistics(e){if(this.mode==="individual"){const n={};return this.calculators.forEach((i,o)=>{n[o]=i.getStatistics(e)}),n}return this.calculators.get(this.indices).getStatistics(e)}};tp.calculators=new Map,tp.indices=[],tp.mode="collective";let PC=tp;function a2e(t,e,r,n,i){if(!i)throw new Error("Segmentation ID is required to be passed inside thresholdSegmentationByRange");const{baseVolumeIdx:o,volumeInfoList:a}=ok(t,r),{voxelManager:s}=a[o],c=s,l=t.voxelManager.getScalarDataLength(),f=t.voxelManager;return a.forEach(u=>{const{volumeSize:d}=u;d===l?c2e(f,c,e,u):s2e(f,c,e,u,a,o,n)}),io(i),t}function s2e(t,e,r,n,i,o,a){const{imageData:s,lower:c,upper:l,dimensions:f}=n;let u,d,h;const g=t.getScalarDataLength();for(let p=0;p{u=u+1,w>=h.lower&&w<=h.upper&&(d=d+1)};u=0,d=0,h={lower:c,upper:l};let m=!1;t.forEach(y,{imageData:s,boundsIJK:v}),m=a===0?d>0:d===u,t.setAtIndex(p,m?r:0)}return{total:u,range:h,overlaps:d}}function c2e(t,e,r,n){const{lower:i,upper:o}=n,a=t.getScalarDataLength();for(let s=0;s=i&&c<=o?r:0)}}function YD(t,e,r){const n=r.toIJK(t),i=r.toIJK(e),o=Ve(),{testIJK:a}=r,s=En(Ve(),n,i),c=Math.round(Math.max(...s.map(Math.abs)));if(c<2)return!0;const l=Ni(Ve(),s,1/c);for(let f=1;f{const l=Ai(Ve(),s,c).map(v=>v/2),f=e.worldToIndex(l).map(Math.round),[u,d,h]=f,g=u+d*o+h*a,p=r.getAtIndex(g);return p===n||(i==null?void 0:i.has(p))},toIJK:s=>e.worldToIndex(s),testIJK:s=>{const[c,l,f]=s,u=Math.round(c)+Math.round(l)*o+Math.round(f)*a,d=r.getAtIndex(u);return d===n||(i==null?void 0:i.has(d))}}}function u2e(t,e,r){const n=Le.getVolume(t);if(!n){console.warn(`No volume found for ${t}`);return}return l2e({dimensions:n.dimensions,imageData:n.imageData,voxelManager:n.voxelManager,segmentIndex:e,containedSegmentIndices:r})}const Zh=.01;function f2e(t,e,r){const{sliceContours:n}=t,{segmentIndex:i,containedSegmentIndices:o}=r;let a;const s=u2e(e,i,o);for(const c of n){const l=d2e(c,s,a);l&&(a=l)}return a&&Object.assign(a,r),a}function d2e(t,e,r={maxMajor:0,maxMinor:0}){const{points:n}=t.polyData,{maxMinor:i,maxMajor:o}=r;let a=o*o,s=i*i,c;for(let v=0;vZh||e.testCenter(m,w)&&YD(m,w,e)&&(s=x,d=[v,y])}if(!d)return;s=Math.sqrt(s);const h=n[d[0]],g=n[d[1]];return{majorAxis:[l,f],minorAxis:[h,g],maxMajor:a,maxMinor:s,...t}}async function ZF(t){const e=await PF({segmentations:t});if(!(e!=null&&e.length)||!e[0].sliceContours.length)return;const{segments:r=[null,{label:"Unspecified",color:null,containedSegmentIndices:null}]}=t,n=Sh(t.segmentationId);if(!n)return;const i=r.findIndex(o=>!!o);if(i!==-1)return r[i].segmentIndex=i,f2e(e[0],n.volumeId,r[i])}function QF(t,e){const{majorAxis:r,minorAxis:n,label:i="",sliceIndex:o}=t,[a,s]=r,[c,l]=n,f=[a,s,c,l];return{highlighted:!0,invalidated:!0,metadata:{toolName:"Bidirectional",...e.getViewReference({sliceIndex:o})},data:{handles:{points:f,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:i,cachedStats:{}},isLocked:!1,isVisible:!0}}const{transformWorldToIndex:Bm}=Mn,t0=class t0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:h2e}}){super(e,r),this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles;let u=c.worldToCanvas(f[0]),d=c.worldToCanvas(f[1]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=hi([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]);return g<=a||(u=c.worldToCanvas(f[2]),d=c.worldToCanvas(f[3]),h={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},g=hi([h.start.x,h.start.y],[h.end.x,h.end.y],[o[0],o[1]]),g<=a)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),Ot(a),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,c=i.data;i.highlighted=!0;let l=!1,f;o.worldPosition?l=!0:f=c.handles.points.findIndex(g=>g===o);const u=_t(s,this.getToolName());Ot(s),this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;this.doneEditMemo(),f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);if(this.editData.handleIndex!==void 0){const{points:d}=f.handles,h=ki(d[0],d[1]);if(ki(d[2],d[3])>h){const p=[[...d[2]],[...d[3]]],v=[...d[0]],y=[...d[1]],m=qt();Va(m,p[1][0]-p[0][0],p[1][1]-p[1][0]);const w=qt();Va(w,-m[1],m[0]);const x=qt();Va(x,y[0]-v[0],y[1]-v[0]);let C;k_(x,w)>0?C=[v,y]:C=[y,v],f.handles.points=[p[0],p[1],C[0],C[1]]}}this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c}=s,{worldToCanvas:l}=c,{annotation:f,viewportIdsToRender:u,handleIndex:d,newAnnotation:h}=this.editData;this.createMemo(a,f,{newAnnotation:h});const{data:g}=f,p=o.world;g.handles.points[d]=[...p];const v=g.handles.points.map(l),y={longLineSegment:{start:{x:v[0][0],y:v[0][1]},end:{x:v[1][0],y:v[1][1]}},shortLineSegment:{start:{x:v[2][0],y:v[2][1]},end:{x:v[3][0],y:v[3][1]}}},w=yr(v[0],v[1])/3,x=y.longLineSegment.start.x-y.longLineSegment.end.x,C=y.longLineSegment.start.y-y.longLineSegment.end.y,S=Math.sqrt(x*x+C*C),_=x/S,T=C/S,E=(y.longLineSegment.start.x+y.longLineSegment.end.x)/2,D=(y.longLineSegment.start.y+y.longLineSegment.end.y)/2,b=E+w*T,I=D-w*_,P=E-w*T,M=D+w*_;g.handles.points[2]=c.canvasToWorld([b,I]),g.handles.points[3]=c.canvasToWorld([P,M]),f.invalidated=!0,Pe(u),tn(f,a,Ht.HandlesUpdated),this.editData.hasMoved=!0},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else this._dragModifyHandle(n),a.invalidated=!0;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragModifyHandle=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c}=s,{annotation:l,handleIndex:f}=this.editData,{data:u}=l,d=o.world,h=[c.worldToCanvas(u.handles.points[0]),c.worldToCanvas(u.handles.points[1]),c.worldToCanvas(u.handles.points[2]),c.worldToCanvas(u.handles.points[3])],g={start:{x:h[0][0],y:h[0][1]},end:{x:h[1][0],y:h[1][1]}},p={start:{x:h[2][0],y:h[2][1]},end:{x:h[3][0],y:h[3][1]}},v=[...d],y=c.worldToCanvas(v);if(f===0||f===1){const w=h[f===0?1:0],x=Va(qt(),y[0]-w[0],y[1]-w[1]),C=Va(qt(),h[f][0]-w[0],h[f][1]-w[1]);Nc(x,x),Nc(C,C);const S={start:{x:w[0],y:w[1]},end:{x:y[0],y:y[1]}};if(this._movingLongAxisWouldPutItThroughShortAxis(S,p))return;const _=w,T=this._getSignedAngle(C,x);let E=h[2][0],D=h[2][1],b=h[3][0],I=h[3][1];E-=_[0],D-=_[1],b-=_[0],I-=_[1];const P=E*Math.cos(T)-D*Math.sin(T),M=E*Math.sin(T)+D*Math.cos(T),L=b*Math.cos(T)-I*Math.sin(T),V=b*Math.sin(T)+I*Math.cos(T);E=P+_[0],D=M+_[1],b=L+_[0],I=V+_[1];const G=c.canvasToWorld([E,D]),A=c.canvasToWorld([b,I]);u.handles.points[f]=v,u.handles.points[2]=G,u.handles.points[3]=A}else{const m=f===2?3:2,w={longLineSegment:{start:g.start,end:g.end},shortLineSegment:{start:p.start,end:p.end}},x=Wr(qt(),[w.longLineSegment.end.x,w.longLineSegment.end.y],[w.longLineSegment.start.x,w.longLineSegment.start.y]),C=Nc(qt(),x),S=Wr(qt(),[y[0],y[1]],[h[f][0],h[f][1]]),_=xv(S),T=this._getSignedAngle(C,S),E=Math.cos(T)*_,D=jK(qt(),[h[m][0],h[m][1]],C,E);if(this._movingLongAxisWouldPutItThroughShortAxis({start:{x:y[0],y:y[1]},end:{x:D[0],y:D[1]}},{start:{x:w.longLineSegment.start.x,y:w.longLineSegment.start.y},end:{x:w.longLineSegment.end.x,y:w.longLineSegment.end.y}})||!Zv([y[0],y[1]],[D[0],D[1]],[g.start.x,g.start.y],[g.end.x,g.end.y]))return;u.handles.points[m]=c.canvasToWorld(D),u.handles.points[f]=v}},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback)},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!0;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(Y));u.annotationUID=g;const{color:w,lineWidth:x,lineDash:C,shadow:S}=this.getAnnotationStyle({annotation:h,styleSpecifier:u});if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let _;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(_=[m[y]]),_&&ir(i,g,"0",_,{color:w});const T=`${g}-line-1`,E=`${g}-line-2`;vn(i,g,"0",m[0],m[1],{color:w,lineDash:C,lineWidth:x,shadow:S},T),vn(i,g,"1",m[2],m[3],{color:w,lineDash:C,lineWidth:x,shadow:S},E),o=!0;const I=this.getLinkedTextBoxStyle(u,h);if(!I.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const P=this.configuration.getTextLines(p,l);if(!P||P.length===0)continue;let M;p.handles.textBox.hasMoved||(M=na(m),p.handles.textBox.worldPosition=a.canvasToWorld(M));const L=a.worldToCanvas(p.handles.textBox.worldPosition),G=qi(i,g,"1",P,L,m,{},I),{x:A,y:k,width:F,height:j}=G;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([A,k]),topRight:a.canvasToWorld([A+F,k]),bottomLeft:a.canvasToWorld([A,k+j]),bottomRight:a.canvasToWorld([A+F,k+j])}}return o},this._movingLongAxisWouldPutItThroughShortAxis=(n,i)=>{const o=qt();Va(o,i.end.x-i.start.x,i.end.y-i.start.y),Nc(o,o);const a={start:{x:i.start.x-o[0]*10,y:i.start.y-o[1]*10},end:{x:i.end.x+o[0]*10,y:i.end.y+o[1]*10}};return!Zv([a.start.x,a.start.y],[a.end.x,a.end.y],[n.start.x,n.start.y],[n.end.x,n.end.y])},this._calculateCachedStats=(n,i,o)=>{const{data:a}=n,{element:s}=o.viewport,c=a.handles.points[0],l=a.handles.points[1],f=a.handles.points[2],u=a.handles.points[3],{cachedStats:d}=a,h=Object.keys(d);for(let p=0;pL?M:L,G=M>L?L:M,A=M>L?b:P,k=M>L?P:b;this._isInsideVolume(x,C,S,_,w)?this.isHandleOutsideImage=!1:this.isHandleOutsideImage=!0,d[v]={length:V,width:G,unit:A,widthUnit:k}}const g=n.invalidated;return n.invalidated=!1,g&&tn(n,s,Ht.StatsUpdated),d},this._isInsideVolume=(n,i,o,a,s)=>sr(n,s)&&sr(i,s)&&sr(o,s)&&sr(a,s),this._getSignedAngle=(n,i)=>Math.atan2(n[0]*i[1]-n[1]*i[0],n[0]*i[0]+n[1]*i[1]),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,o=n.world,a=Ce(i),{viewport:s,renderingEngine:c}=a;this.isDrawing=!0;const l=s.getCamera(),{viewPlaneNormal:f,viewUp:u}=l,d=this.getReferencedImageId(s,o,f,u),h=s.getFrameOfReferenceUID(),g={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...f],viewUp:[...u],FrameOfReferenceUID:h,referencedImageId:d,...s.getViewReference({points:[o]})},data:{handles:{points:[[...o],[...o],[...o],[...o]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};nn(g,i);const p=_t(i,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(i),Ot(i),e.preventDefault(),Pe(p),g}_calculateLength(e,r){const n=e[0]-r[0],i=e[1]-r[1],o=e[2]-r[2];return Math.sqrt(n*n+i*i+o*o)}};t0.toolName="Bidirectional",t0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=t0.hydrateBase(t0,i,r[0],n),[f,u]=r,[d,h]=f,[g,p]=u,v=[d,h,g,p],{toolInstance:y,...m}=n||{},w={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:v,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...m}};return nn(w,l.element),Pe([l.id]),w};let Hp=t0;function h2e(t,e){const{cachedStats:r,label:n}=t,{length:i,width:o,unit:a}=r[e],s=[];return n&&s.push(n),i===void 0||s.push(`L: ${an(i)} ${a||a}`,`W: ${an(o)} ${a}`),s}async function g2e(t,e){console.warn("Deprecation Alert: There is a new getSegmentLargestBidirectional function that handles volume, stack and individual segment cases properly. This function is deprecated and will be removed in a future version.");const{data:r}=e,n=Ce(t),i=(r.getSegment||p2e)(n,r);if(!i)return;const o=n.viewport.getFrameOfReferenceUID(),a=U5(),{segmentIndex:s,segmentationId:c}=i,l=Rr.getAnnotations(this.toolName||Hp.toolName,o);let f=!1;const u=l.filter(h=>{const g=h.data.segment;return g?(g.segmentationId===c&&g.segmentIndex===s&&(f=!0,h.data.segment=g),!0):!1});f||u.push({data:{segment:i}});let d;if(u.forEach(async h=>{const g=[],p=h.data.segment,{segmentIndex:v,segmentationId:y}=p;g[v]=p,Rr.removeAnnotation(h.annotationUID);const m=await ZF({...a.find(C=>C.segmentationId===y),segments:g});if(!m)return;const w=QF(m,n.viewport);w.annotationUID=h.annotationUID,w.data.segment=p;const x=Rr.addAnnotation(w,o);if(p.segmentIndex===i.segmentIndex&&p.segmentationId===i.segmentationId){d=m;const{style:C}=i;C&&HT.setAnnotationStyles(x,C)}}),d){const{sliceIndex:h}=d,g=n.viewport.getImageIds();Aa(t,{imageIndex:g.length-1-h}),n.viewport.render()}else console.warn("No bidirectional found");return d}function p2e(t,e){var a;const r=U5();if(!r.length)return;const n=e.segmentationId||r[0].segmentationId,i=e.segmentIndex??ea(n);if(!i)return;const o=(a=e.segmentData)==null?void 0:a.get(i);return{label:`Segment ${i}`,segmentIndex:i,segmentationId:n,...o}}function eU(t){const e=Kr(t);if(e===void 0)return;_h(t).forEach(a=>{a.invalidateBrushCursor()});const n=e.getViewportsInfo();if(!Object.keys(n).map(a=>n[a]).length)return;const o=e.getViewportIds();Pe(o)}function H4(t,e,r={}){const n=Ln(t),i=n.representationData,o=(r==null?void 0:r.representationType)??Object.keys(i)[0];if(!o)throw new Error(`Segmentation ${t} does not have any representations`);switch(o){case Dt.Labelmap:return m2e(n,e,r);case Dt.Contour:return v2e(n,e,r);default:return}}function m2e(t,e,{viewport:r}){const n=t.representationData.Labelmap;if(r instanceof Ir){const{volumeId:h}=n,g=Le.getVolume(h);return g?g.imageData.getScalarValueFromWorld(e):void 0}const i=Qc(r.id,t.segmentationId);if(i.length>1){console.warn("Segment selection for labelmaps with multiple imageIds in stack viewports is not supported yet.");return}const o=i[0];if(!Le.getImage(o))return;const s=_5(r.id,t.segmentationId),c=s==null?void 0:s.actor.getMapper().getInputData(),l=Ur(c,e),f=c.getDimensions();return(c.voxelManager||tc.createScalarVolumeVoxelManager({dimensions:f,scalarData:c.getPointData().getScalars().getData()})).getAtIJKPoint(l)}function v2e(t,e,{viewport:r}){const n=t.representationData.Contour,i=Array.from(n.annotationUIDsMap.keys()),{viewPlaneNormal:o}=r.getCamera();for(const a of i){const s=n.annotationUIDsMap.get(a);if(s)for(const c of s){const l=Br(c);if(!l)continue;const{polyline:f}=l.data.contour;if($t(o,l.metadata.viewPlaneNormal)&&v4(e,f))return Number(a)}}}function tU(t,e,{viewport:r,searchRadius:n}){const o=Ln(t).representationData.Labelmap;if(r instanceof Ir){const{volumeId:p}=o,v=Le.getVolume(p);if(!v)return;const y=v.voxelManager,m=v.imageData,w=Ur(m,e),x=y.getAtIJK(w[0],w[1],w[2]),C=r.worldToCanvas(e);return w2e(C,x,r,m,n)?x:void 0}const a=Vu(r.id,t);if(!Le.getImage(a))return;const c=_5(r.id,t),l=c==null?void 0:c.actor.getMapper().getInputData(),f=Ur(l,e),u=l.getDimensions(),d=l.voxelManager||tc.createScalarVolumeVoxelManager({dimensions:u,scalarData:l.getPointData().getScalars().getData()}),h=d.getAtIJKPoint(f);return y2e(f,u,d,h)?h:void 0}function nU(t,e,r=1){const n=Array.from({length:2*r+1},(i,o)=>o-r);for(const i of n)for(const o of n)for(const a of n){if(i===0&&o===0&&a===0)continue;const s=t(i,o,a);if(s!==void 0&&e!==s)return!0}return!1}function y2e(t,e,r,n,i){return nU((a,s,c)=>{const l=[t[0]+a,t[1]+s,t[2]+c];return r.getAtIJK(l[0],l[1],l[2])},n,i)}function w2e(t,e,r,n,i){return nU((a,s)=>{const c=[t[0]+a,t[1]+s],l=r.canvasToWorld(c),f=n.get("voxelManager").voxelManager,u=Ur(n,l);return f.getAtIJK(u[0],u[1],u[2])},e,i)}function rU(t){const e=Ln(t),{annotationUIDsMap:r}=e.representationData.Contour;for(const[n,i]of r.entries())if(Array.from(i).find(a=>Br(a).highlighted))return n}const x2e=` const MAX_STRENGTH = 65535f; // Workgroup size - X*Y*Z must be multiple of 32 for better performance @@ -3758,20 +3758,20 @@ fn main( labelmap[currentPixelIndex] = newLabel; strengthData[currentPixelIndex] = newStrength; } -`,C2e=1024*1024*1024,JD=1.99*C2e,d3={windowSize:3,maxProcessingTime:3e4,inspection:{numCyclesInterval:5,numCyclesBelowThreshold:3,threshold:1e-4}};async function $5(t,e,r=d3){var xe;const n=[8,8,4],{windowSize:i,maxProcessingTime:o}=Object.assign({},d3,r),a=Object.assign({},d3.inspection,r.inspection),s=Le.getVolume(t),c=Le.getVolume(e),[l,f,u]=s.dimensions;if(c.dimensions[0]!==l||c.dimensions[1]!==f||c.dimensions[2]!==u)throw new Error("Volume and labelmap must have the same size");let d=Math.floor(Math.sqrt(f**2+l**2+u**2)/2);d=Math.min(d,500);const h=c.voxelManager.getCompleteScalarDataArray();let g=s.voxelManager.getCompleteScalarDataArray();g instanceof Float32Array||(g=new Float32Array(g));const p={maxStorageBufferBindingSize:JD,maxBufferSize:JD},y=await(await((xe=navigator.gpu)==null?void 0:xe.requestAdapter())).requestDevice({requiredLimits:p}),m=g.byteLength,w=d*Uint32Array.BYTES_PER_ELEMENT,x=6*Int32Array.BYTES_PER_ELEMENT,C=y.createShaderModule({code:x2e}),S=3,_=new Uint32Array([l,f,u,0]),T=y.createBuffer({size:_.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),E=y.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});y.queue.writeBuffer(E,0,g);const D=[0,1].map(()=>y.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}));y.queue.writeBuffer(D[0],0,new Uint32Array(h));const b=[0,1].map(()=>y.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),I=y.createBuffer({size:w,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),P=y.createBuffer({size:x,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),M=new Int32Array([l,f,u,-1,-1,-1]);y.queue.writeBuffer(P,0,M);const L=y.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),V=[0,1].map(De=>{const Ne=D[De],ze=b[De],ie=D[(De+1)%2],ae=b[(De+1)%2];return y.createBindGroup({layout:L,entries:[{binding:0,resource:{buffer:T}},{binding:1,resource:{buffer:E}},{binding:2,resource:{buffer:Ne}},{binding:3,resource:{buffer:ze}},{binding:4,resource:{buffer:ie}},{binding:5,resource:{buffer:ae}},{binding:6,resource:{buffer:I}},{binding:7,resource:{buffer:P}}]})}),G=y.createComputePipeline({layout:y.createPipelineLayout({bindGroupLayouts:[L]}),compute:{module:C,entryPoint:"main",constants:{workGroupSizeX:n[0],workGroupSizeY:n[1],workGroupSizeZ:n[2],windowSize:i}}}),A=[Math.ceil(l/n[0]),Math.ceil(f/n[1]),Math.ceil(u/n[2])],k=y.createBuffer({size:w,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),F=o?performance.now()+o:0;let j=a.numCyclesInterval,Y=0;for(let De=0;De0&&!(De%j)){await k.mapAsync(GPUMapMode.READ,0,w);const ae=k.getMappedRange(0,w),se=new Uint32Array(ae.slice(0))[De]/g.length;if(k.unmap(),De>=1&&seF){console.warn(`Exceeded processing time limit (${o})ms`);break}}const re=y.createCommandEncoder(),ue=(d+1)%2,ce=y.createBuffer({size:m,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),pe=y.createBuffer({size:x,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});re.copyBufferToBuffer(D[ue],0,ce,0,m),re.copyBufferToBuffer(P,0,pe,0,x),y.queue.submit([re.finish()]),await ce.mapAsync(GPUMapMode.READ,0,m);const Ee=ce.getMappedRange(0,m),Oe=new Uint32Array(Ee);h.set(Oe),ce.unmap(),await pe.mapAsync(GPUMapMode.READ,0,x);const Se=pe.getMappedRange(0,x),B=new Int32Array(Se.slice(0));pe.unmap();const O=B[0],z=B[1],W=B[2],K=B[3],Z=B[4],ee=B[5];c.voxelManager.setCompleteScalarDataArray(h),c.voxelManager.clearBounds(),c.voxelManager.setBounds([[O,K],[z,Z],[W,ee]])}const{transformWorldToIndex:Kp}=Mn,S2e=254,_2e=255,T2e=.1,E2e=.8;function D2e(t,e){const{topLeftWorld:r,bottomRightWorld:n}=e,i=Kp(t.imageData,r),o=Kp(t.imageData,n);return{...e,topLeftIJK:i,bottomRightIJK:o}}function b2e(t,e){const r=t.imageData.getDirection(),n=bt(r[3],r[4],r[5]),{center:i,radius:o}=e,a=t.imageData,s=Tn(Ve(),i,n,-o),c=Tn(Ve(),i,n,o),l=fF([c,s],a);return D2e(t,l)}function I2e(t,e,r){const n=t.imageData,i=r.getCamera(),{ijkVecRowDir:o,ijkVecColDir:a}=f5(n,i);if([o,a].some(f=>!$t(Math.abs(f[0]),1)&&!$t(Math.abs(f[1]),1)&&!$t(Math.abs(f[2]),1))){console.warn("Oblique view is not supported!");return}const{boundsIJK:c}=b2e(t,e),l={minX:c[0][0],maxX:c[0][1]+1,minY:c[1][0],maxY:c[1][1]+1,minZ:c[2][0],maxZ:c[2][1]+1};return GT(t.volumeId,l,{targetBuffer:{type:"Float32Array"}})}function O2e(t,e,r,n){const i=t.voxelManager.getCompleteScalarDataArray(),o=r.center,[a,s,c]=t.dimensions,l=a*s,f=Kp(t.imageData,o),u=i[f[2]*l+f[1]*a+f[0]],d=n.positiveSeedValue??S2e,h=n.positiveSeedVariance??T2e,g=Math.abs(u*h),p=u-g,v=u+g,y=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]],m=f[2]*l+f[1]*a+f[0];e.voxelManager.setAtIndex(m,d);const w=[f];for(;w.length;){const x=w.shift(),[C,S,_]=x;for(let T=0,E=y.length;T=a||I<0||I>=s||P<0||P>=c)continue;const M=P*l+I*a+b,L=i[M];e.voxelManager.getAtIndex(M)===d||Lv||(e.voxelManager.setAtIndex(M,d),w.push([b,I,P]))}}}function M2e(t,e,r,n,i){const o=t.voxelManager.getCompleteScalarDataArray(),[a,s,c]=e.dimensions,l=a*s,{worldVecRowDir:f,worldVecSliceDir:u}=f5(e.imageData,n.getCamera()),d=Kp(t.imageData,r.center),h=o[d[2]*a*s+d[1]*a+d[0]],g=i.negativeSeedVariance??E2e,p=(i==null?void 0:i.negativeSeedValue)??_2e,v=Math.abs(h*g),y=h-v,m=h+v,w=360,x=2*Math.PI/w,C=jy(yu(),u,x),S=OM(f);for(let _=0;_=a||b<0||b>=s||I<0||I>=c)continue;const P=D+b*a+I*l,M=o[P];(Mm)&&e.voxelManager.setAtIndex(P,p)}}async function P2e(t,e,r,n){const i=await o5(t.volumeId);return O2e(t,i,e,n),M2e(t,i,e,r,n),i}async function iU(t,e,r,n){const i=Le.getVolume(t),o=I2e(i,e,r),a=await P2e(o,e,r,n);return await $5(o.volumeId,a.volumeId),a}const R2e=254,L2e=255,A2e=[-1/0,-995],N2e=[0,1900];function k2e(t,e,r){const{negativeSeedValue:n=L2e,negativePixelRange:i=A2e}=r,o=t.voxelManager.getCompleteScalarDataArray(),[a,s,c]=e.dimensions,l=Math.floor(c/2),f=new Array(a*s).fill(!1),u=l*a*s,d=(g,p)=>{const v=[[g,p]];for(;v.length;){const[y,m]=v.shift(),w=m*a+y;if(y<0||y>=a||m<0||m>=s||f[w])continue;f[w]=!0;const x=u+w,C=o[x];Ci[1]||(e.voxelManager.setAtIndex(x,n),v.push([y-1,m]),v.push([y+1,m]),v.push([y,m-1]),v.push([y,m+1]))}},h=(g,p,v,y)=>{for(let m=g;m!==p;m+=v){const w=y*a+m,x=u+w,C=o[x];if(Ci[1])break;f[w]||d(m,y)}};for(let g=0;g=i[0]&&w<=i[1]&&e.voxelManager.setAtIndex(m,n)}}}}async function F2e(t,e){const r=o5(t.volumeId);return V2e(t,r,e),k2e(t,r,e),r}async function oU(t,e,r){const{boundingBox:n}=e,{ijkTopLeft:i,ijkBottomRight:o}=n,a={minX:i[0],maxX:o[0],minY:i[1],maxY:o[1],minZ:i[2],maxZ:o[2]},s=GT(t,a,{targetBuffer:{type:"Float32Array"}}),c=await F2e(s,r);return await $5(s.volumeId,c.volumeId),c}const U2e=254,B2e=255,G2e=1,aU=1.8,W2e=3.2,RC=30,z2e=70,$2e=50,{transformWorldToIndex:j2e}=Mn,wg=1e5;function sU(t,e,r){const{dimensions:n,imageData:i}=t,[o,a,s]=n,c=t.voxelManager,l=c.getCompleteScalarDataArray(),f=o*a,u=(r==null?void 0:r.initialNeighborhoodRadius)??G2e,d=(r==null?void 0:r.positiveStdDevMultiplier)??aU,h=(r==null?void 0:r.negativeStdDevMultiplier)??W2e,g=(r==null?void 0:r.negativeSeedMargin)??RC,p=(r==null?void 0:r.negativeSeedsTargetPatches)??z2e,v=j2e(i,e).map(Math.round),y=c.toIndex(v);if(v[0]<0||v[0]>=o||v[1]<0||v[1]>=a||v[2]<0||v[2]>=s)return console.warn("Click position is outside volume bounds."),null;const m=JA(l,n,v,u);m.count===0&&(m.mean=l[y],m.stdDev=0);const w=m.mean-d*m.stdDev,x=m.mean+d*m.stdDev,C=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]];let S=1/0,_=1/0,T=1/0,E=-1/0,D=-1/0,b=-1/0;const I=new Set,P=[],M=l[y];if(M>=w&&M<=x)I.add(y),P.push(v),S=E=v[0],_=D=v[1],T=b=v[2];else return console.warn("Clicked voxel intensity is outside the calculated positive range. No positive seeds generated."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let L=0;for(;L=o||ie<0||ie>=a||ae<0||ae>=s)continue;const we=ae*f+ie*o+ze;if(I.has(we))continue;const se=l[we];se>=w&&se<=x&&(I.add(we),I.size=wg&&console.debug(`Reached maximum number of positive seeds (${wg}). Stopping BFS.`),I.size===0)return console.warn("No positive seeds found after BFS."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let V=0,G=0;I.forEach(W=>{const K=l[W];V+=K,G+=K*K});const A=I.size,k=V/A,F=G/A-k*k,j=Math.sqrt(Math.max(0,F)),Y=h*j,re=Math.max(0,S-g),ue=Math.max(0,_-g),ce=Math.max(0,T-g),pe=Math.min(o-1,E+g),Ee=Math.min(a-1,D+g),Oe=Math.min(s-1,b+g),Se=new Set;let B=0,O=0;const z=p*$2e;for(;OY){let De=!1;for(let Ne=-1;Ne<=1;Ne++){const ze=K+Ne;if(!(ze<0||ze>=a))for(let ie=-1;ie<=1;ie++){const ae=W+ie;if(ae<0||ae>=o)continue;const we=Z*f+ze*o+ae;I.has(we)||Se.has(we)||(Se.add(we),De=!0)}}De&&O++}}return Se.size===0&&console.warn("Could not find any negative seeds. GrowCut might fail or produce poor results."),console.debug("positiveSeedIndices",I.size),console.debug("negativeSeedIndices",Se.size),{positiveSeedIndices:I,negativeSeedIndices:Se}}async function cU({referencedVolumeId:t,worldPosition:e,options:r}){const n=Le.getVolume(t),i=o5(t);i.voxelManager.forEach(({index:f,value:u})=>{u!==0&&i.voxelManager.setAtIndex(f,0)});const o=r.seeds??sU(n,e,r),a=(r==null?void 0:r.positiveSeedValue)??U2e,s=(r==null?void 0:r.negativeSeedValue)??B2e;if(!o)return null;const{positiveSeedIndices:c,negativeSeedIndices:l}=o;return c.size<10||c.size>wg||l.size<10?(console.warn("Not enough seeds found. GrowCut might fail or produce poor results."),i):(c.forEach(f=>{i.voxelManager.setAtIndex(f,a)}),l.forEach(f=>{i.voxelManager.setAtIndex(f,s)}),await $5(t,i.volumeId,r),i)}const H2e=Object.freeze(Object.defineProperty({__proto__:null,run:$5,runGrowCutForBoundingBox:oU,runGrowCutForSphere:iU,runOneClickGrowCut:cU},Symbol.toStringTag,{value:"Module"}));function K2e(t,e){const{segmentationId:r,config:n}=e,i={colorLUTIndex:q2e(n),...n};Zn.addSegmentationRepresentation(t,r,e.type,i),e.type===Dt.Contour&&Pe([t]),Ta(r)}function q2e(t){const{colorLUTOrIndex:e}=t||{};return e===void 0?$g(JSON.parse(JSON.stringify(oy))):typeof e=="number"?e:Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===4)?$g(e):$g(JSON.parse(JSON.stringify(oy)))}function Th(t,e){e.map(r=>K2e(t,r))}function K4(t,e){return Th(t,e.map(r=>({...r,type:Dt.Contour})))}function X2e(t){const e={};for(const[r,n]of Object.entries(t))e[r]=K4(r,n);return e}function lU(t,e){return Th(t,e.map(r=>({...r,type:Dt.Labelmap})))}function Y2e(t){for(const[e,r]of Object.entries(t))lU(e,r.map(n=>({...n,type:Dt.Labelmap})))}function uU(t,e){return Th(t,e.map(r=>({...r,type:Dt.Surface})))}function J2e(t){const e={};for(const[r,n]of Object.entries(t))e[r]=uU(r,n);return e}async function Z2e({segmentationId:t,viewportId:e,imageIds:r,options:n}){const i=Ln(t);if(n!=null&&n.removeOriginal){const o=i.representationData.Labelmap;Le.getVolume(o.volumeId)&&Le.removeVolumeLoadObject(o.volumeId),i.representationData.Labelmap={imageIds:r}}else i.representationData.Labelmap={...i.representationData.Labelmap,imageIds:r};await Th(e,[{segmentationId:t,type:Dt.Labelmap}]),Ke.addEventListenerOnce(N.SEGMENTATION_RENDERED,()=>io(t))}async function Q2e({volumeId:t}){return{imageIds:Le.getVolume(t).imageIds}}function eve({segmentationId:t,options:e}){const r=Ln(t);if(!r)return;const{volumeId:n}=r.representationData.Labelmap,i=Le.getVolume(n);return Z2e({segmentationId:t,viewportId:e.viewportId,imageIds:i.imageIds,options:e})}async function fU(t){return ak(t)}async function tve({segmentationId:t,segmentIndices:e,mode:r="individual"}){F5(),oc(xa.COMPUTE_LARGEST_BIDIRECTIONAL,0);const n=IF(t,e);if(!n)return;const{operationData:i,segImageIds:o,reconstructableVolume:a,indices:s}=n,c=a?await nve({operationData:i,indices:s,mode:r}):await rve({segImageIds:o,indices:s,mode:r});return oc(xa.COMPUTE_LARGEST_BIDIRECTIONAL,100),c}async function nve({operationData:t,indices:e,mode:r}){const n=OF(t),{segmentationVoxelManager:i,segmentationImageData:o}=n,s={scalarData:i.getCompleteScalarDataArray(),dimensions:o.getDimensions(),spacing:o.getSpacing(),origin:o.getOrigin(),direction:o.getDirection()};return await il().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:s,indices:e,mode:r})}async function rve({segImageIds:t,indices:e,mode:r}){const{segmentationInfo:n}=MF(t);return await il().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:n,indices:e,mode:r,isStack:!0})}function ive(t){const e=Ln(t);if(!e)return null;let r;const n=e.representationData.Labelmap;if("imageIds"in n){const{imageIds:i}=n,o=Le.getImage(i[0]),a=Le.getVolumeContainingImageId(o.referencedImageId);if(a!=null&&a.volume)return a.volume;r=i.map(s=>Le.getImage(s).referencedImageId)}else if("volumeId"in n){const{volumeId:i,referencedVolumeId:o}=n;if(o){const s=Le.getVolume(o);if(s)return s}const a=Le.getVolume(i);a&&(r=a.imageIds.map(s=>Le.getImage(s).referencedImageId))}return B5(r)}async function ove({segmentationIds:t,segmentIndex:e}){F5(),oc(xa.COMPUTE_STATISTICS,0);const r=Ln(t[0]),{imageIds:n}=r.representationData.Labelmap;if(!Nu(n))throw new Error("Invalid volume - TMTV cannot be calculated");return await ave({segmentationIds:t,segmentIndex:e})}async function ave({segmentationIds:t,segmentIndex:e}){const r=t.map(p=>Sh(p)),n=NF(r,e);if(!n)throw new Error("Invalid volume - TMTV cannot be calculated");const{imageData:i,dimensions:o,direction:a,origin:s,voxelManager:c}=n,l=i.getSpacing(),u={scalarData:c.getCompleteScalarDataArray(),dimensions:o,spacing:l,origin:s,direction:a},d=ive(t[0]),h={dimensions:d.dimensions,spacing:d.spacing,origin:d.origin,direction:d.direction,scalarData:d.voxelManager.getCompleteScalarDataArray()};if(h.scalarData.length===0||u.scalarData.length===0)return{[e]:{name:"TMTV",value:0}};const g=await il().executeTask("compute","computeMetabolicStats",{segmentationInfo:u,imageInfo:h});return oc(xa.COMPUTE_STATISTICS,100),g}const sve=Object.freeze(Object.defineProperty({__proto__:null,IslandRemoval:nd,LabelmapMemo:Hme,SegmentStatsCalculator:PC,VolumetricCalculator:Uf,computeMetabolicStats:ove,computeStackLabelmapFromVolume:Q2e,computeVolumeLabelmapFromStack:fU,contourAndFindLargestBidirectional:ZF,createBidirectionalToolData:QF,createLabelmapVolumeForViewport:fme,createMergedLabelmapForIndex:NF,floodFill:$4,getBrushSizeForToolGroup:r2e,getBrushThresholdForToolGroup:o2e,getBrushToolInstances:_h,getHoveredContourSegmentationAnnotation:rU,getOrCreateImageVolume:B5,getOrCreateSegmentationVolume:Sh,getReferenceVolumeForSegmentationVolume:EF,getSegmentIndexAtLabelmapBorder:tU,getSegmentIndexAtWorldPoint:H4,getSegmentLargestBidirectional:tve,getStatistics:UF,getUniqueSegmentIndices:Qk,growCut:H2e,invalidateBrushCursor:eU,rectangleROIThresholdVolumeByRange:lme,segmentContourAction:g2e,setBrushSizeForToolGroup:n2e,setBrushThresholdForToolGroup:i2e,thresholdSegmentationByRange:a2e,thresholdVolumeByRange:LF,triggerSegmentationRender:wh,triggerSegmentationRenderBySegmentationId:k5,validateLabelmap:Y1e},Symbol.toStringTag,{value:"Module"}));function cve(t){let e="";const r=t[0]<0?"R":"L",n=t[1]<0?"A":"P",i=t[2]<0?"F":"H",o=[Math.abs(t[0]),Math.abs(t[1]),Math.abs(t[2])],a=1e-4;for(let s=0;s<3;s++)if(o[0]>a&&o[0]>o[1]&&o[0]>o[2])e+=r,o[0]=0;else if(o[1]>a&&o[1]>o[0]&&o[1]>o[2])e+=n,o[1]=0;else if(o[2]>a&&o[2]>o[0]&&o[2]>o[1])e+=i,o[2]=0;else if(o[0]>a&&o[1]>a&&o[0]===o[1])e+=r+n,o[0]=0,o[1]=0;else if(o[0]>a&&o[2]>a&&o[0]===o[2])e+=r+i,o[0]=0,o[2]=0;else if(o[1]>a&&o[2]>a&&o[1]===o[2])e+=n+i,o[1]=0,o[2]=0;else break;return e}function lve(t){let e=t.replace("H","f");return e=e.replace("F","h"),e=e.replace("R","l"),e=e.replace("L","r"),e=e.replace("A","p"),e=e.replace("P","a"),e=e.toUpperCase(),e}const uve=Object.freeze(Object.defineProperty({__proto__:null,getOrientationStringLPS:cve,invertOrientationStringLPS:lve},Symbol.toStringTag,{value:"Module"}));var _0;(function(t){t.CLIP_STOPPED="CORNERSTONE_CINE_TOOL_STOPPED",t.CLIP_STARTED="CORNERSTONE_CINE_TOOL_STARTED"})(_0||(_0={}));const q4={};function dU(t,e){const r=Ce(t),{viewportId:n}=r;q4[n]=e}function X4(t){const e=Ce(t),{viewportId:r}=e;return q4[r]}function fve(t){return q4[t]}const{ViewportStatus:hU}=ja,{triggerEvent:h3}=Mn,gU=!0,LC=new Map;function dve(t,e){let r,n;if(t===void 0)throw new Error("playClip: element must not be undefined");const i=Ce(t);if(!i)throw new Error("playClip: element must be a valid Cornerstone enabled element");e||(e={}),e.dynamicCineEnabled=e.dynamicCineEnabled??!0;const{viewport:o}=i,a=yve(o,e);let s=X4(t);const c=e.dynamicCineEnabled;if(c&&mU(t),s?AC(t,{stopDynamicCine:!c,viewportId:o.id}):(s={intervalId:void 0,framesPerSecond:30,lastFrameTimeStamp:void 0,ignoreFrameTimeVector:!1,usingFrameTimeVector:!1,frameTimeVector:e.frameTimeVector??void 0,speed:e.frameTimeVectorSpeedMultiplier??1,reverse:e.reverse??!1,loop:e.loop??!0,bounce:e.bounce??!1},dU(t,s)),s.dynamicCineEnabled=e.dynamicCineEnabled,(e.framesPerSecond<0||e.framesPerSecond>0)&&(s.framesPerSecond=Number(e.framesPerSecond),s.reverse=s.framesPerSecond<0,s.ignoreFrameTimeVector=!0),s.ignoreFrameTimeVector!==!0&&s.frameTimeVector&&s.frameTimeVector.length===a.numScrollSteps&&a.frameTimeVectorEnabled){const{timeouts:u,isTimeVarying:d}=hve(s.frameTimeVector,s.speed);r=u,n=d}e.bounce!==void 0&&(s.bounce=e.bounce);const l=()=>{const{numScrollSteps:u,currentStepIndex:d}=a;let h=d+(s.reverse?-1:1);if(h<0||h>=u)if(s.bounce)s.reverse=!s.reverse,h=d+(s.reverse?-1:1),h=Math.max(0,Math.min(u-1,h));else if(s.loop)h=s.reverse?u-1:0;else{AC(t,{stopDynamicCine:!c,viewportId:o.id}),h3(t,_0.CLIP_STOPPED,{element:t});return}const p=h-d;if(p)try{a.scroll(p)}catch(v){console.warn("Play clip not scrolling",v),vU(s),h3(t,_0.CLIP_STOPPED,{element:t})}};if(c){const u=Y4(o);u&&LC.set(u.volumeId,t)}a.play?s.framesPerSecond=a.play(e.framesPerSecond):r&&r.length>0&&n?(s.usingFrameTimeVector=!0,s.intervalId=window.setTimeout(function u(){s.intervalId=window.setTimeout(u,r[a.currentStepIndex]),l()},0)):(s.usingFrameTimeVector=!1,s.intervalId=window.setInterval(l,1e3/Math.abs(s.framesPerSecond)));const f={element:t};h3(t,_0.CLIP_STARTED,f)}function pU(t,e={}){AC(t,{stopDynamicCine:!0,...e})}function AC(t,e={stopDynamicCine:!0,viewportId:void 0}){const{stopDynamicCine:r,viewportId:n}=e,i=Ce(t);let o;const a=i==null?void 0:i.viewport;if(i){const{viewport:s}=i;o=X4(s.element)}else if(n)o=fve(n);else return;o&&vU(o),a instanceof Rp?a.pause():r&&a instanceof Ir&&mU(t)}function mU(t){const{viewport:e}=Ce(t);if(e instanceof ur){const r=Y4(e);if(r!=null&&r.isDynamicVolume()){const n=LC.get(r.volumeId);LC.delete(r.volumeId),n&&n!==t&&pU(n)}}}function hve(t,e){let r,n,i,o=0;const a=t.length,s=[];let c=!1;for((typeof e!="number"||e<=0)&&(e=1),r=1;r0&&(c?i=o/s.length|0:i=s[0],s.push(i)),{timeouts:s,isTimeVarying:c}}function vU(t){const e=t.intervalId;typeof e<"u"&&(t.intervalId=void 0,t.usingFrameTimeVector?clearTimeout(e):clearInterval(e))}function Y4(t){if(!(t instanceof ur))return;const e=t.getAllVolumeIds();if(!(e!=null&&e.length))return;const n=e.find(i=>{var o;return(o=Le.getVolume(i))==null?void 0:o.isDynamicVolume()})??e[0];return Le.getVolume(n)}function gve(t,e){const r=t.getImageIds();return{get numScrollSteps(){return r.length},get currentStepIndex(){return t.getTargetImageIdIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(n){if(this.waitForRenderedCount<=e&&t.viewportStatus!==hU.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,ps(t,{delta:n,debounceLoading:gU})}}}function pve(t,e){return{get numScrollSteps(){return t.getNumberOfSlices()},get currentStepIndex(){return t.getSliceIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(r){if(this.waitForRenderedCount<=e&&t.viewportStatus!==hU.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,ps(t,{delta:r,debounceLoading:gU})},play(r){return r&&t.setPlaybackRate(r/24),t.play(),t.getFrameRate()}}}function mve(t,e){const{volumeId:r}=e,n={viewPlaneNormal:Ve(),scrollInfo:null},i=()=>{const o=t.getCamera();if(!n.scrollInfo||!Bx(o.viewPlaneNormal,n.viewPlaneNormal)){const s=Vf(t,r);n.viewPlaneNormal=o.viewPlaneNormal,n.scrollInfo=s}return n.scrollInfo};return{get numScrollSteps(){return i().numScrollSteps},get currentStepIndex(){return i().currentStepIndex},get frameTimeVectorEnabled(){const o=t.getCamera(),a=e.direction.slice(6,9).map(c=>-c),s=Et(a,o.viewPlaneNormal);return vu(s,1)},scroll(o){i().currentStepIndex+=o,ps(t,{delta:o})}}}function vve(t){return{get numScrollSteps(){return t.numDimensionGroups},get currentStepIndex(){return t.dimensionGroupNumber-1},get frameTimeVectorEnabled(){return!1},scroll(e){t.scroll(e)}}}function yve(t,e){if(t instanceof lr)return gve(t,e.waitForRendered??30);if(t instanceof ur){const r=Y4(t);return e.dynamicCineEnabled&&(r!=null&&r.isDynamicVolume())?vve(r):mve(t,r)}if(t instanceof Rp)return pve(t,e.waitForRendered??30);throw new Error("Unknown viewport type")}const wve=Object.freeze(Object.defineProperty({__proto__:null,Events:_0,addToolState:dU,getToolState:X4,playClip:dve,stopClip:pU},Symbol.toStringTag,{value:"Module"}));function xve(t,e){var n,i,o;const r=(e==null?void 0:e.knotsRatioPercentage)||30;return!((o=(i=(n=t==null?void 0:t.data)==null?void 0:n.contour)==null?void 0:i.polyline)!=null&&o.length)||r<=0}function Cve(t,e){const r=Zo(),n=Ai(Ve(),e,t),i=Math.abs(t[0])>.1?bt(-t[1],t[0],0):bt(0,-t[2],t[1]);return A_(r,e,n,i),r}function Gm(t,e=Math.floor(Math.random()*(t.length-1))){if(e===0)return 0;const r=[...t],{length:n}=t;for(let i=0;i{const u=Jt(Ve(),f,o);return[u[0],u[1]]});let s=n?Gm(a):0,c=TC(a,0,a.length,(e==null?void 0:e.knotsRatioPercentage)||30);if(c===a)return!1;Gm(c,-s);for(let f=1;f<(e==null?void 0:e.loop);f++)s=n?Gm(c):0,c=TC(c,0,a.length,(e==null?void 0:e.knotsRatioPercentage)||30),Gm(c,-s);const l=oi(Zo(),o);return t.data.contour.polyline=c.map(f=>Jt([0,0,0],[...f,0],l)),!0}const Sve={smoothAnnotation:yU},_ve=Object.freeze(Object.defineProperty({__proto__:null,default:Sve,smoothAnnotation:yU},Symbol.toStringTag,{value:"Module"})),Tve=Object.freeze(Object.defineProperty({__proto__:null,getBoundsIJKFromRectangleAnnotations:AF,isAxisAlignedRectangle:XF},Symbol.toStringTag,{value:"Module"})),wU={};function xU(t,e){const r=Ce(t),{viewportId:n}=r;wU[n]=e}function Eh(t){const e=Ce(t),{viewportId:r}=e;return wU[r]}const Bf=hn.Prefetch,CU=0;function Eve(t,e){t=Math.round(t)||0,e=Math.round(e)||0;const r=[];let n=e-t+1;if(n<=0)return r;for(;n--;)r[n]=e--;return r}function Dve(t,e){let r=0,n=t.length-1;return t.forEach((i,o)=>{ie&&(n=Math.min(o,n))}),{low:r,high:n}}function Dh(t){const e=Ce(t);if(!e)return null;const{viewport:r}=e;return r instanceof lr?{currentImageIdIndex:r.getCurrentImageIdIndex(),imageIds:r.getImageIds()}:null}function j5(t){return function(e){const r=e.detail;let n;try{n=Dh(t)}catch{return}if(!n||!n.imageIds||n.imageIds.length===0)return;const o=n.imageIds.indexOf(r.imageId);if(o<0)return;const a=Eh(t);!a||!a.indicesToRequest||!a.indicesToRequest.length||a.indicesToRequest.push(o)}}const bve=t=>{const e=new Set(t.imageIds);return r=>r.type!==Bf||!e.has(r.additionalDetails.imageId)};let jg={maxImagesToPrefetch:1/0,preserveExistingPool:!0},NC;const Ive=10;function SU(t){var g,p;const e=Eh(t);if(!e)return;const r=e||{},n=Dh(t);if(!((g=n==null?void 0:n.imageIds)!=null&&g.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:i}=n;if(r.enabled=r.enabled&&(((p=r.indicesToRequest)==null?void 0:p.length)??0)>0,r.enabled===!1)return;function o(v){const y=r.indicesToRequest.indexOf(v);y>-1&&r.indicesToRequest.splice(y,1)}if(e.indicesToRequest.sort((v,y)=>v-y),r.indicesToRequest.slice().forEach(function(v){const y=n.imageIds[v];if(!y)return;(Math.abs(i-v)<6?Le.getImageLoadObject(y):Le.isLoaded(y))&&o(v)}),!r.indicesToRequest.length)return;jg.preserveExistingPool||Ao.clearRequestStack(Bf);const s=Dve(r.indicesToRequest,n.currentImageIdIndex);let c,l,f=s.low,u=s.high;const d=[];for(;f>=0||ujg.maxImagesToPrefetch,m=r.indicesToRequest[u]-v>jg.maxImagesToPrefetch,w=!y&&f>=0,x=!m&&uxu(v,y);d.forEach(v=>{const y={requestType:Bf};Ao.addRequest(h.bind(null,v,y),Bf,{imageId:v},CU)})}function kC(t){clearTimeout(NC),NC=setTimeout(function(){const e=t.target;try{SU(e)}catch{return}},Ive)}function Ove(t){const e=Dh(t);if(!e||!e.imageIds||e.imageIds.length===0){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const r={indicesToRequest:Eve(0,e.imageIds.length-1),enabled:!0,direction:1},n=r.indicesToRequest.indexOf(e.currentImageIdIndex);r.indicesToRequest.splice(n,1),xU(t,r),SU(t),t.removeEventListener(Xe.STACK_NEW_IMAGE,kC),t.addEventListener(Xe.STACK_NEW_IMAGE,kC);const i=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,i),Ke.addEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,i)}function Mve(t){clearTimeout(NC),t.removeEventListener(Xe.STACK_NEW_IMAGE,kC);const e=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,e);const r=Eh(t);r&&r.indicesToRequest.length&&(r.enabled=!1,Ao.clearRequestStack(Bf))}function Pve(){return jg}function Rve(t){jg=t}const Lve={enable:Ove,disable:Mve,getConfiguration:Pve,setConfiguration:Rve};let qp={maxImagesToPrefetch:1/0,minBefore:2,maxAfter:2,directionExtraImages:10,preserveExistingPool:!1},VC;const Ave=5,Nve=t=>{var n;const e=Dh(t);if(!e)return;if(!((n=e.imageIds)!=null&&n.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}Z4(t),J4(t),t.removeEventListener(Xe.STACK_NEW_IMAGE,FC),t.addEventListener(Xe.STACK_NEW_IMAGE,FC);const r=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,r),Ke.addEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,r)};function J4(t){var l,f;const e=Dh(t);if(!e)return;if(!((l=e==null?void 0:e.imageIds)!=null&&l.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const r=Eh(t);if(!r)return;const n=r||{};if(n.enabled=n.enabled&&(((f=n.indicesToRequest)==null?void 0:f.length)??0)>0,n.enabled===!1)return;function i(u){const d=n.indicesToRequest.indexOf(u);d>-1&&n.indicesToRequest.splice(d,1)}const o=n.indicesToRequest.slice(),{currentImageIdIndex:a}=e;if(o.forEach(u=>{const d=e.imageIds[u];if(!d)return;(Math.abs(a-u)<6?Le.getImageLoadObject(d):Le.isLoaded(d))&&i(u)}),!n.indicesToRequest.length)return;qp.preserveExistingPool||Ao.filterRequests(bve(e));function s(u){var v,y;const d=e.imageIds.indexOf(u);i(d);const h=Le.getCachedImageBasedOnImageURI(u),{stats:g}=n,p=((v=h==null?void 0:h.image)==null?void 0:v.decodeTimeInMS)||0;if(p){g.imageIds.set(u,p),g.decodeTimeInMS+=p;const m=((y=h==null?void 0:h.image)==null?void 0:y.loadTimeInMS)||0;g.loadTimeInMS+=m}if(!n.indicesToRequest.length&&h!=null&&h.sizeInBytes){const{sizeInBytes:m}=h,w=Le.getMaxCacheSize()/4/m;if(!n.cacheFill)g.initialTime=Date.now()-g.start,g.initialSize=g.imageIds.size,Z4(t,w),J4(t);else if(g.imageIds.size){g.fillTime=Date.now()-g.start;const{size:x}=g.imageIds;g.fillSize=x}}}const c=(u,d)=>xu(u,d).then(()=>s(u));n.indicesToRequest.forEach(u=>{const d=e.imageIds[u],h={requestType:Bf};Ao.addRequest(c.bind(null,d,h),Bf,{imageId:d},CU)})}function FC(t){clearTimeout(VC),VC=setTimeout(function(){const e=t.target;try{Z4(e),J4(e)}catch{return}},Ave)}const kve=t=>t<0?-1:1,Z4=(t,e)=>{var d;const r=Dh(t);if(!r)return;if(!((d=r.imageIds)!=null&&d.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:n}=r;let{maxAfter:i=2,minBefore:o=2}=qp;const{directionExtraImages:a=10}=qp,s=Eh(t)||{indicesToRequest:[],currentImageIdIndex:n,stackCount:0,enabled:!0,direction:1,stats:{start:Date.now(),imageIds:new Map,decodeTimeInMS:0,loadTimeInMS:0,totalBytes:0}},c=n-s.currentImageIdIndex;if(s.direction=kve(c),s.currentImageIdIndex=n,s.enabled=!0,s.stackCount<100&&(s.stackCount+=a),Math.abs(c)>i||!c)if(s.stackCount=0,e){const h=n/r.imageIds.length;o=Math.ceil(e*h),i=Math.ceil(e*(1-h)),s.cacheFill=!0}else s.cacheFill=!1;else c<0?(o+=s.stackCount,i=0):(i+=s.stackCount,o=0);const l=Math.max(0,n-o),f=Math.min(r.imageIds.length-1,n+i),u=[];for(let h=n+1;h<=f;h++)u.push(h);for(let h=n-1;h>=l;h--)u.push(h);s.indicesToRequest=u,xU(t,s)};function Vve(t){clearTimeout(VC),t.removeEventListener(Xe.STACK_NEW_IMAGE,FC);const e=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,e);const r=Eh(t);r&&(r.enabled=!1)}function Fve(){return qp}function Uve(t){qp=t}const Bve={enable:Nve,disable:Vve,getConfiguration:Fve,setConfiguration:Uve},Gve=Object.freeze(Object.defineProperty({__proto__:null,isViewportPreScaled:al},Symbol.toStringTag,{value:"Module"}));function Wve(t,e){let r;const n=e.dimensionGroupNumbers||e.frameNumbers||Array.from({length:t.numDimensionGroups},(i,o)=>o+1);if(e.frameNumbers&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead."),!e.maskVolumeId&&!e.worldCoordinate)throw new Error("You should provide either maskVolumeId or imageCoordinate");if(e.maskVolumeId&&e.worldCoordinate)throw new Error("You can only use one of maskVolumeId or imageCoordinate");if(e.maskVolumeId){const i=Le.getVolume(e.maskVolumeId);if(!i)throw new Error("Segmentation volume not found");const[o,a]=$ve(n,t,i);return[o,a]}return e.worldCoordinate?zve(n,e.worldCoordinate,t):r}function zve(t,e,r){const{dimensions:n,imageData:i}=r,o=i.worldToIndex(e);if(o[0]=Math.floor(o[0]),o[1]=Math.floor(o[1]),o[2]=Math.floor(o[2]),!sr(o,n))throw new Error("outside bounds");const a=n[0],s=n[0]*n[1],c=[];return t.forEach(l=>{const f=o[2]*s+o[1]*a+o[0];c.push(r.voxelManager.getAtIndexAndDimensionGroup(f,l))}),c}function $ve(t,e,r){const{imageData:n}=r,i=r.voxelManager,o=i.getScalarDataLength(),a=[];a.length=o;let s=0;for(let d=0,h=o;d{if(h===0)return;const p=ZT(e.imageData,e.dimensions,e.spacing,d);let v=0;const y=new Map;t.forEach(x=>y.set(x,0));const m=({index:x})=>{for(let C=0;C{w.push(x/v)}),f.push(g),c.push(w)};return r.voxelManager.forEach(u,{imageData:n}),[c,f]}function _U(t,e){const r=t.getScalarDataLength(),n=new Float32Array(r);for(const i of e){const o=t.getDimensionGroupScalarData(i);for(let a=0;a{const n=_U(t,e);for(let i=0;i{const n=jve(t,e);for(let i=0;i{if(e.length!==2)throw new Error("Please provide only 2 dimension groups for subtraction.");const n=t.getScalarDataLength(),i=t.getDimensionGroupScalarData(e[0]),o=t.getDimensionGroupScalarData(e[1]);for(let a=0;au+1);if(o.length<=1)throw new Error("Please provide two or more dimension groups");const a=t.voxelManager,s=a.getScalarDataLength(),c=TU[e];if(!c)throw new Error(`Unsupported operation: ${e}`);const l=new Float32Array(s);return c(a,o,(f,u)=>{l[f]=u}),l}function Kve(t,e,r){const{dimensionGroupNumbers:n,frameNumbers:i,targetVolume:o}=r;if(!o)throw new Error("A target volume must be provided");i&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead.");const a=n||i||Array.from({length:t.numDimensionGroups},(f,u)=>u+1);if(a.length<=1)throw new Error("Please provide two or more dimension groups");const s=t.voxelManager,c=o.voxelManager,l=TU[e];if(!l)throw new Error(`Unsupported operation: ${e}`);l(s,a,(f,u)=>{c.setAtIndex(f,u)}),c.resetModifiedSlices();for(let f=0;f{for(const[c,l]of s.entries())if(l!==void 0)return c;return-1};let a=o(n);for(;a!==-1;){const s=[a];for(;n.has(a);){const c=n.get(a)[1];n.has(c)&&s.push(c),n.delete(a),a=c}i.push(s),a=o(n)}return i.length?i:void 0}function bU(t){const e=DU(t);if(!e)return;const r=t.getPoints().getData();return e.map(n=>n.map(i=>EU(r,i)))}const Xve=Object.freeze(Object.defineProperty({__proto__:null,getPoint:EU,getPolyDataPointIndexes:DU,getPolyDataPoints:bU},Symbol.toStringTag,{value:"Module"}));var pa;(function(t){t.Top="top",t.Left="left",t.Bottom="bottom",t.Right="right"})(pa||(pa={}));const Yve=Object.freeze(Object.defineProperty({__proto__:null,get ColorbarRangeTextPosition(){return pa}},Symbol.toStringTag,{value:"Module"})),Vc=t=>t&&t.upper>t.lower,fy=t=>!!t&&t.width>0&&t.height>0,Xp=(t,e)=>!!t&&!!e&&t.lower===e.lower&&t.upper===e.upper,IU=(t,e)=>!!t&&!!e&&t.width===e.width&&t.height===e.height,Jve=(t,e,r)=>[t[0]*(1-r)+e[0]*r,t[1]*(1-r)+e[1]*r,t[2]*(1-r)+e[2]*r],{clamp:Zve}=Mn;class Q4{constructor(e){Q4.validateProps(e);const{colormap:r,size:n={width:20,height:100},imageRange:i={lower:0,upper:1},voiRange:o={lower:0,upper:1},container:a,showFullPixelValueRange:s=!1}=e;this._colormap=r,this._imageRange=i,this._voiRange=o,this._showFullImageRange=s,this._canvas=this._createRootElement(n),a&&this.appendTo(a)}get colormap(){return this._colormap}set colormap(e){this._colormap=e,this.render()}get size(){const{width:e,height:r}=this._canvas;return{width:e,height:r}}set size(e){const{_canvas:r}=this;!fy(e)||IU(r,e)||(this._setCanvasSize(r,e),this.render())}get imageRange(){return{...this._imageRange}}set imageRange(e){!Vc(e)||Xp(e,this._imageRange)||(this._imageRange=e,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(e){!Vc(e)||Xp(e,this._voiRange)||(this._voiRange=e,this.render())}get showFullImageRange(){return this._showFullImageRange}set showFullImageRange(e){e!==this._showFullImageRange&&(this._showFullImageRange=e,this.render())}appendTo(e){e.appendChild(this._canvas),this.render()}dispose(){const{_canvas:e}=this,{parentElement:r}=e;r==null||r.removeChild(e)}static validateProps(e){const{size:r,imageRange:n,voiRange:i}=e;if(r&&!fy(r))throw new Error('Invalid "size"');if(n&&!Vc(n))throw new Error('Invalid "imageRange"');if(i&&!Vc(i))throw new Error('Invalid "voiRange"')}_setCanvasSize(e,r){const{width:n,height:i}=r;e.width=n,e.height=i,Object.assign(e.style,{width:`${n}px`,height:`${i}px`})}_createRootElement(e){const r=document.createElement("canvas");return Object.assign(r.style,{position:"absolute",top:"0",left:"0",pointerEvents:"none",boxSizing:"border-box"}),this._setCanvasSize(r,e),r}render(){if(!this._canvas.isConnected)return;const{_colormap:e}=this,{RGBPoints:r}=e,n=r.length/4,i=v=>{const y=4*v;if(!(v<0||v>=n))return{index:v,position:r[y],color:[r[y+1],r[y+2],r[y+3]]}},{width:o,height:a}=this._canvas,s=this._canvas.getContext("2d");if(!s)return;const c=o>a,l=c?o:a,{_voiRange:f}=this,u=this._showFullImageRange?this._imageRange:{...f};let d,h=i(0);const g=(u.upper-u.lower)/(l-1);let p=u.lower;for(let v=0;vZve(Math.round(x*255),0,255));s.fillStyle=`rgb(${w[0]}, ${w[1]}, ${w[2]})`,c?s.fillRect(v,0,1,a):s.fillRect(0,a-v-1,o,1),p+=g}}}const pf={FONT:"10px Arial",COLOR:"white",TICK_SIZE:5,TICK_WIDTH:1,TICK_LABEL_MARGIN:3,MAX_NUM_TICKS:8,TICKS_STEPS:[1,2.5,5,10]};class eE{constructor(e){eE.validateProps(e);const{top:r=0,left:n=0,size:i={width:20,height:100},imageRange:o={lower:0,upper:1},voiRange:a={lower:0,upper:1},ticks:s,container:c,showFullPixelValueRange:l=!1}=e,{style:f,position:u}=s??{};this._imageRange=o,this._voiRange=a,this._font=(f==null?void 0:f.font)??pf.FONT,this._color=(f==null?void 0:f.color)??pf.COLOR,this._tickSize=(f==null?void 0:f.tickSize)??pf.TICK_SIZE,this._tickWidth=(f==null?void 0:f.tickWidth)??pf.TICK_WIDTH,this._labelMargin=(f==null?void 0:f.labelMargin)??pf.TICK_LABEL_MARGIN,this._maxNumTicks=(f==null?void 0:f.maxNumTicks)??pf.MAX_NUM_TICKS,this._rangeTextPosition=u??pa.Right,this._showFullPixelValueRange=l,this._canvas=this._createCanvasElement(i,r,n),c&&this.appendTo(c)}get size(){const{width:e,height:r}=this._canvas;return{width:e,height:r}}set size(e){const{_canvas:r}=this;!fy(e)||IU(r,e)||(this._setCanvasSize(r,e),this.render())}get top(){return Number.parseInt(this._canvas.style.top)}set top(e){const{_canvas:r}=this,n=this.top;e!==n&&(r.style.top=`${e}px`,this.render())}get left(){return Number.parseInt(this._canvas.style.left)}set left(e){const{_canvas:r}=this,n=this.left;e!==n&&(r.style.left=`${e}px`,this.render())}get imageRange(){return{...this._imageRange}}set imageRange(e){!Vc(e)||Xp(e,this._imageRange)||(this._imageRange=e,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(e){!Vc(e)||Xp(e,this._voiRange)||(this._voiRange=e,this.render())}get tickSize(){return this._tickSize}set tickSize(e){e!==this._tickSize&&(this._tickSize=e,this.render())}get tickWidth(){return this._tickWidth}set tickWidth(e){e!==this._tickWidth&&(this._tickWidth=e,this.render())}get color(){return this._color}set color(e){e!==this._color&&(this._color=e,this.render())}get showFullPixelValueRange(){return this._showFullPixelValueRange}set showFullPixelValueRange(e){e!==this._showFullPixelValueRange&&(this._showFullPixelValueRange=e,this.render())}get visible(){return this._canvas.style.display==="block"}set visible(e){e!==this.visible&&(this._canvas.style.display=e?"block":"none",e&&this.render())}appendTo(e){e.appendChild(this._canvas),this.render()}static validateProps(e){const{size:r,imageRange:n,voiRange:i}=e;if(r&&!fy(r))throw new Error('Invalid "size"');if(n&&!Vc(n))throw new Error('Invalid "imageRange"');if(i&&!Vc(i))throw new Error('Invalid "voiRange"')}_setCanvasSize(e,r){const{width:n,height:i}=r;e.width=n,e.height=i,Object.assign(e.style,{width:`${n}px`,height:`${i}px`})}_createCanvasElement(e,r,n){const i=document.createElement("canvas");return Object.assign(i.style,{display:"none",position:"absolute",boxSizing:"border-box",top:`${r}px`,left:`${n}px`}),this._setCanvasSize(i,e),i}_getTicks(e){const{lower:r,upper:n}=e,o=(n-r)/(this._maxNumTicks-1),a=Math.pow(10,-Math.floor(Math.log10(Math.abs(o)))),s=o*a,l=pf.TICKS_STEPS.find(g=>g>=s)/a,f=Math.ceil(n/l)*l,u=Math.floor(r/l)*l,d=Math.round((f-u)/l)+1,h=[];for(let g=0;g=n,o=i?r:n,a=e.getContext("2d"),{_voiRange:s}=this,c=this._showFullPixelValueRange?this._imageRange:{...s},l=c.upper-c.lower,{ticks:f}=this._getTicks(c);a.clearRect(0,0,r,n),a.font=this._font,a.textBaseline=i?"top":"middle",a.textAlign=i?"center":"left",a.fillStyle=this._color,a.strokeStyle=this._color,a.lineWidth=this.tickWidth,f.forEach(u=>{let d=Math.round(o*((u-c.lower)/l));if(i||(d=n-d),d<0||d>o)return;const h=u.toString(),g=a.measureText(h);let p;i?this._rangeTextPosition===pa.Top?p=this._getTopTickInfo({position:d,labelMeasure:g}):p=this._getBottomTickInfo({position:d,labelMeasure:g}):this._rangeTextPosition===pa.Left?p=this._getLeftTickInfo({position:d,labelMeasure:g}):p=this._getRightTickInfo({position:d});const{labelPoint:v,tickPoints:y}=p,{start:m,end:w}=y;return a.beginPath(),a.moveTo(m[0],m[1]),a.lineTo(w[0],w[1]),a.fillText(h,v[0],v[1]),a.stroke(),d})}}function Qve(t,e,r){return(t>=e?[pa.Top,pa.Bottom]:[pa.Left,pa.Right]).includes(r)}class eye{constructor({id:e,container:r}){this._containerResizeCallback=n=>{let i,o;const{contentRect:a,contentBoxSize:s}=n[0];a?(i=a.width,o=a.height):s!=null&&s.length&&(i=s[0].inlineSize,o=s[0].blockSize),this._containerSize={width:i,height:o},this.onContainerResize()},this._id=e,this._containerSize={width:0,height:0},this._rootElement=this.createRootElement(e),this._containerResizeObserver=new ResizeObserver(this._containerResizeCallback),r&&this.appendTo(r)}get id(){return this._id}get rootElement(){return this._rootElement}appendTo(e){const{_rootElement:r,_containerResizeObserver:n}=this,{parentElement:i}=r;!e||e===i||(i&&n.unobserve(i),e.appendChild(r),n.observe(e))}destroy(){const{_rootElement:e,_containerResizeObserver:r}=this,{parentElement:n}=e;n==null||n.removeChild(e),r.disconnect()}get containerSize(){return{...this._containerSize}}createRootElement(e){const r=document.createElement("div");return r.id=e,r.classList.add("widget"),Object.assign(r.style,{width:"100%",height:"100%"}),r}onContainerResize(){}}const Qh={MULTIPLIER:1,RANGE_TEXT_POSITION:pa.Right,TICKS_BAR_SIZE:50};class Yp extends eye{constructor(e){var r;super(e),this._isMouseOver=!1,this._isInteracting=!1,this._mouseOverCallback=n=>{this._isMouseOver=!0,this.showTicks(),n.stopPropagation()},this._mouseOutCallback=n=>{this._isMouseOver=!1,this.hideTicks(),n.stopPropagation()},this._mouseDownCallback=n=>{this._isInteracting=!0,this.showTicks(),this._addVOIEventListeners(n),n.stopPropagation()},this._mouseDragCallback=(n,i)=>{const o=this.getVOIMultipliers(),a=this._getPointsFromMouseEvent(n),{points:s,voiRange:c}=i,l=Ga(qt(),a.local,s.local),f=l[0]*o[0],u=l[1]*o[1];if(!f&&!u)return;const{lower:d,upper:h}=c;let{windowWidth:g,windowCenter:p}=m1(d,h);g=Math.max(g+f,1),p+=u;const v=lu(g,p);this.voiRange=v,n.stopPropagation(),n.preventDefault()},this._mouseUpCallback=n=>{this._isInteracting=!1,this.hideTicks(),this._removeVOIEventListeners(),n.stopPropagation()},this._eventListenersManager=new FA,this._colormaps=Yp.getColormapsMap(e),this._activeColormapName=Yp.getInitialColormapName(e),this._canvas=this._createCanvas(e),this._ticksBar=this._createTicksBar(e),this._rangeTextPosition=((r=e.ticks)==null?void 0:r.position)??Qh.RANGE_TEXT_POSITION,this._canvas.appendTo(this.rootElement),this._ticksBar.appendTo(this.rootElement),this._addRootElementEventListeners()}get activeColormapName(){return this._activeColormapName}set activeColormapName(e){if(e===this._activeColormapName)return;const r=this._colormaps.get(e);if(!r){console.warn(`Invalid colormap name (${e})`);return}this._activeColormapName=e,this._canvas.colormap=r}get imageRange(){return this._canvas.imageRange}set imageRange(e){this._canvas.imageRange=e,this._ticksBar.imageRange=e}get voiRange(){return this._canvas.voiRange}set voiRange(e){const{voiRange:r}=this._canvas;!Vc(e)||Xp(e,r)||(this._canvas.voiRange=e,this._ticksBar.voiRange=e,this.onVoiChange(e))}get showFullImageRange(){return this._canvas.showFullImageRange}set showFullImageRange(e){this._canvas.showFullImageRange=e,this._ticksBar.showFullPixelValueRange=e}destroy(){super.destroy(),this._eventListenersManager.reset()}createRootElement(){const e=document.createElement("div");return Object.assign(e.style,{position:"relative",fontSize:"0",width:"100%",height:"100%"}),e}onContainerResize(){super.onContainerResize(),this.updateTicksBar(),this._canvas.size=this.containerSize}getVOIMultipliers(){return[Qh.MULTIPLIER,Qh.MULTIPLIER]}onVoiChange(e){}showTicks(){this.updateTicksBar(),this._ticksBar.visible=!0}hideTicks(){this._isInteracting||this._isMouseOver||(this._ticksBar.visible=!1)}static getColormapsMap(e){const{colormaps:r}=e;return r.reduce((n,i)=>n.set(i.Name,i),new Map)}static getInitialColormapName(e){const{activeColormapName:r,colormaps:n}=e;return!!r&&n.some(o=>o.Name===r)?r:n[0].Name}_createCanvas(e){const{imageRange:r,voiRange:n,showFullPixelValueRange:i}=e,o=this._colormaps.get(this._activeColormapName);return new Q4({colormap:o,imageRange:r,voiRange:n,showFullPixelValueRange:i})}_createTicksBar(e){const r=e.ticks;return new eE({imageRange:e.imageRange,voiRange:e.voiRange,ticks:r,showFullPixelValueRange:e.showFullPixelValueRange})}_getPointsFromMouseEvent(e){const{rootElement:r}=this,n=[e.clientX,e.clientY],i=[e.pageX,e.pageY],o=r.getBoundingClientRect(),a=[i[0]-o.left-window.pageXOffset,i[1]-o.top-window.pageYOffset];return{client:n,page:i,local:a}}updateTicksBar(){const{width:e,height:r}=this.containerSize;if(e===0&&r===0)return;const{_ticksBar:n,_rangeTextPosition:i}=this,o=e>=r,a=o?e:Qh.TICKS_BAR_SIZE,s=o?Qh.TICKS_BAR_SIZE:r;if(!Qve(e,r,i))throw new Error("Invalid rangeTextPosition value for the current colobar orientation");let c,l;n.size={width:a,height:s},o?(l=0,c=i===pa.Top?-s:r):(c=0,l=i===pa.Left?-a:e),n.top=c,n.left=l}_addRootElementEventListeners(){const{_eventListenersManager:e}=this,{rootElement:r}=this;e.addEventListener(r,"mouseover",this._mouseOverCallback),e.addEventListener(r,"mouseout",this._mouseOutCallback),e.addEventListener(r,"mousedown",this._mouseDownCallback)}_addVOIEventListeners(e){const{_eventListenersManager:r}=this,n=this._getPointsFromMouseEvent(e),i={...this._canvas.voiRange},o={points:n,voiRange:i};this._removeVOIEventListeners(),r.addEventListener(document,"voi.mouseup",this._mouseUpCallback),r.addEventListener(document,"voi.mousemove",a=>this._mouseDragCallback(a,o))}_removeVOIEventListeners(){const{_eventListenersManager:e}=this;e.removeEventListener(document,"voi.mouseup"),e.removeEventListener(document,"voi.mousemove")}}const g3=4;function tye(t,e,r){if(ZA(t,e)==="PT"){const{clientWidth:i,clientHeight:o}=t.element,a=5/Math.max(i,o),s=al(t,e),{fixedPTWindowWidth:c=!0}=r??{},l=c?0:a;return s?[l,a]:[l,g3]}return[g3,g3]}const{Events:Rl}=ja,Wm={lower:-1e3,upper:1e3};class Xd extends Yp{constructor(e){const{element:r,volumeId:n}=e,i=Xd._getImageRange(r,n),o=Xd._getVOIRange(r,n);super({...e,imageRange:i,voiRange:o}),this.autoHideTicks=()=>{if(this._hideTicksTimeoutId)return;const a=this._hideTicksTime-Date.now();a<=0?this.hideTicks():this._hideTicksTimeoutId=window.setTimeout(()=>{this._hideTicksTimeoutId=0,this.autoHideTicks()},a)},this._stackNewImageCallback=()=>{this.imageRange=Xd._getImageRange(this._element)},this._imageVolumeModifiedCallback=a=>{const{volumeId:s}=a.detail;if(s!==this._volumeId)return;const{_element:c}=this;this.imageRange=Xd._getImageRange(c,s)},this._viewportVOIModifiedCallback=a=>{const{viewportId:s,volumeId:c,range:l,colormap:f}=a.detail,{viewport:u}=this.enabledElement;s!==u.id||c!==this._volumeId||(this.voiRange=l,f&&(this.activeColormapName=f.name),this.showAndAutoHideTicks())},this._viewportColormapModifiedCallback=a=>{const{viewportId:s,colormap:c,volumeId:l}=a.detail,{viewport:f}=this.enabledElement;s!==f.id||l!==this._volumeId||(this.activeColormapName=c.name)},this._element=r,this._volumeId=n,this._addCornerstoneEventListener()}get element(){return this._element}get enabledElement(){return Ce(this._element)}getVOIMultipliers(){const{viewport:e}=this.enabledElement;return tye(e,this._volumeId)}onVoiChange(e){super.onVoiChange(e);const{viewport:r}=this.enabledElement;if(r instanceof lr)r.setProperties({voiRange:e}),r.render();else if(r instanceof ur){const{_volumeId:n}=this,i=y1(n);r.setProperties({voiRange:e},n),i.forEach(o=>o.render())}}static _getImageRange(e,r){const n=Ce(e),{viewport:i}=n,o=i.getImageActor(r);if(!o)return Wm;const s=o.getMapper().getInputData().getPointData().getScalars();let c;if(s)c=s.getRange();else{if(!r)throw new Error("volumeId is required when scalarData is not available");const l=Le.getVolume(r),[f,u]=l.voxelManager.getRange();c=[f,u]}return c[0]===0&&c[1]===0?Wm:{lower:c[0],upper:c[1]}}static _getVOIRange(e,r){const n=Ce(e),{viewport:i}=n,o=i.getImageActor(r);if(!o)return Wm;const a=o.getProperty().getRGBTransferFunction(0).getRange();return a[0]===0&&a[1]===0?Wm:{lower:a[0],upper:a[1]}}showAndAutoHideTicks(e=1e3){this._hideTicksTime=Date.now()+e,this.showTicks(),this.autoHideTicks()}_addCornerstoneEventListener(){const{_element:e}=this;Ke.addEventListener(Rl.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),e.addEventListener(Rl.STACK_NEW_IMAGE,this._stackNewImageCallback),e.addEventListener(Rl.VOI_MODIFIED,this._viewportVOIModifiedCallback),e.addEventListener(Rl.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}destroy(){super.destroy();const{_element:e}=this;Ke.removeEventListener(Rl.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),e.removeEventListener(Rl.STACK_NEW_IMAGE,this._stackNewImageCallback),e.removeEventListener(Rl.VOI_MODIFIED,this._viewportVOIModifiedCallback),e.removeEventListener(Rl.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}}const nye=Object.freeze(Object.defineProperty({__proto__:null,Colorbar:Yp,Enums:Yve,ViewportColorbar:Xd},Symbol.toStringTag,{value:"Module"}));function OU(t,e,r,n,i){const o=[];let a=0;const s=t.scalarData;let c,l,f;if(t.color)for(l=0;lBF(s,f),imageData:t})}function cye(t,e,r){const[n,i]=t,o=bt((n[0]+i[0])/2,(n[1]+i[1])/2,(n[2]+i[2])/2),a=ki(n,i)/2;let s;if(!r){const c=UC(e,o),l=e.getSpacing(),f=Math.min(...l),u=Math.ceil(a/f);return s=[[c[0]-u,c[0]+u],[c[1]-u,c[1]+u],[c[2]-u,c[2]+u]],{boundsIJK:s,centerWorld:o,radiusWorld:a}}return s=lye(e,r,t,o,a),{boundsIJK:s,centerWorld:o,radiusWorld:a}}function lye(t,e,r,n,i){const[o,a]=r,s=t.getDimensions(),c=e.getCamera(),l=bt(c.viewUp[0],c.viewUp[1],c.viewUp[2]),f=bt(c.viewPlaneNormal[0],c.viewPlaneNormal[1],c.viewPlaneNormal[2]),u=Ve();Rn(u,l,f);const d=Ve(),h=Ve();Tn(d,a,f,i),Tn(h,o,f,-i),Tn(d,d,u,-i),Tn(h,h,u,i);const g=[UC(t,d),UC(t,h)];return Su(g,s)}function RU(t){if(!Array.isArray(t)||t.length!==9)throw new Error("Matrix must be an array of 9 numbers");if(!t.every(e=>typeof e=="number"&&!isNaN(e)))throw new Error("Matrix must contain only valid numbers")}function LU(t){RU(t);const e=[[t[0],t[1],t[2]],[t[3],t[4],t[5]],[t[6],t[7],t[8]]],r=e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]);if(Math.abs(r)<1e-10)throw new Error("Matrix is not invertible (determinant is zero)");const n=[[e[1][1]*e[2][2]-e[1][2]*e[2][1],-(e[0][1]*e[2][2]-e[0][2]*e[2][1]),e[0][1]*e[1][2]-e[0][2]*e[1][1]],[-(e[1][0]*e[2][2]-e[1][2]*e[2][0]),e[0][0]*e[2][2]-e[0][2]*e[2][0],-(e[0][0]*e[1][2]-e[0][2]*e[1][0])],[e[1][0]*e[2][1]-e[1][1]*e[2][0],-(e[0][0]*e[2][1]-e[0][1]*e[2][0]),e[0][0]*e[1][1]-e[0][1]*e[1][0]]],i=[];for(let o=0;o<3;o++)for(let a=0;a<3;a++)i.push(n[o][a]/r);return i}function p3(t){const e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);return t.map(r=>r/e)}function uye(t){RU(t);const e=t.slice(0,3),r=t.slice(3,6),n=t.slice(6,9),i=p3(e),o=p3(r),a=p3(n),s={x:[1,0,0],y:[0,1,0],z:[0,0,1]},c=1e-10,l=i.every((u,d)=>Math.abs(u-s.x[d])Math.abs(u-s.y[d])Math.abs(u-s.z[d]){Ai(s,s,Ni(Ve(),[-o[0],-o[1],-o[2]],a))}),e instanceof lr&&(t.metadata.referencedImageId=e.getCurrentImageId()),t}function pye(t,e,r){const n=e*r,i=t.length/n;if(![1,3,4].includes(i))throw new Error("Buffer must be 1, 3, or 4 channels per pixel");const o=Array.from({length:r},()=>new Array(e).fill(!1));for(let v=0;v0){x=!0;break}o[v][y]=x}const a=Array.from({length:r},()=>new Array(e).fill(0));let s=0;const c={};for(let v=0;vC<0||C>=e||S<0||S>=r?!1:o[S][C]&&a[S][C]===0;let w=0;$4(m,[y,v],{onFlood:(C,S)=>{a[S][C]=s,w++},diagonals:!1}),c[s]=w}if(s===0)return[];const l=Object.keys(c).reduce((v,y)=>c[v]>c[y]?v:y);function f(v,y){if(a[y][v]!==+l)return!1;for(const[m,w]of[[1,0],[-1,0],[0,1],[0,-1]]){const x=v+m,C=y+w;if(x<0||x>=e||C<0||C>=r||a[C][x]!==+l)return!0}return!1}let u=null;e:for(let v=0;vx[0]===v&&x[1]===y);m<0&&(m=0);let w=null;for(let x=1;x<=8;x++){const[C,S]=d[(m+x)%8],_=g[0]+C,T=g[1]+S;if(_>=0&&_=0&&T(y+1)%r,i=(y,m)=>{const w=[];for(let x=y;w.push(x),x!==m;x=n(x));return w};let o=0,a=0;for(let y=1;yt[a][0]&&(a=y);const s=t[o],c=t[a],l=i(o,a),f=i(a,o),u=Math.min(...t.map(y=>y[1])),d=l.some(y=>t[y][1]===u)?l:f,h=Math.min(...d.map(y=>t[y][1]));let g=d.map(y=>t[y]).filter(y=>Math.abs(y[1]-h)<=e);g.length<2&&(g=d.map(y=>t[y]).sort((y,m)=>y[1]-m[1]).slice(0,2));const p=g.reduce((y,m)=>m[0]m[0]>y[0]?m:y,g[0]);return{P1:p,P2:s,P3:c,P4:v}}function yye(t,e,r,n,i,o={}){const{maxDist:a=15,slack:s=2}=o,c={P1:{dx:-1,dy:-1},P2:{dx:-1,dy:1},P3:{dx:1,dy:1},P4:{dx:1,dy:-1}};function l(f,{dx:u,dy:d},h=5){const g=u<0?f[0]-a:f[0]-s,p=u<0?f[0]+s:f[0]+a,v=d<0?f[1]-a:f[1]-s,y=d<0?f[1]+s:f[1]+a;let m=f;for(const[w,x]of i){if(wp||xy)continue;const C=Math.round(w),S=Math.round(x);if(C<0||C>=e||S<0||S>=r)continue;const _=(C-m[0])*u,T=(S-m[0])*d;t[S*e+C]>h&&(_>0||T>0)&&(m=[w,x])}return m}return{P1:l(n.P1,c.P1),P2:l(n.P2,c.P2),P3:l(n.P3,c.P3),P4:l(n.P4,c.P4)}}function wye(t,e,r,n,i){const o=vye(n);return yye(t,e,r,o,i,{maxDist:20})}function ZD(t,e){return Math.atan2(e[1]-t[1],e[0]-t[0])}function xye(t){const{P1:e,P2:r,P3:n,P4:i}=t,o=Zv(e,r,i,n,!0);if(!o)throw new Error("Fan edges appear parallel — no apex found");const a=o;let s=ZD(a,e)*(180/Math.PI),c=ZD(a,i)*(180/Math.PI);if(c<=s){const p=s;s=c,c=p}const l=Math.hypot(e[0]-a[0],e[1]-a[1]),f=Math.hypot(i[0]-a[0],i[1]-a[1]),u=Math.hypot(r[0]-a[0],r[1]-a[1]),d=Math.hypot(n[0]-a[0],n[1]-a[1]),h=Math.min(l,f),g=Math.max(u,d);return{center:a,startAngle:s,endAngle:c,innerRadius:h,outerRadius:g}}function xg(t,e,r,n,i={}){const{strokeStyle:o="#f00",lineWidth:a=2,quality:s=.92}=i,c=document.createElement("canvas");c.width=e,c.height=r;const l=c.getContext("2d"),f=e*r,u=t.length/f,d=l.createImageData(e,r),h=d.data;for(let g=0;g0){l.strokeStyle=o,l.lineWidth=a,l.beginPath(),l.moveTo(n[0][0]+.5,n[0][1]+.5);for(let g=1;g=h;C-=.01){const S=o[0]+l*Math.cos(C),_=o[1]+l*Math.sin(C);v.lineTo(S,_)}return v.closePath(),v.strokeStyle=f,v.lineWidth=u,v.stroke(),p.toDataURL("image/jpeg",d)}function Sye(t,e=5){const{contour:r,simplified:n,hull:i,refined:o,fanGeometry:a}=nE(t),{pixelData:s,width:c,height:l}=tE(t)||{};if(!s)return;let f;e===1?f=xg(s,c,l,r):e===2?f=xg(s,c,l,n):e===3?f=xg(s,c,l,i):e===4?f=xg(s,c,l,[o.P1,o.P2,o.P3,o.P4]):f=Cye(s,c,l,a,{strokeStyle:"#f00",lineWidth:3,quality:.95}),NU(f,"contour.jpg")}function nE(t){const{pixelData:e,width:r,height:n}=tE(t)||{};if(!e)return;const i=pye(e,r,n),{simplified:o,hull:a}=mye(i),s=wye(e,r,n,a,o),c=xye({P1:s.P1,P2:s.P2,P3:s.P3,P4:s.P4});return{contour:i,simplified:o,hull:a,refined:s,fanGeometry:c}}const _ye=Object.freeze(Object.defineProperty({__proto__:null,calculateFanGeometry:nE,default:NU,downloadFanJpeg:Sye,exportContourJpeg:xg,getPixelData:tE},Symbol.toStringTag,{value:"Module"})),Tye=an,Eye=Object.freeze(Object.defineProperty({__proto__:null,AnnotationMultiSlice:O1e,IslandRemoval:nd,annotationHydration:gfe,boundingBox:D1e,calibrateImageSpacing:E1e,cine:wve,contourSegmentation:Yde,contours:ame,debounce:gh,drawing:Qhe,dynamicVolume:qve,geometricSurfaceUtils:hye,getAnnotationNearPoint:S1e,getAnnotationNearPointOnEnabledElement:cF,getCalibratedAspect:I4,getCalibratedLengthUnitsAndScale:ta,getCalibratedProbeUnitsAndValue:iy,getClosestImageIdForStackViewport:a4,getOrCreateImageVolume:B5,getPixelValueUnits:sl,getPixelValueUnitsImageId:yV,getSphereBoundsInfo:fF,getViewportForAnnotation:N2,isObject:r4,math:fde,moveAnnotationToViewPlane:gye,normalizeViewportPlane:kF,orientation:uve,planar:V0e,planarFreehandROITool:_ve,pointInSurroundingSphereCallback:sye,pointToString:dF,polyDataUtils:Xve,rectangleROITool:Tve,roundNumber:Tye,segmentation:sve,setAnnotationLabel:AU,stackContextPrefetch:Bve,stackPrefetch:Lve,throttle:_o,touch:Rue,triggerAnnotationRender:ph,triggerAnnotationRenderForToolGroupIds:hV,triggerAnnotationRenderForViewportIds:Pe,triggerEvent:at,usFanExtraction:_ye,viewport:Gve,viewportFilters:Ade,voi:aye},Symbol.toStringTag,{value:"Module"})),Dye=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function kU(t,e){const r=Zn;t.forEach(n=>{r.updateSegmentation(n.segmentationId,n.payload),e||Ta(n.segmentationId)})}function bye(t,e,r){Zn.setSegmentationRepresentationVisibility(t,e,r)}function Iye(t,e,r){const n=Jo(t,e);n&&n.forEach(i=>{bye(t,{segmentationId:i.segmentationId,type:i.type},r)})}function Oye(t,e){return mV(t,e)}function Mye(t,e,r,n){const i=Jo(t,e);i&&(i.forEach(o=>{o.segments[r].visible=n}),k5(e.segmentationId),Gs(t,e.segmentationId))}function Pye(t,e,r){return!VU(t,e).has(r)}function VU(t,e){const r=t4(t,e);return r?Object.entries(r.segments).reduce((i,[o,a])=>(a.visible||i.add(Number(o)),i),new Set):new Set}const Rye=Object.freeze(Object.defineProperty({__proto__:null,getHiddenSegmentIndices:VU,getSegmentIndexVisibility:Pye,getSegmentationRepresentationVisibility:Oye,setSegmentIndexVisibility:Mye,setSegmentationRepresentationVisibility:Iye},Symbol.toStringTag,{value:"Module"}));function Lye(t){return va.getStyle(t)}function Aye(t,e){va.setStyle(t,e),!t.viewportId&&!t.segmentationId&&U5().forEach(n=>{wh(n.segmentationId)}),Gs(t.viewportId,t.segmentationId,t.type)}function Nye(t,e){va.setRenderInactiveSegmentations(t,e),wh(t),SF(t).forEach(n=>{Gs(t,n.segmentationId)})}function kye(t){return va.getRenderInactiveSegmentations(t)}function Vye(){va.resetToGlobalStyle(),wh()}function Fye(t){return va.hasCustomStyle(t)}const Uye=Object.freeze(Object.defineProperty({__proto__:null,getRenderInactiveSegmentations:kye,getStyle:Lye,hasCustomStyle:Fye,resetToGlobalStyle:Vye,setRenderInactiveSegmentations:Nye,setStyle:Aye},Symbol.toStringTag,{value:"Module"})),Bye=Object.freeze(Object.defineProperty({__proto__:null,color:Pge,style:Uye,visibility:Rye},Symbol.toStringTag,{value:"Module"}));function dy(t,e){const r=Ln(t);typeof e=="string"&&(console.warn("segmentIndex is a string, converting to number"),e=Number(e)),Object.values(r.segments).forEach(i=>{i.active=!1}),r.segments[e]||(r.segments[e]={segmentIndex:e,label:"",locked:!1,cachedStats:{},active:!1}),r.segments[e].active!==!0&&(r.segments[e].active=!0,Ta(t));const n=yh(t);n.forEach(i=>{Jo(i,{segmentationId:t}).forEach(a=>{a.segments[e]||(a.segments[e]={visible:!0})})}),n.forEach(i=>{const o=Or(i);eU(o.id)})}const Gye=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentIndex:ea,setActiveSegmentIndex:dy},Symbol.toStringTag,{value:"Module"}));async function Wye(t){const e=nfe(t);return Ta(t.segmentationId),e}function FU(t,e){const r=Ln(t);if(r.representationData.Labelmap){const{representationData:n}=r,i=n.Labelmap;("imageIds"in i||"volumeId"in i)&&("imageIds"in i?i.imageIds.map(a=>Le.getImage(a)):[Le.getVolume(i.volumeId)]).forEach(a=>{if(!a)return;const{voxelManager:s}=a;s.forEach(({value:c,index:l})=>{c===e&&s.setAtIndex(l,0)})}),io(t)}else throw new Error("Invalid segmentation type, only labelmap is supported right now")}function zye(t,e,r={setNextSegmentAsActive:!0}){FU(t,e);const n=ea(t)===e,i=Ln(t),{segments:o}=i;delete o[e];const a={...o};if(kU([{segmentationId:t,payload:{segments:a}}]),n&&r.setNextSegmentAsActive){const c=Object.keys(o).map(Number).sort((d,h)=>d-h),l=c.indexOf(e),f=c[l+1],u=c[l-1];f!==void 0?dy(t,f):u!==void 0&&dy(t,u)}yh(t).forEach(c=>{Jo(c,{segmentationId:t}).forEach(f=>{delete f.segments[e]})})}function $ye(t){const e=Zn,r=Ln(t);return e.getLabelmapImageIds(r.representationData)}const jye={clearSegmentValue:FU,convertStackToVolumeLabelmap:Wye,computeVolumeLabelmapFromStack:fU,convertVolumeToStackLabelmap:eve},Hye=Object.freeze(Object.defineProperty({__proto__:null,activeSegmentation:w0e,addContourRepresentationToViewport:K4,addContourRepresentationToViewportMap:X2e,addLabelmapRepresentationToViewport:lU,addLabelmapRepresentationToViewportMap:Y2e,addRepresentationData:n4,addSegmentationRepresentations:Th,addSegmentations:gF,addSurfaceRepresentationToViewport:uU,addSurfaceRepresentationToViewportMap:J2e,config:Bye,defaultSegmentationStateManager:Zn,getActiveSegmentation:ed,getCurrentLabelmapImageIdsForViewport:Qc,getLabelmapImageIds:$ye,getLabelmapImageIdsForImageId:u0e,helpers:jye,removeAllSegmentationRepresentations:vF,removeAllSegmentations:CF,removeContourRepresentation:wF,removeLabelmapRepresentation:yF,removeSegment:zye,removeSegmentation:B4,removeSegmentationRepresentation:Ch,removeSegmentationRepresentations:pF,removeSurfaceRepresentation:xF,segmentIndex:Gye,segmentLocking:Ige,segmentationStyle:va,state:K1e,strategies:e2e,triggerSegmentationEvents:que,updateSegmentations:kU},Symbol.toStringTag,{value:"Module"}));class rE{constructor(e){this._controlPoints=[],this._invalidated=!1,this._length=0,this._controlPoints=[],this._resolution=(e==null?void 0:e.resolution)??20,this._fixedResolution=(e==null?void 0:e.fixedResolution)??!1,this._closed=(e==null?void 0:e.closed)??!1,this._invalidated=!0}get controlPoints(){return this._controlPoints}get numControlPoints(){return this._controlPoints.length}get resolution(){return this._resolution}set resolution(e){this._fixedResolution||this._resolution===e||(this._resolution=e,this.invalidated=!0)}get fixedResolution(){return this._fixedResolution}get closed(){return this._closed}set closed(e){this._closed!==e&&(this._closed=e,this.invalidated=!0)}get aabb(){return this._update(),this._aabb}get length(){return this._update(),this._length}get invalidated(){return this._invalidated}set invalidated(e){this._invalidated=e}hasTangentPoints(){return!1}addControlPoint(e){this._controlPoints.push([e[0],e[1]]),this.invalidated=!0}addControlPoints(e){e.forEach(r=>this.addControlPoint(r))}addControlPointAtU(e){const r=this._getLineSegmentAt(e),{start:n,end:i}=r.points,o=Math.floor(e),a=this._curveSegments[o],s=e-Math.floor(o),c=[n[0]+s*(i[0]-n[0]),n[1]+s*(i[1]-n[1])],l=this._controlPoints.indexOf(a.controlPoints.p1)+1;return this._controlPoints.splice(l,0,c),this.invalidated=!0,{index:l,point:c}}deleteControlPointByIndex(e){const r=this._closed?3:1;return e>=0&&er?(this._controlPoints.splice(e,1),this.invalidated=!0,!0):!1}clearControlPoints(){this._controlPoints=[],this.invalidated=!0}setControlPoints(e){this.clearControlPoints(),this.addControlPoints(e)}updateControlPoint(e,r){if(e<0||e>=this._controlPoints.length)throw new Error("Index out of bounds");this._controlPoints[e]=[...r],this.invalidated=!0}getControlPoints(){return this._controlPoints.map(e=>[e[0],e[1]])}getClosestControlPoint(e){const r=this._controlPoints;let n=1/0,i=-1;for(let o=0,a=r.length;ou.distanceSquared-d.distanceSquared);let n,i=-1,o=1/0,a,s;for(let u=0;uo)continue;const{curveSegmentIndex:h,curveSegment:g}=d,{lineSegments:p}=g;for(let v=0;v=c.minY&&e[1]=h.minY&&e[1]=l.maxX?o:l.maxX,a=a>=l.maxY?a:l.maxY,r+=f}this._curveSegments=e,this._aabb={minX:n,minY:i,maxX:o,maxY:a},this._length=r,this._invalidated=!1}_convertCurveSegmentsToPolyline(e){this._update();const r=[];return e.forEach(({lineSegments:n},i)=>{n.forEach((o,a)=>{i===0&&a===0&&r.push([...o.points.start]),r.push([...o.points.end])})}),r}_getCurveSegmmentsDistanceSquaredInfo(e){this._update();const r=[],{_curveSegments:n}=this;for(let i=0;in)return[];const i=this._getCurveSegmmentsDistanceSquaredInfo(e),o=[];for(let a=0,s=i.length;a=c.previousLineSegmentsLength&&a<=l)return c}}_getClosingCurveSegmentWithStraightLineSegment(){if(this.closed)return;const e=this._controlPoints,r=e[0],n=e[e.length-1],i={points:{start:[...r],end:[...n]},aabb:{minX:Math.min(r[0],n[0]),minY:Math.min(r[1],n[1]),maxX:Math.max(r[0],n[0]),maxY:Math.max(r[1],n[1])}};return{aabb:{minX:i.aabb.minX,minY:i.aabb.minY,maxX:i.aabb.maxX,maxY:i.aabb.maxY},lineSegments:[i]}}}const Kye=1e-8;class iE extends rE{getPreviewCurveSegments(e,r){const n=this._getNumCurveSegments()+1,i=Math.max(0,n-2),o=r?n:n-1,a=this.getTransformMatrix(),s=[...this.controlPoints],c=[];r||s.push(e);for(let l=i;l<=o;l++){const f=this._getCurveSegment(l,a,s,r);c.push(f)}return c}getSplineCurves(){const e=this._getNumCurveSegments(),r=new Array(e);if(e<=0)return[];const n=this.getTransformMatrix();let i=0;for(let o=0;o=o)if(this.closed)s=(o+s)%o;else return;const{p0:f,p1:u,p2:d,p3:h}=this._getCurveSegmentPoints(s,n,i),g=c*c,p=g*c,v=v2(1,c,g,p),y=Jl(RM(),v,r);return[u6(y,v2(f[0],u[0],d[0],h[0])),u6(y,v2(f[1],u[1],d[1],h[1]))]}_getCurveSegmentPoints(e,r=this.controlPoints,n=this.closed){const i=this._getNumCurveSegments(r,n),o=e,a=o-1,s=n?(o+1)%i:o+1,c=s+1,l=r[o],f=r[s];let u,d;return a>=0?u=r[a]:u=n?r[r.length-1]:wC(f,l),cl?l:p;const v=this._getPoint(p,r,n,i);if(!g){u=v;continue}d=v;const y=d[0]-u[0],m=d[1]-u[1],w=Math.sqrt(y**2+m**2),x={minX:u[0]<=d[0]?u[0]:d[0],maxX:u[0]>=d[0]?u[0]:d[0],minY:u[1]<=d[1]?u[1]:d[1],maxY:u[1]>=d[1]?u[1]:d[1]};f.push({points:{start:u,end:d},aabb:x,length:w,previousLineSegmentsLength:h}),u=d,h+=w}return f}_getCurveSegment(e,r=this.getTransformMatrix(),n=this.controlPoints,i=this.closed){const{p0:o,p1:a,p2:s,p3:c}=this._getCurveSegmentPoints(e,n,i),l=this._getLineSegments(e,r,n,i);let f=0,u=1/0,d=1/0,h=-1/0,g=-1/0;return l.forEach(({aabb:p,length:v})=>{u=Math.min(u,p.minX),d=Math.min(d,p.minY),h=Math.max(h,p.maxX),g=Math.max(g,p.maxY),f+=v}),{controlPoints:{p0:o,p1:a,p2:s,p3:c},aabb:{minX:u,minY:d,maxX:h,maxY:g},length:f,previousCurveSegmentsLength:0,lineSegments:l}}}const qye=IM(Zo(),b_(1,4,1,0,-3,0,3,0,3,-6,3,0,-1,3,-3,1),1/6);class UU extends iE{getTransformMatrix(){return qye}}class Jp extends iE{constructor(e){super(e),this._scale=(e==null?void 0:e.scale)??.5,this._fixedScale=(e==null?void 0:e.fixedScale)??!1}get scale(){return this._scale}set scale(e){this._fixedScale||this._scale===e||(this._scale=e,this.invalidated=!0)}get fixedScale(){return this._fixedScale}getTransformMatrix(){const{scale:e}=this,r=2*e;return[0,1,0,0,-e,0,e,0,r,e-3,3-r,-e,-e,2-e,e-2,e]}}class BU extends Jp{constructor(){super({scale:.5,fixedScale:!0})}}class GU extends Jp{constructor(){super({resolution:0,fixedResolution:!0,scale:0,fixedScale:!0})}}class WU extends rE{getSplineCurves(){return[]}getLineSegments(){return[]}getPreviewCurveSegments(e,r){return[]}}const Xye=[1,0,0,-2,2,0,1,-2,1];class Yye extends WU{hasTangentPoints(){return!0}getTransformMatrix(){return Xye}}const Jye=Object.freeze(Object.defineProperty({__proto__:null,BSpline:UU,CardinalSpline:Jp,CatmullRomSpline:BU,CubicSpline:iE,LinearSpline:GU,QuadraticBezier:Yye,QuadraticSpline:WU,Spline:rE},Symbol.toStringTag,{value:"Module"}));class j0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r)}touchDragCallback(e){this._dragCallback(e)}mouseDragCallback(e){this._dragCallback(e)}_dragCallback(e){const{element:r,deltaPoints:n}=e.detail,i=Ce(r),o=n.world;if(o[0]===0&&o[1]===0&&o[2]===0)return;const a=i.viewport.getCamera(),{focalPoint:s,position:c}=a,l=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],f=[s[0]-o[0],s[1]-o[1],s[2]-o[2]];i.viewport.setCamera({focalPoint:f,position:l}),i.viewport.render()}}j0.toolName="Pan";class zU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{rotateIncrementDegrees:2,rotateSampleDistanceFactor:2}}){super(e,r),this._resizeObservers=new Map,this._hasResolutionChanged=!1,this.preMouseDownCallback=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a,f=s.getDefaultActor().actor.getMapper();if(!("getSampleDistance"in f||"getCurrentSampleDistance"in f))return!0;const d=f.getSampleDistance();if(!this._hasResolutionChanged){const{rotateSampleDistanceFactor:h}=this.configuration;f.setSampleDistance(d*h),this._hasResolutionChanged=!0,this.cleanUp!==null&&document.removeEventListener("mouseup",this.cleanUp),this.cleanUp=()=>{f.setSampleDistance(d),s.render(),this._hasResolutionChanged=!1},document.addEventListener("mouseup",this.cleanUp,{once:!0})}return!0},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.onSetToolActive=()=>{const n=()=>{this._getViewportsInfo().forEach(({viewportId:o,renderingEngineId:a})=>{if(!this._resizeObservers.has(o)){const{viewport:s}=Ti(o,a)||{viewport:null};if(!s)return;const{element:c}=s,l=new ResizeObserver(()=>{const f=Ti(o,a);if(!f)return;const{viewport:u}=f,d=u.getViewPresentation();u.resetCamera(),u.setViewPresentation(d),u.render()});l.observe(c),this._resizeObservers.set(o,l)}})};n(),this._viewportAddedListener=i=>{i.detail.toolGroupId===this.toolGroupId&&n()},Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener)},this.onSetToolDisabled=()=>{this._resizeObservers.forEach((n,i)=>{n.disconnect(),this._resizeObservers.delete(i)}),this._viewportAddedListener&&(Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener),this._viewportAddedListener=null)},this.rotateCamera=(n,i,o,a)=>{const s=n.getVtkActiveCamera(),c=s.getViewUp(),l=s.getFocalPoint(),f=s.getPosition(),u=[0,0,0],d=[0,0,0],h=[0,0,0],g=Vt(new Float32Array(16));Lr(g,g,i),go(g,g,a,o),Lr(g,g,[-i[0],-i[1],-i[2]]),Jt(u,f,g),Jt(d,l,g),Vt(g),go(g,g,a,o),Jt(h,c,g),n.setCamera({position:u,viewUp:h,focalPoint:d})},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(e){const{element:r,currentPoints:n,lastPoints:i}=e.detail,o=n.canvas,a=i.canvas,{rotateIncrementDegrees:s}=this.configuration,c=Ce(r),{viewport:l}=c,f=l.getCamera(),u=r.clientWidth,d=r.clientHeight,h=[o[0]/u,o[1]/d],g=[a[0]/u,a[1]/d],p=[u*.5,d*.5],v=l.canvasToWorld(p),m=(1+Math.abs([.5,.5][0]))**2,w=[g[0],0,0],x=[h[0],0,0],C=w[0]**2,S=x[0]**2,_=C>m?0:Math.sqrt(m-C),T=S>m?0:Math.sqrt(m-S),E=[w[0],0,_];Xt.normalize(E);const D=[x[0],0,T];Xt.normalize(D);const b=Xt.dot(E,D);if(Math.abs(b)>1e-4){const I=-2*Math.acos(Xt.clampValue(b,-1,1))*Math.sign(h[0]-g[0])*s,P=f.viewUp,M=f.viewPlaneNormal,L=[0,0,0],V=[0,0,0];Xt.cross(P,M,L),Xt.normalize(L),Xt.cross(M,L,V),Xt.normalize(V),Xt.normalize(P),this.rotateCamera(l,v,V,I);const G=(g[1]-h[1])*s;this.rotateCamera(l,v,L,G),l.render()}}}zU.toolName="TrackballRotate";const m3=4,Zye=1024,Qye="PT";class H0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this._getImageDynamicRangeFromMiddleSlice=(n,i)=>{const o=Math.floor(i[2]/2),a=i[0]*i[1];let s,c;n instanceof Float32Array?(s=4,c=Float32Array):n instanceof Uint8Array?(s=1,c=Uint8Array):n instanceof Uint16Array?(s=2,c=Uint16Array):n instanceof Int16Array&&(s=2,c=Int16Array);const l=n.buffer,f=o*a*s,u=new c(l,f,a),{max:d,min:h}=this._getMinMax(u,a);return d-h}}touchDragCallback(e){this.mouseDragCallback(e)}mouseDragCallback(e){var g,p;const{element:r,deltaPoints:n}=e.detail,i=Ce(r),{viewport:o}=i;let a,s,c,l,f,u,d=!1;const h=o.getProperties();if(o instanceof ur){a=o.getVolumeId(),u=y1(a),{lower:s,upper:c}=h.voiRange;const v=Le.getVolume(a);if(!v)throw new Error("Volume not found "+a);l=v.metadata.Modality,d=v.scaling&&Object.keys(v.scaling).length>0}else if(h.voiRange){l=o.modality,{lower:s,upper:c}=h.voiRange;const{preScale:v={scaled:!1}}=((g=o.getImageData)==null?void 0:g.call(o))||{};d=v.scaled&&((p=v.scalingParameters)==null?void 0:p.suvbw)!==void 0}else throw new Error("Viewport is not a valid type");if(l===Qye&&d?f=this.getPTScaledNewRange({deltaPointsCanvas:n.canvas,lower:s,upper:c,clientHeight:r.clientHeight,isPreScaled:d,viewport:o,volumeId:a}):f=this.getNewRange({viewport:o,deltaPointsCanvas:n.canvas,volumeId:a,lower:s,upper:c}),!(f.lower>=f.upper)&&(o.setProperties({voiRange:f}),o.render(),o instanceof ur)){u.forEach(v=>{o!==v&&v.render()});return}}getPTScaledNewRange({deltaPointsCanvas:e,lower:r,upper:n,clientHeight:i,viewport:o,volumeId:a,isPreScaled:s}){let c=m3;s?c=5/i:c=this._getMultiplierFromDynamicRange(o,a)||m3;const f=e[1]*c;return n-=f,n=s?Math.max(n,.1):n,{lower:r,upper:n}}getNewRange({viewport:e,deltaPointsCanvas:r,volumeId:n,lower:i,upper:o}){const a=this._getMultiplierFromDynamicRange(e,n)||m3,s=r[0]*a,c=r[1]*a;let{windowWidth:l,windowCenter:f}=m1(i,o);l+=s,f+=c,l=Math.max(l,1);const u=e.getProperties().VOILUTFunction;return lu(l,f,u)}_getMultiplierFromDynamicRange(e,r){var o;let n;if(r){const a=Le.getVolume(r),{voxelManager:s}=e.getImageData(),l=s.getMiddleSliceData().reduce((d,h)=>[Math.min(d[0],h),Math.max(d[1],h)],[1/0,-1/0]),f=(o=a==null?void 0:a.metadata)==null?void 0:o.BitsStored,u=f?2**f:1/0;n=Math.min(l,u)}else n=this._getImageDynamicRangeFromViewport(e);const i=n/Zye;return i>1?Math.round(i):i}_getImageDynamicRangeFromViewport(e){const{imageData:r,voxelManager:n}=e.getImageData();if(n!=null&&n.getRange){const s=n.getRange();return s[1]-s[0]}const i=r.getDimensions();if(r.getRange){const s=r.getRange();return s[1]-s[0]}let o;if(r.getScalarData?o=r.getScalarData():o=r.getPointData().getScalars().getData(),i[2]!==1)return this._getImageDynamicRangeFromMiddleSlice(o,i);let a;if(o.getRange)a=o.getRange();else{const{min:s,max:c}=this._getMinMax(o,o.length);a=[s,c]}return a[1]-a[0]}_getMinMax(e,r){let n=1/0,i=-1/0;for(let o=0;oi&&(i=a)}return{max:i,min:n}}}H0.toolName="WindowLevel";class $U extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{minWindowWidth:10}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=this.getReferencedImageId(l,s,u,d),g=l.getFrameOfReferenceUID(),p={invalidated:!0,highlighted:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:g,referencedImageId:h},data:{handles:{points:[[...s],[...s],[...s],[...s]]},cachedStats:{}}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,viewportIdsToRender:v},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(v),p},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData;this._deactivateDraw(o),zt(o),this.editData=null,this.isDrawing=!1,gn(a.annotationUID),Pe(s),Nn(a),this.applyWindowLevelRegion(a,o)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData,{data:c}=a,{currentPoints:l}=i,f=Ce(o),{worldToCanvas:u,canvasToWorld:d}=f.viewport,h=l.world,{points:g}=c.handles,p=3;g[p]=[...h];const v=u(g[0]),y=u(g[3]),m=[y[0],v[1]],w=[v[0],y[1]],x=d(m),C=d(w);g[1]=x,g[2]=C,a.invalidated=!0,Pe(s)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(C));l.annotationUID=d;const{color:v,lineWidth:y,lineDash:m}=this.getAnnotationStyle({annotation:u,styleSpecifier:l});if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const w=`${d}-rect`;P1(i,d,"0",p[0],p[3],{color:v,lineDash:m,lineWidth:y},w),o=!0}return o},this.applyWindowLevelRegion=(n,i)=>{const o=Ce(i),{viewport:a}=o,s=PU(a),{data:c}=n,{points:l}=c.handles,f=l.map(_=>a.worldToCanvas(_)),u=f[0],d=f[3];let h=Math.min(u[0],d[0]),g=Math.min(u[1],d[1]),p=Math.abs(u[0]-d[0]),v=Math.abs(u[1]-d[1]);h=Wv(h,0,s.width),g=Wv(g,0,s.height),p=Math.floor(Math.min(p,Math.abs(s.width-h))),v=Math.floor(Math.min(v,Math.abs(s.height-g)));const y=OU(s,Math.round(h),Math.round(g),p,v),m=MU(y,s.minPixelValue,s.maxPixelValue);this.configuration.minWindowWidth===void 0&&(this.configuration.minWindowWidth=10);const w=Math.max(Math.abs(m.max-m.min),this.configuration.minWindowWidth),x=m.mean,C=a.getProperties().VOILUTFunction,S=lu(w,x,C);a.setProperties({voiRange:S}),a.render()},this.cancel=()=>null,this.isPointNearTool=()=>null,this.toolSelectedCallback=()=>null,this.handleSelectedCallback=()=>null,this._activateModify=()=>null,this._deactivateModify=()=>null}}$U.toolName="WindowLevelRegion";class id extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{invert:!1,debounceIfNotLoaded:!0,loop:!1}}){super(e,r),this.deltaY=1}mouseWheelCallback(e){this._scroll(e)}mouseDragCallback(e){this._dragCallback(e)}touchDragCallback(e){this._dragCallback(e)}_dragCallback(e){this._scrollDrag(e)}_scrollDrag(e){const{deltaPoints:r,viewportId:n,renderingEngineId:i}=e.detail,{viewport:o}=Ti(n,i),{debounceIfNotLoaded:a,invert:s,loop:c}=this.configuration,l=r.canvas[1];let f;o instanceof ur&&(f=o.getVolumeId());const u=this._getPixelPerImage(o),d=l+this.deltaY;if(u)if(Math.abs(d)>=u){const h=Math.round(d/u);ps(o,{delta:s?-h:h,volumeId:f,debounceLoading:a,loop:c}),this.deltaY=d%u}else this.deltaY=d}_scroll(e){const{wheel:r,element:n}=e.detail,{direction:i}=r,{invert:o}=this.configuration,{viewport:a}=Ce(n),s=i*(o?-1:1);ps(a,{delta:s,debounceLoading:this.configuration.debounceIfNotLoaded,loop:this.configuration.loop,volumeId:a instanceof Ir?a.getVolumeId():void 0,scrollSlabs:this.configuration.scrollSlabs})}_getPixelPerImage(e){const{element:r}=e,n=e.getNumberOfSlices();return Math.max(2,r.offsetHeight/Math.max(n,8))}}id.toolName="StackScroll";class K0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.mouseWheelCallback=n=>{const{element:i,wheel:o}=n.detail,a=Ce(i),{viewport:s}=a,{invert:c}=this.configuration,l=o.direction*10*(c?-1:1);this.setAngle(s,l)},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(e){const{element:r,currentPoints:n,startPoints:i}=e.detail,o=n.world,a=i.world,s=Ce(r),{viewport:c}=s,l=c.getCamera(),f=r.clientWidth,u=r.clientHeight,d=[f*.5,u*.5],h=c.canvasToWorld(d);let g=S0([a,h],[h,o]);const{viewPlaneNormal:p}=l,v=En(Ve(),h,a),y=En(Ve(),h,o),m=Rn(Ve(),v,y);Et(p,m)>0&&(g=-g),!Number.isNaN(g)&&this.setAngle(c,g)}setAngle(e,r){const{viewPlaneNormal:n,viewUp:i}=e.getCamera();if(e instanceof Ir){const o=(r+360)%360*Math.PI/180,a=Vt(new Float32Array(16));go(a,a,o,n);const s=Jt(Ve(),i,a);e.setCamera({viewUp:s})}else{const{rotation:o}=e.getViewPresentation();e.setViewPresentation({rotation:(o+r+360)%360})}e.render()}}K0.toolName="PlanarRotate";class q0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{zoomToCenter:!1,minZoomScale:.001,maxZoomScale:3e3,pinchToZoom:!0,pan:!0,invert:!1}}){super(e,r),this.preMouseDownCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=a.world,l=Ce(o).viewport.getCamera(),{focalPoint:f}=l;this.initialMousePosWorld=s;let u=bt(f[0]-s[0],f[1]-s[1],f[2]-s[2]);return u=tr(Ve(),u),this.dirVec=u,!1},this.preTouchStartCallback=n=>{if(!this.configuration.pinchToZoom)return this.preMouseDownCallback(n)},this._dragParallelProjection=(n,i,o,a=!1)=>{var _,T,E;const{element:s,deltaPoints:c}=n.detail,l=a?n.detail.deltaDistance.canvas:c.canvas[1],f=[s.clientWidth,s.clientHeight],{parallelScale:u,focalPoint:d,position:h}=o,g=5/f[1],p=l*g*(this.configuration.invert?-1:1),v=(1-p)*u;let y=d,m=h;if(!this.configuration.zoomToCenter){const D=ki(d,this.initialMousePosWorld);m=Tn(Ve(),h,this.dirVec,-D*p),y=Tn(Ve(),d,this.dirVec,-D*p)}const w=i.getImageData();let x=[1,1,1],C=v,S=!1;if(w){x=w.spacing;const{dimensions:D}=w,b=D[0]*x[0],I=D[1]*x[1],P=f[0]/f[1],M=(_=i.options)==null?void 0:_.displayArea,L=((T=M==null?void 0:M.imageArea)==null?void 0:T[0])??1.1,V=((E=M==null?void 0:M.imageArea)==null?void 0:E[1])??1.1,G=b*L,A=I*V,k=G/A;let F;k>P?F=G/P*.5:F=A*.5;const{minZoomScale:j,maxZoomScale:Y}=this.configuration,re=F/Y,ue=F/j;vue&&(C=ue,S=!0)}i.setCamera({parallelScale:C,focalPoint:S?d:y,position:S?h:m})},this._dragPerspectiveProjection=(n,i,o,a=!1)=>{const{element:s,deltaPoints:c}=n.detail,l=a?n.detail.deltaDistance.canvas:c.canvas[1],f=[s.clientWidth,s.clientHeight],{position:u,focalPoint:d,viewPlaneNormal:h}=o,g=Xt.distance2BetweenPoints(u,d),p=Math.sqrt(g)/f[1],v=[-h[0],-h[1],-h[2]],y=this.configuration.invert?l/p:l*p;let m=y*v[0];u[0]+=m,d[0]+=m,m=y*v[1],u[1]+=m,d[1]+=m,m=y*v[2],u[2]+=m,d[2]+=m,i.setCamera({position:u,focalPoint:d})},this.initialMousePosWorld=[0,0,0],this.dirVec=[0,0,0],this.configuration.pinchToZoom?this.touchDragCallback=this._pinchCallback.bind(this):this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}mouseWheelCallback(e){this._zoom(e)}_pinchCallback(e){if(e.detail.currentPointsList.length>1){const{element:n,currentPoints:i}=e.detail,o=Ce(n),{viewport:a}=o,s=a.getCamera(),c=i.world,{focalPoint:l}=s;this.initialMousePosWorld=c;let f=bt(l[0]-c[0],l[1]-c[1],l[2]-c[2]);f=tr(Ve(),f),this.dirVec=f,s.parallelProjection?this._dragParallelProjection(e,a,s,!0):this._dragPerspectiveProjection(e,a,s,!0),a.render()}this.configuration.pan&&this._panCallback(e)}_dragCallback(e){const{element:r}=e.detail,n=Ce(r),{viewport:i}=n,o=i.getCamera();o.parallelProjection?this._dragParallelProjection(e,i,o):this._dragPerspectiveProjection(e,i,o),i.render()}_zoom(e){const{element:r,points:n}=e.detail,i=Ce(r),{viewport:o}=i;o.getCamera();const s=e.detail.wheel.direction,c={detail:{element:r,eventName:N.MOUSE_WHEEL,renderingEngineId:i.renderingEngineId,viewportId:o.id,camera:{},deltaPoints:{page:n.page,client:n.client,world:n.world,canvas:[0,-s*5]},startPoints:n,lastPoints:n,currentPoints:n}};o.type===mr.STACK&&this.preMouseDownCallback(c),this._dragCallback(c)}_panCallback(e){const{element:r,deltaPoints:n}=e.detail,i=Ce(r),o=n.world,a=i.viewport.getCamera(),{focalPoint:s,position:c}=a,l=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],f=[s[0]-o[0],s[1]-o[1],s[2]-o[2]];i.viewport.setCamera({focalPoint:f,position:l}),i.viewport.render()}}q0.toolName="Zoom";class jU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{targetViewportIds:[]}}){super(e,r)}mouseClickCallback(e){const{element:r,currentPoints:n}=e.detail,i=Ce(r),{viewport:o,renderingEngine:a}=i,s=o.getVolumeId();if(!s)throw new Error("MIPJumpToClickTool: targetId is not a volumeId, you should only use MIPJumpToClickTool with a volumeId as the targetId");let c=-1/0;const l=(g,p)=>{if(g>c)return c=g,p},f=O4(o,n.world,s,l);if(!f||!f.length)return;const{targetViewportIds:u,toolGroupId:d}=this.configuration;a.getViewports().filter(g=>{if((u==null?void 0:u.indexOf(g.id))>=0)return!0;const p=Or(g.id,a.id);return!!(d&&d===(p==null?void 0:p.id))}).forEach(g=>{g instanceof ur?g.jumpToWorld(f):console.warn("Cannot jump to specified world coordinates for a viewport that is not a VolumeViewport")})}}jU.toolName="MIPJumpToClickTool";const{RENDERING_DEFAULTS:v3}=cd;function e5e(){return"rgb(0, 200, 0)"}function t5e(){return!0}function n5e(){return!0}function r5e(){return!0}const ns={DRAG:1,ROTATE:2,SLAB:3};class Fs extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse"],configuration:{shadow:!0,viewportIndicators:!1,viewportIndicatorsConfig:{radius:5,x:null,y:null},autoPan:{enabled:!1,panSize:10},handleRadius:3,enableHDPIHandles:!1,referenceLinesCenterGapRadius:20,filterActorUIDsToSetSlabThickness:[],slabThicknessBlendMode:js.MAXIMUM_INTENSITY_BLEND,mobile:{enabled:!1,opacity:.8,handleRadius:9}}}){var n,i,o,a;super(e,r),this.toolCenter=[0,0,0],this.initializeViewport=({renderingEngineId:s,viewportId:c})=>{const l=Ti(c,s);if(!l)return;const{FrameOfReferenceUID:f,viewport:u}=l,{element:d}=u,{position:h,focalPoint:g,viewPlaneNormal:p}=u.getCamera();let v=this._getAnnotations(l);v=this.filterInteractableAnnotationsForElement(d,v),v!=null&&v.length&&gn(v[0].annotationUID);const y={highlighted:!1,metadata:{cameraPosition:[...h],cameraFocalPoint:[...g],FrameOfReferenceUID:f,toolName:this.getToolName()},data:{handles:{rotationPoints:[],slabThicknessPoints:[],toolCenter:this.toolCenter},activeOperation:null,activeViewportIds:[],viewportId:c}};return nn(y,d),{normal:p,point:u.canvasToWorld([u.canvas.clientWidth/2,u.canvas.clientHeight/2])}},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.resetCrosshairs=()=>{const s=this._getViewportsInfo();for(const c of s){const{viewportId:l,renderingEngineId:f}=c,u=Ti(l,f),d=u.viewport;d.resetCamera({resetPan:!0,resetZoom:!0,resetToCenter:!0,resetRotation:!0,suppressEvents:!0}),d.resetSlabThickness();const{element:m}=d;let w=this._getAnnotations(u);w=this.filterInteractableAnnotationsForElement(m,w),w.length&&gn(w[0].annotationUID),d.render()}this._computeToolCenter(s)},this.computeToolCenter=()=>{const s=this._getViewportsInfo();this._computeToolCenter(s)},this._computeToolCenter=s=>{if(!s.length||s.length===1){console.warn("For crosshairs to operate, at least two viewports must be given.");return}const[c,l,f]=s,{normal:u,point:d}=this.initializeViewport(c),{normal:h,point:g}=this.initializeViewport(l);let p=[0,0,0],v=Ve();f?{normal:p,point:v}=this.initializeViewport(f):(Ai(v,d,g),Ni(v,v,.5),Rn(p,u,h));const y=qs(u,d),m=qs(h,g),w=qs(p,v),x=eA(y,m,w);this.setToolCenter(x)},this.addNewAnnotation=s=>{const c=s.detail,{element:l}=c,{currentPoints:f}=c,u=f.world,d=Ce(l),{viewport:h}=d;this._jump(d,u);const g=this._getAnnotations(d),p=this.filterInteractableAnnotationsForElement(h.element,g),{data:v}=p[0],{rotationPoints:y}=v.handles,m=[];for(let w=0;w{console.log("Not implemented yet")},this.handleSelectedCallback=(s,c)=>{const l=s.detail,{element:f}=l;c.highlighted=!0,this._activateModify(f),Ot(f),s.preventDefault()},this.isPointNearTool=(s,c,l,f)=>!!this._pointNearTool(s,c,l,6),this.toolSelectedCallback=(s,c,l)=>{const f=s.detail,{element:u}=f;c.highlighted=!0,this._activateModify(u),Ot(u),s.preventDefault()},this.onCameraModified=s=>{var E;const c=s.detail,{element:l}=c,f=Ce(l),{renderingEngine:u}=f,d=f.viewport,h=this._getAnnotations(f),p=this.filterInteractableAnnotationsForElement(l,h)[0];if(!p)return;const v=d.getCamera(),y=p.metadata.cameraPosition,m=[0,0,0];Xt.subtract(v.position,y,m);const w=p.metadata.cameraFocalPoint,x=[0,0,0];Xt.subtract(v.focalPoint,w,x),p.metadata.cameraPosition=[...v.position],p.metadata.cameraFocalPoint=[...v.focalPoint];const C=this._getReferenceLineControllable(d.id),S=this._getReferenceLineDraggableRotatable(d.id);if(!$t(v.position,y,.001)&&C&&S){let D=!1;$t(m,x,.001)||(D=!0);const I=Math.abs(Xt.dot(m,v.viewPlaneNormal))<.01;!D&&!I&&(this.toolCenter[0]+=m[0],this.toolCenter[1]+=m[1],this.toolCenter[2]+=m[2],at(Ke,N.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter}))}(E=this.configuration.autoPan)!=null&&E.enabled&&Or(d.id,u.id).getViewportIds().filter(I=>I!==d.id).forEach(I=>{this._autoPanViewportIfNecessary(I,u)});const T=_t(l,this.getToolName(),!1);Pe(T)},this.onResetCamera=s=>{this.resetCrosshairs()},this.mouseMoveCallback=(s,c)=>{const{element:l,currentPoints:f}=s.detail,u=f.canvas;let d=!1;for(let h=0;h0?[...p.activeViewportIds]:[];p.activeViewportIds=[],p.handles.activeOperation=null;const w=this.getHandleNearImagePoint(l,g,u,6);let x=!1;w?x=!0:x=this._pointNearTool(l,g,u,6),x&&!v||!x&&v?(g.highlighted=!v,d=!0):(p.handles.activeOperation!==y||!this._areViewportIdArraysEqual(p.activeViewportIds,m))&&(d=!0)}return d},this.filterInteractableAnnotationsForElement=(s,c)=>{if(!c||!c.length)return[];const l=Ce(s),{viewportId:f}=l;return c.filter(d=>d.data.viewportId===f)},this.renderAnnotation=(s,c)=>{let l=!1;const{viewport:f,renderingEngine:u}=s,{element:d}=f,h=this._getAnnotations(s),g=f.getCamera(),v=this.filterInteractableAnnotationsForElement(d,h)[0];if(!(h!=null&&h.length)||!(v!=null&&v.data))return l;const y=v.annotationUID,{clientWidth:m,clientHeight:w}=f.canvas,x=Math.sqrt(m*m+w*w),C=Math.min(m,w),S=v.data,_=f.worldToCanvas(this.toolCenter),T=this._filterAnnotationsByUniqueViewportOrientations(s,h),E=[],D=[0,0,m,w];T.forEach(L=>{const{data:V}=L;V.handles.toolCenter=this.toolCenter;const G=u.getViewport(V.viewportId),A=G.getCamera(),k=this._getReferenceLineControllable(G.id),F=this._getReferenceLineDraggableRotatable(G.id),j=this._getReferenceLineSlabThicknessControlsOn(G.id),{clientWidth:Y,clientHeight:re}=G.canvas,ue=Math.sqrt(Y*Y+re*re),ce=[Y*.5,re*.5],pe=G.canvasToWorld(ce),Ee=[0,0,0];Xt.cross(g.viewPlaneNormal,A.viewPlaneNormal,Ee),Xt.normalize(Ee),Xt.multiplyScalar(Ee,ue);const Oe=[0,0,0];Xt.add(pe,Ee,Oe);const Se=[0,0,0];Xt.subtract(pe,Ee,Se);const B=f.worldToCanvas(Oe),O=f.worldToCanvas(pe),z=qt();Wr(z,B,O),Nc(z,z);const W=qt();Oc(W,z,x*100);const K=qt();Oc(K,z,C*.4);const Z=qt();Oc(Z,z,C*.2);const ee=qt(),xe=this.configuration.referenceLinesCenterGapRadius;Oc(ee,z,T.length===2?xe:0);const De=qt(),Ne=qt(),ze=qt(),ie=qt();let ae=om(_);(!F||!k)&&(ae=om(O)),Qi(De,ae,ee),Qi(Ne,ae,W),Wr(ze,ae,ee),Wr(ie,ae,W),yg(De,Ne,D),yg(ze,ie,D);const we=qt();Wr(we,_,K);const se=qt();Qi(se,_,K);let ge=om(_);!F&&j&&(ge=om(O));let Fe=[...this.toolCenter];!F&&j&&(Fe=[...pe]);const oe=[0,0,0];Xt.subtract(Oe,Se,oe),Xt.normalize(oe);const{viewPlaneNormal:ht}=g,{matrix:wt}=ji.buildFromDegree().rotate(90,ht),gt=[0,0,0];Jt(gt,oe,wt);const Ie=G.getSlabThickness(),$e=[...gt];Xt.multiplyScalar($e,Ie);const tt=[0,0,0];Xt.add(Fe,$e,tt);const nt=f.worldToCanvas(tt),dt=qt();Wr(dt,ge,nt);const Lt=qt();Wr(Lt,ge,W),Qi(Lt,Lt,dt);const xt=qt();Qi(xt,ge,W),Qi(xt,xt,dt),yg(Lt,xt,D);const Ft=qt();Qi(Ft,ge,W),Wr(Ft,Ft,dt);const jt=qt();Wr(jt,ge,W),Wr(jt,jt,dt),yg(Ft,jt,D);const Pn=qt(),$n=qt(),fn=qt(),bn=qt();Wr(Pn,ge,Z),Qi(Pn,Pn,dt),Qi($n,ge,Z),Qi($n,$n,dt),Wr(fn,ge,Z),Wr(fn,fn,dt),Qi(bn,ge,Z),Wr(bn,bn,dt),E.push([G,De,Ne,ze,ie,Lt,xt,Ft,jt,we,se,Pn,$n,fn,bn])});const b=[],I=[],P=this._getReferenceLineColor(f.id),M=P!==void 0?P:"rgb(200, 200, 200)";if(E.forEach((L,V)=>{var Ee,Oe,Se,B;const G=L[0],A=this._getReferenceLineColor(G.id),k=this._getReferenceLineControllable(G.id),F=this._getReferenceLineDraggableRotatable(G.id)||((Ee=this.configuration.mobile)==null?void 0:Ee.enabled),j=this._getReferenceLineSlabThicknessControlsOn(G.id)||((Oe=this.configuration.mobile)==null?void 0:Oe.enabled),Y=S.activeViewportIds.find(O=>O===G.id);let re=A!==void 0?A:"rgb(200, 200, 200)",ue=1;const ce=S.handles.activeOperation!==null&&S.handles.activeOperation===ns.DRAG&&Y;ce&&(ue=2.5);let pe=`${V}`;if(k&&F?(pe=`${V}One`,vn(c,y,pe,L[1],L[2],{color:re,lineWidth:ue}),pe=`${V}Two`,vn(c,y,pe,L[3],L[4],{color:re,lineWidth:ue})):vn(c,y,pe,L[2],L[4],{color:re,lineWidth:ue}),k){re=A!==void 0?A:"rgb(200, 200, 200)";const O=S.handles.activeOperation===ns.ROTATE,z=[L[9],L[10]],W=[f.canvasToWorld(L[9]),G,L[1],L[2]],K=[f.canvasToWorld(L[10]),G,L[3],L[4]];b.push(W,K);const Z=S.handles.activeOperation===ns.SLAB,ee=[L[11],L[12],L[13],L[14]],xe=[f.canvasToWorld(L[11]),G,L[5],L[6]],De=[f.canvasToWorld(L[12]),G,L[5],L[6]],Ne=[f.canvasToWorld(L[13]),G,L[7],L[8]],ze=[f.canvasToWorld(L[14]),G,L[7],L[8]];I.push(xe,De,Ne,ze);let ie=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1),ae=1;if((Se=this.configuration.mobile)!=null&&Se.enabled&&(ie=this.configuration.mobile.handleRadius,ae=this.configuration.mobile.opacity),(ce||(B=this.configuration.mobile)!=null&&B.enabled)&&!O&&!Z&&F&&j){let se=`${V}One`;ir(c,y,se,z,{color:re,handleRadius:ie,opacity:ae,type:"circle"}),se=`${V}Two`,ir(c,y,se,ee,{color:re,handleRadius:ie,opacity:ae,type:"rect"})}else if(ce&&!O&&!Z&&F){const se=`${V}`;ir(c,y,se,z,{color:re,handleRadius:ie,opacity:ae,type:"circle"})}else if(Y&&!O&&!Z&&j){const se=`${V}`;ir(c,y,se,ee,{color:re,handleRadius:ie,opacity:ae,type:"rect"})}else if(O&&F){const se=`${V}`,ge=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);ir(c,y,se,z,{color:re,handleRadius:ge,fill:re,type:"circle"})}else if(Z&&Y&&j){const se=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);ir(c,y,pe,ee,{color:re,handleRadius:se,fill:re,type:"rect"})}G.getSlabThickness()>.5&&j&&(pe=`${V}STOne`,vn(c,y,pe,L[5],L[6],{color:re,width:1,lineDash:[2,3]}),pe=`${V}STTwo`,vn(c,y,pe,L[7],L[8],{color:re,width:L,lineDash:[2,3]}))}}),l=!0,S.handles.rotationPoints=b,S.handles.slabThicknessPoints=I,this.configuration.viewportIndicators){const{viewportIndicatorsConfig:L}=this.configuration,V=(L==null?void 0:L.xOffset)||.95,G=(L==null?void 0:L.yOffset)||.05,A=[m*V,w*G],k=(L==null?void 0:L.circleRadius)||x*.01;No(c,y,"0",A,k,{color:M,fill:M})}return l},this._getAnnotations=s=>{const{viewport:c}=s,l=un(this.getToolName(),c.element)||[],f=this._getViewportsInfo().map(({viewportId:d})=>d);return l.filter(d=>{const{data:h}=d;return f.includes(h.viewportId)})},this._onNewVolume=()=>{const s=this._getViewportsInfo();this._computeToolCenter(s)},this._areViewportIdArraysEqual=(s,c)=>s.length!==c.length?!1:(s.forEach(l=>{let f=!1;for(let u=0;u{const{viewportId:l,renderingEngine:f,viewport:u}=s,d=c.filter(y=>y.data.viewportId!==l);if(!d||!d.length)return[];const h=u.getCamera(),{viewPlaneNormal:g,position:p}=h;return d.filter(y=>{const{viewportId:m}=y.data,x=f.getViewport(m).getCamera();return!($t(x.viewPlaneNormal,g,.01)&&$t(x.position,p,1))})},this._filterViewportWithSameOrientation=(s,c,l)=>{const{renderingEngine:f}=s,{data:u}=c,d=f.getViewport(u.viewportId),h=l.filter(y=>{const{data:m}=y,w=f.getViewport(m.viewportId);return this._getReferenceLineControllable(w.id)===!0});if(!h||!h.length)return[];const g=d.getCamera(),p=g.viewPlaneNormal;return Xt.normalize(p),h.filter(y=>{const{viewportId:m}=y.data,x=f.getViewport(m).getCamera(),C=x.viewPlaneNormal;return Xt.normalize(C),$t(p,C,.01)&&$t(g.viewUp,x.viewUp,.01)})},this._filterAnnotationsByUniqueViewportOrientations=(s,c)=>{const{renderingEngine:l,viewport:f}=s,d=f.getCamera().viewPlaneNormal;Xt.normalize(d);const h=c.filter(y=>{const{data:m}=y,w=l.getViewport(m.viewportId),x=this._getReferenceLineControllable(w.id);return f!==w&&x===!0}),g=[];for(let y=0;y{const{data:m}=y,w=l.getViewport(m.viewportId),x=this._getReferenceLineControllable(w.id);return f!==w&&x!==!0});for(let y=0;yT===m))continue;const{viewportId:w}=m.data,C=l.getViewport(w).getCamera(),S=C.viewPlaneNormal;if(Xt.normalize(S),$t(d,S,.01)||vg(d,S,.01))continue;let _=!1;for(let T=0;T{const l=s.getAllVolumeIds(),f=c.getAllVolumeIds();return l.length===f.length&&l.every(u=>f.includes(u))},this._jump=(s,c)=>{Ge.isInteractingWithTool=!0;const{viewport:l,renderingEngine:f}=s,u=this._getAnnotations(s),d=[0,0,0];Xt.subtract(c,this.toolCenter,d);const g=this._getAnnotationsForViewportsWithDifferentCameras(s,u).filter(p=>{const{data:v}=p,y=f.getViewport(v.viewportId),m=this._checkIfViewportsRenderingSameScene(l,y);return this._getReferenceLineControllable(y.id)&&this._getReferenceLineDraggableRotatable(y.id)&&m});return g.length===0?(Ge.isInteractingWithTool=!1,!1):(this._applyDeltaShiftToSelectedViewportCameras(f,g,d),Ge.isInteractingWithTool=!1,!0)},this._activateModify=s=>{var c;Ge.isInteractingWithTool=!((c=this.configuration.mobile)!=null&&c.enabled),s.addEventListener(N.MOUSE_UP,this._endCallback),s.addEventListener(N.MOUSE_DRAG,this._dragCallback),s.addEventListener(N.MOUSE_CLICK,this._endCallback),s.addEventListener(N.TOUCH_END,this._endCallback),s.addEventListener(N.TOUCH_DRAG,this._dragCallback),s.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=s=>{Ge.isInteractingWithTool=!1,s.removeEventListener(N.MOUSE_UP,this._endCallback),s.removeEventListener(N.MOUSE_DRAG,this._dragCallback),s.removeEventListener(N.MOUSE_CLICK,this._endCallback),s.removeEventListener(N.TOUCH_END,this._endCallback),s.removeEventListener(N.TOUCH_DRAG,this._dragCallback),s.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._endCallback=s=>{const c=s.detail,{element:l}=c;this.editData.annotation.data.handles.activeOperation=null,this.editData.annotation.data.activeViewportIds=[],this._deactivateModify(l),zt(l),this.editData=null;const u=_t(l,this.getToolName(),!1);Pe(u)},this._dragCallback=s=>{const c=s.detail,l=c.deltaPoints.world;if(Math.abs(l[0])<.001&&Math.abs(l[1])<.001&&Math.abs(l[2])<.001)return;const{element:f}=c,u=Ce(f),{renderingEngine:d,viewport:h}=u,g=this._getAnnotations(u),v=this.filterInteractableAnnotationsForElement(f,g)[0];if(!v)return;const{handles:y}=v.data,{currentPoints:m}=s.detail,w=m.canvas;if(y.activeOperation===ns.DRAG){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(S=>{const{data:_}=S,T=d.getViewport(_.viewportId),E=this._getReferenceLineControllable(T.id),D=this._getReferenceLineDraggableRotatable(T.id);return E===!0&&D===!0&&v.data.activeViewportIds.find(b=>b===T.id)});this._applyDeltaShiftToSelectedViewportCameras(d,C,l)}else if(y.activeOperation===ns.ROTATE){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(V=>{const{data:G}=V,A=d.getViewport(G.viewportId),k=this._getReferenceLineControllable(A.id),F=this._getReferenceLineDraggableRotatable(A.id);return k===!0&&F===!0}),S=qt(),_=qt(),T=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]],E=h.worldToCanvas(T),D=c.currentPoints.canvas,b=qt();Ga(b,D,c.deltaPoints.canvas),Ga(S,b,E),Ga(_,D,E);let I=KK(S,_);this._isClockWise(E,b,D)&&(I*=-1),I=Math.round(I*100)/100;const P=h.getCamera().viewPlaneNormal,{matrix:M}=ji.buildFromRadian().translate(T[0],T[1],T[2]).rotate(I,P).translate(-T[0],-T[1],-T[2]),L=[];C.forEach(V=>{const{data:G}=V;G.handles.toolCenter=T;const A=d.getViewport(G.viewportId),k=A.getCamera(),{viewUp:F,position:j,focalPoint:Y}=k;F[0]+=j[0],F[1]+=j[1],F[2]+=j[2],Jt(Y,Y,M),Jt(j,j,M),Jt(F,F,M),F[0]-=j[0],F[1]-=j[1],F[2]-=j[2],A.setCamera({position:j,viewUp:F,focalPoint:Y}),L.push(A.id)}),d.renderViewports(L)}else if(y.activeOperation===ns.SLAB){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(T=>{const{data:E}=T,D=d.getViewport(E.viewportId),b=this._getReferenceLineControllable(D.id),I=this._getReferenceLineSlabThicknessControlsOn(D.id);return b===!0&&I===!0&&v.data.activeViewportIds.find(P=>P===D.id)});if(C.length===0)return;const S=this._filterViewportWithSameOrientation(u,C[0],g),_=[];_.push(h.id),S.forEach(T=>{const{data:E}=T,D=d.getViewport(E.viewportId),I=D.getCamera().viewPlaneNormal,P=Xt.dot(l,I),M=[...I];if(Xt.multiplyScalar(M,P),Math.abs(M[0])>.001||Math.abs(M[1])>.001||Math.abs(M[2])>.001){const L=Math.sqrt(M[0]*M[0]+M[1]*M[1]+M[2]*M[2]),V=c.lastPoints.world,G=[0,0,0],A=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]];if(!this._getReferenceLineDraggableRotatable(D.id)){const{rotationPoints:Oe}=this.editData.annotation.data.handles,Se=Oe.filter(B=>B[1].uid===D.id);if(Se.length===2){const B=h.canvasToWorld(Se[0][3]),O=h.canvasToWorld(Se[1][3]);Xt.add(B,O,A),Xt.multiplyScalar(A,.5)}}Xt.subtract(V,A,G);const F=Xt.dot(G,I),j=[...I];Xt.multiplyScalar(j,F);const Y=[j[0],j[1],j[2]];tr(Y,Y);const re=[M[0],M[1],M[2]];tr(re,re);let ue=D.getSlabThickness();vg(Y,re,.001)?ue-=L:ue+=L,ue=Math.abs(ue),ue=Math.max(v3.MINIMUM_SLAB_THICKNESS,ue),this._pointNearReferenceLine(v,w,6,D)&&(ue=v3.MINIMUM_SLAB_THICKNESS),Or(D.id,d.id).getToolInstance(this.getToolName()).setSlabThickness(D,ue),_.push(D.id)}}),d.renderViewports(_)}},this._pointNearReferenceLine=(s,c,l,f)=>{const{data:u}=s,{rotationPoints:d}=u.handles;for(let h=0;h{const i=Ti(n,r);if(!i)return;const o=this._getAnnotations(i);o!=null&&o.length&&o.forEach(a=>{gn(a.annotationUID)})})}setToolCenter(e,r=!1){this.toolCenter=e;const n=this._getViewportsInfo();Pe(n.map(({viewportId:i})=>i)),r||at(Ke,N.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter})}getHandleNearImagePoint(e,r,n,i){const o=Ce(e),{viewport:a}=o;let s=this._getRotationHandleNearImagePoint(a,r,n,i);if(s!==null||(s=this._getSlabThicknessHandleNearImagePoint(a,r,n,i),s!==null))return s}_unsubscribeToViewportNewVolumeSet(e){e.forEach(({viewportId:r,renderingEngineId:n})=>{const{viewport:i}=Ti(r,n),{element:o}=i;o.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_subscribeToViewportNewVolumeSet(e){e.forEach(({viewportId:r,renderingEngineId:n})=>{const{viewport:i}=Ti(r,n),{element:o}=i;o.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_autoPanViewportIfNecessary(e,r){const n=r.getViewport(e),{clientWidth:i,clientHeight:o}=n.canvas,a=n.worldToCanvas(this.toolCenter),s=this.configuration.autoPan.panSize,c=[a[0],a[1]];if(a[0]<0?c[0]=s:a[0]>i&&(c[0]=i-s),a[1]<0?c[1]=s:a[1]>o&&(c[1]=o-s),c[0]===a[0]&&c[1]===a[1])return;const l=n.canvasToWorld(c),f=[l[0]-this.toolCenter[0],l[1]-this.toolCenter[1],l[2]-this.toolCenter[2]],u=n.getCamera(),{focalPoint:d,position:h}=u,g=[h[0]-f[0],h[1]-f[1],h[2]-f[2]],p=[d[0]-f[0],d[1]-f[1],d[2]-f[2]];n.setCamera({focalPoint:p,position:g}),n.render()}setSlabThickness(e,r){let n;const{filterActorUIDsToSetSlabThickness:i}=this.configuration;i&&i.length>0&&(n=i);let o=this.configuration.slabThicknessBlendMode;r===v3.MINIMUM_SLAB_THICKNESS&&(o=js.COMPOSITE),e.setBlendMode(o,n,!1),e.setSlabThickness(r,n)}_isClockWise(e,r,n){return(r[0]-e[0])*(n[1]-e[1])-(r[1]-e[1])*(n[0]-e[0])>0}_applyDeltaShiftToSelectedViewportCameras(e,r,n){r.forEach(i=>{this._applyDeltaShiftToViewportCamera(e,i,n)})}_applyDeltaShiftToViewportCamera(e,r,n){const{data:i}=r,o=e.getViewport(i.viewportId),a=o.getCamera(),s=a.viewPlaneNormal,c=Xt.dot(n,s),l=[...s];if(Xt.multiplyScalar(l,c),Math.abs(l[0])>.001||Math.abs(l[1])>.001||Math.abs(l[2])>.001){const f=[0,0,0],u=[0,0,0];Xt.add(a.focalPoint,l,f),Xt.add(a.position,l,u),o.setCamera({focalPoint:f,position:u}),o.render()}}_getRotationHandleNearImagePoint(e,r,n,i){const{data:o}=r,{rotationPoints:a}=o.handles;for(let s=0;sP===p.id))continue;const v=this._getReferenceLineControllable(p.id),y=this._getReferenceLineSlabThicknessControlsOn(p.id);if(!v||!y)continue;const m=d[g][2],w=d[g][3],x=qt();Qi(x,m,w),Oc(x,x,.5);const C=qt();Wr(C,m,x),Nc(C,C);const S=qt();Oc(S,C,l*.05);const _=qt(),T=qt();Qi(_,x,S),Wr(T,x,S);const E={start:{x:_[0],y:_[1]},end:{x:m[0],y:m[1]}},D=hi([E.start.x,E.start.y],[E.end.x,E.end.y],[n[0],n[1]]),b={start:{x:T[0],y:T[1]},end:{x:w[0],y:w[1]}},I=hi([b.start.x,b.start.y],[b.end.x,b.end.y],[n[0],n[1]]);(D<=i||I<=i)&&(h.push(p.id),f.handles.activeOperation=null),g++}return f.activeViewportIds=[...h],this.editData={annotation:r},f.handles.activeOperation===ns.DRAG}}Fs.toolName="Crosshairs";const zm="magnify-viewport";class HU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{magnifySize:10,magnifyWidth:250,magnifyHeight:250}}){super(e,r),this._hasBeenRemoved=!1,this.preMouseDownCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o),{viewport:c,renderingEngine:l}=s;if(!(c instanceof lr))throw new Error("MagnifyTool only works on StackViewports");const f=this._getReferencedImageId(c);if(!f)throw new Error("MagnifyTool: No referenced image id found, reconstructed planes not supported yet");const u=_t(o,this.getToolName());return this.editData={referencedImageId:f,viewportIdsToRender:u,enabledElement:s,renderingEngine:l,currentPoints:a},this._createMagnificationViewport(),this._activateDraw(o),Ot(o),n.preventDefault(),Pe(u),!0},this.preTouchStartCallback=n=>{this.preMouseDownCallback(n)},this._createMagnificationViewport=()=>{const{enabledElement:n,referencedImageId:i,viewportIdsToRender:o,renderingEngine:a,currentPoints:s}=this.editData,{viewport:c}=n,{element:l}=c,f=c.getProperties(),{rotation:u}=c.getViewPresentation(),{canvas:d,world:h}=s;let g;if(g=l.querySelector(".magnifyTool"),g===null){const v=document.createElement("div");v.classList.add("magnifyTool"),v.style.display="block",v.style.width=`${this.configuration.magnifyWidth}px`,v.style.height=`${this.configuration.magnifyHeight}px`,v.style.position="absolute",g=v,l.querySelector(".viewport-element").appendChild(v);const m={viewportId:zm,type:mr.STACK,element:g};a.enableElement(m)}g.style.top=`${d[1]-this.configuration.magnifyHeight/2}px`,g.style.left=`${d[0]-this.configuration.magnifyWidth/2}px`;const p=a.getViewport(zm);p.setStack([i]).then(()=>{if(this._hasBeenRemoved)return;p.setProperties(f),p.setViewPresentation({rotation:u});const{parallelScale:v}=c.getCamera(),{focalPoint:y,position:m,viewPlaneNormal:w}=p.getCamera(),x=Math.sqrt(Math.pow(y[0]-m[0],2)+Math.pow(y[1]-m[1],2)+Math.pow(y[2]-m[2],2)),C=[h[0],h[1],h[2]],S=[C[0]+x*w[0],C[1]+x*w[1],C[2]+x*w[2]];p.setCamera({parallelScale:v*(1/this.configuration.magnifySize),focalPoint:C,position:S}),p.render()}),g.style.display="block",Pe(o)},this._dragCallback=n=>{const i=n.detail,{deltaPoints:o,element:a,currentPoints:s}=i,c=o.world,l=s.canvas,f=Ce(a),{renderingEngine:u}=f,d=u.getViewport(zm),h=a.querySelector(".magnifyTool");if(!h)return;h.style.top=`${l[1]-this.configuration.magnifyHeight/2}px`,h.style.left=`${l[0]-this.configuration.magnifyWidth/2}px`;const{focalPoint:g,position:p}=d.getCamera(),v=[p[0]+c[0],p[1]+c[1],p[2]+c[2]],y=[g[0]+c[0],g[1]+c[1],g[2]+c[2]];d.setCamera({focalPoint:y,position:v}),d.render()},this._dragEndCallback=n=>{const{element:i}=n.detail,o=Ce(i),{renderingEngine:a}=o;a.disableElement(zm);const s=i.querySelector(".viewport-element"),c=s.querySelector(".magnifyTool");s.removeChild(c),this._deactivateDraw(i),zt(i),this._hasBeenRemoved=!0},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,this._hasBeenRemoved=!1,n.addEventListener(N.MOUSE_UP,this._dragEndCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._dragEndCallback),n.addEventListener(N.TOUCH_END,this._dragEndCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._dragEndCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._dragEndCallback),n.removeEventListener(N.TOUCH_END,this._dragEndCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)}}_getReferencedImageId(e){const r=this.getTargetId(e);let n;return e instanceof lr&&(n=r.split("imageId:")[1]),n}}HU.toolName="Magnify";const i5e="advancedMagnifyTool",o5e=125,{Events:Ll}=ja,QD=t=>t.uid!==t.referencedId;var BC;(function(t){t.ShowZoomFactorsList="showZoomFactorsList"})(BC||(BC={}));const a5e="AdvancedMagnify",s5e=1-wa,_E=class _E extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,magnifyingGlass:{radius:125,zoomFactor:3,zoomFactorList:[1.5,2,2.5,3,3.5,4,4.5,5],autoPan:{enabled:!0,padding:10}},actions:{showZoomFactorsList:{method:"showZoomFactorsList",bindings:[{mouseButton:nc.Secondary,modifierKey:Oi.Shift}]}}}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c,renderingEngine:l}=s,f=o.world,u=o.canvas,{magnifyingGlass:d}=this.configuration,{radius:h,zoomFactor:g,autoPan:p}=d,v=this._getCanvasHandlePoints(u,h),y=c.getCamera(),{viewPlaneNormal:m,viewUp:w}=y,x=this.getReferencedImageId(c,f,m,w),C=Dn(),S=Dn(),_=c.getFrameOfReferenceUID(),T={annotationUID:C,highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...m],viewUp:[...w],FrameOfReferenceUID:_,referencedImageId:x},data:{sourceViewportId:c.id,magnifyViewportId:S,zoomFactor:g,isCanvasAnnotation:!0,handles:{points:v,activeHandleIndex:null}}};this.magnifyViewportManager.createViewport(T,{magnifyViewportId:S,sourceEnabledElement:s,position:u,radius:h,zoomFactor:g,autoPan:{enabled:p.enabled,padding:p.padding,callback:D=>{const b=T.data.handles.points,{canvas:I}=D.delta;for(let P=0,M=b.length;P{this.magnifyViewportManager.dispose(),S1().forEach(i=>{i.metadata.toolName===this.getToolName()&&gn(i.annotationUID)})},this.isPointNearTool=(n,i,o,a)=>{const{data:s}=i,{points:c}=s.handles,l=c,f=l[0],u=l[2],d=l[3],h=Math.abs(u[1]-f[1])*.5,g=[d[0]+h,f[1]+h],p=du([g,o]);return Math.abs(p-h){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},Ot(a),this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;const{points:l}=c.handles,f=l.findIndex(d=>d===o),u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f},this._activateModify(s),Ot(s),Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{data:l}=a;l.handles.activeHandleIndex=null,this._deactivateModify(o),zt(o),this.editData=null,this.isDrawing=!1,Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{deltaPoints:o}=i,a=(o==null?void 0:o.canvas)??[0,0,0],{annotation:s,viewportIdsToRender:c}=this.editData,{points:l}=s.data.handles;l.forEach(f=>{f[0]+=a[0],f[1]+=a[1]}),s.invalidated=!0,this.editData.hasMoved=!0,Pe(c)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c}=this.editData,{data:l}=a;if(c===void 0){const{deltaPoints:f}=i,u=f.canvas;l.handles.points.forEach(h=>{h[0]+=u[0],h[1]+=u[1]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;Pe(s)},this._dragHandle=n=>{const i=n.detail,{annotation:o}=this.editData,{data:a}=o,{points:s}=a.handles,c=s,l=c[0],f=c[2],u=c[3],d=Math.abs(f[1]-l[1])*.5,h=[u[0]+d,l[1]+d],{currentPoints:g}=i,p=g.canvas,v=du([h,p]),y=this._getCanvasHandlePoints(h,v);s[0]=y[0],s[1]=y[1],s[2]=y[2],s[3]=y[3]},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length))return o;c=c==null?void 0:c.filter(u=>u.data.sourceViewportId===a.id);const l=this.filterInteractableAnnotationsForElement(s,c);if(!(l!=null&&l.length))return o;const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let u=0;u[[n[0],n[1]-i,0],[n[0]+i,n[1],0],[n[0],n[1]+i,0],[n[0]-i,n[1],0]],this.magnifyViewportManager=Yd.getInstance()}showZoomFactorsList(e,r){const{element:n,currentPoints:i}=e.detail,o=Ce(n),{viewport:a}=o,{canvas:s}=i,c=n.querySelector(":scope .viewport-element"),l=r.data.zoomFactor,f=()=>u.parentElement.removeChild(u),u=this._getZoomFactorsListDropdown(l,d=>{d!==void 0&&(r.data.zoomFactor=Number.parseFloat(d),r.invalidated=!0),f(),a.render()});Object.assign(u.style,{left:`${s[0]}px`,top:`${s[1]}px`}),c.appendChild(u),u.focus()}_getZoomFactorsListDropdown(e,r){const{zoomFactorList:n}=this.configuration.magnifyingGlass,i=document.createElement("select");return i.size=5,Object.assign(i.style,{width:"50px",position:"absolute"}),["mousedown","mouseup","mousemove","click"].forEach(o=>{i.addEventListener(o,a=>a.stopPropagation())}),i.addEventListener("change",o=>{o.stopPropagation(),r(i.value)}),i.addEventListener("keydown",o=>{var s;((o.keyCode??o.which===27)||((s=o.key)==null?void 0:s.toLowerCase())==="escape")&&(o.stopPropagation(),r())}),n.forEach(o=>{const a=document.createElement("option");a.label=o,a.title=`Zoom factor ${o.toFixed(1)}`,a.value=o,a.defaultSelected=o===e,i.add(a)}),i}};_E.Actions=BC;let Zp=_E;class Yd{constructor(){this.createViewport=(e,r)=>{const{magnifyViewportId:n,sourceEnabledElement:i,position:o,radius:a,zoomFactor:s,autoPan:c}=r,{viewport:l}=i,{element:f}=l,u=new c5e({magnifyViewportId:n,sourceEnabledElement:i,radius:a,position:o,zoomFactor:s,autoPan:c});return this._addSourceElementEventListener(f),this._magnifyViewportsMap.set(u.viewportId,{annotation:e,magnifyViewport:u,magnifyViewportInfo:r}),u},this._annotationRemovedCallback=e=>{const{annotation:r}=e.detail;r.metadata.toolName===a5e&&this.destroyViewport(r.data.magnifyViewportId)},this._newStackImageCallback=e=>{const{viewportId:r,imageId:n}=e.detail,i=this._getMagnifyViewportsMapEntriesBySourceViewportId(r),{viewport:o}=zn(r);o.stackActorReInitialized&&this._reset(r),i.forEach(({annotation:a})=>{a.metadata.referencedImageId=n,a.invalidated=!0})},this._newVolumeImageCallback=e=>{const{renderingEngineId:r,viewportId:n}=e.detail,o=Jr(r).getViewport(n),{viewPlaneNormal:a}=o.getCamera();this._getMagnifyViewportsMapEntriesBySourceViewportId(n).forEach(({annotation:c})=>{const{viewPlaneNormal:l}=c.metadata;if(!(Math.abs(Et(l,a))>s5e))return;const{handles:u}=c.data,d=o.canvasToWorld([0,0]),h=En(Ve(),d,u.points[0]),g=Et(h,a),p=Ni(Ve(),a,g);for(let v=0,y=u.points.length;vthis.destroyViewport(r))}_getMagnifyViewportsMapEntriesBySourceViewportId(e){return Array.from(this._magnifyViewportsMap.values()).filter(({magnifyViewport:n})=>{const{viewport:i}=n.sourceEnabledElement;return i.id===e})}_reset(e){this._getMagnifyViewportsMapEntriesBySourceViewportId(e).forEach(({magnifyViewport:n,annotation:i,magnifyViewportInfo:o})=>{this.destroyViewport(n.viewportId);const a=zn(e);this.createViewport(i,{...o,sourceEnabledElement:{...a}})})}_addEventListeners(){Ke.addEventListener(N.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_removeEventListeners(){Ke.removeEventListener(N.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_addSourceElementEventListener(e){e.addEventListener(Ll.STACK_NEW_IMAGE,this._newStackImageCallback);const r=i=>{const{viewportId:o}=i.detail;this._reset(o)};e.addEventListener(Ll.VIEWPORT_NEW_IMAGE_SET,r);const n=i=>{const{viewportId:o}=i.detail;this._reset(o)};e.addEventListener(Ll.VOLUME_VIEWPORT_NEW_VOLUME,n),e.addEventListener(Ll.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),e.newStackHandler=r,e.newVolumeHandler=n}_removeSourceElementEventListener(e){e.removeEventListener(Ll.STACK_NEW_IMAGE,this._newStackImageCallback),e.removeEventListener(Ll.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),e.removeEventListener(Ll.VIEWPORT_NEW_IMAGE_SET,e.newStackHandler),e.removeEventListener(Ll.VOLUME_VIEWPORT_NEW_VOLUME,e.newVolumeHandler),delete e.newStackHandler,delete e.newVolumeHandler}_initialize(){this._addEventListeners()}}class c5e{constructor({magnifyViewportId:e,sourceEnabledElement:r,radius:n=o5e,position:i=[0,0],zoomFactor:o,autoPan:a}){this._enabledElement=null,this._sourceToolGroup=null,this._magnifyToolGroup=null,this._isViewportReady=!1,this._radius=0,this._resized=!1,this._canAutoPan=!1,this._viewportId=e??Dn(),this._sourceEnabledElement=r,this._autoPan=a,this.radius=n,this.position=i,this.zoomFactor=o,this.visible=!0,this._browserMouseDownCallback=this._browserMouseDownCallback.bind(this),this._browserMouseUpCallback=this._browserMouseUpCallback.bind(this),this._handleToolModeChanged=this._handleToolModeChanged.bind(this),this._mouseDragCallback=this._mouseDragCallback.bind(this),this._resizeViewportAsync=gh(this._resizeViewport.bind(this),1),this._initialize()}get sourceEnabledElement(){return this._sourceEnabledElement}get viewportId(){return this._viewportId}get radius(){return this._radius}set radius(e){Math.abs(this._radius-e)>1e-5&&(this._radius=e,this._resized=!0)}update(){const{radius:e,position:r,visible:n}=this,{viewport:i}=this._enabledElement,{element:o}=i,a=2*e,[s,c]=r;this._resized&&(this._resizeViewportAsync(),this._resized=!1),Object.assign(o.style,{display:n?"block":"hidden",width:`${a}px`,height:`${a}px`,left:`${-e}px`,top:`${-e}px`,transform:`translate(${s}px, ${c}px)`}),this._isViewportReady&&(this._syncViewports(),i.render())}dispose(){const{viewport:e}=this._enabledElement,{element:r}=e,n=e.getRenderingEngine();this._removeEventListeners(r),n.disableElement(e.id),r.parentNode&&r.parentNode.removeChild(r)}_handleToolModeChanged(e){var s;const{_magnifyToolGroup:r}=this,{toolGroupId:n,toolName:i,mode:o,toolBindingsOptions:a}=e.detail;if(((s=this._sourceToolGroup)==null?void 0:s.id)===n)switch(o){case An.Active:r.setToolActive(i,a);break;case An.Passive:r.setToolPassive(i);break;case An.Enabled:r.setToolEnabled(i);break;case An.Disabled:r.setToolDisabled(i);break;default:throw new Error(`Unknow tool mode (${o})`)}}_inheritBorderRadius(e){const r=e.querySelector(".viewport-element"),n=e.querySelector(".cornerstone-canvas");r.style.borderRadius="inherit",n.style.borderRadius="inherit"}_createViewportNode(){const e=document.createElement("div"),{radius:r}=this,n=r*2;return e.classList.add(i5e),Object.assign(e.style,{display:"block",width:`${n}px`,height:`${n}px`,position:"absolute",overflow:"hidden",borderRadius:"50%",boxSizing:"border-box",left:`${-r}px`,top:`${-r}px`,transform:"translate(-1000px, -1000px)"}),e}_convertZoomFactorToParallelScale(e,r,n){const{parallelScale:i}=e.getCamera(),o=r.canvas.offsetWidth/e.canvas.offsetWidth;return i*(1/n)*o}_isStackViewport(e){return"setStack"in e}_isVolumeViewport(e){return"addVolumes"in e}_cloneToolGroups(e,r){const n=e.getActors(),i=`${r.id}-toolGroup`,o=Or(e.id,e.renderingEngineId),a=o.clone(i,s=>{const c=o.getToolInstance(s);return c instanceof ar&&!(c instanceof Zp)});return a.addViewport(r.id,r.renderingEngineId),n.filter(QD).forEach(s=>{Th(this.viewportId,[{segmentationId:s.referencedId,type:Dt.Labelmap}])}),{sourceToolGroup:o,magnifyToolGroup:a}}_cloneStack(e,r){const n=e.getImageIds();r.setStack(n).then(()=>{this._isViewportReady=!0,this.update()})}_cloneVolumes(e,r){const i=e.getActors().filter(o=>!QD(o)).map(o=>({volumeId:o.uid}));return r.setVolumes(i).then(()=>{this._isViewportReady=!0,this.update()}),r}_cloneViewport(e,r){const{viewportId:n}=this,i=e.getRenderingEngine(),{options:o}=e,a={element:r,viewportId:n,type:e.type,defaultOptions:{...o}};i.enableElement(a);const s=i.getViewport(n);this._isStackViewport(e)?this._cloneStack(e,s):this._isVolumeViewport(e)&&this._cloneVolumes(e,s),this._inheritBorderRadius(r);const c=this._cloneToolGroups(e,s);this._sourceToolGroup=c.sourceToolGroup,this._magnifyToolGroup=c.magnifyToolGroup}_cancelMouseEventCallback(e){e.stopPropagation(),e.preventDefault()}_browserMouseUpCallback(e){const{element:r}=this._enabledElement.viewport;document.removeEventListener("mouseup",this._browserMouseUpCallback),r.addEventListener("mouseup",this._cancelMouseEventCallback),r.addEventListener("mousemove",this._cancelMouseEventCallback)}_browserMouseDownCallback(e){var n;const{element:r}=this._enabledElement.viewport;this._canAutoPan=!!((n=e.target)!=null&&n.closest(".advancedMagnifyTool")),document.addEventListener("mouseup",this._browserMouseUpCallback),r.removeEventListener("mouseup",this._cancelMouseEventCallback),r.removeEventListener("mousemove",this._cancelMouseEventCallback)}_mouseDragCallback(e){if(!Ge.isInteractingWithTool)return;const{_autoPan:r}=this;if(!r.enabled||!this._canAutoPan)return;const{currentPoints:n}=e.detail,{viewport:i}=this._enabledElement,{canvasToWorld:o}=i,{canvas:a}=n,{radius:s}=this,c=[s,s],l=yo(c,a),f=s-r.padding;if(l<=f)return;const u=l-f,d=Ga(qt(),a,c);Nc(d,d),Oc(d,d,u);const h=Qi(qt(),this.position,d),g=o(this.position),p=o(h),v=En(Ve(),p,g),y={points:{currentPosition:{canvas:this.position,world:g},newPosition:{canvas:h,world:p}},delta:{canvas:d,world:v}};r.callback(y)}_addBrowserEventListeners(e){document.addEventListener("mousedown",this._browserMouseDownCallback,!0),e.addEventListener("mousedown",this._cancelMouseEventCallback),e.addEventListener("mouseup",this._cancelMouseEventCallback),e.addEventListener("mousemove",this._cancelMouseEventCallback),e.addEventListener("dblclick",this._cancelMouseEventCallback)}_removeBrowserEventListeners(e){document.removeEventListener("mousedown",this._browserMouseDownCallback,!0),document.removeEventListener("mouseup",this._browserMouseUpCallback),e.removeEventListener("mousedown",this._cancelMouseEventCallback),e.removeEventListener("mouseup",this._cancelMouseEventCallback),e.removeEventListener("mousemove",this._cancelMouseEventCallback),e.removeEventListener("dblclick",this._cancelMouseEventCallback)}_addEventListeners(e){Ke.addEventListener(N.TOOL_MODE_CHANGED,this._handleToolModeChanged),e.addEventListener(N.MOUSE_MOVE,this._mouseDragCallback),e.addEventListener(N.MOUSE_DRAG,this._mouseDragCallback),this._addBrowserEventListeners(e)}_removeEventListeners(e){Ke.removeEventListener(N.TOOL_MODE_CHANGED,this._handleToolModeChanged),e.addEventListener(N.MOUSE_MOVE,this._mouseDragCallback),e.addEventListener(N.MOUSE_DRAG,this._mouseDragCallback),this._removeBrowserEventListeners(e)}_initialize(){const{_sourceEnabledElement:e}=this,{viewport:r}=e,{canvas:n}=r,i=this._createViewportNode();n.parentNode.appendChild(i),this._addEventListeners(i),this._cloneViewport(r,i),this._enabledElement=Ce(i)}_syncViewportsCameras(e,r){const n=e.canvasToWorld(this.position),i=this._convertZoomFactorToParallelScale(e,r,this.zoomFactor),{focalPoint:o,position:a,viewPlaneNormal:s}=r.getCamera(),c=Math.sqrt(Math.pow(o[0]-a[0],2)+Math.pow(o[1]-a[1],2)+Math.pow(o[2]-a[2],2)),l=[n[0],n[1],n[2]],f=[l[0]+c*s[0],l[1]+c*s[1],l[2]+c*s[2]];r.setCamera({parallelScale:i,focalPoint:l,position:f})}_syncStackViewports(e,r){r.setImageIdIndex(e.getCurrentImageIdIndex())}_syncViewports(){const{viewport:e}=this._sourceEnabledElement,{viewport:r}=this._enabledElement,n=e.getProperties();r.getImageData()&&(r.setProperties(n),this._syncViewportsCameras(e,r),this._isStackViewport(e)&&this._syncStackViewports(e,r),this._syncViewportsCameras(e,r),r.render())}_resizeViewport(){const{viewport:e}=this._enabledElement;e.getRenderingEngine().resize()}}Zp.toolName="AdvancedMagnify";const{EPSILON:y3}=cd;class Gf extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceViewportId:"",enforceSameFrameOfReference:!0,showFullDimension:!1}}){super(e,r),this.editData=null,this._init=()=>{var h;const i=Qo()[0];if(!i)return;let o=i.getViewports();o=b5(o,this.getToolName());const a=i.getViewport(this.configuration.sourceViewportId);if(!(a!=null&&a.getImageData()))return;const{element:s}=a,{viewUp:c,viewPlaneNormal:l}=a.getCamera(),f=Gv(a);let u=(h=this.editData)==null?void 0:h.annotation;const d=a.getFrameOfReferenceUID();if(u)this.editData.annotation.data.handles.points=f;else{const g={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...c],FrameOfReferenceUID:d,referencedImageId:null},data:{handles:{points:f}}};nn(g,s),u=g}this.editData={sourceViewportId:a.id,renderingEngine:i,annotation:u},Pe(o.filter(g=>g.id!==a.id).map(g=>g.id))},this.onSetToolEnabled=()=>{this._init()},this.onSetToolConfiguration=()=>{this._init()},this.onCameraModified=n=>{this._init()},this.renderAnnotation=(n,i)=>{var F,j;const{viewport:o}=n;if(!this.editData)return!1;const{annotation:a,sourceViewportId:s}=this.editData;let c=!1;const{viewport:l}=zn(s)||{};if(!l||l.id===o.id||!a||!((j=(F=a==null?void 0:a.data)==null?void 0:F.handles)!=null&&j.points)||this.configuration.enforceSameFrameOfReference&&l.getFrameOfReferenceUID()!==o.getFrameOfReferenceUID())return c;const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=a.data.handles.points[0],d=a.data.handles.points[1],h=a.data.handles.points[2],g=a.data.handles.points[3],{focalPoint:p,viewPlaneNormal:v,viewUp:y}=o.getCamera(),{viewPlaneNormal:m}=l.getCamera();if(this.isParallel(v,m))return c;const w=qs(v,p),x=[u,h,d,g],C=[u,d,h,g];let S=x,_=rr(Ve(),x[0],x[1]);_=tr(Ve(),_);let T=rr(Ve(),x[2],x[0]);T=tr(Ve(),T);const E=Rn(Ve(),_,T);if(this.isParallel(E,v))return c;this.isPerpendicular(_,v)&&(S=C);const D=F0(S[0],S[1],w),b=F0(S[2],S[3],w),{annotationUID:I}=a;f.annotationUID=I;const P=this.getStyle("lineWidth",f,a),M=this.getStyle("lineDash",f,a),L=this.getStyle("color",f,a),V=this.getStyle("shadow",f,a);let G=[D,b].map(Y=>o.worldToCanvas(Y));if(this.configuration.showFullDimension&&(G=this.handleFullDimension(o,D,v,y,b,G)),G.length<2)return c;const A=`${I}-line`;return vn(i,I,"1",G[0],G[1],{color:L,width:P,lineDash:M,shadow:V},A),c=!0,c},this.isPerpendicular=(n,i)=>{const o=Et(n,i);return Math.abs(o)pC(l,m)),[v,y]=[r,o].map(m=>pC(l,m));a=[[d,h],[h,g],[p,g],[d,p]].map(([m,w])=>this.intersectInfiniteLines(m,w,v,y)).filter(m=>m&&this.isInBound(m,u)).map(m=>{const w=jA(l,m);return e.worldToCanvas(w)})}catch(f){console.log(f)}return a}intersectInfiniteLines(e,r,n,i){const[o,a]=e,[s,c]=r,[l,f]=n,[u,d]=i,h=c-a,g=o-s,p=s*a-o*c,v=d-f,y=l-u,m=u*f-l*d;if(Math.abs(h*y-v*g)1-y3}isInBound(e,r){return e[0]>=0&&e[0]<=r[0]&&e[1]>=0&&e[1]<=r[1]}}Gf.toolName="ReferenceLines";const{EPSILON:eb}=cd;class KU extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceImageIds:[]}}){super(e,r),this.onSetToolEnabled=()=>{this._init()},this.onSetToolActive=()=>{this._init()},this._init=()=>{const n=this.configuration.sourceImageIds;if(!(n!=null&&n.length)){console.warn("OverlayGridTool: No sourceImageIds provided in configuration");return}const i=mt("imagePlaneModule",n[0]);if(!i){console.warn("OverlayGridTool: No imagePlaneModule found for sourceImageIds");return}const{frameOfReferenceUID:o}=i,a=Kr(this.toolGroupId).viewportsInfo;if(!(a!=null&&a.length)){console.warn("OverlayGridTool: No viewports found");return}const s=un(this.getToolName(),o);if(!(s!=null&&s.length)){const c=n.map(f=>this.calculateImageIdPointSets(f)),l={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:o,referencedImageId:null},data:{viewportData:new Map,pointSets:c}};nn(l,o)}Pe(a.map(({viewportId:c})=>c))},this.calculateImageIdPointSets=n=>{const{imagePositionPatient:i,rows:o,columns:a,rowCosines:s,columnCosines:c,rowPixelSpacing:l,columnPixelSpacing:f}=mt("imagePlaneModule",n),u=[...i],d=[...i],h=[...i],g=[...i];return Tn(d,i,c,a*f),Tn(h,i,s,o*l),Tn(g,h,c,a*f),{pointSet1:[u,h,d,g],pointSet2:[u,d,h,g]}},this.renderAnnotation=(n,i)=>{const o=this.configuration.sourceImageIds;let a=!1;if(!(o!=null&&o.length))return a;const{viewport:s,FrameOfReferenceUID:c}=n;if(s.getImageIds().length<2)return a;const f=un(this.getToolName(),c);if(!(f!=null&&f.length))return a;const u=f[0],{annotationUID:d}=u,{focalPoint:h,viewPlaneNormal:g}=s.getCamera(),p={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},v=this.getImageIdNormal(o[0]);if(this.isParallel(g,v))return a;const y=qs(g,h),m=u.data.pointSets,w=u.data.viewportData;for(let x=0;xs.worldToCanvas(G)),L=`${d}-line`,V=`${x}`;vn(i,d,V,M[0],M[1],{color:I,width:D,lineDash:b,shadow:P},L)}return a=!0,a},this.initializeViewportData=(n,i)=>(n.set(i,{pointSetsToUse:[],lineStartsWorld:[],lineEndsWorld:[]}),n.get(i)),this.isPerpendicular=(n,i)=>{const o=Et(n,i);return Math.abs(o)1-eb}getImageIdNormal(e){const{imageOrientationPatient:r}=mt("imagePlaneModule",e),n=bt(r[0],r[1],r[2]),i=bt(r[3],r[4],r[5]);return Rn(Ve(),n,i)}}KU.toolName="OverlayGrid";class qU extends Fu{constructor(e={},r={configuration:{opacity:.5}}){super(e,r),this._init=()=>{var s;const n=Kr(this.toolGroupId).viewportsInfo;if(!(n!=null&&n.length)){console.warn(this.getToolName()+"Tool: No viewports found");return}const i=(s=Jr(n[0].renderingEngineId))==null?void 0:s.getViewport(n[0].viewportId);if(!i)return;const o=i.getFrameOfReferenceUID(),a=un(this.getToolName(),o);if(!(a!=null&&a.length)){const c=new Map;l5e(c,n);const l={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:o,referencedImageId:null},data:{actorsWorldPointsMap:c}};nn(l,o)}Pe(n.map(({viewportId:c})=>c))},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=n=>{this._init()},this.renderAnnotation=(n,i)=>{const{viewport:o,FrameOfReferenceUID:a}=n;let s=!1;const c=un(this.getToolName(),a);if(!(c!=null&&c.length))return s;const l=c[0],{annotationUID:f}=l,u=l.data.actorsWorldPointsMap;XU(u,o);const d=o.getActors(),h=YU(o);return d.forEach(g=>{if(!(g!=null&&g.clippingFilter))return;const p=u.get(g.uid);if(!p||!p.get(h))return;let v=1;const{worldPointsSet:y,color:m}=p.get(h);for(let w=0;wo.worldToCanvas(T)),S={color:m,fillColor:m,fillOpacity:this.configuration.opacity,closePath:!0,lineWidth:2},_=g.uid+"#"+v;Wc(i,f,_,C,S),v++}}),s=!0,s}}}function l5e(t,e){e.forEach(({viewportId:r,renderingEngineId:n})=>{var o;const i=(o=Jr(n))==null?void 0:o.getViewport(r);XU(t,i)})}function XU(t,e){const r=e.getActors(),n=YU(e);r.forEach(i=>{if(!(i!=null&&i.clippingFilter))return;let o=t.get(i.uid);if(o||(o=new Map,t.set(i.uid,o)),!o.get(n)){const a=i.clippingFilter.getOutputData(),s=bU(a);if(!s)return;const c=i.actor.getProperty().getColor(),l=u5e(c);o.set(n,{worldPointsSet:s,color:l})}})}function YU(t){const{viewPlaneNormal:e}=t.getCamera(),r=t.getCurrentImageIdIndex();return`${t.id}-${dF(e)}-${r}`}function u5e(t){function e(r){let n=Math.floor(r*255).toString(16);return n.length===1&&(n="0"+n),n}return"#"+e(t[0])+e(t[1])+e(t[2])}qU.toolName="SegmentationIntersection";class ua extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,displayThreshold:5,positionSync:!0,disableCursor:!1}}){super(e,r),this.isDrawing=!1,this.isHandleOutsideImage=!1,this._elementWithCursor=null,this._currentCursorWorldPosition=null,this._currentCanvasPosition=null,this._disableCursorEnabled=!1,this.mouseMoveCallback=n=>{const{detail:i}=n,{element:o,currentPoints:a}=i;this._currentCursorWorldPosition=a.world,this._currentCanvasPosition=a.canvas,this._elementWithCursor=o;const s=this.getActiveAnnotation(o);return s===null?(this.createInitialAnnotation(a.world,o),!1):(this.updateAnnotationPosition(o,s),!1)},this.createInitialAnnotation=(n,i)=>{const o=Ce(i);if(!o)throw new Error("No enabled element found");const{viewport:a,renderingEngine:s}=o;this.isDrawing=!0;const c=a.getCamera(),{viewPlaneNormal:l,viewUp:f}=c;if(!l||!f)throw new Error("Camera not found");const u=this.getReferencedImageId(a,n,l,f),d=a.getFrameOfReferenceUID(),h={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...f],FrameOfReferenceUID:d,referencedImageId:u},data:{label:"",handles:{points:[[...n]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}};if(un(this.getToolName(),i).length>0)return null;if(nn(h,i)===null)return;const v=_t(i,this.getToolName(),!1);Pe(v)},this.onCameraModified=n=>{const i=n.detail,{element:o,previousCamera:a,camera:s}=i,l=Ce(o).viewport;if(o!==this._elementWithCursor)return;const f=a.focalPoint,u=s.viewPlaneNormal,d=s.focalPoint,h=[0,0,0];if(Xt.subtract(d,f,h),h.reduce((v,y)=>v+y,0)===0)return;const g=Xt.dot(h,u);if(Math.abs(g)<.01||!this._currentCanvasPosition)return;const p=l.canvasToWorld(this._currentCanvasPosition);this._currentCursorWorldPosition=p,this.updateAnnotationPosition(o,this.getActiveAnnotation(o))},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a,FrameOfReferenceUID:s}=n,c=this._elementWithCursor===a.element;this.configuration.positionSync&&!c&&this.updateViewportImage(a);const{element:l}=a;let f=un(this.getToolName(),l);if(!(f!=null&&f.length)||(f=this.filterInteractableAnnotationsForElement(l,f),!(f!=null&&f.length)))return o;const u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;disNaN(I)))return o;const S=y.map(I=>a.worldToCanvas(I));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(g))continue;const _={upper:"upper",right:"right",lower:"lower",left:"left"},[T,E]=S[0],D=c?20:7,b=c?5:7;vn(i,g,_.upper,[T,E-(D/2+b)],[T,E-D/2],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.lower,[T,E+(D/2+b)],[T,E+D/2],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.right,[T+(D/2+b),E],[T+D/2,E],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.left,[T-(D/2+b),E],[T-D/2,E],{color:C,lineDash:x,lineWidth:w}),o=!0}return o},this._disableCursorEnabled=this.configuration.disableCursor}onSetToolActive(){if(this._disableCursorEnabled=this.configuration.disableCursor,!this._disableCursorEnabled)return;const e=Kr(this.toolGroupId).viewportsInfo;if(!e)return;e.map(n=>Ti(n.viewportId,n.renderingEngineId)).forEach(n=>{n&&Ot(n.viewport.element)})}onSetToolDisabled(){if(!this._disableCursorEnabled)return;const e=Kr(this.toolGroupId).viewportsInfo;if(!e)return;e.map(n=>Ti(n.viewportId,n.renderingEngineId)).forEach(n=>{n&&zt(n.viewport.element)})}getActiveAnnotation(e){const r=un(this.getToolName(),e);return r.length?r[0]:null}updateAnnotationPosition(e,r){var a,s;const n=this._currentCursorWorldPosition;if(!n||!((s=(a=r.data)==null?void 0:a.handles)!=null&&s.points))return;r.data.handles.points=[[...n]],r.invalidated=!0;const i=_t(e,this.getToolName(),!1);Ce(e)&&Pe(i)}filterInteractableAnnotationsForElement(e,r){var d,h,g;if(!(r instanceof Array)||r.length===0)return[];const n=r[0],i=(d=Ce(e))==null?void 0:d.viewport;if(!i)return[];const o=i.getCamera(),{viewPlaneNormal:a,focalPoint:s}=o;if(!a||!s)return[];const c=(g=(h=n.data)==null?void 0:h.handles)==null?void 0:g.points;if(!(c instanceof Array)||c.length!==1)return[];const l=c[0],f=qs(a,s);return Mp(f,l)isNaN(n)))){if(e instanceof lr){const n=FT(r,e);if(n===null)return;n!==e.getCurrentImageIdIndex()&&e.setImageIdIndex(n)}else if(e instanceof ur){const{focalPoint:n,viewPlaneNormal:i}=e.getCamera();if(!n||!i)return;const o=qs(i,n),a=Mp(o,r,!0);if(Math.abs(a)<.5)return;const s=tr(Ve(),bt(...i)),c=Ni(Ve(),s,a),l=Ai(Ve(),bt(...n),c);{e.setCamera({focalPoint:l});const f=e.getRenderingEngine();f&&f.renderViewport(e.id)}}}}}ua.toolName="ReferenceCursors";const tb=[];class JU extends Fu{constructor(e={},r={configuration:{viewportId:"",scaleLocation:"bottom"}}){super(e,r),this.editData=null,this._init=()=>{var g,p;const i=Qo()[0];if(!i)return;const o=Kr(this.toolGroupId).viewportsInfo;if(!o)return;const a=o.map(v=>Ti(v.viewportId,v.renderingEngineId));let{viewport:s}=a[0];const{FrameOfReferenceUID:c}=a[0];if(this.configuration.viewportId&&a.forEach(v=>{v.viewport.id==this.configuration.viewportId&&(s=v.viewport)}),!s)return;const{viewUp:l,viewPlaneNormal:f}=s.getCamera(),u=Gv(s);let d=(g=this.editData)==null?void 0:g.annotation;const h=un(this.getToolName(),s.element);h.length&&(d=h.filter(v=>v.data.viewportId==s.id)[0]),a.forEach(v=>{const{viewport:y}=v;if(!tb.includes(y.id)){const m={metadata:{toolName:this.getToolName(),viewPlaneNormal:[...f],viewUp:[...l],FrameOfReferenceUID:c,referencedImageId:null},data:{handles:{points:Gv(y)},viewportId:y.id}};tb.push(y.id),nn(m,y.element),d=m}}),(p=this.editData)!=null&&p.annotation&&this.editData.annotation.data.viewportId==s.id&&(this.editData.annotation.data.handles.points=u,this.editData.annotation.data.viewportId=s.id),this.editData={viewport:s,renderingEngine:i,annotation:d}},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=n=>{this.configuration.viewportId=n.detail.viewportId,this._init()},this.computeScaleSize=(n,i,o)=>{const a=[16e3,8e3,4e3,2e3,1e3,500,250,100,50,25,10,5,2];let s;return o=="top"||o=="bottom"?s=a.filter(c=>cn*.2):s=a.filter(c=>ci*.2),s[0]},this.computeEndScaleTicks=(n,i)=>{const o={bottom:[[0,-10],[0,-10]],top:[[0,10],[0,10]],left:[[0,0],[10,0]],right:[[0,0],[-10,0]]},a=[[n[1][0]+o[i][0][0],n[1][1]+o[i][0][0]],[n[1][0]+o[i][1][0],n[1][1]+o[i][1][1]]],s=[[n[0][0]+o[i][0][0],n[0][1]+o[i][0][0]],[n[0][0]+o[i][1][0],n[0][1]+o[i][1][1]]];return{endTick1:a,endTick2:s}},this.computeInnerScaleTicks=(n,i,o,a,s)=>{let c;i=="bottom"||i=="top"?c=s[0][0]-a[0][0]:(i=="left"||i=="right")&&(c=s[0][1]-a[0][1]);const l=[],f=[],u=[];let d=n;n>=50&&(d=n/10);const h=c/d;for(let g=0;g{let a,s=rr(Ve(),o[0],o[1]);s=tr(Ve(),s);let c=rr(Ve(),o[2],o[0]);c=tr(Ve(),c);const l={bottom:[o[1],o[2]],top:[o[0],o[3]],right:[o[2],o[3]],left:[o[0],o[1]]},f=Ai(Ve(),l[i][0],l[i][0]).map(d=>d/2),u=n/2/Math.sqrt(Math.pow(s[0],2)+Math.pow(s[1],2)+Math.pow(s[2],2));return i=="top"||i=="bottom"?a=[rr(Ve(),f,c.map(d=>d*u)),Ai(Ve(),f,c.map(d=>d*u))]:(i=="left"||i=="right")&&(a=[Ai(Ve(),f,s.map(d=>d*u)),rr(Ve(),f,s.map(d=>d*u))]),a},this.computeCanvasScaleCoordinates=(n,i,o,a,s)=>{let c;if(s=="top"||s=="bottom"){const l=i[0][0]-i[1][0];c=[[n.width/2-l/2,o.height],[n.width/2+l/2,o.height]]}else if(s=="left"||s=="right"){const l=i[0][1]-i[1][1];c=[[a.width,n.height/2-l/2],[a.width,n.height/2+l/2]]}return c},this.computeScaleBounds=(n,i,o,a)=>{const s=i*Math.min(1e3,n.width),c=o*Math.min(1e3,n.height),l={bottom:[-c,-s],top:[c,s],left:[c,s],right:[-c,-s]},f={bottom:[n.height,n.width],top:[0,n.width],left:[n.height,0],right:[n.height,n.width]};return{height:f[a][0]+l[a][0],width:f[a][1]+l[a][1]}}}renderAnnotation(e,r){if(!this.editData||!this.editData.viewport)return;const n=this.configuration.scaleLocation,{viewport:i}=e,a=un(this.getToolName(),i.element).filter(pe=>pe.data.viewportId==i.id)[0],s=e.viewport.canvas,c=!1;if(!i)return c;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},f={width:s.width/window.devicePixelRatio||1,height:s.height/window.devicePixelRatio||1},u=a.data.handles.points[0],d=a.data.handles.points[1],h=a.data.handles.points[2],g=a.data.handles.points[3],p=[u,h,d,g],v=ki(h,g),y=ki(u,h),m=this.computeScaleBounds(f,.05,.05,n),w=this.computeScaleBounds(f,.05,.05,n),x=this.computeScaleSize(v,y,n),C=this.computeWorldScaleCoordinates(x,n,p).map(pe=>i.worldToCanvas(pe)),S=this.computeCanvasScaleCoordinates(f,C,w,m,n),_=this.computeEndScaleTicks(S,n),{annotationUID:T}=a;l.annotationUID=T;const E=this.getStyle("lineWidth",l,a),D=this.getStyle("lineDash",l,a),b=this.getStyle("color",l,a),I=this.getStyle("shadow",l,a),P=`${T}-scaleline`;vn(r,T,"1",S[0],S[1],{color:b,width:E,lineDash:D,shadow:I},P);const L=`${T}-left`;vn(r,T,"2",_.endTick1[0],_.endTick1[1],{color:b,width:E,lineDash:D,shadow:I},L);const G=`${T}-right`;vn(r,T,"3",_.endTick2[0],_.endTick2[1],{color:b,width:E,lineDash:D,shadow:I},G);const k={bottom:[-10,-42],top:[-12,-35],left:[-40,-20],right:[-50,-20]},F=[S[0][0]+k[n][0],S[0][1]+k[n][1]],j=this._getTextLines(x),{tickIds:Y,tickUIDs:re,tickCoordinates:ue}=this.computeInnerScaleTicks(x,n,T,_.endTick1,_.endTick2);for(let pe=0;pe=50?(r=e/10,n=" cm"):(r=e,n=" mm"),[r.toString().concat(n)]}}JU.toolName="ScaleOverlay";const ZU=(t,e,r)=>{var a,s,c;if(!((c=(s=(a=e==null?void 0:e.data)==null?void 0:a.contour)==null?void 0:s.polyline)!=null&&c.length))return;const{polyline:n}=e.data.contour,{length:i}=n;let o=1/0;for(let l=0;lthis.toolInfo.toolSize||(this.pushOneHandle(s,a,r),o.first===void 0&&(o.first=s),o.last=s)}if(o.first!==void 0&&o.last!==void 0)for(let s=0;s0&&(i.toolSize=Math.min(i.maxToolSize,o))}getMaxSpacing(e){return Math.max(this.toolInfo.toolSize/4,e)}getInsertPosition(e,r,n){let i;const{points:o,element:a,mouseCanvasPoint:s}=n,c=this.toolInfo.toolSize,l=Ce(a),{viewport:f}=l,u=f.worldToCanvas(o[e]),d=f.worldToCanvas(o[r]),h=[(u[0]+d[0])/2,(u[1]+d[1])/2],g=yo(s,h);if(g=0;l--){if(l>=s-1||l<0)continue;const f=l+1,u=yo(n[l],n[f]);if(u>c){const d=this.directionalVector(n[l],n[f]),g=(u-e.meanDistance)/e.meanDistance*e.meanDistance*Ns.CHAIN_PULL_STRENGTH_FACTOR;n[l][0]+=d[0]*g,n[l][1]+=d[1]*g,n[l][2]+=d[2]*g}}for(let l=a+1;l=s||l<=0)continue;const f=l-1,u=yo(n[l],n[f]);if(u>c){const d=this.directionalVector(n[l],n[f]),g=(u-e.meanDistance)/e.meanDistance*e.meanDistance*Ns.CHAIN_PULL_STRENGTH_FACTOR;n[l][0]+=d[0]*g,n[l][1]+=d[1]*g,n[l][2]+=d[2]*g}}}};Ns.shapeName="Circle",Ns.CHAIN_MAINTENANCE_ITERATIONS=3,Ns.CHAIN_PULL_STRENGTH_FACTOR=.3,Ns.MAX_INTER_DISTANCE_FACTOR=1.2;let Hg=Ns;class X0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{minSpacing:1,referencedToolNames:["PlanarFreehandROI","PlanarFreehandContourSegmentationTool"],toolShape:"circle",referencedToolName:"PlanarFreehandROI",updateCursorSize:"dynamic"}}){super(e,r),this.registeredShapes=new Map,this.isActive=!1,this.commonData={activeAnnotationUID:null,viewportIdsToRender:[],isEditingOpenContour:!1,canvasLocation:void 0},this.preMouseDownCallback=n=>{const i=n.detail,o=i.element;if(this.configureToolSize(n),this.selectFreehandTool(i),this.commonData.activeAnnotationUID!==null)return this.isActive=!0,Ot(o),this.activateModify(o),!0},this.mouseMoveCallback=n=>{this.mode===An.Active?(this.configureToolSize(n),this.updateCursor(n)):this.commonData.canvasLocation=void 0},this.endCallback=n=>{const i=n.detail,{element:o}=i,a=this.configuration,s=Ce(o);this.isActive=!1,this.deactivateModify(o),zt(o);const{renderingEngineId:c,viewportId:l}=s,u=Or(l,c).getToolInstance(a.referencedToolName),h=this.filterSculptableAnnotationsForElement(o).find(g=>g.annotationUID===this.commonData.activeAnnotationUID);u.configuration.calculateStats&&(h.invalidated=!0),tn(h,o,Ht.HandlesUpdated)},this.dragCallback=n=>{const i=n.detail,o=i.element;this.updateCursor(n);const a=this.filterSculptableAnnotationsForElement(o),s=a.find(l=>l.annotationUID===this.commonData.activeAnnotationUID);if(!(a!=null&&a.length)||!this.isActive)return;const c=s.data.contour.polyline;this.sculpt(i,c)},this.registerShapes(Hg.shapeName,Hg),this.setToolShape(this.configuration.toolShape)}registerShapes(e,r){const n=new r;this.registeredShapes.set(e,n)}sculpt(e,r){const n=this.configuration,i=e.element,o=Ce(i),{viewport:a}=o,s=this.registeredShapes.get(this.selectedShape);this.sculptData={mousePoint:e.currentPoints.world,mouseCanvasPoint:e.currentPoints.canvas,deltaWorld:e.deltaPoints.world,points:r,maxSpacing:s.getMaxSpacing(n.minSpacing),element:i};const c=s.pushHandles(a,this.sculptData);c.first!==void 0&&this.insertNewHandles(c)}interpolatePointsWithinMaxSpacing(e,r,n,i){const{element:o}=this.sculptData,a=Ce(o),{viewport:s}=a,c=nb(e+1,r.length),l=s.worldToCanvas(r[e]),f=s.worldToCanvas(r[c]);yo(l,f)>i&&n.push(e)}updateCursor(e){const r=e.detail,n=r.element,i=Ce(n),{renderingEngine:o,viewport:a}=i;this.commonData.viewportIdsToRender=[a.id];const s=this.filterSculptableAnnotationsForElement(n);if(!(s!=null&&s.length))return;const c=s.find(l=>l.annotationUID===this.commonData.activeAnnotationUID);if(this.commonData.canvasLocation=r.currentPoints.canvas,this.isActive)c.highlighted=!0;else{const l=this.registeredShapes.get(this.selectedShape),f=r.currentPoints.canvas;this.configuration.updateCursorSize==="dynamic"&&l.updateToolSize(f,a,c)}Pe(this.commonData.viewportIdsToRender)}filterSculptableAnnotationsForElement(e){const r=this.configuration,n=Ce(e),{renderingEngineId:i,viewportId:o}=n,a=[],c=Or(o,i).getToolInstance(r.referencedToolName);return r.referencedToolNames.forEach(l=>{const f=un(l,e);f&&a.push(...f)}),c.filterInteractableAnnotationsForElement(e,a)}configureToolSize(e){this.registeredShapes.get(this.selectedShape).configureToolSize(e)}insertNewHandles(e){const r=this.findNewHandleIndices(e);let n=0;for(let i=0;i<(r==null?void 0:r.length);i++){const o=r[i]+1+n;this.insertHandleRadially(o),n++}}findNewHandleIndices(e){const{points:r,maxSpacing:n}=this.sculptData,i=[];for(let o=e.first;o<=e.last;o++)this.interpolatePointsWithinMaxSpacing(o,r,i,n);return i}insertHandleRadially(e){const{points:r}=this.sculptData;if(e>r.length-1&&this.commonData.isEditingOpenContour)return;const n=this.registeredShapes.get(this.selectedShape),i=e-1,o=nb(e,r.length),s=n.getInsertPosition(i,o,this.sculptData);r.splice(e,0,s)}selectFreehandTool(e){const r=this.getClosestFreehandToolOnElement(e);r!==void 0&&(this.commonData.activeAnnotationUID=r)}getClosestFreehandToolOnElement(e){const{element:r}=e,n=Ce(r),{viewport:i}=n,o=this.configuration,a=this.filterSculptableAnnotationsForElement(r);if(!(a!=null&&a.length))return;const s=e.currentPoints.canvas,c={distance:1/0,toolIndex:void 0,annotationUID:void 0};for(let l=0;l<(a==null?void 0:a.length);l++){if(a[l].isLocked||!a[l].isVisible)continue;const f=ZU(i,a[l],s);f!==-1&&f(t+e)%e;X0.toolName="SculptorTool";const f5e={Z:[0,0,1]};class QU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{direction:f5e.Z,rotateIncrementDegrees:30}}){super(e,r)}mouseWheelCallback(e){const{element:r,wheel:n}=e.detail,i=Ce(r),{viewport:o}=i,{direction:a,rotateIncrementDegrees:s}=this.configuration,c=o.getCamera(),{viewUp:l,position:f,focalPoint:u}=c,{direction:d}=n,[h,g,p]=u,[v,y,m]=a,w=d*(s*Math.PI)/180,x=[0,0,0],C=[0,0,0],S=[0,0,0],_=Vt(new Float32Array(16));Lr(_,_,[h,g,p]),go(_,_,w,[v,y,m]),Lr(_,_,[-h,-g,-p]),Jt(x,f,_),Jt(C,u,_),Vt(_),go(_,_,w,[v,y,m]),Jt(S,l,_),o.setCamera({position:x,viewUp:S,focalPoint:C}),o.render()}}QU.toolName="VolumeRotateMouseWheel";const np=class np extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,getTextCallback:d5e,changeTextCallback:h5e,preventHandleOutsideImage:!1}}){super(e,r),this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{annotationUID:l}=i,f=i.data.handles.points[0],u=c.worldToCanvas(f);if(yr(o,u)=x&&o[0]<=x+v.width&&o[1]>=C&&o[1]<=C+v.height},this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=this.getReferencedImageId(l,s,u,d),g=l.getFrameOfReferenceUID(),p={annotationUID:null,highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:g,referencedImageId:h,...l.getViewReference({points:[s]})},data:{text:"",handles:{points:[[...s],[...s]]},label:""}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,newAnnotation:!0,viewportIdsToRender:v,offset:[0,0,0]},n.preventDefault(),Pe(v),this.configuration.getTextCallback(y=>{if(!y){gn(p.annotationUID),Pe(v),this.isDrawing=!1;return}zt(a),p.data.text=y,Nn(p),Pe(v)}),this.createMemo(a,p,{newAnnotation:!0}),p},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a,currentPoints:s}=o;i.highlighted=!0;const c=_t(a,this.getToolName());let l=[0,0,0];if(s&&s.world){const f=s.world,u=i.data.handles.points[0];l=[u[0]-f[0],u[1]-f[1],u[2]-f[2]]}this.editData={annotation:i,viewportIdsToRender:c,offset:l},this._activateModify(a),Ot(a),Pe(c),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData;this._deactivateDraw(o),this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragCallback=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,offset:f}=this.editData;f?c.data.handles.points[0]=[s[0]+f[0],s[1]+f[1],s[2]+f[2]]:c.data.handles.points[0]=[...s],c.invalidated=!0,Pe(l),tn(c,a,Ht.LabelChange)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length))return o;c=this.filterInteractableAnnotationsForElement(s,c);const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;f{const o=zn(e);if(!o)return;const{viewport:a}=o,s=a.getFrameOfReferenceUID(),{viewPlaneNormal:c,viewUp:l}=a.getCamera(),f=new np,u=f.getReferencedImageId(a,r,c,l),d={annotationUID:(i==null?void 0:i.annotationUID)||Dn(),data:{text:n,handles:{points:[r]}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:f.getToolName(),viewPlaneNormal:c,FrameOfReferenceUID:s,referencedImageId:u,...i}};nn(d,a.element),Pe([a.id])};let hy=np;function d5e(t){return t(prompt("Enter your annotation:"))}function h5e(t,e,r){return r(prompt("Enter your annotation:"))}hy.toolName="Label";const{transformWorldToIndex:rb}=Mn,n0=class n0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:g5e,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:f,viewUp:u,position:d}=l.getCamera(),h=this.getReferencedImageId(l,s,f,u),g={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:h,viewUp:u,cameraPosition:d},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(g,a);const p=_t(a,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(p),g},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=d.world;u.handles.points[c]=[...h],a.invalidated=!0}this.editData.hasMoved=!0,Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(k));if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let _;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(_=[S[y]]),_&&ir(i,g,"0",S,{color:m,lineDash:x,lineWidth:w});const T=`${g}-line`;if(vn(i,g,"1",S[0],S[1],{color:m,width:w,lineDash:x,shadow:C},T),o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const D=this.getLinkedTextBoxStyle(u,h);if(!D.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const b=this.configuration.getTextLines(p,l);if(!p.handles.textBox.hasMoved){const k=na(S);p.handles.textBox.worldPosition=a.canvasToWorld(k)}const I=a.worldToCanvas(p.handles.textBox.worldPosition),M=qi(i,g,"1",b,I,S,{},D),{x:L,y:V,width:G,height:A}=M;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([L,V]),topRight:a.canvasToWorld([L+G,V]),bottomLeft:a.canvasToWorld([L,V+A]),bottomRight:a.canvasToWorld([L+G,V+A])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(f=>f===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o),Pe(l),e.preventDefault()}_calculateLength(e,r){const n=e[0]-r[0],i=e[1]-r[1],o=e[2]-r[2];return Math.sqrt(n*n+i*i+o*o)}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport,a=i.handles.points[0],s=i.handles.points[1],{cachedStats:c}=i,l=Object.keys(c);for(let u=0;u{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=n0.hydrateBase(n0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let Iu=n0;function g5e(t,e){const r=t.cachedStats[e],{length:n,unit:i}=r;return n==null||isNaN(n)?void 0:[`${an(n)} ${i}`]}const{transformWorldToIndex:ib}=Mn,TE=class TE extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:p5e}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:u,viewUp:d,position:h}=l.getCamera(),g=this.getReferencedImageId(l,s,u,d),p={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:g,viewUp:d,cameraPosition:h},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,viewportIdsToRender:v,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(v),p},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Ce(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l}=this.editData,{data:f}=a;if(l){const{deltaPoints:h}=i,g=h.world,{textBox:p}=f.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=i,g=h.world;f.handles.points.forEach(v=>{v[0]+=g[0],v[1]+=g[1],v[2]+=g[2]}),a.invalidated=!0}else{const{currentPoints:h}=i,g=h.world;f.handles.points[c]=[...g],a.invalidated=!0}this.editData.hasMoved=!0;const u=Ce(o),{renderingEngine:d}=u;Pe(s)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Ce(n),Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(A));let _;if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!Gr(g))continue;if(!Zr(g)&&!this.editData&&y!==null&&(_=[S[y]]),_&&ir(i,g,"0",S,{color:m,lineDash:x,lineWidth:w}),Gk(i,g,"0",S[0],S[1],{color:m,width:w,lineDash:x}),o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const E=this.getLinkedTextBoxStyle(u,h);if(!E.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const D=this.configuration.getTextLines(p,l);if(!p.handles.textBox.hasMoved){const A=na(S);p.handles.textBox.worldPosition=a.canvasToWorld(A)}const b=a.worldToCanvas(p.handles.textBox.worldPosition),P=qi(i,g,"1",D,b,S,{},E),{x:M,y:L,width:V,height:G}=P;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([M,L]),topRight:a.canvasToWorld([M+V,L]),bottomLeft:a.canvasToWorld([M,L+G]),bottomRight:a.canvasToWorld([M+V,L+G])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_calculateHeight(e,r){const n=r[0]-e[0],i=r[1]-e[1],o=r[2]-e[2];if(n==0)return i!=0?Math.abs(o):0;if(i==0)return Math.abs(o);if(o==0)return Math.abs(i)}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport,a=i.handles.points[0],s=i.handles.points[1],{cachedStats:c}=i,l=Object.keys(c);for(let u=0;u{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...s]]}}});nn(f,a);const u=_t(a,this.getToolName());return this.editData={annotation:f,newAnnotation:!0,viewportIdsToRender:u},this._activateModify(a),Ot(a),n.preventDefault(),Pe(u),f},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:f}=Ce(o);this.eventDispatchDetail={viewportId:l,renderingEngineId:f.id},this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,newAnnotation:f}=this.editData,{data:u}=c;this.createMemo(a,c,{newAnnotation:f}),u.handles.points[0]=[...s],c.invalidated=!0,Pe(l)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;d{const I=Vr(_),P=b.hasImageURI(I),M=Vr(b.getCurrentImageId());return P&&M!==I})&&delete p.cachedStats[T]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(g))continue;ir(i,g,"0",[y],{color:m,lineWidth:w,handleRadius:this.configuration.handleRadius}),o=!0;const C=this.getLinkedTextBoxStyle(u,h);if(!C.visibility)continue;const S=this.configuration.getTextLines(p,l);if(S){const _=[y[0]+this.configuration.textCanvasOffset.x,y[1]+this.configuration.textCanvasOffset.y];Eu(i,g,"0",S,[_[0],_[1]],C)}}return o}}isPointNearTool(e,r,n,i){const o=Ce(e),{viewport:a}=o,{data:s}=r,c=s.handles.points[0],l=a.worldToCanvas(c);return yr(n,l)b!==null);_=D?E.values:_,T=D?E.units:"raw"}else T=sl(C,e.metadata.referencedImageId,p);f[g]={index:S,value:_,Modality:C,modalityUnit:T}}else this.isHandleOutsideImage=!0,f[g]={index:S,Modality:C}}const d=e.invalidated;return e.invalidated=!1,d&&tn(e,c,i),f}};Gl.toolName="Probe",Gl.probeDefaults={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:v5e,handleRadius:"6",textCanvasOffset:{x:6,y:-6}}},Gl.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,viewUp:c,instance:l,viewport:f}=Gl.hydrateBase(Gl,i,r,n),{toolInstance:u,...d}=n||{},h={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:l.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...d}};nn(h,f.element),Pe([f.id])};let nl=Gl;function v5e(t,e){const r=t.cachedStats[e],{index:n,value:i,modalityUnit:o}=r;if(i===void 0||!n)return;const a=[];if(a.push(`(${n[0]}, ${n[1]}, ${n[2]})`),i instanceof Array&&o instanceof Array)for(let s=0;s{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p={invalidated:!0,highlighted:!0,isVisible:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:l.getFrameOfReferenceUID(),referencedImageId:g},data:{label:"",handles:{points:[[...s]]},cachedStats:{}}},v=_t(a,this.getToolName());return this.editData={annotation:p,newAnnotation:!0,viewportIdsToRender:v},this._activateModify(a),Ot(a),n.preventDefault(),Pe(v),p},this.postTouchStartCallback=n=>this.postMouseDownCallback(n),this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;if(!this.editData)return o;const s=this.filterInteractableAnnotationsForElement(a.element,[this.editData.annotation]);if(!(s!=null&&s.length))return o;const c=this.getTargetId(a),l=a.getRenderingEngine(),f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=this.editData.annotation,d=u.annotationUID,h=u.data,g=h.handles.points[0],p=a.worldToCanvas(g);f.annotationUID=d;const{color:v}=this.getAnnotationStyle({annotation:u,styleSpecifier:f});if(!h.cachedStats[c]||h.cachedStats[c].value===null?(h.cachedStats[c]={Modality:null,index:null,value:null},this._calculateCachedStats(u,l,n)):u.invalidated&&this._calculateCachedStats(u,l,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;ir(i,d,"0",[p],{color:v}),o=!0;const m=this.configuration.getTextLines(h,c);if(m){const w=[p[0]+6,p[1]-6];Eu(i,d,"0",m,[w[0],w[1]],this.getLinkedTextBoxStyle(f,u))}return o}}};EE.toolName="DragProbe";let WC=EE;function y5e(t,e){const r=t.cachedStats[e],{index:n,value:i,modalityUnit:o}=r;if(i===void 0)return;const a=[];return a.push(`(${n[0]}, ${n[1]}, ${n[2]})`),a.push(`${i.toFixed(2)} ${o}`),a}const{transformWorldToIndex:ob}=Mn,r0=class r0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:w5e,statsCalculator:rc}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world;o.canvas;const c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},cachedStats:{},initialRotation:l.getRotation()}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,centerWorld:s,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=f.map(T=>c.worldToCanvas(T)),[d,h,g,p]=u,v=Math.hypot(g[0]-p[0],g[1]-p[1]),y=Math.hypot(h[0]-d[0],h[1]-d[1]),m=Math.atan2(g[1]-p[1],g[0]-p[0]),w=[(g[0]+p[0])/2,(h[1]+d[1])/2],x={center:w,xRadius:(v-a)/2,yRadius:(y-a)/2,angle:m},C={center:w,xRadius:(v+a)/2,yRadius:(y+a)/2,angle:m},S=this._pointInEllipseCanvas(x,o);return!!(this._pointInEllipseCanvas(C,o)&&!S)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f,u,d,h,g,p;if(o.worldPosition)l=!0;else{const{points:y}=c.handles,{viewport:m}=Ce(s),{worldToCanvas:w,canvasToWorld:x}=m;f=y.findIndex(S=>S===o);const C=y.map(w);p=C[f],h=Math.abs(C[2][0]-C[3][0]),g=Math.abs(C[0][1]-C[1][1]),u=[(C[2][0]+C[3][0])/2,(C[0][1]+C[1][1])/2],d=x(u)}const v=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:v,handleIndex:f,canvasWidth:h,canvasHeight:g,centerWorld:d,originalHandleCanvas:p,movingTextBox:l},this._activateModify(s),Ot(s),Pe(v),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(this.doneEditMemo(),a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a))},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{viewport:l}=c,{canvasToWorld:f}=l,{annotation:u,viewportIdsToRender:d,centerWorld:h,newAnnotation:g}=this.editData;this.createMemo(o,u,{newAnnotation:g});const p=l.worldToCanvas(h),{data:v}=u,y=Math.abs(s[0]-p[0]),m=Math.abs(s[1]-p[1]),w=[p[0],p[1]-m],x=[p[0],p[1]+m],C=[p[0]-y,p[1]],S=[p[0]+y,p[1]];v.handles.points=[f(w),f(x),f(C),f(S)],u.invalidated=!0,this.editData.hasMoved=!0,Pe(d),tn(u,o,Ht.HandlesUpdated)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,{viewport:a}=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a,{annotation:l,canvasWidth:f,canvasHeight:u,handleIndex:d,centerWorld:h,originalHandleCanvas:g}=this.editData,p=a.worldToCanvas(h),{data:v}=l,{points:y}=v.handles,{currentPoints:m}=i,w=m.canvas;if(d===0||d===1){const x=Math.abs(w[1]-p[1]),C=[p[0],p[1]-x],S=[p[0],p[1]+x];y[0]=s(C),y[1]=s(S);const _=w[0]-g[0],T=f/2+_,E=[p[0]-T,p[1]],D=[p[0]+T,p[1]];y[2]=s(E),y[3]=s(D)}else{const x=Math.abs(w[0]-p[0]),C=[p[0]-x,p[1]],S=[p[0]+x,p[1]];y[2]=s(C),y[3]=s(S);const _=w[1]-g[1],T=u/2+_,E=[p[0],p[1]-T],D=[p[0],p[1]+T];y[0]=s(E),y[1]=s(D)}},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(Y)),_=Yv(S),{centerPointRadius:T}=this.configuration;if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null},this._calculateCachedStats(h,a,f);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,f,n),a instanceof ur)){const{referencedImageId:Y}=h.metadata;for(const re in p.cachedStats)re.startsWith("imageId")&&f.getStackViewports().find(pe=>{const Ee=Vr(Y),Oe=pe.hasImageURI(Ee),Se=Vr(pe.getCurrentImageId());return Oe&&Se!==Ee})&&delete p.cachedStats[re]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let E;if(!Gr(g))continue;!Zr(g)&&!this.editData&&m!==null&&(E=[S[m]]),E&&ir(i,g,"0",E,{color:w});const D=`${g}-ellipse`,b="0";if(w4(i,g,b,S,{color:w,lineDash:C,lineWidth:x},D),T>0&&Math.min(Math.abs(_[0][0]-_[1][0])/2,Math.abs(_[0][1]-_[1][1])/2)>3*T){const re=this._getCanvasEllipseCenter(S);No(i,g,`${b}-center`,re,T,{color:w,lineDash:C,lineWidth:x})}o=!0;const I=this.getLinkedTextBoxStyle(u,h);if(!I.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const P=this.configuration.getTextLines(p,l);if(!P||P.length===0)continue;let M;p.handles.textBox.hasMoved||(M=na(_),p.handles.textBox.worldPosition=a.canvasToWorld(M));const L=a.worldToCanvas(p.handles.textBox.worldPosition),G=qi(i,g,"1",P,L,S,{},I),{x:A,y:k,width:F,height:j}=G;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([A,k]),topRight:a.canvasToWorld([A+F,k]),bottomLeft:a.canvasToWorld([A,k+j]),bottomRight:a.canvasToWorld([A+F,k+j])}}return o},this._calculateCachedStats=(n,i,o)=>{var C,S,_,T;if(!this.configuration.calculateStats)return;const a=n.data,{element:s}=i,{points:c}=a.handles,l=c.map(E=>i.worldToCanvas(E)),{viewPlaneNormal:f,viewUp:u}=i.getCamera(),[d,h]=Yv(l),g=i.canvasToWorld(d),p=i.canvasToWorld(h),{cachedStats:v}=a,y=Object.keys(v),m=g,w=p;for(let E=0;ET5(pe,De,{fast:!0}),returnPoints:this.configuration.storePointData});const xe=this.configuration.statsCalculator.getStatistics();v[D]={Modality:M.Modality,area:W,mean:(C=xe.mean)==null?void 0:C.value,max:(S=xe.max)==null?void 0:S.value,min:(_=xe.min)==null?void 0:_.value,stdDev:(T=xe.stdDev)==null?void 0:T.value,statsArray:xe.array,pointsInShape:ee,isEmptyArea:Se,areaUnit:z,modalityUnit:Z}}const x=n.invalidated;return n.invalidated=!1,x&&tn(n,s,Ht.StatsUpdated),v},this._isInsideVolume=(n,i,o)=>sr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}_pointInEllipseCanvas(e,r){const{xRadius:n,yRadius:i,center:o,angle:a}=e,s=HK(qt(),r,o,-a);if(n<=0||i<=0)return!1;const c=[s[0]-o[0],s[1]-o[1]];return c[0]*c[0]/(n*n)+c[1]*c[1]/(i*i)<=1}_getCanvasEllipseCenter(e){const[r,n,i,o]=e,a=[i[0],n[1]],s=[o[0],r[1]];return[(a[0]+s[0])/2,(a[1]+s[1])/2]}};r0.toolName="EllipticalROI",r0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=r0.hydrateBase(r0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let od=r0;function w5e(t,e){const r=t.cachedStats[e],{area:n,mean:i,stdDev:o,max:a,isEmptyArea:s,areaUnit:c,modalityUnit:l,min:f}=r,u=[];if(Ar(n)){const d=s?"Area: Oblique not supported":`Area: ${an(n)} ${c}`;u.push(d)}return Ar(i)&&u.push(`Mean: ${an(i)} ${l}`),Ar(a)&&u.push(`Max: ${an(a)} ${l}`),Ar(f)&&u.push(`Min: ${an(f)} ${l}`),Ar(o)&&u.push(`Std Dev: ${an(o)} ${l}`),u}const{transformWorldToIndex:ab}=Mn,i0=class i0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:x5e,statsCalculator:rc}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s]],activeHandleIndex:null},cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=f.map(g=>c.worldToCanvas(g)),d=du(u),h=du([u[0],o]);return Math.abs(h-d){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:g}=c.handles;f=g.findIndex(p=>p===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Ot(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;this.doneEditMemo(),a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{viewport:l}=c,{canvasToWorld:f}=l,{annotation:u,viewportIdsToRender:d,newAnnotation:h}=this.editData;this.createMemo(o,u,{newAnnotation:h});const{data:g}=u;g.handles.points=[g.handles.points[0],f(s)],u.invalidated=!0,this.editData.hasMoved=!0,Pe(d),tn(u,o,Ht.HandlesUpdated)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a.viewport,{annotation:l,handleIndex:f}=this.editData,{data:u}=l,{points:d}=u.handles,h=d.map(v=>c(v)),{currentPoints:g}=i,p=g.canvas;if(f===0){const v=p[0]-h[0][0],y=p[1]-h[0][1],m=p,w=[h[1][0]+v,h[1][1]+y];d[0]=s(m),d[1]=s(w)}else d[1]=s(p)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(ue)),_=S[0],T=du(S),E=x0(S),{centerPointRadius:D}=this.configuration;if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null,radius:null,radiusUnit:null,perimeter:null},this._calculateCachedStats(h,a,f,n);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,f,n),a instanceof ur)){const{referencedImageId:ue}=h.metadata;for(const ce in p.cachedStats)ce.startsWith("imageId")&&f.getStackViewports().find(Oe=>{const Se=Vr(ue),B=Oe.hasImageURI(Se),O=Vr(Oe.getCurrentImageId());return B&&O!==Se})&&delete p.cachedStats[ce]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let b;if(!Gr(g))continue;!Zr(g)&&!this.editData&&m!==null&&(b=[S[m]]),b&&ir(i,g,"0",b,{color:w});const I=`${g}-circle`,P="0";No(i,g,P,_,T,{color:w,lineDash:C,lineWidth:x},I),D>0&&T>3*D&&No(i,g,`${P}-center`,_,D,{color:w,lineDash:C,lineWidth:x}),o=!0;const M=this.getLinkedTextBoxStyle(u,h);if(!M.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const L=this.configuration.getTextLines(p,l);if(!L||L.length===0)continue;let V;p.handles.textBox.hasMoved||(V=na(E),p.handles.textBox.worldPosition=a.canvasToWorld(V));const G=a.worldToCanvas(p.handles.textBox.worldPosition),k=qi(i,g,"1",L,G,S,{},M),{x:F,y:j,width:Y,height:re}=k;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([F,j]),topRight:a.canvasToWorld([F+Y,j]),bottomLeft:a.canvasToWorld([F,j+re]),bottomRight:a.canvasToWorld([F+Y,j+re])}}return o},this._calculateCachedStats=(n,i,o,a)=>{var S,_,T,E;if(!this.configuration.calculateStats)return;const s=n.data,{element:c}=i,l=n.invalidated,{points:f}=s.handles,u=f.map(D=>i.worldToCanvas(D)),{viewPlaneNormal:d,viewUp:h}=i.getCamera(),[g,p]=x0(u),v=i.canvasToWorld(g),y=i.canvasToWorld(p),{cachedStats:m}=s,w=Object.keys(m),x=v,C=y;for(let D=0;DT5(B,se,{fast:!0}),boundsIJK:ce,imageData:M,returnPoints:this.configuration.storePointData}));const we=this.configuration.statsCalculator.getStatistics();m[b]={Modality:L.Modality,area:Ne,mean:(S=we.mean)==null?void 0:S.value,max:(_=we.max)==null?void 0:_.value,min:(T=we.min)==null?void 0:T.value,pointsInShape:ae,stdDev:(E=we.stdDev)==null?void 0:E.value,statsArray:we.array,isEmptyArea:W,areaUnit:xe,radius:O/2/Z,radiusUnit:ee,perimeter:2*Math.PI*(O/2)/Z,modalityUnit:ie}}else this.isHandleOutsideImage=!0,m[b]={Modality:L.Modality}}return n.invalidated=!1,l&&tn(n,c,Ht.StatsUpdated),m},this._isInsideVolume=(n,i,o)=>sr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}};i0.toolName="CircleROI",i0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=i0.hydrateBase(i0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let gy=i0;function x5e(t,e){const r=t.cachedStats[e],{radius:n,radiusUnit:i,area:o,mean:a,stdDev:s,max:c,min:l,isEmptyArea:f,areaUnit:u,modalityUnit:d}=r,h=[];if(Ar(n)){const g=f?"Radius: Oblique not supported":`Radius: ${an(n)} ${i}`;h.push(g)}if(Ar(o)){const g=f?"Area: Oblique not supported":`Area: ${an(o)} ${u}`;h.push(g)}return Ar(a)&&h.push(`Mean: ${an(a)} ${d}`),Ar(c)&&h.push(`Max: ${an(c)} ${d}`),Ar(l)&&h.push(`Min: ${an(l)} ${d}`),Ar(s)&&h.push(`Std Dev: ${an(s)} ${d}`),h}const $m=5,DE=class DE extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,degrees:[45,135,225,315],diameters:[10,30,60]}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{points:[[...s]]}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,newAnnotation:!0},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=c.worldToCanvas(f[0]),d=du([u,o]);return Math.abs(d){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h}=this.editData,{data:g}=d;g.handles.points=[u(s),u(s)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData,{data:c}=a,{deltaPoints:l}=i,f=l.world;c.handles.points.forEach(g=>{g[0]+=f[0],g[1]+=f[1],g[2]+=f[2]}),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a.viewport,{annotation:l}=this.editData,{data:f}=l,{points:u}=f.handles,d=u.map(w=>c(w)),{currentPoints:h}=i,g=h.canvas,p=g[0]-d[0][0],v=g[1]-d[0][1],y=g,m=[d[1][0]+p,d[1][1]+v];u[0]=s(y),u[1]=s(m)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;i.highlighted=!1,s.handles.activeHandleIndex=null;const{renderingEngine:c}=Ce(n);return Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(b))[0];if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(d))continue;let C=`${d}-crosshair-vertical`,S=[x[0],x[1]+$m],_=[x[0],x[1]-$m];vn(i,d,C,S,_,{color:v,lineDash:m,lineWidth:y}),C=`${d}-crosshair-horizontal`,S=[x[0]+$m,x[1]],_=[x[0]-$m,x[1]],vn(i,d,C,S,_,{color:v,lineDash:m,lineWidth:y});const T=this.configuration.diameters.map(b=>this.worldMeasureToCanvas(b,a));for(let b=0;bb*Math.PI/180,D=this.configuration.degrees.map(b=>E(b));for(let b=0;b{const{instance:s}=i.data.spline;return s.isPointNearCurve(o,a)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:d}=c.handles;f=d.findIndex(h=>h===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,contourHoleProcessingEnabled:l}=this.editData,{data:f}=a;a.autoGenerated=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),d=this.getTargetImageData(this.getTargetId(u.viewport)),{imageData:h,dimensions:g}=d;this.isHandleOutsideImage=f.handles.points.map(v=>Ur(h,v)).some(v=>!sr(v,g)),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const p=c?Ht.Completed:Ht.HandlesUpdated;this.fireChangeOnUpdate?(this.fireChangeOnUpdate.annotationUID=a.annotationUID,this.fireChangeOnUpdate.changeType=p):this.fireChangeOnUpdate={annotationUID:a.annotationUID,changeType:p,contourHoleProcessingEnabled:l},Pe(s),this.doneEditMemo(),this.editData=null,this.isDrawing=!1},this._keyDownCallback=n=>{const i=n.detail,{element:o}=i,a=i.key??"",{lastControlPointDeletionKeys:s}=this.configuration.spline;if(!s.includes(a))return;const{annotation:l}=this.editData,{data:f}=l;if(f.handles.points.length===sb){this.cancel(o);return}else{const u=f.handles.points.length-1;this._deleteControlPointByIndex(o,l,u)}n.preventDefault()},this._mouseMoveCallback=n=>{const{drawPreviewEnabled:i}=this.configuration.spline;if(!i)return;const{element:o}=n.detail,{renderingEngine:a}=Ce(o),s=_t(o,this.getToolName());this.editData.lastCanvasPoint=n.detail.currentPoints.canvas,Pe(s),n.preventDefault()},this._mouseDownCallback=n=>{const i=n.type===N.MOUSE_DOUBLE_CLICK,{annotation:o,viewportIdsToRender:a}=this.editData,{data:s}=o;if(s.contour.closed)return;this.doneEditMemo();const c=n.detail,{currentPoints:l,element:f}=c,{canvas:u,world:d}=l;let h=s.handles.points.length>=2&&i,g=!0;if(s.handles.points.length&&this.createMemo(f,o,{newAnnotation:s.handles.points.length===1}),s.handles.points.length>=3){this.createMemo(f,o);const{instance:p}=s.spline,v=p.getClosestControlPointWithinDistance(u,cb);(v==null?void 0:v.index)===0&&(g=!1,h=!0)}g&&s.handles.points.push(d),s.contour.closed=s.contour.closed||h,o.invalidated=!0,Pe(a),s.contour.closed&&this._endCallback(n),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;this.moveAnnotation(a,p)}else{const{currentPoints:g}=i,p=g.world;u.handles.points[c]=[...p],a.invalidated=!0}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this.triggerAnnotationCompleted=(n,i)=>{const o=N.ANNOTATION_COMPLETED,a={annotation:n,changeType:Ht.Completed,contourHoleProcessingEnabled:i};at(Ke,o,a)},this.triggerAnnotationModified=(n,i,o=Ht.StatsUpdated)=>{const{viewportId:a,renderingEngineId:s}=i,c=N.ANNOTATION_MODIFIED;at(Ke,c,{annotation:n,viewportId:a,renderingEngineId:s,changeType:o})},this.triggerChangeEvent=(n,i,o=Ht.StatsUpdated,a)=>{o===Ht.Completed?this.triggerAnnotationCompleted(n,a):this.triggerAnnotationModified(n,i,o)},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.KEY_DOWN,this._keyDownCallback),n.addEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.KEY_DOWN,this._keyDownCallback),n.removeEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._renderStats=(n,i,o,a)=>{const s=n.data,c=this.getTargetId(i);if(!s.spline.instance.closed||!a.visibility)return;const l=this.configuration.getTextLines(s,c);if(!l||l.length===0)return;const f=s.handles.points.map(m=>i.worldToCanvas(m));if(!s.handles.textBox.hasMoved){const m=na(f);s.handles.textBox.worldPosition=i.canvasToWorld(m)}const u=i.worldToCanvas(s.handles.textBox.worldPosition),h=qi(o,n.annotationUID??"","textBox",l,u,f,{},a),{x:g,y:p,width:v,height:y}=h;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([g,p]),topRight:i.canvasToWorld([g+v,p]),bottomLeft:i.canvasToWorld([g,p+y]),bottomRight:i.canvasToWorld([g+v,p+y])}},this.addControlPointCallback=(n,i)=>{const{data:o}=i,a=o.spline.type,s=this._getSplineConfig(a),c=s.controlPointAdditionDistance;if(s.controlPointAdditionEnabled===!1)return;const l=n.detail,{element:f}=l,u=Ce(f),{renderingEngine:d,viewport:h}=u,{canvasToWorld:g}=h,{instance:p}=o.spline,v=n.detail.currentPoints.canvas,y=p.getClosestPoint(v);if(y.distance>c)return;const{index:m,point:w}=p.addControlPointAtU(y.uValue);o.handles.points.splice(m,0,g(w)),i.invalidated=!0;const x=_t(f,this.getToolName());Pe(x)},this.deleteControlPointCallback=(n,i)=>{const o=i.data.spline.type,a=this._getSplineConfig(o),s=a.controlPointDeletionDistance;if(a.controlPointDeletionEnabled===!1)return;const c=n.detail,{element:l,currentPoints:f}=c,{canvas:u}=f,{instance:d}=i.data.spline,h=d.getClosestControlPointWithinDistance(u,s);h&&this._deleteControlPointByIndex(l,i,h.index)},this._calculateCachedStats=(n,i)=>{if(!this.configuration.calculateStats)return;const o=n.data;if(!o.contour.closed)return;const a=Ce(i);if(!a)return;const{viewport:s}=a,{cachedStats:c}=o,{polyline:l}=o.contour,f=Object.keys(c);for(let d=0;ds.worldToCanvas(b)),y=v[0],m=s.canvasToWorld(y),w=s.canvasToWorld([y[0]+1,y[1]]),x=s.canvasToWorld([y[0],y[1]+1]),C=ki(m,w),S=ki(m,x),{imageData:_}=g,{scale:T,areaUnit:E}=ta(g,()=>{const{maxX:b,maxY:I,minX:P,minY:M}=Tu(v),L=s.canvasToWorld([P,M]),V=Ur(_,L),G=s.canvasToWorld([b,I]),A=Ur(_,G);return[V,A]});let D=M1(v)/T/T;D*=C*S,c[h]={Modality:p.Modality,area:D,areaUnit:E}}const u=n.invalidated;return n.invalidated=!1,u&&this.triggerAnnotationModified(n,a,Ht.StatsUpdated),c},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0}),this.annotationCompletedBinded=this.annotationCompleted.bind(this)}annotationCompleted(e){var n;const{sourceAnnotation:r}=e.detail;!this.splineToolNames.includes((n=r==null?void 0:r.metadata)==null?void 0:n.toolName)||!this.configuration.simplifiedSpline||!this.isContourSegmentationTool()||l4(r)}initializeListeners(){Ke.addEventListener(N.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}removeListeners(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.removeListeners()}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{canvas:o}=n,a=vh(e.detail.event)===this.configuration.contourHoleAdditionModifierKey,s=Ce(i),{renderingEngine:c}=s,l=this.createAnnotation(e);this.isDrawing=!0,this.addAnnotation(l,i);const f=_t(i,this.getToolName());return this.editData={annotation:l,viewportIdsToRender:f,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,lastCanvasPoint:o,contourHoleProcessingEnabled:a},this._activateDraw(i),e.preventDefault(),Pe(f),l}cancel(e){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),zt(e);const{annotation:r,viewportIdsToRender:n,newAnnotation:i}=this.editData;i&&gn(r.annotationUID),super.cancelAnnotation(r);const o=Ce(e),{renderingEngine:a}=o;return Pe(n),this.editData=null,r.annotationUID}isContourSegmentationTool(){return!1}renderAnnotationInstance(e){var M,L,V;const{enabledElement:r,targetId:n,svgDrawingHelper:i,annotationStyle:o}=e,{viewport:a}=r,{worldToCanvas:s}=a,{element:c}=a,l=e.annotation,{annotationUID:f,data:u,highlighted:d}=l,{handles:h}=u,{points:g,activeHandleIndex:p}=h,v=(M=this.editData)==null?void 0:M.newAnnotation,{lineWidth:y,lineDash:m,color:w,locked:x}=o,C=g.map(G=>s(G)),{drawPreviewEnabled:S}=this.configuration.spline,_=l.data.spline.type,T=this._getSplineConfig(_),E=l.data.spline.instance,D=T1(l);if(D.findIndex(G=>!G)!==-1)throw new Error(`Can't find annotation for child ${l.childAnnotationUIDs.join()}`);[l,...D].filter(G=>this._isSplineROIAnnotation(G)).forEach(G=>{const k=this._updateSplineInstance(c,G).getPolylinePoints();this.updateContourPolyline(G,{points:k,closed:u.contour.closed,targetWindingDirection:Lo.Clockwise},a,{updateWindingDirection:u.contour.closed})}),super.renderAnnotationInstance(e),!u.cachedStats[n]||u.cachedStats[n].areaUnit==null?(u.cachedStats[n]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(l,c)):l.invalidated&&this._throttledCalculateCachedStats(l,c);let P;if(!x&&!this.editData&&p!==null&&(P=[C[p]]),(P||v||d)&&ir(i,f,"0",C,{color:w,lineWidth:y,handleRadius:"3"}),S&&E.numControlPoints>1&&((L=this.editData)!=null&&L.lastCanvasPoint)&&!E.closed){const{lastCanvasPoint:G}=this.editData,A=E.getPreviewPolylinePoints(G,cb);Cs(i,f,"previewSplineChange",A,{color:"#9EA0CA",lineDash:m,lineWidth:1})}if(T.showControlPointsConnectors){const G=[...C];E.closed&&G.push(C[0]),Cs(i,f,"controlPointsConnectors",G,{color:"rgba(255, 255, 255, 0.5)",lineWidth:1})}return this._renderStats(l,a,i,o.textbox),((V=this.fireChangeOnUpdate)==null?void 0:V.annotationUID)===f&&(this.triggerChangeEvent(l,r,this.fireChangeOnUpdate.changeType,this.fireChangeOnUpdate.contourHoleProcessingEnabled),this.fireChangeOnUpdate=null),l.invalidated=!1,!0}createInterpolatedSplineControl(e){var o;if((o=e.data.handles.points)!=null&&o.length)return;const{polyline:r}=e.data.contour;if(!r||!r.length)return;e.data.handles.points=[];const{points:n}=e.data.handles,i=Math.max(10,Math.floor(r.length/20));for(let a=0;a({type:o.type,instance:a,resolution:o.resolution});let c;return(l=this.configuration.interpolation)!=null&&l.enabled&&(c=f=>{var u;(u=f.data).spline||(u.spline=s()),this.createInterpolatedSplineControl(f)}),Ei(r,{data:{handles:{points:[[...n]]},spline:s(),cachedStats:{}},onInterpolationComplete:c})}_deleteControlPointByIndex(e,r,n){const i=Ce(e),{points:o}=r.data.handles;o.length===3?gn(r.annotationUID):o.splice(n,1);const{renderingEngine:a}=i,s=_t(e,this.getToolName());r.invalidated=!0,Pe(s)}_isSplineROIAnnotation(e){var r;return!!((r=e.data)!=null&&r.spline)}_getSplineConfig(e){const{configuration:r}=this,n=r.spline.configuration;return Object.assign({type:e},C5e,n[e])}_updateSplineInstance(e,r){const n=Ce(e),{viewport:i}=n,{worldToCanvas:o}=i,{data:a}=r,{type:s,instance:c}=r.data.spline,l=this._getSplineConfig(s),u=a.handles.points.map(o),d=l.resolution!==void 0?parseInt(l.resolution):void 0,h=l.scale!==void 0?parseFloat(l.scale):void 0;return c.setControlPoints(u),c.closed=!!a.contour.closed,!c.fixedResolution&&d!==void 0&&c.resolution!==d&&(c.resolution=d,r.invalidated=!0),c instanceof Jp&&!c.fixedScale&&h!==void 0&&c.scale!==h&&(c.scale=h,r.invalidated=!0),c}};Wl.toolName="SplineROI",Wl.SplineTypes=Dc,Wl.Actions=Kg,Wl.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;if(r.lengthi,this._areEqual=typeof n=="function"?n:(i,o)=>i===o}push(e){const r=this._getBucketIndex(e),n=this._buckets[r],i={value:e,next:n};this._buckets[r]=i,this._size++}pop(){if(this._size===0)throw new Error("Cannot pop because the queue is empty.");for(;this._buckets[this._currentBucketIndex]===null;)this._currentBucketIndex=(this._currentBucketIndex+1)%this._bucketCount;const e=this._buckets[this._currentBucketIndex];return this._buckets[this._currentBucketIndex]=e.next,this._size--,e.value}remove(e){if(!e)return!1;const r=this._getBucketIndex(e),n=this._buckets[r];let i=n,o;for(;i!==null&&!this._areEqual(e,i.value);)o=i,i=i.next;return i===null?!1:(i===n?this._buckets[r]=i.next:o.next=i.next,this._size--,!0)}isEmpty(){return this._size===0}_getBucketIndex(e){return this._getPriority(e)&this._mask}_buildArray(e){const r=new Array(e);return r.fill(null),r}}const w3=4294967295,T5e=2/(3*Math.PI);class my{constructor(e,r,n){this._getPointIndex=(o,a)=>{const{width:s}=this;return o*s+a},this._getPointCoordinate=o=>{const a=o%this.width,s=Math.floor(o/this.width);return[a,s]},this._getPointCost=o=>Math.round(this.searchGranularity*this.costs[o]);const i=e.length;this.searchGranularityBits=8,this.searchGranularity=1<.33?0:1;i[n(o,e-2)]=1,i[n(o,e-1)]=1}return i.fill(1,n(r-2,0)),i}_computeGradientX(){const{width:e,height:r}=this,n=new Float32Array(e*r);let i=0;for(let o=0;o=i||l<0||l>=o)return 1;if(a<0||s<0||a>=i||s>=o)return 0;const f=n(l,c);let u=this.gradMagnitude[f];(a===c||s===l)&&(u*=Math.SQRT1_2);const d=this.laplace[f],h=this._getGradientDirection(a,s,c,l);return .43*u+.43*d+.11*h}_getNeighborPoints(e){const{width:r,height:n}=this,i=[],o=Math.max(e[0]-1,0),a=Math.max(e[1]-1,0),s=Math.min(e[0]+1,r-1),c=Math.min(e[1]+1,n-1);for(let l=a;l<=c;l++)for(let f=o;f<=s;f++)(f!==e[0]||l!==e[1])&&i.push([f,l]);return i}static createInstanceFromRawPixelData(e,r,n,i){const o=e.length,a=new Float32Array(o),{lower:s,upper:c}=i,l=c-s;for(let f=0,u=e.length;fthis.pointArray[e])}getNumControlPoints(){return this._controlPointIndexes.length}removeLastControlPoint(){this._controlPointIndexes.length&&this._controlPointIndexes.pop()}getLastControlPoint(){if(this._controlPointIndexes.length)return this.pointArray[this._controlPointIndexes[this._controlPointIndexes.length-1]]}removeLastPoints(e){this.pointArray.splice(this.pointArray.length-e,e)}addPoints(e){this.pointArray=this.pointArray.concat(e)}prependPath(e){const r=e.pointArray.length,n=[];this.pointArray=e.pointArray.concat(this.pointArray);for(let i=0;ithis._controlPointIndexes.push(r))}}const E5e=10**2,IE=class IE extends $p{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextLines:D5e,calculateStats:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:Oi.Shift,snapHandleNearby:2,interpolation:{enabled:!1,nearestEdge:2,showInterpolationPolyline:!1},decimate:{enabled:!1,epsilon:.1},actions:{cancelInProgress:{method:"cancelInProgress",bindings:[{key:"Escape"}]}}}}){super(e,r),this.isHandleOutsideImage=!1,this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,l=a*a,f=i.data.contour.polyline.map(d=>c.worldToCanvas(d));let u=f[f.length-1];for(let d=0;d{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1};const c=Ce(a),{renderingEngine:l}=c;this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:g}=c.handles;f=g.findIndex(p=>p===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=(n,i=!1)=>{const o=n.detail,{element:a}=o,{annotation:s,viewportIdsToRender:c,newAnnotation:l,contourHoleProcessingEnabled:f}=this.editData,{data:u}=s;this.doneEditMemo(),u.handles.activeHandleIndex=null,this._deactivateModify(a),this._deactivateDraw(a),zt(a);const d=Ce(a);if(this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage||i){gn(s.annotationUID),this.clearEditData(),Pe(c);return}Pe(c);const h=l?Ht.Completed:Ht.HandlesUpdated;this.triggerChangeEvent(s,d,h,f),this.clearEditData()},this.triggerChangeEvent=(n,i,o=Ht.StatsUpdated,a=!1)=>{o===Ht.Completed?v5(n,a):tn(n,i.viewport.element,o)},this._mouseDownCallback=n=>{const i=n.type===N.MOUSE_DOUBLE_CLICK,{annotation:o,viewportIdsToRender:a,worldToSlice:s,sliceToWorld:c,newAnnotation:l}=this.editData;if(this.editData.closed)return;const f=n.detail,{element:u}=f,{currentPoints:d}=f,{canvas:h,world:g}=d;let p=g;const v=Ce(u),{viewport:y,renderingEngine:m}=v,w=this.editData.currentPath.getControlPoints();let x=w.length>=2&&i;if(this.doneEditMemo(),this.createMemo(u,o,{newAnnotation:l&&w.length===1}),w.length>=2){const _={index:-1,distSquared:1/0};for(let T=0,E=w.length;T{const{element:i,currentPoints:o}=n.detail,{world:a,canvas:s}=o,{renderingEngine:c}=Ce(i),l=_t(i,this.getToolName());this.editData.lastCanvasPoint=s;const{width:f,height:u}=this.scissors,{worldToSlice:d}=this.editData,h=d(a);if(h[0]<0||h[1]<0||h[0]>=f||h[1]>=u)return;const g=this.scissors.findPathToPoint(h),p=new _c;p.addPoints(g),p.prependPath(this.editData.confirmedPath),this.editData.currentPath=p,Pe(l),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,movingTextBox:c,handleIndex:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(c){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(l===void 0)console.warn("Drag annotation not implemented");else{const{currentPoints:g}=i,p=g.world;this.editHandle(p,o,a,l)}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData;return a&&gn(i.annotationUID),Pe(o),this.doneEditMemo(),this.scissors=null,i.annotationUID},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._calculateCachedStats=(n,i)=>{if(!this.configuration.calculateStats)return;const o=n.data;if(!o.contour.closed)return;const a=Ce(i),{viewport:s,renderingEngine:c}=a,{cachedStats:l}=o,{polyline:f}=o.contour,u=Object.keys(l);for(let h=0;hs.worldToCanvas(I)),m=y[0],w=s.canvasToWorld(m),x=s.canvasToWorld([m[0]+1,m[1]]),C=s.canvasToWorld([m[0],m[1]+1]),S=ki(w,x),_=ki(w,C),{imageData:T}=p,{scale:E,areaUnit:D}=ta(p,()=>{const{maxX:I,maxY:P,minX:M,minY:L}=Tu(y),V=s.canvasToWorld([M,L]),G=Ur(T,V),A=s.canvasToWorld([I,P]),k=Ur(T,A);return[G,k]});let b=M1(y)/E/E;b*=S*_,l[g]={Modality:v.Modality,area:b,areaUnit:D}}const d=n.invalidated;return n.invalidated=!1,d&&this.triggerAnnotationModified(n,a,Ht.StatsUpdated),l},this._renderStats=(n,i,o,a)=>{const s=n.data,c=this.getTargetId(i);if(!s.contour.closed||!a.visibility)return;const l=this.configuration.getTextLines(s,c);if(!l||l.length===0)return;const f=s.handles.points.map(m=>i.worldToCanvas(m));if(!s.handles.textBox.hasMoved){const m=na(f);s.handles.textBox.worldPosition=i.canvasToWorld(m)}const u=i.worldToCanvas(s.handles.textBox.worldPosition),h=qi(o,n.annotationUID??"","textBox",l,u,f,{},a),{x:g,y:p,width:v,height:y}=h;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([g,p]),topRight:i.canvasToWorld([g+v,p]),bottomLeft:i.canvasToWorld([g,p+y]),bottomRight:i.canvasToWorld([g+v,p+y])}},this.triggerAnnotationModified=(n,i,o=Ht.StatsUpdated)=>{const{viewportId:a,renderingEngineId:s}=i,c=N.ANNOTATION_MODIFIED;at(Ke,c,{annotation:n,viewportId:a,renderingEngineId:s,changeType:o})},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}setupBaseEditData(e,r,n,i,o){var _,T;const a=Ce(r),{viewport:s}=a;this.isDrawing=!0;const c=s.getImageData(),{imageData:l}=c;let f,u,d,h,g;if(!(s instanceof ur))d=c.dimensions[0],h=c.dimensions[1],f=E=>{const D=Ur(l,E);return[D[0],D[1]]},u=E=>B0(l,[E[0],E[1],0]),g=c.scalarData;else if(s instanceof ur){const E=UT(s),{sliceToIndexMatrix:D,indexToSliceMatrix:b}=E;f=I=>{const P=Ur(l,I),M=Jt([0,0,0],P,b);return[M[0],M[1]]},u=I=>{const P=Jt([0,0,0],[I[0],I[1],0],D);return B0(l,P)},g=E.scalarData,d=E.width,h=E.height}else throw new Error("Viewport not supported");g=qA(g,d,h);const{voiRange:p}=s.getProperties(),v=f(e);this.scissors=my.createInstanceFromRawPixelData(g,d,h,p),i&&(this.scissorsNext=my.createInstanceFromRawPixelData(g,d,h,p),this.scissorsNext.startSearch(f(i))),this.scissors.startSearch(v);const y=!i,m=new _c,w=new _c,x=y?void 0:new _c;m.addPoint(v),m.addControlPoint(v);const C=_t(r,this.getToolName()),S=s.worldToCanvas(e);this.editData={annotation:n,viewportIdsToRender:C,newAnnotation:y,hasMoved:!1,lastCanvasPoint:S,confirmedPath:m,currentPath:w,confirmedPathNext:x,closed:!1,handleIndex:((_=this.editData)==null?void 0:_.handleIndex)??((T=n.handles)==null?void 0:T.activeHandleIndex),worldToSlice:f,sliceToWorld:u,contourHoleProcessingEnabled:o}}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n,a=this.createAnnotation(e),s=vh(e.detail.event)===this.configuration.contourHoleAdditionModifierKey;return this.setupBaseEditData(o,i,a,void 0,s),this.addAnnotation(a,i),this._activateDraw(i),e.preventDefault(),Pe(this.editData.viewportIdsToRender),a}clearEditData(){this.editData=null,this.scissors=null,this.scissorsNext=null,this.isDrawing=!1}editHandle(e,r,n,i){var w;const{data:o}=n,{points:a}=o.handles,{length:s}=a,c=a[(i-1+s)%s],l=a[(i+1)%s];if(!((w=this.editData)!=null&&w.confirmedPathNext)){this.setupBaseEditData(c,r,n,l);const{polyline:x}=o.contour,C=new _c,S=new _c,{worldToSlice:_}=this.editData,T=IC(n,i-1),E=IC(n,i+1);if(E===-1||T===-1)throw new Error(`Can't find handle index ${E===-1&&l} ${T===-1&&c}`);i===0?S.addPoints(x.slice(E+1,T).map(_)):(C.addPoints(x.slice(0,T+1).map(_)),S.addPoints(x.slice(E,x.length).map(_))),this.editData.confirmedPath=C,this.editData.confirmedPathNext=S}const{editData:f,scissors:u}=this,{worldToSlice:d,sliceToWorld:h}=f,{activeHandleIndex:g}=o.handles;if(g==null)o.handles.activeHandleIndex=i;else if(g!==i)throw new Error(`Trying to edit a different handle than the one currently being edited ${i}!==${o.handles.activeHandleIndex}`);const p=d(e);if(p[0]<0||p[0]>=u.width||p[1]<0||p[1]>=u.height)return;a[i]=h(p);const v=u.findPathToPoint(p),y=this.scissorsNext.findPathToPoint(p),m=new _c;m.prependPath(f.confirmedPath),i!==0&&m.addPoints(v),m.addPoints(y.reverse()),m.appendPath(f.confirmedPathNext),i===0&&m.addPoints(v),f.currentPath=m,n.invalidated=!0,f.hasMoved=!0,f.closed=!0}renderAnnotation(e,r){var n;return this.updateAnnotation((n=this.editData)==null?void 0:n.currentPath),super.renderAnnotation(e,r)}isContourSegmentationTool(){return!1}createAnnotation(e){const r=super.createAnnotation(e),{world:n}=e.detail.currentPoints;return Ei(r,{data:{handles:{points:[[...n]]}}})}cancelInProgress(e,r,n){if(!this.editData){this.undo();return}this._endCallback(n,!0)}renderAnnotationInstance(e){var m,w,x,C;const{annotation:r,enabledElement:n,svgDrawingHelper:i,annotationStyle:o,targetId:a}=e,{viewport:s}=n,{element:c}=s,{worldToCanvas:l}=s,{annotationUID:f,data:u,highlighted:d}=r,{handles:h}=u,g=(m=this.editData)==null?void 0:m.newAnnotation,{lineWidth:p,lineDash:v,color:y}=o;if(d||g&&r.annotationUID===((x=(w=this.editData)==null?void 0:w.annotation)==null?void 0:x.annotationUID)){const S="0",_=h.points.map(l);ir(i,f,S,_,{color:y,lineDash:v,lineWidth:p})}return super.renderAnnotationInstance(e),!u.cachedStats[a]||((C=u.cachedStats[a])==null?void 0:C.areaUnit)===null?(u.cachedStats[a]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(r,c)):r.invalidated&&this._throttledCalculateCachedStats(r,c),this._renderStats(r,s,i,o.textbox),!0}updateAnnotation(e){if(!this.editData||!e)return;const{annotation:r,sliceToWorld:n,worldToSlice:i,closed:o,newAnnotation:a}=this.editData;let{pointArray:s}=e;s.length>1&&(s=[...s,s[0]]);const c=a&&o?Lo.Clockwise:void 0;this.updateContourPolyline(r,{points:s,closed:o,targetWindingDirection:c},{canvasToWorld:n,worldToCanvas:i})}};IE.toolName="LivewireContour";let vy=IE;function D5e(t,e){const r=t.cachedStats[e],{area:n,areaUnit:i}=r,o=[];if(n){const a=`Area: ${an(n)} ${i}`;o.push(a)}return o}const OE=class OE extends vy{updateInterpolatedAnnotation(e,r){this.editData||!e.invalidated||!e.data.handles.interpolationSources||(e.data.contour.originalPolyline=e.data.contour.polyline,queueMicrotask(()=>{if(!e.data.handles.interpolationSources)return;const{points:n}=e.data.handles,{element:i}=r.viewport;this.setupBaseEditData(n[0],i,e);const{length:o}=n,{scissors:a}=this,{nearestEdge:s,repeatInterpolation:c}=this.configuration.interpolation;e.data.handles.originalPoints=n;const{worldToSlice:l,sliceToWorld:f}=this.editData,u=[];if(s){let h=l(n[n.length-1]);n.forEach((g,p)=>{const v=l(g);h=v,u.push(v),a.startSearch(h),a.findPathToPoint(v),a.findPathToPoint(l(n[(p+3)%n.length]));const y=a.findMinNearby(v,s);$t(v,y)||(u[p]=y,h=y,n[p]=f(y))})}const d=new _c;for(let h=0;h{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),{arrowFirst:p}=this.configuration,v=l.getFrameOfReferenceUID(),y={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:v,referencedImageId:g,...l.getViewReference({points:[s]})},data:{text:"",handles:{points:[[...s],[...s]],activeHandleIndex:null,arrowFirst:p,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:""}};nn(y,a);const m=_t(a,this.getToolName());return this.editData={annotation:y,viewportIdsToRender:m,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(m),y},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l,movingTextBox:f}=this.editData,{data:u}=a;c&&!l||(u.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),c?this.configuration.getTextCallback(d=>{if(!d){gn(a.annotationUID),Pe(s),this.editData=null,this.isDrawing=!1;return}a.data.text=d,tn(a,o,Ht.HandlesUpdated),Nn(a),this.createMemo(o,a,{newAnnotation:!!this.memo}),AU(a,o,d),Pe(s)}):f||tn(a,o,Ht.HandlesUpdated),this.doneEditMemo(),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=d.world;u.handles.points[c]=[...h],a.invalidated=!0}this.editData.hasMoved=!0,Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.touchTapCallback=n=>{n.detail.taps==2&&this.doubleClickCallback(n)},this.doubleClickCallback=n=>{const i=n.detail,{element:o}=i;let a=un(this.getToolName(),o);if(a=this.filterInteractableAnnotationsForElement(o,a),!(a!=null&&a.length))return;const s=a.find(l=>this.isPointNearTool(o,l,i.currentPoints.canvas,6));if(!s)return;const c=s;this.configuration.changeTextCallback(s,n.detail,this._doneChangingTextCallback.bind(this,o,c)),this.editData=null,this.isDrawing=!1,n.stopImmediatePropagation(),n.preventDefault()},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(G));let _;if(!Zr(d)&&!this.editData&&y!==null&&(_=[S[y]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(d))continue;_&&ir(i,d,"0",S,{color:m,lineWidth:w});const T="1";if(this.configuration.arrowFirst?ey(i,d,T,S[1],S[0],{color:m,width:w,lineDash:x,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:C}):ey(i,d,T,S[0],S[1],{color:m,width:w,lineDash:x,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:C}),o=!0,!p)continue;const E=this.getLinkedTextBoxStyle(l,u);if(!E.visibility){h.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}if(!h.handles.textBox.hasMoved){const G=S[1];h.handles.textBox.worldPosition=a.canvasToWorld(G)}const D=a.worldToCanvas(h.handles.textBox.worldPosition),I=qi(i,d,"1",[p],D,S,{},E),{x:P,y:M,width:L,height:V}=I;h.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([P,M]),topRight:a.canvasToWorld([P+L,M]),bottomLeft:a.canvasToWorld([P,M+V]),bottomRight:a.canvasToWorld([P+L,M+V])}}return o}}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_doneChangingTextCallback(e,r,n){r.data.text=n,Ce(e);const i=_t(e,this.getToolName());Pe(i),tn(r,e)}_isInsideVolume(e,r,n){return sr(e,n)&&sr(r,n)}};o0.toolName="ArrowAnnotate",o0.hydrate=(e,r,n,i)=>{const o=zn(e);if(!o)return;const{FrameOfReferenceUID:a,referencedImageId:s,viewPlaneNormal:c,instance:l,viewport:f}=o0.hydrateBase(o0,o,r,i),{toolInstance:u,...d}=i||{},h={annotationUID:(i==null?void 0:i.annotationUID)||Dn(),data:{text:n||"",handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:l.getToolName(),viewPlaneNormal:c,FrameOfReferenceUID:a,referencedImageId:s,...d}};nn(h,f.element),Pe([f.id])};let Ou=o0;function b5e(t){return t(prompt("Enter your annotation:"))}function I5e(t,e,r){return r(prompt("Enter your annotation:"))}const a0=class a0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,showAngleArc:!1,arcOffset:5,preventHandleOutsideImage:!1,getTextLines:O5e}}){super(e,r),this.addNewAnnotation=n=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u,d]=l.handles.points,h=c.worldToCanvas(f),g=c.worldToCanvas(u),p={start:{x:h[0],y:h[1]},end:{x:g[0],y:g[1]}};if(hi([p.start.x,p.start.y],[p.end.x,p.end.y],[o[0],o[1]])<=a)return!0;if(!d)return!1;const y=c.worldToCanvas(d),m={start:{x:g[0],y:g[1]},end:{x:y[0],y:y[1]}};return hi([m.start.x,m.start.y],[m.end.x,m.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.angleStartedNotYetCompleted&&f.handles.points.length===2){this.editData.handleIndex=2;return}this.angleStartedNotYetCompleted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else{const{currentPoints:g}=i,p=g.world;u.handles.points[c]=[...p],a.invalidated=!0}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,this.angleStartedNotYetCompleted=!1,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{var d;let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let h=0;ha.worldToCanvas(k));!v.cachedStats[l]||v.cachedStats[l].angle==null?(v.cachedStats[l]={angle:null},this._calculateCachedStats(g,f,n)):g.invalidated&&this._throttledCalculateCachedStats(g,f,n);let T;if(!Zr(g.annotationUID)&&!this.editData&&m!==null&&(T=[_[m]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(p))continue;T&&ir(i,p,"0",_,{color:w,lineDash:C,lineWidth:x});let E="1";if(vn(i,p,E,_[0],_[1],{color:w,width:x,lineDash:C}),o=!0,_.length!==3)return o;if(E="2",vn(i,p,E,_[1],_[2],{color:w,width:x,lineDash:C}),this.configuration.showAngleArc){const k=_[1],F=this.configuration.arcOffset,j=Math.min(hi([k[0],k[1]],[_[0][0],_[0][1]],[_[2][0],_[2][1]]),hi([k[0],k[1]],[_[2][0],_[2][1]],[_[0][0],_[0][1]]))/F,Y=[];let re=Math.atan2(_[0][1]-k[1],_[0][0]-k[0]),ue=Math.atan2(_[2][1]-k[1],_[2][0]-k[0]);if(ueMath.PI){const Ee=re;re=ue,ue=Ee+2*Math.PI}const pe=32;for(let Ee=0;Ee<=pe;Ee++){const Oe=re+Ee/pe*(ue-re);Y.push([k[0]+j*Math.cos(Oe),k[1]+j*Math.sin(Oe)])}Wc(i,p,"3",Y,{color:w,width:x,lineDash:S})}if(!((d=v.cachedStats[l])!=null&&d.angle))continue;const D=this.getLinkedTextBoxStyle(u,g);if(!D.visibility){v.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const b=this.configuration.getTextLines(v,l);if(!v.handles.textBox.hasMoved){const k=_[1];v.handles.textBox.worldPosition=a.canvasToWorld(k)}const I=a.worldToCanvas(v.handles.textBox.worldPosition),M=qi(i,p,"1",b,I,_,{},D),{x:L,y:V,width:G,height:A}=M;v.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([L,V]),topRight:a.canvasToWorld([L+G,V]),bottomLeft:a.canvasToWorld([L,V+A]),bottomRight:a.canvasToWorld([L+G,V+A])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport;if(i.handles.points.length!==3)return;const a=i.handles.points[0],s=i.handles.points[1],c=i.handles.points[2],{cachedStats:l}=i,f=Object.keys(l);for(let d=0;dUr(v,y)).some(y=>!sr(y,p)),l[h]={angle:isNaN(g)?"Incomplete Angle":g}}const u=e.invalidated;return e.invalidated=!1,u&&tn(e,o,Ht.StatsUpdated),l}};a0.toolName="Angle",a0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=a0.hydrateBase(a0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let HC=a0;function O5e(t,e){const r=t.cachedStats[e],{angle:n}=r;return n===void 0?void 0:isNaN(n)?[`${n}`]:[`${an(n)} °`]}const M5e=(...t)=>{const e=t[0].length===2?[0,0]:[0,0,0],r=t.length;for(const n of t)e[0]+=n[0]/r,e[1]+=n[1]/r,e.length===3&&(e[2]+=n[2]/r);return e},Sc=M5e,ME=class ME extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:P5e,showArcLines:!1}}){super(e,r),this.addNewAnnotation=n=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{distanceToPoint:f,distanceToPoint2:u}=this.distanceToLines({viewport:c,points:l.handles.points,canvasCoords:o,proximity:a});return f<=a||u<=a},this.toolSelectedCallback=(n,i,o,a,s=6)=>{const c=n.detail,{element:l}=c;i.highlighted=!0;const f=_t(l,this.getToolName()),u=Ce(l),{renderingEngine:d,viewport:h}=u,{isNearFirstLine:g,isNearSecondLine:p}=this.distanceToLines({viewport:h,points:i.data.handles.points,canvasCoords:a,proximity:s});this.editData={annotation:i,viewportIdsToRender:f,movingTextBox:!1,isNearFirstLine:g,isNearSecondLine:p},this._activateModify(l),Ot(l),Pe(f),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.doneEditMemo(),this.angleStartedNotYetCompleted&&f.handles.points.length<4){zt(o),this.editData.handleIndex=f.handles.points.length;return}this.angleStartedNotYetCompleted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._mouseDownCallback=n=>{const{annotation:i,handleIndex:o}=this.editData,a=n.detail,{element:s,currentPoints:c}=a,l=c.world,{data:f}=i;if(o===1){f.handles.points[1]=l,this.editData.hasMoved=f.handles.points[1][0]!==f.handles.points[0][0]||f.handles.points[1][1]!==f.handles.points[0][0];return}if(o===3){f.handles.points[3]=l,this.editData.hasMoved=f.handles.points[3][0]!==f.handles.points[2][0]||f.handles.points[3][1]!==f.handles.points[2][0],this.angleStartedNotYetCompleted=!1;return}this.editData.hasMoved=!1,Ot(s),f.handles.points[2]=f.handles.points[3]=l,this.editData.handleIndex=f.handles.points.length-1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,isNearFirstLine:f,isNearSecondLine:u,newAnnotation:d}=this.editData;this.createMemo(o,a,{newAnnotation:d});const{data:h}=a;if(l){const{deltaPoints:v}=i,y=v.world,{textBox:m}=h.handles,{worldPosition:w}=m;w[0]+=y[0],w[1]+=y[1],w[2]+=y[2],m.hasMoved=!0}else if(c===void 0&&(f||u)){const{deltaPoints:v}=i,y=v.world,m=h.handles.points;f?[m[0],m[1]].forEach(x=>{x[0]+=y[0],x[1]+=y[1],x[2]+=y[2]}):u&&[m[2],m[3]].forEach(x=>{x[0]+=y[0],x[1]+=y[1],x[2]+=y[2]}),a.invalidated=!0}else{const{currentPoints:v}=i,y=v.world;h.handles.points[c]=[...y],a.invalidated=!0}this.editData.hasMoved=!0;const g=Ce(o),{renderingEngine:p}=g;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;s.handles.points.length<4&&gn(i.annotationUID),i.highlighted=!1,s.handles.activeHandleIndex=null;const c=Ce(n),{renderingEngine:l}=c;return Pe(o),a&&Nn(i),this.editData=null,this.angleStartedNotYetCompleted=!1,i.annotationUID},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_START,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_START,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_START,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_START,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{var d;let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let h=0;ha.worldToCanvas(Oe));!v.cachedStats[l]||v.cachedStats[l].angle==null?(v.cachedStats[l]={angle:null,arc1Angle:null,arc2Angle:null,points:{world:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null},canvas:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null}}},this._calculateCachedStats(g,f,n)):g.invalidated&&this._throttledCalculateCachedStats(g,f,n);let _;if(!Zr(p)&&!this.editData&&m!==null&&(_=[S[m]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(p))continue;_&&ir(i,p,"0",S,{color:w,lineDash:C,lineWidth:x});const T=[S[0],S[1]],E=[S[2],S[3]];let D="line1";if(vn(i,p,D,T[0],T[1],{color:w,width:x,lineDash:C}),o=!0,S.length<4)return o;D="line2",vn(i,p,D,E[0],E[1],{color:w,width:x,lineDash:C}),D="linkLine";const b=Sc(T[0],T[1]),I=Sc(E[0],E[1]);vn(i,p,D,b,I,{color:w,lineWidth:"1",lineDash:"1,4"});const{arc1Start:P,arc1End:M,arc2End:L,arc2Start:V}=v.cachedStats[l].points.canvas,{arc1Angle:G,arc2Angle:A}=v.cachedStats[l];if(this.configuration.showArcLines&&(D="arc1",vn(i,p,D,P,M,{color:w,lineWidth:"1"}),D="arc2",vn(i,p,D,V,L,{color:w,lineWidth:"1"})),!((d=v.cachedStats[l])!=null&&d.angle))continue;const k=this.getLinkedTextBoxStyle(u,g);if(!k.visibility){v.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const F=this.configuration.getTextLines(v,l);if(!v.handles.textBox.hasMoved){const Oe=na(S);v.handles.textBox.worldPosition=a.canvasToWorld(Oe)}const j=a.worldToCanvas(v.handles.textBox.worldPosition),re=qi(i,p,"cobbAngleText",F,j,S,{},k),{x:ue,y:ce,width:pe,height:Ee}=re;if(v.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([ue,ce]),topRight:a.canvasToWorld([ue+pe,ce]),bottomLeft:a.canvasToWorld([ue,ce+Ee]),bottomRight:a.canvasToWorld([ue+pe,ce+Ee])},this.configuration.showArcLines){const Oe="arcAngle1",Se=[`${G.toFixed(2)} °`],B=Sc(P,M);Eu(i,p,Oe,Se,B,{...k,padding:3});const O="arcAngle2",z=[`${A.toFixed(2)} °`],W=Sc(V,L);Eu(i,p,O,z,W,{...k,padding:3})}}return o},this.distanceToLines=({viewport:n,points:i,canvasCoords:o,proximity:a})=>{const[s,c,l,f]=i,u=n.worldToCanvas(s),d=n.worldToCanvas(c),h=n.worldToCanvas(l),g=n.worldToCanvas(f),p={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},v={start:{x:h[0],y:h[1]},end:{x:g[0],y:g[1]}},y=hi([p.start.x,p.start.y],[p.end.x,p.end.y],[o[0],o[1]]),m=hi([v.start.x,v.start.y],[v.end.x,v.end.y],[o[0],o[1]]);let w=!1,x=!1;return y<=a?w=!0:m<=a&&(x=!0),{distanceToPoint:y,distanceToPoint2:m,isNearFirstLine:w,isNearSecondLine:x}},this.getArcsStartEndPoints=({firstLine:n,secondLine:i,mid1:o,mid2:a})=>{const s=[o,a],c=S0(n,s),l=S0(i,s),f=c>90?1:0,u=l>90?0:1,d=Sc(s[0],s[1]),h=Math.sqrt((s[1][0]-s[0][0])**2+(s[1][1]-s[0][1])**2),g=.1,p=Sc(n[0],n[1]),v=Sc(i[0],i[1]),y=[n[f][0]-p[0],n[f][1]-p[1]],m=Math.sqrt(y[0]**2+y[1]**2),w=[y[0]/m,y[1]/m],x=[p[0]+w[0]*h*g,p[1]+w[1]*h*g],C=[d[0]-o[0],d[1]-o[1]],S=Math.sqrt(C[0]**2+C[1]**2),_=[C[0]/S,C[1]/S],T=[o[0]+_[0]*h*g,o[1]+_[1]*h*g],E=[i[u][0]-v[0],i[u][1]-v[1]],D=Math.sqrt(E[0]**2+E[1]**2),b=[E[0]/D,E[1]/D],I=[v[0]+b[0]*h*g,v[1]+b[1]*h*g],P=[d[0]-a[0],d[1]-a[1]],M=Math.sqrt(P[0]**2+P[1]**2),L=[P[0]/M,P[1]/M],V=[a[0]+L[0]*h*g,a[1]+L[1]*h*g];return{arc1Start:x,arc1End:T,arc2Start:I,arc2End:V,arc1Angle:c>90?180-c:c,arc2Angle:l>90?180-l:l}},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,25,{trailing:!0})}handleSelectedCallback(e,r,n,i="mouse"){const o=e.detail,{element:a}=o,{data:s}=r;r.highlighted=!0;let c=!1,l;n.worldPosition?c=!0:l=s.handles.points.findIndex(u=>u===n);const f=_t(a,this.getToolName());this.editData={annotation:r,viewportIdsToRender:f,handleIndex:l,movingTextBox:c},this._activateModify(a),Ot(a),Pe(f),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data;if(i.handles.points.length!==4)return;const o=[null,null],a=[null,null];let s=Number.MAX_VALUE;for(let T=0;T<2;T+=1)for(let E=2;E<4;E+=1){const D=ki(i.handles.points[T],i.handles.points[E]);Dc.worldToCanvas(T)),u=[f[0],f[1]],d=[f[2],f[3]],h=Sc(u[0],u[1]),g=Sc(d[0],d[1]),{arc1Start:p,arc1End:v,arc2End:y,arc2Start:m,arc1Angle:w,arc2Angle:x}=this.getArcsStartEndPoints({firstLine:u,secondLine:d,mid1:h,mid2:g}),{cachedStats:C}=i,S=Object.keys(C);for(let T=0;T{if(this.startedDrawing)return;this.startedDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;if(!(l instanceof lr))throw new Error("UltrasoundDirectionalTool can only be used on a StackViewport");Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.startedDrawing&&f.handles.points.length===1){this.editData.handleIndex=1;return}this.startedDrawing=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l}=this.editData,{data:f}=a;if(l){const{deltaPoints:h}=i,g=h.world,{textBox:p}=f.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=i,g=h.world;f.handles.points.forEach(v=>{v[0]+=g[0],v[1]+=g[1],v[2]+=g[2]}),a.invalidated=!0}else{const{currentPoints:h}=i,g=h.world;f.handles.points[c]=[...g],a.invalidated=!0}this.editData.hasMoved=!0;const u=Ce(o),{renderingEngine:d}=u;Pe(s)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,this.startedDrawing=!1,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(M));if(!p.cachedStats[l]||p.cachedStats[l].xValues==null?(p.cachedStats[l]={xValues:[0,0],yValues:[0,0],isHorizontal:!1,units:[""],isUnitless:!1},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let w="0";if(Qv(i,g,w,m[0],{color:y},0),o=!0,m.length!==2)return o;if(w="1",Qv(i,g,w,m[1],{color:y},1),p.cachedStats[l].isUnitless){const M=`${g}-line-1`;vn(i,g,"1",m[0],m[1],{color:y,width:1,shadow:this.configuration.shadow},M)}else{const M=m[0],L=m[1],V=L[1]-M[1],G=L[0]-M[0],A=p.cachedStats[l].isHorizontal;let k=[0,0];A?k=[M[0]+G,M[1]]:k=[M[0],M[1]+V];let F=`${g}-line-1`,j="1";vn(i,g,j,m[0],k,{color:y,width:1,shadow:this.configuration.shadow},F),F=`${g}-line-2`,j="2",vn(i,g,j,m[1],k,{color:y,width:1,lineDash:[1,1],shadow:this.configuration.shadow},F)}const C=this.getLinkedTextBoxStyle(u,h);if(!C.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const S=this.configuration.getTextLines(p,l,this.configuration);if(!p.handles.textBox.hasMoved){const M=m[1];p.handles.textBox.worldPosition=a.canvasToWorld(M)}const _=a.worldToCanvas(p.handles.textBox.worldPosition),E=qi(i,g,"1",S,_,m,{},C),{x:D,y:b,width:I,height:P}=E;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([D,b]),topRight:a.canvasToWorld([D+I,b]),bottomLeft:a.canvasToWorld([D,b+P]),bottomRight:a.canvasToWorld([D+I,b+P])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}toolSelectedCallback(e,r,n,i){}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;const s=_t(o,this.getToolName());let c;n.worldPosition||(c=a.handles.points.findIndex(u=>u===n)),this.editData={handleIndex:c,annotation:r,viewportIdsToRender:s},this._activateModify(o),Ot(o);const l=Ce(o),{renderingEngine:f}=l;Pe(s),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport;if(i.handles.points.length!==2)return;const{cachedStats:a}=i,s=Object.keys(a);for(let l=0;lMath.abs(I),C=[y[0],w[0]],S=[y[1],w[1]],_=[m[0],m[1]]}a[f]={xValues:C,yValues:S,isHorizontal:T,units:_,isUnitless:E}}const c=e.invalidated;return e.invalidated=!1,c&&tn(e,o,Ht.StatsUpdated),a}};PE.toolName="UltrasoundDirectionalTool";let qC=PE;function R5e(t,e,r){const n=t.cachedStats[e],{xValues:i,yValues:o,units:a,isUnitless:s,isHorizontal:c}=n;if(s)return[`${an(i[0])} px`];if(r.displayBothAxesDistances){const l=Math.abs(i[1]-i[0]),f=Math.abs(o[1]-o[0]);return[`${an(l)} ${a[0]}`,`${an(f)} ${a[1]}`]}if(c){const l=Math.abs(i[1]-i[0]);return[`${an(l)} ${a[0]}`]}else{const l=Math.abs(o[1]-o[0]);return[`${an(l)} ${a[1]}`]}}function L5e(t){return(t%360+360)%360}function XC(t,e){const r=e[0]-t[0],n=e[1]-t[1],i=Math.atan2(n,r)*(180/Math.PI);return L5e(i)}function yy(t,e){const r=XC(t,e[0]),n=XC(t,e[1]);return rr[0]-n[0]);const e=[t[0].slice()];for(let r=1;r[Math.max(f,r),Math.min(u,n)]).filter(([f,u])=>u>f);if(i.length===0)return[[r,n]];i.sort((f,u)=>f[0]-u[0]);const o=[];let[a,s]=i[0];for(let f=1;fl&&c.push([l,f]),l=Math.max(l,u);return lyy(t,f)),i=YC(n),o=i.reduce((f,[u,d])=>f+(d-u),0);if(o===0)return 0;const a=[];for(const f of r){const u=yy(t,f),d=eB(u,i);a.push(...d)}const l=YC(a).reduce((f,[u,d])=>f+(d-u),0)/o*100;return Math.min(100,Math.max(0,l))}const{transformIndexToWorld:fb}=Mn,pr=class pr extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:N5e,center:null,innerRadius:null,outerRadius:null,startAngle:null,endAngle:null,bLineColor:"rgb(60, 255, 60)",pleuraColor:"rgb(0, 4, 255)",drawDepthGuide:!0,depth_ratio:.5,depthGuideColor:"rgb(0, 255, 255)",depthGuideThickness:4,depthGuideDashLength:20,depthGuideDashGap:16,depthGuideOpacity:.2,fanOpacity:.1,showFanAnnotations:!0,updatePercentageCallback:null,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(e,r),this.pleuraAnnotations=[],this.bLineAnnotations=[],this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:f,viewUp:u,position:d}=l.getCamera(),h=this.getReferencedImageId(l,s,f,u),g={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:h,viewUp:u,cameraPosition:d},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null},annotationType:this.getActiveAnnotationType(),label:""}};nn(g,a);const p=_t(a,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(p),g},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{viewport:a}=Ce(o)||{};if(!a)return;const{annotation:s,viewportIdsToRender:c,handleIndex:l,movingTextBox:f,newAnnotation:u}=this.editData,{data:d}=s;if(this.createMemo(o,s,{newAnnotation:u}),f){const{deltaPoints:h}=i,g=h.world,{textBox:p}=d.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(l===void 0){const{deltaPoints:h}=i,g=h.world,p=d.handles.points;p.every(y=>{const m=[y[0]+g[0],y[1]+g[1],y[2]+g[2]];return this.isInsideFanShape(a,m)})&&(p.forEach(y=>{y[0]+=g[0],y[1]+=g[1],y[2]+=g[2]}),s.invalidated=!0)}else{const{currentPoints:h}=i,g=h.world;this.isInsideFanShape(a,g)&&(d.handles.points[l]=[...g],s.invalidated=!0)}this.editData.hasMoved=!0,Pe(c),s.invalidated&&tn(s,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;if(!this.getFanShapeGeometryParameters(a))return;const{imageData:c}=a.getImageData()||{};if(!c)return o;this.configuration.drawDepthGuide&&this.drawDepthGuide(i,a);let l=un(this.getToolName(),s);if(!(l!=null&&l.length)||(l=this.filterInteractableAnnotationsForElement(s,l),!(l!=null&&l.length)))return o;this.getTargetId(a),a.getRenderingEngine();const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=a.worldToCanvas(fb(c,this.configuration.center)),d=this.getIndexToCanvasRatio(a),h=this.configuration.innerRadius*d,g=this.configuration.outerRadius*d,p=a.getCurrentImageId(),v=l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===p).map(_=>{const T=_.data.handles.points.map(D=>a.worldToCanvas(D));return yy(u,T)}),y=YC(v),m=[],w=[],x=_=>{const{annotationUID:T,data:E}=_,{points:D,activeHandleIndex:b}=E.handles;f.annotationUID=T;const{color:I,lineWidth:P,lineDash:M,shadow:L}=this.getAnnotationStyle({annotation:_,styleSpecifier:f}),V=D.map(F=>a.worldToCanvas(F));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let G;if(!Gr(T))return;!Zr(T)&&!this.editData&&b!==null&&(G=[V[b]]),G&&ir(i,T,"0",V,{color:this.getColorForLineType(_),fill:this.getColorForLineType(_),lineDash:M,lineWidth:P});const A=`${T}-line`;if(vn(i,T,"1",V[0],V[1],{color:this.getColorForLineType(_),width:P,lineDash:M,shadow:L},A),this.configuration.showFanAnnotations){const F=yy(u,V);let j=0;_.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE?ub(w,F).forEach(re=>{eB(re,y).forEach(ce=>{j++;const pe=j,Ee=`${T}-fan-${pe}`,Oe=`2-${pe}`;SC(i,T,Oe,u,h,g,ce[0],ce[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:P,lineDash:M,shadow:L},Ee,10),w.push(ce)})}):_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&ub(m,F).forEach((re,ue)=>{j++;const ce=j,pe=`${T}-fan-${ce}`,Ee=`2-${ce}`;SC(i,T,Ee,u,h,g,re[0],re[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:P,lineDash:M,shadow:L},pe,5),m.push(re)})}};return l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===p).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;x(_)}),l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE&&_.metadata.referencedImageId===p).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;x(_)}),o=!0,this.configuration.updatePercentageCallback&&a&&this.configuration.updatePercentageCallback(this.calculateBLinePleuraPercentage(a)),o},this.activeAnnotationType=pr.USPleuraBLineAnnotationType.BLINE}static filterAnnotations(e,r=()=>!0){const n=un(pr.toolName,e);return n!=null&&n.length?n.filter(o=>{const a=o.metadata.referencedImageId;return r(a)}):[]}static countAnnotations(e,r=()=>!0){const n=un(pr.toolName,e),{viewport:i}=Ce(e),o=i.getImageIds(),a=c=>{const l=o.findIndex(f=>f===c);return l===-1?0:l};if(!(n!=null&&n.length))return;const s=new Map;return n.forEach(c=>{const l=c.metadata.referencedImageId;if(!r(l))return;const{annotationType:f}=c.data;let u;s.has(l)?u=s.get(l):u={frame:a(l),bLine:0,pleura:0},f===pr.USPleuraBLineAnnotationType.PLEURA?u.pleura++:f===pr.USPleuraBLineAnnotationType.BLINE&&u.bLine++,s.set(l,u)}),s}static deleteAnnotations(e,r=()=>!1){const n=un(pr.toolName,e);n!=null&&n.length&&n.forEach(i=>{r(i.metadata.referencedImageId)&&gn(i.annotationUID)})}setActiveAnnotationType(e){this.activeAnnotationType=e}getActiveAnnotationType(){return this.activeAnnotationType}deleteLastAnnotationType(e,r){let n;const i=un(pr.toolName,e);if(r===pr.USPleuraBLineAnnotationType.PLEURA?n=i.filter(o=>o.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA):r===pr.USPleuraBLineAnnotationType.BLINE&&(n=i.filter(o=>o.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE)),(n==null?void 0:n.length)>0){const o=n.pop();gn(o.annotationUID)}}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(f=>f===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o),Pe(l),e.preventDefault()}isInsideFanShape(e,r){if(!this.getFanShapeGeometryParameters(e))return!1;const{imageData:n}=e.getImageData()||{};if(n){const i=e.worldToCanvas(n.indexToWorld(this.configuration.center)),o=e.worldToCanvas(r),a=XC(i,o);return a>=this.configuration.startAngle&&a<=this.configuration.endAngle}}updateFanGeometryConfiguration(e){e&&(this.isFanShapeGeometryParametersValid(e)&&(this.configuration.center=[e.center[0],e.center[1],0]),this.configuration.innerRadius=e.innerRadius,this.configuration.outerRadius=e.outerRadius,this.configuration.startAngle=e.startAngle,this.configuration.endAngle=e.endAngle)}deriveFanGeometryFromViewport(e){const r=e.getCurrentImageId(),{fanGeometry:n}=nE(r)||{};n&&this.updateFanGeometryConfiguration(n)}isFanShapeGeometryParametersValid(e){return e||(e=this.configuration),(e==null?void 0:e.center)&&(e==null?void 0:e.innerRadius)>0&&(e==null?void 0:e.outerRadius)&&(e==null?void 0:e.startAngle)>0&&(e==null?void 0:e.startAngle)<360&&(e==null?void 0:e.endAngle)>0&&(e==null?void 0:e.endAngle)<360}getFanShapeGeometryParameters(e){if(this.isFanShapeGeometryParametersValid())return!0;if(!this.isFanShapeGeometryParametersValid()){const r=e.getCurrentImageId(),n=mt("ultrasoundFanShapeGeometry",r);this.updateFanGeometryConfiguration(n)}return this.isFanShapeGeometryParametersValid()||this.deriveFanGeometryFromViewport(e),this.isFanShapeGeometryParametersValid()}calculateBLinePleuraPercentage(e){if(!this.getFanShapeGeometryParameters(e))return;const{imageData:r}=e.getImageData()||{};if(!r)return;const{element:n}=e,i=e.worldToCanvas(r.indexToWorld(this.configuration.center)),o=e.getCurrentImageId(),a=un(this.getToolName(),n)||[],s=a.filter(l=>l.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&l.metadata.referencedImageId===o).map(l=>l.data.handles.points.map(u=>e.worldToCanvas(u))),c=a.filter(l=>l.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE&&l.metadata.referencedImageId===o).map(l=>l.data.handles.points.map(u=>e.worldToCanvas(u)));return A5e(i,s,c)}getColorForLineType(e){const{annotationType:r}=e.data,{bLineColor:n,pleuraColor:i}=this.configuration;return r===pr.USPleuraBLineAnnotationType.BLINE?n:r===pr.USPleuraBLineAnnotationType.PLEURA?i:n}getIndexToCanvasRatio(e){const{imageData:r}=e.getImageData()||{},n=e.worldToCanvas(r.indexToWorld([1,0,0])),i=e.worldToCanvas(r.indexToWorld([2,0,0])),o=[i[0]-n[0],i[1]-n[1]];return Math.sqrt(o[0]*o[0]+o[1]*o[1])}drawDepthGuide(e,r){if(!this.getFanShapeGeometryParameters(r))return;const{imageData:n}=r.getImageData()||{};if(!n)return;const i=g=>g*180/Math.PI,o=g=>g*Math.PI/180,a=g=>r.worldToCanvas(fb(n,g)),s=this.configuration.innerRadius+this.configuration.depth_ratio*(this.configuration.outerRadius-this.configuration.innerRadius),c=this.configuration.startAngle,f=this.configuration.endAngle-c,u=o(f)*s;let d=Math.round(u/(this.configuration.depthGuideDashLength+this.configuration.depthGuideDashGap));d<=0&&(d=Math.max(15,Math.round(f/5)));const h=f/d;for(let g=0;g{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=pr.hydrateBase(pr,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let JC=pr;function N5e(t,e){return[""]}const rp=class rp extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextCallback:k5e,changeTextCallback:V5e,canvasPosition:[10,10],canvasSize:10,handleRadius:"6",seriesLevel:!1,isPoint:!1}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o),{viewport:c}=s,l=a.world,f=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...l]]},seriesLevel:this.configuration.seriesLevel,isPoint:this.configuration.isPoint}});nn(f,o);const u=_t(o,this.getToolName());return n.preventDefault(),Pe(u),this.configuration.getTextCallback(d=>{if(!d){gn(f.annotationUID),Pe(u),this.isDrawing=!1;return}f.data.text=d,Nn(f),Pe(u)}),this.createMemo(o,f,{newAnnotation:!0}),f},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i;if(!(l!=null&&l.isPoint))return!1;const{canvasPosition:f,canvasSize:u}=this.configuration;return f!=null&&f.length?Math.abs(o[0]-f[0]+u/2)<=u/2&&Math.abs(o[1]-f[1]+u/2)<=u/2:!1},this.toolSelectedCallback=(n,i)=>{i.highlighted=!0,n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:f}=Ce(o);this.eventDispatchDetail={viewportId:l,renderingEngineId:f.id},this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this.doubleClickCallback=n=>{const i=n.detail,{element:o}=i;let a=un(this.getToolName(),o);if(a=this.filterInteractableAnnotationsForElement(o,a),!(a!=null&&a.length))return;const s=a.find(l=>this.isPointNearTool(o,l,i.currentPoints.canvas,6));if(!s)return;const c=s;this.createMemo(o,c),this.configuration.changeTextCallback(s,n.detail,this._doneChangingTextCallback.bind(this,o,c)),this.isDrawing=!1,this.doneEditMemo(),n.stopImmediatePropagation(),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,newAnnotation:f}=this.editData,{data:u}=c;this.createMemo(a,c,{newAnnotation:f}),u.handles.points[0]=[...s],c.invalidated=!0,Pe(l)},this._activateModify=n=>{Ge.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Ge.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fw+y),v,{color:g,width:1});if(o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o}return o}}handleSelectedCallback(e,r){const n=e.detail,{element:i}=n;r.highlighted=!0;const o=_t(i,this.getToolName());this.editData={annotation:r,viewportIdsToRender:o},this._activateModify(i),Ot(i),Pe(o),e.preventDefault()}static setPoint(e,r=!e.data.isPoint,n){e.data.isPoint=r,tn(e,n)}_doneChangingTextCallback(e,r,n){r.data.text=n;const i=_t(e,this.getToolName());Pe(i),tn(r,e)}cancel(e){if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(e),zt(e);const{annotation:r,viewportIdsToRender:n,newAnnotation:i}=this.editData,{data:o}=r;return r.highlighted=!1,o.handles.activeHandleIndex=null,Pe(n),i&&Nn(r),this.editData=null,r.annotationUID}}_isInsideVolume(e,r,n){return sr(e,n)&&sr(r,n)}};rp.toolName="KeyImage",rp.dataSeries={data:{seriesLevel:!0}},rp.dataPoint={data:{isPoint:!0}};let ZC=rp;function k5e(t){return t(prompt("Enter your annotation:"))}function V5e(t,e,r){return r(prompt("Enter your annotation:"))}class tB extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.preMouseDownCallback=n=>this._deleteNearbyAnnotations(n,"mouse"),this.preTouchStartCallback=n=>this._deleteNearbyAnnotations(n,"touch")}_deleteNearbyAnnotations(e,r){const{renderingEngineId:n,viewportId:i,element:o,currentPoints:a}=e.detail,s=Or(i,n);if(!s)return!1;const c=s._toolInstances,l=[];for(const f in c){const u=c[f];if(typeof u.isPointNearTool!="function"||typeof u.filterInteractableAnnotationsForElement!="function")continue;const d=un(f,o),h=u.filterInteractableAnnotationsForElement(o,d);if(h)for(const g of h)u.isPointNearTool(o,g,a.canvas,10,r)&&l.push(g.annotationUID)}for(const f of l){Ro(f);const u=Br(f);ar.createAnnotationMemo(o,u,{deleting:!0}),gn(f)}return e.preventDefault(),!0}}tB.toolName="Eraser";const{transformWorldToIndex:db,transformIndexToWorld:F5e}=Mn,ip=class ip extends ai{constructor(e,r){const n=Ei({configuration:{positiveStdDevMultiplier:aU,shrinkExpandIncrement:.1,islandRemoval:{enabled:!1}}},r);super(e,n)}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a,{viewUp:l}=s.getCamera(),{segmentationId:f,segmentIndex:u,labelmapVolumeId:d,referencedVolumeId:h}=await this.getLabelmapSegmentationData(s);if(!this._isOrthogonalView(s,h))throw new Error("Oblique view is not supported yet");return this.growCutData={metadata:{...s.getViewReference({points:[o]}),viewUp:l},segmentation:{segmentationId:f,segmentIndex:u,labelmapVolumeId:d,referencedVolumeId:h},viewportId:s.id,renderingEngineId:c.id},e.preventDefault(),!0}shrink(){this._runLastCommand({shrinkExpandAmount:-this.configuration.shrinkExpandIncrement})}expand(){this._runLastCommand({shrinkExpandAmount:this.configuration.shrinkExpandIncrement})}refresh(){this._runLastCommand()}async getGrowCutLabelmap(e){throw new Error("Not implemented")}async runGrowCut(){const{growCutData:e,configuration:r}=this,{segmentation:{segmentationId:n,segmentIndex:i,labelmapVolumeId:o}}=e,a=Le.getVolume(o);let s=0;const c=async({shrinkExpandAmount:l=0}={})=>{l!==0&&(this.seeds=null),s+=l;const f=Math.max(.1,r.positiveStdDevMultiplier+s),u=l<0?Math.max(1,RC-Math.abs(s)*3):RC+s*3,d={...e,options:{...e.options||{},positiveSeedValue:i,negativeSeedValue:255,positiveStdDevMultiplier:f,negativeSeedMargin:u}},h=await this.getGrowCutLabelmap(d),{isPartialVolume:g}=r;(g?this.applyPartialGrowCutLabelmap:this.applyGrowCutLabelmap)(n,i,a,h),this._removeIslands(d)};await c(),ip.lastGrowCutCommand=c,this.growCutData=null}applyPartialGrowCutLabelmap(e,r,n,i){const o=i.voxelManager.getCompleteScalarDataArray(),a=n.voxelManager,[s,c,l]=i.dimensions,[f,u]=n.dimensions,d=s*c,h=f*u;for(let g=0;g{s===r&&o.setAtIndex(c,s)}),io(e)}_runLastCommand({shrinkExpandAmount:e=0}={}){const r=ip.lastGrowCutCommand;r&&r({shrinkExpandAmount:e})}async getLabelmapSegmentationData(e){const r=ol(e.id);if(!r)throw new Error("No active segmentation found");const{segmentationId:n}=r,i=ea(n),{representationData:o}=Ln(n),a=o[Dt.Labelmap];let{volumeId:s,referencedVolumeId:c}=a;if(!s){const l=e.getImageIds();if(Nu(l))s=Sh(n).volumeId;else{const f=e.getCurrentImageId(),u=Le.getImage(f),d=iC(f);c=this._createFakeVolume([u.imageId,d.imageId]).volumeId;const g=Vu(e.id,n),p=iC(g);s=this._createFakeVolume([g,p.imageId]).volumeId}}if(!c){const{imageIds:l}=a,f=l.map(h=>Le.getImage(h).referencedImageId),u=Le.generateVolumeId(f),d=Le.getVolume(u);c=d?d.volumeId:(await i5(u,f)).volumeId}return{segmentationId:n,segmentIndex:i,labelmapVolumeId:s,referencedVolumeId:c}}_createFakeVolume(e){const r=Le.generateVolumeId(e),n=Le.getVolume(r);if(n)return n;const i=r5(e,r),o=i.spacing;o[2]===0&&(o[2]=1);const a=new lh({volumeId:r,dataType:i.dataType,metadata:structuredClone(i.metadata),dimensions:i.dimensions,spacing:i.spacing,origin:i.origin,direction:i.direction,referencedVolumeId:i.referencedVolumeId,imageIds:i.imageIds,referencedImageIds:i.referencedImageIds});return Le.putVolumeSync(r,a),a}_isOrthogonalView(e,r){const i=Le.getVolume(r).imageData,o=e.getCamera(),{ijkVecColDir:a,ijkVecSliceDir:s}=f5(i,o);return[a,s].every(c=>$t(Math.abs(c[0]),1)||$t(Math.abs(c[1]),1)||$t(Math.abs(c[2]),1))}getRemoveIslandData(e){}_removeIslands(e){const{islandRemoval:r}=this.configuration;if(!r.enabled)return;const{segmentation:{segmentIndex:n,labelmapVolumeId:i},renderingEngineId:o,viewportId:a}=e,s=Le.getVolume(i),c=this.getRemoveIslandData(e);if(!c)return;const[l,f]=s.dimensions,u=l*f,{worldIslandPoints:d=[],islandPointIndexes:h=[]}=c;let g=[...(c==null?void 0:c.ijkIslandPoints)??[]];const v=Jr(o).getViewport(a),{voxelManager:y}=s,m=new nd;g=g.concat(d.map(w=>db(s.imageData,w))),g=g.concat(h.map(w=>{const x=w%l,C=Math.floor(w/l)%f,S=Math.floor(w/u);return[x,C,S]})),m.initialize(v,y,{points:g,previewSegmentIndex:n,segmentIndex:n}),m.floodFillSegmentIsland(),m.removeExternalIslands(),m.removeInternalIslands()}getSegmentStyle({segmentationId:e,viewportId:r,segmentIndex:n}){return vV({segmentationId:e,segmentIndex:n,viewportId:r})}};ip.lastGrowCutCommand=null;let Y0=ip;Y0.toolName="GrowCutBaseTool";const RE=class RE extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positiveSeedVariance:.5,negativeSeedVariance:.9}}){super(e,r),this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,{world:s}=a,c=Ce(o),{viewport:l}=c;this.growCutData.circleBorderPoint=s,Pe([l.id])},this._endCallback=async n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a;this.runGrowCut(),this._deactivateDraw(o),this.growCutData=null,zt(o),Pe([s.id])},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a;return await super.preMouseDownCallback(e),Object.assign(this.growCutData,{circleCenterPoint:o,circleBorderPoint:o}),this._activateDraw(n),Ot(n),Pe([s.id]),!0}async getGrowCutLabelmap(e){const{segmentation:{referencedVolumeId:r},renderingEngineId:n,viewportId:i,circleCenterPoint:o,circleBorderPoint:a,options:s}=e,l=Jr(n).getViewport(i),f=N0(En(Ve(),o,a));return iU(r,{center:o,radius:f},l,s)}_activateDraw(e){e.addEventListener(N.MOUSE_UP,this._endCallback),e.addEventListener(N.MOUSE_DRAG,this._dragCallback),e.addEventListener(N.MOUSE_CLICK,this._endCallback)}renderAnnotation(e,r){if(!this.growCutData)return;const{viewport:n}=e,{segmentation:i,circleCenterPoint:o,circleBorderPoint:a}=this.growCutData,s=n.worldToCanvas(o),c=n.worldToCanvas(a),l=Ga(qt(),c,s),f=qK(l);if($t(f,0))return;const u="growcut",d="0",{color:h}=this.getSegmentStyle({segmentationId:i.segmentationId,segmentIndex:i.segmentIndex,viewportId:n.id});No(r,u,d,s,f,{color:h})}};RE.toolName="RegionSegment";let QC=RE;const LE=class LE extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!1,positiveSeedVariance:.4,negativeSeedVariance:.9,subVolumePaddingPercentage:.1,islandRemoval:{enabled:!1}}}){super(e,r),this.mouseTimer=null,this.allowedToProceed=!1}mouseMoveCallback(e){if(this.mode!==An.Active)return;const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n;i.style.cursor="default",this.mouseTimer!==null&&(window.clearTimeout(this.mouseTimer),this.mouseTimer=null),this.mouseTimer=window.setTimeout(()=>{this.onMouseStable(e,o,i)},this.configuration.mouseStabilityDelay||500)}async onMouseStable(e,r,n){await super.preMouseDownCallback(e);const i=Le.getVolume(this.growCutData.segmentation.referencedVolumeId),o=sU(i,r,{})||{positiveSeedIndices:new Set,negativeSeedIndices:new Set},{positiveSeedIndices:a,negativeSeedIndices:s}=o;let c;a.size/s.size>20||s.size<30?(c="not-allowed",this.allowedToProceed=!1):(c="copy",this.allowedToProceed=!0);const l=Ce(n);n&&(n.style.cursor=c,requestAnimationFrame(()=>{n.style.cursor!==c&&(n.style.cursor=c)})),this.allowedToProceed&&(this.seeds=o),l&&l.viewport&&l.viewport.render()}async preMouseDownCallback(e){if(!this.allowedToProceed)return!1;const r=e.detail,{currentPoints:n,element:i}=r;Ce(i)&&(i.style.cursor="wait",requestAnimationFrame(()=>{i.style.cursor!=="wait"&&(i.style.cursor="wait")}));const{world:a}=n;return await super.preMouseDownCallback(e),this.growCutData=Ei(this.growCutData,{worldPoint:a,islandRemoval:{worldIslandPoints:[a]}}),this.growCutData.worldPoint=a,this.growCutData.islandRemoval={worldIslandPoints:[a]},await this.runGrowCut(),i&&(i.style.cursor="default"),!0}getRemoveIslandData(e){const{worldPoint:r}=e;return{worldIslandPoints:[r]}}async getGrowCutLabelmap(e){const{segmentation:{referencedVolumeId:r},worldPoint:n,options:i}=e,{subVolumePaddingPercentage:o}=this.configuration,a={...i,subVolumePaddingPercentage:o,seeds:this.seeds};return cU({referencedVolumeId:r,worldPosition:n,options:a})}};LE.toolName="RegionSegmentPlus";let eS=LE;const U5e=[-1/0,-995],B5e=[0,1900],G5e=[1e3,1900],{transformWorldToIndex:jm,transformIndexToWorld:x3}=Mn;class nB extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positivePixelRange:B5e,negativePixelRange:U5e,islandRemoval:{enabled:!0,islandPixelRange:G5e}}}){super(e,r),this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,{world:s}=a,c=Ce(o),{viewport:l}=c,f=this._getHorizontalLineWorldPoints(c,s);this.growCutData.horizontalLines[1]=f,Pe([l.id])},this._endCallback=async n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a;await this.runGrowCut(),this._deactivateDraw(o),this.growCutData=null,zt(o),Pe([s.id])},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a,l=this._getHorizontalLineWorldPoints(a,o);return await super.preMouseDownCallback(e),this.growCutData.horizontalLines=[l,l],this._activateDraw(n),Ot(n),Pe([s.id]),!0}renderAnnotation(e,r){if(!this.growCutData)return;const{segmentation:n,horizontalLines:i}=this.growCutData;if(i.length!==2)return;const{viewport:o}=e,{segmentationId:a,segmentIndex:s}=n,[c,l]=i,[f,u]=c,[d,h]=l,g=[f,u,h,d].map(S=>o.worldToCanvas(S)),p="growCutRect",v="0",{color:y,fillColor:m,lineWidth:w,fillOpacity:x,lineDash:C}=this.getSegmentStyle({segmentationId:a,segmentIndex:s,viewportId:o.id});Cs(r,p,v,g,{color:y,fillColor:m,fillOpacity:x,lineWidth:w,lineDash:C,closePath:!0})}async getGrowCutLabelmap(e){const{segmentation:{segmentIndex:r,referencedVolumeId:n},renderingEngineId:i,viewportId:o,horizontalLines:a}=e,c=Jr(i).getViewport(o),[l,f]=a,u=[l[0],l[1],f[1],f[0]],d=Le.getVolume(n),{topLeft:h,bottomRight:g}=this._getWorldBoundingBoxFromProjectedSquare(c,u),p=jm(d.imageData,h),v=jm(d.imageData,g),y={boundingBox:{ijkTopLeft:p,ijkBottomRight:v}},m=this.configuration,w={positiveSeedValue:r,negativeSeedValue:255,negativePixelRange:m.negativePixelRange,positivePixelRange:m.positivePixelRange};return oU(n,y,w)}getRemoveIslandData(){const{segmentation:{segmentIndex:e,referencedVolumeId:r,labelmapVolumeId:n}}=this.growCutData,i=Le.getVolume(r),o=Le.getVolume(n),a=i.voxelManager.getCompleteScalarDataArray(),s=o.voxelManager.getCompleteScalarDataArray(),{islandPixelRange:c}=this.configuration.islandRemoval,l=[];for(let f=0,u=s.length;f=c[0]&&d<=c[1]&&l.push(f)}return{islandPointIndexes:l}}_activateDraw(e){e.addEventListener(N.MOUSE_UP,this._endCallback),e.addEventListener(N.MOUSE_DRAG,this._dragCallback),e.addEventListener(N.MOUSE_CLICK,this._endCallback)}_projectWorldPointAcrossSlices(e,r,n){const i=this._getViewportVolume(e),{dimensions:o}=i,a=jm(i.imageData,r),s=n.findIndex(f=>$t(Math.abs(f),1));if(s===-1)throw new Error("Non-orthogonal direction vector");const c=[...a],l=[...a];return c[s]=0,l[s]=o[s]-1,[c,l]}_getCuboidIJKEdgePointsFromProjectedWorldPoint(e,r){const{viewPlaneNormal:n}=e.getCamera();return this._projectWorldPointAcrossSlices(e,r,n)}_getWorldCuboidCornerPoints(e,r){const n=[],i=this._getViewportVolume(e);return r.forEach(o=>{const s=this._getCuboidIJKEdgePointsFromProjectedWorldPoint(e,o).map(c=>x3(i.imageData,c));n.push(...s)}),n}_getWorldBoundingBoxFromProjectedSquare(e,r){const n=this._getWorldCuboidCornerPoints(e,r),i=[...n[0]],o=[...n[0]];return n.forEach(a=>{NK(i,i,a),kK(o,o,a)}),{topLeft:i,bottomRight:o}}_getViewportVolume(e){if(!(e instanceof Ir))throw new Error("Viewport is not a BaseVolumeViewport");const r=e.getAllVolumeIds()[0];return Le.getVolume(r)}_getHorizontalLineIJKPoints(e,r){const{viewport:n}=e,i=this._getViewportVolume(n),{dimensions:o}=i,a=jm(i.imageData,r),{viewUp:s,viewPlaneNormal:c}=n.getCamera(),f=Rn(Ve(),s,c).findIndex(h=>$t(Math.abs(h),1)),u=[...a],d=[...a];return u[f]=0,d[f]=o[f]-1,[u,d]}_getHorizontalLineWorldPoints(e,r){const{viewport:n}=e,i=this._getViewportVolume(n),[o,a]=this._getHorizontalLineIJKPoints(e,r),s=x3(i.imageData,o),c=x3(i.imageData,a);return[s,c]}}nB.toolName="WholeBodySegment";function W5e(t,e,r=!0){const n=Object.assign({},e,{segmentIndex:0});j4(t,n)}function z5e(t,e){W5e(t,e,!0)}class rB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:j4,ERASE_INSIDE:z5e},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=ol(l.id);if(!h)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:g}=h,p=ea(g),v=dd(g),y=el(l.id,g,p),{representationData:m}=Ln(g),w=m[Dt.Labelmap],x={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:l.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:y},data:{handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null}}},C=_t(a,this.getToolName());if(this.editData={annotation:x,segmentIndex:p,segmentationId:g,segmentsLocked:v,segmentColor:y,viewportIdsToRender:C,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},l instanceof Ir){const{volumeId:S}=w,_=Le.getVolume(S);this.editData={...this.editData,volumeId:S,referencedVolumeId:_.referencedVolumeId}}else{const S=Vu(l.id,g);this.editData={...this.editData,imageId:S}}return this._activateDraw(a),Ot(a),n.preventDefault(),Pe(C),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c}=this.editData,{data:l}=a,{currentPoints:f}=i,u=Ce(o),{worldToCanvas:d,canvasToWorld:h}=u.viewport,g=f.world,{points:p}=l.handles;p[c]=[...g];let v,y,m,w,x,C,S,_;switch(c){case 0:case 3:v=d(p[0]),w=d(p[3]),y=[w[0],v[1]],m=[v[0],w[1]],C=h(y),S=h(m),p[1]=C,p[2]=S;break;case 1:case 2:y=d(p[1]),m=d(p[2]),v=[m[0],y[1]],w=[y[0],m[1]],x=h(v),_=h(w),p[0]=x,p[3]=_;break}a.invalidated=!0,this.editData.hasMoved=!0,Pe(s)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=a;if(s&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const f=Ce(o),u={...this.editData,points:l.handles.points,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(f,u),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{annotation:s}=this.editData,c=s.metadata,l=s.annotationUID,f=s.data,{points:u}=f.handles,d=u.map(p=>a.worldToCanvas(p)),h=`rgb(${c.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(P1(i,l,"0",d[0],d[3],{color:h}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}rB.toolName="RectangleScissor";class iB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:G5,ERASE_INSIDE:HF},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=o.canvas,l=Ce(a),{viewport:f}=l;this.isDrawing=!0;const u=f.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=ol(f.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:p}=g,v=ea(p),y=dd(p),m=el(f.id,p,v),{representationData:w}=Ln(p),x=w.Labelmap;if(!x)throw new Error("No labelmap data found for the active segmentation, create one before using scissors tool");const C={invalidated:!0,highlighted:!0,metadata:{viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:f.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:m},data:{handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},isDrawing:!0,cachedStats:{}}},S=[f.id];if(this.editData={annotation:C,centerCanvas:c,segmentIndex:v,segmentationId:p,segmentsLocked:y,segmentColor:m,viewportIdsToRender:S,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},f instanceof Ir){const{volumeId:_}=x,T=Le.getVolume(_);this.editData={...this.editData,volumeId:_,referencedVolumeId:T.referencedVolumeId}}else{const _=Vu(f.id,p);this.editData={...this.editData,imageId:_}}return this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h,centerCanvas:g}=this.editData,{data:p}=d,v=Math.abs(s[0]-g[0]),y=Math.abs(s[1]-g[1]),m=Math.sqrt(v*v+y*y),w=[g[0],g[1]+m],x=[g[0],g[1]-m],C=[g[0]-m,g[1]],S=[g[0]+m,g[1]];p.handles.points=[u(w),u(x),u(C),u(S)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=a,{viewPlaneNormal:f,viewUp:u}=a.metadata;if(s&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const d=Ce(o),h={...this.editData,points:l.handles.points,viewPlaneNormal:f,viewUp:u,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(d,h),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_END,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{viewportIdsToRender:s}=this.editData;if(!s.includes(a.id))return o;const{annotation:c}=this.editData,l=c.metadata,f=c.annotationUID,u=c.data,{points:d}=u.handles,h=d.map(x=>a.worldToCanvas(x)),g=h[0],p=h[1],v=[Math.floor((g[0]+p[0])/2),Math.floor((g[1]+p[1])/2)],y=Math.abs(g[1]-Math.floor((g[1]+p[1])/2)),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(No(i,f,"0",v,y,{color:m}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}iB.toolName="CircleScissor";class oB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:$F,ERASE_INSIDE:jF},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;this.doneEditMemo();const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=o.canvas,l=Ce(a),{viewport:f}=l;this.isDrawing=!0;const u=f.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=ol(f.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:p}=g,v=ea(p),y=dd(p),m=el(f.id,p,v);this.isDrawing=!0;const w={metadata:{viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:f.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:m},data:{invalidated:!0,handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},cachedStats:{},highlighted:!0}},x=[f.id];this.editData={annotation:w,centerCanvas:c,segmentIndex:v,segmentationId:p,segmentsLocked:y,segmentColor:m,toolGroupId:this.toolGroupId,viewportIdsToRender:x,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null};const{representationData:C}=Ln(p),S=this.getEditData({viewport:f,representationData:C,segmentsLocked:y,segmentationId:p});return this.editData={...this.editData,...S},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(x),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h,centerCanvas:g}=this.editData,{data:p}=d,v=Math.abs(s[0]-g[0]),y=Math.abs(s[1]-g[1]),m=Math.sqrt(v*v+y*y),w=[g[0],g[1]+m],x=[g[0],g[1]-m],C=[g[0]-m,g[1]],S=[g[0]+m,g[1]];p.handles.points=[u(w),u(x),u(C),u(S)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c,segmentIndex:l,segmentsLocked:f}=this.editData,{data:u}=a,{viewPlaneNormal:d,viewUp:h}=a.metadata;if(s&&!c)return;a.highlighted=!1,u.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const g=Ce(o),p={...this.editData,points:u.handles.points,segmentIndex:l,segmentsLocked:f,viewPlaneNormal:d,viewUp:h,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(g,p),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{viewportIdsToRender:s}=this.editData;if(!s.includes(a.id))return o;const{annotation:c}=this.editData,l=c.metadata,f=c.annotationUID,u=c.data,{points:d}=u.handles,h=d.map(x=>a.worldToCanvas(x)),g=h[0],p=h[1],v=[Math.floor((g[0]+p[0])/2),Math.floor((g[1]+p[1])/2)],y=Math.abs(g[1]-Math.floor((g[1]+p[1])/2)),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(No(i,f,"0",v,y,{color:m}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}oB.toolName="SphereScissor";const{transformWorldToIndex:eg}=Mn;class aB extends gy{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:$5e,statsCalculator:rc,showTextBox:!1,throttleTimeout:100}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u;let g,p,v;if(l instanceof lr)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);v=sc(_),p=Le.getVolume(v),g=qc(p,s,d)}const y=Au(p,d),m=this._getStartCoordinate(s,y,d),w=this._getEndCoordinate(s,y,d),x=l.getFrameOfReferenceUID(),C={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:x,referencedImageId:g,volumeId:v,spacingInNormal:y,enabledElement:c},data:{label:"",startCoordinate:m,endCoordinate:w,handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s]],activeHandleIndex:null},cachedStats:{pointsInVolume:[],projectionPoints:[],statistics:[]},labelmapUID:null}};this._computeProjectionPoints(C,p),nn(C,a);const S=_t(a,this.getToolName());return this.editData={annotation:C,viewportIdsToRender:S,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),C},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const d=this.getTargetId(u.viewport),h=Le.getVolume(d.split(/volumeId:|\?/)[1]);this._computePointsInsideVolume(a,h,d,u),Pe(s),c?Nn(a):tn(a,o)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;let s=un(this.getToolName(),a.element);if(!(s!=null&&s.length))return o;s=L5(s,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let l=0;la.worldToCanvas(ue)),S=C[0],_=du(C),{centerPointRadius:T}=this.configuration,E=x0(C),D=a.getCamera().focalPoint,b=a.getCamera().viewPlaneNormal;let I=g,P=p;Array.isArray(g)&&(I=this._getCoordinateForViewplaneNormal(I,b),d.startCoordinate=I),Array.isArray(p)&&(P=this._getCoordinateForViewplaneNormal(P,b),d.endCoordinate=P);const M=eu(d.startCoordinate),L=eu(d.endCoordinate),V=this._getCoordinateForViewplaneNormal(D,b),G=eu(V);if(GMath.max(M,L))continue;const A=eu((d.startCoordinate+d.endCoordinate)/2);let k=!1;if(G===A&&(k=!0),d.handles.points[0][this._getIndexOfCoordinatesForViewplaneNormal(b)]=A,f.invalidated&&this._throttledCalculateCachedStats(f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let F;if(!Gr(u))continue;!Zr(u)&&!this.editData&&y!==null&&k&&(F=[C[y]]),F&&ir(i,u,"0",F,{color:x});let j=m,Y=w;k?(j=m,Y=[]):Y=[5,5];const re="0";if(No(i,u,re,S,_,{color:x,lineDash:Y,lineWidth:j}),T>0&&_>3*T&&No(i,u,`${re}-center`,S,T,{color:x,lineDash:w,lineWidth:m}),o=!0,this.configuration.showTextBox){const ue=this.getLinkedTextBoxStyle(c,f);if(!ue.visibility){d.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const ce=this.configuration.getTextLines(d,{metadata:h});if(!ce||ce.length===0)continue;let pe;d.handles.textBox.hasMoved||(pe=na(E),d.handles.textBox.worldPosition=a.canvasToWorld(pe));const Ee=a.worldToCanvas(d.handles.textBox.worldPosition),Se=qi(i,u,"1",ce,Ee,C,{},ue),{x:B,y:O,width:z,height:W}=Se;d.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([B,O]),topRight:a.canvasToWorld([B+z,O]),bottomLeft:a.canvasToWorld([B,O+W]),bottomRight:a.canvasToWorld([B+z,O+W])}}}return o},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=_o(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=gh(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(e,r){const{data:n,metadata:i}=e,{viewPlaneNormal:o,spacingInNormal:a}=i,{imageData:s}=r,{startCoordinate:c,endCoordinate:l}=n,{points:f}=n.handles,u=eg(s,f[0]),d=eg(s,f[0]),h=Fa(f),g=Ve();s.indexToWorldVec3(u,g);const p=Ve();s.indexToWorldVec3(d,p),this._getIndexOfCoordinatesForViewplaneNormal(o)==2?(g[2]=c,p[2]=l,h[0][2]=c,h[1][2]=c):this._getIndexOfCoordinatesForViewplaneNormal(o)==0?(g[0]=c,p[0]=l,h[0][0]=c,h[1][0]=c):this._getIndexOfCoordinatesForViewplaneNormal(o)==1&&(g[1]=c,p[1]=l,h[0][1]=c,h[1][1]=c);const v=ki(g,p),y=[];for(let m=0;m{const x=Ve();return Tn(x,w,o,m),Array.from(x)}));n.cachedStats.projectionPoints=y}_computePointsInsideVolume(e,r,n,i){var D,b,I;const{data:o,metadata:a}=e,{viewPlaneNormal:s,viewUp:c}=a,{viewport:l}=i,f=o.cachedStats.projectionPoints,u=[[]],d=this.getTargetImageData(n),h=o.handles.points.map(P=>l.worldToCanvas(P)),[g,p]=x0(h),v=l.canvasToWorld(g),y=l.canvasToWorld(p),{worldWidth:m,worldHeight:w}=mh(s,c,v,y),x=ta(d,o.handles),C=I4(d),S=Math.abs(Math.PI*(m/x.scale/2)*(w/C/x.scale/2)),_={isPreScaled:al(l,n),isSuvScaled:this.isSuvScaled(l,n,e.metadata.referencedImageId)},T=sl(a.Modality,e.metadata.referencedImageId,_);for(let P=0;Pl.worldToCanvas(Se)),[V,G]=x0(L),A=l.canvasToWorld(V),k=l.canvasToWorld(G),F=A,j=k,{dimensions:Y,imageData:re,voxelManager:ue}=r,ce=eg(re,F),pe=eg(re,M),Ee=this._getIndexOfCoordinatesForViewplaneNormal(s);ce[0]=Math.floor(ce[0]),ce[1]=Math.floor(ce[1]),ce[2]=Math.floor(ce[2]),ce[Ee]=pe[Ee];const Oe=eg(re,j);if(Oe[0]=Math.floor(Oe[0]),Oe[1]=Math.floor(Oe[1]),Oe[2]=Math.floor(Oe[2]),Oe[Ee]=pe[Ee],this._isInsideVolume(ce,Oe,Y)){const Se=Math.min(ce[0],Oe[0]),B=Math.max(ce[0],Oe[0]),O=Math.min(ce[1],Oe[1]),z=Math.max(ce[1],Oe[1]),W=Math.min(ce[2],Oe[2]),K=Math.max(ce[2],Oe[2]),Z=[[Se,B],[O,z],[W,K]],xe={center:M,xRadius:Math.abs(A[0]-k[0])/2,yRadius:Math.abs(A[1]-k[1])/2,zRadius:Math.abs(A[2]-k[2])/2},De=ue.forEach(this.configuration.statsCalculator.statsCallback,{isInObject:Ne=>T5(xe,Ne),boundsIJK:Z,imageData:re,returnPoints:this.configuration.storePointData});u.push(De)}}const E=this.configuration.statsCalculator.getStatistics();o.cachedStats.pointsInVolume=u,o.cachedStats.statistics={Modality:a.Modality,area:S,mean:(D=E.mean)==null?void 0:D.value,stdDev:(b=E.stdDev)==null?void 0:b.value,max:(I=E.max)==null?void 0:I.value,statsArray:E.array,areaUnit:x.areaUnit,modalityUnit:T}}_calculateCachedStatsTool(e,r){const n=e.data,{viewport:i}=r,{cachedStats:o}=n,a=this.getTargetId(i),s=Le.getVolume(a.split(/volumeId:|\?/)[1]);return this._computeProjectionPoints(e,s),this._computePointsInsideVolume(e,s,a,r),e.invalidated=!1,tn(e,i.element),o}_getStartCoordinate(e,r,n){const i=this.configuration.numSlicesToPropagate,o=Math.round(i/2),a=Ve();return Tn(a,e,n,o*-r),this._getCoordinateForViewplaneNormal(a,n)}_getEndCoordinate(e,r,n){const i=this.configuration.numSlicesToPropagate,o=i-Math.round(i/2),a=Ve();return Tn(a,e,n,o*r),this._getCoordinateForViewplaneNormal(a,n)}_getIndexOfCoordinatesForViewplaneNormal(e){const r=[Math.abs(e[0]),Math.abs(e[1]),Math.abs(e[2])];return r.indexOf(Math.max(...r))}_getCoordinateForViewplaneNormal(e,r){const n=this._getIndexOfCoordinatesForViewplaneNormal(r);return e[n]}}function $5e(t,e={}){const r=t.cachedStats.statistics,{area:n,mean:i,max:o,stdDev:a,areaUnit:s,modalityUnit:c}=r;if(i===void 0)return;const l=[];return l.push(`Area: ${an(n)} ${s}`),l.push(`Mean: ${an(i)} ${c}`),l.push(`Max: ${an(o)} ${c}`),l.push(`Std Dev: ${an(a)} ${c}`),l}aB.toolName="CircleROIStartEndThreshold";const{transformWorldToIndex:hb,isEqual:C3}=Mn;class sB extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.preMouseDownCallback=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c,f=l.getCamera(),{viewPlaneNormal:u}=f,d=ol(l.id);if(!d)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:h}=d,g=ea(h),p=dd(h),{representationData:v}=Ln(h);let y,m,w,x;if(this.doneEditMemo(),l instanceof Ir){const{volumeId:L}=v[Dt.Labelmap],V=Le.getVolume(L);({dimensions:y,direction:m}=V),x=V.voxelManager,w=hb(V.imageData,s)}else{const L=Vu(l.id,h);if(!L)throw new Error("No active segmentation imageId detected, create one before using scissors tool");const{imageData:V}=l.getImageData();y=V.getDimensions(),m=V.getDirection(),x=Le.getImage(L).voxelManager,w=hb(V,s)}const C=this.getFixedDimension(u,m);if(C===void 0){console.warn("Oblique paint fill not yet supported");return}const{floodFillGetter:S,getLabelValue:_,getScalarDataPositionFromPlane:T,inPlaneSeedPoint:E,fixedDimensionValue:D}=this.generateHelpers(x,y,w,C);if(w[0]<0||w[0]>=y[0]||w[1]<0||w[1]>=y[1]||w[2]<0||w[2]>=y[2])return;const b=_(w[0],w[1],w[2]);if(p.includes(b))return;const I=$4(S,E),{flooded:P}=I;P.forEach(L=>{const V=T(L[0],L[1]);x.setAtIndex(V,g)});const M=this.getFramesModified(C,D,I);return io(h,M),!0},this.getFramesModified=(n,i,o)=>{const{flooded:a}=o;if(n===2)return[i];let s=1/0,c=-1/0;for(let f=0;fc&&(c=u)}const l=[];for(let f=s;f<=c;f++)l.push(f);return l},this.generateHelpers=(n,i,o,a=2)=>{let s,c;switch(a){case 0:s=o[0],c=[o[1],o[2]];break;case 1:s=o[1],c=[o[0],o[2]];break;case 2:s=o[2],c=[o[0],o[1]];break;default:throw new Error(`Invalid fixedDimension: ${a}`)}const l=(h,g,p)=>n.toIndex([h,g,p]),f=(h,g,p)=>n.getAtIJK(h,g,p),u=this.generateFloodFillGetter(i,a,s,f);return{getScalarDataPositionFromPlane:this.generateGetScalarDataPositionFromPlane(l,a,s),getLabelValue:f,floodFillGetter:u,inPlaneSeedPoint:c,fixedDimensionValue:s}},this.generateFloodFillGetter=(n,i,o,a)=>{let s;switch(i){case 0:s=(c,l)=>{if(!(c>=n[1]||c<0||l>=n[2]||l<0))return a(o,c,l)};break;case 1:s=(c,l)=>{if(!(c>=n[0]||c<0||l>=n[2]||l<0))return a(c,o,l)};break;case 2:s=(c,l)=>{if(!(c>=n[0]||c<0||l>=n[1]||l<0))return a(c,l,o)};break;default:throw new Error(`Invalid fixedDimension: ${i}`)}return s},this.generateGetScalarDataPositionFromPlane=(n,i,o)=>{let a;switch(i){case 0:a=(s,c)=>n(o,s,c);break;case 1:a=(s,c)=>n(s,o,c);break;case 2:a=(s,c)=>n(s,c,o);break;default:throw new Error(`Invalid fixedDimension: ${i}`)}return a}}getFixedDimension(e,r){const n=r.slice(0,3),i=r.slice(3,6),o=r.slice(6,9),a=[Math.abs(e[0]),Math.abs(e[1]),Math.abs(e[2])],s=[Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2])];if(C3(a,s))return 0;const c=[Math.abs(i[0]),Math.abs(i[1]),Math.abs(i[2])];if(C3(a,c))return 1;const l=[Math.abs(o[0]),Math.abs(o[1]),Math.abs(o[2])];if(C3(a,l))return 2}}sB.toolName="PaintFill";const j5e={TOP_LEFT:"TOP_LEFT",TOP_RIGHT:"TOP_RIGHT",BOTTOM_LEFT:"BOTTOM_LEFT",BOTTOM_RIGHT:"BOTTOM_RIGHT"};var oE={Corners:j5e};const{vtkErrorMacro:S3}=ne,{Corners:Hm}=oE;function H5e(t,e){e.classHierarchy.push("vtkOrientationMarkerWidget");const r={...t},n=[],i=PR.newInstance(),o=new ResizeObserver(d=>{t.updateViewport()});let a=null,s=null,c=null,l=null,f=null;function u(){e._interactor.isAnimating()||t.updateMarkerOrientation()}e._onParentRendererChanged=()=>t.updateViewport(),t.computeViewport=()=>{const d=e.parentRenderer||e._interactor.getCurrentRenderer(),[h,g,p,v]=d.getViewport(),y=e._interactor.getView(),m=y.getSize(),[w,x]=y.getViewportSize(d),C=Math.min(w,x);let S=e.viewportSize*C;S=Math.max(Math.min(e.minPixelSize,C),Math.min(e.maxPixelSize,S));const _=S/m[0],T=S/m[1];switch(e.viewportCorner){case Hm.TOP_LEFT:return[h,v-T,h+_,v];case Hm.TOP_RIGHT:return[p-_,v-T,p,v];case Hm.BOTTOM_LEFT:return[h,g,h+_,g+T];case Hm.BOTTOM_RIGHT:return[p-_,g,p,g+T];default:return S3("Invalid widget corner"),null}},t.updateViewport=()=>{e.enabled&&(i.setViewport(...t.computeViewport()),e._interactor.render())},t.updateMarkerOrientation=()=>{const h=(e.parentRenderer||e._interactor.getCurrentRenderer()).getActiveCamera();if(!h)return;const g=h.getReferenceByName("position"),p=h.getReferenceByName("focalPoint"),v=h.getReferenceByName("viewUp");if(n[0]!==g[0]||n[1]!==g[1]||n[2]!==g[2]||n[3]!==p[0]||n[4]!==p[1]||n[5]!==p[2]||n[6]!==v[0]||n[7]!==v[1]||n[8]!==v[2]){n[0]=g[0],n[1]=g[1],n[2]=g[2],n[3]=p[0],n[4]=p[1],n[5]=p[2],n[6]=v[0],n[7]=v[1],n[8]=v[2];const y=i.getActiveCamera();y.setPosition(g[0],g[1],g[2]),y.setFocalPoint(p[0],p[1],p[2]),y.setViewUp(v[0],v[1],v[2]),i.resetCamera()}},t.setEnabled=d=>{var h,g;if(d){if(e.enabled)return;if(!e.actor){S3("Must set actor before enabling orientation marker.");return}if(!e._interactor){S3("Must set interactor before enabling orientation marker.");return}const p=e.parentRenderer||e._interactor.getCurrentRenderer(),v=p.getRenderWindow();v.addRenderer(i),v.getNumberOfLayers()<2&&v.setNumberOfLayers(2),i.setLayer(v.getNumberOfLayers()-1),i.setInteractive(e.interactiveRenderer),i.addViewProp(e.actor),e.actor.setVisibility(!0),a=p.onEvent(y=>{y.type==="ActiveCameraEvent"&&(s&&s.unsubscribe(),s=y.camera.onModified(u))}),s=p.getActiveCamera().onModified(u),c=e._interactor.onAnimation(t.updateMarkerOrientation),l=e._interactor.onEndAnimation(t.updateMarkerOrientation),o.observe(e._interactor.getView().getCanvas()),t.updateViewport(),t.updateMarkerOrientation(),e.enabled=!0}else{if(!e.enabled)return;e.enabled=!1,o.disconnect(),a.unsubscribe(),a=null,s.unsubscribe(),s=null,c.unsubscribe(),c=null,l.unsubscribe(),l=null,e.actor.setVisibility(!1),i.removeViewProp(e.actor);const p=(g=(h=e._interactor)==null?void 0:h.findPokedRenderer())==null?void 0:g.getRenderWindow();p&&p.removeRenderer(i)}t.modified()},t.setViewportCorner=d=>{d!==e.viewportCorner&&(e.viewportCorner=d,t.updateViewport())},t.setViewportSize=d=>{const h=Math.min(1,Math.max(0,d));h!==e.viewportSize&&(e.viewportSize=h,t.updateViewport())},t.setActor=d=>{const h=e.enabled;t.setEnabled(!1),e.actor=d,t.setEnabled(h)},t.getRenderer=()=>i,t.delete=()=>{r.delete(),f&&(f.unsubscribe(),f=null),a&&(a.unsubscribe(),a=null),s&&(s.unsubscribe(),s=null),c&&(c.unsubscribe(),c=null),l&&(l.unsubscribe(),l=null),o.disconnect()},f=t.onModified(t.updateViewport)}const K5e={viewportCorner:oE.Corners.BOTTOM_LEFT,viewportSize:.2,minPixelSize:50,maxPixelSize:200,parentRenderer:null,interactiveRenderer:!1};function cB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,K5e,r),ne.obj(t,e),ne.get(t,e,["enabled","viewportCorner","viewportSize","interactiveRenderer"]),ne.setGet(t,e,["_interactor","minPixelSize","maxPixelSize","parentRenderer"]),ne.get(t,e,["actor"]),ne.moveToProtected(t,e,["interactor"]),H5e(t,e)}const q5e=ne.newInstance(cB,"vtkOrientationMarkerWidget");var gb={newInstance:q5e,extend:cB,...oE};function lB(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[0,0,0,0];const[r,n,i,o]=e,s=t.getContext("2d").getImageData(r,n,i||t.width,o||t.height),c=h1.newInstance({type:"vtkImageData"});c.setOrigin(0,0,0),c.setSpacing(1,1,1),c.setExtent(0,(i||t.width)-1,0,(o||t.height)-1,0,0);const l=Yt.newInstance({numberOfComponents:4,values:new Uint8Array(s.data.buffer)});return l.setName("scalars"),c.getPointData().setScalars(l),c}function X5e(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{flipX:!1,flipY:!1,rotate:0};const r=document.createElement("canvas");r.width=t.width,r.height=t.height;const n=r.getContext("2d"),{flipX:i,flipY:o,rotate:a}=e;return n.translate(r.width/2,r.height/2),n.scale(i?-1:1,o?-1:1),n.rotate(a*Math.PI/180),n.drawImage(t,-t.width/2,-t.height/2),lB(r)}var Y5e={canvasToImageData:lB,imageToImageData:X5e};const uB={default:{defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:t=>t/2,faceColor:"white",edgeThickness:.1,edgeColor:"black",resolution:400},xMinusFaceProperty:{text:"X-",faceColor:"yellow"},xPlusFaceProperty:{text:"X+",faceColor:"yellow"},yMinusFaceProperty:{text:"Y-",faceColor:"red"},yPlusFaceProperty:{text:"Y+",faceColor:"red"},zMinusFaceProperty:{text:"Z-",faceColor:"#008000"},zPlusFaceProperty:{text:"Z+",faceColor:"#008000"}},lps:{xMinusFaceProperty:{text:"R",faceRotation:-90},xPlusFaceProperty:{text:"L",faceRotation:90},yMinusFaceProperty:{text:"A",faceRotation:0},yPlusFaceProperty:{text:"P",faceRotation:180},zMinusFaceProperty:{text:"I",faceRotation:180},zPlusFaceProperty:{text:"S",faceRotation:0}}};function fB(t,e){e.set(t)}function J5e(t,e){return fB(uB[t],e)}function Z5e(t,e){uB[t]=e}var Q5e={applyDefinitions:fB,applyPreset:J5e,registerStylePreset:Z5e};const ewe={xPlus:0,xMinus:1,yPlus:2,yMinus:3,zPlus:4,zMinus:5};function twe(t,e){e.classHierarchy.push("vtkAnnotatedCubeActor"),e.xPlusFaceProperty={...e.xPlusFaceProperty},e.xMinusFaceProperty={...e.xMinusFaceProperty},e.yPlusFaceProperty={...e.yPlusFaceProperty},e.yMinusFaceProperty={...e.yMinusFaceProperty},e.zPlusFaceProperty={...e.zPlusFaceProperty},e.zMinusFaceProperty={...e.zMinusFaceProperty};let r=null;const n=document.createElement("canvas"),i=g1.newInstance(),o=Ace.newInstance();o.setInterpolate(!0);function a(c){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;l&&Object.assign(e[`${c}FaceProperty`],l);const f={...e.defaultStyle,...e[`${c}FaceProperty`]};n.width=f.resolution,n.height=f.resolution;const u=n.getContext("2d");u.fillStyle=f.faceColor,u.fillRect(0,0,n.width,n.height),f.edgeThickness>0&&(u.strokeStyle=f.edgeColor,u.lineWidth=f.edgeThickness*n.width,u.strokeRect(0,0,n.width,n.height)),u.save(),u.translate(0,n.height),u.scale(1,-1),u.translate(n.width/2,n.height/2),u.rotate(-Math.PI*(f.faceRotation/180));const d=f.fontSizeScale(f.resolution);u.fillStyle=f.fontColor,u.textAlign="center",u.textBaseline="middle",u.font=`${f.fontStyle} ${d}px "${f.fontFamily}"`,u.fillText(f.text,0,0),u.restore();const h=Y5e.canvasToImageData(n);o.setInputData(h,ewe[c]),t.modified()}function s(){r=xL.newInstance({generate3DTextureCoordinates:!0}),i.setInputConnection(r.getOutputPort()),a("xPlus"),a("xMinus"),a("yPlus"),a("yMinus"),a("zPlus"),a("zMinus")}t.setDefaultStyle=c=>{e.defaultStyle={...e.defaultStyle,...c},s()},t.setXPlusFaceProperty=c=>a("xPlus",c),t.setXMinusFaceProperty=c=>a("xMinus",c),t.setYPlusFaceProperty=c=>a("yPlus",c),t.setYMinusFaceProperty=c=>a("yMinus",c),t.setZPlusFaceProperty=c=>a("zPlus",c),t.setZMinusFaceProperty=c=>a("zMinus",c),s(),i.setInputConnection(r.getOutputPort()),t.setMapper(i),t.addTexture(o)}const nwe={defaultStyle:{text:"",faceColor:"white",faceRotation:0,fontFamily:"Arial",fontColor:"black",fontStyle:"normal",fontSizeScale:t=>t/1.8,edgeThickness:.1,edgeColor:"black",resolution:200}};function dB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,nwe,r),Qy.extend(t,e,r),ne.get(t,e,["defaultStyle","xPlusFaceProperty","xMinusFaceProperty","yPlusFaceProperty","yMinusFaceProperty","zPlusFaceProperty","zMinusFaceProperty"]),twe(t,e)}const rwe=ne.newInstance(dB,"vtkAnnotatedCubeActor");var pb={newInstance:rwe,extend:dB,Presets:Q5e};const{vtkErrorMacro:iwe}=ne;function owe(t,e){let r=0;return t.map((n,i)=>i===r?(r+=n+1,n):n+e)}function Km(t,e,r,n){t.set(owe(e,r),n)}function awe(t,e){e.classHierarchy.push("vtkAppendPolyData"),t.requestData=(r,n)=>{const i=t.getNumberOfInputPorts();if(!i){iwe("No input specified.");return}if(i===1){n[0]=r[0];return}const o=Xo.newInstance();let a=0,s=0,c=1,l=1,f=0,u=0,d=0,h=0,g=!0,p=!0,v=!0;for(let b=0;bc?s:c);const M=I.getPointData();M?(g=g&&M.getNormals()!==null,p=p&&M.getTCoords()!==null,v=v&&M.getScalars()!==null):(g=!1,p=!1,v=!1)}e.outputPointsPrecision===Cv.SINGLE?s=pn.FLOAT:e.outputPointsPrecision===Cv.DOUBLE&&(s=pn.DOUBLE);const y=Pv.newInstance({dataType:s});y.setNumberOfPoints(a);const m=y.getData(),w=new Uint32Array(f),x=new Uint32Array(u),C=new Uint32Array(d),S=new Uint32Array(h);let _=null,T=null,E=null;const D=r[i-1];if(g){const b=D.getPointData().getNormals();_=Yt.newInstance({numberOfComponents:3,numberOfTuples:a,size:3*a,dataType:b.getDataType(),name:b.getName()})}if(p){const b=D.getPointData().getTCoords();T=Yt.newInstance({numberOfComponents:2,numberOfTuples:a,size:2*a,dataType:b.getDataType(),name:b.getName()})}if(v){const b=D.getPointData().getScalars();E=Yt.newInstance({numberOfComponents:b.getNumberOfComponents(),numberOfTuples:a,size:a*b.getNumberOfComponents(),dataType:b.getDataType(),name:b.getName()})}a=0,f=0,u=0,d=0,h=0;for(let b=0;b2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,swe,r),ne.setGet(t,e,["outputPointsPrecision"]),ne.obj(t,e),ne.algo(t,e,1,1),awe(t,e)}const cwe=ne.newInstance(hB,"vtkAppendPolyData");var gB={newInstance:cwe,extend:hB};function lwe(t,e){e.classHierarchy.push("vtkConeSource");function r(n,i){if(e.deleted)return;let o=i[0];const a=2*Math.PI/e.resolution,s=-e.height/2,c=e.resolution+1,l=4*e.resolution+1+e.resolution;let f=0;const u=ne.newTypedArray(e.pointType,c*3);let d=0;const h=new Uint32Array(l);u[0]=e.height/2,u[1]=0,u[2]=0,e.capping&&(h[d++]=e.resolution);for(let g=0;ge.resolution?1:g+2;ji.buildFromRadian().translate(...e.center).rotateFromDirections([1,0,0],e.direction).apply(u),o=Xo.newInstance(),o.getPoints().setData(u,3),o.getPolys().setData(h,1),i[0]=o}t.requestData=r}const uwe={height:1,radius:.5,resolution:6,center:[0,0,0],direction:[1,0,0],capping:!0,pointType:"Float64Array"};function pB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,uwe,r),ne.obj(t,e),ne.setGet(t,e,["height","radius","resolution","capping"]),ne.setGetArray(t,e,["center","direction"],3),ne.algo(t,e,0,1),lwe(t,e)}const fwe=ne.newInstance(pB,"vtkConeSource");var dwe={newInstance:fwe,extend:pB};function hwe(t,e){e.classHierarchy.push("vtkCylinderSource");function r(n,i){if(e.deleted)return;let o=i[0];const a=2*Math.PI/e.resolution;let s=2*e.resolution,c=5*e.resolution;e.capping&&(s=4*e.resolution,c=7*e.resolution+2);const l=ne.newTypedArray(e.pointType,s*3);let f=0;const u=new Uint32Array(c),d=new Float32Array(s*3),h=Yt.newInstance({numberOfComponents:3,values:d,name:"Normals"}),g=new Float32Array(s*2),p=Yt.newInstance({numberOfComponents:2,values:g,name:"TCoords"}),v=[0,0,0],y=[0,0,0],m=[0,0,0],w=[0,0,0],x=[0,0],C=[0,0],S=e.otherRadius==null?e.radius:e.otherRadius;for(let _=0;__*-1)).apply(l),o=Xo.newInstance(),o.getPoints().setData(l,3),o.getPolys().setData(u,1),o.getPointData().setNormals(h),o.getPointData().setTCoords(p),i[0]=o}t.requestData=r}const gwe={height:1,initAngle:0,radius:1,resolution:6,center:[0,0,0],direction:[0,1,0],capping:!0,pointType:"Float64Array"};function mB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,gwe,r),ne.obj(t,e),ne.setGet(t,e,["height","initAngle","otherRadius","radius","resolution","capping"]),ne.setGetArray(t,e,["center","direction"],3),ne.algo(t,e,0,1),hwe(t,e)}const pwe=ne.newInstance(mB,"vtkCylinderSource");var mwe={newInstance:pwe,extend:mB};function vwe(t,e){e.classHierarchy.push("vtkArrowSource");function r(n,i){if(e.deleted)return;const o=mwe.newInstance({capping:!0});o.setResolution(e.shaftResolution),o.setRadius(e.shaftRadius),o.setHeight(1-e.tipLength),o.setCenter(0,(1-e.tipLength)*.5,0);const a=o.getOutputData(),s=a.getPoints().getData(),c=a.getPointData().getNormals().getData();ji.buildFromDegree().rotateZ(-90).apply(s).apply(c);const l=dwe.newInstance();l.setResolution(e.tipResolution),l.setHeight(e.tipLength),l.setRadius(e.tipRadius);const f=l.getOutputData(),u=f.getPoints().getData();ji.buildFromRadian().translate(1-e.tipLength*.5,0,0).apply(u);const d=gB.newInstance();d.setInputData(a),d.addInputData(f);const h=d.getOutputData(),g=h.getPoints().getData();ji.buildFromRadian().translate(-.5+e.tipLength*.5,0,0).apply(g),e.invert?(ji.buildFromRadian().rotateFromDirections([1,0,0],e.direction).scale(-1,-1,-1).apply(g),i[0]=h):(ji.buildFromRadian().rotateFromDirections([1,0,0],e.direction).scale(1,1,1).apply(g),i[0]=d.getOutputData())}t.requestData=r}const ywe={tipResolution:6,tipRadius:.1,tipLength:.35,shaftResolution:6,shaftRadius:.03,invert:!1,direction:[1,0,0],pointType:"Float64Array"};function vB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,ywe,r),ne.obj(t,e),ne.setGet(t,e,["tipResolution","tipRadius","tipLength","shaftResolution","shaftRadius","invert"]),ne.setGetArray(t,e,["direction"],3),ne.algo(t,e,0,1),vwe(t,e)}const wwe=ne.newInstance(vB,"vtkArrowSource");var _3={newInstance:wwe,extend:vB};function T3(t){const e=t.getPoints().getBounds(),r=[-(e[0]+e[1])*.5,-(e[2]+e[3])*.5,-(e[4]+e[5])*.5];ji.buildFromDegree().translate(...r).apply(t.getPoints().getData())}function E3(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=t.getPoints().getBounds(),i=[0,0,0];r?i[e]=-n[e*2+1]:i[e]=-n[e*2],ji.buildFromDegree().translate(...i).apply(t.getPoints().getData())}function D3(t,e,r,n){const i=t.getPoints().getData().length,o=new Uint8ClampedArray(i);let a=0;for(;a{let i={...e.config,...e.xConfig};const o=_3.newInstance({direction:[1,0,0],...i}).getOutputData();e.config.recenter?T3(o):E3(o,0,i.invert),D3(o,...i.color),i={...e.config,...e.yConfig};const a=_3.newInstance({direction:[0,1,0],...i}).getOutputData();e.config.recenter?T3(a):E3(a,1,i.invert),D3(a,...i.color),i={...e.config,...e.zConfig};const s=_3.newInstance({direction:[0,0,1],...i}).getOutputData();e.config.recenter?T3(s):E3(s,2,i.invert),D3(s,...i.color);const c=gB.newInstance();c.setInputData(o),c.addInputData(a),c.addInputData(s),r.setInputConnection(c.getOutputPort())},t.update();const n=ne.debounce(t.update,0);t.setXAxisColor=i=>t.setXConfig({...t.getXConfig(),color:i}),t.setYAxisColor=i=>t.setYConfig({...t.getYConfig(),color:i}),t.setZAxisColor=i=>t.setZConfig({...t.getZConfig(),color:i}),t.getXAxisColor=()=>e.getXConfig().color,t.getYAxisColor=()=>e.getYConfig().color,t.getZAxisColor=()=>e.getZConfig().color,e._onConfigChanged=n,e._onXConfigChanged=n,e._onYConfigChanged=n,e._onZConfigChanged=n}function Cwe(t){return{config:{recenter:!0,tipResolution:60,tipRadius:.1,tipLength:.2,shaftResolution:60,shaftRadius:.03,invert:!1,...t==null?void 0:t.config},xConfig:{color:[255,0,0],invert:!1,...t==null?void 0:t.xConfig},yConfig:{color:[255,255,0],invert:!1,...t==null?void 0:t.yConfig},zConfig:{color:[0,128,0],invert:!1,...t==null?void 0:t.zConfig}}}function yB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Qy.extend(t,e,Cwe(r)),ne.setGet(t,e,["config","xConfig","yConfig","zConfig"]),xwe(t,e)}const Swe=ne.newInstance(yB,"vtkAxesActor");var _we={newInstance:Swe,extend:yB},wy;(function(t){t[t.ANNOTATED_CUBE=1]="ANNOTATED_CUBE",t[t.AXES=2]="AXES",t[t.CUSTOM=3]="CUSTOM"})(wy||(wy={}));const ks=class ks extends ai{constructor(e={},r={configuration:{orientationWidget:{enabled:!0,viewportCorner:gb.Corners.BOTTOM_RIGHT,viewportSize:.15,minPixelSize:100,maxPixelSize:300},overlayMarkerType:ks.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE,overlayConfiguration:{[ks.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE]:{faceProperties:{xPlus:{text:"L",faceColor:"#ffff00",faceRotation:90},xMinus:{text:"R",faceColor:"#ffff00",faceRotation:270},yPlus:{text:"P",faceColor:"#00ffff",fontColor:"white",faceRotation:180},yMinus:{text:"A",faceColor:"#00ffff",fontColor:"white"},zPlus:{text:"S"},zMinus:{text:"I"}},defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:n=>n/2,faceColor:"#0000ff",edgeThickness:.1,edgeColor:"black",resolution:400}},[ks.OVERLAY_MARKER_TYPES.AXES]:{},[ks.OVERLAY_MARKER_TYPES.CUSTOM]:{polyDataURL:"https://raw.githubusercontent.com/Slicer/Slicer/80ad0a04dacf134754459557bf2638c63f3d1d1b/Base/Logic/Resources/OrientationMarkers/Human.vtp"}}}}){super(e,r),this._resizeObservers=new Map,this.onSetToolEnabled=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolActive=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolDisabled=()=>{this.cleanUpData(),this._unsubscribeToViewportNewVolumeSet()},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.resize=n=>{const i=this.orientationMarkers[n];if(!i)return;const{orientationWidget:o}=i;o.updateViewport()},this.orientationMarkers={},this.updatingOrientationMarker={}}_unsubscribeToViewportNewVolumeSet(){const e=()=>{this._getViewportsInfo().forEach(({viewportId:n,renderingEngineId:i})=>{const{viewport:o}=Ti(n,i),{element:a}=o;a.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this)),this._resizeObservers.get(n).unobserve(a)})};Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,r=>{r.detail.toolGroupId===this.toolGroupId&&(e(),this.initViewports())})}_subscribeToViewportEvents(){const e=()=>{this._getViewportsInfo().forEach(({viewportId:n,renderingEngineId:i})=>{const{viewport:o}=Ti(n,i),{element:a}=o;this.initViewports(),a.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this));const s=new ResizeObserver(()=>{setTimeout(()=>{const c=Ti(n,i);if(!c)return;const{viewport:l}=c;this.resize(n),l.render()},100)});s.observe(a),this._resizeObservers.set(n,s)})};e(),Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,r=>{r.detail.toolGroupId===this.toolGroupId&&(e(),this.initViewports())})}cleanUpData(){Qo()[0].getViewports().forEach(i=>{const o=this.orientationMarkers[i.id];if(!o)return;const{actor:a,orientationWidget:s}=o;s==null||s.setEnabled(!1),s==null||s.delete(),a==null||a.delete(),i.getRenderingEngine().offscreenMultiRenderWindow.getRenderWindow().render(),i.getRenderingEngine().render(),delete this.orientationMarkers[i.id]})}initViewports(){const r=Qo()[0];if(!r)return;let n=r.getViewports();n=b5(n,this.getToolName()),n.forEach(i=>{const o=i.getWidget(this.getToolName());(!o||o.isDeleted())&&this.addAxisActorInViewport(i)})}async addAxisActorInViewport(e){const r=e.id;if(!this.updatingOrientationMarker[r]){this.updatingOrientationMarker[r]=!0;const n=this.configuration.overlayMarkerType,i=this.configuration.overlayConfiguration[n];if(this.orientationMarkers[r]){const{actor:g,orientationWidget:p}=this.orientationMarkers[r];e.getRenderer().removeActor(g),p.setEnabled(!1)}let o;n===1?o=this.createAnnotationCube(i):n===2?o=_we.newInstance():n===3&&(o=await this.createCustomActor());const a=e.getRenderer(),s=e.getRenderingEngine().offscreenMultiRenderWindow.getRenderWindow(),{enabled:c,viewportCorner:l,viewportSize:f,minPixelSize:u,maxPixelSize:d}=this.configuration.orientationWidget,h=gb.newInstance({actor:o,interactor:s.getInteractor(),parentRenderer:a});h.setEnabled(c),h.setViewportCorner(l),h.setViewportSize(f),h.setMinPixelSize(u),h.setMaxPixelSize(d),h.updateMarkerOrientation(),this.orientationMarkers[r]={orientationWidget:h,actor:o},e.addWidget(this.getToolName(),h),s.render(),e.getRenderingEngine().render(),this.updatingOrientationMarker[r]=!1}}async createCustomActor(){const e=this.configuration.overlayConfiguration[wy.CUSTOM].polyDataURL,n=await(await fetch(e)).arrayBuffer(),i=Lse.newInstance();i.parseAsArrayBuffer(n),i.update();const o=Xo.newInstance();o.shallowCopy(i.getOutputData()),o.getPointData().setActiveScalars("Color");const a=g1.newInstance();a.setInputData(o),a.setColorModeToDirectScalars();const s=Qy.newInstance();return s.setMapper(a),s.rotateZ(180),s}createAnnotationCube(e){const r=pb.newInstance();return r.setDefaultStyle({...e.defaultStyle}),r.setXPlusFaceProperty({...e.faceProperties.xPlus}),r.setXMinusFaceProperty({...e.faceProperties.xMinus}),r.setYPlusFaceProperty({...e.faceProperties.yPlus}),r.setYMinusFaceProperty({...e.faceProperties.yMinus}),r.setZPlusFaceProperty({...e.faceProperties.zPlus}),r.setZMinusFaceProperty({...e.faceProperties.zMinus}),r}async createAnnotatedCubeActor(){const e=pb.newInstance(),{faceProperties:r,defaultStyle:n}=this.configuration.annotatedCube;return e.setDefaultStyle(n),Object.keys(r).forEach(i=>{const o=`set${i.charAt(0).toUpperCase()+i.slice(1)}FaceProperty`;e[o](r[i])}),e}};ks.CUBE=1,ks.AXIS=2,ks.VTPFILE=3,ks.OVERLAY_MARKER_TYPES=wy;let xy=ks;xy.toolName="OrientationMarker";const op=class op extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{hoverTimeout:100,mode:op.SelectMode.Border,searchRadius:6}}){super(e,r),this.mouseMoveCallback=n=>{if(this.mode===An.Active)return this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setActiveSegment(n),this.hoverTimer=null},this.configuration.hoverTimeout),!0},this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.hoverTimer=null}_setActiveSegment(e={}){if(Ge.isInteractingWithTool)return;const{element:r,currentPoints:n}=e.detail,i=n.world,o=Ce(r);if(!o)return;const{viewport:a}=o,s=ol(a.id);s&&this._setActiveSegmentForType(s,i,a)}_setActiveSegmentForType(e,r,n){if(!n.getImageData())return;const{segmentationId:o,representationData:a}=e;let s;if(this.configuration.mode===op.SelectMode.Inside?s=H4(o,r,{viewport:n}):a.Labelmap?s=tU(o,r,{viewport:n,searchRadius:this.configuration.searchRadius}):a.Contour?s=rU(o):a.Surface,!s||s===0)return;dy(o,s);const l=n.getRenderingEngine().getViewports().map(f=>f.id);Ta(o),Pe(l)}};op.SelectMode={Inside:"Inside",Border:"Border"};let Cy=op;Cy.toolName="SegmentSelectTool";const s0=class s0 extends Hp{constructor(e={}){super(e),this.renderAnnotation=(r,n)=>{let i=!0;const{viewport:o}=r,{element:a}=o,s=o.id;let c=un(this.getToolName(),a);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(a,c),!(c!=null&&c.length)))return i;const l=this.getTargetId(o),f=o.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:r.viewport.id};for(let d=0;do.worldToCanvas(ce));u.annotationUID=g;const{segmentIndex:w,segmentationId:x}=h.metadata,{lineWidth:C,lineDash:S,shadow:_}=this.getAnnotationStyle({annotation:h,styleSpecifier:u}),E=`rgb(${el(s,x,w).slice(0,3).join(",")})`;if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(h,f,r)):h.invalidated&&this._throttledCalculateCachedStats(h,f,r),!o.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),i;let D;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(D=[m[y]]),D&&ir(n,g,"0",D,{color:E});const b=`${g}-line-1`,I=`${g}-line-2`;vn(n,g,"0",m[0],m[1],{color:E,lineWidth:C,lineDash:S,shadow:_},b),vn(n,g,"1",m[2],m[3],{color:E,lineWidth:C,lineDash:S,shadow:_},I),i=!0;const L=this.getLinkedTextBoxStyle(u,h);if(!L.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}L.color=E;const V=this.configuration.getTextLines(p,l);if(!V||V.length===0)continue;let G;p.handles.textBox.hasMoved||(G=na(m),p.handles.textBox.worldPosition=o.canvasToWorld(G));const A=o.worldToCanvas(p.handles.textBox.worldPosition),F=qi(n,g,"1",V,A,m,{},L),{x:j,y:Y,width:re,height:ue}=F;p.handles.textBox.worldBoundingBox={topLeft:o.canvasToWorld([j,Y]),topRight:o.canvasToWorld([j+re,Y]),bottomLeft:o.canvasToWorld([j,Y+ue]),bottomRight:o.canvasToWorld([j+re,Y+ue])}}return i}}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,o=n.world,a=Ce(i),{viewport:s}=a;this.isDrawing=!0;const c=s.getCamera(),{viewPlaneNormal:l,viewUp:f}=c,u=this.getReferencedImageId(s,o,l,f),d=s.getFrameOfReferenceUID(),h={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...f],FrameOfReferenceUID:d,referencedImageId:u,...s.getViewReference({points:[o]})},data:{handles:{points:[[...o],[...o],[...o],[...o]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};nn(h,i);const g=_t(i,this.getToolName());return this.editData={annotation:h,viewportIdsToRender:g,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(i),Ot(i),e.preventDefault(),Pe(g),h}};s0.toolName="SegmentBidirectional",s0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{viewport:o}=i,c=S1().filter(_=>_.metadata.toolName==="SegmentBidirectional").find(_=>{const{metadata:T}=_;return T.segmentIndex===(n==null?void 0:n.segmentIndex)&&T.segmentationId===(n==null?void 0:n.segmentationId)});c&&gn(c.annotationUID);const{FrameOfReferenceUID:l,referencedImageId:f,viewPlaneNormal:u,instance:d}=s0.hydrateBase(s0,i,r[0],n),[h,g]=r,[p,v]=h,[y,m]=g,w=[p,v,y,m],{toolInstance:x,...C}=n||{},S={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:w,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{segmentIndex:n==null?void 0:n.segmentIndex,segmentationId:n==null?void 0:n.segmentationId,toolName:d.getToolName(),viewPlaneNormal:u,FrameOfReferenceUID:l,referencedImageId:f,...C}};return nn(S,o.element),Pe([o.id]),S};let tS=s0;class wB extends ai{constructor(e={data:{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{hoverTimeout:100,searchRadius:6}}){super(e,r),this.mouseMoveCallback=n=>(this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setHoveredSegment(n),this.hoverTimer=null},this.configuration.hoverTimeout),!0),this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.data=e.data??{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}},this.hoverTimer=null}_setHoveredSegment(e={}){if(Ge.isInteractingWithTool)return;const{element:r,currentPoints:n}=e.detail,i=n.world,o=Ce(r);if(!o)return;const{viewport:a}=o,s=ol(a.id);s&&this._setHoveredSegmentForType(s,i,a)}_setHoveredSegmentForType(e,r,n){if(!n.getImageData())return;const{segmentationId:o}=e,a=H4(o,r,{viewport:n}),s=e.segments[a],c=s==null?void 0:s.label,l=n.worldToCanvas(r);if(this._editData={hoveredSegmentIndex:a,hoveredSegmentLabel:c,canvasCoordinates:l,worldPoint:r},!a||a===0)return;const u=n.getRenderingEngine().getViewports().map(d=>d.id);Ta(o),Pe(u)}renderAnnotation(e,r){if(!this._editData)return;const{viewport:n}=e,{hoveredSegmentIndex:i,hoveredSegmentLabel:o,canvasCoordinates:a,worldPoint:s}=this._editData;if(!i)return;const c=n.worldToCanvas(s),l=qi(r,"segmentSelectLabelAnnotation","segmentSelectLabelTextBox",[o||"(unnamed segment)"],c,[a],{},{}),f=a[0],u=a[1],{width:d,height:h}=l;this.data.handles.textBox.worldBoundingBox={topLeft:n.canvasToWorld([f,u]),topRight:n.canvasToWorld([f+d,u]),bottomLeft:n.canvasToWorld([f,u+h]),bottomRight:n.canvasToWorld([f+d,u+h])}}}wB.toolName="SegmentLabelTool";const fo=class fo extends ic{constructor(e={}){const r=Ei({configuration:{calculateStats:!1,allowOpenContours:!1}},e);super(r),this.onViewportAddedToToolGroupBinded=this.onViewportAddedToToolGroup.bind(this),this.onSegmentationModifiedBinded=this.onSegmentationModified.bind(this)}initializeListeners(){fo.annotationsToViewportMap.clear(),fo.viewportIdsChecked=[],Ke.addEventListener(N.ANNOTATION_MODIFIED,this.annotationModified),Ke.addEventListener(N.ANNOTATION_COMPLETED,this.annotationCompleted),Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroupBinded),Ke.addEventListener(N.SEGMENTATION_MODIFIED,this.onSegmentationModifiedBinded)}cleanUpListeners(){fo.annotationsToViewportMap.clear(),fo.viewportIdsChecked=[],Ke.removeEventListener(N.ANNOTATION_MODIFIED,this.annotationModified),Ke.removeEventListener(N.ANNOTATION_COMPLETED,this.annotationCompleted),Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroup.bind(this)),Ke.removeEventListener(N.SEGMENTATION_MODIFIED,this.onSegmentationModified.bind(this))}async checkContourSegmentation(e){if(fo.viewportIdsChecked.includes(e))return;const r=ed(e);if(!r)return console.log("No active segmentation detected"),!1;const n=r.segmentationId;return r.representationData.Contour?fo.viewportIdsChecked.push(e):(fo.viewportIdsChecked.push(e),await K4(e,[{segmentationId:n,type:Dt.Contour}]),n4({segmentationId:n,type:Dt.Contour,data:{}})),!0}onViewportAddedToToolGroup(e){const{toolGroupId:r,viewportId:n}=e.detail;r===this.toolGroupId&&this.checkContourSegmentation(n)}onSegmentationModified(e){const{segmentationId:r}=e.detail||{};if(!r)return;const n=sk(r);n&&n.forEach(async({viewportId:i})=>await this.checkContourSegmentation(i))}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.cleanUpListeners()}annotationModified(e){var a;const{annotation:r,renderingEngineId:n,viewportId:i}=e.detail,o=(a=Jr(n))==null?void 0:a.getViewport(i);o&&fo.annotationsToViewportMap.set(r.annotationUID,o)}annotationCompleted(e){var i,o;const{annotation:r}=e.detail,{polyline:n}=((i=r.data)==null?void 0:i.contour)||{};if(((o=r==null?void 0:r.metadata)==null?void 0:o.toolName)===fo.toolName&&n&&fo.annotationsToViewportMap.has(r.annotationUID)){const a=fo.annotationsToViewportMap.get(r.annotationUID);n.length>3&&z5.viewportContoursToLabelmap(a)}}};fo.toolName="LabelMapEditWithContour",fo.annotationsToViewportMap=new Map,fo.viewportIdsChecked=[];let nS=fo;const AE=class AE extends ar{constructor(e={}){super(e,{supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1}}),this.addNewAnnotation=r=>{const n=r.detail,{currentPoints:i,element:o}=n,a=i.world,s=Ce(o),{viewport:c}=s;this.isDrawing=!0;const l=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...a],[...a],[...a],[...a]]}}});nn(l,o);const f=_t(o,this.getToolName(),!1);return this.editData={annotation:l,viewportUIDsToRender:f,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(o),Ot(o),r.preventDefault(),Pe(f),l},this.getHandleNearImagePoint=(r,n,i,o)=>{const a=Ce(r),{viewport:s}=a,{data:c}=n,{points:l}=c.handles;for(let f=0;f{const a=Ce(r),{viewport:s}=a,{data:c}=n,{points:l}=c.handles,f=s.worldToCanvas(l[0]),u=s.worldToCanvas(l[3]),d=this._getRectangleImageCoordinates([f,u]),h=[i[0],i[1]],{left:g,top:p,width:v,height:y}=d;if(y4([g,p,v,y],h)<=o)return!0},this.toolSelectedCallback=(r,n,i="mouse")=>{const o=r.detail,{element:a}=o,{data:s}=n;s.active=!0;const c=_t(a,this.getToolName(),!1);this.editData={annotation:n,viewportUIDsToRender:c},this._activateModify(a),Ot(a),Pe(c),r.preventDefault()},this.handleSelectedCallback=(r,n,i,o="mouse")=>{const a=r.detail,{element:s}=a,{data:c}=n;c.active=!0;let l;i.worldPosition||(l=c.handles.points.findIndex(u=>u===i));const f=_t(s,this.getToolName(),!1);this.editData={annotation:n,viewportUIDsToRender:f,handleIndex:l},this._activateModify(s),Ot(s),Pe(f),r.preventDefault()},this._endCallback=r=>{const n=r.detail,{element:i}=n,{annotation:o,viewportUIDsToRender:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=o;s&&!c||(this.doneEditMemo(),l.active=!1,l.handles.activeHandleIndex=null,this._deactivateModify(i),this._deactivateDraw(i),zt(i),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(o.annotationUID),Pe(a))},this._dragCallback=r=>{this.isDrawing=!0;const n=r.detail,{element:i}=n,{annotation:o,viewportUIDsToRender:a,handleIndex:s,newAnnotation:c}=this.editData;this.createMemo(i,o,{newAnnotation:c});const{data:l}=o;if(s===void 0){const{deltaPoints:f}=n,u=f.world,{points:d}=l.handles;d.forEach(h=>{h[0]+=u[0],h[1]+=u[1],h[2]+=u[2]}),l.invalidated=!0}else{const{currentPoints:f}=n,u=Ce(i),{worldToCanvas:d,canvasToWorld:h}=u.viewport,g=f.world,{points:p}=l.handles;p[s]=[...g];let v,y,m,w,x,C,S,_;switch(s){case 0:case 3:v=d(p[0]),w=d(p[3]),y=[w[0],v[1]],m=[v[0],w[1]],C=h(y),S=h(m),p[1]=C,p[2]=S;break;case 1:case 2:y=d(p[1]),m=d(p[2]),v=[m[0],y[1]],w=[y[0],m[1]],x=h(v),_=h(w),p[0]=x,p[3]=_;break}l.invalidated=!0}this.editData.hasMoved=!0,Ce(i),Pe(a)},this._activateDraw=r=>{Ge.isInteractingWithTool=!0,r.addEventListener(N.MOUSE_UP,this._endCallback),r.addEventListener(N.MOUSE_DRAG,this._dragCallback),r.addEventListener(N.MOUSE_MOVE,this._dragCallback),r.addEventListener(N.MOUSE_CLICK,this._endCallback),r.addEventListener(N.TOUCH_END,this._endCallback),r.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=r=>{Ge.isInteractingWithTool=!1,r.removeEventListener(N.MOUSE_UP,this._endCallback),r.removeEventListener(N.MOUSE_DRAG,this._dragCallback),r.removeEventListener(N.MOUSE_MOVE,this._dragCallback),r.removeEventListener(N.MOUSE_CLICK,this._endCallback),r.removeEventListener(N.TOUCH_END,this._endCallback),r.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateModify=r=>{Ge.isInteractingWithTool=!0,r.addEventListener(N.MOUSE_UP,this._endCallback),r.addEventListener(N.MOUSE_DRAG,this._dragCallback),r.addEventListener(N.MOUSE_CLICK,this._endCallback),r.addEventListener(N.TOUCH_END,this._endCallback),r.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=r=>{Ge.isInteractingWithTool=!1,r.removeEventListener(N.MOUSE_UP,this._endCallback),r.removeEventListener(N.MOUSE_DRAG,this._dragCallback),r.removeEventListener(N.MOUSE_CLICK,this._endCallback),r.removeEventListener(N.TOUCH_END,this._endCallback),r.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(r,n)=>{const{viewport:o}=r,{element:a}=o;let s=un(this.getToolName(),a);if(!(s!=null&&s.length)||(s=this.filterInteractableAnnotationsForElement(a,s),!(s!=null&&s.length)))return!1;const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:r.viewport.id};for(let l=0;lo.worldToCanvas(C)),v=this.getStyle("lineWidth",c,f),y=this.getStyle("lineDash",c,f),m=this.getStyle("color",c,f);if(!o.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}let w;!this.editData&&g!==null&&(w=[p[g]]),w&&ir(n,u,"0",w,{color:m}),Wk(n,u,"0",p[0],p[3],{color:"black",lineDash:y,lineWidth:v})}},this._getRectangleImageCoordinates=r=>{const[n,i]=r;return{left:Math.min(n[0],i[0]),top:Math.min(n[1],i[1]),width:Math.abs(n[0]-i[0]),height:Math.abs(n[1]-i[1])}},this._calculateCachedStats=(r,n,i,o,a)=>{const{data:s}=r,{viewportUID:c,renderingEngineUID:l,sceneUID:f}=a,u=s.handles.points[0],d=s.handles.points[3],{cachedStats:h}=s,g=Object.keys(h);for(let v=0;vsr(r,i)&&sr(n,i),this._getTargetVolumeUID=r=>{if(this.configuration.volumeUID)return this.configuration.volumeUID;const n=r.getVolumeActors();if(!(!n&&!n.length))return n[0].uid},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}cancel(e){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),zt(e);const{annotation:r,viewportUIDsToRender:n}=this.editData,{data:i}=r;return i.active=!1,i.handles.activeHandleIndex=null,Pe(n),this.editData=null,r.metadata.annotationUID}_getImageVolumeFromTargetUID(e,r){let n,i;if(e.startsWith("stackTarget")){const o=e.indexOf(":"),a=e.substring(o+1);n=r.getViewport(a).getImageData()}else n=Le.getVolume(e);return{imageVolume:n,viewport:i}}_getTargetStackUID(e){return`stackTarget:${e.uid}`}};AE.toolName="VideoRedaction";let rS=AE;const Twe=Object.freeze(Object.defineProperty({__proto__:null,AdvancedMagnifyTool:Zp,AngleTool:HC,AnnotationDisplayTool:Fu,AnnotationTool:ar,ArrowAnnotateTool:Ou,BaseTool:ai,BidirectionalTool:Hp,BrushTool:z5,CONSTANTS:e1e,CircleROIStartEndThresholdTool:aB,CircleROITool:gy,CircleScissorsTool:iB,CobbAngleTool:KC,CrosshairsTool:Fs,DragProbeTool:WC,ETDRSGridTool:zC,EllipticalROITool:od,Enums:nN,EraserTool:tB,HeightTool:GC,KeyImageTool:ZC,LabelMapEditWithContourTool:nS,LabelTool:hy,LabelmapBaseTool:rd,LengthTool:Iu,LivewireContourSegmentationTool:jC,LivewireContourTool:vy,MIPJumpToClickTool:jU,MagnifyTool:HU,OrientationMarkerTool:xy,OverlayGridTool:KU,PaintFillTool:sB,PanTool:j0,PlanarFreehandContourSegmentationTool:ic,PlanarFreehandROITool:bu,PlanarRotateTool:K0,ProbeTool:nl,RectangleROIStartEndThresholdTool:W4,RectangleROIThresholdTool:z4,RectangleROITool:tl,RectangleScissorsTool:rB,ReferenceCursors:ua,ReferenceLinesTool:Gf,RegionSegmentPlusTool:eS,RegionSegmentTool:QC,ScaleOverlayTool:JU,SculptorTool:X0,SegmentBidirectionalTool:tS,SegmentLabelTool:wB,SegmentSelectTool:Cy,SegmentationIntersectionTool:qU,SphereScissorsTool:oB,SplineContourSegmentationTool:$C,SplineROITool:py,StackScrollTool:id,Synchronizer:F4,SynchronizerManager:rF,ToolGroupManager:vN,TrackballRotateTool:zU,Types:Dye,UltrasoundDirectionalTool:qC,UltrasoundPleuraBLineTool:JC,VideoRedactionTool:rS,VolumeRotateTool:QU,WholeBodySegmentTool:nB,WindowLevelRegionTool:$U,WindowLevelTool:H0,ZoomTool:q0,addTool:Ci,annotation:nge,cancelActiveManipulations:nF,cursors:eue,destroy:Jpe,drawing:Ede,init:iF,removeTool:TN,segmentation:Hye,splines:Jye,get state(){return Ge},store:Ype,synchronizers:C1e,utilities:Eye,version:t1e},Symbol.toStringTag,{value:"Module"}));function xB(t,e,r){if(t===void 0)throw new Error("decodeRGB: rgbBuffer must be defined");if(t.length%3!==0)throw new Error(`decodeRGB: rgbBuffer length ${t.length} must be divisible by 3`);const n=t.length/3;let i=0,o=0;if(r){for(let a=0;a>e;return n}function I3(t,e,r){const n=t[`${e}PaletteColorLookupTableData`];if(n)return Promise.resolve(n);const i=mt("imagePixelModule",t.imageId);return i&&typeof i.then=="function"?i.then(o=>o?o[`${e}PaletteColorLookupTableData`]:r):Promise.resolve(i?i[`${e}PaletteColorLookupTableData`]:r)}function TB(t,e,r){const n=t.columns*t.rows,i=t.pixelData;Promise.all([I3(t,"red",null),I3(t,"green",null),I3(t,"blue",null)]).then(([o,a,s])=>{if(!o||!a||!s)throw new Error("The image does not have a complete color palette. R, G, and B palette data are required.");const c=o.length;let l=0,f=0;const u=t.redPaletteColorLookupTableDescriptor[1],d=t.redPaletteColorLookupTableDescriptor[2]===8?0:8,h=b3(o,d),g=b3(a,d),p=b3(s,d);if(r){for(let v=0;vu+c-1?y=c-1:y-=u,e[f++]=h[y],e[f++]=g[y],e[f++]=p[y],e[f++]=255}return}for(let v=0;vu+c-1?y=c-1:y-=u,e[f++]=h[y],e[f++]=g[y],e[f++]=p[y]}})}function O3(t,e){if(!(!t.elements[e]||t.elements[e].length!==6))return[t.uint16(e,0),t.uint16(e,1),t.uint16(e,2)]}function M3(t,e,r){const n=[],i=t.elements[e];for(let o=0;o0?0:t.uint16("x00280103")}function _s(t,e,r){const n=[],i=t.string(e);if(!i)return;const o=i.split("\\");if(!(r&&o.lengthie.byteArray.length-ie.position&&(wt=ie.byteArray.length-ie.position),ae.fragments.push({offset:ie.position-oe-8,position:ie.position,length:wt}),ie.seek(wt),void(ae.length=ie.position-ae.dataOffset);ae.fragments.push({offset:ie.position-oe-8,position:ie.position,length:wt}),ie.seek(wt)}we&&we.push("pixel data element ".concat(ae.tag," missing sequence delimiter tag xfffee0dd"))}function _(ie,ae){if(ie===void 0)throw"dicomParser.findAndSetUNElementLength: missing required parameter 'byteStream'";for(var we=ie.byteArray.length-8;ie.position<=we;)if(ie.readUint16()===65534){var se=ie.readUint16();if(se===57565)return ie.readUint32()!==0&&ie.warnings("encountered non zero length following item delimiter at position ".concat(ie.position-4," while reading element of undefined length with tag ").concat(ae.tag)),void(ae.length=ie.position-ae.dataOffset)}ae.length=ie.byteArray.length-ae.dataOffset,ie.seek(ie.byteArray.length-ie.position)}function T(ie,ae,we){if(we<0)throw"dicomParser.readFixedString - length cannot be less than 0";if(ae+we>ie.length)throw"dicomParser.readFixedString: attempt to read past end of buffer";for(var se,ge="",Fe=0;Feae.byteArray.length)throw"dicomParser.parseDicomDataSetExplicit: invalid value for parameter 'maxP osition'";for(var ge=ie.elements;ae.positionwe)throw"dicomParser:parseDicomDataSetExplicit: buffer overrun"}function re(ie,ae,we){var se=3ae.byteArray.length)throw"dicomParser.parseDicomDataSetImplicit: invalid value for parameter 'maxPosition'";for(var ge=ie.elements;ae.positionie.length)throw"bigEndianByteArrayParser.readUint16: attempt to read past end of buffer";return(ie[ae]<<8)+ie[ae+1]},readInt16:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readInt16: position cannot be less than 0";if(ae+2>ie.length)throw"bigEndianByteArrayParser.readInt16: attempt to read past end of buffer";return ae=(ie[ae]<<8)+ie[ae+1],ae=32768&ae?ae-65535-1:ae},readUint32:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readUint32: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readUint32: attempt to read past end of buffer";return 256*(256*(256*ie[ae]+ie[ae+1])+ie[ae+2])+ie[ae+3]},readInt32:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readInt32: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readInt32: attempt to read past end of buffer";return(ie[ae]<<24)+(ie[ae+1]<<16)+(ie[ae+2]<<8)+ie[ae+3]},readFloat:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readFloat: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readFloat: attempt to read past end of buffer";var we=new Uint8Array(4);return we[3]=ie[ae],we[2]=ie[ae+1],we[1]=ie[ae+2],we[0]=ie[ae+3],new Float32Array(we.buffer)[0]},readDouble:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readDouble: position cannot be less than 0";if(ae+8>ie.length)throw"bigEndianByteArrayParser.readDouble: attempt to read past end of buffer";var we=new Uint8Array(8);return we[7]=ie[ae],we[6]=ie[ae+1],we[5]=ie[ae+2],we[4]=ie[ae+3],we[3]=ie[ae+4],we[2]=ie[ae+5],we[1]=ie[ae+6],we[0]=ie[ae+7],new Float64Array(we.buffer)[0]}};function Ee(ie,ae,we){if(typeof Buffer<"u"&&ie instanceof Buffer)return ie.slice(ae,ae+we);if(ie instanceof Uint8Array)return new Uint8Array(ie.buffer,ie.byteOffset+ae,we);throw"dicomParser.from: unknown type for byteArray"}function Oe(ie,ae){for(var we=0;we"u"||!(ge instanceof Buffer)))throw"dicomParser.ByteStream: parameter byteArray is not of type Uint8Array or Buffer";if(Fe<0)throw"dicomParser.ByteStream: parameter 'position' cannot be less than 0";if(Fe>=ge.length)throw"dicomParser.ByteStream: parameter 'position' cannot be greater than or equal to 'byteArray' length";this.byteArrayParser=se,this.byteArray=ge,this.position=Fe||0,this.warnings=[]}var ae,we;return ae=ie,(we=[{key:"seek",value:function(se){if(this.position+se<0)throw"dicomParser.ByteStream.prototype.seek: cannot seek to position < 0";this.position+=se}},{key:"readByteStream",value:function(se){if(this.position+se>this.byteArray.length)throw"dicomParser.ByteStream.prototype.readByteStream: readByteStream - buffer overread";var ge=Ee(this.byteArray,this.position,se);return this.position+=se,new ie(this.byteArrayParser,ge)}},{key:"getSize",value:function(){return this.byteArray.length}},{key:"readUint16",value:function(){var se=this.byteArrayParser.readUint16(this.byteArray,this.position);return this.position+=2,se}},{key:"readUint32",value:function(){var se=this.byteArrayParser.readUint32(this.byteArray,this.position);return this.position+=4,se}},{key:"readFixedString",value:function(se){var ge=T(this.byteArray,this.position,se);return this.position+=se,ge}}])&&Oe(ae.prototype,we),Object.defineProperty(ae,"prototype",{writable:!1}),ie}(),B={readUint16:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readUint16: position cannot be less than 0";if(ae+2>ie.length)throw"littleEndianByteArrayParser.readUint16: attempt to read past end of buffer";return ie[ae]+256*ie[ae+1]},readInt16:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readInt16: position cannot be less than 0";if(ae+2>ie.length)throw"littleEndianByteArrayParser.readInt16: attempt to read past end of buffer";return ae=ie[ae]+(ie[ae+1]<<8),ae=32768&ae?ae-65535-1:ae},readUint32:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readUint32: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readUint32: attempt to read past end of buffer";return ie[ae]+256*ie[ae+1]+256*ie[ae+2]*256+256*ie[ae+3]*256*256},readInt32:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readInt32: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readInt32: attempt to read past end of buffer";return ie[ae]+(ie[ae+1]<<8)+(ie[ae+2]<<16)+(ie[ae+3]<<24)},readFloat:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readFloat: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readFloat: attempt to read past end of buffer";var we=new Uint8Array(4);return we[0]=ie[ae],we[1]=ie[ae+1],we[2]=ie[ae+2],we[3]=ie[ae+3],new Float32Array(we.buffer)[0]},readDouble:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readDouble: position cannot be less than 0";if(ae+8>ie.length)throw"littleEndianByteArrayParser.readDouble: attempt to read past end of buffer";var we=new Uint8Array(8);return we[0]=ie[ae],we[1]=ie[ae+1],we[2]=ie[ae+2],we[3]=ie[ae+3],we[4]=ie[ae+4],we[5]=ie[ae+5],we[6]=ie[ae+6],we[7]=ie[ae+7],new Float64Array(we.buffer)[0]}};function O(ie){var ae=1"u")throw"dicomParser.parseDicom: no inflater available to handle deflate transfer syntax";return tt=ie.slice(Ie),nt=pako.inflateRaw(tt),(tt=ue(ie,nt.length+Ie)).set(ie.slice(0,Ie),0),tt.set(nt,Ie),new Se(B,tt,0)}(ht,wt.position),wt=new b(ht.byteArrayParser,ht.byteArray,{});wt.warnings=ht.warnings;try{(oe?Y:re)(wt,ht,ht.byteArray.length,ae)}catch(gt){throw{exception:gt,dataSet:wt}}return wt}return function(Fe,oe){for(var ht in Fe.elements)Fe.elements.hasOwnProperty(ht)&&(oe.elements[ht]=Fe.elements[ht]);return Fe.warnings!==void 0&&(oe.warnings=Fe.warnings.concat(oe.warnings)),oe}(we=O(ie,ae),ge(we))}var K=function(ie,ae,we){for(var se=0,ge=ae;ge= 0";if(we>=oe.fragments.length)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragmentIndex' must be < number of fragments";if(se<1)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'numFragments' must be > 0";if(we+se>oe.fragments.length)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragment' + 'numFragments' < number of fragments";var Fe=new Se(ie.byteArrayParser,ie.byteArray,oe.dataOffset),oe=L(Fe);if(oe.tag!=="xfffee000")throw"dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000";Fe.seek(oe.length);var ht=Fe.position;if(se===1)return Ee(Fe.byteArray,ht+ge[we].offset+8,ge[we].length);for(var oe=K(ge,we,se),wt=ue(Fe.byteArray,oe),gt=0,Ie=we;Ie= 0";if(we>=se.length)throw"dicomParser.readEncapsulatedImageFrame: parameter 'frameIndex' must be < basicOffsetTable.length";var Fe=se[we],Fe=ee(ge,Fe);if(Fe===void 0)throw"dicomParser.readEncapsulatedImageFrame: unable to find fragment that matches basic offset table entry";return Z(ie,ae,Fe,xe(we,se,ge,Fe),ge)}var Ne=!1;function ze(ie,ae,we){if(Ne||(Ne=!0,console&&console.log&&console.log("WARNING: dicomParser.readEncapsulatedPixelData() has been deprecated")),ie===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'dataSet'";if(ae===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'element'";if(we===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'frame'";if(ae.tag!=="x7fe00010")throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to non pixel data tag (expected tag = x7fe00010)";if(ae.encapsulatedPixelData!==!0||ae.hadUndefinedLength!==!0||ae.basicOffsetTable===void 0||ae.fragments===void 0)throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";if(we<0)throw"dicomParser.readEncapsulatedPixelData: parameter 'frame' must be >= 0";return ae.basicOffsetTable.length!==0?De(ie,ae,we):Z(ie,ae,0,ae.fragments.length)}s.default={isStringVr:f,isPrivateTag:u,parsePN:d,parseTM:h,parseDA:p,explicitElementToString:v,explicitDataSetToJS:y,createJPEGBasicOffsetTable:x,parseDicomDataSetExplicit:Y,parseDicomDataSetImplicit:re,readFixedString:T,alloc:ue,version:ce,bigEndianByteArrayParser:pe,ByteStream:Se,sharedCopy:Ee,DataSet:b,findAndSetUNElementLength:_,findEndOfEncapsulatedElement:S,findItemDelimitationItemAndSetElementLength:I,littleEndianByteArrayParser:B,parseDicom:W,readDicomElementExplicit:j,readDicomElementImplicit:M,readEncapsulatedImageFrame:De,readEncapsulatedPixelData:ze,readEncapsulatedPixelDataFromFragments:Z,readPart10Header:O,readSequenceItemsExplicit:k,readSequenceItemsImplicit:G,readSequenceItem:L,readTag:C,LEI:"1.2.840.10008.1.2",LEE:"1.2.840.10008.1.2.1"}}],o={},n.m=i,n.c=o,n.d=function(a,s,c){n.o(a,s)||Object.defineProperty(a,s,{enumerable:!0,get:c})},n.r=function(a){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(a,"__esModule",{value:!0})},n.t=function(a,s){if(1&s&&(a=n(a)),8&s||4&s&&typeof a=="object"&&a&&a.__esModule)return a;var c=Object.create(null);if(n.r(c),Object.defineProperty(c,"default",{enumerable:!0,value:a}),2&s&&typeof a!="string")for(var l in a)n.d(c,l,(function(f){return a[f]}).bind(null,l));return c},n.n=function(a){var s=a&&a.__esModule?function(){return a.default}:function(){return a};return n.d(s,"a",s),s},n.o=function(a,s){return Object.prototype.hasOwnProperty.call(a,s)},n.p="",n(n.s=1);function n(a){if(o[a])return o[a].exports;var s=o[a]={i:a,l:!1,exports:{}};return i[a].call(s.exports,s,s.exports,n),s.l=!0,s.exports}var i,o})})(bB);var Tr=bB.exports;function k1(t){const e=t.indexOf(":");let r=t.substring(e+1);const n=r.indexOf("frame=");let i;if(n!==-1){const s=r.substring(n+6);i=parseInt(s,10),r=r.substring(0,n-1)}const o=t.substring(0,e),a=i!==void 0?i-1:void 0;return{scheme:o,url:r,frame:i,pixelDataFrame:a}}let oS={open(t,e){t.open("get",e,!0)},beforeSend(){},beforeProcessing(t){return Promise.resolve(t.response)},imageCreated(){},strict:!1};function IB(t){oS=Object.assign(oS,t)}function V1(){return oS}function H5(t,e,r={},n={}){const i=V1(),o=c=>{if(typeof i.errorInterceptor=="function"){const l=new Error("request failed");l.request=c,l.response=c.response,l.status=c.status,i.errorInterceptor(l)}},a=new XMLHttpRequest,s=new Promise((c,l)=>{i.open(a,t,r,n);const f=i.beforeSend(a,e,r,n);a.responseType="arraybuffer";const u=Object.assign({},r,f);Object.keys(u).forEach(function(d){u[d]!==null&&(d==="Accept"&&t.indexOf("accept=")!==-1||a.setRequestHeader(d,u[d]))}),n.deferred={resolve:c,reject:l},n.url=t,n.imageId=e,a.onloadstart=function(d){i.onloadstart&&i.onloadstart(d,n),at(Ke,"cornerstoneimageloadstart",{url:t,imageId:e})},a.onloadend=function(d){i.onloadend&&i.onloadend(d,n),at(Ke,"cornerstoneimageloadend",{url:t,imageId:e})},a.onreadystatechange=function(d){i.onreadystatechange&&i.onreadystatechange(d,n),a.readyState===4&&(a.status===200||a.status===206?i.beforeProcessing(a).then(c).catch(()=>{o(a),l(a)}):(o(a),l(a)))},a.onprogress=function(d){const h=d.loaded;let g,p;d.lengthComputable&&(g=d.total,p=Math.round(h/g*100)),at(Ke,"cornerstoneimageloadprogress",{url:t,imageId:e,loaded:h,total:g,percentComplete:p}),i.onprogress&&i.onprogress(d,n)},a.onerror=function(){o(a),l(a)},a.onabort=function(){o(a),l(a)},a.send()});return s.xhr=a,s}function Mwe(t,e,r){if(r+t.length>e.length)return!1;let n=r;for(let i=0;iy.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}));y.queue.writeBuffer(D[0],0,new Uint32Array(h));const b=[0,1].map(()=>y.createBuffer({size:m,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),I=y.createBuffer({size:w,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),P=y.createBuffer({size:x,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),M=new Int32Array([l,f,u,-1,-1,-1]);y.queue.writeBuffer(P,0,M);const L=y.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),V=[0,1].map(De=>{const Ne=D[De],$e=b[De],ie=D[(De+1)%2],ae=b[(De+1)%2];return y.createBindGroup({layout:L,entries:[{binding:0,resource:{buffer:T}},{binding:1,resource:{buffer:E}},{binding:2,resource:{buffer:Ne}},{binding:3,resource:{buffer:$e}},{binding:4,resource:{buffer:ie}},{binding:5,resource:{buffer:ae}},{binding:6,resource:{buffer:I}},{binding:7,resource:{buffer:P}}]})}),G=y.createComputePipeline({layout:y.createPipelineLayout({bindGroupLayouts:[L]}),compute:{module:C,entryPoint:"main",constants:{workGroupSizeX:n[0],workGroupSizeY:n[1],workGroupSizeZ:n[2],windowSize:i}}}),A=[Math.ceil(l/n[0]),Math.ceil(f/n[1]),Math.ceil(u/n[2])],k=y.createBuffer({size:w,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),F=o?performance.now()+o:0;let j=a.numCyclesInterval,Y=0;for(let De=0;De0&&!(De%j)){await k.mapAsync(GPUMapMode.READ,0,w);const ae=k.getMappedRange(0,w),se=new Uint32Array(ae.slice(0))[De]/g.length;if(k.unmap(),De>=1&&seF){console.warn(`Exceeded processing time limit (${o})ms`);break}}const re=y.createCommandEncoder(),ue=(d+1)%2,ce=y.createBuffer({size:m,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),pe=y.createBuffer({size:x,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});re.copyBufferToBuffer(D[ue],0,ce,0,m),re.copyBufferToBuffer(P,0,pe,0,x),y.queue.submit([re.finish()]),await ce.mapAsync(GPUMapMode.READ,0,m);const Ee=ce.getMappedRange(0,m),Oe=new Uint32Array(Ee);h.set(Oe),ce.unmap(),await pe.mapAsync(GPUMapMode.READ,0,x);const _e=pe.getMappedRange(0,x),B=new Int32Array(_e.slice(0));pe.unmap();const O=B[0],z=B[1],W=B[2],K=B[3],Z=B[4],ee=B[5];c.voxelManager.setCompleteScalarDataArray(h),c.voxelManager.clearBounds(),c.voxelManager.setBounds([[O,K],[z,Z],[W,ee]])}const{transformWorldToIndex:Kp}=Mn,S2e=254,_2e=255,T2e=.1,E2e=.8;function D2e(t,e){const{topLeftWorld:r,bottomRightWorld:n}=e,i=Kp(t.imageData,r),o=Kp(t.imageData,n);return{...e,topLeftIJK:i,bottomRightIJK:o}}function b2e(t,e){const r=t.imageData.getDirection(),n=bt(r[3],r[4],r[5]),{center:i,radius:o}=e,a=t.imageData,s=Tn(Ve(),i,n,-o),c=Tn(Ve(),i,n,o),l=fF([c,s],a);return D2e(t,l)}function I2e(t,e,r){const n=t.imageData,i=r.getCamera(),{ijkVecRowDir:o,ijkVecColDir:a}=f5(n,i);if([o,a].some(f=>!$t(Math.abs(f[0]),1)&&!$t(Math.abs(f[1]),1)&&!$t(Math.abs(f[2]),1))){console.warn("Oblique view is not supported!");return}const{boundsIJK:c}=b2e(t,e),l={minX:c[0][0],maxX:c[0][1]+1,minY:c[1][0],maxY:c[1][1]+1,minZ:c[2][0],maxZ:c[2][1]+1};return GT(t.volumeId,l,{targetBuffer:{type:"Float32Array"}})}function O2e(t,e,r,n){const i=t.voxelManager.getCompleteScalarDataArray(),o=r.center,[a,s,c]=t.dimensions,l=a*s,f=Kp(t.imageData,o),u=i[f[2]*l+f[1]*a+f[0]],d=n.positiveSeedValue??S2e,h=n.positiveSeedVariance??T2e,g=Math.abs(u*h),p=u-g,v=u+g,y=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]],m=f[2]*l+f[1]*a+f[0];e.voxelManager.setAtIndex(m,d);const w=[f];for(;w.length;){const x=w.shift(),[C,S,_]=x;for(let T=0,E=y.length;T=a||I<0||I>=s||P<0||P>=c)continue;const M=P*l+I*a+b,L=i[M];e.voxelManager.getAtIndex(M)===d||Lv||(e.voxelManager.setAtIndex(M,d),w.push([b,I,P]))}}}function M2e(t,e,r,n,i){const o=t.voxelManager.getCompleteScalarDataArray(),[a,s,c]=e.dimensions,l=a*s,{worldVecRowDir:f,worldVecSliceDir:u}=f5(e.imageData,n.getCamera()),d=Kp(t.imageData,r.center),h=o[d[2]*a*s+d[1]*a+d[0]],g=i.negativeSeedVariance??E2e,p=(i==null?void 0:i.negativeSeedValue)??_2e,v=Math.abs(h*g),y=h-v,m=h+v,w=360,x=2*Math.PI/w,C=jy(yu(),u,x),S=OM(f);for(let _=0;_=a||b<0||b>=s||I<0||I>=c)continue;const P=D+b*a+I*l,M=o[P];(Mm)&&e.voxelManager.setAtIndex(P,p)}}async function P2e(t,e,r,n){const i=await o5(t.volumeId);return O2e(t,i,e,n),M2e(t,i,e,r,n),i}async function iU(t,e,r,n){const i=Le.getVolume(t),o=I2e(i,e,r),a=await P2e(o,e,r,n);return await $5(o.volumeId,a.volumeId),a}const R2e=254,L2e=255,A2e=[-1/0,-995],N2e=[0,1900];function k2e(t,e,r){const{negativeSeedValue:n=L2e,negativePixelRange:i=A2e}=r,o=t.voxelManager.getCompleteScalarDataArray(),[a,s,c]=e.dimensions,l=Math.floor(c/2),f=new Array(a*s).fill(!1),u=l*a*s,d=(g,p)=>{const v=[[g,p]];for(;v.length;){const[y,m]=v.shift(),w=m*a+y;if(y<0||y>=a||m<0||m>=s||f[w])continue;f[w]=!0;const x=u+w,C=o[x];Ci[1]||(e.voxelManager.setAtIndex(x,n),v.push([y-1,m]),v.push([y+1,m]),v.push([y,m-1]),v.push([y,m+1]))}},h=(g,p,v,y)=>{for(let m=g;m!==p;m+=v){const w=y*a+m,x=u+w,C=o[x];if(Ci[1])break;f[w]||d(m,y)}};for(let g=0;g=i[0]&&w<=i[1]&&e.voxelManager.setAtIndex(m,n)}}}}async function F2e(t,e){const r=o5(t.volumeId);return V2e(t,r,e),k2e(t,r,e),r}async function oU(t,e,r){const{boundingBox:n}=e,{ijkTopLeft:i,ijkBottomRight:o}=n,a={minX:i[0],maxX:o[0],minY:i[1],maxY:o[1],minZ:i[2],maxZ:o[2]},s=GT(t,a,{targetBuffer:{type:"Float32Array"}}),c=await F2e(s,r);return await $5(s.volumeId,c.volumeId),c}const U2e=254,B2e=255,G2e=1,aU=1.8,W2e=3.2,RC=30,z2e=70,$2e=50,{transformWorldToIndex:j2e}=Mn,wg=1e5;function sU(t,e,r){const{dimensions:n,imageData:i}=t,[o,a,s]=n,c=t.voxelManager,l=c.getCompleteScalarDataArray(),f=o*a,u=(r==null?void 0:r.initialNeighborhoodRadius)??G2e,d=(r==null?void 0:r.positiveStdDevMultiplier)??aU,h=(r==null?void 0:r.negativeStdDevMultiplier)??W2e,g=(r==null?void 0:r.negativeSeedMargin)??RC,p=(r==null?void 0:r.negativeSeedsTargetPatches)??z2e,v=j2e(i,e).map(Math.round),y=c.toIndex(v);if(v[0]<0||v[0]>=o||v[1]<0||v[1]>=a||v[2]<0||v[2]>=s)return console.warn("Click position is outside volume bounds."),null;const m=JA(l,n,v,u);m.count===0&&(m.mean=l[y],m.stdDev=0);const w=m.mean-d*m.stdDev,x=m.mean+d*m.stdDev,C=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]];let S=1/0,_=1/0,T=1/0,E=-1/0,D=-1/0,b=-1/0;const I=new Set,P=[],M=l[y];if(M>=w&&M<=x)I.add(y),P.push(v),S=E=v[0],_=D=v[1],T=b=v[2];else return console.warn("Clicked voxel intensity is outside the calculated positive range. No positive seeds generated."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let L=0;for(;L=o||ie<0||ie>=a||ae<0||ae>=s)continue;const ye=ae*f+ie*o+$e;if(I.has(ye))continue;const se=l[ye];se>=w&&se<=x&&(I.add(ye),I.size=wg&&console.debug(`Reached maximum number of positive seeds (${wg}). Stopping BFS.`),I.size===0)return console.warn("No positive seeds found after BFS."),{positiveSeedIndices:new Set,negativeSeedIndices:new Set};let V=0,G=0;I.forEach(W=>{const K=l[W];V+=K,G+=K*K});const A=I.size,k=V/A,F=G/A-k*k,j=Math.sqrt(Math.max(0,F)),Y=h*j,re=Math.max(0,S-g),ue=Math.max(0,_-g),ce=Math.max(0,T-g),pe=Math.min(o-1,E+g),Ee=Math.min(a-1,D+g),Oe=Math.min(s-1,b+g),_e=new Set;let B=0,O=0;const z=p*$2e;for(;OY){let De=!1;for(let Ne=-1;Ne<=1;Ne++){const $e=K+Ne;if(!($e<0||$e>=a))for(let ie=-1;ie<=1;ie++){const ae=W+ie;if(ae<0||ae>=o)continue;const ye=Z*f+$e*o+ae;I.has(ye)||_e.has(ye)||(_e.add(ye),De=!0)}}De&&O++}}return _e.size===0&&console.warn("Could not find any negative seeds. GrowCut might fail or produce poor results."),console.debug("positiveSeedIndices",I.size),console.debug("negativeSeedIndices",_e.size),{positiveSeedIndices:I,negativeSeedIndices:_e}}async function cU({referencedVolumeId:t,worldPosition:e,options:r}){const n=Le.getVolume(t),i=o5(t);i.voxelManager.forEach(({index:f,value:u})=>{u!==0&&i.voxelManager.setAtIndex(f,0)});const o=r.seeds??sU(n,e,r),a=(r==null?void 0:r.positiveSeedValue)??U2e,s=(r==null?void 0:r.negativeSeedValue)??B2e;if(!o)return null;const{positiveSeedIndices:c,negativeSeedIndices:l}=o;return c.size<10||c.size>wg||l.size<10?(console.warn("Not enough seeds found. GrowCut might fail or produce poor results."),i):(c.forEach(f=>{i.voxelManager.setAtIndex(f,a)}),l.forEach(f=>{i.voxelManager.setAtIndex(f,s)}),await $5(t,i.volumeId,r),i)}const H2e=Object.freeze(Object.defineProperty({__proto__:null,run:$5,runGrowCutForBoundingBox:oU,runGrowCutForSphere:iU,runOneClickGrowCut:cU},Symbol.toStringTag,{value:"Module"}));function K2e(t,e){const{segmentationId:r,config:n}=e,i={colorLUTIndex:q2e(n),...n};Zn.addSegmentationRepresentation(t,r,e.type,i),e.type===Dt.Contour&&Pe([t]),Ta(r)}function q2e(t){const{colorLUTOrIndex:e}=t||{};return e===void 0?$g(JSON.parse(JSON.stringify(oy))):typeof e=="number"?e:Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===4)?$g(e):$g(JSON.parse(JSON.stringify(oy)))}function Th(t,e){e.map(r=>K2e(t,r))}function K4(t,e){return Th(t,e.map(r=>({...r,type:Dt.Contour})))}function X2e(t){const e={};for(const[r,n]of Object.entries(t))e[r]=K4(r,n);return e}function lU(t,e){return Th(t,e.map(r=>({...r,type:Dt.Labelmap})))}function Y2e(t){for(const[e,r]of Object.entries(t))lU(e,r.map(n=>({...n,type:Dt.Labelmap})))}function uU(t,e){return Th(t,e.map(r=>({...r,type:Dt.Surface})))}function J2e(t){const e={};for(const[r,n]of Object.entries(t))e[r]=uU(r,n);return e}async function Z2e({segmentationId:t,viewportId:e,imageIds:r,options:n}){const i=Ln(t);if(n!=null&&n.removeOriginal){const o=i.representationData.Labelmap;Le.getVolume(o.volumeId)&&Le.removeVolumeLoadObject(o.volumeId),i.representationData.Labelmap={imageIds:r}}else i.representationData.Labelmap={...i.representationData.Labelmap,imageIds:r};await Th(e,[{segmentationId:t,type:Dt.Labelmap}]),Ke.addEventListenerOnce(N.SEGMENTATION_RENDERED,()=>io(t))}async function Q2e({volumeId:t}){return{imageIds:Le.getVolume(t).imageIds}}function eve({segmentationId:t,options:e}){const r=Ln(t);if(!r)return;const{volumeId:n}=r.representationData.Labelmap,i=Le.getVolume(n);return Z2e({segmentationId:t,viewportId:e.viewportId,imageIds:i.imageIds,options:e})}async function fU(t){return ak(t)}async function tve({segmentationId:t,segmentIndices:e,mode:r="individual"}){F5(),oc(xa.COMPUTE_LARGEST_BIDIRECTIONAL,0);const n=IF(t,e);if(!n)return;const{operationData:i,segImageIds:o,reconstructableVolume:a,indices:s}=n,c=a?await nve({operationData:i,indices:s,mode:r}):await rve({segImageIds:o,indices:s,mode:r});return oc(xa.COMPUTE_LARGEST_BIDIRECTIONAL,100),c}async function nve({operationData:t,indices:e,mode:r}){const n=OF(t),{segmentationVoxelManager:i,segmentationImageData:o}=n,s={scalarData:i.getCompleteScalarDataArray(),dimensions:o.getDimensions(),spacing:o.getSpacing(),origin:o.getOrigin(),direction:o.getDirection()};return await il().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:s,indices:e,mode:r})}async function rve({segImageIds:t,indices:e,mode:r}){const{segmentationInfo:n}=MF(t);return await il().executeTask("compute","getSegmentLargestBidirectionalInternal",{segmentationInfo:n,indices:e,mode:r,isStack:!0})}function ive(t){const e=Ln(t);if(!e)return null;let r;const n=e.representationData.Labelmap;if("imageIds"in n){const{imageIds:i}=n,o=Le.getImage(i[0]),a=Le.getVolumeContainingImageId(o.referencedImageId);if(a!=null&&a.volume)return a.volume;r=i.map(s=>Le.getImage(s).referencedImageId)}else if("volumeId"in n){const{volumeId:i,referencedVolumeId:o}=n;if(o){const s=Le.getVolume(o);if(s)return s}const a=Le.getVolume(i);a&&(r=a.imageIds.map(s=>Le.getImage(s).referencedImageId))}return B5(r)}async function ove({segmentationIds:t,segmentIndex:e}){F5(),oc(xa.COMPUTE_STATISTICS,0);const r=Ln(t[0]),{imageIds:n}=r.representationData.Labelmap;if(!Nu(n))throw new Error("Invalid volume - TMTV cannot be calculated");return await ave({segmentationIds:t,segmentIndex:e})}async function ave({segmentationIds:t,segmentIndex:e}){const r=t.map(p=>Sh(p)),n=NF(r,e);if(!n)throw new Error("Invalid volume - TMTV cannot be calculated");const{imageData:i,dimensions:o,direction:a,origin:s,voxelManager:c}=n,l=i.getSpacing(),u={scalarData:c.getCompleteScalarDataArray(),dimensions:o,spacing:l,origin:s,direction:a},d=ive(t[0]),h={dimensions:d.dimensions,spacing:d.spacing,origin:d.origin,direction:d.direction,scalarData:d.voxelManager.getCompleteScalarDataArray()};if(h.scalarData.length===0||u.scalarData.length===0)return{[e]:{name:"TMTV",value:0}};const g=await il().executeTask("compute","computeMetabolicStats",{segmentationInfo:u,imageInfo:h});return oc(xa.COMPUTE_STATISTICS,100),g}const sve=Object.freeze(Object.defineProperty({__proto__:null,IslandRemoval:nd,LabelmapMemo:Hme,SegmentStatsCalculator:PC,VolumetricCalculator:Uf,computeMetabolicStats:ove,computeStackLabelmapFromVolume:Q2e,computeVolumeLabelmapFromStack:fU,contourAndFindLargestBidirectional:ZF,createBidirectionalToolData:QF,createLabelmapVolumeForViewport:fme,createMergedLabelmapForIndex:NF,floodFill:$4,getBrushSizeForToolGroup:r2e,getBrushThresholdForToolGroup:o2e,getBrushToolInstances:_h,getHoveredContourSegmentationAnnotation:rU,getOrCreateImageVolume:B5,getOrCreateSegmentationVolume:Sh,getReferenceVolumeForSegmentationVolume:EF,getSegmentIndexAtLabelmapBorder:tU,getSegmentIndexAtWorldPoint:H4,getSegmentLargestBidirectional:tve,getStatistics:UF,getUniqueSegmentIndices:Qk,growCut:H2e,invalidateBrushCursor:eU,rectangleROIThresholdVolumeByRange:lme,segmentContourAction:g2e,setBrushSizeForToolGroup:n2e,setBrushThresholdForToolGroup:i2e,thresholdSegmentationByRange:a2e,thresholdVolumeByRange:LF,triggerSegmentationRender:wh,triggerSegmentationRenderBySegmentationId:k5,validateLabelmap:Y1e},Symbol.toStringTag,{value:"Module"}));function cve(t){let e="";const r=t[0]<0?"R":"L",n=t[1]<0?"A":"P",i=t[2]<0?"F":"H",o=[Math.abs(t[0]),Math.abs(t[1]),Math.abs(t[2])],a=1e-4;for(let s=0;s<3;s++)if(o[0]>a&&o[0]>o[1]&&o[0]>o[2])e+=r,o[0]=0;else if(o[1]>a&&o[1]>o[0]&&o[1]>o[2])e+=n,o[1]=0;else if(o[2]>a&&o[2]>o[0]&&o[2]>o[1])e+=i,o[2]=0;else if(o[0]>a&&o[1]>a&&o[0]===o[1])e+=r+n,o[0]=0,o[1]=0;else if(o[0]>a&&o[2]>a&&o[0]===o[2])e+=r+i,o[0]=0,o[2]=0;else if(o[1]>a&&o[2]>a&&o[1]===o[2])e+=n+i,o[1]=0,o[2]=0;else break;return e}function lve(t){let e=t.replace("H","f");return e=e.replace("F","h"),e=e.replace("R","l"),e=e.replace("L","r"),e=e.replace("A","p"),e=e.replace("P","a"),e=e.toUpperCase(),e}const uve=Object.freeze(Object.defineProperty({__proto__:null,getOrientationStringLPS:cve,invertOrientationStringLPS:lve},Symbol.toStringTag,{value:"Module"}));var _0;(function(t){t.CLIP_STOPPED="CORNERSTONE_CINE_TOOL_STOPPED",t.CLIP_STARTED="CORNERSTONE_CINE_TOOL_STARTED"})(_0||(_0={}));const q4={};function dU(t,e){const r=Ce(t),{viewportId:n}=r;q4[n]=e}function X4(t){const e=Ce(t),{viewportId:r}=e;return q4[r]}function fve(t){return q4[t]}const{ViewportStatus:hU}=ja,{triggerEvent:h3}=Mn,gU=!0,LC=new Map;function dve(t,e){let r,n;if(t===void 0)throw new Error("playClip: element must not be undefined");const i=Ce(t);if(!i)throw new Error("playClip: element must be a valid Cornerstone enabled element");e||(e={}),e.dynamicCineEnabled=e.dynamicCineEnabled??!0;const{viewport:o}=i,a=yve(o,e);let s=X4(t);const c=e.dynamicCineEnabled;if(c&&mU(t),s?AC(t,{stopDynamicCine:!c,viewportId:o.id}):(s={intervalId:void 0,framesPerSecond:30,lastFrameTimeStamp:void 0,ignoreFrameTimeVector:!1,usingFrameTimeVector:!1,frameTimeVector:e.frameTimeVector??void 0,speed:e.frameTimeVectorSpeedMultiplier??1,reverse:e.reverse??!1,loop:e.loop??!0,bounce:e.bounce??!1},dU(t,s)),s.dynamicCineEnabled=e.dynamicCineEnabled,(e.framesPerSecond<0||e.framesPerSecond>0)&&(s.framesPerSecond=Number(e.framesPerSecond),s.reverse=s.framesPerSecond<0,s.ignoreFrameTimeVector=!0),s.ignoreFrameTimeVector!==!0&&s.frameTimeVector&&s.frameTimeVector.length===a.numScrollSteps&&a.frameTimeVectorEnabled){const{timeouts:u,isTimeVarying:d}=hve(s.frameTimeVector,s.speed);r=u,n=d}e.bounce!==void 0&&(s.bounce=e.bounce);const l=()=>{const{numScrollSteps:u,currentStepIndex:d}=a;let h=d+(s.reverse?-1:1);if(h<0||h>=u)if(s.bounce)s.reverse=!s.reverse,h=d+(s.reverse?-1:1),h=Math.max(0,Math.min(u-1,h));else if(s.loop)h=s.reverse?u-1:0;else{AC(t,{stopDynamicCine:!c,viewportId:o.id}),h3(t,_0.CLIP_STOPPED,{element:t});return}const p=h-d;if(p)try{a.scroll(p)}catch(v){console.warn("Play clip not scrolling",v),vU(s),h3(t,_0.CLIP_STOPPED,{element:t})}};if(c){const u=Y4(o);u&&LC.set(u.volumeId,t)}a.play?s.framesPerSecond=a.play(e.framesPerSecond):r&&r.length>0&&n?(s.usingFrameTimeVector=!0,s.intervalId=window.setTimeout(function u(){s.intervalId=window.setTimeout(u,r[a.currentStepIndex]),l()},0)):(s.usingFrameTimeVector=!1,s.intervalId=window.setInterval(l,1e3/Math.abs(s.framesPerSecond)));const f={element:t};h3(t,_0.CLIP_STARTED,f)}function pU(t,e={}){AC(t,{stopDynamicCine:!0,...e})}function AC(t,e={stopDynamicCine:!0,viewportId:void 0}){const{stopDynamicCine:r,viewportId:n}=e,i=Ce(t);let o;const a=i==null?void 0:i.viewport;if(i){const{viewport:s}=i;o=X4(s.element)}else if(n)o=fve(n);else return;o&&vU(o),a instanceof Rp?a.pause():r&&a instanceof Ir&&mU(t)}function mU(t){const{viewport:e}=Ce(t);if(e instanceof ur){const r=Y4(e);if(r!=null&&r.isDynamicVolume()){const n=LC.get(r.volumeId);LC.delete(r.volumeId),n&&n!==t&&pU(n)}}}function hve(t,e){let r,n,i,o=0;const a=t.length,s=[];let c=!1;for((typeof e!="number"||e<=0)&&(e=1),r=1;r0&&(c?i=o/s.length|0:i=s[0],s.push(i)),{timeouts:s,isTimeVarying:c}}function vU(t){const e=t.intervalId;typeof e<"u"&&(t.intervalId=void 0,t.usingFrameTimeVector?clearTimeout(e):clearInterval(e))}function Y4(t){if(!(t instanceof ur))return;const e=t.getAllVolumeIds();if(!(e!=null&&e.length))return;const n=e.find(i=>{var o;return(o=Le.getVolume(i))==null?void 0:o.isDynamicVolume()})??e[0];return Le.getVolume(n)}function gve(t,e){const r=t.getImageIds();return{get numScrollSteps(){return r.length},get currentStepIndex(){return t.getTargetImageIdIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(n){if(this.waitForRenderedCount<=e&&t.viewportStatus!==hU.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,ps(t,{delta:n,debounceLoading:gU})}}}function pve(t,e){return{get numScrollSteps(){return t.getNumberOfSlices()},get currentStepIndex(){return t.getSliceIndex()},get frameTimeVectorEnabled(){return!0},waitForRenderedCount:0,scroll(r){if(this.waitForRenderedCount<=e&&t.viewportStatus!==hU.RENDERED){this.waitForRenderedCount++;return}this.waitForRenderedCount=0,ps(t,{delta:r,debounceLoading:gU})},play(r){return r&&t.setPlaybackRate(r/24),t.play(),t.getFrameRate()}}}function mve(t,e){const{volumeId:r}=e,n={viewPlaneNormal:Ve(),scrollInfo:null},i=()=>{const o=t.getCamera();if(!n.scrollInfo||!Bx(o.viewPlaneNormal,n.viewPlaneNormal)){const s=Vf(t,r);n.viewPlaneNormal=o.viewPlaneNormal,n.scrollInfo=s}return n.scrollInfo};return{get numScrollSteps(){return i().numScrollSteps},get currentStepIndex(){return i().currentStepIndex},get frameTimeVectorEnabled(){const o=t.getCamera(),a=e.direction.slice(6,9).map(c=>-c),s=Et(a,o.viewPlaneNormal);return vu(s,1)},scroll(o){i().currentStepIndex+=o,ps(t,{delta:o})}}}function vve(t){return{get numScrollSteps(){return t.numDimensionGroups},get currentStepIndex(){return t.dimensionGroupNumber-1},get frameTimeVectorEnabled(){return!1},scroll(e){t.scroll(e)}}}function yve(t,e){if(t instanceof lr)return gve(t,e.waitForRendered??30);if(t instanceof ur){const r=Y4(t);return e.dynamicCineEnabled&&(r!=null&&r.isDynamicVolume())?vve(r):mve(t,r)}if(t instanceof Rp)return pve(t,e.waitForRendered??30);throw new Error("Unknown viewport type")}const wve=Object.freeze(Object.defineProperty({__proto__:null,Events:_0,addToolState:dU,getToolState:X4,playClip:dve,stopClip:pU},Symbol.toStringTag,{value:"Module"}));function xve(t,e){var n,i,o;const r=(e==null?void 0:e.knotsRatioPercentage)||30;return!((o=(i=(n=t==null?void 0:t.data)==null?void 0:n.contour)==null?void 0:i.polyline)!=null&&o.length)||r<=0}function Cve(t,e){const r=Zo(),n=Ai(Ve(),e,t),i=Math.abs(t[0])>.1?bt(-t[1],t[0],0):bt(0,-t[2],t[1]);return A_(r,e,n,i),r}function Gm(t,e=Math.floor(Math.random()*(t.length-1))){if(e===0)return 0;const r=[...t],{length:n}=t;for(let i=0;i{const u=Jt(Ve(),f,o);return[u[0],u[1]]});let s=n?Gm(a):0,c=TC(a,0,a.length,(e==null?void 0:e.knotsRatioPercentage)||30);if(c===a)return!1;Gm(c,-s);for(let f=1;f<(e==null?void 0:e.loop);f++)s=n?Gm(c):0,c=TC(c,0,a.length,(e==null?void 0:e.knotsRatioPercentage)||30),Gm(c,-s);const l=oi(Zo(),o);return t.data.contour.polyline=c.map(f=>Jt([0,0,0],[...f,0],l)),!0}const Sve={smoothAnnotation:yU},_ve=Object.freeze(Object.defineProperty({__proto__:null,default:Sve,smoothAnnotation:yU},Symbol.toStringTag,{value:"Module"})),Tve=Object.freeze(Object.defineProperty({__proto__:null,getBoundsIJKFromRectangleAnnotations:AF,isAxisAlignedRectangle:XF},Symbol.toStringTag,{value:"Module"})),wU={};function xU(t,e){const r=Ce(t),{viewportId:n}=r;wU[n]=e}function Eh(t){const e=Ce(t),{viewportId:r}=e;return wU[r]}const Bf=hn.Prefetch,CU=0;function Eve(t,e){t=Math.round(t)||0,e=Math.round(e)||0;const r=[];let n=e-t+1;if(n<=0)return r;for(;n--;)r[n]=e--;return r}function Dve(t,e){let r=0,n=t.length-1;return t.forEach((i,o)=>{ie&&(n=Math.min(o,n))}),{low:r,high:n}}function Dh(t){const e=Ce(t);if(!e)return null;const{viewport:r}=e;return r instanceof lr?{currentImageIdIndex:r.getCurrentImageIdIndex(),imageIds:r.getImageIds()}:null}function j5(t){return function(e){const r=e.detail;let n;try{n=Dh(t)}catch{return}if(!n||!n.imageIds||n.imageIds.length===0)return;const o=n.imageIds.indexOf(r.imageId);if(o<0)return;const a=Eh(t);!a||!a.indicesToRequest||!a.indicesToRequest.length||a.indicesToRequest.push(o)}}const bve=t=>{const e=new Set(t.imageIds);return r=>r.type!==Bf||!e.has(r.additionalDetails.imageId)};let jg={maxImagesToPrefetch:1/0,preserveExistingPool:!0},NC;const Ive=10;function SU(t){var g,p;const e=Eh(t);if(!e)return;const r=e||{},n=Dh(t);if(!((g=n==null?void 0:n.imageIds)!=null&&g.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:i}=n;if(r.enabled=r.enabled&&(((p=r.indicesToRequest)==null?void 0:p.length)??0)>0,r.enabled===!1)return;function o(v){const y=r.indicesToRequest.indexOf(v);y>-1&&r.indicesToRequest.splice(y,1)}if(e.indicesToRequest.sort((v,y)=>v-y),r.indicesToRequest.slice().forEach(function(v){const y=n.imageIds[v];if(!y)return;(Math.abs(i-v)<6?Le.getImageLoadObject(y):Le.isLoaded(y))&&o(v)}),!r.indicesToRequest.length)return;jg.preserveExistingPool||Ao.clearRequestStack(Bf);const s=Dve(r.indicesToRequest,n.currentImageIdIndex);let c,l,f=s.low,u=s.high;const d=[];for(;f>=0||ujg.maxImagesToPrefetch,m=r.indicesToRequest[u]-v>jg.maxImagesToPrefetch,w=!y&&f>=0,x=!m&&uxu(v,y);d.forEach(v=>{const y={requestType:Bf};Ao.addRequest(h.bind(null,v,y),Bf,{imageId:v},CU)})}function kC(t){clearTimeout(NC),NC=setTimeout(function(){const e=t.target;try{SU(e)}catch{return}},Ive)}function Ove(t){const e=Dh(t);if(!e||!e.imageIds||e.imageIds.length===0){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const r={indicesToRequest:Eve(0,e.imageIds.length-1),enabled:!0,direction:1},n=r.indicesToRequest.indexOf(e.currentImageIdIndex);r.indicesToRequest.splice(n,1),xU(t,r),SU(t),t.removeEventListener(Xe.STACK_NEW_IMAGE,kC),t.addEventListener(Xe.STACK_NEW_IMAGE,kC);const i=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,i),Ke.addEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,i)}function Mve(t){clearTimeout(NC),t.removeEventListener(Xe.STACK_NEW_IMAGE,kC);const e=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,e);const r=Eh(t);r&&r.indicesToRequest.length&&(r.enabled=!1,Ao.clearRequestStack(Bf))}function Pve(){return jg}function Rve(t){jg=t}const Lve={enable:Ove,disable:Mve,getConfiguration:Pve,setConfiguration:Rve};let qp={maxImagesToPrefetch:1/0,minBefore:2,maxAfter:2,directionExtraImages:10,preserveExistingPool:!1},VC;const Ave=5,Nve=t=>{var n;const e=Dh(t);if(!e)return;if(!((n=e.imageIds)!=null&&n.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}Z4(t),J4(t),t.removeEventListener(Xe.STACK_NEW_IMAGE,FC),t.addEventListener(Xe.STACK_NEW_IMAGE,FC);const r=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,r),Ke.addEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,r)};function J4(t){var l,f;const e=Dh(t);if(!e)return;if(!((l=e==null?void 0:e.imageIds)!=null&&l.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const r=Eh(t);if(!r)return;const n=r||{};if(n.enabled=n.enabled&&(((f=n.indicesToRequest)==null?void 0:f.length)??0)>0,n.enabled===!1)return;function i(u){const d=n.indicesToRequest.indexOf(u);d>-1&&n.indicesToRequest.splice(d,1)}const o=n.indicesToRequest.slice(),{currentImageIdIndex:a}=e;if(o.forEach(u=>{const d=e.imageIds[u];if(!d)return;(Math.abs(a-u)<6?Le.getImageLoadObject(d):Le.isLoaded(d))&&i(u)}),!n.indicesToRequest.length)return;qp.preserveExistingPool||Ao.filterRequests(bve(e));function s(u){var v,y;const d=e.imageIds.indexOf(u);i(d);const h=Le.getCachedImageBasedOnImageURI(u),{stats:g}=n,p=((v=h==null?void 0:h.image)==null?void 0:v.decodeTimeInMS)||0;if(p){g.imageIds.set(u,p),g.decodeTimeInMS+=p;const m=((y=h==null?void 0:h.image)==null?void 0:y.loadTimeInMS)||0;g.loadTimeInMS+=m}if(!n.indicesToRequest.length&&h!=null&&h.sizeInBytes){const{sizeInBytes:m}=h,w=Le.getMaxCacheSize()/4/m;if(!n.cacheFill)g.initialTime=Date.now()-g.start,g.initialSize=g.imageIds.size,Z4(t,w),J4(t);else if(g.imageIds.size){g.fillTime=Date.now()-g.start;const{size:x}=g.imageIds;g.fillSize=x}}}const c=(u,d)=>xu(u,d).then(()=>s(u));n.indicesToRequest.forEach(u=>{const d=e.imageIds[u],h={requestType:Bf};Ao.addRequest(c.bind(null,d,h),Bf,{imageId:d},CU)})}function FC(t){clearTimeout(VC),VC=setTimeout(function(){const e=t.target;try{Z4(e),J4(e)}catch{return}},Ave)}const kve=t=>t<0?-1:1,Z4=(t,e)=>{var d;const r=Dh(t);if(!r)return;if(!((d=r.imageIds)!=null&&d.length)){console.warn("CornerstoneTools.stackPrefetch: No images in stack.");return}const{currentImageIdIndex:n}=r;let{maxAfter:i=2,minBefore:o=2}=qp;const{directionExtraImages:a=10}=qp,s=Eh(t)||{indicesToRequest:[],currentImageIdIndex:n,stackCount:0,enabled:!0,direction:1,stats:{start:Date.now(),imageIds:new Map,decodeTimeInMS:0,loadTimeInMS:0,totalBytes:0}},c=n-s.currentImageIdIndex;if(s.direction=kve(c),s.currentImageIdIndex=n,s.enabled=!0,s.stackCount<100&&(s.stackCount+=a),Math.abs(c)>i||!c)if(s.stackCount=0,e){const h=n/r.imageIds.length;o=Math.ceil(e*h),i=Math.ceil(e*(1-h)),s.cacheFill=!0}else s.cacheFill=!1;else c<0?(o+=s.stackCount,i=0):(i+=s.stackCount,o=0);const l=Math.max(0,n-o),f=Math.min(r.imageIds.length-1,n+i),u=[];for(let h=n+1;h<=f;h++)u.push(h);for(let h=n-1;h>=l;h--)u.push(h);s.indicesToRequest=u,xU(t,s)};function Vve(t){clearTimeout(VC),t.removeEventListener(Xe.STACK_NEW_IMAGE,FC);const e=j5(t);Ke.removeEventListener(Xe.IMAGE_CACHE_IMAGE_REMOVED,e);const r=Eh(t);r&&(r.enabled=!1)}function Fve(){return qp}function Uve(t){qp=t}const Bve={enable:Nve,disable:Vve,getConfiguration:Fve,setConfiguration:Uve},Gve=Object.freeze(Object.defineProperty({__proto__:null,isViewportPreScaled:al},Symbol.toStringTag,{value:"Module"}));function Wve(t,e){let r;const n=e.dimensionGroupNumbers||e.frameNumbers||Array.from({length:t.numDimensionGroups},(i,o)=>o+1);if(e.frameNumbers&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead."),!e.maskVolumeId&&!e.worldCoordinate)throw new Error("You should provide either maskVolumeId or imageCoordinate");if(e.maskVolumeId&&e.worldCoordinate)throw new Error("You can only use one of maskVolumeId or imageCoordinate");if(e.maskVolumeId){const i=Le.getVolume(e.maskVolumeId);if(!i)throw new Error("Segmentation volume not found");const[o,a]=$ve(n,t,i);return[o,a]}return e.worldCoordinate?zve(n,e.worldCoordinate,t):r}function zve(t,e,r){const{dimensions:n,imageData:i}=r,o=i.worldToIndex(e);if(o[0]=Math.floor(o[0]),o[1]=Math.floor(o[1]),o[2]=Math.floor(o[2]),!sr(o,n))throw new Error("outside bounds");const a=n[0],s=n[0]*n[1],c=[];return t.forEach(l=>{const f=o[2]*s+o[1]*a+o[0];c.push(r.voxelManager.getAtIndexAndDimensionGroup(f,l))}),c}function $ve(t,e,r){const{imageData:n}=r,i=r.voxelManager,o=i.getScalarDataLength(),a=[];a.length=o;let s=0;for(let d=0,h=o;d{if(h===0)return;const p=ZT(e.imageData,e.dimensions,e.spacing,d);let v=0;const y=new Map;t.forEach(x=>y.set(x,0));const m=({index:x})=>{for(let C=0;C{w.push(x/v)}),f.push(g),c.push(w)};return r.voxelManager.forEach(u,{imageData:n}),[c,f]}function _U(t,e){const r=t.getScalarDataLength(),n=new Float32Array(r);for(const i of e){const o=t.getDimensionGroupScalarData(i);for(let a=0;a{const n=_U(t,e);for(let i=0;i{const n=jve(t,e);for(let i=0;i{if(e.length!==2)throw new Error("Please provide only 2 dimension groups for subtraction.");const n=t.getScalarDataLength(),i=t.getDimensionGroupScalarData(e[0]),o=t.getDimensionGroupScalarData(e[1]);for(let a=0;au+1);if(o.length<=1)throw new Error("Please provide two or more dimension groups");const a=t.voxelManager,s=a.getScalarDataLength(),c=TU[e];if(!c)throw new Error(`Unsupported operation: ${e}`);const l=new Float32Array(s);return c(a,o,(f,u)=>{l[f]=u}),l}function Kve(t,e,r){const{dimensionGroupNumbers:n,frameNumbers:i,targetVolume:o}=r;if(!o)throw new Error("A target volume must be provided");i&&console.warn("Warning: frameNumbers parameter is deprecated. Please use dimensionGroupNumbers instead.");const a=n||i||Array.from({length:t.numDimensionGroups},(f,u)=>u+1);if(a.length<=1)throw new Error("Please provide two or more dimension groups");const s=t.voxelManager,c=o.voxelManager,l=TU[e];if(!l)throw new Error(`Unsupported operation: ${e}`);l(s,a,(f,u)=>{c.setAtIndex(f,u)}),c.resetModifiedSlices();for(let f=0;f{for(const[c,l]of s.entries())if(l!==void 0)return c;return-1};let a=o(n);for(;a!==-1;){const s=[a];for(;n.has(a);){const c=n.get(a)[1];n.has(c)&&s.push(c),n.delete(a),a=c}i.push(s),a=o(n)}return i.length?i:void 0}function bU(t){const e=DU(t);if(!e)return;const r=t.getPoints().getData();return e.map(n=>n.map(i=>EU(r,i)))}const Xve=Object.freeze(Object.defineProperty({__proto__:null,getPoint:EU,getPolyDataPointIndexes:DU,getPolyDataPoints:bU},Symbol.toStringTag,{value:"Module"}));var pa;(function(t){t.Top="top",t.Left="left",t.Bottom="bottom",t.Right="right"})(pa||(pa={}));const Yve=Object.freeze(Object.defineProperty({__proto__:null,get ColorbarRangeTextPosition(){return pa}},Symbol.toStringTag,{value:"Module"})),Vc=t=>t&&t.upper>t.lower,fy=t=>!!t&&t.width>0&&t.height>0,Xp=(t,e)=>!!t&&!!e&&t.lower===e.lower&&t.upper===e.upper,IU=(t,e)=>!!t&&!!e&&t.width===e.width&&t.height===e.height,Jve=(t,e,r)=>[t[0]*(1-r)+e[0]*r,t[1]*(1-r)+e[1]*r,t[2]*(1-r)+e[2]*r],{clamp:Zve}=Mn;class Q4{constructor(e){Q4.validateProps(e);const{colormap:r,size:n={width:20,height:100},imageRange:i={lower:0,upper:1},voiRange:o={lower:0,upper:1},container:a,showFullPixelValueRange:s=!1}=e;this._colormap=r,this._imageRange=i,this._voiRange=o,this._showFullImageRange=s,this._canvas=this._createRootElement(n),a&&this.appendTo(a)}get colormap(){return this._colormap}set colormap(e){this._colormap=e,this.render()}get size(){const{width:e,height:r}=this._canvas;return{width:e,height:r}}set size(e){const{_canvas:r}=this;!fy(e)||IU(r,e)||(this._setCanvasSize(r,e),this.render())}get imageRange(){return{...this._imageRange}}set imageRange(e){!Vc(e)||Xp(e,this._imageRange)||(this._imageRange=e,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(e){!Vc(e)||Xp(e,this._voiRange)||(this._voiRange=e,this.render())}get showFullImageRange(){return this._showFullImageRange}set showFullImageRange(e){e!==this._showFullImageRange&&(this._showFullImageRange=e,this.render())}appendTo(e){e.appendChild(this._canvas),this.render()}dispose(){const{_canvas:e}=this,{parentElement:r}=e;r==null||r.removeChild(e)}static validateProps(e){const{size:r,imageRange:n,voiRange:i}=e;if(r&&!fy(r))throw new Error('Invalid "size"');if(n&&!Vc(n))throw new Error('Invalid "imageRange"');if(i&&!Vc(i))throw new Error('Invalid "voiRange"')}_setCanvasSize(e,r){const{width:n,height:i}=r;e.width=n,e.height=i,Object.assign(e.style,{width:`${n}px`,height:`${i}px`})}_createRootElement(e){const r=document.createElement("canvas");return Object.assign(r.style,{position:"absolute",top:"0",left:"0",pointerEvents:"none",boxSizing:"border-box"}),this._setCanvasSize(r,e),r}render(){if(!this._canvas.isConnected)return;const{_colormap:e}=this,{RGBPoints:r}=e,n=r.length/4,i=v=>{const y=4*v;if(!(v<0||v>=n))return{index:v,position:r[y],color:[r[y+1],r[y+2],r[y+3]]}},{width:o,height:a}=this._canvas,s=this._canvas.getContext("2d");if(!s)return;const c=o>a,l=c?o:a,{_voiRange:f}=this,u=this._showFullImageRange?this._imageRange:{...f};let d,h=i(0);const g=(u.upper-u.lower)/(l-1);let p=u.lower;for(let v=0;vZve(Math.round(x*255),0,255));s.fillStyle=`rgb(${w[0]}, ${w[1]}, ${w[2]})`,c?s.fillRect(v,0,1,a):s.fillRect(0,a-v-1,o,1),p+=g}}}const pf={FONT:"10px Arial",COLOR:"white",TICK_SIZE:5,TICK_WIDTH:1,TICK_LABEL_MARGIN:3,MAX_NUM_TICKS:8,TICKS_STEPS:[1,2.5,5,10]};class eE{constructor(e){eE.validateProps(e);const{top:r=0,left:n=0,size:i={width:20,height:100},imageRange:o={lower:0,upper:1},voiRange:a={lower:0,upper:1},ticks:s,container:c,showFullPixelValueRange:l=!1}=e,{style:f,position:u}=s??{};this._imageRange=o,this._voiRange=a,this._font=(f==null?void 0:f.font)??pf.FONT,this._color=(f==null?void 0:f.color)??pf.COLOR,this._tickSize=(f==null?void 0:f.tickSize)??pf.TICK_SIZE,this._tickWidth=(f==null?void 0:f.tickWidth)??pf.TICK_WIDTH,this._labelMargin=(f==null?void 0:f.labelMargin)??pf.TICK_LABEL_MARGIN,this._maxNumTicks=(f==null?void 0:f.maxNumTicks)??pf.MAX_NUM_TICKS,this._rangeTextPosition=u??pa.Right,this._showFullPixelValueRange=l,this._canvas=this._createCanvasElement(i,r,n),c&&this.appendTo(c)}get size(){const{width:e,height:r}=this._canvas;return{width:e,height:r}}set size(e){const{_canvas:r}=this;!fy(e)||IU(r,e)||(this._setCanvasSize(r,e),this.render())}get top(){return Number.parseInt(this._canvas.style.top)}set top(e){const{_canvas:r}=this,n=this.top;e!==n&&(r.style.top=`${e}px`,this.render())}get left(){return Number.parseInt(this._canvas.style.left)}set left(e){const{_canvas:r}=this,n=this.left;e!==n&&(r.style.left=`${e}px`,this.render())}get imageRange(){return{...this._imageRange}}set imageRange(e){!Vc(e)||Xp(e,this._imageRange)||(this._imageRange=e,this.render())}get voiRange(){return{...this._voiRange}}set voiRange(e){!Vc(e)||Xp(e,this._voiRange)||(this._voiRange=e,this.render())}get tickSize(){return this._tickSize}set tickSize(e){e!==this._tickSize&&(this._tickSize=e,this.render())}get tickWidth(){return this._tickWidth}set tickWidth(e){e!==this._tickWidth&&(this._tickWidth=e,this.render())}get color(){return this._color}set color(e){e!==this._color&&(this._color=e,this.render())}get showFullPixelValueRange(){return this._showFullPixelValueRange}set showFullPixelValueRange(e){e!==this._showFullPixelValueRange&&(this._showFullPixelValueRange=e,this.render())}get visible(){return this._canvas.style.display==="block"}set visible(e){e!==this.visible&&(this._canvas.style.display=e?"block":"none",e&&this.render())}appendTo(e){e.appendChild(this._canvas),this.render()}static validateProps(e){const{size:r,imageRange:n,voiRange:i}=e;if(r&&!fy(r))throw new Error('Invalid "size"');if(n&&!Vc(n))throw new Error('Invalid "imageRange"');if(i&&!Vc(i))throw new Error('Invalid "voiRange"')}_setCanvasSize(e,r){const{width:n,height:i}=r;e.width=n,e.height=i,Object.assign(e.style,{width:`${n}px`,height:`${i}px`})}_createCanvasElement(e,r,n){const i=document.createElement("canvas");return Object.assign(i.style,{display:"none",position:"absolute",boxSizing:"border-box",top:`${r}px`,left:`${n}px`}),this._setCanvasSize(i,e),i}_getTicks(e){const{lower:r,upper:n}=e,o=(n-r)/(this._maxNumTicks-1),a=Math.pow(10,-Math.floor(Math.log10(Math.abs(o)))),s=o*a,l=pf.TICKS_STEPS.find(g=>g>=s)/a,f=Math.ceil(n/l)*l,u=Math.floor(r/l)*l,d=Math.round((f-u)/l)+1,h=[];for(let g=0;g=n,o=i?r:n,a=e.getContext("2d"),{_voiRange:s}=this,c=this._showFullPixelValueRange?this._imageRange:{...s},l=c.upper-c.lower,{ticks:f}=this._getTicks(c);a.clearRect(0,0,r,n),a.font=this._font,a.textBaseline=i?"top":"middle",a.textAlign=i?"center":"left",a.fillStyle=this._color,a.strokeStyle=this._color,a.lineWidth=this.tickWidth,f.forEach(u=>{let d=Math.round(o*((u-c.lower)/l));if(i||(d=n-d),d<0||d>o)return;const h=u.toString(),g=a.measureText(h);let p;i?this._rangeTextPosition===pa.Top?p=this._getTopTickInfo({position:d,labelMeasure:g}):p=this._getBottomTickInfo({position:d,labelMeasure:g}):this._rangeTextPosition===pa.Left?p=this._getLeftTickInfo({position:d,labelMeasure:g}):p=this._getRightTickInfo({position:d});const{labelPoint:v,tickPoints:y}=p,{start:m,end:w}=y;return a.beginPath(),a.moveTo(m[0],m[1]),a.lineTo(w[0],w[1]),a.fillText(h,v[0],v[1]),a.stroke(),d})}}function Qve(t,e,r){return(t>=e?[pa.Top,pa.Bottom]:[pa.Left,pa.Right]).includes(r)}class eye{constructor({id:e,container:r}){this._containerResizeCallback=n=>{let i,o;const{contentRect:a,contentBoxSize:s}=n[0];a?(i=a.width,o=a.height):s!=null&&s.length&&(i=s[0].inlineSize,o=s[0].blockSize),this._containerSize={width:i,height:o},this.onContainerResize()},this._id=e,this._containerSize={width:0,height:0},this._rootElement=this.createRootElement(e),this._containerResizeObserver=new ResizeObserver(this._containerResizeCallback),r&&this.appendTo(r)}get id(){return this._id}get rootElement(){return this._rootElement}appendTo(e){const{_rootElement:r,_containerResizeObserver:n}=this,{parentElement:i}=r;!e||e===i||(i&&n.unobserve(i),e.appendChild(r),n.observe(e))}destroy(){const{_rootElement:e,_containerResizeObserver:r}=this,{parentElement:n}=e;n==null||n.removeChild(e),r.disconnect()}get containerSize(){return{...this._containerSize}}createRootElement(e){const r=document.createElement("div");return r.id=e,r.classList.add("widget"),Object.assign(r.style,{width:"100%",height:"100%"}),r}onContainerResize(){}}const Qh={MULTIPLIER:1,RANGE_TEXT_POSITION:pa.Right,TICKS_BAR_SIZE:50};class Yp extends eye{constructor(e){var r;super(e),this._isMouseOver=!1,this._isInteracting=!1,this._mouseOverCallback=n=>{this._isMouseOver=!0,this.showTicks(),n.stopPropagation()},this._mouseOutCallback=n=>{this._isMouseOver=!1,this.hideTicks(),n.stopPropagation()},this._mouseDownCallback=n=>{this._isInteracting=!0,this.showTicks(),this._addVOIEventListeners(n),n.stopPropagation()},this._mouseDragCallback=(n,i)=>{const o=this.getVOIMultipliers(),a=this._getPointsFromMouseEvent(n),{points:s,voiRange:c}=i,l=Ga(qt(),a.local,s.local),f=l[0]*o[0],u=l[1]*o[1];if(!f&&!u)return;const{lower:d,upper:h}=c;let{windowWidth:g,windowCenter:p}=m1(d,h);g=Math.max(g+f,1),p+=u;const v=lu(g,p);this.voiRange=v,n.stopPropagation(),n.preventDefault()},this._mouseUpCallback=n=>{this._isInteracting=!1,this.hideTicks(),this._removeVOIEventListeners(),n.stopPropagation()},this._eventListenersManager=new FA,this._colormaps=Yp.getColormapsMap(e),this._activeColormapName=Yp.getInitialColormapName(e),this._canvas=this._createCanvas(e),this._ticksBar=this._createTicksBar(e),this._rangeTextPosition=((r=e.ticks)==null?void 0:r.position)??Qh.RANGE_TEXT_POSITION,this._canvas.appendTo(this.rootElement),this._ticksBar.appendTo(this.rootElement),this._addRootElementEventListeners()}get activeColormapName(){return this._activeColormapName}set activeColormapName(e){if(e===this._activeColormapName)return;const r=this._colormaps.get(e);if(!r){console.warn(`Invalid colormap name (${e})`);return}this._activeColormapName=e,this._canvas.colormap=r}get imageRange(){return this._canvas.imageRange}set imageRange(e){this._canvas.imageRange=e,this._ticksBar.imageRange=e}get voiRange(){return this._canvas.voiRange}set voiRange(e){const{voiRange:r}=this._canvas;!Vc(e)||Xp(e,r)||(this._canvas.voiRange=e,this._ticksBar.voiRange=e,this.onVoiChange(e))}get showFullImageRange(){return this._canvas.showFullImageRange}set showFullImageRange(e){this._canvas.showFullImageRange=e,this._ticksBar.showFullPixelValueRange=e}destroy(){super.destroy(),this._eventListenersManager.reset()}createRootElement(){const e=document.createElement("div");return Object.assign(e.style,{position:"relative",fontSize:"0",width:"100%",height:"100%"}),e}onContainerResize(){super.onContainerResize(),this.updateTicksBar(),this._canvas.size=this.containerSize}getVOIMultipliers(){return[Qh.MULTIPLIER,Qh.MULTIPLIER]}onVoiChange(e){}showTicks(){this.updateTicksBar(),this._ticksBar.visible=!0}hideTicks(){this._isInteracting||this._isMouseOver||(this._ticksBar.visible=!1)}static getColormapsMap(e){const{colormaps:r}=e;return r.reduce((n,i)=>n.set(i.Name,i),new Map)}static getInitialColormapName(e){const{activeColormapName:r,colormaps:n}=e;return!!r&&n.some(o=>o.Name===r)?r:n[0].Name}_createCanvas(e){const{imageRange:r,voiRange:n,showFullPixelValueRange:i}=e,o=this._colormaps.get(this._activeColormapName);return new Q4({colormap:o,imageRange:r,voiRange:n,showFullPixelValueRange:i})}_createTicksBar(e){const r=e.ticks;return new eE({imageRange:e.imageRange,voiRange:e.voiRange,ticks:r,showFullPixelValueRange:e.showFullPixelValueRange})}_getPointsFromMouseEvent(e){const{rootElement:r}=this,n=[e.clientX,e.clientY],i=[e.pageX,e.pageY],o=r.getBoundingClientRect(),a=[i[0]-o.left-window.pageXOffset,i[1]-o.top-window.pageYOffset];return{client:n,page:i,local:a}}updateTicksBar(){const{width:e,height:r}=this.containerSize;if(e===0&&r===0)return;const{_ticksBar:n,_rangeTextPosition:i}=this,o=e>=r,a=o?e:Qh.TICKS_BAR_SIZE,s=o?Qh.TICKS_BAR_SIZE:r;if(!Qve(e,r,i))throw new Error("Invalid rangeTextPosition value for the current colobar orientation");let c,l;n.size={width:a,height:s},o?(l=0,c=i===pa.Top?-s:r):(c=0,l=i===pa.Left?-a:e),n.top=c,n.left=l}_addRootElementEventListeners(){const{_eventListenersManager:e}=this,{rootElement:r}=this;e.addEventListener(r,"mouseover",this._mouseOverCallback),e.addEventListener(r,"mouseout",this._mouseOutCallback),e.addEventListener(r,"mousedown",this._mouseDownCallback)}_addVOIEventListeners(e){const{_eventListenersManager:r}=this,n=this._getPointsFromMouseEvent(e),i={...this._canvas.voiRange},o={points:n,voiRange:i};this._removeVOIEventListeners(),r.addEventListener(document,"voi.mouseup",this._mouseUpCallback),r.addEventListener(document,"voi.mousemove",a=>this._mouseDragCallback(a,o))}_removeVOIEventListeners(){const{_eventListenersManager:e}=this;e.removeEventListener(document,"voi.mouseup"),e.removeEventListener(document,"voi.mousemove")}}const g3=4;function tye(t,e,r){if(ZA(t,e)==="PT"){const{clientWidth:i,clientHeight:o}=t.element,a=5/Math.max(i,o),s=al(t,e),{fixedPTWindowWidth:c=!0}=r??{},l=c?0:a;return s?[l,a]:[l,g3]}return[g3,g3]}const{Events:Rl}=ja,Wm={lower:-1e3,upper:1e3};class Xd extends Yp{constructor(e){const{element:r,volumeId:n}=e,i=Xd._getImageRange(r,n),o=Xd._getVOIRange(r,n);super({...e,imageRange:i,voiRange:o}),this.autoHideTicks=()=>{if(this._hideTicksTimeoutId)return;const a=this._hideTicksTime-Date.now();a<=0?this.hideTicks():this._hideTicksTimeoutId=window.setTimeout(()=>{this._hideTicksTimeoutId=0,this.autoHideTicks()},a)},this._stackNewImageCallback=()=>{this.imageRange=Xd._getImageRange(this._element)},this._imageVolumeModifiedCallback=a=>{const{volumeId:s}=a.detail;if(s!==this._volumeId)return;const{_element:c}=this;this.imageRange=Xd._getImageRange(c,s)},this._viewportVOIModifiedCallback=a=>{const{viewportId:s,volumeId:c,range:l,colormap:f}=a.detail,{viewport:u}=this.enabledElement;s!==u.id||c!==this._volumeId||(this.voiRange=l,f&&(this.activeColormapName=f.name),this.showAndAutoHideTicks())},this._viewportColormapModifiedCallback=a=>{const{viewportId:s,colormap:c,volumeId:l}=a.detail,{viewport:f}=this.enabledElement;s!==f.id||l!==this._volumeId||(this.activeColormapName=c.name)},this._element=r,this._volumeId=n,this._addCornerstoneEventListener()}get element(){return this._element}get enabledElement(){return Ce(this._element)}getVOIMultipliers(){const{viewport:e}=this.enabledElement;return tye(e,this._volumeId)}onVoiChange(e){super.onVoiChange(e);const{viewport:r}=this.enabledElement;if(r instanceof lr)r.setProperties({voiRange:e}),r.render();else if(r instanceof ur){const{_volumeId:n}=this,i=y1(n);r.setProperties({voiRange:e},n),i.forEach(o=>o.render())}}static _getImageRange(e,r){const n=Ce(e),{viewport:i}=n,o=i.getImageActor(r);if(!o)return Wm;const s=o.getMapper().getInputData().getPointData().getScalars();let c;if(s)c=s.getRange();else{if(!r)throw new Error("volumeId is required when scalarData is not available");const l=Le.getVolume(r),[f,u]=l.voxelManager.getRange();c=[f,u]}return c[0]===0&&c[1]===0?Wm:{lower:c[0],upper:c[1]}}static _getVOIRange(e,r){const n=Ce(e),{viewport:i}=n,o=i.getImageActor(r);if(!o)return Wm;const a=o.getProperty().getRGBTransferFunction(0).getRange();return a[0]===0&&a[1]===0?Wm:{lower:a[0],upper:a[1]}}showAndAutoHideTicks(e=1e3){this._hideTicksTime=Date.now()+e,this.showTicks(),this.autoHideTicks()}_addCornerstoneEventListener(){const{_element:e}=this;Ke.addEventListener(Rl.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),e.addEventListener(Rl.STACK_NEW_IMAGE,this._stackNewImageCallback),e.addEventListener(Rl.VOI_MODIFIED,this._viewportVOIModifiedCallback),e.addEventListener(Rl.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}destroy(){super.destroy();const{_element:e}=this;Ke.removeEventListener(Rl.IMAGE_VOLUME_MODIFIED,this._imageVolumeModifiedCallback),e.removeEventListener(Rl.STACK_NEW_IMAGE,this._stackNewImageCallback),e.removeEventListener(Rl.VOI_MODIFIED,this._viewportVOIModifiedCallback),e.removeEventListener(Rl.COLORMAP_MODIFIED,this._viewportColormapModifiedCallback)}}const nye=Object.freeze(Object.defineProperty({__proto__:null,Colorbar:Yp,Enums:Yve,ViewportColorbar:Xd},Symbol.toStringTag,{value:"Module"}));function OU(t,e,r,n,i){const o=[];let a=0;const s=t.scalarData;let c,l,f;if(t.color)for(l=0;lBF(s,f),imageData:t})}function cye(t,e,r){const[n,i]=t,o=bt((n[0]+i[0])/2,(n[1]+i[1])/2,(n[2]+i[2])/2),a=ki(n,i)/2;let s;if(!r){const c=UC(e,o),l=e.getSpacing(),f=Math.min(...l),u=Math.ceil(a/f);return s=[[c[0]-u,c[0]+u],[c[1]-u,c[1]+u],[c[2]-u,c[2]+u]],{boundsIJK:s,centerWorld:o,radiusWorld:a}}return s=lye(e,r,t,o,a),{boundsIJK:s,centerWorld:o,radiusWorld:a}}function lye(t,e,r,n,i){const[o,a]=r,s=t.getDimensions(),c=e.getCamera(),l=bt(c.viewUp[0],c.viewUp[1],c.viewUp[2]),f=bt(c.viewPlaneNormal[0],c.viewPlaneNormal[1],c.viewPlaneNormal[2]),u=Ve();Rn(u,l,f);const d=Ve(),h=Ve();Tn(d,a,f,i),Tn(h,o,f,-i),Tn(d,d,u,-i),Tn(h,h,u,i);const g=[UC(t,d),UC(t,h)];return Su(g,s)}function RU(t){if(!Array.isArray(t)||t.length!==9)throw new Error("Matrix must be an array of 9 numbers");if(!t.every(e=>typeof e=="number"&&!isNaN(e)))throw new Error("Matrix must contain only valid numbers")}function LU(t){RU(t);const e=[[t[0],t[1],t[2]],[t[3],t[4],t[5]],[t[6],t[7],t[8]]],r=e[0][0]*(e[1][1]*e[2][2]-e[1][2]*e[2][1])-e[0][1]*(e[1][0]*e[2][2]-e[1][2]*e[2][0])+e[0][2]*(e[1][0]*e[2][1]-e[1][1]*e[2][0]);if(Math.abs(r)<1e-10)throw new Error("Matrix is not invertible (determinant is zero)");const n=[[e[1][1]*e[2][2]-e[1][2]*e[2][1],-(e[0][1]*e[2][2]-e[0][2]*e[2][1]),e[0][1]*e[1][2]-e[0][2]*e[1][1]],[-(e[1][0]*e[2][2]-e[1][2]*e[2][0]),e[0][0]*e[2][2]-e[0][2]*e[2][0],-(e[0][0]*e[1][2]-e[0][2]*e[1][0])],[e[1][0]*e[2][1]-e[1][1]*e[2][0],-(e[0][0]*e[2][1]-e[0][1]*e[2][0]),e[0][0]*e[1][1]-e[0][1]*e[1][0]]],i=[];for(let o=0;o<3;o++)for(let a=0;a<3;a++)i.push(n[o][a]/r);return i}function p3(t){const e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);return t.map(r=>r/e)}function uye(t){RU(t);const e=t.slice(0,3),r=t.slice(3,6),n=t.slice(6,9),i=p3(e),o=p3(r),a=p3(n),s={x:[1,0,0],y:[0,1,0],z:[0,0,1]},c=1e-10,l=i.every((u,d)=>Math.abs(u-s.x[d])Math.abs(u-s.y[d])Math.abs(u-s.z[d]){Ai(s,s,Ni(Ve(),[-o[0],-o[1],-o[2]],a))}),e instanceof lr&&(t.metadata.referencedImageId=e.getCurrentImageId()),t}function pye(t,e,r){const n=e*r,i=t.length/n;if(![1,3,4].includes(i))throw new Error("Buffer must be 1, 3, or 4 channels per pixel");const o=Array.from({length:r},()=>new Array(e).fill(!1));for(let v=0;v0){x=!0;break}o[v][y]=x}const a=Array.from({length:r},()=>new Array(e).fill(0));let s=0;const c={};for(let v=0;vC<0||C>=e||S<0||S>=r?!1:o[S][C]&&a[S][C]===0;let w=0;$4(m,[y,v],{onFlood:(C,S)=>{a[S][C]=s,w++},diagonals:!1}),c[s]=w}if(s===0)return[];const l=Object.keys(c).reduce((v,y)=>c[v]>c[y]?v:y);function f(v,y){if(a[y][v]!==+l)return!1;for(const[m,w]of[[1,0],[-1,0],[0,1],[0,-1]]){const x=v+m,C=y+w;if(x<0||x>=e||C<0||C>=r||a[C][x]!==+l)return!0}return!1}let u=null;e:for(let v=0;vx[0]===v&&x[1]===y);m<0&&(m=0);let w=null;for(let x=1;x<=8;x++){const[C,S]=d[(m+x)%8],_=g[0]+C,T=g[1]+S;if(_>=0&&_=0&&T(y+1)%r,i=(y,m)=>{const w=[];for(let x=y;w.push(x),x!==m;x=n(x));return w};let o=0,a=0;for(let y=1;yt[a][0]&&(a=y);const s=t[o],c=t[a],l=i(o,a),f=i(a,o),u=Math.min(...t.map(y=>y[1])),d=l.some(y=>t[y][1]===u)?l:f,h=Math.min(...d.map(y=>t[y][1]));let g=d.map(y=>t[y]).filter(y=>Math.abs(y[1]-h)<=e);g.length<2&&(g=d.map(y=>t[y]).sort((y,m)=>y[1]-m[1]).slice(0,2));const p=g.reduce((y,m)=>m[0]m[0]>y[0]?m:y,g[0]);return{P1:p,P2:s,P3:c,P4:v}}function yye(t,e,r,n,i,o={}){const{maxDist:a=15,slack:s=2}=o,c={P1:{dx:-1,dy:-1},P2:{dx:-1,dy:1},P3:{dx:1,dy:1},P4:{dx:1,dy:-1}};function l(f,{dx:u,dy:d},h=5){const g=u<0?f[0]-a:f[0]-s,p=u<0?f[0]+s:f[0]+a,v=d<0?f[1]-a:f[1]-s,y=d<0?f[1]+s:f[1]+a;let m=f;for(const[w,x]of i){if(wp||xy)continue;const C=Math.round(w),S=Math.round(x);if(C<0||C>=e||S<0||S>=r)continue;const _=(C-m[0])*u,T=(S-m[0])*d;t[S*e+C]>h&&(_>0||T>0)&&(m=[w,x])}return m}return{P1:l(n.P1,c.P1),P2:l(n.P2,c.P2),P3:l(n.P3,c.P3),P4:l(n.P4,c.P4)}}function wye(t,e,r,n,i){const o=vye(n);return yye(t,e,r,o,i,{maxDist:20})}function ZD(t,e){return Math.atan2(e[1]-t[1],e[0]-t[0])}function xye(t){const{P1:e,P2:r,P3:n,P4:i}=t,o=Zv(e,r,i,n,!0);if(!o)throw new Error("Fan edges appear parallel — no apex found");const a=o;let s=ZD(a,e)*(180/Math.PI),c=ZD(a,i)*(180/Math.PI);if(c<=s){const p=s;s=c,c=p}const l=Math.hypot(e[0]-a[0],e[1]-a[1]),f=Math.hypot(i[0]-a[0],i[1]-a[1]),u=Math.hypot(r[0]-a[0],r[1]-a[1]),d=Math.hypot(n[0]-a[0],n[1]-a[1]),h=Math.min(l,f),g=Math.max(u,d);return{center:a,startAngle:s,endAngle:c,innerRadius:h,outerRadius:g}}function xg(t,e,r,n,i={}){const{strokeStyle:o="#f00",lineWidth:a=2,quality:s=.92}=i,c=document.createElement("canvas");c.width=e,c.height=r;const l=c.getContext("2d"),f=e*r,u=t.length/f,d=l.createImageData(e,r),h=d.data;for(let g=0;g0){l.strokeStyle=o,l.lineWidth=a,l.beginPath(),l.moveTo(n[0][0]+.5,n[0][1]+.5);for(let g=1;g=h;C-=.01){const S=o[0]+l*Math.cos(C),_=o[1]+l*Math.sin(C);v.lineTo(S,_)}return v.closePath(),v.strokeStyle=f,v.lineWidth=u,v.stroke(),p.toDataURL("image/jpeg",d)}function Sye(t,e=5){const{contour:r,simplified:n,hull:i,refined:o,fanGeometry:a}=nE(t),{pixelData:s,width:c,height:l}=tE(t)||{};if(!s)return;let f;e===1?f=xg(s,c,l,r):e===2?f=xg(s,c,l,n):e===3?f=xg(s,c,l,i):e===4?f=xg(s,c,l,[o.P1,o.P2,o.P3,o.P4]):f=Cye(s,c,l,a,{strokeStyle:"#f00",lineWidth:3,quality:.95}),NU(f,"contour.jpg")}function nE(t){const{pixelData:e,width:r,height:n}=tE(t)||{};if(!e)return;const i=pye(e,r,n),{simplified:o,hull:a}=mye(i),s=wye(e,r,n,a,o),c=xye({P1:s.P1,P2:s.P2,P3:s.P3,P4:s.P4});return{contour:i,simplified:o,hull:a,refined:s,fanGeometry:c}}const _ye=Object.freeze(Object.defineProperty({__proto__:null,calculateFanGeometry:nE,default:NU,downloadFanJpeg:Sye,exportContourJpeg:xg,getPixelData:tE},Symbol.toStringTag,{value:"Module"})),Tye=an,Eye=Object.freeze(Object.defineProperty({__proto__:null,AnnotationMultiSlice:O1e,IslandRemoval:nd,annotationHydration:gfe,boundingBox:D1e,calibrateImageSpacing:E1e,cine:wve,contourSegmentation:Yde,contours:ame,debounce:gh,drawing:Qhe,dynamicVolume:qve,geometricSurfaceUtils:hye,getAnnotationNearPoint:S1e,getAnnotationNearPointOnEnabledElement:cF,getCalibratedAspect:I4,getCalibratedLengthUnitsAndScale:ta,getCalibratedProbeUnitsAndValue:iy,getClosestImageIdForStackViewport:a4,getOrCreateImageVolume:B5,getPixelValueUnits:sl,getPixelValueUnitsImageId:yV,getSphereBoundsInfo:fF,getViewportForAnnotation:N2,isObject:r4,math:fde,moveAnnotationToViewPlane:gye,normalizeViewportPlane:kF,orientation:uve,planar:V0e,planarFreehandROITool:_ve,pointInSurroundingSphereCallback:sye,pointToString:dF,polyDataUtils:Xve,rectangleROITool:Tve,roundNumber:Tye,segmentation:sve,setAnnotationLabel:AU,stackContextPrefetch:Bve,stackPrefetch:Lve,throttle:_o,touch:Rue,triggerAnnotationRender:ph,triggerAnnotationRenderForToolGroupIds:hV,triggerAnnotationRenderForViewportIds:Pe,triggerEvent:at,usFanExtraction:_ye,viewport:Gve,viewportFilters:Ade,voi:aye},Symbol.toStringTag,{value:"Module"})),Dye=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));function kU(t,e){const r=Zn;t.forEach(n=>{r.updateSegmentation(n.segmentationId,n.payload),e||Ta(n.segmentationId)})}function bye(t,e,r){Zn.setSegmentationRepresentationVisibility(t,e,r)}function Iye(t,e,r){const n=Jo(t,e);n&&n.forEach(i=>{bye(t,{segmentationId:i.segmentationId,type:i.type},r)})}function Oye(t,e){return mV(t,e)}function Mye(t,e,r,n){const i=Jo(t,e);i&&(i.forEach(o=>{o.segments[r].visible=n}),k5(e.segmentationId),Gs(t,e.segmentationId))}function Pye(t,e,r){return!VU(t,e).has(r)}function VU(t,e){const r=t4(t,e);return r?Object.entries(r.segments).reduce((i,[o,a])=>(a.visible||i.add(Number(o)),i),new Set):new Set}const Rye=Object.freeze(Object.defineProperty({__proto__:null,getHiddenSegmentIndices:VU,getSegmentIndexVisibility:Pye,getSegmentationRepresentationVisibility:Oye,setSegmentIndexVisibility:Mye,setSegmentationRepresentationVisibility:Iye},Symbol.toStringTag,{value:"Module"}));function Lye(t){return va.getStyle(t)}function Aye(t,e){va.setStyle(t,e),!t.viewportId&&!t.segmentationId&&U5().forEach(n=>{wh(n.segmentationId)}),Gs(t.viewportId,t.segmentationId,t.type)}function Nye(t,e){va.setRenderInactiveSegmentations(t,e),wh(t),SF(t).forEach(n=>{Gs(t,n.segmentationId)})}function kye(t){return va.getRenderInactiveSegmentations(t)}function Vye(){va.resetToGlobalStyle(),wh()}function Fye(t){return va.hasCustomStyle(t)}const Uye=Object.freeze(Object.defineProperty({__proto__:null,getRenderInactiveSegmentations:kye,getStyle:Lye,hasCustomStyle:Fye,resetToGlobalStyle:Vye,setRenderInactiveSegmentations:Nye,setStyle:Aye},Symbol.toStringTag,{value:"Module"})),Bye=Object.freeze(Object.defineProperty({__proto__:null,color:Pge,style:Uye,visibility:Rye},Symbol.toStringTag,{value:"Module"}));function dy(t,e){const r=Ln(t);typeof e=="string"&&(console.warn("segmentIndex is a string, converting to number"),e=Number(e)),Object.values(r.segments).forEach(i=>{i.active=!1}),r.segments[e]||(r.segments[e]={segmentIndex:e,label:"",locked:!1,cachedStats:{},active:!1}),r.segments[e].active!==!0&&(r.segments[e].active=!0,Ta(t));const n=yh(t);n.forEach(i=>{Jo(i,{segmentationId:t}).forEach(a=>{a.segments[e]||(a.segments[e]={visible:!0})})}),n.forEach(i=>{const o=Or(i);eU(o.id)})}const Gye=Object.freeze(Object.defineProperty({__proto__:null,getActiveSegmentIndex:ea,setActiveSegmentIndex:dy},Symbol.toStringTag,{value:"Module"}));async function Wye(t){const e=nfe(t);return Ta(t.segmentationId),e}function FU(t,e){const r=Ln(t);if(r.representationData.Labelmap){const{representationData:n}=r,i=n.Labelmap;("imageIds"in i||"volumeId"in i)&&("imageIds"in i?i.imageIds.map(a=>Le.getImage(a)):[Le.getVolume(i.volumeId)]).forEach(a=>{if(!a)return;const{voxelManager:s}=a;s.forEach(({value:c,index:l})=>{c===e&&s.setAtIndex(l,0)})}),io(t)}else throw new Error("Invalid segmentation type, only labelmap is supported right now")}function zye(t,e,r={setNextSegmentAsActive:!0}){FU(t,e);const n=ea(t)===e,i=Ln(t),{segments:o}=i;delete o[e];const a={...o};if(kU([{segmentationId:t,payload:{segments:a}}]),n&&r.setNextSegmentAsActive){const c=Object.keys(o).map(Number).sort((d,h)=>d-h),l=c.indexOf(e),f=c[l+1],u=c[l-1];f!==void 0?dy(t,f):u!==void 0&&dy(t,u)}yh(t).forEach(c=>{Jo(c,{segmentationId:t}).forEach(f=>{delete f.segments[e]})})}function $ye(t){const e=Zn,r=Ln(t);return e.getLabelmapImageIds(r.representationData)}const jye={clearSegmentValue:FU,convertStackToVolumeLabelmap:Wye,computeVolumeLabelmapFromStack:fU,convertVolumeToStackLabelmap:eve},Hye=Object.freeze(Object.defineProperty({__proto__:null,activeSegmentation:w0e,addContourRepresentationToViewport:K4,addContourRepresentationToViewportMap:X2e,addLabelmapRepresentationToViewport:lU,addLabelmapRepresentationToViewportMap:Y2e,addRepresentationData:n4,addSegmentationRepresentations:Th,addSegmentations:gF,addSurfaceRepresentationToViewport:uU,addSurfaceRepresentationToViewportMap:J2e,config:Bye,defaultSegmentationStateManager:Zn,getActiveSegmentation:ed,getCurrentLabelmapImageIdsForViewport:Qc,getLabelmapImageIds:$ye,getLabelmapImageIdsForImageId:u0e,helpers:jye,removeAllSegmentationRepresentations:vF,removeAllSegmentations:CF,removeContourRepresentation:wF,removeLabelmapRepresentation:yF,removeSegment:zye,removeSegmentation:B4,removeSegmentationRepresentation:Ch,removeSegmentationRepresentations:pF,removeSurfaceRepresentation:xF,segmentIndex:Gye,segmentLocking:Ige,segmentationStyle:va,state:K1e,strategies:e2e,triggerSegmentationEvents:que,updateSegmentations:kU},Symbol.toStringTag,{value:"Module"}));class rE{constructor(e){this._controlPoints=[],this._invalidated=!1,this._length=0,this._controlPoints=[],this._resolution=(e==null?void 0:e.resolution)??20,this._fixedResolution=(e==null?void 0:e.fixedResolution)??!1,this._closed=(e==null?void 0:e.closed)??!1,this._invalidated=!0}get controlPoints(){return this._controlPoints}get numControlPoints(){return this._controlPoints.length}get resolution(){return this._resolution}set resolution(e){this._fixedResolution||this._resolution===e||(this._resolution=e,this.invalidated=!0)}get fixedResolution(){return this._fixedResolution}get closed(){return this._closed}set closed(e){this._closed!==e&&(this._closed=e,this.invalidated=!0)}get aabb(){return this._update(),this._aabb}get length(){return this._update(),this._length}get invalidated(){return this._invalidated}set invalidated(e){this._invalidated=e}hasTangentPoints(){return!1}addControlPoint(e){this._controlPoints.push([e[0],e[1]]),this.invalidated=!0}addControlPoints(e){e.forEach(r=>this.addControlPoint(r))}addControlPointAtU(e){const r=this._getLineSegmentAt(e),{start:n,end:i}=r.points,o=Math.floor(e),a=this._curveSegments[o],s=e-Math.floor(o),c=[n[0]+s*(i[0]-n[0]),n[1]+s*(i[1]-n[1])],l=this._controlPoints.indexOf(a.controlPoints.p1)+1;return this._controlPoints.splice(l,0,c),this.invalidated=!0,{index:l,point:c}}deleteControlPointByIndex(e){const r=this._closed?3:1;return e>=0&&er?(this._controlPoints.splice(e,1),this.invalidated=!0,!0):!1}clearControlPoints(){this._controlPoints=[],this.invalidated=!0}setControlPoints(e){this.clearControlPoints(),this.addControlPoints(e)}updateControlPoint(e,r){if(e<0||e>=this._controlPoints.length)throw new Error("Index out of bounds");this._controlPoints[e]=[...r],this.invalidated=!0}getControlPoints(){return this._controlPoints.map(e=>[e[0],e[1]])}getClosestControlPoint(e){const r=this._controlPoints;let n=1/0,i=-1;for(let o=0,a=r.length;ou.distanceSquared-d.distanceSquared);let n,i=-1,o=1/0,a,s;for(let u=0;uo)continue;const{curveSegmentIndex:h,curveSegment:g}=d,{lineSegments:p}=g;for(let v=0;v=c.minY&&e[1]=h.minY&&e[1]=l.maxX?o:l.maxX,a=a>=l.maxY?a:l.maxY,r+=f}this._curveSegments=e,this._aabb={minX:n,minY:i,maxX:o,maxY:a},this._length=r,this._invalidated=!1}_convertCurveSegmentsToPolyline(e){this._update();const r=[];return e.forEach(({lineSegments:n},i)=>{n.forEach((o,a)=>{i===0&&a===0&&r.push([...o.points.start]),r.push([...o.points.end])})}),r}_getCurveSegmmentsDistanceSquaredInfo(e){this._update();const r=[],{_curveSegments:n}=this;for(let i=0;in)return[];const i=this._getCurveSegmmentsDistanceSquaredInfo(e),o=[];for(let a=0,s=i.length;a=c.previousLineSegmentsLength&&a<=l)return c}}_getClosingCurveSegmentWithStraightLineSegment(){if(this.closed)return;const e=this._controlPoints,r=e[0],n=e[e.length-1],i={points:{start:[...r],end:[...n]},aabb:{minX:Math.min(r[0],n[0]),minY:Math.min(r[1],n[1]),maxX:Math.max(r[0],n[0]),maxY:Math.max(r[1],n[1])}};return{aabb:{minX:i.aabb.minX,minY:i.aabb.minY,maxX:i.aabb.maxX,maxY:i.aabb.maxY},lineSegments:[i]}}}const Kye=1e-8;class iE extends rE{getPreviewCurveSegments(e,r){const n=this._getNumCurveSegments()+1,i=Math.max(0,n-2),o=r?n:n-1,a=this.getTransformMatrix(),s=[...this.controlPoints],c=[];r||s.push(e);for(let l=i;l<=o;l++){const f=this._getCurveSegment(l,a,s,r);c.push(f)}return c}getSplineCurves(){const e=this._getNumCurveSegments(),r=new Array(e);if(e<=0)return[];const n=this.getTransformMatrix();let i=0;for(let o=0;o=o)if(this.closed)s=(o+s)%o;else return;const{p0:f,p1:u,p2:d,p3:h}=this._getCurveSegmentPoints(s,n,i),g=c*c,p=g*c,v=v2(1,c,g,p),y=Jl(RM(),v,r);return[u6(y,v2(f[0],u[0],d[0],h[0])),u6(y,v2(f[1],u[1],d[1],h[1]))]}_getCurveSegmentPoints(e,r=this.controlPoints,n=this.closed){const i=this._getNumCurveSegments(r,n),o=e,a=o-1,s=n?(o+1)%i:o+1,c=s+1,l=r[o],f=r[s];let u,d;return a>=0?u=r[a]:u=n?r[r.length-1]:wC(f,l),cl?l:p;const v=this._getPoint(p,r,n,i);if(!g){u=v;continue}d=v;const y=d[0]-u[0],m=d[1]-u[1],w=Math.sqrt(y**2+m**2),x={minX:u[0]<=d[0]?u[0]:d[0],maxX:u[0]>=d[0]?u[0]:d[0],minY:u[1]<=d[1]?u[1]:d[1],maxY:u[1]>=d[1]?u[1]:d[1]};f.push({points:{start:u,end:d},aabb:x,length:w,previousLineSegmentsLength:h}),u=d,h+=w}return f}_getCurveSegment(e,r=this.getTransformMatrix(),n=this.controlPoints,i=this.closed){const{p0:o,p1:a,p2:s,p3:c}=this._getCurveSegmentPoints(e,n,i),l=this._getLineSegments(e,r,n,i);let f=0,u=1/0,d=1/0,h=-1/0,g=-1/0;return l.forEach(({aabb:p,length:v})=>{u=Math.min(u,p.minX),d=Math.min(d,p.minY),h=Math.max(h,p.maxX),g=Math.max(g,p.maxY),f+=v}),{controlPoints:{p0:o,p1:a,p2:s,p3:c},aabb:{minX:u,minY:d,maxX:h,maxY:g},length:f,previousCurveSegmentsLength:0,lineSegments:l}}}const qye=IM(Zo(),b_(1,4,1,0,-3,0,3,0,3,-6,3,0,-1,3,-3,1),1/6);class UU extends iE{getTransformMatrix(){return qye}}class Jp extends iE{constructor(e){super(e),this._scale=(e==null?void 0:e.scale)??.5,this._fixedScale=(e==null?void 0:e.fixedScale)??!1}get scale(){return this._scale}set scale(e){this._fixedScale||this._scale===e||(this._scale=e,this.invalidated=!0)}get fixedScale(){return this._fixedScale}getTransformMatrix(){const{scale:e}=this,r=2*e;return[0,1,0,0,-e,0,e,0,r,e-3,3-r,-e,-e,2-e,e-2,e]}}class BU extends Jp{constructor(){super({scale:.5,fixedScale:!0})}}class GU extends Jp{constructor(){super({resolution:0,fixedResolution:!0,scale:0,fixedScale:!0})}}class WU extends rE{getSplineCurves(){return[]}getLineSegments(){return[]}getPreviewCurveSegments(e,r){return[]}}const Xye=[1,0,0,-2,2,0,1,-2,1];class Yye extends WU{hasTangentPoints(){return!0}getTransformMatrix(){return Xye}}const Jye=Object.freeze(Object.defineProperty({__proto__:null,BSpline:UU,CardinalSpline:Jp,CatmullRomSpline:BU,CubicSpline:iE,LinearSpline:GU,QuadraticBezier:Yye,QuadraticSpline:WU,Spline:rE},Symbol.toStringTag,{value:"Module"}));class j0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r)}touchDragCallback(e){this._dragCallback(e)}mouseDragCallback(e){this._dragCallback(e)}_dragCallback(e){const{element:r,deltaPoints:n}=e.detail,i=Ce(r),o=n.world;if(o[0]===0&&o[1]===0&&o[2]===0)return;const a=i.viewport.getCamera(),{focalPoint:s,position:c}=a,l=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],f=[s[0]-o[0],s[1]-o[1],s[2]-o[2]];i.viewport.setCamera({focalPoint:f,position:l}),i.viewport.render()}}j0.toolName="Pan";class zU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{rotateIncrementDegrees:2,rotateSampleDistanceFactor:2}}){super(e,r),this._resizeObservers=new Map,this._hasResolutionChanged=!1,this.preMouseDownCallback=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a,f=s.getDefaultActor().actor.getMapper();if(!("getSampleDistance"in f||"getCurrentSampleDistance"in f))return!0;const d=f.getSampleDistance();if(!this._hasResolutionChanged){const{rotateSampleDistanceFactor:h}=this.configuration;f.setSampleDistance(d*h),this._hasResolutionChanged=!0,this.cleanUp!==null&&document.removeEventListener("mouseup",this.cleanUp),this.cleanUp=()=>{f.setSampleDistance(d),s.render(),this._hasResolutionChanged=!1},document.addEventListener("mouseup",this.cleanUp,{once:!0})}return!0},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.onSetToolActive=()=>{const n=()=>{this._getViewportsInfo().forEach(({viewportId:o,renderingEngineId:a})=>{if(!this._resizeObservers.has(o)){const{viewport:s}=Ti(o,a)||{viewport:null};if(!s)return;const{element:c}=s,l=new ResizeObserver(()=>{const f=Ti(o,a);if(!f)return;const{viewport:u}=f,d=u.getViewPresentation();u.resetCamera(),u.setViewPresentation(d),u.render()});l.observe(c),this._resizeObservers.set(o,l)}})};n(),this._viewportAddedListener=i=>{i.detail.toolGroupId===this.toolGroupId&&n()},Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener)},this.onSetToolDisabled=()=>{this._resizeObservers.forEach((n,i)=>{n.disconnect(),this._resizeObservers.delete(i)}),this._viewportAddedListener&&(Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this._viewportAddedListener),this._viewportAddedListener=null)},this.rotateCamera=(n,i,o,a)=>{const s=n.getVtkActiveCamera(),c=s.getViewUp(),l=s.getFocalPoint(),f=s.getPosition(),u=[0,0,0],d=[0,0,0],h=[0,0,0],g=Vt(new Float32Array(16));Lr(g,g,i),go(g,g,a,o),Lr(g,g,[-i[0],-i[1],-i[2]]),Jt(u,f,g),Jt(d,l,g),Vt(g),go(g,g,a,o),Jt(h,c,g),n.setCamera({position:u,viewUp:h,focalPoint:d})},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(e){const{element:r,currentPoints:n,lastPoints:i}=e.detail,o=n.canvas,a=i.canvas,{rotateIncrementDegrees:s}=this.configuration,c=Ce(r),{viewport:l}=c,f=l.getCamera(),u=r.clientWidth,d=r.clientHeight,h=[o[0]/u,o[1]/d],g=[a[0]/u,a[1]/d],p=[u*.5,d*.5],v=l.canvasToWorld(p),m=(1+Math.abs([.5,.5][0]))**2,w=[g[0],0,0],x=[h[0],0,0],C=w[0]**2,S=x[0]**2,_=C>m?0:Math.sqrt(m-C),T=S>m?0:Math.sqrt(m-S),E=[w[0],0,_];Xt.normalize(E);const D=[x[0],0,T];Xt.normalize(D);const b=Xt.dot(E,D);if(Math.abs(b)>1e-4){const I=-2*Math.acos(Xt.clampValue(b,-1,1))*Math.sign(h[0]-g[0])*s,P=f.viewUp,M=f.viewPlaneNormal,L=[0,0,0],V=[0,0,0];Xt.cross(P,M,L),Xt.normalize(L),Xt.cross(M,L,V),Xt.normalize(V),Xt.normalize(P),this.rotateCamera(l,v,V,I);const G=(g[1]-h[1])*s;this.rotateCamera(l,v,L,G),l.render()}}}zU.toolName="TrackballRotate";const m3=4,Zye=1024,Qye="PT";class H0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this._getImageDynamicRangeFromMiddleSlice=(n,i)=>{const o=Math.floor(i[2]/2),a=i[0]*i[1];let s,c;n instanceof Float32Array?(s=4,c=Float32Array):n instanceof Uint8Array?(s=1,c=Uint8Array):n instanceof Uint16Array?(s=2,c=Uint16Array):n instanceof Int16Array&&(s=2,c=Int16Array);const l=n.buffer,f=o*a*s,u=new c(l,f,a),{max:d,min:h}=this._getMinMax(u,a);return d-h}}touchDragCallback(e){this.mouseDragCallback(e)}mouseDragCallback(e){var g,p;const{element:r,deltaPoints:n}=e.detail,i=Ce(r),{viewport:o}=i;let a,s,c,l,f,u,d=!1;const h=o.getProperties();if(o instanceof ur){a=o.getVolumeId(),u=y1(a),{lower:s,upper:c}=h.voiRange;const v=Le.getVolume(a);if(!v)throw new Error("Volume not found "+a);l=v.metadata.Modality,d=v.scaling&&Object.keys(v.scaling).length>0}else if(h.voiRange){l=o.modality,{lower:s,upper:c}=h.voiRange;const{preScale:v={scaled:!1}}=((g=o.getImageData)==null?void 0:g.call(o))||{};d=v.scaled&&((p=v.scalingParameters)==null?void 0:p.suvbw)!==void 0}else throw new Error("Viewport is not a valid type");if(l===Qye&&d?f=this.getPTScaledNewRange({deltaPointsCanvas:n.canvas,lower:s,upper:c,clientHeight:r.clientHeight,isPreScaled:d,viewport:o,volumeId:a}):f=this.getNewRange({viewport:o,deltaPointsCanvas:n.canvas,volumeId:a,lower:s,upper:c}),!(f.lower>=f.upper)&&(o.setProperties({voiRange:f}),o.render(),o instanceof ur)){u.forEach(v=>{o!==v&&v.render()});return}}getPTScaledNewRange({deltaPointsCanvas:e,lower:r,upper:n,clientHeight:i,viewport:o,volumeId:a,isPreScaled:s}){let c=m3;s?c=5/i:c=this._getMultiplierFromDynamicRange(o,a)||m3;const f=e[1]*c;return n-=f,n=s?Math.max(n,.1):n,{lower:r,upper:n}}getNewRange({viewport:e,deltaPointsCanvas:r,volumeId:n,lower:i,upper:o}){const a=this._getMultiplierFromDynamicRange(e,n)||m3,s=r[0]*a,c=r[1]*a;let{windowWidth:l,windowCenter:f}=m1(i,o);l+=s,f+=c,l=Math.max(l,1);const u=e.getProperties().VOILUTFunction;return lu(l,f,u)}_getMultiplierFromDynamicRange(e,r){var o;let n;if(r){const a=Le.getVolume(r),{voxelManager:s}=e.getImageData(),l=s.getMiddleSliceData().reduce((d,h)=>[Math.min(d[0],h),Math.max(d[1],h)],[1/0,-1/0]),f=(o=a==null?void 0:a.metadata)==null?void 0:o.BitsStored,u=f?2**f:1/0;n=Math.min(l,u)}else n=this._getImageDynamicRangeFromViewport(e);const i=n/Zye;return i>1?Math.round(i):i}_getImageDynamicRangeFromViewport(e){const{imageData:r,voxelManager:n}=e.getImageData();if(n!=null&&n.getRange){const s=n.getRange();return s[1]-s[0]}const i=r.getDimensions();if(r.getRange){const s=r.getRange();return s[1]-s[0]}let o;if(r.getScalarData?o=r.getScalarData():o=r.getPointData().getScalars().getData(),i[2]!==1)return this._getImageDynamicRangeFromMiddleSlice(o,i);let a;if(o.getRange)a=o.getRange();else{const{min:s,max:c}=this._getMinMax(o,o.length);a=[s,c]}return a[1]-a[0]}_getMinMax(e,r){let n=1/0,i=-1/0;for(let o=0;oi&&(i=a)}return{max:i,min:n}}}H0.toolName="WindowLevel";class $U extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{minWindowWidth:10}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=this.getReferencedImageId(l,s,u,d),g=l.getFrameOfReferenceUID(),p={invalidated:!0,highlighted:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:g,referencedImageId:h},data:{handles:{points:[[...s],[...s],[...s],[...s]]},cachedStats:{}}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,viewportIdsToRender:v},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(v),p},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData;this._deactivateDraw(o),zt(o),this.editData=null,this.isDrawing=!1,gn(a.annotationUID),Pe(s),Nn(a),this.applyWindowLevelRegion(a,o)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData,{data:c}=a,{currentPoints:l}=i,f=Ce(o),{worldToCanvas:u,canvasToWorld:d}=f.viewport,h=l.world,{points:g}=c.handles,p=3;g[p]=[...h];const v=u(g[0]),y=u(g[3]),m=[y[0],v[1]],w=[v[0],y[1]],x=d(m),C=d(w);g[1]=x,g[2]=C,a.invalidated=!0,Pe(s)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(C));l.annotationUID=d;const{color:v,lineWidth:y,lineDash:m}=this.getAnnotationStyle({annotation:u,styleSpecifier:l});if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const w=`${d}-rect`;P1(i,d,"0",p[0],p[3],{color:v,lineDash:m,lineWidth:y},w),o=!0}return o},this.applyWindowLevelRegion=(n,i)=>{const o=Ce(i),{viewport:a}=o,s=PU(a),{data:c}=n,{points:l}=c.handles,f=l.map(_=>a.worldToCanvas(_)),u=f[0],d=f[3];let h=Math.min(u[0],d[0]),g=Math.min(u[1],d[1]),p=Math.abs(u[0]-d[0]),v=Math.abs(u[1]-d[1]);h=Wv(h,0,s.width),g=Wv(g,0,s.height),p=Math.floor(Math.min(p,Math.abs(s.width-h))),v=Math.floor(Math.min(v,Math.abs(s.height-g)));const y=OU(s,Math.round(h),Math.round(g),p,v),m=MU(y,s.minPixelValue,s.maxPixelValue);this.configuration.minWindowWidth===void 0&&(this.configuration.minWindowWidth=10);const w=Math.max(Math.abs(m.max-m.min),this.configuration.minWindowWidth),x=m.mean,C=a.getProperties().VOILUTFunction,S=lu(w,x,C);a.setProperties({voiRange:S}),a.render()},this.cancel=()=>null,this.isPointNearTool=()=>null,this.toolSelectedCallback=()=>null,this.handleSelectedCallback=()=>null,this._activateModify=()=>null,this._deactivateModify=()=>null}}$U.toolName="WindowLevelRegion";class id extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{invert:!1,debounceIfNotLoaded:!0,loop:!1}}){super(e,r),this.deltaY=1}mouseWheelCallback(e){this._scroll(e)}mouseDragCallback(e){this._dragCallback(e)}touchDragCallback(e){this._dragCallback(e)}_dragCallback(e){this._scrollDrag(e)}_scrollDrag(e){const{deltaPoints:r,viewportId:n,renderingEngineId:i}=e.detail,{viewport:o}=Ti(n,i),{debounceIfNotLoaded:a,invert:s,loop:c}=this.configuration,l=r.canvas[1];let f;o instanceof ur&&(f=o.getVolumeId());const u=this._getPixelPerImage(o),d=l+this.deltaY;if(u)if(Math.abs(d)>=u){const h=Math.round(d/u);ps(o,{delta:s?-h:h,volumeId:f,debounceLoading:a,loop:c}),this.deltaY=d%u}else this.deltaY=d}_scroll(e){const{wheel:r,element:n}=e.detail,{direction:i}=r,{invert:o}=this.configuration,{viewport:a}=Ce(n),s=i*(o?-1:1);ps(a,{delta:s,debounceLoading:this.configuration.debounceIfNotLoaded,loop:this.configuration.loop,volumeId:a instanceof Ir?a.getVolumeId():void 0,scrollSlabs:this.configuration.scrollSlabs})}_getPixelPerImage(e){const{element:r}=e,n=e.getNumberOfSlices();return Math.max(2,r.offsetHeight/Math.max(n,8))}}id.toolName="StackScroll";class K0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.mouseWheelCallback=n=>{const{element:i,wheel:o}=n.detail,a=Ce(i),{viewport:s}=a,{invert:c}=this.configuration,l=o.direction*10*(c?-1:1);this.setAngle(s,l)},this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}_dragCallback(e){const{element:r,currentPoints:n,startPoints:i}=e.detail,o=n.world,a=i.world,s=Ce(r),{viewport:c}=s,l=c.getCamera(),f=r.clientWidth,u=r.clientHeight,d=[f*.5,u*.5],h=c.canvasToWorld(d);let g=S0([a,h],[h,o]);const{viewPlaneNormal:p}=l,v=En(Ve(),h,a),y=En(Ve(),h,o),m=Rn(Ve(),v,y);Et(p,m)>0&&(g=-g),!Number.isNaN(g)&&this.setAngle(c,g)}setAngle(e,r){const{viewPlaneNormal:n,viewUp:i}=e.getCamera();if(e instanceof Ir){const o=(r+360)%360*Math.PI/180,a=Vt(new Float32Array(16));go(a,a,o,n);const s=Jt(Ve(),i,a);e.setCamera({viewUp:s})}else{const{rotation:o}=e.getViewPresentation();e.setViewPresentation({rotation:(o+r+360)%360})}e.render()}}K0.toolName="PlanarRotate";class q0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{zoomToCenter:!1,minZoomScale:.001,maxZoomScale:3e3,pinchToZoom:!0,pan:!0,invert:!1}}){super(e,r),this.preMouseDownCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=a.world,l=Ce(o).viewport.getCamera(),{focalPoint:f}=l;this.initialMousePosWorld=s;let u=bt(f[0]-s[0],f[1]-s[1],f[2]-s[2]);return u=tr(Ve(),u),this.dirVec=u,!1},this.preTouchStartCallback=n=>{if(!this.configuration.pinchToZoom)return this.preMouseDownCallback(n)},this._dragParallelProjection=(n,i,o,a=!1)=>{var _,T,E;const{element:s,deltaPoints:c}=n.detail,l=a?n.detail.deltaDistance.canvas:c.canvas[1],f=[s.clientWidth,s.clientHeight],{parallelScale:u,focalPoint:d,position:h}=o,g=5/f[1],p=l*g*(this.configuration.invert?-1:1),v=(1-p)*u;let y=d,m=h;if(!this.configuration.zoomToCenter){const D=ki(d,this.initialMousePosWorld);m=Tn(Ve(),h,this.dirVec,-D*p),y=Tn(Ve(),d,this.dirVec,-D*p)}const w=i.getImageData();let x=[1,1,1],C=v,S=!1;if(w){x=w.spacing;const{dimensions:D}=w,b=D[0]*x[0],I=D[1]*x[1],P=f[0]/f[1],M=(_=i.options)==null?void 0:_.displayArea,L=((T=M==null?void 0:M.imageArea)==null?void 0:T[0])??1.1,V=((E=M==null?void 0:M.imageArea)==null?void 0:E[1])??1.1,G=b*L,A=I*V,k=G/A;let F;k>P?F=G/P*.5:F=A*.5;const{minZoomScale:j,maxZoomScale:Y}=this.configuration,re=F/Y,ue=F/j;vue&&(C=ue,S=!0)}i.setCamera({parallelScale:C,focalPoint:S?d:y,position:S?h:m})},this._dragPerspectiveProjection=(n,i,o,a=!1)=>{const{element:s,deltaPoints:c}=n.detail,l=a?n.detail.deltaDistance.canvas:c.canvas[1],f=[s.clientWidth,s.clientHeight],{position:u,focalPoint:d,viewPlaneNormal:h}=o,g=Xt.distance2BetweenPoints(u,d),p=Math.sqrt(g)/f[1],v=[-h[0],-h[1],-h[2]],y=this.configuration.invert?l/p:l*p;let m=y*v[0];u[0]+=m,d[0]+=m,m=y*v[1],u[1]+=m,d[1]+=m,m=y*v[2],u[2]+=m,d[2]+=m,i.setCamera({position:u,focalPoint:d})},this.initialMousePosWorld=[0,0,0],this.dirVec=[0,0,0],this.configuration.pinchToZoom?this.touchDragCallback=this._pinchCallback.bind(this):this.touchDragCallback=this._dragCallback.bind(this),this.mouseDragCallback=this._dragCallback.bind(this)}mouseWheelCallback(e){this._zoom(e)}_pinchCallback(e){if(e.detail.currentPointsList.length>1){const{element:n,currentPoints:i}=e.detail,o=Ce(n),{viewport:a}=o,s=a.getCamera(),c=i.world,{focalPoint:l}=s;this.initialMousePosWorld=c;let f=bt(l[0]-c[0],l[1]-c[1],l[2]-c[2]);f=tr(Ve(),f),this.dirVec=f,s.parallelProjection?this._dragParallelProjection(e,a,s,!0):this._dragPerspectiveProjection(e,a,s,!0),a.render()}this.configuration.pan&&this._panCallback(e)}_dragCallback(e){const{element:r}=e.detail,n=Ce(r),{viewport:i}=n,o=i.getCamera();o.parallelProjection?this._dragParallelProjection(e,i,o):this._dragPerspectiveProjection(e,i,o),i.render()}_zoom(e){const{element:r,points:n}=e.detail,i=Ce(r),{viewport:o}=i;o.getCamera();const s=e.detail.wheel.direction,c={detail:{element:r,eventName:N.MOUSE_WHEEL,renderingEngineId:i.renderingEngineId,viewportId:o.id,camera:{},deltaPoints:{page:n.page,client:n.client,world:n.world,canvas:[0,-s*5]},startPoints:n,lastPoints:n,currentPoints:n}};o.type===mr.STACK&&this.preMouseDownCallback(c),this._dragCallback(c)}_panCallback(e){const{element:r,deltaPoints:n}=e.detail,i=Ce(r),o=n.world,a=i.viewport.getCamera(),{focalPoint:s,position:c}=a,l=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],f=[s[0]-o[0],s[1]-o[1],s[2]-o[2]];i.viewport.setCamera({focalPoint:f,position:l}),i.viewport.render()}}q0.toolName="Zoom";class jU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{targetViewportIds:[]}}){super(e,r)}mouseClickCallback(e){const{element:r,currentPoints:n}=e.detail,i=Ce(r),{viewport:o,renderingEngine:a}=i,s=o.getVolumeId();if(!s)throw new Error("MIPJumpToClickTool: targetId is not a volumeId, you should only use MIPJumpToClickTool with a volumeId as the targetId");let c=-1/0;const l=(g,p)=>{if(g>c)return c=g,p},f=O4(o,n.world,s,l);if(!f||!f.length)return;const{targetViewportIds:u,toolGroupId:d}=this.configuration;a.getViewports().filter(g=>{if((u==null?void 0:u.indexOf(g.id))>=0)return!0;const p=Or(g.id,a.id);return!!(d&&d===(p==null?void 0:p.id))}).forEach(g=>{g instanceof ur?g.jumpToWorld(f):console.warn("Cannot jump to specified world coordinates for a viewport that is not a VolumeViewport")})}}jU.toolName="MIPJumpToClickTool";const{RENDERING_DEFAULTS:v3}=cd;function e5e(){return"rgb(0, 200, 0)"}function t5e(){return!0}function n5e(){return!0}function r5e(){return!0}const ns={DRAG:1,ROTATE:2,SLAB:3};class Fs extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse"],configuration:{shadow:!0,viewportIndicators:!1,viewportIndicatorsConfig:{radius:5,x:null,y:null},autoPan:{enabled:!1,panSize:10},handleRadius:3,enableHDPIHandles:!1,referenceLinesCenterGapRadius:20,filterActorUIDsToSetSlabThickness:[],slabThicknessBlendMode:js.MAXIMUM_INTENSITY_BLEND,mobile:{enabled:!1,opacity:.8,handleRadius:9}}}){var n,i,o,a;super(e,r),this.toolCenter=[0,0,0],this.initializeViewport=({renderingEngineId:s,viewportId:c})=>{const l=Ti(c,s);if(!l)return;const{FrameOfReferenceUID:f,viewport:u}=l,{element:d}=u,{position:h,focalPoint:g,viewPlaneNormal:p}=u.getCamera();let v=this._getAnnotations(l);v=this.filterInteractableAnnotationsForElement(d,v),v!=null&&v.length&&gn(v[0].annotationUID);const y={highlighted:!1,metadata:{cameraPosition:[...h],cameraFocalPoint:[...g],FrameOfReferenceUID:f,toolName:this.getToolName()},data:{handles:{rotationPoints:[],slabThicknessPoints:[],toolCenter:this.toolCenter},activeOperation:null,activeViewportIds:[],viewportId:c}};return nn(y,d),{normal:p,point:u.canvasToWorld([u.canvas.clientWidth/2,u.canvas.clientHeight/2])}},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.resetCrosshairs=()=>{const s=this._getViewportsInfo();for(const c of s){const{viewportId:l,renderingEngineId:f}=c,u=Ti(l,f),d=u.viewport;d.resetCamera({resetPan:!0,resetZoom:!0,resetToCenter:!0,resetRotation:!0,suppressEvents:!0}),d.resetSlabThickness();const{element:m}=d;let w=this._getAnnotations(u);w=this.filterInteractableAnnotationsForElement(m,w),w.length&&gn(w[0].annotationUID),d.render()}this._computeToolCenter(s)},this.computeToolCenter=()=>{const s=this._getViewportsInfo();this._computeToolCenter(s)},this._computeToolCenter=s=>{if(!s.length||s.length===1){console.warn("For crosshairs to operate, at least two viewports must be given.");return}const[c,l,f]=s,{normal:u,point:d}=this.initializeViewport(c),{normal:h,point:g}=this.initializeViewport(l);let p=[0,0,0],v=Ve();f?{normal:p,point:v}=this.initializeViewport(f):(Ai(v,d,g),Ni(v,v,.5),Rn(p,u,h));const y=qs(u,d),m=qs(h,g),w=qs(p,v),x=eA(y,m,w);this.setToolCenter(x)},this.addNewAnnotation=s=>{const c=s.detail,{element:l}=c,{currentPoints:f}=c,u=f.world,d=Ce(l),{viewport:h}=d;this._jump(d,u);const g=this._getAnnotations(d),p=this.filterInteractableAnnotationsForElement(h.element,g),{data:v}=p[0],{rotationPoints:y}=v.handles,m=[];for(let w=0;w{console.log("Not implemented yet")},this.handleSelectedCallback=(s,c)=>{const l=s.detail,{element:f}=l;c.highlighted=!0,this._activateModify(f),Ot(f),s.preventDefault()},this.isPointNearTool=(s,c,l,f)=>!!this._pointNearTool(s,c,l,6),this.toolSelectedCallback=(s,c,l)=>{const f=s.detail,{element:u}=f;c.highlighted=!0,this._activateModify(u),Ot(u),s.preventDefault()},this.onCameraModified=s=>{var E;const c=s.detail,{element:l}=c,f=Ce(l),{renderingEngine:u}=f,d=f.viewport,h=this._getAnnotations(f),p=this.filterInteractableAnnotationsForElement(l,h)[0];if(!p)return;const v=d.getCamera(),y=p.metadata.cameraPosition,m=[0,0,0];Xt.subtract(v.position,y,m);const w=p.metadata.cameraFocalPoint,x=[0,0,0];Xt.subtract(v.focalPoint,w,x),p.metadata.cameraPosition=[...v.position],p.metadata.cameraFocalPoint=[...v.focalPoint];const C=this._getReferenceLineControllable(d.id),S=this._getReferenceLineDraggableRotatable(d.id);if(!$t(v.position,y,.001)&&C&&S){let D=!1;$t(m,x,.001)||(D=!0);const I=Math.abs(Xt.dot(m,v.viewPlaneNormal))<.01;!D&&!I&&(this.toolCenter[0]+=m[0],this.toolCenter[1]+=m[1],this.toolCenter[2]+=m[2],at(Ke,N.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter}))}(E=this.configuration.autoPan)!=null&&E.enabled&&Or(d.id,u.id).getViewportIds().filter(I=>I!==d.id).forEach(I=>{this._autoPanViewportIfNecessary(I,u)});const T=_t(l,this.getToolName(),!1);Pe(T)},this.onResetCamera=s=>{this.resetCrosshairs()},this.mouseMoveCallback=(s,c)=>{const{element:l,currentPoints:f}=s.detail,u=f.canvas;let d=!1;for(let h=0;h0?[...p.activeViewportIds]:[];p.activeViewportIds=[],p.handles.activeOperation=null;const w=this.getHandleNearImagePoint(l,g,u,6);let x=!1;w?x=!0:x=this._pointNearTool(l,g,u,6),x&&!v||!x&&v?(g.highlighted=!v,d=!0):(p.handles.activeOperation!==y||!this._areViewportIdArraysEqual(p.activeViewportIds,m))&&(d=!0)}return d},this.filterInteractableAnnotationsForElement=(s,c)=>{if(!c||!c.length)return[];const l=Ce(s),{viewportId:f}=l;return c.filter(d=>d.data.viewportId===f)},this.renderAnnotation=(s,c)=>{let l=!1;const{viewport:f,renderingEngine:u}=s,{element:d}=f,h=this._getAnnotations(s),g=f.getCamera(),v=this.filterInteractableAnnotationsForElement(d,h)[0];if(!(h!=null&&h.length)||!(v!=null&&v.data))return l;const y=v.annotationUID,{clientWidth:m,clientHeight:w}=f.canvas,x=Math.sqrt(m*m+w*w),C=Math.min(m,w),S=v.data,_=f.worldToCanvas(this.toolCenter),T=this._filterAnnotationsByUniqueViewportOrientations(s,h),E=[],D=[0,0,m,w];T.forEach(L=>{const{data:V}=L;V.handles.toolCenter=this.toolCenter;const G=u.getViewport(V.viewportId),A=G.getCamera(),k=this._getReferenceLineControllable(G.id),F=this._getReferenceLineDraggableRotatable(G.id),j=this._getReferenceLineSlabThicknessControlsOn(G.id),{clientWidth:Y,clientHeight:re}=G.canvas,ue=Math.sqrt(Y*Y+re*re),ce=[Y*.5,re*.5],pe=G.canvasToWorld(ce),Ee=[0,0,0];Xt.cross(g.viewPlaneNormal,A.viewPlaneNormal,Ee),Xt.normalize(Ee),Xt.multiplyScalar(Ee,ue);const Oe=[0,0,0];Xt.add(pe,Ee,Oe);const _e=[0,0,0];Xt.subtract(pe,Ee,_e);const B=f.worldToCanvas(Oe),O=f.worldToCanvas(pe),z=qt();Wr(z,B,O),Nc(z,z);const W=qt();Oc(W,z,x*100);const K=qt();Oc(K,z,C*.4);const Z=qt();Oc(Z,z,C*.2);const ee=qt(),xe=this.configuration.referenceLinesCenterGapRadius;Oc(ee,z,T.length===2?xe:0);const De=qt(),Ne=qt(),$e=qt(),ie=qt();let ae=om(_);(!F||!k)&&(ae=om(O)),Qi(De,ae,ee),Qi(Ne,ae,W),Wr($e,ae,ee),Wr(ie,ae,W),yg(De,Ne,D),yg($e,ie,D);const ye=qt();Wr(ye,_,K);const se=qt();Qi(se,_,K);let ge=om(_);!F&&j&&(ge=om(O));let Fe=[...this.toolCenter];!F&&j&&(Fe=[...pe]);const oe=[0,0,0];Xt.subtract(Oe,_e,oe),Xt.normalize(oe);const{viewPlaneNormal:ht}=g,{matrix:wt}=ji.buildFromDegree().rotate(90,ht),gt=[0,0,0];Jt(gt,oe,wt);const Ie=G.getSlabThickness(),je=[...gt];Xt.multiplyScalar(je,Ie);const nt=[0,0,0];Xt.add(Fe,je,nt);const rt=f.worldToCanvas(nt),dt=qt();Wr(dt,ge,rt);const Lt=qt();Wr(Lt,ge,W),Qi(Lt,Lt,dt);const xt=qt();Qi(xt,ge,W),Qi(xt,xt,dt),yg(Lt,xt,D);const Ft=qt();Qi(Ft,ge,W),Wr(Ft,Ft,dt);const jt=qt();Wr(jt,ge,W),Wr(jt,jt,dt),yg(Ft,jt,D);const Pn=qt(),$n=qt(),fn=qt(),bn=qt();Wr(Pn,ge,Z),Qi(Pn,Pn,dt),Qi($n,ge,Z),Qi($n,$n,dt),Wr(fn,ge,Z),Wr(fn,fn,dt),Qi(bn,ge,Z),Wr(bn,bn,dt),E.push([G,De,Ne,$e,ie,Lt,xt,Ft,jt,ye,se,Pn,$n,fn,bn])});const b=[],I=[],P=this._getReferenceLineColor(f.id),M=P!==void 0?P:"rgb(200, 200, 200)";if(E.forEach((L,V)=>{var Ee,Oe,_e,B;const G=L[0],A=this._getReferenceLineColor(G.id),k=this._getReferenceLineControllable(G.id),F=this._getReferenceLineDraggableRotatable(G.id)||((Ee=this.configuration.mobile)==null?void 0:Ee.enabled),j=this._getReferenceLineSlabThicknessControlsOn(G.id)||((Oe=this.configuration.mobile)==null?void 0:Oe.enabled),Y=S.activeViewportIds.find(O=>O===G.id);let re=A!==void 0?A:"rgb(200, 200, 200)",ue=1;const ce=S.handles.activeOperation!==null&&S.handles.activeOperation===ns.DRAG&&Y;ce&&(ue=2.5);let pe=`${V}`;if(k&&F?(pe=`${V}One`,vn(c,y,pe,L[1],L[2],{color:re,lineWidth:ue}),pe=`${V}Two`,vn(c,y,pe,L[3],L[4],{color:re,lineWidth:ue})):vn(c,y,pe,L[2],L[4],{color:re,lineWidth:ue}),k){re=A!==void 0?A:"rgb(200, 200, 200)";const O=S.handles.activeOperation===ns.ROTATE,z=[L[9],L[10]],W=[f.canvasToWorld(L[9]),G,L[1],L[2]],K=[f.canvasToWorld(L[10]),G,L[3],L[4]];b.push(W,K);const Z=S.handles.activeOperation===ns.SLAB,ee=[L[11],L[12],L[13],L[14]],xe=[f.canvasToWorld(L[11]),G,L[5],L[6]],De=[f.canvasToWorld(L[12]),G,L[5],L[6]],Ne=[f.canvasToWorld(L[13]),G,L[7],L[8]],$e=[f.canvasToWorld(L[14]),G,L[7],L[8]];I.push(xe,De,Ne,$e);let ie=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1),ae=1;if((_e=this.configuration.mobile)!=null&&_e.enabled&&(ie=this.configuration.mobile.handleRadius,ae=this.configuration.mobile.opacity),(ce||(B=this.configuration.mobile)!=null&&B.enabled)&&!O&&!Z&&F&&j){let se=`${V}One`;ir(c,y,se,z,{color:re,handleRadius:ie,opacity:ae,type:"circle"}),se=`${V}Two`,ir(c,y,se,ee,{color:re,handleRadius:ie,opacity:ae,type:"rect"})}else if(ce&&!O&&!Z&&F){const se=`${V}`;ir(c,y,se,z,{color:re,handleRadius:ie,opacity:ae,type:"circle"})}else if(Y&&!O&&!Z&&j){const se=`${V}`;ir(c,y,se,ee,{color:re,handleRadius:ie,opacity:ae,type:"rect"})}else if(O&&F){const se=`${V}`,ge=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);ir(c,y,se,z,{color:re,handleRadius:ge,fill:re,type:"circle"})}else if(Z&&Y&&j){const se=this.configuration.handleRadius*(this.configuration.enableHDPIHandles?window.devicePixelRatio:1);ir(c,y,pe,ee,{color:re,handleRadius:se,fill:re,type:"rect"})}G.getSlabThickness()>.5&&j&&(pe=`${V}STOne`,vn(c,y,pe,L[5],L[6],{color:re,width:1,lineDash:[2,3]}),pe=`${V}STTwo`,vn(c,y,pe,L[7],L[8],{color:re,width:L,lineDash:[2,3]}))}}),l=!0,S.handles.rotationPoints=b,S.handles.slabThicknessPoints=I,this.configuration.viewportIndicators){const{viewportIndicatorsConfig:L}=this.configuration,V=(L==null?void 0:L.xOffset)||.95,G=(L==null?void 0:L.yOffset)||.05,A=[m*V,w*G],k=(L==null?void 0:L.circleRadius)||x*.01;No(c,y,"0",A,k,{color:M,fill:M})}return l},this._getAnnotations=s=>{const{viewport:c}=s,l=un(this.getToolName(),c.element)||[],f=this._getViewportsInfo().map(({viewportId:d})=>d);return l.filter(d=>{const{data:h}=d;return f.includes(h.viewportId)})},this._onNewVolume=()=>{const s=this._getViewportsInfo();this._computeToolCenter(s)},this._areViewportIdArraysEqual=(s,c)=>s.length!==c.length?!1:(s.forEach(l=>{let f=!1;for(let u=0;u{const{viewportId:l,renderingEngine:f,viewport:u}=s,d=c.filter(y=>y.data.viewportId!==l);if(!d||!d.length)return[];const h=u.getCamera(),{viewPlaneNormal:g,position:p}=h;return d.filter(y=>{const{viewportId:m}=y.data,x=f.getViewport(m).getCamera();return!($t(x.viewPlaneNormal,g,.01)&&$t(x.position,p,1))})},this._filterViewportWithSameOrientation=(s,c,l)=>{const{renderingEngine:f}=s,{data:u}=c,d=f.getViewport(u.viewportId),h=l.filter(y=>{const{data:m}=y,w=f.getViewport(m.viewportId);return this._getReferenceLineControllable(w.id)===!0});if(!h||!h.length)return[];const g=d.getCamera(),p=g.viewPlaneNormal;return Xt.normalize(p),h.filter(y=>{const{viewportId:m}=y.data,x=f.getViewport(m).getCamera(),C=x.viewPlaneNormal;return Xt.normalize(C),$t(p,C,.01)&&$t(g.viewUp,x.viewUp,.01)})},this._filterAnnotationsByUniqueViewportOrientations=(s,c)=>{const{renderingEngine:l,viewport:f}=s,d=f.getCamera().viewPlaneNormal;Xt.normalize(d);const h=c.filter(y=>{const{data:m}=y,w=l.getViewport(m.viewportId),x=this._getReferenceLineControllable(w.id);return f!==w&&x===!0}),g=[];for(let y=0;y{const{data:m}=y,w=l.getViewport(m.viewportId),x=this._getReferenceLineControllable(w.id);return f!==w&&x!==!0});for(let y=0;yT===m))continue;const{viewportId:w}=m.data,C=l.getViewport(w).getCamera(),S=C.viewPlaneNormal;if(Xt.normalize(S),$t(d,S,.01)||vg(d,S,.01))continue;let _=!1;for(let T=0;T{const l=s.getAllVolumeIds(),f=c.getAllVolumeIds();return l.length===f.length&&l.every(u=>f.includes(u))},this._jump=(s,c)=>{Be.isInteractingWithTool=!0;const{viewport:l,renderingEngine:f}=s,u=this._getAnnotations(s),d=[0,0,0];Xt.subtract(c,this.toolCenter,d);const g=this._getAnnotationsForViewportsWithDifferentCameras(s,u).filter(p=>{const{data:v}=p,y=f.getViewport(v.viewportId),m=this._checkIfViewportsRenderingSameScene(l,y);return this._getReferenceLineControllable(y.id)&&this._getReferenceLineDraggableRotatable(y.id)&&m});return g.length===0?(Be.isInteractingWithTool=!1,!1):(this._applyDeltaShiftToSelectedViewportCameras(f,g,d),Be.isInteractingWithTool=!1,!0)},this._activateModify=s=>{var c;Be.isInteractingWithTool=!((c=this.configuration.mobile)!=null&&c.enabled),s.addEventListener(N.MOUSE_UP,this._endCallback),s.addEventListener(N.MOUSE_DRAG,this._dragCallback),s.addEventListener(N.MOUSE_CLICK,this._endCallback),s.addEventListener(N.TOUCH_END,this._endCallback),s.addEventListener(N.TOUCH_DRAG,this._dragCallback),s.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=s=>{Be.isInteractingWithTool=!1,s.removeEventListener(N.MOUSE_UP,this._endCallback),s.removeEventListener(N.MOUSE_DRAG,this._dragCallback),s.removeEventListener(N.MOUSE_CLICK,this._endCallback),s.removeEventListener(N.TOUCH_END,this._endCallback),s.removeEventListener(N.TOUCH_DRAG,this._dragCallback),s.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._endCallback=s=>{const c=s.detail,{element:l}=c;this.editData.annotation.data.handles.activeOperation=null,this.editData.annotation.data.activeViewportIds=[],this._deactivateModify(l),zt(l),this.editData=null;const u=_t(l,this.getToolName(),!1);Pe(u)},this._dragCallback=s=>{const c=s.detail,l=c.deltaPoints.world;if(Math.abs(l[0])<.001&&Math.abs(l[1])<.001&&Math.abs(l[2])<.001)return;const{element:f}=c,u=Ce(f),{renderingEngine:d,viewport:h}=u,g=this._getAnnotations(u),v=this.filterInteractableAnnotationsForElement(f,g)[0];if(!v)return;const{handles:y}=v.data,{currentPoints:m}=s.detail,w=m.canvas;if(y.activeOperation===ns.DRAG){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(S=>{const{data:_}=S,T=d.getViewport(_.viewportId),E=this._getReferenceLineControllable(T.id),D=this._getReferenceLineDraggableRotatable(T.id);return E===!0&&D===!0&&v.data.activeViewportIds.find(b=>b===T.id)});this._applyDeltaShiftToSelectedViewportCameras(d,C,l)}else if(y.activeOperation===ns.ROTATE){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(V=>{const{data:G}=V,A=d.getViewport(G.viewportId),k=this._getReferenceLineControllable(A.id),F=this._getReferenceLineDraggableRotatable(A.id);return k===!0&&F===!0}),S=qt(),_=qt(),T=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]],E=h.worldToCanvas(T),D=c.currentPoints.canvas,b=qt();Ga(b,D,c.deltaPoints.canvas),Ga(S,b,E),Ga(_,D,E);let I=KK(S,_);this._isClockWise(E,b,D)&&(I*=-1),I=Math.round(I*100)/100;const P=h.getCamera().viewPlaneNormal,{matrix:M}=ji.buildFromRadian().translate(T[0],T[1],T[2]).rotate(I,P).translate(-T[0],-T[1],-T[2]),L=[];C.forEach(V=>{const{data:G}=V;G.handles.toolCenter=T;const A=d.getViewport(G.viewportId),k=A.getCamera(),{viewUp:F,position:j,focalPoint:Y}=k;F[0]+=j[0],F[1]+=j[1],F[2]+=j[2],Jt(Y,Y,M),Jt(j,j,M),Jt(F,F,M),F[0]-=j[0],F[1]-=j[1],F[2]-=j[2],A.setCamera({position:j,viewUp:F,focalPoint:Y}),L.push(A.id)}),d.renderViewports(L)}else if(y.activeOperation===ns.SLAB){const C=this._getAnnotationsForViewportsWithDifferentCameras(u,g).filter(T=>{const{data:E}=T,D=d.getViewport(E.viewportId),b=this._getReferenceLineControllable(D.id),I=this._getReferenceLineSlabThicknessControlsOn(D.id);return b===!0&&I===!0&&v.data.activeViewportIds.find(P=>P===D.id)});if(C.length===0)return;const S=this._filterViewportWithSameOrientation(u,C[0],g),_=[];_.push(h.id),S.forEach(T=>{const{data:E}=T,D=d.getViewport(E.viewportId),I=D.getCamera().viewPlaneNormal,P=Xt.dot(l,I),M=[...I];if(Xt.multiplyScalar(M,P),Math.abs(M[0])>.001||Math.abs(M[1])>.001||Math.abs(M[2])>.001){const L=Math.sqrt(M[0]*M[0]+M[1]*M[1]+M[2]*M[2]),V=c.lastPoints.world,G=[0,0,0],A=[this.toolCenter[0],this.toolCenter[1],this.toolCenter[2]];if(!this._getReferenceLineDraggableRotatable(D.id)){const{rotationPoints:Oe}=this.editData.annotation.data.handles,_e=Oe.filter(B=>B[1].uid===D.id);if(_e.length===2){const B=h.canvasToWorld(_e[0][3]),O=h.canvasToWorld(_e[1][3]);Xt.add(B,O,A),Xt.multiplyScalar(A,.5)}}Xt.subtract(V,A,G);const F=Xt.dot(G,I),j=[...I];Xt.multiplyScalar(j,F);const Y=[j[0],j[1],j[2]];tr(Y,Y);const re=[M[0],M[1],M[2]];tr(re,re);let ue=D.getSlabThickness();vg(Y,re,.001)?ue-=L:ue+=L,ue=Math.abs(ue),ue=Math.max(v3.MINIMUM_SLAB_THICKNESS,ue),this._pointNearReferenceLine(v,w,6,D)&&(ue=v3.MINIMUM_SLAB_THICKNESS),Or(D.id,d.id).getToolInstance(this.getToolName()).setSlabThickness(D,ue),_.push(D.id)}}),d.renderViewports(_)}},this._pointNearReferenceLine=(s,c,l,f)=>{const{data:u}=s,{rotationPoints:d}=u.handles;for(let h=0;h{const i=Ti(n,r);if(!i)return;const o=this._getAnnotations(i);o!=null&&o.length&&o.forEach(a=>{gn(a.annotationUID)})})}setToolCenter(e,r=!1){this.toolCenter=e;const n=this._getViewportsInfo();Pe(n.map(({viewportId:i})=>i)),r||at(Ke,N.CROSSHAIR_TOOL_CENTER_CHANGED,{toolGroupId:this.toolGroupId,toolCenter:this.toolCenter})}getHandleNearImagePoint(e,r,n,i){const o=Ce(e),{viewport:a}=o;let s=this._getRotationHandleNearImagePoint(a,r,n,i);if(s!==null||(s=this._getSlabThicknessHandleNearImagePoint(a,r,n,i),s!==null))return s}_unsubscribeToViewportNewVolumeSet(e){e.forEach(({viewportId:r,renderingEngineId:n})=>{const{viewport:i}=Ti(r,n),{element:o}=i;o.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_subscribeToViewportNewVolumeSet(e){e.forEach(({viewportId:r,renderingEngineId:n})=>{const{viewport:i}=Ti(r,n),{element:o}=i;o.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this._onNewVolume)})}_autoPanViewportIfNecessary(e,r){const n=r.getViewport(e),{clientWidth:i,clientHeight:o}=n.canvas,a=n.worldToCanvas(this.toolCenter),s=this.configuration.autoPan.panSize,c=[a[0],a[1]];if(a[0]<0?c[0]=s:a[0]>i&&(c[0]=i-s),a[1]<0?c[1]=s:a[1]>o&&(c[1]=o-s),c[0]===a[0]&&c[1]===a[1])return;const l=n.canvasToWorld(c),f=[l[0]-this.toolCenter[0],l[1]-this.toolCenter[1],l[2]-this.toolCenter[2]],u=n.getCamera(),{focalPoint:d,position:h}=u,g=[h[0]-f[0],h[1]-f[1],h[2]-f[2]],p=[d[0]-f[0],d[1]-f[1],d[2]-f[2]];n.setCamera({focalPoint:p,position:g}),n.render()}setSlabThickness(e,r){let n;const{filterActorUIDsToSetSlabThickness:i}=this.configuration;i&&i.length>0&&(n=i);let o=this.configuration.slabThicknessBlendMode;r===v3.MINIMUM_SLAB_THICKNESS&&(o=js.COMPOSITE),e.setBlendMode(o,n,!1),e.setSlabThickness(r,n)}_isClockWise(e,r,n){return(r[0]-e[0])*(n[1]-e[1])-(r[1]-e[1])*(n[0]-e[0])>0}_applyDeltaShiftToSelectedViewportCameras(e,r,n){r.forEach(i=>{this._applyDeltaShiftToViewportCamera(e,i,n)})}_applyDeltaShiftToViewportCamera(e,r,n){const{data:i}=r,o=e.getViewport(i.viewportId),a=o.getCamera(),s=a.viewPlaneNormal,c=Xt.dot(n,s),l=[...s];if(Xt.multiplyScalar(l,c),Math.abs(l[0])>.001||Math.abs(l[1])>.001||Math.abs(l[2])>.001){const f=[0,0,0],u=[0,0,0];Xt.add(a.focalPoint,l,f),Xt.add(a.position,l,u),o.setCamera({focalPoint:f,position:u}),o.render()}}_getRotationHandleNearImagePoint(e,r,n,i){const{data:o}=r,{rotationPoints:a}=o.handles;for(let s=0;sP===p.id))continue;const v=this._getReferenceLineControllable(p.id),y=this._getReferenceLineSlabThicknessControlsOn(p.id);if(!v||!y)continue;const m=d[g][2],w=d[g][3],x=qt();Qi(x,m,w),Oc(x,x,.5);const C=qt();Wr(C,m,x),Nc(C,C);const S=qt();Oc(S,C,l*.05);const _=qt(),T=qt();Qi(_,x,S),Wr(T,x,S);const E={start:{x:_[0],y:_[1]},end:{x:m[0],y:m[1]}},D=hi([E.start.x,E.start.y],[E.end.x,E.end.y],[n[0],n[1]]),b={start:{x:T[0],y:T[1]},end:{x:w[0],y:w[1]}},I=hi([b.start.x,b.start.y],[b.end.x,b.end.y],[n[0],n[1]]);(D<=i||I<=i)&&(h.push(p.id),f.handles.activeOperation=null),g++}return f.activeViewportIds=[...h],this.editData={annotation:r},f.handles.activeOperation===ns.DRAG}}Fs.toolName="Crosshairs";const zm="magnify-viewport";class HU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{magnifySize:10,magnifyWidth:250,magnifyHeight:250}}){super(e,r),this._hasBeenRemoved=!1,this.preMouseDownCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o),{viewport:c,renderingEngine:l}=s;if(!(c instanceof lr))throw new Error("MagnifyTool only works on StackViewports");const f=this._getReferencedImageId(c);if(!f)throw new Error("MagnifyTool: No referenced image id found, reconstructed planes not supported yet");const u=_t(o,this.getToolName());return this.editData={referencedImageId:f,viewportIdsToRender:u,enabledElement:s,renderingEngine:l,currentPoints:a},this._createMagnificationViewport(),this._activateDraw(o),Ot(o),n.preventDefault(),Pe(u),!0},this.preTouchStartCallback=n=>{this.preMouseDownCallback(n)},this._createMagnificationViewport=()=>{const{enabledElement:n,referencedImageId:i,viewportIdsToRender:o,renderingEngine:a,currentPoints:s}=this.editData,{viewport:c}=n,{element:l}=c,f=c.getProperties(),{rotation:u}=c.getViewPresentation(),{canvas:d,world:h}=s;let g;if(g=l.querySelector(".magnifyTool"),g===null){const v=document.createElement("div");v.classList.add("magnifyTool"),v.style.display="block",v.style.width=`${this.configuration.magnifyWidth}px`,v.style.height=`${this.configuration.magnifyHeight}px`,v.style.position="absolute",g=v,l.querySelector(".viewport-element").appendChild(v);const m={viewportId:zm,type:mr.STACK,element:g};a.enableElement(m)}g.style.top=`${d[1]-this.configuration.magnifyHeight/2}px`,g.style.left=`${d[0]-this.configuration.magnifyWidth/2}px`;const p=a.getViewport(zm);p.setStack([i]).then(()=>{if(this._hasBeenRemoved)return;p.setProperties(f),p.setViewPresentation({rotation:u});const{parallelScale:v}=c.getCamera(),{focalPoint:y,position:m,viewPlaneNormal:w}=p.getCamera(),x=Math.sqrt(Math.pow(y[0]-m[0],2)+Math.pow(y[1]-m[1],2)+Math.pow(y[2]-m[2],2)),C=[h[0],h[1],h[2]],S=[C[0]+x*w[0],C[1]+x*w[1],C[2]+x*w[2]];p.setCamera({parallelScale:v*(1/this.configuration.magnifySize),focalPoint:C,position:S}),p.render()}),g.style.display="block",Pe(o)},this._dragCallback=n=>{const i=n.detail,{deltaPoints:o,element:a,currentPoints:s}=i,c=o.world,l=s.canvas,f=Ce(a),{renderingEngine:u}=f,d=u.getViewport(zm),h=a.querySelector(".magnifyTool");if(!h)return;h.style.top=`${l[1]-this.configuration.magnifyHeight/2}px`,h.style.left=`${l[0]-this.configuration.magnifyWidth/2}px`;const{focalPoint:g,position:p}=d.getCamera(),v=[p[0]+c[0],p[1]+c[1],p[2]+c[2]],y=[g[0]+c[0],g[1]+c[1],g[2]+c[2]];d.setCamera({focalPoint:y,position:v}),d.render()},this._dragEndCallback=n=>{const{element:i}=n.detail,o=Ce(i),{renderingEngine:a}=o;a.disableElement(zm);const s=i.querySelector(".viewport-element"),c=s.querySelector(".magnifyTool");s.removeChild(c),this._deactivateDraw(i),zt(i),this._hasBeenRemoved=!0},this._activateDraw=n=>{Be.isInteractingWithTool=!0,this._hasBeenRemoved=!1,n.addEventListener(N.MOUSE_UP,this._dragEndCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._dragEndCallback),n.addEventListener(N.TOUCH_END,this._dragEndCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._dragEndCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._dragEndCallback),n.removeEventListener(N.TOUCH_END,this._dragEndCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)}}_getReferencedImageId(e){const r=this.getTargetId(e);let n;return e instanceof lr&&(n=r.split("imageId:")[1]),n}}HU.toolName="Magnify";const i5e="advancedMagnifyTool",o5e=125,{Events:Ll}=ja,QD=t=>t.uid!==t.referencedId;var BC;(function(t){t.ShowZoomFactorsList="showZoomFactorsList"})(BC||(BC={}));const a5e="AdvancedMagnify",s5e=1-wa,_E=class _E extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,magnifyingGlass:{radius:125,zoomFactor:3,zoomFactorList:[1.5,2,2.5,3,3.5,4,4.5,5],autoPan:{enabled:!0,padding:10}},actions:{showZoomFactorsList:{method:"showZoomFactorsList",bindings:[{mouseButton:nc.Secondary,modifierKey:Oi.Shift}]}}}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=Ce(a),{viewport:c,renderingEngine:l}=s,f=o.world,u=o.canvas,{magnifyingGlass:d}=this.configuration,{radius:h,zoomFactor:g,autoPan:p}=d,v=this._getCanvasHandlePoints(u,h),y=c.getCamera(),{viewPlaneNormal:m,viewUp:w}=y,x=this.getReferencedImageId(c,f,m,w),C=Dn(),S=Dn(),_=c.getFrameOfReferenceUID(),T={annotationUID:C,highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...m],viewUp:[...w],FrameOfReferenceUID:_,referencedImageId:x},data:{sourceViewportId:c.id,magnifyViewportId:S,zoomFactor:g,isCanvasAnnotation:!0,handles:{points:v,activeHandleIndex:null}}};this.magnifyViewportManager.createViewport(T,{magnifyViewportId:S,sourceEnabledElement:s,position:u,radius:h,zoomFactor:g,autoPan:{enabled:p.enabled,padding:p.padding,callback:D=>{const b=T.data.handles.points,{canvas:I}=D.delta;for(let P=0,M=b.length;P{this.magnifyViewportManager.dispose(),S1().forEach(i=>{i.metadata.toolName===this.getToolName()&&gn(i.annotationUID)})},this.isPointNearTool=(n,i,o,a)=>{const{data:s}=i,{points:c}=s.handles,l=c,f=l[0],u=l[2],d=l[3],h=Math.abs(u[1]-f[1])*.5,g=[d[0]+h,f[1]+h],p=du([g,o]);return Math.abs(p-h){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},Ot(a),this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;const{points:l}=c.handles,f=l.findIndex(d=>d===o),u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f},this._activateModify(s),Ot(s),Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{data:l}=a;l.handles.activeHandleIndex=null,this._deactivateModify(o),zt(o),this.editData=null,this.isDrawing=!1,Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{deltaPoints:o}=i,a=(o==null?void 0:o.canvas)??[0,0,0],{annotation:s,viewportIdsToRender:c}=this.editData,{points:l}=s.data.handles;l.forEach(f=>{f[0]+=a[0],f[1]+=a[1]}),s.invalidated=!0,this.editData.hasMoved=!0,Pe(c)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c}=this.editData,{data:l}=a;if(c===void 0){const{deltaPoints:f}=i,u=f.canvas;l.handles.points.forEach(h=>{h[0]+=u[0],h[1]+=u[1]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;Pe(s)},this._dragHandle=n=>{const i=n.detail,{annotation:o}=this.editData,{data:a}=o,{points:s}=a.handles,c=s,l=c[0],f=c[2],u=c[3],d=Math.abs(f[1]-l[1])*.5,h=[u[0]+d,l[1]+d],{currentPoints:g}=i,p=g.canvas,v=du([h,p]),y=this._getCanvasHandlePoints(h,v);s[0]=y[0],s[1]=y[1],s[2]=y[2],s[3]=y[3]},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length))return o;c=c==null?void 0:c.filter(u=>u.data.sourceViewportId===a.id);const l=this.filterInteractableAnnotationsForElement(s,c);if(!(l!=null&&l.length))return o;const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let u=0;u[[n[0],n[1]-i,0],[n[0]+i,n[1],0],[n[0],n[1]+i,0],[n[0]-i,n[1],0]],this.magnifyViewportManager=Yd.getInstance()}showZoomFactorsList(e,r){const{element:n,currentPoints:i}=e.detail,o=Ce(n),{viewport:a}=o,{canvas:s}=i,c=n.querySelector(":scope .viewport-element"),l=r.data.zoomFactor,f=()=>u.parentElement.removeChild(u),u=this._getZoomFactorsListDropdown(l,d=>{d!==void 0&&(r.data.zoomFactor=Number.parseFloat(d),r.invalidated=!0),f(),a.render()});Object.assign(u.style,{left:`${s[0]}px`,top:`${s[1]}px`}),c.appendChild(u),u.focus()}_getZoomFactorsListDropdown(e,r){const{zoomFactorList:n}=this.configuration.magnifyingGlass,i=document.createElement("select");return i.size=5,Object.assign(i.style,{width:"50px",position:"absolute"}),["mousedown","mouseup","mousemove","click"].forEach(o=>{i.addEventListener(o,a=>a.stopPropagation())}),i.addEventListener("change",o=>{o.stopPropagation(),r(i.value)}),i.addEventListener("keydown",o=>{var s;((o.keyCode??o.which===27)||((s=o.key)==null?void 0:s.toLowerCase())==="escape")&&(o.stopPropagation(),r())}),n.forEach(o=>{const a=document.createElement("option");a.label=o,a.title=`Zoom factor ${o.toFixed(1)}`,a.value=o,a.defaultSelected=o===e,i.add(a)}),i}};_E.Actions=BC;let Zp=_E;class Yd{constructor(){this.createViewport=(e,r)=>{const{magnifyViewportId:n,sourceEnabledElement:i,position:o,radius:a,zoomFactor:s,autoPan:c}=r,{viewport:l}=i,{element:f}=l,u=new c5e({magnifyViewportId:n,sourceEnabledElement:i,radius:a,position:o,zoomFactor:s,autoPan:c});return this._addSourceElementEventListener(f),this._magnifyViewportsMap.set(u.viewportId,{annotation:e,magnifyViewport:u,magnifyViewportInfo:r}),u},this._annotationRemovedCallback=e=>{const{annotation:r}=e.detail;r.metadata.toolName===a5e&&this.destroyViewport(r.data.magnifyViewportId)},this._newStackImageCallback=e=>{const{viewportId:r,imageId:n}=e.detail,i=this._getMagnifyViewportsMapEntriesBySourceViewportId(r),{viewport:o}=zn(r);o.stackActorReInitialized&&this._reset(r),i.forEach(({annotation:a})=>{a.metadata.referencedImageId=n,a.invalidated=!0})},this._newVolumeImageCallback=e=>{const{renderingEngineId:r,viewportId:n}=e.detail,o=Jr(r).getViewport(n),{viewPlaneNormal:a}=o.getCamera();this._getMagnifyViewportsMapEntriesBySourceViewportId(n).forEach(({annotation:c})=>{const{viewPlaneNormal:l}=c.metadata;if(!(Math.abs(Et(l,a))>s5e))return;const{handles:u}=c.data,d=o.canvasToWorld([0,0]),h=En(Ve(),d,u.points[0]),g=Et(h,a),p=Ni(Ve(),a,g);for(let v=0,y=u.points.length;vthis.destroyViewport(r))}_getMagnifyViewportsMapEntriesBySourceViewportId(e){return Array.from(this._magnifyViewportsMap.values()).filter(({magnifyViewport:n})=>{const{viewport:i}=n.sourceEnabledElement;return i.id===e})}_reset(e){this._getMagnifyViewportsMapEntriesBySourceViewportId(e).forEach(({magnifyViewport:n,annotation:i,magnifyViewportInfo:o})=>{this.destroyViewport(n.viewportId);const a=zn(e);this.createViewport(i,{...o,sourceEnabledElement:{...a}})})}_addEventListeners(){Ke.addEventListener(N.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_removeEventListeners(){Ke.removeEventListener(N.ANNOTATION_REMOVED,this._annotationRemovedCallback)}_addSourceElementEventListener(e){e.addEventListener(Ll.STACK_NEW_IMAGE,this._newStackImageCallback);const r=i=>{const{viewportId:o}=i.detail;this._reset(o)};e.addEventListener(Ll.VIEWPORT_NEW_IMAGE_SET,r);const n=i=>{const{viewportId:o}=i.detail;this._reset(o)};e.addEventListener(Ll.VOLUME_VIEWPORT_NEW_VOLUME,n),e.addEventListener(Ll.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),e.newStackHandler=r,e.newVolumeHandler=n}_removeSourceElementEventListener(e){e.removeEventListener(Ll.STACK_NEW_IMAGE,this._newStackImageCallback),e.removeEventListener(Ll.VOLUME_NEW_IMAGE,this._newVolumeImageCallback),e.removeEventListener(Ll.VIEWPORT_NEW_IMAGE_SET,e.newStackHandler),e.removeEventListener(Ll.VOLUME_VIEWPORT_NEW_VOLUME,e.newVolumeHandler),delete e.newStackHandler,delete e.newVolumeHandler}_initialize(){this._addEventListeners()}}class c5e{constructor({magnifyViewportId:e,sourceEnabledElement:r,radius:n=o5e,position:i=[0,0],zoomFactor:o,autoPan:a}){this._enabledElement=null,this._sourceToolGroup=null,this._magnifyToolGroup=null,this._isViewportReady=!1,this._radius=0,this._resized=!1,this._canAutoPan=!1,this._viewportId=e??Dn(),this._sourceEnabledElement=r,this._autoPan=a,this.radius=n,this.position=i,this.zoomFactor=o,this.visible=!0,this._browserMouseDownCallback=this._browserMouseDownCallback.bind(this),this._browserMouseUpCallback=this._browserMouseUpCallback.bind(this),this._handleToolModeChanged=this._handleToolModeChanged.bind(this),this._mouseDragCallback=this._mouseDragCallback.bind(this),this._resizeViewportAsync=gh(this._resizeViewport.bind(this),1),this._initialize()}get sourceEnabledElement(){return this._sourceEnabledElement}get viewportId(){return this._viewportId}get radius(){return this._radius}set radius(e){Math.abs(this._radius-e)>1e-5&&(this._radius=e,this._resized=!0)}update(){const{radius:e,position:r,visible:n}=this,{viewport:i}=this._enabledElement,{element:o}=i,a=2*e,[s,c]=r;this._resized&&(this._resizeViewportAsync(),this._resized=!1),Object.assign(o.style,{display:n?"block":"hidden",width:`${a}px`,height:`${a}px`,left:`${-e}px`,top:`${-e}px`,transform:`translate(${s}px, ${c}px)`}),this._isViewportReady&&(this._syncViewports(),i.render())}dispose(){const{viewport:e}=this._enabledElement,{element:r}=e,n=e.getRenderingEngine();this._removeEventListeners(r),n.disableElement(e.id),r.parentNode&&r.parentNode.removeChild(r)}_handleToolModeChanged(e){var s;const{_magnifyToolGroup:r}=this,{toolGroupId:n,toolName:i,mode:o,toolBindingsOptions:a}=e.detail;if(((s=this._sourceToolGroup)==null?void 0:s.id)===n)switch(o){case An.Active:r.setToolActive(i,a);break;case An.Passive:r.setToolPassive(i);break;case An.Enabled:r.setToolEnabled(i);break;case An.Disabled:r.setToolDisabled(i);break;default:throw new Error(`Unknow tool mode (${o})`)}}_inheritBorderRadius(e){const r=e.querySelector(".viewport-element"),n=e.querySelector(".cornerstone-canvas");r.style.borderRadius="inherit",n.style.borderRadius="inherit"}_createViewportNode(){const e=document.createElement("div"),{radius:r}=this,n=r*2;return e.classList.add(i5e),Object.assign(e.style,{display:"block",width:`${n}px`,height:`${n}px`,position:"absolute",overflow:"hidden",borderRadius:"50%",boxSizing:"border-box",left:`${-r}px`,top:`${-r}px`,transform:"translate(-1000px, -1000px)"}),e}_convertZoomFactorToParallelScale(e,r,n){const{parallelScale:i}=e.getCamera(),o=r.canvas.offsetWidth/e.canvas.offsetWidth;return i*(1/n)*o}_isStackViewport(e){return"setStack"in e}_isVolumeViewport(e){return"addVolumes"in e}_cloneToolGroups(e,r){const n=e.getActors(),i=`${r.id}-toolGroup`,o=Or(e.id,e.renderingEngineId),a=o.clone(i,s=>{const c=o.getToolInstance(s);return c instanceof ar&&!(c instanceof Zp)});return a.addViewport(r.id,r.renderingEngineId),n.filter(QD).forEach(s=>{Th(this.viewportId,[{segmentationId:s.referencedId,type:Dt.Labelmap}])}),{sourceToolGroup:o,magnifyToolGroup:a}}_cloneStack(e,r){const n=e.getImageIds();r.setStack(n).then(()=>{this._isViewportReady=!0,this.update()})}_cloneVolumes(e,r){const i=e.getActors().filter(o=>!QD(o)).map(o=>({volumeId:o.uid}));return r.setVolumes(i).then(()=>{this._isViewportReady=!0,this.update()}),r}_cloneViewport(e,r){const{viewportId:n}=this,i=e.getRenderingEngine(),{options:o}=e,a={element:r,viewportId:n,type:e.type,defaultOptions:{...o}};i.enableElement(a);const s=i.getViewport(n);this._isStackViewport(e)?this._cloneStack(e,s):this._isVolumeViewport(e)&&this._cloneVolumes(e,s),this._inheritBorderRadius(r);const c=this._cloneToolGroups(e,s);this._sourceToolGroup=c.sourceToolGroup,this._magnifyToolGroup=c.magnifyToolGroup}_cancelMouseEventCallback(e){e.stopPropagation(),e.preventDefault()}_browserMouseUpCallback(e){const{element:r}=this._enabledElement.viewport;document.removeEventListener("mouseup",this._browserMouseUpCallback),r.addEventListener("mouseup",this._cancelMouseEventCallback),r.addEventListener("mousemove",this._cancelMouseEventCallback)}_browserMouseDownCallback(e){var n;const{element:r}=this._enabledElement.viewport;this._canAutoPan=!!((n=e.target)!=null&&n.closest(".advancedMagnifyTool")),document.addEventListener("mouseup",this._browserMouseUpCallback),r.removeEventListener("mouseup",this._cancelMouseEventCallback),r.removeEventListener("mousemove",this._cancelMouseEventCallback)}_mouseDragCallback(e){if(!Be.isInteractingWithTool)return;const{_autoPan:r}=this;if(!r.enabled||!this._canAutoPan)return;const{currentPoints:n}=e.detail,{viewport:i}=this._enabledElement,{canvasToWorld:o}=i,{canvas:a}=n,{radius:s}=this,c=[s,s],l=yo(c,a),f=s-r.padding;if(l<=f)return;const u=l-f,d=Ga(qt(),a,c);Nc(d,d),Oc(d,d,u);const h=Qi(qt(),this.position,d),g=o(this.position),p=o(h),v=En(Ve(),p,g),y={points:{currentPosition:{canvas:this.position,world:g},newPosition:{canvas:h,world:p}},delta:{canvas:d,world:v}};r.callback(y)}_addBrowserEventListeners(e){document.addEventListener("mousedown",this._browserMouseDownCallback,!0),e.addEventListener("mousedown",this._cancelMouseEventCallback),e.addEventListener("mouseup",this._cancelMouseEventCallback),e.addEventListener("mousemove",this._cancelMouseEventCallback),e.addEventListener("dblclick",this._cancelMouseEventCallback)}_removeBrowserEventListeners(e){document.removeEventListener("mousedown",this._browserMouseDownCallback,!0),document.removeEventListener("mouseup",this._browserMouseUpCallback),e.removeEventListener("mousedown",this._cancelMouseEventCallback),e.removeEventListener("mouseup",this._cancelMouseEventCallback),e.removeEventListener("mousemove",this._cancelMouseEventCallback),e.removeEventListener("dblclick",this._cancelMouseEventCallback)}_addEventListeners(e){Ke.addEventListener(N.TOOL_MODE_CHANGED,this._handleToolModeChanged),e.addEventListener(N.MOUSE_MOVE,this._mouseDragCallback),e.addEventListener(N.MOUSE_DRAG,this._mouseDragCallback),this._addBrowserEventListeners(e)}_removeEventListeners(e){Ke.removeEventListener(N.TOOL_MODE_CHANGED,this._handleToolModeChanged),e.addEventListener(N.MOUSE_MOVE,this._mouseDragCallback),e.addEventListener(N.MOUSE_DRAG,this._mouseDragCallback),this._removeBrowserEventListeners(e)}_initialize(){const{_sourceEnabledElement:e}=this,{viewport:r}=e,{canvas:n}=r,i=this._createViewportNode();n.parentNode.appendChild(i),this._addEventListeners(i),this._cloneViewport(r,i),this._enabledElement=Ce(i)}_syncViewportsCameras(e,r){const n=e.canvasToWorld(this.position),i=this._convertZoomFactorToParallelScale(e,r,this.zoomFactor),{focalPoint:o,position:a,viewPlaneNormal:s}=r.getCamera(),c=Math.sqrt(Math.pow(o[0]-a[0],2)+Math.pow(o[1]-a[1],2)+Math.pow(o[2]-a[2],2)),l=[n[0],n[1],n[2]],f=[l[0]+c*s[0],l[1]+c*s[1],l[2]+c*s[2]];r.setCamera({parallelScale:i,focalPoint:l,position:f})}_syncStackViewports(e,r){r.setImageIdIndex(e.getCurrentImageIdIndex())}_syncViewports(){const{viewport:e}=this._sourceEnabledElement,{viewport:r}=this._enabledElement,n=e.getProperties();r.getImageData()&&(r.setProperties(n),this._syncViewportsCameras(e,r),this._isStackViewport(e)&&this._syncStackViewports(e,r),this._syncViewportsCameras(e,r),r.render())}_resizeViewport(){const{viewport:e}=this._enabledElement;e.getRenderingEngine().resize()}}Zp.toolName="AdvancedMagnify";const{EPSILON:y3}=cd;class Gf extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceViewportId:"",enforceSameFrameOfReference:!0,showFullDimension:!1}}){super(e,r),this.editData=null,this._init=()=>{var h;const i=Qo()[0];if(!i)return;let o=i.getViewports();o=b5(o,this.getToolName());const a=i.getViewport(this.configuration.sourceViewportId);if(!(a!=null&&a.getImageData()))return;const{element:s}=a,{viewUp:c,viewPlaneNormal:l}=a.getCamera(),f=Gv(a);let u=(h=this.editData)==null?void 0:h.annotation;const d=a.getFrameOfReferenceUID();if(u)this.editData.annotation.data.handles.points=f;else{const g={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...c],FrameOfReferenceUID:d,referencedImageId:null},data:{handles:{points:f}}};nn(g,s),u=g}this.editData={sourceViewportId:a.id,renderingEngine:i,annotation:u},Pe(o.filter(g=>g.id!==a.id).map(g=>g.id))},this.onSetToolEnabled=()=>{this._init()},this.onSetToolConfiguration=()=>{this._init()},this.onCameraModified=n=>{this._init()},this.renderAnnotation=(n,i)=>{var F,j;const{viewport:o}=n;if(!this.editData)return!1;const{annotation:a,sourceViewportId:s}=this.editData;let c=!1;const{viewport:l}=zn(s)||{};if(!l||l.id===o.id||!a||!((j=(F=a==null?void 0:a.data)==null?void 0:F.handles)!=null&&j.points)||this.configuration.enforceSameFrameOfReference&&l.getFrameOfReferenceUID()!==o.getFrameOfReferenceUID())return c;const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=a.data.handles.points[0],d=a.data.handles.points[1],h=a.data.handles.points[2],g=a.data.handles.points[3],{focalPoint:p,viewPlaneNormal:v,viewUp:y}=o.getCamera(),{viewPlaneNormal:m}=l.getCamera();if(this.isParallel(v,m))return c;const w=qs(v,p),x=[u,h,d,g],C=[u,d,h,g];let S=x,_=rr(Ve(),x[0],x[1]);_=tr(Ve(),_);let T=rr(Ve(),x[2],x[0]);T=tr(Ve(),T);const E=Rn(Ve(),_,T);if(this.isParallel(E,v))return c;this.isPerpendicular(_,v)&&(S=C);const D=F0(S[0],S[1],w),b=F0(S[2],S[3],w),{annotationUID:I}=a;f.annotationUID=I;const P=this.getStyle("lineWidth",f,a),M=this.getStyle("lineDash",f,a),L=this.getStyle("color",f,a),V=this.getStyle("shadow",f,a);let G=[D,b].map(Y=>o.worldToCanvas(Y));if(this.configuration.showFullDimension&&(G=this.handleFullDimension(o,D,v,y,b,G)),G.length<2)return c;const A=`${I}-line`;return vn(i,I,"1",G[0],G[1],{color:L,width:P,lineDash:M,shadow:V},A),c=!0,c},this.isPerpendicular=(n,i)=>{const o=Et(n,i);return Math.abs(o)pC(l,m)),[v,y]=[r,o].map(m=>pC(l,m));a=[[d,h],[h,g],[p,g],[d,p]].map(([m,w])=>this.intersectInfiniteLines(m,w,v,y)).filter(m=>m&&this.isInBound(m,u)).map(m=>{const w=jA(l,m);return e.worldToCanvas(w)})}catch(f){console.log(f)}return a}intersectInfiniteLines(e,r,n,i){const[o,a]=e,[s,c]=r,[l,f]=n,[u,d]=i,h=c-a,g=o-s,p=s*a-o*c,v=d-f,y=l-u,m=u*f-l*d;if(Math.abs(h*y-v*g)1-y3}isInBound(e,r){return e[0]>=0&&e[0]<=r[0]&&e[1]>=0&&e[1]<=r[1]}}Gf.toolName="ReferenceLines";const{EPSILON:eb}=cd;class KU extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{sourceImageIds:[]}}){super(e,r),this.onSetToolEnabled=()=>{this._init()},this.onSetToolActive=()=>{this._init()},this._init=()=>{const n=this.configuration.sourceImageIds;if(!(n!=null&&n.length)){console.warn("OverlayGridTool: No sourceImageIds provided in configuration");return}const i=mt("imagePlaneModule",n[0]);if(!i){console.warn("OverlayGridTool: No imagePlaneModule found for sourceImageIds");return}const{frameOfReferenceUID:o}=i,a=Kr(this.toolGroupId).viewportsInfo;if(!(a!=null&&a.length)){console.warn("OverlayGridTool: No viewports found");return}const s=un(this.getToolName(),o);if(!(s!=null&&s.length)){const c=n.map(f=>this.calculateImageIdPointSets(f)),l={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:o,referencedImageId:null},data:{viewportData:new Map,pointSets:c}};nn(l,o)}Pe(a.map(({viewportId:c})=>c))},this.calculateImageIdPointSets=n=>{const{imagePositionPatient:i,rows:o,columns:a,rowCosines:s,columnCosines:c,rowPixelSpacing:l,columnPixelSpacing:f}=mt("imagePlaneModule",n),u=[...i],d=[...i],h=[...i],g=[...i];return Tn(d,i,c,a*f),Tn(h,i,s,o*l),Tn(g,h,c,a*f),{pointSet1:[u,h,d,g],pointSet2:[u,d,h,g]}},this.renderAnnotation=(n,i)=>{const o=this.configuration.sourceImageIds;let a=!1;if(!(o!=null&&o.length))return a;const{viewport:s,FrameOfReferenceUID:c}=n;if(s.getImageIds().length<2)return a;const f=un(this.getToolName(),c);if(!(f!=null&&f.length))return a;const u=f[0],{annotationUID:d}=u,{focalPoint:h,viewPlaneNormal:g}=s.getCamera(),p={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},v=this.getImageIdNormal(o[0]);if(this.isParallel(g,v))return a;const y=qs(g,h),m=u.data.pointSets,w=u.data.viewportData;for(let x=0;xs.worldToCanvas(G)),L=`${d}-line`,V=`${x}`;vn(i,d,V,M[0],M[1],{color:I,width:D,lineDash:b,shadow:P},L)}return a=!0,a},this.initializeViewportData=(n,i)=>(n.set(i,{pointSetsToUse:[],lineStartsWorld:[],lineEndsWorld:[]}),n.get(i)),this.isPerpendicular=(n,i)=>{const o=Et(n,i);return Math.abs(o)1-eb}getImageIdNormal(e){const{imageOrientationPatient:r}=mt("imagePlaneModule",e),n=bt(r[0],r[1],r[2]),i=bt(r[3],r[4],r[5]);return Rn(Ve(),n,i)}}KU.toolName="OverlayGrid";class qU extends Fu{constructor(e={},r={configuration:{opacity:.5}}){super(e,r),this._init=()=>{var s;const n=Kr(this.toolGroupId).viewportsInfo;if(!(n!=null&&n.length)){console.warn(this.getToolName()+"Tool: No viewports found");return}const i=(s=Jr(n[0].renderingEngineId))==null?void 0:s.getViewport(n[0].viewportId);if(!i)return;const o=i.getFrameOfReferenceUID(),a=un(this.getToolName(),o);if(!(a!=null&&a.length)){const c=new Map;l5e(c,n);const l={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),FrameOfReferenceUID:o,referencedImageId:null},data:{actorsWorldPointsMap:c}};nn(l,o)}Pe(n.map(({viewportId:c})=>c))},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=n=>{this._init()},this.renderAnnotation=(n,i)=>{const{viewport:o,FrameOfReferenceUID:a}=n;let s=!1;const c=un(this.getToolName(),a);if(!(c!=null&&c.length))return s;const l=c[0],{annotationUID:f}=l,u=l.data.actorsWorldPointsMap;XU(u,o);const d=o.getActors(),h=YU(o);return d.forEach(g=>{if(!(g!=null&&g.clippingFilter))return;const p=u.get(g.uid);if(!p||!p.get(h))return;let v=1;const{worldPointsSet:y,color:m}=p.get(h);for(let w=0;wo.worldToCanvas(T)),S={color:m,fillColor:m,fillOpacity:this.configuration.opacity,closePath:!0,lineWidth:2},_=g.uid+"#"+v;Wc(i,f,_,C,S),v++}}),s=!0,s}}}function l5e(t,e){e.forEach(({viewportId:r,renderingEngineId:n})=>{var o;const i=(o=Jr(n))==null?void 0:o.getViewport(r);XU(t,i)})}function XU(t,e){const r=e.getActors(),n=YU(e);r.forEach(i=>{if(!(i!=null&&i.clippingFilter))return;let o=t.get(i.uid);if(o||(o=new Map,t.set(i.uid,o)),!o.get(n)){const a=i.clippingFilter.getOutputData(),s=bU(a);if(!s)return;const c=i.actor.getProperty().getColor(),l=u5e(c);o.set(n,{worldPointsSet:s,color:l})}})}function YU(t){const{viewPlaneNormal:e}=t.getCamera(),r=t.getCurrentImageIdIndex();return`${t.id}-${dF(e)}-${r}`}function u5e(t){function e(r){let n=Math.floor(r*255).toString(16);return n.length===1&&(n="0"+n),n}return"#"+e(t[0])+e(t[1])+e(t[2])}qU.toolName="SegmentationIntersection";class ua extends Fu{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,displayThreshold:5,positionSync:!0,disableCursor:!1}}){super(e,r),this.isDrawing=!1,this.isHandleOutsideImage=!1,this._elementWithCursor=null,this._currentCursorWorldPosition=null,this._currentCanvasPosition=null,this._disableCursorEnabled=!1,this.mouseMoveCallback=n=>{const{detail:i}=n,{element:o,currentPoints:a}=i;this._currentCursorWorldPosition=a.world,this._currentCanvasPosition=a.canvas,this._elementWithCursor=o;const s=this.getActiveAnnotation(o);return s===null?(this.createInitialAnnotation(a.world,o),!1):(this.updateAnnotationPosition(o,s),!1)},this.createInitialAnnotation=(n,i)=>{const o=Ce(i);if(!o)throw new Error("No enabled element found");const{viewport:a,renderingEngine:s}=o;this.isDrawing=!0;const c=a.getCamera(),{viewPlaneNormal:l,viewUp:f}=c;if(!l||!f)throw new Error("Camera not found");const u=this.getReferencedImageId(a,n,l,f),d=a.getFrameOfReferenceUID(),h={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...f],FrameOfReferenceUID:d,referencedImageId:u},data:{label:"",handles:{points:[[...n]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}};if(un(this.getToolName(),i).length>0)return null;if(nn(h,i)===null)return;const v=_t(i,this.getToolName(),!1);Pe(v)},this.onCameraModified=n=>{const i=n.detail,{element:o,previousCamera:a,camera:s}=i,l=Ce(o).viewport;if(o!==this._elementWithCursor)return;const f=a.focalPoint,u=s.viewPlaneNormal,d=s.focalPoint,h=[0,0,0];if(Xt.subtract(d,f,h),h.reduce((v,y)=>v+y,0)===0)return;const g=Xt.dot(h,u);if(Math.abs(g)<.01||!this._currentCanvasPosition)return;const p=l.canvasToWorld(this._currentCanvasPosition);this._currentCursorWorldPosition=p,this.updateAnnotationPosition(o,this.getActiveAnnotation(o))},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a,FrameOfReferenceUID:s}=n,c=this._elementWithCursor===a.element;this.configuration.positionSync&&!c&&this.updateViewportImage(a);const{element:l}=a;let f=un(this.getToolName(),l);if(!(f!=null&&f.length)||(f=this.filterInteractableAnnotationsForElement(l,f),!(f!=null&&f.length)))return o;const u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;disNaN(I)))return o;const S=y.map(I=>a.worldToCanvas(I));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(g))continue;const _={upper:"upper",right:"right",lower:"lower",left:"left"},[T,E]=S[0],D=c?20:7,b=c?5:7;vn(i,g,_.upper,[T,E-(D/2+b)],[T,E-D/2],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.lower,[T,E+(D/2+b)],[T,E+D/2],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.right,[T+(D/2+b),E],[T+D/2,E],{color:C,lineDash:x,lineWidth:w}),vn(i,g,_.left,[T-(D/2+b),E],[T-D/2,E],{color:C,lineDash:x,lineWidth:w}),o=!0}return o},this._disableCursorEnabled=this.configuration.disableCursor}onSetToolActive(){if(this._disableCursorEnabled=this.configuration.disableCursor,!this._disableCursorEnabled)return;const e=Kr(this.toolGroupId).viewportsInfo;if(!e)return;e.map(n=>Ti(n.viewportId,n.renderingEngineId)).forEach(n=>{n&&Ot(n.viewport.element)})}onSetToolDisabled(){if(!this._disableCursorEnabled)return;const e=Kr(this.toolGroupId).viewportsInfo;if(!e)return;e.map(n=>Ti(n.viewportId,n.renderingEngineId)).forEach(n=>{n&&zt(n.viewport.element)})}getActiveAnnotation(e){const r=un(this.getToolName(),e);return r.length?r[0]:null}updateAnnotationPosition(e,r){var a,s;const n=this._currentCursorWorldPosition;if(!n||!((s=(a=r.data)==null?void 0:a.handles)!=null&&s.points))return;r.data.handles.points=[[...n]],r.invalidated=!0;const i=_t(e,this.getToolName(),!1);Ce(e)&&Pe(i)}filterInteractableAnnotationsForElement(e,r){var d,h,g;if(!(r instanceof Array)||r.length===0)return[];const n=r[0],i=(d=Ce(e))==null?void 0:d.viewport;if(!i)return[];const o=i.getCamera(),{viewPlaneNormal:a,focalPoint:s}=o;if(!a||!s)return[];const c=(g=(h=n.data)==null?void 0:h.handles)==null?void 0:g.points;if(!(c instanceof Array)||c.length!==1)return[];const l=c[0],f=qs(a,s);return Mp(f,l)isNaN(n)))){if(e instanceof lr){const n=FT(r,e);if(n===null)return;n!==e.getCurrentImageIdIndex()&&e.setImageIdIndex(n)}else if(e instanceof ur){const{focalPoint:n,viewPlaneNormal:i}=e.getCamera();if(!n||!i)return;const o=qs(i,n),a=Mp(o,r,!0);if(Math.abs(a)<.5)return;const s=tr(Ve(),bt(...i)),c=Ni(Ve(),s,a),l=Ai(Ve(),bt(...n),c);{e.setCamera({focalPoint:l});const f=e.getRenderingEngine();f&&f.renderViewport(e.id)}}}}}ua.toolName="ReferenceCursors";const tb=[];class JU extends Fu{constructor(e={},r={configuration:{viewportId:"",scaleLocation:"bottom"}}){super(e,r),this.editData=null,this._init=()=>{var g,p;const i=Qo()[0];if(!i)return;const o=Kr(this.toolGroupId).viewportsInfo;if(!o)return;const a=o.map(v=>Ti(v.viewportId,v.renderingEngineId));let{viewport:s}=a[0];const{FrameOfReferenceUID:c}=a[0];if(this.configuration.viewportId&&a.forEach(v=>{v.viewport.id==this.configuration.viewportId&&(s=v.viewport)}),!s)return;const{viewUp:l,viewPlaneNormal:f}=s.getCamera(),u=Gv(s);let d=(g=this.editData)==null?void 0:g.annotation;const h=un(this.getToolName(),s.element);h.length&&(d=h.filter(v=>v.data.viewportId==s.id)[0]),a.forEach(v=>{const{viewport:y}=v;if(!tb.includes(y.id)){const m={metadata:{toolName:this.getToolName(),viewPlaneNormal:[...f],viewUp:[...l],FrameOfReferenceUID:c,referencedImageId:null},data:{handles:{points:Gv(y)},viewportId:y.id}};tb.push(y.id),nn(m,y.element),d=m}}),(p=this.editData)!=null&&p.annotation&&this.editData.annotation.data.viewportId==s.id&&(this.editData.annotation.data.handles.points=u,this.editData.annotation.data.viewportId=s.id),this.editData={viewport:s,renderingEngine:i,annotation:d}},this.onSetToolEnabled=()=>{this._init()},this.onCameraModified=n=>{this.configuration.viewportId=n.detail.viewportId,this._init()},this.computeScaleSize=(n,i,o)=>{const a=[16e3,8e3,4e3,2e3,1e3,500,250,100,50,25,10,5,2];let s;return o=="top"||o=="bottom"?s=a.filter(c=>cn*.2):s=a.filter(c=>ci*.2),s[0]},this.computeEndScaleTicks=(n,i)=>{const o={bottom:[[0,-10],[0,-10]],top:[[0,10],[0,10]],left:[[0,0],[10,0]],right:[[0,0],[-10,0]]},a=[[n[1][0]+o[i][0][0],n[1][1]+o[i][0][0]],[n[1][0]+o[i][1][0],n[1][1]+o[i][1][1]]],s=[[n[0][0]+o[i][0][0],n[0][1]+o[i][0][0]],[n[0][0]+o[i][1][0],n[0][1]+o[i][1][1]]];return{endTick1:a,endTick2:s}},this.computeInnerScaleTicks=(n,i,o,a,s)=>{let c;i=="bottom"||i=="top"?c=s[0][0]-a[0][0]:(i=="left"||i=="right")&&(c=s[0][1]-a[0][1]);const l=[],f=[],u=[];let d=n;n>=50&&(d=n/10);const h=c/d;for(let g=0;g{let a,s=rr(Ve(),o[0],o[1]);s=tr(Ve(),s);let c=rr(Ve(),o[2],o[0]);c=tr(Ve(),c);const l={bottom:[o[1],o[2]],top:[o[0],o[3]],right:[o[2],o[3]],left:[o[0],o[1]]},f=Ai(Ve(),l[i][0],l[i][0]).map(d=>d/2),u=n/2/Math.sqrt(Math.pow(s[0],2)+Math.pow(s[1],2)+Math.pow(s[2],2));return i=="top"||i=="bottom"?a=[rr(Ve(),f,c.map(d=>d*u)),Ai(Ve(),f,c.map(d=>d*u))]:(i=="left"||i=="right")&&(a=[Ai(Ve(),f,s.map(d=>d*u)),rr(Ve(),f,s.map(d=>d*u))]),a},this.computeCanvasScaleCoordinates=(n,i,o,a,s)=>{let c;if(s=="top"||s=="bottom"){const l=i[0][0]-i[1][0];c=[[n.width/2-l/2,o.height],[n.width/2+l/2,o.height]]}else if(s=="left"||s=="right"){const l=i[0][1]-i[1][1];c=[[a.width,n.height/2-l/2],[a.width,n.height/2+l/2]]}return c},this.computeScaleBounds=(n,i,o,a)=>{const s=i*Math.min(1e3,n.width),c=o*Math.min(1e3,n.height),l={bottom:[-c,-s],top:[c,s],left:[c,s],right:[-c,-s]},f={bottom:[n.height,n.width],top:[0,n.width],left:[n.height,0],right:[n.height,n.width]};return{height:f[a][0]+l[a][0],width:f[a][1]+l[a][1]}}}renderAnnotation(e,r){if(!this.editData||!this.editData.viewport)return;const n=this.configuration.scaleLocation,{viewport:i}=e,a=un(this.getToolName(),i.element).filter(pe=>pe.data.viewportId==i.id)[0],s=e.viewport.canvas,c=!1;if(!i)return c;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:e.viewport.id},f={width:s.width/window.devicePixelRatio||1,height:s.height/window.devicePixelRatio||1},u=a.data.handles.points[0],d=a.data.handles.points[1],h=a.data.handles.points[2],g=a.data.handles.points[3],p=[u,h,d,g],v=ki(h,g),y=ki(u,h),m=this.computeScaleBounds(f,.05,.05,n),w=this.computeScaleBounds(f,.05,.05,n),x=this.computeScaleSize(v,y,n),C=this.computeWorldScaleCoordinates(x,n,p).map(pe=>i.worldToCanvas(pe)),S=this.computeCanvasScaleCoordinates(f,C,w,m,n),_=this.computeEndScaleTicks(S,n),{annotationUID:T}=a;l.annotationUID=T;const E=this.getStyle("lineWidth",l,a),D=this.getStyle("lineDash",l,a),b=this.getStyle("color",l,a),I=this.getStyle("shadow",l,a),P=`${T}-scaleline`;vn(r,T,"1",S[0],S[1],{color:b,width:E,lineDash:D,shadow:I},P);const L=`${T}-left`;vn(r,T,"2",_.endTick1[0],_.endTick1[1],{color:b,width:E,lineDash:D,shadow:I},L);const G=`${T}-right`;vn(r,T,"3",_.endTick2[0],_.endTick2[1],{color:b,width:E,lineDash:D,shadow:I},G);const k={bottom:[-10,-42],top:[-12,-35],left:[-40,-20],right:[-50,-20]},F=[S[0][0]+k[n][0],S[0][1]+k[n][1]],j=this._getTextLines(x),{tickIds:Y,tickUIDs:re,tickCoordinates:ue}=this.computeInnerScaleTicks(x,n,T,_.endTick1,_.endTick2);for(let pe=0;pe=50?(r=e/10,n=" cm"):(r=e,n=" mm"),[r.toString().concat(n)]}}JU.toolName="ScaleOverlay";const ZU=(t,e,r)=>{var a,s,c;if(!((c=(s=(a=e==null?void 0:e.data)==null?void 0:a.contour)==null?void 0:s.polyline)!=null&&c.length))return;const{polyline:n}=e.data.contour,{length:i}=n;let o=1/0;for(let l=0;lthis.toolInfo.toolSize||(this.pushOneHandle(s,a,r),o.first===void 0&&(o.first=s),o.last=s)}if(o.first!==void 0&&o.last!==void 0)for(let s=0;s0&&(i.toolSize=Math.min(i.maxToolSize,o))}getMaxSpacing(e){return Math.max(this.toolInfo.toolSize/4,e)}getInsertPosition(e,r,n){let i;const{points:o,element:a,mouseCanvasPoint:s}=n,c=this.toolInfo.toolSize,l=Ce(a),{viewport:f}=l,u=f.worldToCanvas(o[e]),d=f.worldToCanvas(o[r]),h=[(u[0]+d[0])/2,(u[1]+d[1])/2],g=yo(s,h);if(g=0;l--){if(l>=s-1||l<0)continue;const f=l+1,u=yo(n[l],n[f]);if(u>c){const d=this.directionalVector(n[l],n[f]),g=(u-e.meanDistance)/e.meanDistance*e.meanDistance*Ns.CHAIN_PULL_STRENGTH_FACTOR;n[l][0]+=d[0]*g,n[l][1]+=d[1]*g,n[l][2]+=d[2]*g}}for(let l=a+1;l=s||l<=0)continue;const f=l-1,u=yo(n[l],n[f]);if(u>c){const d=this.directionalVector(n[l],n[f]),g=(u-e.meanDistance)/e.meanDistance*e.meanDistance*Ns.CHAIN_PULL_STRENGTH_FACTOR;n[l][0]+=d[0]*g,n[l][1]+=d[1]*g,n[l][2]+=d[2]*g}}}};Ns.shapeName="Circle",Ns.CHAIN_MAINTENANCE_ITERATIONS=3,Ns.CHAIN_PULL_STRENGTH_FACTOR=.3,Ns.MAX_INTER_DISTANCE_FACTOR=1.2;let Hg=Ns;class X0 extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{minSpacing:1,referencedToolNames:["PlanarFreehandROI","PlanarFreehandContourSegmentationTool"],toolShape:"circle",referencedToolName:"PlanarFreehandROI",updateCursorSize:"dynamic"}}){super(e,r),this.registeredShapes=new Map,this.isActive=!1,this.commonData={activeAnnotationUID:null,viewportIdsToRender:[],isEditingOpenContour:!1,canvasLocation:void 0},this.preMouseDownCallback=n=>{const i=n.detail,o=i.element;if(this.configureToolSize(n),this.selectFreehandTool(i),this.commonData.activeAnnotationUID!==null)return this.isActive=!0,Ot(o),this.activateModify(o),!0},this.mouseMoveCallback=n=>{this.mode===An.Active?(this.configureToolSize(n),this.updateCursor(n)):this.commonData.canvasLocation=void 0},this.endCallback=n=>{const i=n.detail,{element:o}=i,a=this.configuration,s=Ce(o);this.isActive=!1,this.deactivateModify(o),zt(o);const{renderingEngineId:c,viewportId:l}=s,u=Or(l,c).getToolInstance(a.referencedToolName),h=this.filterSculptableAnnotationsForElement(o).find(g=>g.annotationUID===this.commonData.activeAnnotationUID);u.configuration.calculateStats&&(h.invalidated=!0),tn(h,o,Ht.HandlesUpdated)},this.dragCallback=n=>{const i=n.detail,o=i.element;this.updateCursor(n);const a=this.filterSculptableAnnotationsForElement(o),s=a.find(l=>l.annotationUID===this.commonData.activeAnnotationUID);if(!(a!=null&&a.length)||!this.isActive)return;const c=s.data.contour.polyline;this.sculpt(i,c)},this.registerShapes(Hg.shapeName,Hg),this.setToolShape(this.configuration.toolShape)}registerShapes(e,r){const n=new r;this.registeredShapes.set(e,n)}sculpt(e,r){const n=this.configuration,i=e.element,o=Ce(i),{viewport:a}=o,s=this.registeredShapes.get(this.selectedShape);this.sculptData={mousePoint:e.currentPoints.world,mouseCanvasPoint:e.currentPoints.canvas,deltaWorld:e.deltaPoints.world,points:r,maxSpacing:s.getMaxSpacing(n.minSpacing),element:i};const c=s.pushHandles(a,this.sculptData);c.first!==void 0&&this.insertNewHandles(c)}interpolatePointsWithinMaxSpacing(e,r,n,i){const{element:o}=this.sculptData,a=Ce(o),{viewport:s}=a,c=nb(e+1,r.length),l=s.worldToCanvas(r[e]),f=s.worldToCanvas(r[c]);yo(l,f)>i&&n.push(e)}updateCursor(e){const r=e.detail,n=r.element,i=Ce(n),{renderingEngine:o,viewport:a}=i;this.commonData.viewportIdsToRender=[a.id];const s=this.filterSculptableAnnotationsForElement(n);if(!(s!=null&&s.length))return;const c=s.find(l=>l.annotationUID===this.commonData.activeAnnotationUID);if(this.commonData.canvasLocation=r.currentPoints.canvas,this.isActive)c.highlighted=!0;else{const l=this.registeredShapes.get(this.selectedShape),f=r.currentPoints.canvas;this.configuration.updateCursorSize==="dynamic"&&l.updateToolSize(f,a,c)}Pe(this.commonData.viewportIdsToRender)}filterSculptableAnnotationsForElement(e){const r=this.configuration,n=Ce(e),{renderingEngineId:i,viewportId:o}=n,a=[],c=Or(o,i).getToolInstance(r.referencedToolName);return r.referencedToolNames.forEach(l=>{const f=un(l,e);f&&a.push(...f)}),c.filterInteractableAnnotationsForElement(e,a)}configureToolSize(e){this.registeredShapes.get(this.selectedShape).configureToolSize(e)}insertNewHandles(e){const r=this.findNewHandleIndices(e);let n=0;for(let i=0;i<(r==null?void 0:r.length);i++){const o=r[i]+1+n;this.insertHandleRadially(o),n++}}findNewHandleIndices(e){const{points:r,maxSpacing:n}=this.sculptData,i=[];for(let o=e.first;o<=e.last;o++)this.interpolatePointsWithinMaxSpacing(o,r,i,n);return i}insertHandleRadially(e){const{points:r}=this.sculptData;if(e>r.length-1&&this.commonData.isEditingOpenContour)return;const n=this.registeredShapes.get(this.selectedShape),i=e-1,o=nb(e,r.length),s=n.getInsertPosition(i,o,this.sculptData);r.splice(e,0,s)}selectFreehandTool(e){const r=this.getClosestFreehandToolOnElement(e);r!==void 0&&(this.commonData.activeAnnotationUID=r)}getClosestFreehandToolOnElement(e){const{element:r}=e,n=Ce(r),{viewport:i}=n,o=this.configuration,a=this.filterSculptableAnnotationsForElement(r);if(!(a!=null&&a.length))return;const s=e.currentPoints.canvas,c={distance:1/0,toolIndex:void 0,annotationUID:void 0};for(let l=0;l<(a==null?void 0:a.length);l++){if(a[l].isLocked||!a[l].isVisible)continue;const f=ZU(i,a[l],s);f!==-1&&f(t+e)%e;X0.toolName="SculptorTool";const f5e={Z:[0,0,1]};class QU extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{direction:f5e.Z,rotateIncrementDegrees:30}}){super(e,r)}mouseWheelCallback(e){const{element:r,wheel:n}=e.detail,i=Ce(r),{viewport:o}=i,{direction:a,rotateIncrementDegrees:s}=this.configuration,c=o.getCamera(),{viewUp:l,position:f,focalPoint:u}=c,{direction:d}=n,[h,g,p]=u,[v,y,m]=a,w=d*(s*Math.PI)/180,x=[0,0,0],C=[0,0,0],S=[0,0,0],_=Vt(new Float32Array(16));Lr(_,_,[h,g,p]),go(_,_,w,[v,y,m]),Lr(_,_,[-h,-g,-p]),Jt(x,f,_),Jt(C,u,_),Vt(_),go(_,_,w,[v,y,m]),Jt(S,l,_),o.setCamera({position:x,viewUp:S,focalPoint:C}),o.render()}}QU.toolName="VolumeRotateMouseWheel";const np=class np extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,getTextCallback:d5e,changeTextCallback:h5e,preventHandleOutsideImage:!1}}){super(e,r),this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{annotationUID:l}=i,f=i.data.handles.points[0],u=c.worldToCanvas(f);if(yr(o,u)=x&&o[0]<=x+v.width&&o[1]>=C&&o[1]<=C+v.height},this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=this.getReferencedImageId(l,s,u,d),g=l.getFrameOfReferenceUID(),p={annotationUID:null,highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:g,referencedImageId:h,...l.getViewReference({points:[s]})},data:{text:"",handles:{points:[[...s],[...s]]},label:""}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,newAnnotation:!0,viewportIdsToRender:v,offset:[0,0,0]},n.preventDefault(),Pe(v),this.configuration.getTextCallback(y=>{if(!y){gn(p.annotationUID),Pe(v),this.isDrawing=!1;return}zt(a),p.data.text=y,Nn(p),Pe(v)}),this.createMemo(a,p,{newAnnotation:!0}),p},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a,currentPoints:s}=o;i.highlighted=!0;const c=_t(a,this.getToolName());let l=[0,0,0];if(s&&s.world){const f=s.world,u=i.data.handles.points[0];l=[u[0]-f[0],u[1]-f[1],u[2]-f[2]]}this.editData={annotation:i,viewportIdsToRender:c,offset:l},this._activateModify(a),Ot(a),Pe(c),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData;this._deactivateDraw(o),this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragCallback=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,offset:f}=this.editData;f?c.data.handles.points[0]=[s[0]+f[0],s[1]+f[1],s[2]+f[2]]:c.data.handles.points[0]=[...s],c.invalidated=!0,Pe(l),tn(c,a,Ht.LabelChange)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length))return o;c=this.filterInteractableAnnotationsForElement(s,c);const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;f{const o=zn(e);if(!o)return;const{viewport:a}=o,s=a.getFrameOfReferenceUID(),{viewPlaneNormal:c,viewUp:l}=a.getCamera(),f=new np,u=f.getReferencedImageId(a,r,c,l),d={annotationUID:(i==null?void 0:i.annotationUID)||Dn(),data:{text:n,handles:{points:[r]}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:f.getToolName(),viewPlaneNormal:c,FrameOfReferenceUID:s,referencedImageId:u,...i}};nn(d,a.element),Pe([a.id])};let hy=np;function d5e(t){return t(prompt("Enter your annotation:"))}function h5e(t,e,r){return r(prompt("Enter your annotation:"))}hy.toolName="Label";const{transformWorldToIndex:rb}=Mn,n0=class n0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:g5e,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:f,viewUp:u,position:d}=l.getCamera(),h=this.getReferencedImageId(l,s,f,u),g={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:h,viewUp:u,cameraPosition:d},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(g,a);const p=_t(a,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(p),g},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=d.world;u.handles.points[c]=[...h],a.invalidated=!0}this.editData.hasMoved=!0,Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(k));if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let _;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(_=[S[y]]),_&&ir(i,g,"0",S,{color:m,lineDash:x,lineWidth:w});const T=`${g}-line`;if(vn(i,g,"1",S[0],S[1],{color:m,width:w,lineDash:x,shadow:C},T),o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const D=this.getLinkedTextBoxStyle(u,h);if(!D.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const b=this.configuration.getTextLines(p,l);if(!p.handles.textBox.hasMoved){const k=na(S);p.handles.textBox.worldPosition=a.canvasToWorld(k)}const I=a.worldToCanvas(p.handles.textBox.worldPosition),M=qi(i,g,"1",b,I,S,{},D),{x:L,y:V,width:G,height:A}=M;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([L,V]),topRight:a.canvasToWorld([L+G,V]),bottomLeft:a.canvasToWorld([L,V+A]),bottomRight:a.canvasToWorld([L+G,V+A])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(f=>f===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o),Pe(l),e.preventDefault()}_calculateLength(e,r){const n=e[0]-r[0],i=e[1]-r[1],o=e[2]-r[2];return Math.sqrt(n*n+i*i+o*o)}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport,a=i.handles.points[0],s=i.handles.points[1],{cachedStats:c}=i,l=Object.keys(c);for(let u=0;u{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=n0.hydrateBase(n0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let Iu=n0;function g5e(t,e){const r=t.cachedStats[e],{length:n,unit:i}=r;return n==null||isNaN(n)?void 0:[`${an(n)} ${i}`]}const{transformWorldToIndex:ib}=Mn,TE=class TE extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:p5e}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:u,viewUp:d,position:h}=l.getCamera(),g=this.getReferencedImageId(l,s,u,d),p={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:g,viewUp:d,cameraPosition:h},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(p,a);const v=_t(a,this.getToolName());return this.editData={annotation:p,viewportIdsToRender:v,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(v),p},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Ce(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l}=this.editData,{data:f}=a;if(l){const{deltaPoints:h}=i,g=h.world,{textBox:p}=f.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=i,g=h.world;f.handles.points.forEach(v=>{v[0]+=g[0],v[1]+=g[1],v[2]+=g[2]}),a.invalidated=!0}else{const{currentPoints:h}=i,g=h.world;f.handles.points[c]=[...g],a.invalidated=!0}this.editData.hasMoved=!0;const u=Ce(o),{renderingEngine:d}=u;Pe(s)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Ce(n),Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(A));let _;if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,unit:null},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!Gr(g))continue;if(!Zr(g)&&!this.editData&&y!==null&&(_=[S[y]]),_&&ir(i,g,"0",S,{color:m,lineDash:x,lineWidth:w}),Gk(i,g,"0",S[0],S[1],{color:m,width:w,lineDash:x}),o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;const E=this.getLinkedTextBoxStyle(u,h);if(!E.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const D=this.configuration.getTextLines(p,l);if(!p.handles.textBox.hasMoved){const A=na(S);p.handles.textBox.worldPosition=a.canvasToWorld(A)}const b=a.worldToCanvas(p.handles.textBox.worldPosition),P=qi(i,g,"1",D,b,S,{},E),{x:M,y:L,width:V,height:G}=P;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([M,L]),topRight:a.canvasToWorld([M+V,L]),bottomLeft:a.canvasToWorld([M,L+G]),bottomRight:a.canvasToWorld([M+V,L+G])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_calculateHeight(e,r){const n=r[0]-e[0],i=r[1]-e[1],o=r[2]-e[2];if(n==0)return i!=0?Math.abs(o):0;if(i==0)return Math.abs(o);if(o==0)return Math.abs(i)}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport,a=i.handles.points[0],s=i.handles.points[1],{cachedStats:c}=i,l=Object.keys(c);for(let u=0;u{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=this.constructor.createAnnotationForViewport(l,{data:{handles:{points:[[...s]]}}});nn(f,a);const u=_t(a,this.getToolName());return this.editData={annotation:f,newAnnotation:!0,viewportIdsToRender:u},this._activateModify(a),Ot(a),n.preventDefault(),Pe(u),f},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:f}=Ce(o);this.eventDispatchDetail={viewportId:l,renderingEngineId:f.id},this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,newAnnotation:f}=this.editData,{data:u}=c;this.createMemo(a,c,{newAnnotation:f}),u.handles.points[0]=[...s],c.invalidated=!0,Pe(l)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;d{const I=Vr(_),P=b.hasImageURI(I),M=Vr(b.getCurrentImageId());return P&&M!==I})&&delete p.cachedStats[T]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(g))continue;ir(i,g,"0",[y],{color:m,lineWidth:w,handleRadius:this.configuration.handleRadius}),o=!0;const C=this.getLinkedTextBoxStyle(u,h);if(!C.visibility)continue;const S=this.configuration.getTextLines(p,l);if(S){const _=[y[0]+this.configuration.textCanvasOffset.x,y[1]+this.configuration.textCanvasOffset.y];Eu(i,g,"0",S,[_[0],_[1]],C)}}return o}}isPointNearTool(e,r,n,i){const o=Ce(e),{viewport:a}=o,{data:s}=r,c=s.handles.points[0],l=a.worldToCanvas(c);return yr(n,l)b!==null);_=D?E.values:_,T=D?E.units:"raw"}else T=sl(C,e.metadata.referencedImageId,p);f[g]={index:S,value:_,Modality:C,modalityUnit:T}}else this.isHandleOutsideImage=!0,f[g]={index:S,Modality:C}}const d=e.invalidated;return e.invalidated=!1,d&&tn(e,c,i),f}};Gl.toolName="Probe",Gl.probeDefaults={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:v5e,handleRadius:"6",textCanvasOffset:{x:6,y:-6}}},Gl.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,viewUp:c,instance:l,viewport:f}=Gl.hydrateBase(Gl,i,r,n),{toolInstance:u,...d}=n||{},h={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:l.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...d}};nn(h,f.element),Pe([f.id])};let nl=Gl;function v5e(t,e){const r=t.cachedStats[e],{index:n,value:i,modalityUnit:o}=r;if(i===void 0||!n)return;const a=[];if(a.push(`(${n[0]}, ${n[1]}, ${n[2]})`),i instanceof Array&&o instanceof Array)for(let s=0;s{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p={invalidated:!0,highlighted:!0,isVisible:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:l.getFrameOfReferenceUID(),referencedImageId:g},data:{label:"",handles:{points:[[...s]]},cachedStats:{}}},v=_t(a,this.getToolName());return this.editData={annotation:p,newAnnotation:!0,viewportIdsToRender:v},this._activateModify(a),Ot(a),n.preventDefault(),Pe(v),p},this.postTouchStartCallback=n=>this.postMouseDownCallback(n),this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;if(!this.editData)return o;const s=this.filterInteractableAnnotationsForElement(a.element,[this.editData.annotation]);if(!(s!=null&&s.length))return o;const c=this.getTargetId(a),l=a.getRenderingEngine(),f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=this.editData.annotation,d=u.annotationUID,h=u.data,g=h.handles.points[0],p=a.worldToCanvas(g);f.annotationUID=d;const{color:v}=this.getAnnotationStyle({annotation:u,styleSpecifier:f});if(!h.cachedStats[c]||h.cachedStats[c].value===null?(h.cachedStats[c]={Modality:null,index:null,value:null},this._calculateCachedStats(u,l,n)):u.invalidated&&this._calculateCachedStats(u,l,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;ir(i,d,"0",[p],{color:v}),o=!0;const m=this.configuration.getTextLines(h,c);if(m){const w=[p[0]+6,p[1]-6];Eu(i,d,"0",m,[w[0],w[1]],this.getLinkedTextBoxStyle(f,u))}return o}}};EE.toolName="DragProbe";let WC=EE;function y5e(t,e){const r=t.cachedStats[e],{index:n,value:i,modalityUnit:o}=r;if(i===void 0)return;const a=[];return a.push(`(${n[0]}, ${n[1]}, ${n[2]})`),a.push(`${i.toFixed(2)} ${o}`),a}const{transformWorldToIndex:ob}=Mn,r0=class r0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:w5e,statsCalculator:rc}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world;o.canvas;const c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},cachedStats:{},initialRotation:l.getRotation()}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,centerWorld:s,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=f.map(T=>c.worldToCanvas(T)),[d,h,g,p]=u,v=Math.hypot(g[0]-p[0],g[1]-p[1]),y=Math.hypot(h[0]-d[0],h[1]-d[1]),m=Math.atan2(g[1]-p[1],g[0]-p[0]),w=[(g[0]+p[0])/2,(h[1]+d[1])/2],x={center:w,xRadius:(v-a)/2,yRadius:(y-a)/2,angle:m},C={center:w,xRadius:(v+a)/2,yRadius:(y+a)/2,angle:m},S=this._pointInEllipseCanvas(x,o);return!!(this._pointInEllipseCanvas(C,o)&&!S)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f,u,d,h,g,p;if(o.worldPosition)l=!0;else{const{points:y}=c.handles,{viewport:m}=Ce(s),{worldToCanvas:w,canvasToWorld:x}=m;f=y.findIndex(S=>S===o);const C=y.map(w);p=C[f],h=Math.abs(C[2][0]-C[3][0]),g=Math.abs(C[0][1]-C[1][1]),u=[(C[2][0]+C[3][0])/2,(C[0][1]+C[1][1])/2],d=x(u)}const v=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:v,handleIndex:f,canvasWidth:h,canvasHeight:g,centerWorld:d,originalHandleCanvas:p,movingTextBox:l},this._activateModify(s),Ot(s),Pe(v),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(this.doneEditMemo(),a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a))},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{viewport:l}=c,{canvasToWorld:f}=l,{annotation:u,viewportIdsToRender:d,centerWorld:h,newAnnotation:g}=this.editData;this.createMemo(o,u,{newAnnotation:g});const p=l.worldToCanvas(h),{data:v}=u,y=Math.abs(s[0]-p[0]),m=Math.abs(s[1]-p[1]),w=[p[0],p[1]-m],x=[p[0],p[1]+m],C=[p[0]-y,p[1]],S=[p[0]+y,p[1]];v.handles.points=[f(w),f(x),f(C),f(S)],u.invalidated=!0,this.editData.hasMoved=!0,Pe(d),tn(u,o,Ht.HandlesUpdated)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,{viewport:a}=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a,{annotation:l,canvasWidth:f,canvasHeight:u,handleIndex:d,centerWorld:h,originalHandleCanvas:g}=this.editData,p=a.worldToCanvas(h),{data:v}=l,{points:y}=v.handles,{currentPoints:m}=i,w=m.canvas;if(d===0||d===1){const x=Math.abs(w[1]-p[1]),C=[p[0],p[1]-x],S=[p[0],p[1]+x];y[0]=s(C),y[1]=s(S);const _=w[0]-g[0],T=f/2+_,E=[p[0]-T,p[1]],D=[p[0]+T,p[1]];y[2]=s(E),y[3]=s(D)}else{const x=Math.abs(w[0]-p[0]),C=[p[0]-x,p[1]],S=[p[0]+x,p[1]];y[2]=s(C),y[3]=s(S);const _=w[1]-g[1],T=u/2+_,E=[p[0],p[1]-T],D=[p[0],p[1]+T];y[0]=s(E),y[1]=s(D)}},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(Y)),_=Yv(S),{centerPointRadius:T}=this.configuration;if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null},this._calculateCachedStats(h,a,f);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,f,n),a instanceof ur)){const{referencedImageId:Y}=h.metadata;for(const re in p.cachedStats)re.startsWith("imageId")&&f.getStackViewports().find(pe=>{const Ee=Vr(Y),Oe=pe.hasImageURI(Ee),_e=Vr(pe.getCurrentImageId());return Oe&&_e!==Ee})&&delete p.cachedStats[re]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let E;if(!Gr(g))continue;!Zr(g)&&!this.editData&&m!==null&&(E=[S[m]]),E&&ir(i,g,"0",E,{color:w});const D=`${g}-ellipse`,b="0";if(w4(i,g,b,S,{color:w,lineDash:C,lineWidth:x},D),T>0&&Math.min(Math.abs(_[0][0]-_[1][0])/2,Math.abs(_[0][1]-_[1][1])/2)>3*T){const re=this._getCanvasEllipseCenter(S);No(i,g,`${b}-center`,re,T,{color:w,lineDash:C,lineWidth:x})}o=!0;const I=this.getLinkedTextBoxStyle(u,h);if(!I.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const P=this.configuration.getTextLines(p,l);if(!P||P.length===0)continue;let M;p.handles.textBox.hasMoved||(M=na(_),p.handles.textBox.worldPosition=a.canvasToWorld(M));const L=a.worldToCanvas(p.handles.textBox.worldPosition),G=qi(i,g,"1",P,L,S,{},I),{x:A,y:k,width:F,height:j}=G;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([A,k]),topRight:a.canvasToWorld([A+F,k]),bottomLeft:a.canvasToWorld([A,k+j]),bottomRight:a.canvasToWorld([A+F,k+j])}}return o},this._calculateCachedStats=(n,i,o)=>{var C,S,_,T;if(!this.configuration.calculateStats)return;const a=n.data,{element:s}=i,{points:c}=a.handles,l=c.map(E=>i.worldToCanvas(E)),{viewPlaneNormal:f,viewUp:u}=i.getCamera(),[d,h]=Yv(l),g=i.canvasToWorld(d),p=i.canvasToWorld(h),{cachedStats:v}=a,y=Object.keys(v),m=g,w=p;for(let E=0;ET5(pe,De,{fast:!0}),returnPoints:this.configuration.storePointData});const xe=this.configuration.statsCalculator.getStatistics();v[D]={Modality:M.Modality,area:W,mean:(C=xe.mean)==null?void 0:C.value,max:(S=xe.max)==null?void 0:S.value,min:(_=xe.min)==null?void 0:_.value,stdDev:(T=xe.stdDev)==null?void 0:T.value,statsArray:xe.array,pointsInShape:ee,isEmptyArea:_e,areaUnit:z,modalityUnit:Z}}const x=n.invalidated;return n.invalidated=!1,x&&tn(n,s,Ht.StatsUpdated),v},this._isInsideVolume=(n,i,o)=>sr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}_pointInEllipseCanvas(e,r){const{xRadius:n,yRadius:i,center:o,angle:a}=e,s=HK(qt(),r,o,-a);if(n<=0||i<=0)return!1;const c=[s[0]-o[0],s[1]-o[1]];return c[0]*c[0]/(n*n)+c[1]*c[1]/(i*i)<=1}_getCanvasEllipseCenter(e){const[r,n,i,o]=e,a=[i[0],n[1]],s=[o[0],r[1]];return[(a[0]+s[0])/2,(a[1]+s[1])/2]}};r0.toolName="EllipticalROI",r0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=r0.hydrateBase(r0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let od=r0;function w5e(t,e){const r=t.cachedStats[e],{area:n,mean:i,stdDev:o,max:a,isEmptyArea:s,areaUnit:c,modalityUnit:l,min:f}=r,u=[];if(Ar(n)){const d=s?"Area: Oblique not supported":`Area: ${an(n)} ${c}`;u.push(d)}return Ar(i)&&u.push(`Mean: ${an(i)} ${l}`),Ar(a)&&u.push(`Max: ${an(a)} ${l}`),Ar(f)&&u.push(`Min: ${an(f)} ${l}`),Ar(o)&&u.push(`Std Dev: ${an(o)} ${l}`),u}const{transformWorldToIndex:ab}=Mn,i0=class i0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,storePointData:!1,centerPointRadius:0,calculateStats:!0,getTextLines:x5e,statsCalculator:rc}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s]],activeHandleIndex:null},cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=f.map(g=>c.worldToCanvas(g)),d=du(u),h=du([u[0],o]);return Math.abs(h-d){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:g}=c.handles;f=g.findIndex(p=>p===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Ot(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;this.doneEditMemo(),a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{viewport:l}=c,{canvasToWorld:f}=l,{annotation:u,viewportIdsToRender:d,newAnnotation:h}=this.editData;this.createMemo(o,u,{newAnnotation:h});const{data:g}=u;g.handles.points=[g.handles.points[0],f(s)],u.invalidated=!0,this.editData.hasMoved=!0,Pe(d),tn(u,o,Ht.HandlesUpdated)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else this._dragHandle(n),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a.viewport,{annotation:l,handleIndex:f}=this.editData,{data:u}=l,{points:d}=u.handles,h=d.map(v=>c(v)),{currentPoints:g}=i,p=g.canvas;if(f===0){const v=p[0]-h[0][0],y=p[1]-h[0][1],m=p,w=[h[1][0]+v,h[1][1]+y];d[0]=s(m),d[1]=s(w)}else d[1]=s(p)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(ue)),_=S[0],T=du(S),E=x0(S),{centerPointRadius:D}=this.configuration;if(!p.cachedStats[l]||p.cachedStats[l].areaUnit==null)p.cachedStats[l]={Modality:null,area:null,max:null,mean:null,stdDev:null,areaUnit:null,radius:null,radiusUnit:null,perimeter:null},this._calculateCachedStats(h,a,f,n);else if(h.invalidated&&(this._throttledCalculateCachedStats(h,a,f,n),a instanceof ur)){const{referencedImageId:ue}=h.metadata;for(const ce in p.cachedStats)ce.startsWith("imageId")&&f.getStackViewports().find(Oe=>{const _e=Vr(ue),B=Oe.hasImageURI(_e),O=Vr(Oe.getCurrentImageId());return B&&O!==_e})&&delete p.cachedStats[ce]}if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let b;if(!Gr(g))continue;!Zr(g)&&!this.editData&&m!==null&&(b=[S[m]]),b&&ir(i,g,"0",b,{color:w});const I=`${g}-circle`,P="0";No(i,g,P,_,T,{color:w,lineDash:C,lineWidth:x},I),D>0&&T>3*D&&No(i,g,`${P}-center`,_,D,{color:w,lineDash:C,lineWidth:x}),o=!0;const M=this.getLinkedTextBoxStyle(u,h);if(!M.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const L=this.configuration.getTextLines(p,l);if(!L||L.length===0)continue;let V;p.handles.textBox.hasMoved||(V=na(E),p.handles.textBox.worldPosition=a.canvasToWorld(V));const G=a.worldToCanvas(p.handles.textBox.worldPosition),k=qi(i,g,"1",L,G,S,{},M),{x:F,y:j,width:Y,height:re}=k;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([F,j]),topRight:a.canvasToWorld([F+Y,j]),bottomLeft:a.canvasToWorld([F,j+re]),bottomRight:a.canvasToWorld([F+Y,j+re])}}return o},this._calculateCachedStats=(n,i,o,a)=>{var S,_,T,E;if(!this.configuration.calculateStats)return;const s=n.data,{element:c}=i,l=n.invalidated,{points:f}=s.handles,u=f.map(D=>i.worldToCanvas(D)),{viewPlaneNormal:d,viewUp:h}=i.getCamera(),[g,p]=x0(u),v=i.canvasToWorld(g),y=i.canvasToWorld(p),{cachedStats:m}=s,w=Object.keys(m),x=v,C=y;for(let D=0;DT5(B,se,{fast:!0}),boundsIJK:ce,imageData:M,returnPoints:this.configuration.storePointData}));const ye=this.configuration.statsCalculator.getStatistics();m[b]={Modality:L.Modality,area:Ne,mean:(S=ye.mean)==null?void 0:S.value,max:(_=ye.max)==null?void 0:_.value,min:(T=ye.min)==null?void 0:T.value,pointsInShape:ae,stdDev:(E=ye.stdDev)==null?void 0:E.value,statsArray:ye.array,isEmptyArea:W,areaUnit:xe,radius:O/2/Z,radiusUnit:ee,perimeter:2*Math.PI*(O/2)/Z,modalityUnit:ie}}else this.isHandleOutsideImage=!0,m[b]={Modality:L.Modality}}return n.invalidated=!1,l&&tn(n,c,Ht.StatsUpdated),m},this._isInsideVolume=(n,i,o)=>sr(n,o)&&sr(i,o),this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}};i0.toolName="CircleROI",i0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=i0.hydrateBase(i0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let gy=i0;function x5e(t,e){const r=t.cachedStats[e],{radius:n,radiusUnit:i,area:o,mean:a,stdDev:s,max:c,min:l,isEmptyArea:f,areaUnit:u,modalityUnit:d}=r,h=[];if(Ar(n)){const g=f?"Radius: Oblique not supported":`Radius: ${an(n)} ${i}`;h.push(g)}if(Ar(o)){const g=f?"Area: Oblique not supported":`Area: ${an(o)} ${u}`;h.push(g)}return Ar(a)&&h.push(`Mean: ${an(a)} ${d}`),Ar(c)&&h.push(`Max: ${an(c)} ${d}`),Ar(l)&&h.push(`Min: ${an(l)} ${d}`),Ar(s)&&h.push(`Std Dev: ${an(s)} ${d}`),h}const $m=5,DE=class DE extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,degrees:[45,135,225,315],diameters:[10,30,60]}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{label:"",handles:{points:[[...s]]}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,newAnnotation:!0},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{points:f}=l.handles,u=c.worldToCanvas(f[0]),d=du([u,o]);return Math.abs(d){const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},Ot(a),this._activateModify(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const{renderingEngine:u}=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this._dragDrawCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h}=this.editData,{data:g}=d;g.handles.points=[u(s),u(s)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._dragModifyCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s}=this.editData,{data:c}=a,{deltaPoints:l}=i,f=l.world;c.handles.points.forEach(g=>{g[0]+=f[0],g[1]+=f[1],g[2]+=f[2]}),a.invalidated=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this._dragHandle=n=>{const i=n.detail,{element:o}=i,a=Ce(o),{canvasToWorld:s,worldToCanvas:c}=a.viewport,{annotation:l}=this.editData,{data:f}=l,{points:u}=f.handles,d=u.map(w=>c(w)),{currentPoints:h}=i,g=h.canvas,p=g[0]-d[0][0],v=g[1]-d[0][1],y=g,m=[d[1][0]+p,d[1][1]+v];u[0]=s(y),u[1]=s(m)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;i.highlighted=!1,s.handles.activeHandleIndex=null;const{renderingEngine:c}=Ce(n);return Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragModifyCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragModifyCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.addEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragDrawCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragDrawCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragDrawCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(b))[0];if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(d))continue;let C=`${d}-crosshair-vertical`,S=[x[0],x[1]+$m],_=[x[0],x[1]-$m];vn(i,d,C,S,_,{color:v,lineDash:m,lineWidth:y}),C=`${d}-crosshair-horizontal`,S=[x[0]+$m,x[1]],_=[x[0]-$m,x[1]],vn(i,d,C,S,_,{color:v,lineDash:m,lineWidth:y});const T=this.configuration.diameters.map(b=>this.worldMeasureToCanvas(b,a));for(let b=0;bb*Math.PI/180,D=this.configuration.degrees.map(b=>E(b));for(let b=0;b{const{instance:s}=i.data.spline;return s.isPointNearCurve(o,a)},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:d}=c.handles;f=d.findIndex(h=>h===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s),Pe(u),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,contourHoleProcessingEnabled:l}=this.editData,{data:f}=a;a.autoGenerated=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),d=this.getTargetImageData(this.getTargetId(u.viewport)),{imageData:h,dimensions:g}=d;this.isHandleOutsideImage=f.handles.points.map(v=>Ur(h,v)).some(v=>!sr(v,g)),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const p=c?Ht.Completed:Ht.HandlesUpdated;this.fireChangeOnUpdate?(this.fireChangeOnUpdate.annotationUID=a.annotationUID,this.fireChangeOnUpdate.changeType=p):this.fireChangeOnUpdate={annotationUID:a.annotationUID,changeType:p,contourHoleProcessingEnabled:l},Pe(s),this.doneEditMemo(),this.editData=null,this.isDrawing=!1},this._keyDownCallback=n=>{const i=n.detail,{element:o}=i,a=i.key??"",{lastControlPointDeletionKeys:s}=this.configuration.spline;if(!s.includes(a))return;const{annotation:l}=this.editData,{data:f}=l;if(f.handles.points.length===sb){this.cancel(o);return}else{const u=f.handles.points.length-1;this._deleteControlPointByIndex(o,l,u)}n.preventDefault()},this._mouseMoveCallback=n=>{const{drawPreviewEnabled:i}=this.configuration.spline;if(!i)return;const{element:o}=n.detail,{renderingEngine:a}=Ce(o),s=_t(o,this.getToolName());this.editData.lastCanvasPoint=n.detail.currentPoints.canvas,Pe(s),n.preventDefault()},this._mouseDownCallback=n=>{const i=n.type===N.MOUSE_DOUBLE_CLICK,{annotation:o,viewportIdsToRender:a}=this.editData,{data:s}=o;if(s.contour.closed)return;this.doneEditMemo();const c=n.detail,{currentPoints:l,element:f}=c,{canvas:u,world:d}=l;let h=s.handles.points.length>=2&&i,g=!0;if(s.handles.points.length&&this.createMemo(f,o,{newAnnotation:s.handles.points.length===1}),s.handles.points.length>=3){this.createMemo(f,o);const{instance:p}=s.spline,v=p.getClosestControlPointWithinDistance(u,cb);(v==null?void 0:v.index)===0&&(g=!1,h=!0)}g&&s.handles.points.push(d),s.contour.closed=s.contour.closed||h,o.invalidated=!0,Pe(a),s.contour.closed&&this._endCallback(n),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;this.moveAnnotation(a,p)}else{const{currentPoints:g}=i,p=g.world;u.handles.points[c]=[...p],a.invalidated=!0}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this.triggerAnnotationCompleted=(n,i)=>{const o=N.ANNOTATION_COMPLETED,a={annotation:n,changeType:Ht.Completed,contourHoleProcessingEnabled:i};at(Ke,o,a)},this.triggerAnnotationModified=(n,i,o=Ht.StatsUpdated)=>{const{viewportId:a,renderingEngineId:s}=i,c=N.ANNOTATION_MODIFIED;at(Ke,c,{annotation:n,viewportId:a,renderingEngineId:s,changeType:o})},this.triggerChangeEvent=(n,i,o=Ht.StatsUpdated,a)=>{o===Ht.Completed?this.triggerAnnotationCompleted(n,a):this.triggerAnnotationModified(n,i,o)},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.KEY_DOWN,this._keyDownCallback),n.addEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.KEY_DOWN,this._keyDownCallback),n.removeEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._renderStats=(n,i,o,a)=>{const s=n.data,c=this.getTargetId(i);if(!s.spline.instance.closed||!a.visibility)return;const l=this.configuration.getTextLines(s,c);if(!l||l.length===0)return;const f=s.handles.points.map(m=>i.worldToCanvas(m));if(!s.handles.textBox.hasMoved){const m=na(f);s.handles.textBox.worldPosition=i.canvasToWorld(m)}const u=i.worldToCanvas(s.handles.textBox.worldPosition),h=qi(o,n.annotationUID??"","textBox",l,u,f,{},a),{x:g,y:p,width:v,height:y}=h;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([g,p]),topRight:i.canvasToWorld([g+v,p]),bottomLeft:i.canvasToWorld([g,p+y]),bottomRight:i.canvasToWorld([g+v,p+y])}},this.addControlPointCallback=(n,i)=>{const{data:o}=i,a=o.spline.type,s=this._getSplineConfig(a),c=s.controlPointAdditionDistance;if(s.controlPointAdditionEnabled===!1)return;const l=n.detail,{element:f}=l,u=Ce(f),{renderingEngine:d,viewport:h}=u,{canvasToWorld:g}=h,{instance:p}=o.spline,v=n.detail.currentPoints.canvas,y=p.getClosestPoint(v);if(y.distance>c)return;const{index:m,point:w}=p.addControlPointAtU(y.uValue);o.handles.points.splice(m,0,g(w)),i.invalidated=!0;const x=_t(f,this.getToolName());Pe(x)},this.deleteControlPointCallback=(n,i)=>{const o=i.data.spline.type,a=this._getSplineConfig(o),s=a.controlPointDeletionDistance;if(a.controlPointDeletionEnabled===!1)return;const c=n.detail,{element:l,currentPoints:f}=c,{canvas:u}=f,{instance:d}=i.data.spline,h=d.getClosestControlPointWithinDistance(u,s);h&&this._deleteControlPointByIndex(l,i,h.index)},this._calculateCachedStats=(n,i)=>{if(!this.configuration.calculateStats)return;const o=n.data;if(!o.contour.closed)return;const a=Ce(i);if(!a)return;const{viewport:s}=a,{cachedStats:c}=o,{polyline:l}=o.contour,f=Object.keys(c);for(let d=0;ds.worldToCanvas(b)),y=v[0],m=s.canvasToWorld(y),w=s.canvasToWorld([y[0]+1,y[1]]),x=s.canvasToWorld([y[0],y[1]+1]),C=ki(m,w),S=ki(m,x),{imageData:_}=g,{scale:T,areaUnit:E}=ta(g,()=>{const{maxX:b,maxY:I,minX:P,minY:M}=Tu(v),L=s.canvasToWorld([P,M]),V=Ur(_,L),G=s.canvasToWorld([b,I]),A=Ur(_,G);return[V,A]});let D=M1(v)/T/T;D*=C*S,c[h]={Modality:p.Modality,area:D,areaUnit:E}}const u=n.invalidated;return n.invalidated=!1,u&&this.triggerAnnotationModified(n,a,Ht.StatsUpdated),c},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0}),this.annotationCompletedBinded=this.annotationCompleted.bind(this)}annotationCompleted(e){var n;const{sourceAnnotation:r}=e.detail;!this.splineToolNames.includes((n=r==null?void 0:r.metadata)==null?void 0:n.toolName)||!this.configuration.simplifiedSpline||!this.isContourSegmentationTool()||l4(r)}initializeListeners(){Ke.addEventListener(N.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}removeListeners(){Ke.removeEventListener(N.ANNOTATION_COMPLETED,this.annotationCompletedBinded)}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.removeListeners()}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{canvas:o}=n,a=vh(e.detail.event)===this.configuration.contourHoleAdditionModifierKey,s=Ce(i),{renderingEngine:c}=s,l=this.createAnnotation(e);this.isDrawing=!0,this.addAnnotation(l,i);const f=_t(i,this.getToolName());return this.editData={annotation:l,viewportIdsToRender:f,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,lastCanvasPoint:o,contourHoleProcessingEnabled:a},this._activateDraw(i),e.preventDefault(),Pe(f),l}cancel(e){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),zt(e);const{annotation:r,viewportIdsToRender:n,newAnnotation:i}=this.editData;i&&gn(r.annotationUID),super.cancelAnnotation(r);const o=Ce(e),{renderingEngine:a}=o;return Pe(n),this.editData=null,r.annotationUID}isContourSegmentationTool(){return!1}renderAnnotationInstance(e){var M,L,V;const{enabledElement:r,targetId:n,svgDrawingHelper:i,annotationStyle:o}=e,{viewport:a}=r,{worldToCanvas:s}=a,{element:c}=a,l=e.annotation,{annotationUID:f,data:u,highlighted:d}=l,{handles:h}=u,{points:g,activeHandleIndex:p}=h,v=(M=this.editData)==null?void 0:M.newAnnotation,{lineWidth:y,lineDash:m,color:w,locked:x}=o,C=g.map(G=>s(G)),{drawPreviewEnabled:S}=this.configuration.spline,_=l.data.spline.type,T=this._getSplineConfig(_),E=l.data.spline.instance,D=T1(l);if(D.findIndex(G=>!G)!==-1)throw new Error(`Can't find annotation for child ${l.childAnnotationUIDs.join()}`);[l,...D].filter(G=>this._isSplineROIAnnotation(G)).forEach(G=>{const k=this._updateSplineInstance(c,G).getPolylinePoints();this.updateContourPolyline(G,{points:k,closed:u.contour.closed,targetWindingDirection:Lo.Clockwise},a,{updateWindingDirection:u.contour.closed})}),super.renderAnnotationInstance(e),!u.cachedStats[n]||u.cachedStats[n].areaUnit==null?(u.cachedStats[n]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(l,c)):l.invalidated&&this._throttledCalculateCachedStats(l,c);let P;if(!x&&!this.editData&&p!==null&&(P=[C[p]]),(P||v||d)&&ir(i,f,"0",C,{color:w,lineWidth:y,handleRadius:"3"}),S&&E.numControlPoints>1&&((L=this.editData)!=null&&L.lastCanvasPoint)&&!E.closed){const{lastCanvasPoint:G}=this.editData,A=E.getPreviewPolylinePoints(G,cb);Cs(i,f,"previewSplineChange",A,{color:"#9EA0CA",lineDash:m,lineWidth:1})}if(T.showControlPointsConnectors){const G=[...C];E.closed&&G.push(C[0]),Cs(i,f,"controlPointsConnectors",G,{color:"rgba(255, 255, 255, 0.5)",lineWidth:1})}return this._renderStats(l,a,i,o.textbox),((V=this.fireChangeOnUpdate)==null?void 0:V.annotationUID)===f&&(this.triggerChangeEvent(l,r,this.fireChangeOnUpdate.changeType,this.fireChangeOnUpdate.contourHoleProcessingEnabled),this.fireChangeOnUpdate=null),l.invalidated=!1,!0}createInterpolatedSplineControl(e){var o;if((o=e.data.handles.points)!=null&&o.length)return;const{polyline:r}=e.data.contour;if(!r||!r.length)return;e.data.handles.points=[];const{points:n}=e.data.handles,i=Math.max(10,Math.floor(r.length/20));for(let a=0;a({type:o.type,instance:a,resolution:o.resolution});let c;return(l=this.configuration.interpolation)!=null&&l.enabled&&(c=f=>{var u;(u=f.data).spline||(u.spline=s()),this.createInterpolatedSplineControl(f)}),Ei(r,{data:{handles:{points:[[...n]]},spline:s(),cachedStats:{}},onInterpolationComplete:c})}_deleteControlPointByIndex(e,r,n){const i=Ce(e),{points:o}=r.data.handles;o.length===3?gn(r.annotationUID):o.splice(n,1);const{renderingEngine:a}=i,s=_t(e,this.getToolName());r.invalidated=!0,Pe(s)}_isSplineROIAnnotation(e){var r;return!!((r=e.data)!=null&&r.spline)}_getSplineConfig(e){const{configuration:r}=this,n=r.spline.configuration;return Object.assign({type:e},C5e,n[e])}_updateSplineInstance(e,r){const n=Ce(e),{viewport:i}=n,{worldToCanvas:o}=i,{data:a}=r,{type:s,instance:c}=r.data.spline,l=this._getSplineConfig(s),u=a.handles.points.map(o),d=l.resolution!==void 0?parseInt(l.resolution):void 0,h=l.scale!==void 0?parseFloat(l.scale):void 0;return c.setControlPoints(u),c.closed=!!a.contour.closed,!c.fixedResolution&&d!==void 0&&c.resolution!==d&&(c.resolution=d,r.invalidated=!0),c instanceof Jp&&!c.fixedScale&&h!==void 0&&c.scale!==h&&(c.scale=h,r.invalidated=!0),c}};Wl.toolName="SplineROI",Wl.SplineTypes=Dc,Wl.Actions=Kg,Wl.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;if(r.lengthi,this._areEqual=typeof n=="function"?n:(i,o)=>i===o}push(e){const r=this._getBucketIndex(e),n=this._buckets[r],i={value:e,next:n};this._buckets[r]=i,this._size++}pop(){if(this._size===0)throw new Error("Cannot pop because the queue is empty.");for(;this._buckets[this._currentBucketIndex]===null;)this._currentBucketIndex=(this._currentBucketIndex+1)%this._bucketCount;const e=this._buckets[this._currentBucketIndex];return this._buckets[this._currentBucketIndex]=e.next,this._size--,e.value}remove(e){if(!e)return!1;const r=this._getBucketIndex(e),n=this._buckets[r];let i=n,o;for(;i!==null&&!this._areEqual(e,i.value);)o=i,i=i.next;return i===null?!1:(i===n?this._buckets[r]=i.next:o.next=i.next,this._size--,!0)}isEmpty(){return this._size===0}_getBucketIndex(e){return this._getPriority(e)&this._mask}_buildArray(e){const r=new Array(e);return r.fill(null),r}}const w3=4294967295,T5e=2/(3*Math.PI);class my{constructor(e,r,n){this._getPointIndex=(o,a)=>{const{width:s}=this;return o*s+a},this._getPointCoordinate=o=>{const a=o%this.width,s=Math.floor(o/this.width);return[a,s]},this._getPointCost=o=>Math.round(this.searchGranularity*this.costs[o]);const i=e.length;this.searchGranularityBits=8,this.searchGranularity=1<.33?0:1;i[n(o,e-2)]=1,i[n(o,e-1)]=1}return i.fill(1,n(r-2,0)),i}_computeGradientX(){const{width:e,height:r}=this,n=new Float32Array(e*r);let i=0;for(let o=0;o=i||l<0||l>=o)return 1;if(a<0||s<0||a>=i||s>=o)return 0;const f=n(l,c);let u=this.gradMagnitude[f];(a===c||s===l)&&(u*=Math.SQRT1_2);const d=this.laplace[f],h=this._getGradientDirection(a,s,c,l);return .43*u+.43*d+.11*h}_getNeighborPoints(e){const{width:r,height:n}=this,i=[],o=Math.max(e[0]-1,0),a=Math.max(e[1]-1,0),s=Math.min(e[0]+1,r-1),c=Math.min(e[1]+1,n-1);for(let l=a;l<=c;l++)for(let f=o;f<=s;f++)(f!==e[0]||l!==e[1])&&i.push([f,l]);return i}static createInstanceFromRawPixelData(e,r,n,i){const o=e.length,a=new Float32Array(o),{lower:s,upper:c}=i,l=c-s;for(let f=0,u=e.length;fthis.pointArray[e])}getNumControlPoints(){return this._controlPointIndexes.length}removeLastControlPoint(){this._controlPointIndexes.length&&this._controlPointIndexes.pop()}getLastControlPoint(){if(this._controlPointIndexes.length)return this.pointArray[this._controlPointIndexes[this._controlPointIndexes.length-1]]}removeLastPoints(e){this.pointArray.splice(this.pointArray.length-e,e)}addPoints(e){this.pointArray=this.pointArray.concat(e)}prependPath(e){const r=e.pointArray.length,n=[];this.pointArray=e.pointArray.concat(this.pointArray);for(let i=0;ithis._controlPointIndexes.push(r))}}const E5e=10**2,IE=class IE extends $p{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextLines:D5e,calculateStats:!0,preventHandleOutsideImage:!1,contourHoleAdditionModifierKey:Oi.Shift,snapHandleNearby:2,interpolation:{enabled:!1,nearestEdge:2,showInterpolationPolyline:!1},decimate:{enabled:!1,epsilon:.1},actions:{cancelInProgress:{method:"cancelInProgress",bindings:[{key:"Escape"}]}}}}){super(e,r),this.isHandleOutsideImage=!1,this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,l=a*a,f=i.data.contour.polyline.map(d=>c.worldToCanvas(d));let u=f[f.length-1];for(let d=0;d{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1};const c=Ce(a),{renderingEngine:l}=c;this._activateModify(a),Pe(s),n.preventDefault()},this.handleSelectedCallback=(n,i,o)=>{const a=n.detail,{element:s}=a,{data:c}=i;i.highlighted=!0;let l=!1,f;if(o.worldPosition)l=!0;else{const{points:g}=c.handles;f=g.findIndex(p=>p===o)}const u=_t(s,this.getToolName());this.editData={annotation:i,viewportIdsToRender:u,handleIndex:f,movingTextBox:l},this._activateModify(s);const d=Ce(s),{renderingEngine:h}=d;Pe(u),n.preventDefault()},this._endCallback=(n,i=!1)=>{const o=n.detail,{element:a}=o,{annotation:s,viewportIdsToRender:c,newAnnotation:l,contourHoleProcessingEnabled:f}=this.editData,{data:u}=s;this.doneEditMemo(),u.handles.activeHandleIndex=null,this._deactivateModify(a),this._deactivateDraw(a),zt(a);const d=Ce(a);if(this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage||i){gn(s.annotationUID),this.clearEditData(),Pe(c);return}Pe(c);const h=l?Ht.Completed:Ht.HandlesUpdated;this.triggerChangeEvent(s,d,h,f),this.clearEditData()},this.triggerChangeEvent=(n,i,o=Ht.StatsUpdated,a=!1)=>{o===Ht.Completed?v5(n,a):tn(n,i.viewport.element,o)},this._mouseDownCallback=n=>{const i=n.type===N.MOUSE_DOUBLE_CLICK,{annotation:o,viewportIdsToRender:a,worldToSlice:s,sliceToWorld:c,newAnnotation:l}=this.editData;if(this.editData.closed)return;const f=n.detail,{element:u}=f,{currentPoints:d}=f,{canvas:h,world:g}=d;let p=g;const v=Ce(u),{viewport:y,renderingEngine:m}=v,w=this.editData.currentPath.getControlPoints();let x=w.length>=2&&i;if(this.doneEditMemo(),this.createMemo(u,o,{newAnnotation:l&&w.length===1}),w.length>=2){const _={index:-1,distSquared:1/0};for(let T=0,E=w.length;T{const{element:i,currentPoints:o}=n.detail,{world:a,canvas:s}=o,{renderingEngine:c}=Ce(i),l=_t(i,this.getToolName());this.editData.lastCanvasPoint=s;const{width:f,height:u}=this.scissors,{worldToSlice:d}=this.editData,h=d(a);if(h[0]<0||h[1]<0||h[0]>=f||h[1]>=u)return;const g=this.scissors.findPathToPoint(h),p=new _c;p.addPoints(g),p.prependPath(this.editData.confirmedPath),this.editData.currentPath=p,Pe(l),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,movingTextBox:c,handleIndex:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(c){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(l===void 0)console.warn("Drag annotation not implemented");else{const{currentPoints:g}=i,p=g.world;this.editHandle(p,o,a,l)}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s)},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData;return a&&gn(i.annotationUID),Pe(o),this.doneEditMemo(),this.scissors=null,i.annotationUID},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_MOVE,this._mouseMoveCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.MOUSE_DOUBLE_CLICK,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._mouseDownCallback)},this._calculateCachedStats=(n,i)=>{if(!this.configuration.calculateStats)return;const o=n.data;if(!o.contour.closed)return;const a=Ce(i),{viewport:s,renderingEngine:c}=a,{cachedStats:l}=o,{polyline:f}=o.contour,u=Object.keys(l);for(let h=0;hs.worldToCanvas(I)),m=y[0],w=s.canvasToWorld(m),x=s.canvasToWorld([m[0]+1,m[1]]),C=s.canvasToWorld([m[0],m[1]+1]),S=ki(w,x),_=ki(w,C),{imageData:T}=p,{scale:E,areaUnit:D}=ta(p,()=>{const{maxX:I,maxY:P,minX:M,minY:L}=Tu(y),V=s.canvasToWorld([M,L]),G=Ur(T,V),A=s.canvasToWorld([I,P]),k=Ur(T,A);return[G,k]});let b=M1(y)/E/E;b*=S*_,l[g]={Modality:v.Modality,area:b,areaUnit:D}}const d=n.invalidated;return n.invalidated=!1,d&&this.triggerAnnotationModified(n,a,Ht.StatsUpdated),l},this._renderStats=(n,i,o,a)=>{const s=n.data,c=this.getTargetId(i);if(!s.contour.closed||!a.visibility)return;const l=this.configuration.getTextLines(s,c);if(!l||l.length===0)return;const f=s.handles.points.map(m=>i.worldToCanvas(m));if(!s.handles.textBox.hasMoved){const m=na(f);s.handles.textBox.worldPosition=i.canvasToWorld(m)}const u=i.worldToCanvas(s.handles.textBox.worldPosition),h=qi(o,n.annotationUID??"","textBox",l,u,f,{},a),{x:g,y:p,width:v,height:y}=h;s.handles.textBox.worldBoundingBox={topLeft:i.canvasToWorld([g,p]),topRight:i.canvasToWorld([g+v,p]),bottomLeft:i.canvasToWorld([g,p+y]),bottomRight:i.canvasToWorld([g+v,p+y])}},this.triggerAnnotationModified=(n,i,o=Ht.StatsUpdated)=>{const{viewportId:a,renderingEngineId:s}=i,c=N.ANNOTATION_MODIFIED;at(Ke,c,{annotation:n,viewportId:a,renderingEngineId:s,changeType:o})},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}setupBaseEditData(e,r,n,i,o){var _,T;const a=Ce(r),{viewport:s}=a;this.isDrawing=!0;const c=s.getImageData(),{imageData:l}=c;let f,u,d,h,g;if(!(s instanceof ur))d=c.dimensions[0],h=c.dimensions[1],f=E=>{const D=Ur(l,E);return[D[0],D[1]]},u=E=>B0(l,[E[0],E[1],0]),g=c.scalarData;else if(s instanceof ur){const E=UT(s),{sliceToIndexMatrix:D,indexToSliceMatrix:b}=E;f=I=>{const P=Ur(l,I),M=Jt([0,0,0],P,b);return[M[0],M[1]]},u=I=>{const P=Jt([0,0,0],[I[0],I[1],0],D);return B0(l,P)},g=E.scalarData,d=E.width,h=E.height}else throw new Error("Viewport not supported");g=qA(g,d,h);const{voiRange:p}=s.getProperties(),v=f(e);this.scissors=my.createInstanceFromRawPixelData(g,d,h,p),i&&(this.scissorsNext=my.createInstanceFromRawPixelData(g,d,h,p),this.scissorsNext.startSearch(f(i))),this.scissors.startSearch(v);const y=!i,m=new _c,w=new _c,x=y?void 0:new _c;m.addPoint(v),m.addControlPoint(v);const C=_t(r,this.getToolName()),S=s.worldToCanvas(e);this.editData={annotation:n,viewportIdsToRender:C,newAnnotation:y,hasMoved:!1,lastCanvasPoint:S,confirmedPath:m,currentPath:w,confirmedPathNext:x,closed:!1,handleIndex:((_=this.editData)==null?void 0:_.handleIndex)??((T=n.handles)==null?void 0:T.activeHandleIndex),worldToSlice:f,sliceToWorld:u,contourHoleProcessingEnabled:o}}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n,a=this.createAnnotation(e),s=vh(e.detail.event)===this.configuration.contourHoleAdditionModifierKey;return this.setupBaseEditData(o,i,a,void 0,s),this.addAnnotation(a,i),this._activateDraw(i),e.preventDefault(),Pe(this.editData.viewportIdsToRender),a}clearEditData(){this.editData=null,this.scissors=null,this.scissorsNext=null,this.isDrawing=!1}editHandle(e,r,n,i){var w;const{data:o}=n,{points:a}=o.handles,{length:s}=a,c=a[(i-1+s)%s],l=a[(i+1)%s];if(!((w=this.editData)!=null&&w.confirmedPathNext)){this.setupBaseEditData(c,r,n,l);const{polyline:x}=o.contour,C=new _c,S=new _c,{worldToSlice:_}=this.editData,T=IC(n,i-1),E=IC(n,i+1);if(E===-1||T===-1)throw new Error(`Can't find handle index ${E===-1&&l} ${T===-1&&c}`);i===0?S.addPoints(x.slice(E+1,T).map(_)):(C.addPoints(x.slice(0,T+1).map(_)),S.addPoints(x.slice(E,x.length).map(_))),this.editData.confirmedPath=C,this.editData.confirmedPathNext=S}const{editData:f,scissors:u}=this,{worldToSlice:d,sliceToWorld:h}=f,{activeHandleIndex:g}=o.handles;if(g==null)o.handles.activeHandleIndex=i;else if(g!==i)throw new Error(`Trying to edit a different handle than the one currently being edited ${i}!==${o.handles.activeHandleIndex}`);const p=d(e);if(p[0]<0||p[0]>=u.width||p[1]<0||p[1]>=u.height)return;a[i]=h(p);const v=u.findPathToPoint(p),y=this.scissorsNext.findPathToPoint(p),m=new _c;m.prependPath(f.confirmedPath),i!==0&&m.addPoints(v),m.addPoints(y.reverse()),m.appendPath(f.confirmedPathNext),i===0&&m.addPoints(v),f.currentPath=m,n.invalidated=!0,f.hasMoved=!0,f.closed=!0}renderAnnotation(e,r){var n;return this.updateAnnotation((n=this.editData)==null?void 0:n.currentPath),super.renderAnnotation(e,r)}isContourSegmentationTool(){return!1}createAnnotation(e){const r=super.createAnnotation(e),{world:n}=e.detail.currentPoints;return Ei(r,{data:{handles:{points:[[...n]]}}})}cancelInProgress(e,r,n){if(!this.editData){this.undo();return}this._endCallback(n,!0)}renderAnnotationInstance(e){var m,w,x,C;const{annotation:r,enabledElement:n,svgDrawingHelper:i,annotationStyle:o,targetId:a}=e,{viewport:s}=n,{element:c}=s,{worldToCanvas:l}=s,{annotationUID:f,data:u,highlighted:d}=r,{handles:h}=u,g=(m=this.editData)==null?void 0:m.newAnnotation,{lineWidth:p,lineDash:v,color:y}=o;if(d||g&&r.annotationUID===((x=(w=this.editData)==null?void 0:w.annotation)==null?void 0:x.annotationUID)){const S="0",_=h.points.map(l);ir(i,f,S,_,{color:y,lineDash:v,lineWidth:p})}return super.renderAnnotationInstance(e),!u.cachedStats[a]||((C=u.cachedStats[a])==null?void 0:C.areaUnit)===null?(u.cachedStats[a]={Modality:null,area:null,areaUnit:null},this._calculateCachedStats(r,c)):r.invalidated&&this._throttledCalculateCachedStats(r,c),this._renderStats(r,s,i,o.textbox),!0}updateAnnotation(e){if(!this.editData||!e)return;const{annotation:r,sliceToWorld:n,worldToSlice:i,closed:o,newAnnotation:a}=this.editData;let{pointArray:s}=e;s.length>1&&(s=[...s,s[0]]);const c=a&&o?Lo.Clockwise:void 0;this.updateContourPolyline(r,{points:s,closed:o,targetWindingDirection:c},{canvasToWorld:n,worldToCanvas:i})}};IE.toolName="LivewireContour";let vy=IE;function D5e(t,e){const r=t.cachedStats[e],{area:n,areaUnit:i}=r,o=[];if(n){const a=`Area: ${an(n)} ${i}`;o.push(a)}return o}const OE=class OE extends vy{updateInterpolatedAnnotation(e,r){this.editData||!e.invalidated||!e.data.handles.interpolationSources||(e.data.contour.originalPolyline=e.data.contour.polyline,queueMicrotask(()=>{if(!e.data.handles.interpolationSources)return;const{points:n}=e.data.handles,{element:i}=r.viewport;this.setupBaseEditData(n[0],i,e);const{length:o}=n,{scissors:a}=this,{nearestEdge:s,repeatInterpolation:c}=this.configuration.interpolation;e.data.handles.originalPoints=n;const{worldToSlice:l,sliceToWorld:f}=this.editData,u=[];if(s){let h=l(n[n.length-1]);n.forEach((g,p)=>{const v=l(g);h=v,u.push(v),a.startSearch(h),a.findPathToPoint(v),a.findPathToPoint(l(n[(p+3)%n.length]));const y=a.findMinNearby(v,s);$t(v,y)||(u[p]=y,h=y,n[p]=f(y))})}const d=new _c;for(let h=0;h{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),{arrowFirst:p}=this.configuration,v=l.getFrameOfReferenceUID(),y={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:v,referencedImageId:g,...l.getViewReference({points:[s]})},data:{text:"",handles:{points:[[...s],[...s]],activeHandleIndex:null,arrowFirst:p,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:""}};nn(y,a);const m=_t(a,this.getToolName());return this.editData={annotation:y,viewportIdsToRender:m,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(m),y},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l,movingTextBox:f}=this.editData,{data:u}=a;c&&!l||(u.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),c?this.configuration.getTextCallback(d=>{if(!d){gn(a.annotationUID),Pe(s),this.editData=null,this.isDrawing=!1;return}a.data.text=d,tn(a,o,Ht.HandlesUpdated),Nn(a),this.createMemo(o,a,{newAnnotation:!!this.memo}),AU(a,o,d),Pe(s)}):f||tn(a,o,Ht.HandlesUpdated),this.doneEditMemo(),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData;this.createMemo(o,a,{newAnnotation:f});const{data:u}=a;if(l){const{deltaPoints:d}=i,h=d.world,{textBox:g}=u.handles,{worldPosition:p}=g;p[0]+=h[0],p[1]+=h[1],p[2]+=h[2],g.hasMoved=!0}else if(c===void 0){const{deltaPoints:d}=i,h=d.world;u.handles.points.forEach(p=>{p[0]+=h[0],p[1]+=h[1],p[2]+=h[2]}),a.invalidated=!0}else{const{currentPoints:d}=i,h=d.world;u.handles.points[c]=[...h],a.invalidated=!0}this.editData.hasMoved=!0,Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.touchTapCallback=n=>{n.detail.taps==2&&this.doubleClickCallback(n)},this.doubleClickCallback=n=>{const i=n.detail,{element:o}=i;let a=un(this.getToolName(),o);if(a=this.filterInteractableAnnotationsForElement(o,a),!(a!=null&&a.length))return;const s=a.find(l=>this.isPointNearTool(o,l,i.currentPoints.canvas,6));if(!s)return;const c=s;this.configuration.changeTextCallback(s,n.detail,this._doneChangingTextCallback.bind(this,o,c)),this.editData=null,this.isDrawing=!1,n.stopImmediatePropagation(),n.preventDefault()},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fa.worldToCanvas(G));let _;if(!Zr(d)&&!this.editData&&y!==null&&(_=[S[y]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(d))continue;_&&ir(i,d,"0",S,{color:m,lineWidth:w});const T="1";if(this.configuration.arrowFirst?ey(i,d,T,S[1],S[0],{color:m,width:w,lineDash:x,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:C}):ey(i,d,T,S[0],S[1],{color:m,width:w,lineDash:x,viaMarker:this.configuration.arrowHeadStyle!=="legacy",markerSize:C}),o=!0,!p)continue;const E=this.getLinkedTextBoxStyle(l,u);if(!E.visibility){h.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}if(!h.handles.textBox.hasMoved){const G=S[1];h.handles.textBox.worldPosition=a.canvasToWorld(G)}const D=a.worldToCanvas(h.handles.textBox.worldPosition),I=qi(i,d,"1",[p],D,S,{},E),{x:P,y:M,width:L,height:V}=I;h.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([P,M]),topRight:a.canvasToWorld([P+L,M]),bottomLeft:a.canvasToWorld([P,M+V]),bottomRight:a.canvasToWorld([P+L,M+V])}}return o}}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_doneChangingTextCallback(e,r,n){r.data.text=n,Ce(e);const i=_t(e,this.getToolName());Pe(i),tn(r,e)}_isInsideVolume(e,r,n){return sr(e,n)&&sr(r,n)}};o0.toolName="ArrowAnnotate",o0.hydrate=(e,r,n,i)=>{const o=zn(e);if(!o)return;const{FrameOfReferenceUID:a,referencedImageId:s,viewPlaneNormal:c,instance:l,viewport:f}=o0.hydrateBase(o0,o,r,i),{toolInstance:u,...d}=i||{},h={annotationUID:(i==null?void 0:i.annotationUID)||Dn(),data:{text:n||"",handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:l.getToolName(),viewPlaneNormal:c,FrameOfReferenceUID:a,referencedImageId:s,...d}};nn(h,f.element),Pe([f.id])};let Ou=o0;function b5e(t){return t(prompt("Enter your annotation:"))}function I5e(t,e,r){return r(prompt("Enter your annotation:"))}const a0=class a0 extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,showAngleArc:!1,arcOffset:5,preventHandleOutsideImage:!1,getTextLines:O5e}}){super(e,r),this.addNewAnnotation=n=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u,d]=l.handles.points,h=c.worldToCanvas(f),g=c.worldToCanvas(u),p={start:{x:h[0],y:h[1]},end:{x:g[0],y:g[1]}};if(hi([p.start.x,p.start.y],[p.end.x,p.end.y],[o[0],o[1]])<=a)return!0;if(!d)return!1;const y=c.worldToCanvas(d),m={start:{x:g[0],y:g[1]},end:{x:y[0],y:y[1]}};return hi([m.start.x,m.start.y],[m.end.x,m.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a);const c=Ce(a),{renderingEngine:l}=c;Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.angleStartedNotYetCompleted&&f.handles.points.length===2){this.editData.handleIndex=2;return}this.angleStartedNotYetCompleted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,newAnnotation:f}=this.editData,{data:u}=a;if(this.createMemo(o,a,{newAnnotation:f}),l){const{deltaPoints:g}=i,p=g.world,{textBox:v}=u.handles,{worldPosition:y}=v;y[0]+=p[0],y[1]+=p[1],y[2]+=p[2],v.hasMoved=!0}else if(c===void 0){const{deltaPoints:g}=i,p=g.world;u.handles.points.forEach(y=>{y[0]+=p[0],y[1]+=p[1],y[2]+=p[2]}),a.invalidated=!0}else{const{currentPoints:g}=i,p=g.world;u.handles.points[c]=[...p],a.invalidated=!0}this.editData.hasMoved=!0;const d=Ce(o),{renderingEngine:h}=d;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,this.angleStartedNotYetCompleted=!1,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{var d;let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let h=0;ha.worldToCanvas(k));!v.cachedStats[l]||v.cachedStats[l].angle==null?(v.cachedStats[l]={angle:null},this._calculateCachedStats(g,f,n)):g.invalidated&&this._throttledCalculateCachedStats(g,f,n);let T;if(!Zr(g.annotationUID)&&!this.editData&&m!==null&&(T=[_[m]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(p))continue;T&&ir(i,p,"0",_,{color:w,lineDash:C,lineWidth:x});let E="1";if(vn(i,p,E,_[0],_[1],{color:w,width:x,lineDash:C}),o=!0,_.length!==3)return o;if(E="2",vn(i,p,E,_[1],_[2],{color:w,width:x,lineDash:C}),this.configuration.showAngleArc){const k=_[1],F=this.configuration.arcOffset,j=Math.min(hi([k[0],k[1]],[_[0][0],_[0][1]],[_[2][0],_[2][1]]),hi([k[0],k[1]],[_[2][0],_[2][1]],[_[0][0],_[0][1]]))/F,Y=[];let re=Math.atan2(_[0][1]-k[1],_[0][0]-k[0]),ue=Math.atan2(_[2][1]-k[1],_[2][0]-k[0]);if(ueMath.PI){const Ee=re;re=ue,ue=Ee+2*Math.PI}const pe=32;for(let Ee=0;Ee<=pe;Ee++){const Oe=re+Ee/pe*(ue-re);Y.push([k[0]+j*Math.cos(Oe),k[1]+j*Math.sin(Oe)])}Wc(i,p,"3",Y,{color:w,width:x,lineDash:S})}if(!((d=v.cachedStats[l])!=null&&d.angle))continue;const D=this.getLinkedTextBoxStyle(u,g);if(!D.visibility){v.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const b=this.configuration.getTextLines(v,l);if(!v.handles.textBox.hasMoved){const k=_[1];v.handles.textBox.worldPosition=a.canvasToWorld(k)}const I=a.worldToCanvas(v.handles.textBox.worldPosition),M=qi(i,p,"1",b,I,_,{},D),{x:L,y:V,width:G,height:A}=M;v.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([L,V]),topRight:a.canvasToWorld([L+G,V]),bottomLeft:a.canvasToWorld([L,V+A]),bottomRight:a.canvasToWorld([L+G,V+A])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(d=>d===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o);const f=Ce(o),{renderingEngine:u}=f;Pe(l),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport;if(i.handles.points.length!==3)return;const a=i.handles.points[0],s=i.handles.points[1],c=i.handles.points[2],{cachedStats:l}=i,f=Object.keys(l);for(let d=0;dUr(v,y)).some(y=>!sr(y,p)),l[h]={angle:isNaN(g)?"Incomplete Angle":g}}const u=e.invalidated;return e.invalidated=!1,u&&tn(e,o,Ht.StatsUpdated),l}};a0.toolName="Angle",a0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=a0.hydrateBase(a0,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let HC=a0;function O5e(t,e){const r=t.cachedStats[e],{angle:n}=r;return n===void 0?void 0:isNaN(n)?[`${n}`]:[`${an(n)} °`]}const M5e=(...t)=>{const e=t[0].length===2?[0,0]:[0,0,0],r=t.length;for(const n of t)e[0]+=n[0]/r,e[1]+=n[1]/r,e.length===3&&(e[2]+=n[2]/r);return e},Sc=M5e,ME=class ME extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1,getTextLines:P5e,showArcLines:!1}}){super(e,r),this.addNewAnnotation=n=>{if(this.angleStartedNotYetCompleted)return;this.angleStartedNotYetCompleted=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g,...l.getViewReference({points:[s]})},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,{distanceToPoint:f,distanceToPoint2:u}=this.distanceToLines({viewport:c,points:l.handles.points,canvasCoords:o,proximity:a});return f<=a||u<=a},this.toolSelectedCallback=(n,i,o,a,s=6)=>{const c=n.detail,{element:l}=c;i.highlighted=!0;const f=_t(l,this.getToolName()),u=Ce(l),{renderingEngine:d,viewport:h}=u,{isNearFirstLine:g,isNearSecondLine:p}=this.distanceToLines({viewport:h,points:i.data.handles.points,canvasCoords:a,proximity:s});this.editData={annotation:i,viewportIdsToRender:f,movingTextBox:!1,isNearFirstLine:g,isNearSecondLine:p},this._activateModify(l),Ot(l),Pe(f),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.doneEditMemo(),this.angleStartedNotYetCompleted&&f.handles.points.length<4){zt(o),this.editData.handleIndex=f.handles.points.length;return}this.angleStartedNotYetCompleted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._mouseDownCallback=n=>{const{annotation:i,handleIndex:o}=this.editData,a=n.detail,{element:s,currentPoints:c}=a,l=c.world,{data:f}=i;if(o===1){f.handles.points[1]=l,this.editData.hasMoved=f.handles.points[1][0]!==f.handles.points[0][0]||f.handles.points[1][1]!==f.handles.points[0][0];return}if(o===3){f.handles.points[3]=l,this.editData.hasMoved=f.handles.points[3][0]!==f.handles.points[2][0]||f.handles.points[3][1]!==f.handles.points[2][0],this.angleStartedNotYetCompleted=!1;return}this.editData.hasMoved=!1,Ot(s),f.handles.points[2]=f.handles.points[3]=l,this.editData.handleIndex=f.handles.points.length-1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l,isNearFirstLine:f,isNearSecondLine:u,newAnnotation:d}=this.editData;this.createMemo(o,a,{newAnnotation:d});const{data:h}=a;if(l){const{deltaPoints:v}=i,y=v.world,{textBox:m}=h.handles,{worldPosition:w}=m;w[0]+=y[0],w[1]+=y[1],w[2]+=y[2],m.hasMoved=!0}else if(c===void 0&&(f||u)){const{deltaPoints:v}=i,y=v.world,m=h.handles.points;f?[m[0],m[1]].forEach(x=>{x[0]+=y[0],x[1]+=y[1],x[2]+=y[2]}):u&&[m[2],m[3]].forEach(x=>{x[0]+=y[0],x[1]+=y[1],x[2]+=y[2]}),a.invalidated=!0}else{const{currentPoints:v}=i,y=v.world;h.handles.points[c]=[...y],a.invalidated=!0}this.editData.hasMoved=!0;const g=Ce(o),{renderingEngine:p}=g;Pe(s),a.invalidated&&tn(a,o,Ht.HandlesUpdated)},this.cancel=n=>{if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;s.handles.points.length<4&&gn(i.annotationUID),i.highlighted=!1,s.handles.activeHandleIndex=null;const c=Ce(n),{renderingEngine:l}=c;return Pe(o),a&&Nn(i),this.editData=null,this.angleStartedNotYetCompleted=!1,i.annotationUID},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_START,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_START,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_START,this._mouseDownCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_DOWN,this._mouseDownCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_START,this._mouseDownCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{var d;let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let h=0;ha.worldToCanvas(Oe));!v.cachedStats[l]||v.cachedStats[l].angle==null?(v.cachedStats[l]={angle:null,arc1Angle:null,arc2Angle:null,points:{world:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null},canvas:{arc1Start:null,arc1End:null,arc2Start:null,arc2End:null,arc1Angle:null,arc2Angle:null}}},this._calculateCachedStats(g,f,n)):g.invalidated&&this._throttledCalculateCachedStats(g,f,n);let _;if(!Zr(p)&&!this.editData&&m!==null&&(_=[S[m]]),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;if(!Gr(p))continue;_&&ir(i,p,"0",S,{color:w,lineDash:C,lineWidth:x});const T=[S[0],S[1]],E=[S[2],S[3]];let D="line1";if(vn(i,p,D,T[0],T[1],{color:w,width:x,lineDash:C}),o=!0,S.length<4)return o;D="line2",vn(i,p,D,E[0],E[1],{color:w,width:x,lineDash:C}),D="linkLine";const b=Sc(T[0],T[1]),I=Sc(E[0],E[1]);vn(i,p,D,b,I,{color:w,lineWidth:"1",lineDash:"1,4"});const{arc1Start:P,arc1End:M,arc2End:L,arc2Start:V}=v.cachedStats[l].points.canvas,{arc1Angle:G,arc2Angle:A}=v.cachedStats[l];if(this.configuration.showArcLines&&(D="arc1",vn(i,p,D,P,M,{color:w,lineWidth:"1"}),D="arc2",vn(i,p,D,V,L,{color:w,lineWidth:"1"})),!((d=v.cachedStats[l])!=null&&d.angle))continue;const k=this.getLinkedTextBoxStyle(u,g);if(!k.visibility){v.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const F=this.configuration.getTextLines(v,l);if(!v.handles.textBox.hasMoved){const Oe=na(S);v.handles.textBox.worldPosition=a.canvasToWorld(Oe)}const j=a.worldToCanvas(v.handles.textBox.worldPosition),re=qi(i,p,"cobbAngleText",F,j,S,{},k),{x:ue,y:ce,width:pe,height:Ee}=re;if(v.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([ue,ce]),topRight:a.canvasToWorld([ue+pe,ce]),bottomLeft:a.canvasToWorld([ue,ce+Ee]),bottomRight:a.canvasToWorld([ue+pe,ce+Ee])},this.configuration.showArcLines){const Oe="arcAngle1",_e=[`${G.toFixed(2)} °`],B=Sc(P,M);Eu(i,p,Oe,_e,B,{...k,padding:3});const O="arcAngle2",z=[`${A.toFixed(2)} °`],W=Sc(V,L);Eu(i,p,O,z,W,{...k,padding:3})}}return o},this.distanceToLines=({viewport:n,points:i,canvasCoords:o,proximity:a})=>{const[s,c,l,f]=i,u=n.worldToCanvas(s),d=n.worldToCanvas(c),h=n.worldToCanvas(l),g=n.worldToCanvas(f),p={start:{x:u[0],y:u[1]},end:{x:d[0],y:d[1]}},v={start:{x:h[0],y:h[1]},end:{x:g[0],y:g[1]}},y=hi([p.start.x,p.start.y],[p.end.x,p.end.y],[o[0],o[1]]),m=hi([v.start.x,v.start.y],[v.end.x,v.end.y],[o[0],o[1]]);let w=!1,x=!1;return y<=a?w=!0:m<=a&&(x=!0),{distanceToPoint:y,distanceToPoint2:m,isNearFirstLine:w,isNearSecondLine:x}},this.getArcsStartEndPoints=({firstLine:n,secondLine:i,mid1:o,mid2:a})=>{const s=[o,a],c=S0(n,s),l=S0(i,s),f=c>90?1:0,u=l>90?0:1,d=Sc(s[0],s[1]),h=Math.sqrt((s[1][0]-s[0][0])**2+(s[1][1]-s[0][1])**2),g=.1,p=Sc(n[0],n[1]),v=Sc(i[0],i[1]),y=[n[f][0]-p[0],n[f][1]-p[1]],m=Math.sqrt(y[0]**2+y[1]**2),w=[y[0]/m,y[1]/m],x=[p[0]+w[0]*h*g,p[1]+w[1]*h*g],C=[d[0]-o[0],d[1]-o[1]],S=Math.sqrt(C[0]**2+C[1]**2),_=[C[0]/S,C[1]/S],T=[o[0]+_[0]*h*g,o[1]+_[1]*h*g],E=[i[u][0]-v[0],i[u][1]-v[1]],D=Math.sqrt(E[0]**2+E[1]**2),b=[E[0]/D,E[1]/D],I=[v[0]+b[0]*h*g,v[1]+b[1]*h*g],P=[d[0]-a[0],d[1]-a[1]],M=Math.sqrt(P[0]**2+P[1]**2),L=[P[0]/M,P[1]/M],V=[a[0]+L[0]*h*g,a[1]+L[1]*h*g];return{arc1Start:x,arc1End:T,arc2Start:I,arc2End:V,arc1Angle:c>90?180-c:c,arc2Angle:l>90?180-l:l}},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,25,{trailing:!0})}handleSelectedCallback(e,r,n,i="mouse"){const o=e.detail,{element:a}=o,{data:s}=r;r.highlighted=!0;let c=!1,l;n.worldPosition?c=!0:l=s.handles.points.findIndex(u=>u===n);const f=_t(a,this.getToolName());this.editData={annotation:r,viewportIdsToRender:f,handleIndex:l,movingTextBox:c},this._activateModify(a),Ot(a),Pe(f),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data;if(i.handles.points.length!==4)return;const o=[null,null],a=[null,null];let s=Number.MAX_VALUE;for(let T=0;T<2;T+=1)for(let E=2;E<4;E+=1){const D=ki(i.handles.points[T],i.handles.points[E]);Dc.worldToCanvas(T)),u=[f[0],f[1]],d=[f[2],f[3]],h=Sc(u[0],u[1]),g=Sc(d[0],d[1]),{arc1Start:p,arc1End:v,arc2End:y,arc2Start:m,arc1Angle:w,arc2Angle:x}=this.getArcsStartEndPoints({firstLine:u,secondLine:d,mid1:h,mid2:g}),{cachedStats:C}=i,S=Object.keys(C);for(let T=0;T{if(this.startedDrawing)return;this.startedDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;if(!(l instanceof lr))throw new Error("UltrasoundDirectionalTool can only be used on a StackViewport");Ot(a),this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=this.getReferencedImageId(l,s,d,h),p=l.getFrameOfReferenceUID(),v={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:p,referencedImageId:g},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},label:"",cachedStats:{}}};nn(v,a);const y=_t(a,this.getToolName());return this.editData={annotation:v,viewportIdsToRender:y,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(y),v},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;if(this.startedDrawing&&f.handles.points.length===1){this.editData.handleIndex=1;return}this.startedDrawing=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o),{renderingEngine:d}=u;this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a),this.editData=null,this.isDrawing=!1},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c,movingTextBox:l}=this.editData,{data:f}=a;if(l){const{deltaPoints:h}=i,g=h.world,{textBox:p}=f.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(c===void 0){const{deltaPoints:h}=i,g=h.world;f.handles.points.forEach(v=>{v[0]+=g[0],v[1]+=g[1],v[2]+=g[2]}),a.invalidated=!0}else{const{currentPoints:h}=i,g=h.world;f.handles.points[c]=[...g],a.invalidated=!0}this.editData.hasMoved=!0;const u=Ce(o),{renderingEngine:d}=u;Pe(s)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,this.startedDrawing=!1,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l=this.getTargetId(a),f=a.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let d=0;da.worldToCanvas(M));if(!p.cachedStats[l]||p.cachedStats[l].xValues==null?(p.cachedStats[l]={xValues:[0,0],yValues:[0,0],isHorizontal:!1,units:[""],isUnitless:!1},this._calculateCachedStats(h,f,n)):h.invalidated&&this._throttledCalculateCachedStats(h,f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let w="0";if(Qv(i,g,w,m[0],{color:y},0),o=!0,m.length!==2)return o;if(w="1",Qv(i,g,w,m[1],{color:y},1),p.cachedStats[l].isUnitless){const M=`${g}-line-1`;vn(i,g,"1",m[0],m[1],{color:y,width:1,shadow:this.configuration.shadow},M)}else{const M=m[0],L=m[1],V=L[1]-M[1],G=L[0]-M[0],A=p.cachedStats[l].isHorizontal;let k=[0,0];A?k=[M[0]+G,M[1]]:k=[M[0],M[1]+V];let F=`${g}-line-1`,j="1";vn(i,g,j,m[0],k,{color:y,width:1,shadow:this.configuration.shadow},F),F=`${g}-line-2`,j="2",vn(i,g,j,m[1],k,{color:y,width:1,lineDash:[1,1],shadow:this.configuration.shadow},F)}const C=this.getLinkedTextBoxStyle(u,h);if(!C.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const S=this.configuration.getTextLines(p,l,this.configuration);if(!p.handles.textBox.hasMoved){const M=m[1];p.handles.textBox.worldPosition=a.canvasToWorld(M)}const _=a.worldToCanvas(p.handles.textBox.worldPosition),E=qi(i,g,"1",S,_,m,{},C),{x:D,y:b,width:I,height:P}=E;p.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([D,b]),topRight:a.canvasToWorld([D+I,b]),bottomLeft:a.canvasToWorld([D,b+P]),bottomRight:a.canvasToWorld([D+I,b+P])}}return o},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}toolSelectedCallback(e,r,n,i){}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;const s=_t(o,this.getToolName());let c;n.worldPosition||(c=a.handles.points.findIndex(u=>u===n)),this.editData={handleIndex:c,annotation:r,viewportIdsToRender:s},this._activateModify(o),Ot(o);const l=Ce(o),{renderingEngine:f}=l;Pe(s),e.preventDefault()}_calculateCachedStats(e,r,n){const i=e.data,{element:o}=n.viewport;if(i.handles.points.length!==2)return;const{cachedStats:a}=i,s=Object.keys(a);for(let l=0;lMath.abs(I),C=[y[0],w[0]],S=[y[1],w[1]],_=[m[0],m[1]]}a[f]={xValues:C,yValues:S,isHorizontal:T,units:_,isUnitless:E}}const c=e.invalidated;return e.invalidated=!1,c&&tn(e,o,Ht.StatsUpdated),a}};PE.toolName="UltrasoundDirectionalTool";let qC=PE;function R5e(t,e,r){const n=t.cachedStats[e],{xValues:i,yValues:o,units:a,isUnitless:s,isHorizontal:c}=n;if(s)return[`${an(i[0])} px`];if(r.displayBothAxesDistances){const l=Math.abs(i[1]-i[0]),f=Math.abs(o[1]-o[0]);return[`${an(l)} ${a[0]}`,`${an(f)} ${a[1]}`]}if(c){const l=Math.abs(i[1]-i[0]);return[`${an(l)} ${a[0]}`]}else{const l=Math.abs(o[1]-o[0]);return[`${an(l)} ${a[1]}`]}}function L5e(t){return(t%360+360)%360}function XC(t,e){const r=e[0]-t[0],n=e[1]-t[1],i=Math.atan2(n,r)*(180/Math.PI);return L5e(i)}function yy(t,e){const r=XC(t,e[0]),n=XC(t,e[1]);return rr[0]-n[0]);const e=[t[0].slice()];for(let r=1;r[Math.max(f,r),Math.min(u,n)]).filter(([f,u])=>u>f);if(i.length===0)return[[r,n]];i.sort((f,u)=>f[0]-u[0]);const o=[];let[a,s]=i[0];for(let f=1;fl&&c.push([l,f]),l=Math.max(l,u);return lyy(t,f)),i=YC(n),o=i.reduce((f,[u,d])=>f+(d-u),0);if(o===0)return 0;const a=[];for(const f of r){const u=yy(t,f),d=eB(u,i);a.push(...d)}const l=YC(a).reduce((f,[u,d])=>f+(d-u),0)/o*100;return Math.min(100,Math.max(0,l))}const{transformIndexToWorld:fb}=Mn,pr=class pr extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{preventHandleOutsideImage:!1,getTextLines:N5e,center:null,innerRadius:null,outerRadius:null,startAngle:null,endAngle:null,bLineColor:"rgb(60, 255, 60)",pleuraColor:"rgb(0, 4, 255)",drawDepthGuide:!0,depth_ratio:.5,depthGuideColor:"rgb(0, 255, 255)",depthGuideThickness:4,depthGuideDashLength:20,depthGuideDashGap:16,depthGuideOpacity:.2,fanOpacity:.1,showFanAnnotations:!0,updatePercentageCallback:null,actions:{undo:{method:"undo",bindings:[{key:"z"}]},redo:{method:"redo",bindings:[{key:"y"}]}}}}){super(e,r),this.pleuraAnnotations=[],this.bLineAnnotations=[],this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;Ot(a),this.isDrawing=!0;const{viewPlaneNormal:f,viewUp:u,position:d}=l.getCamera(),h=this.getReferencedImageId(l,s,f,u),g={highlighted:!0,invalidated:!0,metadata:{...l.getViewReference({points:[s]}),toolName:this.getToolName(),referencedImageId:h,viewUp:u,cameraPosition:d},data:{handles:{points:[[...s],[...s]],activeHandleIndex:null},annotationType:this.getActiveAnnotationType(),label:""}};nn(g,a);const p=_t(a,this.getToolName());return this.editData={annotation:g,viewportIdsToRender:p,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),n.preventDefault(),Pe(p),g},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i,[f,u]=l.handles.points,d=c.worldToCanvas(f),h=c.worldToCanvas(u),g={start:{x:d[0],y:d[1]},end:{x:h[0],y:h[1]}};return hi([g.start.x,g.start.y],[g.end.x,g.end.y],[o[0],o[1]])<=a},this.toolSelectedCallback=(n,i)=>{const o=n.detail,{element:a}=o;i.highlighted=!0;const s=_t(a,this.getToolName());this.editData={annotation:i,viewportIdsToRender:s,movingTextBox:!1},this._activateModify(a),Ot(a),Pe(s),n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;c&&!l||(f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),this.doneEditMemo(),c&&Nn(a),this.editData=null,this.isDrawing=!1)},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{viewport:a}=Ce(o)||{};if(!a)return;const{annotation:s,viewportIdsToRender:c,handleIndex:l,movingTextBox:f,newAnnotation:u}=this.editData,{data:d}=s;if(this.createMemo(o,s,{newAnnotation:u}),f){const{deltaPoints:h}=i,g=h.world,{textBox:p}=d.handles,{worldPosition:v}=p;v[0]+=g[0],v[1]+=g[1],v[2]+=g[2],p.hasMoved=!0}else if(l===void 0){const{deltaPoints:h}=i,g=h.world,p=d.handles.points;p.every(y=>{const m=[y[0]+g[0],y[1]+g[1],y[2]+g[2]];return this.isInsideFanShape(a,m)})&&(p.forEach(y=>{y[0]+=g[0],y[1]+=g[1],y[2]+=g[2]}),s.invalidated=!0)}else{const{currentPoints:h}=i,g=h.world;this.isInsideFanShape(a,g)&&(d.handles.points[l]=[...g],s.invalidated=!0)}this.editData.hasMoved=!0,Pe(c),s.invalidated&&tn(s,o,Ht.HandlesUpdated)},this.cancel=n=>{if(this.isDrawing){this.isDrawing=!1,this._deactivateDraw(n),this._deactivateModify(n),zt(n);const{annotation:i,viewportIdsToRender:o,newAnnotation:a}=this.editData,{data:s}=i;return i.highlighted=!1,s.handles.activeHandleIndex=null,Pe(o),a&&Nn(i),this.editData=null,i.annotationUID}},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this._activateDraw=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;if(!this.getFanShapeGeometryParameters(a))return;const{imageData:c}=a.getImageData()||{};if(!c)return o;this.configuration.drawDepthGuide&&this.drawDepthGuide(i,a);let l=un(this.getToolName(),s);if(!(l!=null&&l.length)||(l=this.filterInteractableAnnotationsForElement(s,l),!(l!=null&&l.length)))return o;this.getTargetId(a),a.getRenderingEngine();const f={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id},u=a.worldToCanvas(fb(c,this.configuration.center)),d=this.getIndexToCanvasRatio(a),h=this.configuration.innerRadius*d,g=this.configuration.outerRadius*d,p=a.getCurrentImageId(),v=l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===p).map(_=>{const T=_.data.handles.points.map(D=>a.worldToCanvas(D));return yy(u,T)}),y=YC(v),m=[],w=[],x=_=>{const{annotationUID:T,data:E}=_,{points:D,activeHandleIndex:b}=E.handles;f.annotationUID=T;const{color:I,lineWidth:P,lineDash:M,shadow:L}=this.getAnnotationStyle({annotation:_,styleSpecifier:f}),V=D.map(F=>a.worldToCanvas(F));if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let G;if(!Gr(T))return;!Zr(T)&&!this.editData&&b!==null&&(G=[V[b]]),G&&ir(i,T,"0",V,{color:this.getColorForLineType(_),fill:this.getColorForLineType(_),lineDash:M,lineWidth:P});const A=`${T}-line`;if(vn(i,T,"1",V[0],V[1],{color:this.getColorForLineType(_),width:P,lineDash:M,shadow:L},A),this.configuration.showFanAnnotations){const F=yy(u,V);let j=0;_.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE?ub(w,F).forEach(re=>{eB(re,y).forEach(ce=>{j++;const pe=j,Ee=`${T}-fan-${pe}`,Oe=`2-${pe}`;SC(i,T,Oe,u,h,g,ce[0],ce[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:P,lineDash:M,shadow:L},Ee,10),w.push(ce)})}):_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&ub(m,F).forEach((re,ue)=>{j++;const ce=j,pe=`${T}-fan-${ce}`,Ee=`2-${ce}`;SC(i,T,Ee,u,h,g,re[0],re[1],{color:"transparent",fill:this.getColorForLineType(_),fillOpacity:this.configuration.fanOpacity,width:P,lineDash:M,shadow:L},pe,5),m.push(re)})}};return l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&_.metadata.referencedImageId===p).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;x(_)}),l.filter(_=>_.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE&&_.metadata.referencedImageId===p).forEach(_=>{if(!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;x(_)}),o=!0,this.configuration.updatePercentageCallback&&a&&this.configuration.updatePercentageCallback(this.calculateBLinePleuraPercentage(a)),o},this.activeAnnotationType=pr.USPleuraBLineAnnotationType.BLINE}static filterAnnotations(e,r=()=>!0){const n=un(pr.toolName,e);return n!=null&&n.length?n.filter(o=>{const a=o.metadata.referencedImageId;return r(a)}):[]}static countAnnotations(e,r=()=>!0){const n=un(pr.toolName,e),{viewport:i}=Ce(e),o=i.getImageIds(),a=c=>{const l=o.findIndex(f=>f===c);return l===-1?0:l};if(!(n!=null&&n.length))return;const s=new Map;return n.forEach(c=>{const l=c.metadata.referencedImageId;if(!r(l))return;const{annotationType:f}=c.data;let u;s.has(l)?u=s.get(l):u={frame:a(l),bLine:0,pleura:0},f===pr.USPleuraBLineAnnotationType.PLEURA?u.pleura++:f===pr.USPleuraBLineAnnotationType.BLINE&&u.bLine++,s.set(l,u)}),s}static deleteAnnotations(e,r=()=>!1){const n=un(pr.toolName,e);n!=null&&n.length&&n.forEach(i=>{r(i.metadata.referencedImageId)&&gn(i.annotationUID)})}setActiveAnnotationType(e){this.activeAnnotationType=e}getActiveAnnotationType(){return this.activeAnnotationType}deleteLastAnnotationType(e,r){let n;const i=un(pr.toolName,e);if(r===pr.USPleuraBLineAnnotationType.PLEURA?n=i.filter(o=>o.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA):r===pr.USPleuraBLineAnnotationType.BLINE&&(n=i.filter(o=>o.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE)),(n==null?void 0:n.length)>0){const o=n.pop();gn(o.annotationUID)}}handleSelectedCallback(e,r,n){const i=e.detail,{element:o}=i,{data:a}=r;r.highlighted=!0;let s=!1,c;n.worldPosition?s=!0:c=a.handles.points.findIndex(f=>f===n);const l=_t(o,this.getToolName());this.editData={annotation:r,viewportIdsToRender:l,handleIndex:c,movingTextBox:s},this._activateModify(o),Ot(o),Pe(l),e.preventDefault()}isInsideFanShape(e,r){if(!this.getFanShapeGeometryParameters(e))return!1;const{imageData:n}=e.getImageData()||{};if(n){const i=e.worldToCanvas(n.indexToWorld(this.configuration.center)),o=e.worldToCanvas(r),a=XC(i,o);return a>=this.configuration.startAngle&&a<=this.configuration.endAngle}}updateFanGeometryConfiguration(e){e&&(this.isFanShapeGeometryParametersValid(e)&&(this.configuration.center=[e.center[0],e.center[1],0]),this.configuration.innerRadius=e.innerRadius,this.configuration.outerRadius=e.outerRadius,this.configuration.startAngle=e.startAngle,this.configuration.endAngle=e.endAngle)}deriveFanGeometryFromViewport(e){const r=e.getCurrentImageId(),{fanGeometry:n}=nE(r)||{};n&&this.updateFanGeometryConfiguration(n)}isFanShapeGeometryParametersValid(e){return e||(e=this.configuration),(e==null?void 0:e.center)&&(e==null?void 0:e.innerRadius)>0&&(e==null?void 0:e.outerRadius)&&(e==null?void 0:e.startAngle)>0&&(e==null?void 0:e.startAngle)<360&&(e==null?void 0:e.endAngle)>0&&(e==null?void 0:e.endAngle)<360}getFanShapeGeometryParameters(e){if(this.isFanShapeGeometryParametersValid())return!0;if(!this.isFanShapeGeometryParametersValid()){const r=e.getCurrentImageId(),n=mt("ultrasoundFanShapeGeometry",r);this.updateFanGeometryConfiguration(n)}return this.isFanShapeGeometryParametersValid()||this.deriveFanGeometryFromViewport(e),this.isFanShapeGeometryParametersValid()}calculateBLinePleuraPercentage(e){if(!this.getFanShapeGeometryParameters(e))return;const{imageData:r}=e.getImageData()||{};if(!r)return;const{element:n}=e,i=e.worldToCanvas(r.indexToWorld(this.configuration.center)),o=e.getCurrentImageId(),a=un(this.getToolName(),n)||[],s=a.filter(l=>l.data.annotationType===pr.USPleuraBLineAnnotationType.PLEURA&&l.metadata.referencedImageId===o).map(l=>l.data.handles.points.map(u=>e.worldToCanvas(u))),c=a.filter(l=>l.data.annotationType===pr.USPleuraBLineAnnotationType.BLINE&&l.metadata.referencedImageId===o).map(l=>l.data.handles.points.map(u=>e.worldToCanvas(u)));return A5e(i,s,c)}getColorForLineType(e){const{annotationType:r}=e.data,{bLineColor:n,pleuraColor:i}=this.configuration;return r===pr.USPleuraBLineAnnotationType.BLINE?n:r===pr.USPleuraBLineAnnotationType.PLEURA?i:n}getIndexToCanvasRatio(e){const{imageData:r}=e.getImageData()||{},n=e.worldToCanvas(r.indexToWorld([1,0,0])),i=e.worldToCanvas(r.indexToWorld([2,0,0])),o=[i[0]-n[0],i[1]-n[1]];return Math.sqrt(o[0]*o[0]+o[1]*o[1])}drawDepthGuide(e,r){if(!this.getFanShapeGeometryParameters(r))return;const{imageData:n}=r.getImageData()||{};if(!n)return;const i=g=>g*180/Math.PI,o=g=>g*Math.PI/180,a=g=>r.worldToCanvas(fb(n,g)),s=this.configuration.innerRadius+this.configuration.depth_ratio*(this.configuration.outerRadius-this.configuration.innerRadius),c=this.configuration.startAngle,f=this.configuration.endAngle-c,u=o(f)*s;let d=Math.round(u/(this.configuration.depthGuideDashLength+this.configuration.depthGuideDashGap));d<=0&&(d=Math.max(15,Math.round(f/5)));const h=f/d;for(let g=0;g{const i=zn(e);if(!i)return;const{FrameOfReferenceUID:o,referencedImageId:a,viewPlaneNormal:s,instance:c,viewport:l}=pr.hydrateBase(pr,i,r,n),{toolInstance:f,...u}=n||{},d={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:r}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{toolName:c.getToolName(),viewPlaneNormal:s,FrameOfReferenceUID:o,referencedImageId:a,...u}};nn(d,l.element),Pe([l.id])};let JC=pr;function N5e(t,e){return[""]}const rp=class rp extends ar{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{getTextCallback:k5e,changeTextCallback:V5e,canvasPosition:[10,10],canvasSize:10,handleRadius:"6",seriesLevel:!1,isPoint:!1}}){super(e,r),this.addNewAnnotation=n=>{const i=n.detail,{element:o,currentPoints:a}=i,s=Ce(o),{viewport:c}=s,l=a.world,f=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...l]]},seriesLevel:this.configuration.seriesLevel,isPoint:this.configuration.isPoint}});nn(f,o);const u=_t(o,this.getToolName());return n.preventDefault(),Pe(u),this.configuration.getTextCallback(d=>{if(!d){gn(f.annotationUID),Pe(u),this.isDrawing=!1;return}f.data.text=d,Nn(f),Pe(u)}),this.createMemo(o,f,{newAnnotation:!0}),f},this.isPointNearTool=(n,i,o,a)=>{const s=Ce(n),{viewport:c}=s,{data:l}=i;if(!(l!=null&&l.isPoint))return!1;const{canvasPosition:f,canvasSize:u}=this.configuration;return f!=null&&f.length?Math.abs(o[0]-f[0]+u/2)<=u/2&&Math.abs(o[1]-f[1]+u/2)<=u/2:!1},this.toolSelectedCallback=(n,i)=>{i.highlighted=!0,n.preventDefault()},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c}=this.editData,{viewportId:l,renderingEngine:f}=Ce(o);this.eventDispatchDetail={viewportId:l,renderingEngineId:f.id},this._deactivateModify(o),zt(o),c&&this.createMemo(o,a,{newAnnotation:c}),this.editData=null,this.isDrawing=!1,this.doneEditMemo(),this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID),Pe(s),c&&Nn(a)},this.doubleClickCallback=n=>{const i=n.detail,{element:o}=i;let a=un(this.getToolName(),o);if(a=this.filterInteractableAnnotationsForElement(o,a),!(a!=null&&a.length))return;const s=a.find(l=>this.isPointNearTool(o,l,i.currentPoints.canvas,6));if(!s)return;const c=s;this.createMemo(o,c),this.configuration.changeTextCallback(s,n.detail,this._doneChangingTextCallback.bind(this,o,c)),this.isDrawing=!1,this.doneEditMemo(),n.stopImmediatePropagation(),n.preventDefault()},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,{annotation:c,viewportIdsToRender:l,newAnnotation:f}=this.editData,{data:u}=c;this.createMemo(a,c,{newAnnotation:f}),u.handles.points[0]=[...s],c.invalidated=!0,Pe(l)},this._activateModify=n=>{Be.isInteractingWithTool=!0,n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateModify=n=>{Be.isInteractingWithTool=!1,n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n,{element:s}=a;let c=un(this.getToolName(),s);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(s,c),!(c!=null&&c.length)))return o;const l={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let f=0;fw+y),v,{color:g,width:1});if(o=!0,!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o}return o}}handleSelectedCallback(e,r){const n=e.detail,{element:i}=n;r.highlighted=!0;const o=_t(i,this.getToolName());this.editData={annotation:r,viewportIdsToRender:o},this._activateModify(i),Ot(i),Pe(o),e.preventDefault()}static setPoint(e,r=!e.data.isPoint,n){e.data.isPoint=r,tn(e,n)}_doneChangingTextCallback(e,r,n){r.data.text=n;const i=_t(e,this.getToolName());Pe(i),tn(r,e)}cancel(e){if(this.isDrawing){this.isDrawing=!1,this._deactivateModify(e),zt(e);const{annotation:r,viewportIdsToRender:n,newAnnotation:i}=this.editData,{data:o}=r;return r.highlighted=!1,o.handles.activeHandleIndex=null,Pe(n),i&&Nn(r),this.editData=null,r.annotationUID}}_isInsideVolume(e,r,n){return sr(e,n)&&sr(r,n)}};rp.toolName="KeyImage",rp.dataSeries={data:{seriesLevel:!0}},rp.dataPoint={data:{isPoint:!0}};let ZC=rp;function k5e(t){return t(prompt("Enter your annotation:"))}function V5e(t,e,r){return r(prompt("Enter your annotation:"))}class tB extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.preMouseDownCallback=n=>this._deleteNearbyAnnotations(n,"mouse"),this.preTouchStartCallback=n=>this._deleteNearbyAnnotations(n,"touch")}_deleteNearbyAnnotations(e,r){const{renderingEngineId:n,viewportId:i,element:o,currentPoints:a}=e.detail,s=Or(i,n);if(!s)return!1;const c=s._toolInstances,l=[];for(const f in c){const u=c[f];if(typeof u.isPointNearTool!="function"||typeof u.filterInteractableAnnotationsForElement!="function")continue;const d=un(f,o),h=u.filterInteractableAnnotationsForElement(o,d);if(h)for(const g of h)u.isPointNearTool(o,g,a.canvas,10,r)&&l.push(g.annotationUID)}for(const f of l){Ro(f);const u=Br(f);ar.createAnnotationMemo(o,u,{deleting:!0}),gn(f)}return e.preventDefault(),!0}}tB.toolName="Eraser";const{transformWorldToIndex:db,transformIndexToWorld:F5e}=Mn,ip=class ip extends ai{constructor(e,r){const n=Ei({configuration:{positiveStdDevMultiplier:aU,shrinkExpandIncrement:.1,islandRemoval:{enabled:!1}}},r);super(e,n)}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a,{viewUp:l}=s.getCamera(),{segmentationId:f,segmentIndex:u,labelmapVolumeId:d,referencedVolumeId:h}=await this.getLabelmapSegmentationData(s);if(!this._isOrthogonalView(s,h))throw new Error("Oblique view is not supported yet");return this.growCutData={metadata:{...s.getViewReference({points:[o]}),viewUp:l},segmentation:{segmentationId:f,segmentIndex:u,labelmapVolumeId:d,referencedVolumeId:h},viewportId:s.id,renderingEngineId:c.id},e.preventDefault(),!0}shrink(){this._runLastCommand({shrinkExpandAmount:-this.configuration.shrinkExpandIncrement})}expand(){this._runLastCommand({shrinkExpandAmount:this.configuration.shrinkExpandIncrement})}refresh(){this._runLastCommand()}async getGrowCutLabelmap(e){throw new Error("Not implemented")}async runGrowCut(){const{growCutData:e,configuration:r}=this,{segmentation:{segmentationId:n,segmentIndex:i,labelmapVolumeId:o}}=e,a=Le.getVolume(o);let s=0;const c=async({shrinkExpandAmount:l=0}={})=>{l!==0&&(this.seeds=null),s+=l;const f=Math.max(.1,r.positiveStdDevMultiplier+s),u=l<0?Math.max(1,RC-Math.abs(s)*3):RC+s*3,d={...e,options:{...e.options||{},positiveSeedValue:i,negativeSeedValue:255,positiveStdDevMultiplier:f,negativeSeedMargin:u}},h=await this.getGrowCutLabelmap(d),{isPartialVolume:g}=r;(g?this.applyPartialGrowCutLabelmap:this.applyGrowCutLabelmap)(n,i,a,h),this._removeIslands(d)};await c(),ip.lastGrowCutCommand=c,this.growCutData=null}applyPartialGrowCutLabelmap(e,r,n,i){const o=i.voxelManager.getCompleteScalarDataArray(),a=n.voxelManager,[s,c,l]=i.dimensions,[f,u]=n.dimensions,d=s*c,h=f*u;for(let g=0;g{s===r&&o.setAtIndex(c,s)}),io(e)}_runLastCommand({shrinkExpandAmount:e=0}={}){const r=ip.lastGrowCutCommand;r&&r({shrinkExpandAmount:e})}async getLabelmapSegmentationData(e){const r=ol(e.id);if(!r)throw new Error("No active segmentation found");const{segmentationId:n}=r,i=ea(n),{representationData:o}=Ln(n),a=o[Dt.Labelmap];let{volumeId:s,referencedVolumeId:c}=a;if(!s){const l=e.getImageIds();if(Nu(l))s=Sh(n).volumeId;else{const f=e.getCurrentImageId(),u=Le.getImage(f),d=iC(f);c=this._createFakeVolume([u.imageId,d.imageId]).volumeId;const g=Vu(e.id,n),p=iC(g);s=this._createFakeVolume([g,p.imageId]).volumeId}}if(!c){const{imageIds:l}=a,f=l.map(h=>Le.getImage(h).referencedImageId),u=Le.generateVolumeId(f),d=Le.getVolume(u);c=d?d.volumeId:(await i5(u,f)).volumeId}return{segmentationId:n,segmentIndex:i,labelmapVolumeId:s,referencedVolumeId:c}}_createFakeVolume(e){const r=Le.generateVolumeId(e),n=Le.getVolume(r);if(n)return n;const i=r5(e,r),o=i.spacing;o[2]===0&&(o[2]=1);const a=new lh({volumeId:r,dataType:i.dataType,metadata:structuredClone(i.metadata),dimensions:i.dimensions,spacing:i.spacing,origin:i.origin,direction:i.direction,referencedVolumeId:i.referencedVolumeId,imageIds:i.imageIds,referencedImageIds:i.referencedImageIds});return Le.putVolumeSync(r,a),a}_isOrthogonalView(e,r){const i=Le.getVolume(r).imageData,o=e.getCamera(),{ijkVecColDir:a,ijkVecSliceDir:s}=f5(i,o);return[a,s].every(c=>$t(Math.abs(c[0]),1)||$t(Math.abs(c[1]),1)||$t(Math.abs(c[2]),1))}getRemoveIslandData(e){}_removeIslands(e){const{islandRemoval:r}=this.configuration;if(!r.enabled)return;const{segmentation:{segmentIndex:n,labelmapVolumeId:i},renderingEngineId:o,viewportId:a}=e,s=Le.getVolume(i),c=this.getRemoveIslandData(e);if(!c)return;const[l,f]=s.dimensions,u=l*f,{worldIslandPoints:d=[],islandPointIndexes:h=[]}=c;let g=[...(c==null?void 0:c.ijkIslandPoints)??[]];const v=Jr(o).getViewport(a),{voxelManager:y}=s,m=new nd;g=g.concat(d.map(w=>db(s.imageData,w))),g=g.concat(h.map(w=>{const x=w%l,C=Math.floor(w/l)%f,S=Math.floor(w/u);return[x,C,S]})),m.initialize(v,y,{points:g,previewSegmentIndex:n,segmentIndex:n}),m.floodFillSegmentIsland(),m.removeExternalIslands(),m.removeInternalIslands()}getSegmentStyle({segmentationId:e,viewportId:r,segmentIndex:n}){return vV({segmentationId:e,segmentIndex:n,viewportId:r})}};ip.lastGrowCutCommand=null;let Y0=ip;Y0.toolName="GrowCutBaseTool";const RE=class RE extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positiveSeedVariance:.5,negativeSeedVariance:.9}}){super(e,r),this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,{world:s}=a,c=Ce(o),{viewport:l}=c;this.growCutData.circleBorderPoint=s,Pe([l.id])},this._endCallback=async n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a;this.runGrowCut(),this._deactivateDraw(o),this.growCutData=null,zt(o),Pe([s.id])},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a;return await super.preMouseDownCallback(e),Object.assign(this.growCutData,{circleCenterPoint:o,circleBorderPoint:o}),this._activateDraw(n),Ot(n),Pe([s.id]),!0}async getGrowCutLabelmap(e){const{segmentation:{referencedVolumeId:r},renderingEngineId:n,viewportId:i,circleCenterPoint:o,circleBorderPoint:a,options:s}=e,l=Jr(n).getViewport(i),f=N0(En(Ve(),o,a));return iU(r,{center:o,radius:f},l,s)}_activateDraw(e){e.addEventListener(N.MOUSE_UP,this._endCallback),e.addEventListener(N.MOUSE_DRAG,this._dragCallback),e.addEventListener(N.MOUSE_CLICK,this._endCallback)}renderAnnotation(e,r){if(!this.growCutData)return;const{viewport:n}=e,{segmentation:i,circleCenterPoint:o,circleBorderPoint:a}=this.growCutData,s=n.worldToCanvas(o),c=n.worldToCanvas(a),l=Ga(qt(),c,s),f=qK(l);if($t(f,0))return;const u="growcut",d="0",{color:h}=this.getSegmentStyle({segmentationId:i.segmentationId,segmentIndex:i.segmentIndex,viewportId:n.id});No(r,u,d,s,f,{color:h})}};RE.toolName="RegionSegment";let QC=RE;const LE=class LE extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!1,positiveSeedVariance:.4,negativeSeedVariance:.9,subVolumePaddingPercentage:.1,islandRemoval:{enabled:!1}}}){super(e,r),this.mouseTimer=null,this.allowedToProceed=!1}mouseMoveCallback(e){if(this.mode!==An.Active)return;const r=e.detail,{currentPoints:n,element:i}=r,{world:o}=n;i.style.cursor="default",this.mouseTimer!==null&&(window.clearTimeout(this.mouseTimer),this.mouseTimer=null),this.mouseTimer=window.setTimeout(()=>{this.onMouseStable(e,o,i)},this.configuration.mouseStabilityDelay||500)}async onMouseStable(e,r,n){await super.preMouseDownCallback(e);const i=Le.getVolume(this.growCutData.segmentation.referencedVolumeId),o=sU(i,r,{})||{positiveSeedIndices:new Set,negativeSeedIndices:new Set},{positiveSeedIndices:a,negativeSeedIndices:s}=o;let c;a.size/s.size>20||s.size<30?(c="not-allowed",this.allowedToProceed=!1):(c="copy",this.allowedToProceed=!0);const l=Ce(n);n&&(n.style.cursor=c,requestAnimationFrame(()=>{n.style.cursor!==c&&(n.style.cursor=c)})),this.allowedToProceed&&(this.seeds=o),l&&l.viewport&&l.viewport.render()}async preMouseDownCallback(e){if(!this.allowedToProceed)return!1;const r=e.detail,{currentPoints:n,element:i}=r;Ce(i)&&(i.style.cursor="wait",requestAnimationFrame(()=>{i.style.cursor!=="wait"&&(i.style.cursor="wait")}));const{world:a}=n;return await super.preMouseDownCallback(e),this.growCutData=Ei(this.growCutData,{worldPoint:a,islandRemoval:{worldIslandPoints:[a]}}),this.growCutData.worldPoint=a,this.growCutData.islandRemoval={worldIslandPoints:[a]},await this.runGrowCut(),i&&(i.style.cursor="default"),!0}getRemoveIslandData(e){const{worldPoint:r}=e;return{worldIslandPoints:[r]}}async getGrowCutLabelmap(e){const{segmentation:{referencedVolumeId:r},worldPoint:n,options:i}=e,{subVolumePaddingPercentage:o}=this.configuration,a={...i,subVolumePaddingPercentage:o,seeds:this.seeds};return cU({referencedVolumeId:r,worldPosition:n,options:a})}};LE.toolName="RegionSegmentPlus";let eS=LE;const U5e=[-1/0,-995],B5e=[0,1900],G5e=[1e3,1900],{transformWorldToIndex:jm,transformIndexToWorld:x3}=Mn;class nB extends Y0{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{isPartialVolume:!0,positivePixelRange:B5e,negativePixelRange:U5e,islandRemoval:{enabled:!0,islandPixelRange:G5e}}}){super(e,r),this._dragCallback=n=>{const i=n.detail,{element:o,currentPoints:a}=i,{world:s}=a,c=Ce(o),{viewport:l}=c,f=this._getHorizontalLineWorldPoints(c,s);this.growCutData.horizontalLines[1]=f,Pe([l.id])},this._endCallback=async n=>{const i=n.detail,{element:o}=i,a=Ce(o),{viewport:s}=a;await this.runGrowCut(),this._deactivateDraw(o),this.growCutData=null,zt(o),Pe([s.id])},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback)}}async preMouseDownCallback(e){const r=e.detail,{element:n,currentPoints:i}=r,{world:o}=i,a=Ce(n),{viewport:s,renderingEngine:c}=a,l=this._getHorizontalLineWorldPoints(a,o);return await super.preMouseDownCallback(e),this.growCutData.horizontalLines=[l,l],this._activateDraw(n),Ot(n),Pe([s.id]),!0}renderAnnotation(e,r){if(!this.growCutData)return;const{segmentation:n,horizontalLines:i}=this.growCutData;if(i.length!==2)return;const{viewport:o}=e,{segmentationId:a,segmentIndex:s}=n,[c,l]=i,[f,u]=c,[d,h]=l,g=[f,u,h,d].map(S=>o.worldToCanvas(S)),p="growCutRect",v="0",{color:y,fillColor:m,lineWidth:w,fillOpacity:x,lineDash:C}=this.getSegmentStyle({segmentationId:a,segmentIndex:s,viewportId:o.id});Cs(r,p,v,g,{color:y,fillColor:m,fillOpacity:x,lineWidth:w,lineDash:C,closePath:!0})}async getGrowCutLabelmap(e){const{segmentation:{segmentIndex:r,referencedVolumeId:n},renderingEngineId:i,viewportId:o,horizontalLines:a}=e,c=Jr(i).getViewport(o),[l,f]=a,u=[l[0],l[1],f[1],f[0]],d=Le.getVolume(n),{topLeft:h,bottomRight:g}=this._getWorldBoundingBoxFromProjectedSquare(c,u),p=jm(d.imageData,h),v=jm(d.imageData,g),y={boundingBox:{ijkTopLeft:p,ijkBottomRight:v}},m=this.configuration,w={positiveSeedValue:r,negativeSeedValue:255,negativePixelRange:m.negativePixelRange,positivePixelRange:m.positivePixelRange};return oU(n,y,w)}getRemoveIslandData(){const{segmentation:{segmentIndex:e,referencedVolumeId:r,labelmapVolumeId:n}}=this.growCutData,i=Le.getVolume(r),o=Le.getVolume(n),a=i.voxelManager.getCompleteScalarDataArray(),s=o.voxelManager.getCompleteScalarDataArray(),{islandPixelRange:c}=this.configuration.islandRemoval,l=[];for(let f=0,u=s.length;f=c[0]&&d<=c[1]&&l.push(f)}return{islandPointIndexes:l}}_activateDraw(e){e.addEventListener(N.MOUSE_UP,this._endCallback),e.addEventListener(N.MOUSE_DRAG,this._dragCallback),e.addEventListener(N.MOUSE_CLICK,this._endCallback)}_projectWorldPointAcrossSlices(e,r,n){const i=this._getViewportVolume(e),{dimensions:o}=i,a=jm(i.imageData,r),s=n.findIndex(f=>$t(Math.abs(f),1));if(s===-1)throw new Error("Non-orthogonal direction vector");const c=[...a],l=[...a];return c[s]=0,l[s]=o[s]-1,[c,l]}_getCuboidIJKEdgePointsFromProjectedWorldPoint(e,r){const{viewPlaneNormal:n}=e.getCamera();return this._projectWorldPointAcrossSlices(e,r,n)}_getWorldCuboidCornerPoints(e,r){const n=[],i=this._getViewportVolume(e);return r.forEach(o=>{const s=this._getCuboidIJKEdgePointsFromProjectedWorldPoint(e,o).map(c=>x3(i.imageData,c));n.push(...s)}),n}_getWorldBoundingBoxFromProjectedSquare(e,r){const n=this._getWorldCuboidCornerPoints(e,r),i=[...n[0]],o=[...n[0]];return n.forEach(a=>{NK(i,i,a),kK(o,o,a)}),{topLeft:i,bottomRight:o}}_getViewportVolume(e){if(!(e instanceof Ir))throw new Error("Viewport is not a BaseVolumeViewport");const r=e.getAllVolumeIds()[0];return Le.getVolume(r)}_getHorizontalLineIJKPoints(e,r){const{viewport:n}=e,i=this._getViewportVolume(n),{dimensions:o}=i,a=jm(i.imageData,r),{viewUp:s,viewPlaneNormal:c}=n.getCamera(),f=Rn(Ve(),s,c).findIndex(h=>$t(Math.abs(h),1)),u=[...a],d=[...a];return u[f]=0,d[f]=o[f]-1,[u,d]}_getHorizontalLineWorldPoints(e,r){const{viewport:n}=e,i=this._getViewportVolume(n),[o,a]=this._getHorizontalLineIJKPoints(e,r),s=x3(i.imageData,o),c=x3(i.imageData,a);return[s,c]}}nB.toolName="WholeBodySegment";function W5e(t,e,r=!0){const n=Object.assign({},e,{segmentIndex:0});j4(t,n)}function z5e(t,e){W5e(t,e,!0)}class rB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:j4,ERASE_INSIDE:z5e},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c;this.isDrawing=!0;const f=l.getCamera(),{viewPlaneNormal:u,viewUp:d}=f,h=ol(l.id);if(!h)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:g}=h,p=ea(g),v=dd(g),y=el(l.id,g,p),{representationData:m}=Ln(g),w=m[Dt.Labelmap],x={highlighted:!0,invalidated:!0,metadata:{viewPlaneNormal:[...u],viewUp:[...d],FrameOfReferenceUID:l.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:y},data:{handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null}}},C=_t(a,this.getToolName());if(this.editData={annotation:x,segmentIndex:p,segmentationId:g,segmentsLocked:v,segmentColor:y,viewportIdsToRender:C,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},l instanceof Ir){const{volumeId:S}=w,_=Le.getVolume(S);this.editData={...this.editData,volumeId:S,referencedVolumeId:_.referencedVolumeId}}else{const S=Vu(l.id,g);this.editData={...this.editData,imageId:S}}return this._activateDraw(a),Ot(a),n.preventDefault(),Pe(C),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,handleIndex:c}=this.editData,{data:l}=a,{currentPoints:f}=i,u=Ce(o),{worldToCanvas:d,canvasToWorld:h}=u.viewport,g=f.world,{points:p}=l.handles;p[c]=[...g];let v,y,m,w,x,C,S,_;switch(c){case 0:case 3:v=d(p[0]),w=d(p[3]),y=[w[0],v[1]],m=[v[0],w[1]],C=h(y),S=h(m),p[1]=C,p[2]=S;break;case 1:case 2:y=d(p[1]),m=d(p[2]),v=[m[0],y[1]],w=[y[0],m[1]],x=h(v),_=h(w),p[0]=x,p[3]=_;break}a.invalidated=!0,this.editData.hasMoved=!0,Pe(s)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=a;if(s&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const f=Ce(o),u={...this.editData,points:l.handles.points,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(f,u),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{annotation:s}=this.editData,c=s.metadata,l=s.annotationUID,f=s.data,{points:u}=f.handles,d=u.map(p=>a.worldToCanvas(p)),h=`rgb(${c.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(P1(i,l,"0",d[0],d[3],{color:h}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}rB.toolName="RectangleScissor";class iB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:G5,ERASE_INSIDE:HF},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=o.canvas,l=Ce(a),{viewport:f}=l;this.isDrawing=!0;const u=f.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=ol(f.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:p}=g,v=ea(p),y=dd(p),m=el(f.id,p,v),{representationData:w}=Ln(p),x=w.Labelmap;if(!x)throw new Error("No labelmap data found for the active segmentation, create one before using scissors tool");const C={invalidated:!0,highlighted:!0,metadata:{viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:f.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:m},data:{handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},isDrawing:!0,cachedStats:{}}},S=[f.id];if(this.editData={annotation:C,centerCanvas:c,segmentIndex:v,segmentationId:p,segmentsLocked:y,segmentColor:m,viewportIdsToRender:S,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null},f instanceof Ir){const{volumeId:_}=x,T=Le.getVolume(_);this.editData={...this.editData,volumeId:_,referencedVolumeId:T.referencedVolumeId}}else{const _=Vu(f.id,p);this.editData={...this.editData,imageId:_}}return this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h,centerCanvas:g}=this.editData,{data:p}=d,v=Math.abs(s[0]-g[0]),y=Math.abs(s[1]-g[1]),m=Math.sqrt(v*v+y*y),w=[g[0],g[1]+m],x=[g[0],g[1]-m],C=[g[0]-m,g[1]],S=[g[0]+m,g[1]];p.handles.points=[u(w),u(x),u(C),u(S)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=a,{viewPlaneNormal:f,viewUp:u}=a.metadata;if(s&&!c)return;l.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const d=Ce(o),h={...this.editData,points:l.handles.points,viewPlaneNormal:f,viewUp:u,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(d,h),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback),n.addEventListener(N.TOUCH_END,this._endCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{viewportIdsToRender:s}=this.editData;if(!s.includes(a.id))return o;const{annotation:c}=this.editData,l=c.metadata,f=c.annotationUID,u=c.data,{points:d}=u.handles,h=d.map(x=>a.worldToCanvas(x)),g=h[0],p=h[1],v=[Math.floor((g[0]+p[0])/2),Math.floor((g[1]+p[1])/2)],y=Math.abs(g[1]-Math.floor((g[1]+p[1])/2)),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(No(i,f,"0",v,y,{color:m}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}iB.toolName="CircleScissor";class oB extends rd{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{strategies:{FILL_INSIDE:$F,ERASE_INSIDE:jF},defaultStrategy:"FILL_INSIDE",activeStrategy:"FILL_INSIDE"}}){super(e,r),this.preMouseDownCallback=n=>{if(this.isDrawing===!0)return;this.doneEditMemo();const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=o.canvas,l=Ce(a),{viewport:f}=l;this.isDrawing=!0;const u=f.getCamera(),{viewPlaneNormal:d,viewUp:h}=u,g=ol(f.id);if(!g)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:p}=g,v=ea(p),y=dd(p),m=el(f.id,p,v);this.isDrawing=!0;const w={metadata:{viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:f.getFrameOfReferenceUID(),referencedImageId:"",toolName:this.getToolName(),segmentColor:m},data:{invalidated:!0,handles:{points:[[...s],[...s],[...s],[...s]],activeHandleIndex:null},cachedStats:{},highlighted:!0}},x=[f.id];this.editData={annotation:w,centerCanvas:c,segmentIndex:v,segmentationId:p,segmentsLocked:y,segmentColor:m,toolGroupId:this.toolGroupId,viewportIdsToRender:x,handleIndex:3,movingTextBox:!1,newAnnotation:!0,hasMoved:!1,volumeId:null,referencedVolumeId:null,imageId:null};const{representationData:C}=Ln(p),S=this.getEditData({viewport:f,representationData:C,segmentsLocked:y,segmentationId:p});return this.editData={...this.editData,...S},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(x),!0},this._dragCallback=n=>{this.isDrawing=!0;const i=n.detail,{element:o}=i,{currentPoints:a}=i,s=a.canvas,c=Ce(o),{renderingEngine:l,viewport:f}=c,{canvasToWorld:u}=f,{annotation:d,viewportIdsToRender:h,centerCanvas:g}=this.editData,{data:p}=d,v=Math.abs(s[0]-g[0]),y=Math.abs(s[1]-g[1]),m=Math.sqrt(v*v+y*y),w=[g[0],g[1]+m],x=[g[0],g[1]-m],C=[g[0]-m,g[1]],S=[g[0]+m,g[1]];p.handles.points=[u(w),u(x),u(C),u(S)],d.invalidated=!0,this.editData.hasMoved=!0,Pe(h)},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,newAnnotation:s,hasMoved:c,segmentIndex:l,segmentsLocked:f}=this.editData,{data:u}=a,{viewPlaneNormal:d,viewUp:h}=a.metadata;if(s&&!c)return;a.highlighted=!1,u.handles.activeHandleIndex=null,this._deactivateDraw(o),zt(o);const g=Ce(o),p={...this.editData,points:u.handles.points,segmentIndex:l,segmentsLocked:f,viewPlaneNormal:d,viewUp:h,createMemo:this.createMemo.bind(this)};this.editData=null,this.isDrawing=!1,this.applyActiveStrategy(g,p),this.doneEditMemo()},this._activateDraw=n=>{n.addEventListener(N.MOUSE_UP,this._endCallback),n.addEventListener(N.MOUSE_DRAG,this._dragCallback),n.addEventListener(N.MOUSE_CLICK,this._endCallback),n.addEventListener(N.MOUSE_MOVE,this._dragCallback),n.addEventListener(N.TOUCH_END,this._endCallback),n.addEventListener(N.TOUCH_TAP,this._endCallback),n.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=n=>{n.removeEventListener(N.MOUSE_UP,this._endCallback),n.removeEventListener(N.MOUSE_DRAG,this._dragCallback),n.removeEventListener(N.MOUSE_CLICK,this._endCallback),n.removeEventListener(N.MOUSE_MOVE,this._dragCallback),n.removeEventListener(N.TOUCH_END,this._endCallback),n.removeEventListener(N.TOUCH_DRAG,this._dragCallback),n.removeEventListener(N.TOUCH_TAP,this._endCallback)},this.renderAnnotation=(n,i)=>{let o=!1;if(!this.editData)return o;const{viewport:a}=n,{viewportIdsToRender:s}=this.editData;if(!s.includes(a.id))return o;const{annotation:c}=this.editData,l=c.metadata,f=c.annotationUID,u=c.data,{points:d}=u.handles,h=d.map(x=>a.worldToCanvas(x)),g=h[0],p=h[1],v=[Math.floor((g[0]+p[0])/2),Math.floor((g[1]+p[1])/2)],y=Math.abs(g[1]-Math.floor((g[1]+p[1])/2)),m=`rgb(${l.segmentColor.slice(0,3)})`;return a.getRenderingEngine()?(No(i,f,"0",v,y,{color:m}),o=!0,o):(console.warn("Rendering Engine has been destroyed"),o)}}}oB.toolName="SphereScissor";const{transformWorldToIndex:eg}=Mn;class aB extends gy{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{storePointData:!1,numSlicesToPropagate:10,calculatePointsInsideVolume:!0,getTextLines:$5e,statsCalculator:rc,showTextBox:!1,throttleTimeout:100}}){super(e,r),this.isHandleOutsideImage=!1,this.addNewAnnotation=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l,renderingEngine:f}=c;this.isDrawing=!0;const u=l.getCamera(),{viewPlaneNormal:d,viewUp:h}=u;let g,p,v;if(l instanceof lr)throw new Error("Stack Viewport Not implemented");{const _=this.getTargetId(l);v=sc(_),p=Le.getVolume(v),g=qc(p,s,d)}const y=Au(p,d),m=this._getStartCoordinate(s,y,d),w=this._getEndCoordinate(s,y,d),x=l.getFrameOfReferenceUID(),C={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...d],viewUp:[...h],FrameOfReferenceUID:x,referencedImageId:g,volumeId:v,spacingInNormal:y,enabledElement:c},data:{label:"",startCoordinate:m,endCoordinate:w,handles:{textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},points:[[...s],[...s]],activeHandleIndex:null},cachedStats:{pointsInVolume:[],projectionPoints:[],statistics:[]},labelmapUID:null}};this._computeProjectionPoints(C,p),nn(C,a);const S=_t(a,this.getToolName());return this.editData={annotation:C,viewportIdsToRender:S,newAnnotation:!0,hasMoved:!1},this._activateDraw(a),Ot(a),n.preventDefault(),Pe(S),C},this._endCallback=n=>{const i=n.detail,{element:o}=i,{annotation:a,viewportIdsToRender:s,newAnnotation:c,hasMoved:l}=this.editData,{data:f}=a;if(c&&!l)return;a.highlighted=!1,f.handles.activeHandleIndex=null,this._deactivateModify(o),this._deactivateDraw(o),zt(o);const u=Ce(o);this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(a.annotationUID);const d=this.getTargetId(u.viewport),h=Le.getVolume(d.split(/volumeId:|\?/)[1]);this._computePointsInsideVolume(a,h,d,u),Pe(s),c?Nn(a):tn(a,o)},this.renderAnnotation=(n,i)=>{let o=!1;const{viewport:a}=n;let s=un(this.getToolName(),a.element);if(!(s!=null&&s.length))return o;s=L5(s,a.getCamera());const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:n.viewport.id};for(let l=0;la.worldToCanvas(ue)),S=C[0],_=du(C),{centerPointRadius:T}=this.configuration,E=x0(C),D=a.getCamera().focalPoint,b=a.getCamera().viewPlaneNormal;let I=g,P=p;Array.isArray(g)&&(I=this._getCoordinateForViewplaneNormal(I,b),d.startCoordinate=I),Array.isArray(p)&&(P=this._getCoordinateForViewplaneNormal(P,b),d.endCoordinate=P);const M=eu(d.startCoordinate),L=eu(d.endCoordinate),V=this._getCoordinateForViewplaneNormal(D,b),G=eu(V);if(GMath.max(M,L))continue;const A=eu((d.startCoordinate+d.endCoordinate)/2);let k=!1;if(G===A&&(k=!0),d.handles.points[0][this._getIndexOfCoordinatesForViewplaneNormal(b)]=A,f.invalidated&&this._throttledCalculateCachedStats(f,n),!a.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),o;let F;if(!Gr(u))continue;!Zr(u)&&!this.editData&&y!==null&&k&&(F=[C[y]]),F&&ir(i,u,"0",F,{color:x});let j=m,Y=w;k?(j=m,Y=[]):Y=[5,5];const re="0";if(No(i,u,re,S,_,{color:x,lineDash:Y,lineWidth:j}),T>0&&_>3*T&&No(i,u,`${re}-center`,S,T,{color:x,lineDash:w,lineWidth:m}),o=!0,this.configuration.showTextBox){const ue=this.getLinkedTextBoxStyle(c,f);if(!ue.visibility){d.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}const ce=this.configuration.getTextLines(d,{metadata:h});if(!ce||ce.length===0)continue;let pe;d.handles.textBox.hasMoved||(pe=na(E),d.handles.textBox.worldPosition=a.canvasToWorld(pe));const Ee=a.worldToCanvas(d.handles.textBox.worldPosition),_e=qi(i,u,"1",ce,Ee,C,{},ue),{x:B,y:O,width:z,height:W}=_e;d.handles.textBox.worldBoundingBox={topLeft:a.canvasToWorld([B,O]),topRight:a.canvasToWorld([B+z,O]),bottomLeft:a.canvasToWorld([B,O+W]),bottomRight:a.canvasToWorld([B+z,O+W])}}}return o},this.configuration.calculatePointsInsideVolume?this._throttledCalculateCachedStats=_o(this._calculateCachedStatsTool,this.configuration.throttleTimeout,{trailing:!0}):this._throttledCalculateCachedStats=gh(this._calculateCachedStatsTool,this.configuration.throttleTimeout)}_computeProjectionPoints(e,r){const{data:n,metadata:i}=e,{viewPlaneNormal:o,spacingInNormal:a}=i,{imageData:s}=r,{startCoordinate:c,endCoordinate:l}=n,{points:f}=n.handles,u=eg(s,f[0]),d=eg(s,f[0]),h=Fa(f),g=Ve();s.indexToWorldVec3(u,g);const p=Ve();s.indexToWorldVec3(d,p),this._getIndexOfCoordinatesForViewplaneNormal(o)==2?(g[2]=c,p[2]=l,h[0][2]=c,h[1][2]=c):this._getIndexOfCoordinatesForViewplaneNormal(o)==0?(g[0]=c,p[0]=l,h[0][0]=c,h[1][0]=c):this._getIndexOfCoordinatesForViewplaneNormal(o)==1&&(g[1]=c,p[1]=l,h[0][1]=c,h[1][1]=c);const v=ki(g,p),y=[];for(let m=0;m{const x=Ve();return Tn(x,w,o,m),Array.from(x)}));n.cachedStats.projectionPoints=y}_computePointsInsideVolume(e,r,n,i){var D,b,I;const{data:o,metadata:a}=e,{viewPlaneNormal:s,viewUp:c}=a,{viewport:l}=i,f=o.cachedStats.projectionPoints,u=[[]],d=this.getTargetImageData(n),h=o.handles.points.map(P=>l.worldToCanvas(P)),[g,p]=x0(h),v=l.canvasToWorld(g),y=l.canvasToWorld(p),{worldWidth:m,worldHeight:w}=mh(s,c,v,y),x=ta(d,o.handles),C=I4(d),S=Math.abs(Math.PI*(m/x.scale/2)*(w/C/x.scale/2)),_={isPreScaled:al(l,n),isSuvScaled:this.isSuvScaled(l,n,e.metadata.referencedImageId)},T=sl(a.Modality,e.metadata.referencedImageId,_);for(let P=0;Pl.worldToCanvas(_e)),[V,G]=x0(L),A=l.canvasToWorld(V),k=l.canvasToWorld(G),F=A,j=k,{dimensions:Y,imageData:re,voxelManager:ue}=r,ce=eg(re,F),pe=eg(re,M),Ee=this._getIndexOfCoordinatesForViewplaneNormal(s);ce[0]=Math.floor(ce[0]),ce[1]=Math.floor(ce[1]),ce[2]=Math.floor(ce[2]),ce[Ee]=pe[Ee];const Oe=eg(re,j);if(Oe[0]=Math.floor(Oe[0]),Oe[1]=Math.floor(Oe[1]),Oe[2]=Math.floor(Oe[2]),Oe[Ee]=pe[Ee],this._isInsideVolume(ce,Oe,Y)){const _e=Math.min(ce[0],Oe[0]),B=Math.max(ce[0],Oe[0]),O=Math.min(ce[1],Oe[1]),z=Math.max(ce[1],Oe[1]),W=Math.min(ce[2],Oe[2]),K=Math.max(ce[2],Oe[2]),Z=[[_e,B],[O,z],[W,K]],xe={center:M,xRadius:Math.abs(A[0]-k[0])/2,yRadius:Math.abs(A[1]-k[1])/2,zRadius:Math.abs(A[2]-k[2])/2},De=ue.forEach(this.configuration.statsCalculator.statsCallback,{isInObject:Ne=>T5(xe,Ne),boundsIJK:Z,imageData:re,returnPoints:this.configuration.storePointData});u.push(De)}}const E=this.configuration.statsCalculator.getStatistics();o.cachedStats.pointsInVolume=u,o.cachedStats.statistics={Modality:a.Modality,area:S,mean:(D=E.mean)==null?void 0:D.value,stdDev:(b=E.stdDev)==null?void 0:b.value,max:(I=E.max)==null?void 0:I.value,statsArray:E.array,areaUnit:x.areaUnit,modalityUnit:T}}_calculateCachedStatsTool(e,r){const n=e.data,{viewport:i}=r,{cachedStats:o}=n,a=this.getTargetId(i),s=Le.getVolume(a.split(/volumeId:|\?/)[1]);return this._computeProjectionPoints(e,s),this._computePointsInsideVolume(e,s,a,r),e.invalidated=!1,tn(e,i.element),o}_getStartCoordinate(e,r,n){const i=this.configuration.numSlicesToPropagate,o=Math.round(i/2),a=Ve();return Tn(a,e,n,o*-r),this._getCoordinateForViewplaneNormal(a,n)}_getEndCoordinate(e,r,n){const i=this.configuration.numSlicesToPropagate,o=i-Math.round(i/2),a=Ve();return Tn(a,e,n,o*r),this._getCoordinateForViewplaneNormal(a,n)}_getIndexOfCoordinatesForViewplaneNormal(e){const r=[Math.abs(e[0]),Math.abs(e[1]),Math.abs(e[2])];return r.indexOf(Math.max(...r))}_getCoordinateForViewplaneNormal(e,r){const n=this._getIndexOfCoordinatesForViewplaneNormal(r);return e[n]}}function $5e(t,e={}){const r=t.cachedStats.statistics,{area:n,mean:i,max:o,stdDev:a,areaUnit:s,modalityUnit:c}=r;if(i===void 0)return;const l=[];return l.push(`Area: ${an(n)} ${s}`),l.push(`Mean: ${an(i)} ${c}`),l.push(`Max: ${an(o)} ${c}`),l.push(`Std Dev: ${an(a)} ${c}`),l}aB.toolName="CircleROIStartEndThreshold";const{transformWorldToIndex:hb,isEqual:C3}=Mn;class sB extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"]}){super(e,r),this.preMouseDownCallback=n=>{const i=n.detail,{currentPoints:o,element:a}=i,s=o.world,c=Ce(a),{viewport:l}=c,f=l.getCamera(),{viewPlaneNormal:u}=f,d=ol(l.id);if(!d)throw new Error("No active segmentation detected, create one before using scissors tool");const{segmentationId:h}=d,g=ea(h),p=dd(h),{representationData:v}=Ln(h);let y,m,w,x;if(this.doneEditMemo(),l instanceof Ir){const{volumeId:L}=v[Dt.Labelmap],V=Le.getVolume(L);({dimensions:y,direction:m}=V),x=V.voxelManager,w=hb(V.imageData,s)}else{const L=Vu(l.id,h);if(!L)throw new Error("No active segmentation imageId detected, create one before using scissors tool");const{imageData:V}=l.getImageData();y=V.getDimensions(),m=V.getDirection(),x=Le.getImage(L).voxelManager,w=hb(V,s)}const C=this.getFixedDimension(u,m);if(C===void 0){console.warn("Oblique paint fill not yet supported");return}const{floodFillGetter:S,getLabelValue:_,getScalarDataPositionFromPlane:T,inPlaneSeedPoint:E,fixedDimensionValue:D}=this.generateHelpers(x,y,w,C);if(w[0]<0||w[0]>=y[0]||w[1]<0||w[1]>=y[1]||w[2]<0||w[2]>=y[2])return;const b=_(w[0],w[1],w[2]);if(p.includes(b))return;const I=$4(S,E),{flooded:P}=I;P.forEach(L=>{const V=T(L[0],L[1]);x.setAtIndex(V,g)});const M=this.getFramesModified(C,D,I);return io(h,M),!0},this.getFramesModified=(n,i,o)=>{const{flooded:a}=o;if(n===2)return[i];let s=1/0,c=-1/0;for(let f=0;fc&&(c=u)}const l=[];for(let f=s;f<=c;f++)l.push(f);return l},this.generateHelpers=(n,i,o,a=2)=>{let s,c;switch(a){case 0:s=o[0],c=[o[1],o[2]];break;case 1:s=o[1],c=[o[0],o[2]];break;case 2:s=o[2],c=[o[0],o[1]];break;default:throw new Error(`Invalid fixedDimension: ${a}`)}const l=(h,g,p)=>n.toIndex([h,g,p]),f=(h,g,p)=>n.getAtIJK(h,g,p),u=this.generateFloodFillGetter(i,a,s,f);return{getScalarDataPositionFromPlane:this.generateGetScalarDataPositionFromPlane(l,a,s),getLabelValue:f,floodFillGetter:u,inPlaneSeedPoint:c,fixedDimensionValue:s}},this.generateFloodFillGetter=(n,i,o,a)=>{let s;switch(i){case 0:s=(c,l)=>{if(!(c>=n[1]||c<0||l>=n[2]||l<0))return a(o,c,l)};break;case 1:s=(c,l)=>{if(!(c>=n[0]||c<0||l>=n[2]||l<0))return a(c,o,l)};break;case 2:s=(c,l)=>{if(!(c>=n[0]||c<0||l>=n[1]||l<0))return a(c,l,o)};break;default:throw new Error(`Invalid fixedDimension: ${i}`)}return s},this.generateGetScalarDataPositionFromPlane=(n,i,o)=>{let a;switch(i){case 0:a=(s,c)=>n(o,s,c);break;case 1:a=(s,c)=>n(s,o,c);break;case 2:a=(s,c)=>n(s,c,o);break;default:throw new Error(`Invalid fixedDimension: ${i}`)}return a}}getFixedDimension(e,r){const n=r.slice(0,3),i=r.slice(3,6),o=r.slice(6,9),a=[Math.abs(e[0]),Math.abs(e[1]),Math.abs(e[2])],s=[Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2])];if(C3(a,s))return 0;const c=[Math.abs(i[0]),Math.abs(i[1]),Math.abs(i[2])];if(C3(a,c))return 1;const l=[Math.abs(o[0]),Math.abs(o[1]),Math.abs(o[2])];if(C3(a,l))return 2}}sB.toolName="PaintFill";const j5e={TOP_LEFT:"TOP_LEFT",TOP_RIGHT:"TOP_RIGHT",BOTTOM_LEFT:"BOTTOM_LEFT",BOTTOM_RIGHT:"BOTTOM_RIGHT"};var oE={Corners:j5e};const{vtkErrorMacro:S3}=ne,{Corners:Hm}=oE;function H5e(t,e){e.classHierarchy.push("vtkOrientationMarkerWidget");const r={...t},n=[],i=PR.newInstance(),o=new ResizeObserver(d=>{t.updateViewport()});let a=null,s=null,c=null,l=null,f=null;function u(){e._interactor.isAnimating()||t.updateMarkerOrientation()}e._onParentRendererChanged=()=>t.updateViewport(),t.computeViewport=()=>{const d=e.parentRenderer||e._interactor.getCurrentRenderer(),[h,g,p,v]=d.getViewport(),y=e._interactor.getView(),m=y.getSize(),[w,x]=y.getViewportSize(d),C=Math.min(w,x);let S=e.viewportSize*C;S=Math.max(Math.min(e.minPixelSize,C),Math.min(e.maxPixelSize,S));const _=S/m[0],T=S/m[1];switch(e.viewportCorner){case Hm.TOP_LEFT:return[h,v-T,h+_,v];case Hm.TOP_RIGHT:return[p-_,v-T,p,v];case Hm.BOTTOM_LEFT:return[h,g,h+_,g+T];case Hm.BOTTOM_RIGHT:return[p-_,g,p,g+T];default:return S3("Invalid widget corner"),null}},t.updateViewport=()=>{e.enabled&&(i.setViewport(...t.computeViewport()),e._interactor.render())},t.updateMarkerOrientation=()=>{const h=(e.parentRenderer||e._interactor.getCurrentRenderer()).getActiveCamera();if(!h)return;const g=h.getReferenceByName("position"),p=h.getReferenceByName("focalPoint"),v=h.getReferenceByName("viewUp");if(n[0]!==g[0]||n[1]!==g[1]||n[2]!==g[2]||n[3]!==p[0]||n[4]!==p[1]||n[5]!==p[2]||n[6]!==v[0]||n[7]!==v[1]||n[8]!==v[2]){n[0]=g[0],n[1]=g[1],n[2]=g[2],n[3]=p[0],n[4]=p[1],n[5]=p[2],n[6]=v[0],n[7]=v[1],n[8]=v[2];const y=i.getActiveCamera();y.setPosition(g[0],g[1],g[2]),y.setFocalPoint(p[0],p[1],p[2]),y.setViewUp(v[0],v[1],v[2]),i.resetCamera()}},t.setEnabled=d=>{var h,g;if(d){if(e.enabled)return;if(!e.actor){S3("Must set actor before enabling orientation marker.");return}if(!e._interactor){S3("Must set interactor before enabling orientation marker.");return}const p=e.parentRenderer||e._interactor.getCurrentRenderer(),v=p.getRenderWindow();v.addRenderer(i),v.getNumberOfLayers()<2&&v.setNumberOfLayers(2),i.setLayer(v.getNumberOfLayers()-1),i.setInteractive(e.interactiveRenderer),i.addViewProp(e.actor),e.actor.setVisibility(!0),a=p.onEvent(y=>{y.type==="ActiveCameraEvent"&&(s&&s.unsubscribe(),s=y.camera.onModified(u))}),s=p.getActiveCamera().onModified(u),c=e._interactor.onAnimation(t.updateMarkerOrientation),l=e._interactor.onEndAnimation(t.updateMarkerOrientation),o.observe(e._interactor.getView().getCanvas()),t.updateViewport(),t.updateMarkerOrientation(),e.enabled=!0}else{if(!e.enabled)return;e.enabled=!1,o.disconnect(),a.unsubscribe(),a=null,s.unsubscribe(),s=null,c.unsubscribe(),c=null,l.unsubscribe(),l=null,e.actor.setVisibility(!1),i.removeViewProp(e.actor);const p=(g=(h=e._interactor)==null?void 0:h.findPokedRenderer())==null?void 0:g.getRenderWindow();p&&p.removeRenderer(i)}t.modified()},t.setViewportCorner=d=>{d!==e.viewportCorner&&(e.viewportCorner=d,t.updateViewport())},t.setViewportSize=d=>{const h=Math.min(1,Math.max(0,d));h!==e.viewportSize&&(e.viewportSize=h,t.updateViewport())},t.setActor=d=>{const h=e.enabled;t.setEnabled(!1),e.actor=d,t.setEnabled(h)},t.getRenderer=()=>i,t.delete=()=>{r.delete(),f&&(f.unsubscribe(),f=null),a&&(a.unsubscribe(),a=null),s&&(s.unsubscribe(),s=null),c&&(c.unsubscribe(),c=null),l&&(l.unsubscribe(),l=null),o.disconnect()},f=t.onModified(t.updateViewport)}const K5e={viewportCorner:oE.Corners.BOTTOM_LEFT,viewportSize:.2,minPixelSize:50,maxPixelSize:200,parentRenderer:null,interactiveRenderer:!1};function cB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,K5e,r),ne.obj(t,e),ne.get(t,e,["enabled","viewportCorner","viewportSize","interactiveRenderer"]),ne.setGet(t,e,["_interactor","minPixelSize","maxPixelSize","parentRenderer"]),ne.get(t,e,["actor"]),ne.moveToProtected(t,e,["interactor"]),H5e(t,e)}const q5e=ne.newInstance(cB,"vtkOrientationMarkerWidget");var gb={newInstance:q5e,extend:cB,...oE};function lB(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[0,0,0,0];const[r,n,i,o]=e,s=t.getContext("2d").getImageData(r,n,i||t.width,o||t.height),c=h1.newInstance({type:"vtkImageData"});c.setOrigin(0,0,0),c.setSpacing(1,1,1),c.setExtent(0,(i||t.width)-1,0,(o||t.height)-1,0,0);const l=Yt.newInstance({numberOfComponents:4,values:new Uint8Array(s.data.buffer)});return l.setName("scalars"),c.getPointData().setScalars(l),c}function X5e(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{flipX:!1,flipY:!1,rotate:0};const r=document.createElement("canvas");r.width=t.width,r.height=t.height;const n=r.getContext("2d"),{flipX:i,flipY:o,rotate:a}=e;return n.translate(r.width/2,r.height/2),n.scale(i?-1:1,o?-1:1),n.rotate(a*Math.PI/180),n.drawImage(t,-t.width/2,-t.height/2),lB(r)}var Y5e={canvasToImageData:lB,imageToImageData:X5e};const uB={default:{defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:t=>t/2,faceColor:"white",edgeThickness:.1,edgeColor:"black",resolution:400},xMinusFaceProperty:{text:"X-",faceColor:"yellow"},xPlusFaceProperty:{text:"X+",faceColor:"yellow"},yMinusFaceProperty:{text:"Y-",faceColor:"red"},yPlusFaceProperty:{text:"Y+",faceColor:"red"},zMinusFaceProperty:{text:"Z-",faceColor:"#008000"},zPlusFaceProperty:{text:"Z+",faceColor:"#008000"}},lps:{xMinusFaceProperty:{text:"R",faceRotation:-90},xPlusFaceProperty:{text:"L",faceRotation:90},yMinusFaceProperty:{text:"A",faceRotation:0},yPlusFaceProperty:{text:"P",faceRotation:180},zMinusFaceProperty:{text:"I",faceRotation:180},zPlusFaceProperty:{text:"S",faceRotation:0}}};function fB(t,e){e.set(t)}function J5e(t,e){return fB(uB[t],e)}function Z5e(t,e){uB[t]=e}var Q5e={applyDefinitions:fB,applyPreset:J5e,registerStylePreset:Z5e};const ewe={xPlus:0,xMinus:1,yPlus:2,yMinus:3,zPlus:4,zMinus:5};function twe(t,e){e.classHierarchy.push("vtkAnnotatedCubeActor"),e.xPlusFaceProperty={...e.xPlusFaceProperty},e.xMinusFaceProperty={...e.xMinusFaceProperty},e.yPlusFaceProperty={...e.yPlusFaceProperty},e.yMinusFaceProperty={...e.yMinusFaceProperty},e.zPlusFaceProperty={...e.zPlusFaceProperty},e.zMinusFaceProperty={...e.zMinusFaceProperty};let r=null;const n=document.createElement("canvas"),i=g1.newInstance(),o=Ace.newInstance();o.setInterpolate(!0);function a(c){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;l&&Object.assign(e[`${c}FaceProperty`],l);const f={...e.defaultStyle,...e[`${c}FaceProperty`]};n.width=f.resolution,n.height=f.resolution;const u=n.getContext("2d");u.fillStyle=f.faceColor,u.fillRect(0,0,n.width,n.height),f.edgeThickness>0&&(u.strokeStyle=f.edgeColor,u.lineWidth=f.edgeThickness*n.width,u.strokeRect(0,0,n.width,n.height)),u.save(),u.translate(0,n.height),u.scale(1,-1),u.translate(n.width/2,n.height/2),u.rotate(-Math.PI*(f.faceRotation/180));const d=f.fontSizeScale(f.resolution);u.fillStyle=f.fontColor,u.textAlign="center",u.textBaseline="middle",u.font=`${f.fontStyle} ${d}px "${f.fontFamily}"`,u.fillText(f.text,0,0),u.restore();const h=Y5e.canvasToImageData(n);o.setInputData(h,ewe[c]),t.modified()}function s(){r=xL.newInstance({generate3DTextureCoordinates:!0}),i.setInputConnection(r.getOutputPort()),a("xPlus"),a("xMinus"),a("yPlus"),a("yMinus"),a("zPlus"),a("zMinus")}t.setDefaultStyle=c=>{e.defaultStyle={...e.defaultStyle,...c},s()},t.setXPlusFaceProperty=c=>a("xPlus",c),t.setXMinusFaceProperty=c=>a("xMinus",c),t.setYPlusFaceProperty=c=>a("yPlus",c),t.setYMinusFaceProperty=c=>a("yMinus",c),t.setZPlusFaceProperty=c=>a("zPlus",c),t.setZMinusFaceProperty=c=>a("zMinus",c),s(),i.setInputConnection(r.getOutputPort()),t.setMapper(i),t.addTexture(o)}const nwe={defaultStyle:{text:"",faceColor:"white",faceRotation:0,fontFamily:"Arial",fontColor:"black",fontStyle:"normal",fontSizeScale:t=>t/1.8,edgeThickness:.1,edgeColor:"black",resolution:200}};function dB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,nwe,r),Qy.extend(t,e,r),ne.get(t,e,["defaultStyle","xPlusFaceProperty","xMinusFaceProperty","yPlusFaceProperty","yMinusFaceProperty","zPlusFaceProperty","zMinusFaceProperty"]),twe(t,e)}const rwe=ne.newInstance(dB,"vtkAnnotatedCubeActor");var pb={newInstance:rwe,extend:dB,Presets:Q5e};const{vtkErrorMacro:iwe}=ne;function owe(t,e){let r=0;return t.map((n,i)=>i===r?(r+=n+1,n):n+e)}function Km(t,e,r,n){t.set(owe(e,r),n)}function awe(t,e){e.classHierarchy.push("vtkAppendPolyData"),t.requestData=(r,n)=>{const i=t.getNumberOfInputPorts();if(!i){iwe("No input specified.");return}if(i===1){n[0]=r[0];return}const o=Xo.newInstance();let a=0,s=0,c=1,l=1,f=0,u=0,d=0,h=0,g=!0,p=!0,v=!0;for(let b=0;bc?s:c);const M=I.getPointData();M?(g=g&&M.getNormals()!==null,p=p&&M.getTCoords()!==null,v=v&&M.getScalars()!==null):(g=!1,p=!1,v=!1)}e.outputPointsPrecision===Cv.SINGLE?s=pn.FLOAT:e.outputPointsPrecision===Cv.DOUBLE&&(s=pn.DOUBLE);const y=Pv.newInstance({dataType:s});y.setNumberOfPoints(a);const m=y.getData(),w=new Uint32Array(f),x=new Uint32Array(u),C=new Uint32Array(d),S=new Uint32Array(h);let _=null,T=null,E=null;const D=r[i-1];if(g){const b=D.getPointData().getNormals();_=Yt.newInstance({numberOfComponents:3,numberOfTuples:a,size:3*a,dataType:b.getDataType(),name:b.getName()})}if(p){const b=D.getPointData().getTCoords();T=Yt.newInstance({numberOfComponents:2,numberOfTuples:a,size:2*a,dataType:b.getDataType(),name:b.getName()})}if(v){const b=D.getPointData().getScalars();E=Yt.newInstance({numberOfComponents:b.getNumberOfComponents(),numberOfTuples:a,size:a*b.getNumberOfComponents(),dataType:b.getDataType(),name:b.getName()})}a=0,f=0,u=0,d=0,h=0;for(let b=0;b2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,swe,r),ne.setGet(t,e,["outputPointsPrecision"]),ne.obj(t,e),ne.algo(t,e,1,1),awe(t,e)}const cwe=ne.newInstance(hB,"vtkAppendPolyData");var gB={newInstance:cwe,extend:hB};function lwe(t,e){e.classHierarchy.push("vtkConeSource");function r(n,i){if(e.deleted)return;let o=i[0];const a=2*Math.PI/e.resolution,s=-e.height/2,c=e.resolution+1,l=4*e.resolution+1+e.resolution;let f=0;const u=ne.newTypedArray(e.pointType,c*3);let d=0;const h=new Uint32Array(l);u[0]=e.height/2,u[1]=0,u[2]=0,e.capping&&(h[d++]=e.resolution);for(let g=0;ge.resolution?1:g+2;ji.buildFromRadian().translate(...e.center).rotateFromDirections([1,0,0],e.direction).apply(u),o=Xo.newInstance(),o.getPoints().setData(u,3),o.getPolys().setData(h,1),i[0]=o}t.requestData=r}const uwe={height:1,radius:.5,resolution:6,center:[0,0,0],direction:[1,0,0],capping:!0,pointType:"Float64Array"};function pB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,uwe,r),ne.obj(t,e),ne.setGet(t,e,["height","radius","resolution","capping"]),ne.setGetArray(t,e,["center","direction"],3),ne.algo(t,e,0,1),lwe(t,e)}const fwe=ne.newInstance(pB,"vtkConeSource");var dwe={newInstance:fwe,extend:pB};function hwe(t,e){e.classHierarchy.push("vtkCylinderSource");function r(n,i){if(e.deleted)return;let o=i[0];const a=2*Math.PI/e.resolution;let s=2*e.resolution,c=5*e.resolution;e.capping&&(s=4*e.resolution,c=7*e.resolution+2);const l=ne.newTypedArray(e.pointType,s*3);let f=0;const u=new Uint32Array(c),d=new Float32Array(s*3),h=Yt.newInstance({numberOfComponents:3,values:d,name:"Normals"}),g=new Float32Array(s*2),p=Yt.newInstance({numberOfComponents:2,values:g,name:"TCoords"}),v=[0,0,0],y=[0,0,0],m=[0,0,0],w=[0,0,0],x=[0,0],C=[0,0],S=e.otherRadius==null?e.radius:e.otherRadius;for(let _=0;__*-1)).apply(l),o=Xo.newInstance(),o.getPoints().setData(l,3),o.getPolys().setData(u,1),o.getPointData().setNormals(h),o.getPointData().setTCoords(p),i[0]=o}t.requestData=r}const gwe={height:1,initAngle:0,radius:1,resolution:6,center:[0,0,0],direction:[0,1,0],capping:!0,pointType:"Float64Array"};function mB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,gwe,r),ne.obj(t,e),ne.setGet(t,e,["height","initAngle","otherRadius","radius","resolution","capping"]),ne.setGetArray(t,e,["center","direction"],3),ne.algo(t,e,0,1),hwe(t,e)}const pwe=ne.newInstance(mB,"vtkCylinderSource");var mwe={newInstance:pwe,extend:mB};function vwe(t,e){e.classHierarchy.push("vtkArrowSource");function r(n,i){if(e.deleted)return;const o=mwe.newInstance({capping:!0});o.setResolution(e.shaftResolution),o.setRadius(e.shaftRadius),o.setHeight(1-e.tipLength),o.setCenter(0,(1-e.tipLength)*.5,0);const a=o.getOutputData(),s=a.getPoints().getData(),c=a.getPointData().getNormals().getData();ji.buildFromDegree().rotateZ(-90).apply(s).apply(c);const l=dwe.newInstance();l.setResolution(e.tipResolution),l.setHeight(e.tipLength),l.setRadius(e.tipRadius);const f=l.getOutputData(),u=f.getPoints().getData();ji.buildFromRadian().translate(1-e.tipLength*.5,0,0).apply(u);const d=gB.newInstance();d.setInputData(a),d.addInputData(f);const h=d.getOutputData(),g=h.getPoints().getData();ji.buildFromRadian().translate(-.5+e.tipLength*.5,0,0).apply(g),e.invert?(ji.buildFromRadian().rotateFromDirections([1,0,0],e.direction).scale(-1,-1,-1).apply(g),i[0]=h):(ji.buildFromRadian().rotateFromDirections([1,0,0],e.direction).scale(1,1,1).apply(g),i[0]=d.getOutputData())}t.requestData=r}const ywe={tipResolution:6,tipRadius:.1,tipLength:.35,shaftResolution:6,shaftRadius:.03,invert:!1,direction:[1,0,0],pointType:"Float64Array"};function vB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Object.assign(e,ywe,r),ne.obj(t,e),ne.setGet(t,e,["tipResolution","tipRadius","tipLength","shaftResolution","shaftRadius","invert"]),ne.setGetArray(t,e,["direction"],3),ne.algo(t,e,0,1),vwe(t,e)}const wwe=ne.newInstance(vB,"vtkArrowSource");var _3={newInstance:wwe,extend:vB};function T3(t){const e=t.getPoints().getBounds(),r=[-(e[0]+e[1])*.5,-(e[2]+e[3])*.5,-(e[4]+e[5])*.5];ji.buildFromDegree().translate(...r).apply(t.getPoints().getData())}function E3(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=t.getPoints().getBounds(),i=[0,0,0];r?i[e]=-n[e*2+1]:i[e]=-n[e*2],ji.buildFromDegree().translate(...i).apply(t.getPoints().getData())}function D3(t,e,r,n){const i=t.getPoints().getData().length,o=new Uint8ClampedArray(i);let a=0;for(;a{let i={...e.config,...e.xConfig};const o=_3.newInstance({direction:[1,0,0],...i}).getOutputData();e.config.recenter?T3(o):E3(o,0,i.invert),D3(o,...i.color),i={...e.config,...e.yConfig};const a=_3.newInstance({direction:[0,1,0],...i}).getOutputData();e.config.recenter?T3(a):E3(a,1,i.invert),D3(a,...i.color),i={...e.config,...e.zConfig};const s=_3.newInstance({direction:[0,0,1],...i}).getOutputData();e.config.recenter?T3(s):E3(s,2,i.invert),D3(s,...i.color);const c=gB.newInstance();c.setInputData(o),c.addInputData(a),c.addInputData(s),r.setInputConnection(c.getOutputPort())},t.update();const n=ne.debounce(t.update,0);t.setXAxisColor=i=>t.setXConfig({...t.getXConfig(),color:i}),t.setYAxisColor=i=>t.setYConfig({...t.getYConfig(),color:i}),t.setZAxisColor=i=>t.setZConfig({...t.getZConfig(),color:i}),t.getXAxisColor=()=>e.getXConfig().color,t.getYAxisColor=()=>e.getYConfig().color,t.getZAxisColor=()=>e.getZConfig().color,e._onConfigChanged=n,e._onXConfigChanged=n,e._onYConfigChanged=n,e._onZConfigChanged=n}function Cwe(t){return{config:{recenter:!0,tipResolution:60,tipRadius:.1,tipLength:.2,shaftResolution:60,shaftRadius:.03,invert:!1,...t==null?void 0:t.config},xConfig:{color:[255,0,0],invert:!1,...t==null?void 0:t.xConfig},yConfig:{color:[255,255,0],invert:!1,...t==null?void 0:t.yConfig},zConfig:{color:[0,128,0],invert:!1,...t==null?void 0:t.zConfig}}}function yB(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Qy.extend(t,e,Cwe(r)),ne.setGet(t,e,["config","xConfig","yConfig","zConfig"]),xwe(t,e)}const Swe=ne.newInstance(yB,"vtkAxesActor");var _we={newInstance:Swe,extend:yB},wy;(function(t){t[t.ANNOTATED_CUBE=1]="ANNOTATED_CUBE",t[t.AXES=2]="AXES",t[t.CUSTOM=3]="CUSTOM"})(wy||(wy={}));const ks=class ks extends ai{constructor(e={},r={configuration:{orientationWidget:{enabled:!0,viewportCorner:gb.Corners.BOTTOM_RIGHT,viewportSize:.15,minPixelSize:100,maxPixelSize:300},overlayMarkerType:ks.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE,overlayConfiguration:{[ks.OVERLAY_MARKER_TYPES.ANNOTATED_CUBE]:{faceProperties:{xPlus:{text:"L",faceColor:"#ffff00",faceRotation:90},xMinus:{text:"R",faceColor:"#ffff00",faceRotation:270},yPlus:{text:"P",faceColor:"#00ffff",fontColor:"white",faceRotation:180},yMinus:{text:"A",faceColor:"#00ffff",fontColor:"white"},zPlus:{text:"S"},zMinus:{text:"I"}},defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:n=>n/2,faceColor:"#0000ff",edgeThickness:.1,edgeColor:"black",resolution:400}},[ks.OVERLAY_MARKER_TYPES.AXES]:{},[ks.OVERLAY_MARKER_TYPES.CUSTOM]:{polyDataURL:"https://raw.githubusercontent.com/Slicer/Slicer/80ad0a04dacf134754459557bf2638c63f3d1d1b/Base/Logic/Resources/OrientationMarkers/Human.vtp"}}}}){super(e,r),this._resizeObservers=new Map,this.onSetToolEnabled=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolActive=()=>{this.initViewports(),this._subscribeToViewportEvents()},this.onSetToolDisabled=()=>{this.cleanUpData(),this._unsubscribeToViewportNewVolumeSet()},this._getViewportsInfo=()=>Kr(this.toolGroupId).viewportsInfo,this.resize=n=>{const i=this.orientationMarkers[n];if(!i)return;const{orientationWidget:o}=i;o.updateViewport()},this.orientationMarkers={},this.updatingOrientationMarker={}}_unsubscribeToViewportNewVolumeSet(){const e=()=>{this._getViewportsInfo().forEach(({viewportId:n,renderingEngineId:i})=>{const{viewport:o}=Ti(n,i),{element:a}=o;a.removeEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this)),this._resizeObservers.get(n).unobserve(a)})};Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,r=>{r.detail.toolGroupId===this.toolGroupId&&(e(),this.initViewports())})}_subscribeToViewportEvents(){const e=()=>{this._getViewportsInfo().forEach(({viewportId:n,renderingEngineId:i})=>{const{viewport:o}=Ti(n,i),{element:a}=o;this.initViewports(),a.addEventListener(Xe.VOLUME_VIEWPORT_NEW_VOLUME,this.initViewports.bind(this));const s=new ResizeObserver(()=>{setTimeout(()=>{const c=Ti(n,i);if(!c)return;const{viewport:l}=c;this.resize(n),l.render()},100)});s.observe(a),this._resizeObservers.set(n,s)})};e(),Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,r=>{r.detail.toolGroupId===this.toolGroupId&&(e(),this.initViewports())})}cleanUpData(){Qo()[0].getViewports().forEach(i=>{const o=this.orientationMarkers[i.id];if(!o)return;const{actor:a,orientationWidget:s}=o;s==null||s.setEnabled(!1),s==null||s.delete(),a==null||a.delete(),i.getRenderingEngine().offscreenMultiRenderWindow.getRenderWindow().render(),i.getRenderingEngine().render(),delete this.orientationMarkers[i.id]})}initViewports(){const r=Qo()[0];if(!r)return;let n=r.getViewports();n=b5(n,this.getToolName()),n.forEach(i=>{const o=i.getWidget(this.getToolName());(!o||o.isDeleted())&&this.addAxisActorInViewport(i)})}async addAxisActorInViewport(e){const r=e.id;if(!this.updatingOrientationMarker[r]){this.updatingOrientationMarker[r]=!0;const n=this.configuration.overlayMarkerType,i=this.configuration.overlayConfiguration[n];if(this.orientationMarkers[r]){const{actor:g,orientationWidget:p}=this.orientationMarkers[r];e.getRenderer().removeActor(g),p.setEnabled(!1)}let o;n===1?o=this.createAnnotationCube(i):n===2?o=_we.newInstance():n===3&&(o=await this.createCustomActor());const a=e.getRenderer(),s=e.getRenderingEngine().offscreenMultiRenderWindow.getRenderWindow(),{enabled:c,viewportCorner:l,viewportSize:f,minPixelSize:u,maxPixelSize:d}=this.configuration.orientationWidget,h=gb.newInstance({actor:o,interactor:s.getInteractor(),parentRenderer:a});h.setEnabled(c),h.setViewportCorner(l),h.setViewportSize(f),h.setMinPixelSize(u),h.setMaxPixelSize(d),h.updateMarkerOrientation(),this.orientationMarkers[r]={orientationWidget:h,actor:o},e.addWidget(this.getToolName(),h),s.render(),e.getRenderingEngine().render(),this.updatingOrientationMarker[r]=!1}}async createCustomActor(){const e=this.configuration.overlayConfiguration[wy.CUSTOM].polyDataURL,n=await(await fetch(e)).arrayBuffer(),i=Lse.newInstance();i.parseAsArrayBuffer(n),i.update();const o=Xo.newInstance();o.shallowCopy(i.getOutputData()),o.getPointData().setActiveScalars("Color");const a=g1.newInstance();a.setInputData(o),a.setColorModeToDirectScalars();const s=Qy.newInstance();return s.setMapper(a),s.rotateZ(180),s}createAnnotationCube(e){const r=pb.newInstance();return r.setDefaultStyle({...e.defaultStyle}),r.setXPlusFaceProperty({...e.faceProperties.xPlus}),r.setXMinusFaceProperty({...e.faceProperties.xMinus}),r.setYPlusFaceProperty({...e.faceProperties.yPlus}),r.setYMinusFaceProperty({...e.faceProperties.yMinus}),r.setZPlusFaceProperty({...e.faceProperties.zPlus}),r.setZMinusFaceProperty({...e.faceProperties.zMinus}),r}async createAnnotatedCubeActor(){const e=pb.newInstance(),{faceProperties:r,defaultStyle:n}=this.configuration.annotatedCube;return e.setDefaultStyle(n),Object.keys(r).forEach(i=>{const o=`set${i.charAt(0).toUpperCase()+i.slice(1)}FaceProperty`;e[o](r[i])}),e}};ks.CUBE=1,ks.AXIS=2,ks.VTPFILE=3,ks.OVERLAY_MARKER_TYPES=wy;let xy=ks;xy.toolName="OrientationMarker";const op=class op extends ai{constructor(e={},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{hoverTimeout:100,mode:op.SelectMode.Border,searchRadius:6}}){super(e,r),this.mouseMoveCallback=n=>{if(this.mode===An.Active)return this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setActiveSegment(n),this.hoverTimer=null},this.configuration.hoverTimeout),!0},this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.hoverTimer=null}_setActiveSegment(e={}){if(Be.isInteractingWithTool)return;const{element:r,currentPoints:n}=e.detail,i=n.world,o=Ce(r);if(!o)return;const{viewport:a}=o,s=ol(a.id);s&&this._setActiveSegmentForType(s,i,a)}_setActiveSegmentForType(e,r,n){if(!n.getImageData())return;const{segmentationId:o,representationData:a}=e;let s;if(this.configuration.mode===op.SelectMode.Inside?s=H4(o,r,{viewport:n}):a.Labelmap?s=tU(o,r,{viewport:n,searchRadius:this.configuration.searchRadius}):a.Contour?s=rU(o):a.Surface,!s||s===0)return;dy(o,s);const l=n.getRenderingEngine().getViewports().map(f=>f.id);Ta(o),Pe(l)}};op.SelectMode={Inside:"Inside",Border:"Border"};let Cy=op;Cy.toolName="SegmentSelectTool";const s0=class s0 extends Hp{constructor(e={}){super(e),this.renderAnnotation=(r,n)=>{let i=!0;const{viewport:o}=r,{element:a}=o,s=o.id;let c=un(this.getToolName(),a);if(!(c!=null&&c.length)||(c=this.filterInteractableAnnotationsForElement(a,c),!(c!=null&&c.length)))return i;const l=this.getTargetId(o),f=o.getRenderingEngine(),u={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:r.viewport.id};for(let d=0;do.worldToCanvas(ce));u.annotationUID=g;const{segmentIndex:w,segmentationId:x}=h.metadata,{lineWidth:C,lineDash:S,shadow:_}=this.getAnnotationStyle({annotation:h,styleSpecifier:u}),E=`rgb(${el(s,x,w).slice(0,3).join(",")})`;if(!p.cachedStats[l]||p.cachedStats[l].unit==null?(p.cachedStats[l]={length:null,width:null,unit:null},this._calculateCachedStats(h,f,r)):h.invalidated&&this._throttledCalculateCachedStats(h,f,r),!o.getRenderingEngine())return console.warn("Rendering Engine has been destroyed"),i;let D;if(!Gr(g))continue;!Zr(g)&&!this.editData&&y!==null&&(D=[m[y]]),D&&ir(n,g,"0",D,{color:E});const b=`${g}-line-1`,I=`${g}-line-2`;vn(n,g,"0",m[0],m[1],{color:E,lineWidth:C,lineDash:S,shadow:_},b),vn(n,g,"1",m[2],m[3],{color:E,lineWidth:C,lineDash:S,shadow:_},I),i=!0;const L=this.getLinkedTextBoxStyle(u,h);if(!L.visibility){p.handles.textBox={hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}};continue}L.color=E;const V=this.configuration.getTextLines(p,l);if(!V||V.length===0)continue;let G;p.handles.textBox.hasMoved||(G=na(m),p.handles.textBox.worldPosition=o.canvasToWorld(G));const A=o.worldToCanvas(p.handles.textBox.worldPosition),F=qi(n,g,"1",V,A,m,{},L),{x:j,y:Y,width:re,height:ue}=F;p.handles.textBox.worldBoundingBox={topLeft:o.canvasToWorld([j,Y]),topRight:o.canvasToWorld([j+re,Y]),bottomLeft:o.canvasToWorld([j,Y+ue]),bottomRight:o.canvasToWorld([j+re,Y+ue])}}return i}}addNewAnnotation(e){const r=e.detail,{currentPoints:n,element:i}=r,o=n.world,a=Ce(i),{viewport:s}=a;this.isDrawing=!0;const c=s.getCamera(),{viewPlaneNormal:l,viewUp:f}=c,u=this.getReferencedImageId(s,o,l,f),d=s.getFrameOfReferenceUID(),h={highlighted:!0,invalidated:!0,metadata:{toolName:this.getToolName(),viewPlaneNormal:[...l],viewUp:[...f],FrameOfReferenceUID:d,referencedImageId:u,...s.getViewReference({points:[o]})},data:{handles:{points:[[...o],[...o],[...o],[...o]],textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}},activeHandleIndex:null},label:"",cachedStats:{}}};nn(h,i);const g=_t(i,this.getToolName());return this.editData={annotation:h,viewportIdsToRender:g,handleIndex:1,movingTextBox:!1,newAnnotation:!0,hasMoved:!1},this._activateDraw(i),Ot(i),e.preventDefault(),Pe(g),h}};s0.toolName="SegmentBidirectional",s0.hydrate=(e,r,n)=>{const i=zn(e);if(!i)return;const{viewport:o}=i,c=S1().filter(_=>_.metadata.toolName==="SegmentBidirectional").find(_=>{const{metadata:T}=_;return T.segmentIndex===(n==null?void 0:n.segmentIndex)&&T.segmentationId===(n==null?void 0:n.segmentationId)});c&&gn(c.annotationUID);const{FrameOfReferenceUID:l,referencedImageId:f,viewPlaneNormal:u,instance:d}=s0.hydrateBase(s0,i,r[0],n),[h,g]=r,[p,v]=h,[y,m]=g,w=[p,v,y,m],{toolInstance:x,...C}=n||{},S={annotationUID:(n==null?void 0:n.annotationUID)||Dn(),data:{handles:{points:w,activeHandleIndex:null,textBox:{hasMoved:!1,worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}},cachedStats:{}},highlighted:!1,autoGenerated:!1,invalidated:!1,isLocked:!1,isVisible:!0,metadata:{segmentIndex:n==null?void 0:n.segmentIndex,segmentationId:n==null?void 0:n.segmentationId,toolName:d.getToolName(),viewPlaneNormal:u,FrameOfReferenceUID:l,referencedImageId:f,...C}};return nn(S,o.element),Pe([o.id]),S};let tS=s0;class wB extends ai{constructor(e={data:{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}}},r={supportedInteractionTypes:["Mouse","Touch"],configuration:{hoverTimeout:100,searchRadius:6}}){super(e,r),this.mouseMoveCallback=n=>(this.hoverTimer&&clearTimeout(this.hoverTimer),this.hoverTimer=setTimeout(()=>{this._setHoveredSegment(n),this.hoverTimer=null},this.configuration.hoverTimeout),!0),this.onSetToolEnabled=()=>{this.onSetToolActive()},this.onSetToolActive=()=>{this.hoverTimer=null},this.onSetToolDisabled=()=>{this.hoverTimer=null},this.data=e.data??{handles:{textBox:{worldPosition:[0,0,0],worldBoundingBox:{topLeft:[0,0,0],topRight:[0,0,0],bottomLeft:[0,0,0],bottomRight:[0,0,0]}}}},this.hoverTimer=null}_setHoveredSegment(e={}){if(Be.isInteractingWithTool)return;const{element:r,currentPoints:n}=e.detail,i=n.world,o=Ce(r);if(!o)return;const{viewport:a}=o,s=ol(a.id);s&&this._setHoveredSegmentForType(s,i,a)}_setHoveredSegmentForType(e,r,n){if(!n.getImageData())return;const{segmentationId:o}=e,a=H4(o,r,{viewport:n}),s=e.segments[a],c=s==null?void 0:s.label,l=n.worldToCanvas(r);if(this._editData={hoveredSegmentIndex:a,hoveredSegmentLabel:c,canvasCoordinates:l,worldPoint:r},!a||a===0)return;const u=n.getRenderingEngine().getViewports().map(d=>d.id);Ta(o),Pe(u)}renderAnnotation(e,r){if(!this._editData)return;const{viewport:n}=e,{hoveredSegmentIndex:i,hoveredSegmentLabel:o,canvasCoordinates:a,worldPoint:s}=this._editData;if(!i)return;const c=n.worldToCanvas(s),l=qi(r,"segmentSelectLabelAnnotation","segmentSelectLabelTextBox",[o||"(unnamed segment)"],c,[a],{},{}),f=a[0],u=a[1],{width:d,height:h}=l;this.data.handles.textBox.worldBoundingBox={topLeft:n.canvasToWorld([f,u]),topRight:n.canvasToWorld([f+d,u]),bottomLeft:n.canvasToWorld([f,u+h]),bottomRight:n.canvasToWorld([f+d,u+h])}}}wB.toolName="SegmentLabelTool";const fo=class fo extends ic{constructor(e={}){const r=Ei({configuration:{calculateStats:!1,allowOpenContours:!1}},e);super(r),this.onViewportAddedToToolGroupBinded=this.onViewportAddedToToolGroup.bind(this),this.onSegmentationModifiedBinded=this.onSegmentationModified.bind(this)}initializeListeners(){fo.annotationsToViewportMap.clear(),fo.viewportIdsChecked=[],Ke.addEventListener(N.ANNOTATION_MODIFIED,this.annotationModified),Ke.addEventListener(N.ANNOTATION_COMPLETED,this.annotationCompleted),Ke.addEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroupBinded),Ke.addEventListener(N.SEGMENTATION_MODIFIED,this.onSegmentationModifiedBinded)}cleanUpListeners(){fo.annotationsToViewportMap.clear(),fo.viewportIdsChecked=[],Ke.removeEventListener(N.ANNOTATION_MODIFIED,this.annotationModified),Ke.removeEventListener(N.ANNOTATION_COMPLETED,this.annotationCompleted),Ke.removeEventListener(N.TOOLGROUP_VIEWPORT_ADDED,this.onViewportAddedToToolGroup.bind(this)),Ke.removeEventListener(N.SEGMENTATION_MODIFIED,this.onSegmentationModified.bind(this))}async checkContourSegmentation(e){if(fo.viewportIdsChecked.includes(e))return;const r=ed(e);if(!r)return console.log("No active segmentation detected"),!1;const n=r.segmentationId;return r.representationData.Contour?fo.viewportIdsChecked.push(e):(fo.viewportIdsChecked.push(e),await K4(e,[{segmentationId:n,type:Dt.Contour}]),n4({segmentationId:n,type:Dt.Contour,data:{}})),!0}onViewportAddedToToolGroup(e){const{toolGroupId:r,viewportId:n}=e.detail;r===this.toolGroupId&&this.checkContourSegmentation(n)}onSegmentationModified(e){const{segmentationId:r}=e.detail||{};if(!r)return;const n=sk(r);n&&n.forEach(async({viewportId:i})=>await this.checkContourSegmentation(i))}onSetToolEnabled(){this.initializeListeners()}onSetToolActive(){this.initializeListeners()}onSetToolDisabled(){this.cleanUpListeners()}annotationModified(e){var a;const{annotation:r,renderingEngineId:n,viewportId:i}=e.detail,o=(a=Jr(n))==null?void 0:a.getViewport(i);o&&fo.annotationsToViewportMap.set(r.annotationUID,o)}annotationCompleted(e){var i,o;const{annotation:r}=e.detail,{polyline:n}=((i=r.data)==null?void 0:i.contour)||{};if(((o=r==null?void 0:r.metadata)==null?void 0:o.toolName)===fo.toolName&&n&&fo.annotationsToViewportMap.has(r.annotationUID)){const a=fo.annotationsToViewportMap.get(r.annotationUID);n.length>3&&z5.viewportContoursToLabelmap(a)}}};fo.toolName="LabelMapEditWithContour",fo.annotationsToViewportMap=new Map,fo.viewportIdsChecked=[];let nS=fo;const AE=class AE extends ar{constructor(e={}){super(e,{supportedInteractionTypes:["Mouse","Touch"],configuration:{shadow:!0,preventHandleOutsideImage:!1}}),this.addNewAnnotation=r=>{const n=r.detail,{currentPoints:i,element:o}=n,a=i.world,s=Ce(o),{viewport:c}=s;this.isDrawing=!0;const l=this.constructor.createAnnotationForViewport(c,{data:{handles:{points:[[...a],[...a],[...a],[...a]]}}});nn(l,o);const f=_t(o,this.getToolName(),!1);return this.editData={annotation:l,viewportUIDsToRender:f,handleIndex:3,newAnnotation:!0,hasMoved:!1},this._activateDraw(o),Ot(o),r.preventDefault(),Pe(f),l},this.getHandleNearImagePoint=(r,n,i,o)=>{const a=Ce(r),{viewport:s}=a,{data:c}=n,{points:l}=c.handles;for(let f=0;f{const a=Ce(r),{viewport:s}=a,{data:c}=n,{points:l}=c.handles,f=s.worldToCanvas(l[0]),u=s.worldToCanvas(l[3]),d=this._getRectangleImageCoordinates([f,u]),h=[i[0],i[1]],{left:g,top:p,width:v,height:y}=d;if(y4([g,p,v,y],h)<=o)return!0},this.toolSelectedCallback=(r,n,i="mouse")=>{const o=r.detail,{element:a}=o,{data:s}=n;s.active=!0;const c=_t(a,this.getToolName(),!1);this.editData={annotation:n,viewportUIDsToRender:c},this._activateModify(a),Ot(a),Pe(c),r.preventDefault()},this.handleSelectedCallback=(r,n,i,o="mouse")=>{const a=r.detail,{element:s}=a,{data:c}=n;c.active=!0;let l;i.worldPosition||(l=c.handles.points.findIndex(u=>u===i));const f=_t(s,this.getToolName(),!1);this.editData={annotation:n,viewportUIDsToRender:f,handleIndex:l},this._activateModify(s),Ot(s),Pe(f),r.preventDefault()},this._endCallback=r=>{const n=r.detail,{element:i}=n,{annotation:o,viewportUIDsToRender:a,newAnnotation:s,hasMoved:c}=this.editData,{data:l}=o;s&&!c||(this.doneEditMemo(),l.active=!1,l.handles.activeHandleIndex=null,this._deactivateModify(i),this._deactivateDraw(i),zt(i),this.editData=null,this.isDrawing=!1,this.isHandleOutsideImage&&this.configuration.preventHandleOutsideImage&&gn(o.annotationUID),Pe(a))},this._dragCallback=r=>{this.isDrawing=!0;const n=r.detail,{element:i}=n,{annotation:o,viewportUIDsToRender:a,handleIndex:s,newAnnotation:c}=this.editData;this.createMemo(i,o,{newAnnotation:c});const{data:l}=o;if(s===void 0){const{deltaPoints:f}=n,u=f.world,{points:d}=l.handles;d.forEach(h=>{h[0]+=u[0],h[1]+=u[1],h[2]+=u[2]}),l.invalidated=!0}else{const{currentPoints:f}=n,u=Ce(i),{worldToCanvas:d,canvasToWorld:h}=u.viewport,g=f.world,{points:p}=l.handles;p[s]=[...g];let v,y,m,w,x,C,S,_;switch(s){case 0:case 3:v=d(p[0]),w=d(p[3]),y=[w[0],v[1]],m=[v[0],w[1]],C=h(y),S=h(m),p[1]=C,p[2]=S;break;case 1:case 2:y=d(p[1]),m=d(p[2]),v=[m[0],y[1]],w=[y[0],m[1]],x=h(v),_=h(w),p[0]=x,p[3]=_;break}l.invalidated=!0}this.editData.hasMoved=!0,Ce(i),Pe(a)},this._activateDraw=r=>{Be.isInteractingWithTool=!0,r.addEventListener(N.MOUSE_UP,this._endCallback),r.addEventListener(N.MOUSE_DRAG,this._dragCallback),r.addEventListener(N.MOUSE_MOVE,this._dragCallback),r.addEventListener(N.MOUSE_CLICK,this._endCallback),r.addEventListener(N.TOUCH_END,this._endCallback),r.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateDraw=r=>{Be.isInteractingWithTool=!1,r.removeEventListener(N.MOUSE_UP,this._endCallback),r.removeEventListener(N.MOUSE_DRAG,this._dragCallback),r.removeEventListener(N.MOUSE_MOVE,this._dragCallback),r.removeEventListener(N.MOUSE_CLICK,this._endCallback),r.removeEventListener(N.TOUCH_END,this._endCallback),r.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this._activateModify=r=>{Be.isInteractingWithTool=!0,r.addEventListener(N.MOUSE_UP,this._endCallback),r.addEventListener(N.MOUSE_DRAG,this._dragCallback),r.addEventListener(N.MOUSE_CLICK,this._endCallback),r.addEventListener(N.TOUCH_END,this._endCallback),r.addEventListener(N.TOUCH_DRAG,this._dragCallback)},this._deactivateModify=r=>{Be.isInteractingWithTool=!1,r.removeEventListener(N.MOUSE_UP,this._endCallback),r.removeEventListener(N.MOUSE_DRAG,this._dragCallback),r.removeEventListener(N.MOUSE_CLICK,this._endCallback),r.removeEventListener(N.TOUCH_END,this._endCallback),r.removeEventListener(N.TOUCH_DRAG,this._dragCallback)},this.renderAnnotation=(r,n)=>{const{viewport:o}=r,{element:a}=o;let s=un(this.getToolName(),a);if(!(s!=null&&s.length)||(s=this.filterInteractableAnnotationsForElement(a,s),!(s!=null&&s.length)))return!1;const c={toolGroupId:this.toolGroupId,toolName:this.getToolName(),viewportId:r.viewport.id};for(let l=0;lo.worldToCanvas(C)),v=this.getStyle("lineWidth",c,f),y=this.getStyle("lineDash",c,f),m=this.getStyle("color",c,f);if(!o.getRenderingEngine()){console.warn("Rendering Engine has been destroyed");return}let w;!this.editData&&g!==null&&(w=[p[g]]),w&&ir(n,u,"0",w,{color:m}),Wk(n,u,"0",p[0],p[3],{color:"black",lineDash:y,lineWidth:v})}},this._getRectangleImageCoordinates=r=>{const[n,i]=r;return{left:Math.min(n[0],i[0]),top:Math.min(n[1],i[1]),width:Math.abs(n[0]-i[0]),height:Math.abs(n[1]-i[1])}},this._calculateCachedStats=(r,n,i,o,a)=>{const{data:s}=r,{viewportUID:c,renderingEngineUID:l,sceneUID:f}=a,u=s.handles.points[0],d=s.handles.points[3],{cachedStats:h}=s,g=Object.keys(h);for(let v=0;vsr(r,i)&&sr(n,i),this._getTargetVolumeUID=r=>{if(this.configuration.volumeUID)return this.configuration.volumeUID;const n=r.getVolumeActors();if(!(!n&&!n.length))return n[0].uid},this._throttledCalculateCachedStats=_o(this._calculateCachedStats,100,{trailing:!0})}cancel(e){if(!this.isDrawing)return;this.isDrawing=!1,this._deactivateDraw(e),this._deactivateModify(e),zt(e);const{annotation:r,viewportUIDsToRender:n}=this.editData,{data:i}=r;return i.active=!1,i.handles.activeHandleIndex=null,Pe(n),this.editData=null,r.metadata.annotationUID}_getImageVolumeFromTargetUID(e,r){let n,i;if(e.startsWith("stackTarget")){const o=e.indexOf(":"),a=e.substring(o+1);n=r.getViewport(a).getImageData()}else n=Le.getVolume(e);return{imageVolume:n,viewport:i}}_getTargetStackUID(e){return`stackTarget:${e.uid}`}};AE.toolName="VideoRedaction";let rS=AE;const Twe=Object.freeze(Object.defineProperty({__proto__:null,AdvancedMagnifyTool:Zp,AngleTool:HC,AnnotationDisplayTool:Fu,AnnotationTool:ar,ArrowAnnotateTool:Ou,BaseTool:ai,BidirectionalTool:Hp,BrushTool:z5,CONSTANTS:e1e,CircleROIStartEndThresholdTool:aB,CircleROITool:gy,CircleScissorsTool:iB,CobbAngleTool:KC,CrosshairsTool:Fs,DragProbeTool:WC,ETDRSGridTool:zC,EllipticalROITool:od,Enums:nN,EraserTool:tB,HeightTool:GC,KeyImageTool:ZC,LabelMapEditWithContourTool:nS,LabelTool:hy,LabelmapBaseTool:rd,LengthTool:Iu,LivewireContourSegmentationTool:jC,LivewireContourTool:vy,MIPJumpToClickTool:jU,MagnifyTool:HU,OrientationMarkerTool:xy,OverlayGridTool:KU,PaintFillTool:sB,PanTool:j0,PlanarFreehandContourSegmentationTool:ic,PlanarFreehandROITool:bu,PlanarRotateTool:K0,ProbeTool:nl,RectangleROIStartEndThresholdTool:W4,RectangleROIThresholdTool:z4,RectangleROITool:tl,RectangleScissorsTool:rB,ReferenceCursors:ua,ReferenceLinesTool:Gf,RegionSegmentPlusTool:eS,RegionSegmentTool:QC,ScaleOverlayTool:JU,SculptorTool:X0,SegmentBidirectionalTool:tS,SegmentLabelTool:wB,SegmentSelectTool:Cy,SegmentationIntersectionTool:qU,SphereScissorsTool:oB,SplineContourSegmentationTool:$C,SplineROITool:py,StackScrollTool:id,Synchronizer:F4,SynchronizerManager:rF,ToolGroupManager:vN,TrackballRotateTool:zU,Types:Dye,UltrasoundDirectionalTool:qC,UltrasoundPleuraBLineTool:JC,VideoRedactionTool:rS,VolumeRotateTool:QU,WholeBodySegmentTool:nB,WindowLevelRegionTool:$U,WindowLevelTool:H0,ZoomTool:q0,addTool:Ci,annotation:nge,cancelActiveManipulations:nF,cursors:eue,destroy:Jpe,drawing:Ede,init:iF,removeTool:TN,segmentation:Hye,splines:Jye,get state(){return Be},store:Ype,synchronizers:C1e,utilities:Eye,version:t1e},Symbol.toStringTag,{value:"Module"}));function xB(t,e,r){if(t===void 0)throw new Error("decodeRGB: rgbBuffer must be defined");if(t.length%3!==0)throw new Error(`decodeRGB: rgbBuffer length ${t.length} must be divisible by 3`);const n=t.length/3;let i=0,o=0;if(r){for(let a=0;a>e;return n}function I3(t,e,r){const n=t[`${e}PaletteColorLookupTableData`];if(n)return Promise.resolve(n);const i=mt("imagePixelModule",t.imageId);return i&&typeof i.then=="function"?i.then(o=>o?o[`${e}PaletteColorLookupTableData`]:r):Promise.resolve(i?i[`${e}PaletteColorLookupTableData`]:r)}function TB(t,e,r){const n=t.columns*t.rows,i=t.pixelData;Promise.all([I3(t,"red",null),I3(t,"green",null),I3(t,"blue",null)]).then(([o,a,s])=>{if(!o||!a||!s)throw new Error("The image does not have a complete color palette. R, G, and B palette data are required.");const c=o.length;let l=0,f=0;const u=t.redPaletteColorLookupTableDescriptor[1],d=t.redPaletteColorLookupTableDescriptor[2]===8?0:8,h=b3(o,d),g=b3(a,d),p=b3(s,d);if(r){for(let v=0;vu+c-1?y=c-1:y-=u,e[f++]=h[y],e[f++]=g[y],e[f++]=p[y],e[f++]=255}return}for(let v=0;vu+c-1?y=c-1:y-=u,e[f++]=h[y],e[f++]=g[y],e[f++]=p[y]}})}function O3(t,e){if(!(!t.elements[e]||t.elements[e].length!==6))return[t.uint16(e,0),t.uint16(e,1),t.uint16(e,2)]}function M3(t,e,r){const n=[],i=t.elements[e];for(let o=0;o0?0:t.uint16("x00280103")}function _s(t,e,r){const n=[],i=t.string(e);if(!i)return;const o=i.split("\\");if(!(r&&o.lengthie.byteArray.length-ie.position&&(wt=ie.byteArray.length-ie.position),ae.fragments.push({offset:ie.position-oe-8,position:ie.position,length:wt}),ie.seek(wt),void(ae.length=ie.position-ae.dataOffset);ae.fragments.push({offset:ie.position-oe-8,position:ie.position,length:wt}),ie.seek(wt)}ye&&ye.push("pixel data element ".concat(ae.tag," missing sequence delimiter tag xfffee0dd"))}function _(ie,ae){if(ie===void 0)throw"dicomParser.findAndSetUNElementLength: missing required parameter 'byteStream'";for(var ye=ie.byteArray.length-8;ie.position<=ye;)if(ie.readUint16()===65534){var se=ie.readUint16();if(se===57565)return ie.readUint32()!==0&&ie.warnings("encountered non zero length following item delimiter at position ".concat(ie.position-4," while reading element of undefined length with tag ").concat(ae.tag)),void(ae.length=ie.position-ae.dataOffset)}ae.length=ie.byteArray.length-ae.dataOffset,ie.seek(ie.byteArray.length-ie.position)}function T(ie,ae,ye){if(ye<0)throw"dicomParser.readFixedString - length cannot be less than 0";if(ae+ye>ie.length)throw"dicomParser.readFixedString: attempt to read past end of buffer";for(var se,ge="",Fe=0;Feae.byteArray.length)throw"dicomParser.parseDicomDataSetExplicit: invalid value for parameter 'maxP osition'";for(var ge=ie.elements;ae.positionye)throw"dicomParser:parseDicomDataSetExplicit: buffer overrun"}function re(ie,ae,ye){var se=3ae.byteArray.length)throw"dicomParser.parseDicomDataSetImplicit: invalid value for parameter 'maxPosition'";for(var ge=ie.elements;ae.positionie.length)throw"bigEndianByteArrayParser.readUint16: attempt to read past end of buffer";return(ie[ae]<<8)+ie[ae+1]},readInt16:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readInt16: position cannot be less than 0";if(ae+2>ie.length)throw"bigEndianByteArrayParser.readInt16: attempt to read past end of buffer";return ae=(ie[ae]<<8)+ie[ae+1],ae=32768&ae?ae-65535-1:ae},readUint32:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readUint32: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readUint32: attempt to read past end of buffer";return 256*(256*(256*ie[ae]+ie[ae+1])+ie[ae+2])+ie[ae+3]},readInt32:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readInt32: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readInt32: attempt to read past end of buffer";return(ie[ae]<<24)+(ie[ae+1]<<16)+(ie[ae+2]<<8)+ie[ae+3]},readFloat:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readFloat: position cannot be less than 0";if(ae+4>ie.length)throw"bigEndianByteArrayParser.readFloat: attempt to read past end of buffer";var ye=new Uint8Array(4);return ye[3]=ie[ae],ye[2]=ie[ae+1],ye[1]=ie[ae+2],ye[0]=ie[ae+3],new Float32Array(ye.buffer)[0]},readDouble:function(ie,ae){if(ae<0)throw"bigEndianByteArrayParser.readDouble: position cannot be less than 0";if(ae+8>ie.length)throw"bigEndianByteArrayParser.readDouble: attempt to read past end of buffer";var ye=new Uint8Array(8);return ye[7]=ie[ae],ye[6]=ie[ae+1],ye[5]=ie[ae+2],ye[4]=ie[ae+3],ye[3]=ie[ae+4],ye[2]=ie[ae+5],ye[1]=ie[ae+6],ye[0]=ie[ae+7],new Float64Array(ye.buffer)[0]}};function Ee(ie,ae,ye){if(typeof Buffer<"u"&&ie instanceof Buffer)return ie.slice(ae,ae+ye);if(ie instanceof Uint8Array)return new Uint8Array(ie.buffer,ie.byteOffset+ae,ye);throw"dicomParser.from: unknown type for byteArray"}function Oe(ie,ae){for(var ye=0;ye"u"||!(ge instanceof Buffer)))throw"dicomParser.ByteStream: parameter byteArray is not of type Uint8Array or Buffer";if(Fe<0)throw"dicomParser.ByteStream: parameter 'position' cannot be less than 0";if(Fe>=ge.length)throw"dicomParser.ByteStream: parameter 'position' cannot be greater than or equal to 'byteArray' length";this.byteArrayParser=se,this.byteArray=ge,this.position=Fe||0,this.warnings=[]}var ae,ye;return ae=ie,(ye=[{key:"seek",value:function(se){if(this.position+se<0)throw"dicomParser.ByteStream.prototype.seek: cannot seek to position < 0";this.position+=se}},{key:"readByteStream",value:function(se){if(this.position+se>this.byteArray.length)throw"dicomParser.ByteStream.prototype.readByteStream: readByteStream - buffer overread";var ge=Ee(this.byteArray,this.position,se);return this.position+=se,new ie(this.byteArrayParser,ge)}},{key:"getSize",value:function(){return this.byteArray.length}},{key:"readUint16",value:function(){var se=this.byteArrayParser.readUint16(this.byteArray,this.position);return this.position+=2,se}},{key:"readUint32",value:function(){var se=this.byteArrayParser.readUint32(this.byteArray,this.position);return this.position+=4,se}},{key:"readFixedString",value:function(se){var ge=T(this.byteArray,this.position,se);return this.position+=se,ge}}])&&Oe(ae.prototype,ye),Object.defineProperty(ae,"prototype",{writable:!1}),ie}(),B={readUint16:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readUint16: position cannot be less than 0";if(ae+2>ie.length)throw"littleEndianByteArrayParser.readUint16: attempt to read past end of buffer";return ie[ae]+256*ie[ae+1]},readInt16:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readInt16: position cannot be less than 0";if(ae+2>ie.length)throw"littleEndianByteArrayParser.readInt16: attempt to read past end of buffer";return ae=ie[ae]+(ie[ae+1]<<8),ae=32768&ae?ae-65535-1:ae},readUint32:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readUint32: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readUint32: attempt to read past end of buffer";return ie[ae]+256*ie[ae+1]+256*ie[ae+2]*256+256*ie[ae+3]*256*256},readInt32:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readInt32: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readInt32: attempt to read past end of buffer";return ie[ae]+(ie[ae+1]<<8)+(ie[ae+2]<<16)+(ie[ae+3]<<24)},readFloat:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readFloat: position cannot be less than 0";if(ae+4>ie.length)throw"littleEndianByteArrayParser.readFloat: attempt to read past end of buffer";var ye=new Uint8Array(4);return ye[0]=ie[ae],ye[1]=ie[ae+1],ye[2]=ie[ae+2],ye[3]=ie[ae+3],new Float32Array(ye.buffer)[0]},readDouble:function(ie,ae){if(ae<0)throw"littleEndianByteArrayParser.readDouble: position cannot be less than 0";if(ae+8>ie.length)throw"littleEndianByteArrayParser.readDouble: attempt to read past end of buffer";var ye=new Uint8Array(8);return ye[0]=ie[ae],ye[1]=ie[ae+1],ye[2]=ie[ae+2],ye[3]=ie[ae+3],ye[4]=ie[ae+4],ye[5]=ie[ae+5],ye[6]=ie[ae+6],ye[7]=ie[ae+7],new Float64Array(ye.buffer)[0]}};function O(ie){var ae=1"u")throw"dicomParser.parseDicom: no inflater available to handle deflate transfer syntax";return nt=ie.slice(Ie),rt=pako.inflateRaw(nt),(nt=ue(ie,rt.length+Ie)).set(ie.slice(0,Ie),0),nt.set(rt,Ie),new _e(B,nt,0)}(ht,wt.position),wt=new b(ht.byteArrayParser,ht.byteArray,{});wt.warnings=ht.warnings;try{(oe?Y:re)(wt,ht,ht.byteArray.length,ae)}catch(gt){throw{exception:gt,dataSet:wt}}return wt}return function(Fe,oe){for(var ht in Fe.elements)Fe.elements.hasOwnProperty(ht)&&(oe.elements[ht]=Fe.elements[ht]);return Fe.warnings!==void 0&&(oe.warnings=Fe.warnings.concat(oe.warnings)),oe}(ye=O(ie,ae),ge(ye))}var K=function(ie,ae,ye){for(var se=0,ge=ae;ge= 0";if(ye>=oe.fragments.length)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragmentIndex' must be < number of fragments";if(se<1)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'numFragments' must be > 0";if(ye+se>oe.fragments.length)throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragment' + 'numFragments' < number of fragments";var Fe=new _e(ie.byteArrayParser,ie.byteArray,oe.dataOffset),oe=L(Fe);if(oe.tag!=="xfffee000")throw"dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000";Fe.seek(oe.length);var ht=Fe.position;if(se===1)return Ee(Fe.byteArray,ht+ge[ye].offset+8,ge[ye].length);for(var oe=K(ge,ye,se),wt=ue(Fe.byteArray,oe),gt=0,Ie=ye;Ie= 0";if(ye>=se.length)throw"dicomParser.readEncapsulatedImageFrame: parameter 'frameIndex' must be < basicOffsetTable.length";var Fe=se[ye],Fe=ee(ge,Fe);if(Fe===void 0)throw"dicomParser.readEncapsulatedImageFrame: unable to find fragment that matches basic offset table entry";return Z(ie,ae,Fe,xe(ye,se,ge,Fe),ge)}var Ne=!1;function $e(ie,ae,ye){if(Ne||(Ne=!0,console&&console.log&&console.log("WARNING: dicomParser.readEncapsulatedPixelData() has been deprecated")),ie===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'dataSet'";if(ae===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'element'";if(ye===void 0)throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'frame'";if(ae.tag!=="x7fe00010")throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to non pixel data tag (expected tag = x7fe00010)";if(ae.encapsulatedPixelData!==!0||ae.hadUndefinedLength!==!0||ae.basicOffsetTable===void 0||ae.fragments===void 0)throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";if(ye<0)throw"dicomParser.readEncapsulatedPixelData: parameter 'frame' must be >= 0";return ae.basicOffsetTable.length!==0?De(ie,ae,ye):Z(ie,ae,0,ae.fragments.length)}s.default={isStringVr:f,isPrivateTag:u,parsePN:d,parseTM:h,parseDA:p,explicitElementToString:v,explicitDataSetToJS:y,createJPEGBasicOffsetTable:x,parseDicomDataSetExplicit:Y,parseDicomDataSetImplicit:re,readFixedString:T,alloc:ue,version:ce,bigEndianByteArrayParser:pe,ByteStream:_e,sharedCopy:Ee,DataSet:b,findAndSetUNElementLength:_,findEndOfEncapsulatedElement:S,findItemDelimitationItemAndSetElementLength:I,littleEndianByteArrayParser:B,parseDicom:W,readDicomElementExplicit:j,readDicomElementImplicit:M,readEncapsulatedImageFrame:De,readEncapsulatedPixelData:$e,readEncapsulatedPixelDataFromFragments:Z,readPart10Header:O,readSequenceItemsExplicit:k,readSequenceItemsImplicit:G,readSequenceItem:L,readTag:C,LEI:"1.2.840.10008.1.2",LEE:"1.2.840.10008.1.2.1"}}],o={},n.m=i,n.c=o,n.d=function(a,s,c){n.o(a,s)||Object.defineProperty(a,s,{enumerable:!0,get:c})},n.r=function(a){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(a,"__esModule",{value:!0})},n.t=function(a,s){if(1&s&&(a=n(a)),8&s||4&s&&typeof a=="object"&&a&&a.__esModule)return a;var c=Object.create(null);if(n.r(c),Object.defineProperty(c,"default",{enumerable:!0,value:a}),2&s&&typeof a!="string")for(var l in a)n.d(c,l,(function(f){return a[f]}).bind(null,l));return c},n.n=function(a){var s=a&&a.__esModule?function(){return a.default}:function(){return a};return n.d(s,"a",s),s},n.o=function(a,s){return Object.prototype.hasOwnProperty.call(a,s)},n.p="",n(n.s=1);function n(a){if(o[a])return o[a].exports;var s=o[a]={i:a,l:!1,exports:{}};return i[a].call(s.exports,s,s.exports,n),s.l=!0,s.exports}var i,o})})(bB);var Tr=bB.exports;function k1(t){const e=t.indexOf(":");let r=t.substring(e+1);const n=r.indexOf("frame=");let i;if(n!==-1){const s=r.substring(n+6);i=parseInt(s,10),r=r.substring(0,n-1)}const o=t.substring(0,e),a=i!==void 0?i-1:void 0;return{scheme:o,url:r,frame:i,pixelDataFrame:a}}let oS={open(t,e){t.open("get",e,!0)},beforeSend(){},beforeProcessing(t){return Promise.resolve(t.response)},imageCreated(){},strict:!1};function IB(t){oS=Object.assign(oS,t)}function V1(){return oS}function H5(t,e,r={},n={}){const i=V1(),o=c=>{if(typeof i.errorInterceptor=="function"){const l=new Error("request failed");l.request=c,l.response=c.response,l.status=c.status,i.errorInterceptor(l)}},a=new XMLHttpRequest,s=new Promise((c,l)=>{i.open(a,t,r,n);const f=i.beforeSend(a,e,r,n);a.responseType="arraybuffer";const u=Object.assign({},r,f);Object.keys(u).forEach(function(d){u[d]!==null&&(d==="Accept"&&t.indexOf("accept=")!==-1||a.setRequestHeader(d,u[d]))}),n.deferred={resolve:c,reject:l},n.url=t,n.imageId=e,a.onloadstart=function(d){i.onloadstart&&i.onloadstart(d,n),at(Ke,"cornerstoneimageloadstart",{url:t,imageId:e})},a.onloadend=function(d){i.onloadend&&i.onloadend(d,n),at(Ke,"cornerstoneimageloadend",{url:t,imageId:e})},a.onreadystatechange=function(d){i.onreadystatechange&&i.onreadystatechange(d,n),a.readyState===4&&(a.status===200||a.status===206?i.beforeProcessing(a).then(c).catch(()=>{o(a),l(a)}):(o(a),l(a)))},a.onprogress=function(d){const h=d.loaded;let g,p;d.lengthComputable&&(g=d.total,p=Math.round(h/g*100)),at(Ke,"cornerstoneimageloadprogress",{url:t,imageId:e,loaded:h,total:g,percentComplete:p}),i.onprogress&&i.onprogress(d,n)},a.onerror=function(){o(a),l(a)},a.onabort=function(){o(a),l(a)},a.send()});return s.xhr=a,s}function Mwe(t,e,r){if(r+t.length>e.length)return!1;let n=r;for(let i=0;i{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}},l=new Nwe("streamRequest");return l.generate(async(f,u)=>{var g,p;const d=(g=i.beforeSend)==null?void 0:g.call(i,null,t,r,{}),h=Object.assign({},r,d);Object.keys(h).forEach(function(v){h[v]===null&&(h[v]=void 0),v==="Accept"&&t.indexOf("accept=")!==-1&&(h[v]=void 0)});try{const v=await fetch(t,{headers:h,signal:void 0});if(v.status!==200)throw new Error(`Couldn't retrieve ${t} got status ${v.status}`);const y=v.body.getReader(),m=v.headers,w=m.get("content-type"),x=Number(m.get("Content-Length"));let C=!1,S=a.encodedData,_=a.lastSize||0;for(a.isPartial=!0;!C;){const{done:T,value:E}=await y.read();if(S=kwe(S,E),!S){if(C)throw new Error(`Done but no image frame available ${e}`);continue}if(C=T||S.byteLength===x,!C&&S.length<_+s)continue;_=S.length,a.isPartial=!T;const D=aE(w,S,a),b=sE(o,C),I={url:t,imageId:e,...D,percentComplete:T?100:((p=D.pixelData)==null?void 0:p.length)*100/x,imageQualityStatus:b,done:C};f.add(I,C)}}catch(v){c(),console.error(v),u(v)}}),l.getNextPromise()}function kwe(t,e){if(!t)return e;if(!e)return t;const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}const Vwe={xhrRequest:H5,streamRequest:OB,setOptions:IB,getOptions:V1};function Fwe(t){const e=t.elements.x7fe00010.fragments,r=t.byteArray.length;for(const n of e){const{position:i,length:o}=n;o>r-i&&(console.log(`Truncated fragment, changing fragment length from ${n.length} to ${r-i}`),n.length=r-i)}return t}function Uwe(t){let e=Tr.parseDicom(t,{untilTag:"x7fe00010"});e.elements.x7fe00010||console.warn("Pixel data not found!");let r;try{r=Tr.parseDicom(t)}catch(n){console.error(n),console.log("pixel data dataset:",n.dataSet),r=n.dataSet}return e.elements.x7fe00010=r.elements.x7fe00010,e=Fwe(e),e}async function MB(t,e,r){const n=Uwe(t),{uri:i,imageId:o,fileTotalLength:a}=r;return n.fetchMore=async function(s){const c=Object.assign({uri:i,imageId:o,fetchedLength:t.length,lengthToFetch:a-t.length},s),{fetchedLength:l,lengthToFetch:f}=c,{arrayBuffer:u}=await e(i,o,{byteRange:`${l}-${l+f}`}),d=new Uint8Array(u),h=new Uint8Array(n.byteArray.length+d.length);return h.set(n.byteArray),h.set(d,n.byteArray.length),MB(h,e,r)},n}function Bwe(t,e){if(!t)return;const{NumberOfFrames:r,PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i}=RB(t);if(n||r>1){const{shared:o,perFrame:a}=PB(n,i,e);return{NumberOfFrames:r,PerFrameFunctionalInformation:a,SharedFunctionalInformation:o}}return{NumberOfFrames:r}}function PB(t,e,r){const n={};(e?Object.values(e.items[0].dataSet.elements):[]).map(o=>n[o.tag]=o);const i={};return(t?Object.values(t.items[r-1].dataSet.elements):[]).map(o=>i[o.tag]=o),{shared:n,perFrame:i}}function RB(t){if(!t)return;const{elements:e,...r}=t,{x52009230:n,x52009229:i,...o}=e;return{NumberOfFrames:t.intString("x00280008"),PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i,otherElements:o,otherAttributtes:r}}function Gwe(t,e){if(!e)return;const{NumberOfFrames:r,PerFrameFunctionalGroupsSequence:n,SharedFunctionalGroupsSequence:i,otherElements:o}=RB(e);if(n||r>1){const{shared:a,perFrame:s}=PB(n,i,t),c={elements:{...o,...a,...s}},l=Object.create(e);return Object.assign(l,c)}return e}let Ri={};const Wwe=()=>{Ri={}};function cE(t){if(Ri[t])return Ri[t]}function zwe(t){const e=cE(t);return LB(e)}function LB(t){if(!t)return!1;const e=t.intString("x00280008");return e&&e>1}function $we(t){return t.indexOf("&frame=")}function jwe(t){const e=$we(t),r=e===-1?t:t.slice(0,e),n=parseInt(t.slice(e+7),10)||1;let i;return Ri[r]?i=Ri[r].dataSet:i=void 0,{dataSet:i,frame:n}}function Hwe(t){const e=[],r=cE(t);if(LB(r)){const n=r.intString("x00280008");for(let i=1;i<=n;i++)e.push(`${t}&frame=${i}`)}else e.push(t);return e}const AB={_get:cE,generateMultiframeWADOURIs:Hwe,retrieveMultiframeDataset:jwe,isMultiframeDataset:zwe};let J0=0,xf={};function Kwe(t){return Ri[t]!==void 0}function qwe(t){let e;if(t.includes("&frame=")){const{frame:r,dataSet:n}=AB.retrieveMultiframeDataset(t);e=Gwe(r,n)}else Ri[t]&&(e=Ri[t].dataSet);return e}function Xwe(t,e){const r=Ri[t];if(!r){console.error(`No loaded dataSet for uri ${t}`);return}J0-=r.dataSet.byteArray.length,r.dataSet=e,J0+=e.byteArray.length,at(Ke,"datasetscachechanged",{uri:t,action:"updated",cacheInfo:K5()})}function Ywe(t,e=H5,r){if(Ri[t])return new Promise(o=>{Ri[t].cacheCount++,o(Ri[t].dataSet)});if(xf[t])return xf[t].cacheCount++,xf[t];const n=e(t,r),i=new Promise((o,a)=>{n.then(async function(s){const c={isPartialContent:!1,fileTotalLength:null};if(!(s instanceof ArrayBuffer)){if(!s.arrayBuffer)return a(new Error("If not returning ArrayBuffer, must return object with `arrayBuffer` parameter"));c.isPartialContent=s.flags.isPartialContent,c.fileTotalLength=s.flags.fileTotalLength,s=s.arrayBuffer}const l=new Uint8Array(s);let f;try{c.isPartialContent?f=await MB(l,e,{uri:t,imageId:r,fileTotalLength:c.fileTotalLength}):f=Tr.parseDicom(l)}catch(u){return a(u)}Ri[t]={dataSet:f,cacheCount:i.cacheCount},J0+=f.byteArray.length,o(f),at(Ke,"datasetscachechanged",{uri:t,action:"loaded",cacheInfo:K5()})},a).then(()=>{delete xf[t]},()=>{delete xf[t]})});return i.cacheCount=1,xf[t]=i,i}function Jwe(t){Ri[t]&&(Ri[t].cacheCount--,Ri[t].cacheCount===0&&(J0-=Ri[t].dataSet.byteArray.length,delete Ri[t],at(Ke,"datasetscachechanged",{uri:t,action:"unloaded",cacheInfo:K5()})))}function K5(){return{cacheSizeInBytes:J0,numberOfDataSetsCached:Object.keys(Ri).length}}function Zwe(){Wwe(),xf={},J0=0}const T0={isLoaded:Kwe,load:Ywe,unload:Jwe,getInfo:K5,purge:Zwe,get:qwe,update:Xwe};function Qwe(t){const e=[];for(let r=0;r<=30;r+=2){let n=`x60${r.toString(16)}`;n.length===4&&(n=`x600${r.toString(16)}`);const i=t.elements[`${n}3000`];if(!i)continue;const o=[];for(let a=0;a>s&1}e.push({rows:t.uint16(`${n}0010`),columns:t.uint16(`${n}0011`),type:t.string(`${n}0040`),x:t.int16(`${n}0050`,1)-1,y:t.int16(`${n}0050`,0)-1,pixelData:o,description:t.string(`${n}0022`),label:t.string(`${n}1500`),roiArea:t.string(`${n}1301`),roiMean:t.string(`${n}1302`),roiStandardDeviation:t.string(`${n}1303`)})}return{overlays:e}}function bh(t){return t==="RECON TOMO"||t==="RECON GATED TOMO"}function lE(t,e){const r=t.string("x00080008");if(r){const n=r.split("\\");if(n.length>e)return n[e]}}function e3e(t){let e;const r=t.string("x00080060");if(r!=null&&r.includes("NM")){const n=lE(t,2);n&&bh(n)&&t.elements.x00540022&&(e=_s(t.elements.x00540022.items[0].dataSet,"x00200037",6))}return e}function t3e(t){let e;const r=t.string("x00080060");if(r!=null&&r.includes("NM")){const n=lE(t,2);n&&bh(n)&&t.elements.x00540022&&(e=_s(t.elements.x00540022.items[0].dataSet,"x00200032",3))}return e}function yb(t){let e=_s(t,"x00200037",6);return!e&&t.elements.x00209116&&(e=_s(t.elements.x00209116.items[0].dataSet,"x00200037",6)),e||(e=e3e(t)),e}function wb(t){let e=_s(t,"x00200032",3);return!e&&t.elements.x00209113&&(e=_s(t.elements.x00209113.items[0].dataSet,"x00200032",3)),e||(e=t3e(t)),e}function xb(t){let e=_s(t,"x00280030",2);return!e&&t.elements.x00289110&&(e=_s(t.elements.x00289110.items[0].dataSet,"x00280030",2)),e}function Cb(t){let e;return t.elements.x00180050?e=t.floatString("x00180050"):t.elements.x00289110&&t.elements.x00289110.items.length&&t.elements.x00289110.items[0].dataSet.elements.x00180050&&(e=t.elements.x00289110.items[0].dataSet.floatString("x00180050")),e}function NB(t,e,r){const n={};for(const i of r)try{const o=e(i,t);if(o){const a={};for(const s in o)if(s in o){const c=n3e(s);a[c]=o[s]}Object.assign(n,a)}}catch(o){console.error(`Error retrieving ${i} data:`,o)}return n}const n3e=t=>t.charAt(0).toUpperCase()+t.slice(1),kB=["multiframeModule","generalSeriesModule","patientStudyModule","imagePlaneModule","nmMultiframeGeometryModule","imagePixelModule","modalityLutModule","voiLutModule","sopCommonModule","petIsotopeModule","overlayPlaneModule","transferSyntax","petSeriesModule","petImageModule"];function Sb(t){const e=t.elements.x00186011;return!e||!e.items?[]:e.items.map(n=>{const i=n.dataSet.double("x0018602c"),o=n.dataSet.double("x0018602e"),a=n.dataSet.uint16("x00186024"),s=n.dataSet.uint16("x00186026"),c=n.dataSet.uint16("x0018601a"),l=n.dataSet.uint16("x0018601e"),f=n.dataSet.uint16("x00186018"),u=n.dataSet.uint16("x0018601c"),d=n.dataSet.int32("x00186020")||null,h=n.dataSet.int32("x00186022")||null,g=n.dataSet.uint16("x0018602a"),p=n.dataSet.uint16("x00186028"),v=n.dataSet.uint16("x00186012"),y=n.dataSet.uint16("x00186014"),m=n.dataSet.uint16("x00186016"),w=n.dataSet.uint16("x00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function uE(t,e){const{MetadataModules:r}=ja;if(Array.isArray(e))return;const n=k1(e);if(t===r.MULTIFRAME){const a=AB.retrieveMultiframeDataset(n.url);return a.dataSet?Bwe(a.dataSet,a.frame):void 0}let i=n.url;n.frame&&(i=`${i}&frame=${n.frame}`);const o=T0.get(i);if(o)return VB(t,e,o)}function VB(t,e,r){const{MetadataModules:n}=ja;if(t===n.GENERAL_STUDY)return{studyDescription:r.string("x00081030"),studyDate:Tr.parseDA(r.string("x00080020")),studyTime:Tr.parseTM(r.string("x00080030")||""),accessionNumber:r.string("x00080050")};if(t===n.GENERAL_SERIES)return{modality:r.string("x00080060"),seriesInstanceUID:r.string("x0020000e"),seriesDescription:r.string("x0008103e"),seriesNumber:r.intString("x00200011"),studyInstanceUID:r.string("x0020000d"),seriesDate:Tr.parseDA(r.string("x00080021")),seriesTime:Tr.parseTM(r.string("x00080031")||""),acquisitionDate:Tr.parseDA(r.string("x00080022")),acquisitionTime:Tr.parseTM(r.string("x00080032")||"")};if(t===n.GENERAL_IMAGE)return{sopInstanceUID:r.string("x00080018"),instanceNumber:r.intString("x00200013"),lossyImageCompression:r.string("x00282110"),lossyImageCompressionRatio:r.floatString("x00282112"),lossyImageCompressionMethod:r.string("x00282114")};if(t===n.PATIENT)return{patientID:r.string("x00100020"),patientName:r.string("x00100010")};if(t===n.PATIENT_STUDY)return{patientAge:r.intString("x00101010"),patientSize:r.floatString("x00101020"),patientSex:r.string("x00100040"),patientWeight:r.floatString("x00101030")};if(t===n.NM_MULTIFRAME_GEOMETRY){const i=r.string("x00080060"),o=lE(r,2);return{modality:i,imageType:r.string("x00080008"),imageSubType:o,imageOrientationPatient:yb(r),imagePositionPatient:wb(r),sliceThickness:Cb(r),pixelSpacing:xb(r),numberOfFrames:r.uint16("x00280008"),isNMReconstructable:bh(o)&&i.includes("NM")}}if(t===n.IMAGE_PLANE){const i=yb(r),o=wb(r),a=xb(r),s=Cb(r);let c=null,l=null;a&&(l=a[0],c=a[1]);let f=null,u=null;return i&&(f=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],u=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]),{frameOfReferenceUID:r.string("x00200052"),rows:r.uint16("x00280010"),columns:r.uint16("x00280011"),imageOrientationPatient:i,rowCosines:f,columnCosines:u,imagePositionPatient:o,sliceThickness:s,sliceLocation:r.floatString("x00201041"),pixelSpacing:a,rowPixelSpacing:l,columnPixelSpacing:c}}if(t===n.CINE)return{frameTime:r.floatString("x00181063")};if(t===n.IMAGE_PIXEL)return EB(r);if(t===n.VOI_LUT){const i=DB(r);return{windowCenter:_s(r,"x00281050",1),windowWidth:_s(r,"x00281051",1),voiLUTSequence:iS(i,r.elements.x00283010),voiLUTFunction:r.string("x00281056")}}if(t===n.MODALITY_LUT)return{rescaleIntercept:r.floatString("x00281052"),rescaleSlope:r.floatString("x00281053"),rescaleType:r.string("x00281054"),modalityLUTSequence:iS(r.uint16("x00280103"),r.elements.x00283000)};if(t===n.SOP_COMMON)return{sopClassUID:r.string("x00080016"),sopInstanceUID:r.string("x00080018")};if(t===n.PET_ISOTOPE){const i=r.elements.x00540016;if(i===void 0)return;const o=i.items[0].dataSet;return{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:Tr.parseTM(o.string("x00181072")||""),radionuclideTotalDose:o.floatString("x00181074"),radionuclideHalfLife:o.floatString("x00181075")}}}if(t===n.OVERLAY_PLANE)return Qwe(r);if(t==="transferSyntax"){let i;try{i=r.string("x00020010")}catch{}return{transferSyntaxUID:i}}if(t===n.PET_SERIES)return{correctedImage:r.string("x00280051"),units:r.string("x00541001"),decayCorrection:r.string("x00541102")};if(t===n.PET_IMAGE)return{frameReferenceTime:r.floatString(r.string("x00541300")||""),actualFrameDuration:r.intString(r.string("x00181242"))};if(t===n.ULTRASOUND_ENHANCED_REGION)return Sb(r);if(t===n.CALIBRATION&&r.string("x00080060")==="US")return{sequenceOfUltrasoundRegions:Sb(r)};if(t==="instance")return NB(e,uE,kB)}let q5=[];function r3e(t){return`dicomfile:${q5.push(t)-1}`}function i3e(t){return q5[t]}function o3e(t){q5[t]=void 0}function a3e(){q5=[]}const FB={add:r3e,get:i3e,remove:o3e,purge:a3e};function s3e(t){const e=t.intString("x00280008"),r=t.elements.x7fe00010;return e!==r.fragments.length}function UB(t,e){if(t.elements.x7fe00010&&t.elements.x7fe00010.basicOffsetTable.length)return Tr.readEncapsulatedImageFrame(t,t.elements.x7fe00010,e);if(s3e(t)){const l=Tr.createJPEGBasicOffsetTable(t,t.elements.x7fe00010);return Tr.readEncapsulatedImageFrame(t,t.elements.x7fe00010,e,l)}const r=t.elements.x7fe00010.fragments,n=new Tr.ByteStream(t.byteArrayParser,t.byteArray,t.elements.x7fe00010.dataOffset),i=Tr.readSequenceItem(n);if(i.tag!=="xfffee000")throw"dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000";n.seek(i.length);const o=n.position;if(e+1>r.length)throw"dicomParser.readEncapsulatedPixelData: frame exceeds number of fragments";const s=o+r[e].offset+8,c=r[e].length;return new Uint8Array(n.byteArray.buffer.slice(n.byteArray.byteOffset+s,n.byteArray.byteOffset+s+c))}function c3e(t,e){return t&1<=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l))}else if(n===16){if(f=c+e*l*2,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*2))}else if(n===1){if(f=c+e*l*.125,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return BB(t.byteArray,f,l)}else if(n===32){if(f=c+e*l*4,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*4))}throw new Error("unsupported pixel format")}function WB(t){const e=k1(t),r=parseInt(e.url,10),n=FB.get(r);return new Promise((i,o)=>{const a=new FileReader;a.onload=s=>{const c=s.target.result;i(c)},a.onerror=o,a.readAsArrayBuffer(n)})}function fE(t,e=0){const r=t.elements.x7fe00010||t.elements.x7fe00008;return r?r.encapsulatedPixelData?UB(t,e):GB(t,e):null}function X5(t){let e=t[0],r=t[0],n;const i=t.length;for(let o=1;o{const s=new FileReader;s.readAsBinaryString===void 0?s.readAsArrayBuffer(i):s.readAsBinaryString(i),s.onload=function(){const c=new Image;c.onload=function(){r.height=c.height,r.width=c.width,t.rows=c.height,t.columns=c.width;const l=r.getContext("2d");l.drawImage(this,0,0);const f=l.getImageData(0,0,c.width,c.height),u=new Date().getTime();t.pixelData=new Uint8Array(f.data.buffer),t.imageData=f,t.decodeTimeInMS=u-n;const d=X5(t.pixelData);t.smallestPixelValue=d.min,t.largestPixelValue=d.max,t.pixelDataLength=t.pixelData.length,o(t)},c.onerror=function(l){a(l)},s.readAsBinaryString===void 0?c.src=`data:image/jpeg;base64,${window.btoa(f3e(s.result))}`:c.src=`data:image/jpeg;base64,${window.btoa(s.result)}`},s.onerror=c=>{a(c)}})}function zo(t,e,r,n,i){const o={...n};delete o.loader,delete o.streamingData;const a=il(),s=o.priority||void 0;return o.transferPixelData&&r.buffer,a.executeTask("dicomImageLoader","decodeTask",{imageFrame:t,transferSyntax:e,pixelData:r,options:o,decodeConfig:i},{priority:s,requestType:o==null?void 0:o.requestType})}function h3e(t,e,r,n,i={},o){switch(e){case"1.2.840.10008.1.2":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.1":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.2":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.1.99":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.5":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.50":return t.bitsAllocated===8&&(t.samplesPerPixel===3||t.samplesPerPixel===4)?$B(t,r,n):zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.51":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.57":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.70":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.80":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.81":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.90":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.91":return zo(t,e,r,i,o);case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":return zo(t,e,r,i,o)}return Promise.reject(new Error(`No decoder for transfer syntax ${e}`))}function jB(t){const e=mt("imagePixelModule",t);return{samplesPerPixel:e.samplesPerPixel,photometricInterpretation:e.photometricInterpretation,planarConfiguration:e.planarConfiguration,rows:e.rows,columns:e.columns,bitsAllocated:e.bitsAllocated,bitsStored:e.bitsStored,pixelRepresentation:e.pixelRepresentation,smallestPixelValue:e.smallestPixelValue,largestPixelValue:e.largestPixelValue,redPaletteColorLookupTableDescriptor:e.redPaletteColorLookupTableDescriptor,greenPaletteColorLookupTableDescriptor:e.greenPaletteColorLookupTableDescriptor,bluePaletteColorLookupTableDescriptor:e.bluePaletteColorLookupTableDescriptor,redPaletteColorLookupTableData:e.redPaletteColorLookupTableData,greenPaletteColorLookupTableData:e.greenPaletteColorLookupTableData,bluePaletteColorLookupTableData:e.bluePaletteColorLookupTableData,pixelData:void 0,imageId:t}}function g3e(t,e){const r=t.get("modalityLutModule",e)||{},n=t.get("generalSeriesModule",e)||{},{modality:i}=n,o={rescaleSlope:r.rescaleSlope,rescaleIntercept:r.rescaleIntercept,modality:i},a=t.get("scalingModule",e)||{};return{...o,...i==="PT"&&{suvbw:a.suvbw},...i==="RTDOSE"&&{doseGridScaling:a.DoseGridScaling,doseSummation:a.DoseSummation,doseType:a.DoseType,doseUnit:a.DoseUnit}}}function dE(t){return t==="RGB"||t==="PALETTE COLOR"||t==="YBR_FULL"||t==="YBR_FULL_422"||t==="YBR_PARTIAL_422"||t==="YBR_PARTIAL_420"||t==="YBR_RCT"||t==="YBR_ICT"}function p3e(t,e){const r=t.length/4;let n=0,i=0;for(let o=0;o=0?e<=255?r=Uint8Array:e<=65535?r=Uint16Array:e<=4294967295&&(r=Uint32Array):t>=-128&&e<=127?r=Int8Array:t>=-32768&&e<=32767&&(r=Int16Array)),r||Float32Array}function v3e(t,e,r){return hE(t,e)===r}function y3e(t){const e=t.smallestPixelValue,r=t.largestPixelValue,n=hE(e,r);if(n){const i=new n(t.pixelData);t.pixelData=i}else throw new Error("Could not apply a typed array to the pixel data")}let _b="";function Y5(t,e,r,n={}){const i=n.useRGBA;if(n.preScale={enabled:n.preScale&&n.preScale.enabled!==void 0?n.preScale.enabled:!0},!(e!=null&&e.length))return Promise.reject(new Error("The pixel data is missing"));const{MetadataModules:o}=ja,a=document.createElement("canvas"),s=jB(t);if(s.decodeLevel=n.decodeLevel,n.allowFloatRendering=aT(),n.preScale.enabled){const u=g3e(rL,t);u&&(n.preScale={...n.preScale,scalingParameters:u})}const{decodeConfig:c}=V1();Object.keys(s).forEach(u=>{(typeof s[u]=="function"||s[u]instanceof Promise)&&delete s[u]});const l=h3e(s,r,e,a,n,c),f=dE(s.photometricInterpretation);return new Promise((u,d)=>{l.then(function(h){let g=!1;if(n.targetBuffer&&n.targetBuffer.type&&!f){const{arrayBuffer:T,type:E,offset:D=0,length:b}=n.targetBuffer,I=h.pixelDataLength,P=D,M=b??I-P,L={Uint8Array,Uint16Array,Int16Array,Float32Array,Uint32Array};if(M!==h.pixelDataLength)throw new Error(`target array for image does not have the same length (${M}) as the decoded image length (${h.pixelDataLength}).`);const V=L[E],G=T?new V(T,P,M):new V(h.pixelData);if(M!==h.pixelDataLength)throw new Error("target array for image does not have the same length as the decoded image length.");h.pixelData=G,g=!0}g||y3e(h);const p=mt(o.IMAGE_PLANE,t)||{},v=mt(o.VOI_LUT,t)||{},y=mt(o.MODALITY_LUT,t)||{},m=mt(o.SOP_COMMON,t)||{},w=mt(o.CALIBRATION,t)||{},{rows:x,columns:C}=h;if(f){if(u3e(h)){a.height=h.rows,a.width=h.columns;let D=a.getContext("2d").createImageData(h.columns,h.rows);i||(D={...D,data:new Uint8ClampedArray(3*h.columns*h.rows)}),zB(h,D.data,i),h.imageData=D,h.pixelData=D.data,h.pixelDataLength=D.data.length}else if(!i&&h.pixelDataLength===4*x*C){const E=new Uint8Array(h.pixelData.length/4*3);h.pixelData=p3e(h.pixelData,E),h.pixelDataLength=h.pixelData.length}const T=X5(h.pixelData);h.smallestPixelValue=T.min,h.largestPixelValue=T.max}const S=tc.createImageVoxelManager({scalarData:h.pixelData,width:h.columns,height:h.rows,numberOfComponents:h.samplesPerPixel}),_={imageId:t,dataType:h.pixelData.constructor.name,color:f,calibration:w,columnPixelSpacing:p.columnPixelSpacing,columns:h.columns,height:h.rows,preScale:h.preScale,intercept:y.rescaleIntercept?y.rescaleIntercept:0,slope:y.rescaleSlope?y.rescaleSlope:1,invert:h.photometricInterpretation==="MONOCHROME1",minPixelValue:h.smallestPixelValue,maxPixelValue:h.largestPixelValue,rowPixelSpacing:p.rowPixelSpacing,rows:h.rows,sizeInBytes:h.pixelData.byteLength,width:h.columns,windowCenter:v.windowCenter?v.windowCenter[0]:void 0,windowWidth:v.windowWidth?v.windowWidth[0]:void 0,voiLUTFunction:v.voiLUTFunction?v.voiLUTFunction:void 0,decodeTimeInMS:h.decodeTimeInMS,floatPixelData:void 0,imageFrame:h,voxelManager:S,rgba:f&&i,getPixelData:()=>h.pixelData,getCanvas:void 0,numberOfComponents:h.samplesPerPixel};if(_.color&&(_.getCanvas=function(){if(_b===t)return a;const T=_.columns,E=_.rows;a.height=E,a.width=T;const D=a.getContext("2d"),b=D.createImageData(T,E),I=h.pixelData;if(I.length===T*E*4)for(let P=0;P0&&m3e(m.sopClassUID)&&(_.modalityLUT=y.modalityLUTSequence[0]),v.voiLUTSequence&&v.voiLUTSequence.length>0&&(_.voiLUT=v.voiLUTSequence[0]),_.color&&(_.windowWidth=256,_.windowCenter=128),_.windowCenter===void 0||_.windowWidth===void 0){const T=_.imageFrame.smallestPixelValue,E=_.imageFrame.largestPixelValue;_.windowWidth=E-T,_.windowCenter=(E+T)/2}u(_)},d)})}const{ImageQualityStatus:HB}=ja;function w3e(t,e){t.decache=function(){const r=k1(e);T0.unload(r.url)}}function KB(t,e,r=0,n,i,o){const a=new Date().getTime(),s={cancelFn:void 0,promise:void 0};return s.promise=new Promise((c,l)=>{t.then(f=>{const u=fE(f,r),d=f.string("x00020010"),h=new Date().getTime(),g=Y5(e,u,d,i);w3e(s,e),g.then(p=>{p=p,p.data=f,p.sharedCacheKey=n;const v=new Date().getTime();p.loadTimeInMS=h-a,p.totalTimeInMS=v-a,p.imageQualityStatus=HB.FULL_RESOLUTION,o!==void 0&&o.imageDoneCallback!==void 0&&o.imageDoneCallback(p),c(p)},function(p){l({error:p,dataSet:f})})},function(f){l({error:f})})}),s}function x3e(t,e,r=0,n,i){const o=new Date().getTime();return{promise:new Promise((s,c)=>{const l=new Date().getTime();let f;try{const u=fE(t,r),d=t.string("x00020010");f=Y5(e,u,d,i)}catch(u){c({error:u,dataSet:t});return}f.then(u=>{u=u,u.data=t;const d=new Date().getTime();u.loadTimeInMS=l-o,u.totalTimeInMS=d-o,u.imageQualityStatus=HB.FULL_RESOLUTION,s(u)},c)}),cancelFn:void 0}}function qB(t){if(t==="dicomweb"||t==="wadouri")return H5;if(t==="dicomfile")return WB}function k2(t,e={}){const r=k1(t);e=Object.assign({},e),delete e.loader;const n=qB(r.scheme);if(T0.isLoaded(r.url)){const o=T0.get(r.url,n,t);return x3e(o,t,r.pixelDataFrame,r.url,e)}const i=T0.load(r.url,n,t);return KB(i,t,r.frame,r.url,e)}function XB(){b2("dicomweb",k2),b2("wadouri",k2),b2("dicomfile",k2),ah(uE)}const C3e={getImagePixelModule:EB,getLUTs:iS,getModalityLUTOutputPixelRepresentation:DB,getNumberValues:_s,metaDataProvider:uE,metadataForDataset:VB},S3e={metaData:C3e,dataSetCacheManager:T0,fileManager:FB,getEncapsulatedImageFrame:UB,getUncompressedImageFrame:GB,loadFileRequest:WB,loadImageFromPromise:KB,getLoaderForScheme:qB,getPixelData:fE,loadImage:k2,parseImageId:k1,unpackBinaryFrame:BB,register:XB};function en(t,e,r){return e=e||0,!t||!t.Value||Array.isArray(t.Value)&&t.Value.length<=e?r:t.Value[e]}function _3e(t,e,r){const n=en(t,e,r);if(n!==void 0)return parseFloat(String(n))}function Kn(t,e){const r=en(t,e);if(r!==void 0)return parseFloat(r)}function ho(t,e){if(!t||!t.Value||!Array.isArray(t.Value)||e&&t.Value.length>s&1}e.push({rows:Kn(t[`${n}0010`]),columns:Kn(t[`${n}0011`]),type:en(t[`${n}0040`]),x:Kn(t[`${n}0050`],1)-1,y:Kn(t[`${n}0050`],0)-1,pixelData:o,description:en(t[`${n}0022`]),label:en(t[`${n}1500`]),roiArea:en(t[`${n}1301`]),roiMean:en(t[`${n}1302`]),roiStandardDeviation:en(t[`${n}1303`])})}return{overlays:e}}function J5(t){const e=t.indexOf(":");return t.substring(e+1)}function E0(t,e=!0){return t&&t.Value?t.Value[0]&&e?t.Value[0]:t.Value:t}function YB(t,e,r){const n=(e?Object.values(e[0]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object"),i=(t?Object.values(t[r-1]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object");return{shared:n,perFrame:i}}function JB(t){let{52009230:e,52009229:r,"00280008":n,...i}=t;return e=E0(e,!1),r=E0(r,!1),n=E0(n),{PerFrameFunctionalGroupsSequence:e,SharedFunctionalGroupsSequence:r,NumberOfFrames:n,rest:i}}function E3e(t,e){const{PerFrameFunctionalGroupsSequence:r,SharedFunctionalGroupsSequence:n,NumberOfFrames:i,rest:o}=JB(e);if(r||i>1){const{shared:a,perFrame:s}=YB(r,n,t),c=Object.assign(e,{frameNumber:t});return[...a,...s].forEach(l=>{Object.entries(l).forEach(([f,u])=>{c[f]=u})}),Object.assign(o,{"00280008":i},c)}return e}let F1=[],Sy={};function ZB(t){const e=t.indexOf("/frames/")+8,r=t.slice(0,e),n=parseInt(t.slice(e),10);return{metadata:F1[`${r}1`],frame:n}}function D3e(t){const e=J5(t);return ZB(e)}function b3e(t){if(t[52009230]!==void 0||t[52009229]!==void 0)return!0;const e=en(t["00280008"]);return e&&e>1}function I3e(t,e){const r=J5(t);Object.defineProperty(e,"isMultiframe",{value:b3e(e),enumerable:!1}),F1[r]=e}function O3e(t){const e=J5(t),r=F1[e];if(r&&!(r!=null&&r.isMultiframe))return r;const n=Sy[e];if(n)return n;const i=ZB(e);if(!i||!i.metadata)return;const{metadata:o,frame:a}=i;if(o){const s=E3e(a,o);return Sy[e]=s,s}}function M3e(t){const e=J5(t);F1[e]=void 0,Sy[e]=void 0}function P3e(){F1=[],Sy={}}const gE={add:I3e,get:O3e,remove:M3e,purge:P3e};function QB(t){return en(t["00080060"]).includes("NM")}function pE(t,e){const r=E0(t["00080008"],!1);if(r)return r[e]}function R3e(t){let e;const r=pE(t,2);if(r&&bh(r)){const n=E0(t["00540022"]);n&&(e=ho(n["00200037"],6))}return e}function L3e(t){let e;const r=pE(t,2);if(r&&bh(r)){const n=E0(t["00540022"]);n&&(e=ho(n["00200032"],3))}return e}function Tb(t){let e=ho(t["00200037"],6);return!e&&QB(t)&&(e=R3e(t)),e}function Eb(t){let e=ho(t["00200032"],3);return!e&&QB(t)&&(e=L3e(t)),e}function uo(t,e){const r=ho(t[e]);return r?r[0]:null}function A3e(t){var e;return(e=t==null?void 0:t.Value)!=null&&e.length?Array.isArray(t.Value)?t.Value:typeof t.Value=="object"?(console.warn("Warning: Value should be an array, but an object was found. Encapsulating the object in an array."),[t.Value]):[]:[]}function Db(t){const e=A3e(t["00186011"]);return!e||!e.length?null:e.map(n=>{const i=uo(n,"0018602C"),o=uo(n,"0018602E"),a=uo(n,"00186024"),s=uo(n,"00186026"),c=uo(n,"0018601A"),l=uo(n,"0018601E"),f=uo(n,"00186018"),u=uo(n,"0018601C"),d=uo(n,"00186020"),h=uo(n,"00186022"),g=uo(n,"0018602A"),p=uo(n,"00186028"),v=uo(n,"00186012"),y=uo(n,"00186014"),m=uo(n,"00186016"),w=uo(n,"00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function mE(t,e){const{MetadataModules:r}=ja;if(t===r.MULTIFRAME){const{metadata:i,frame:o}=D3e(e);if(!i)return;const{PerFrameFunctionalGroupsSequence:a,SharedFunctionalGroupsSequence:s,NumberOfFrames:c}=JB(i);if(a||c>1){const{shared:l,perFrame:f}=YB(a,s,o);return{NumberOfFrames:c,PerFrameFunctionalInformation:f,SharedFunctionalInformation:l}}return{NumberOfFrames:c}}const n=gE.get(e);if(n){if(t===r.GENERAL_STUDY)return{studyDescription:en(n["00081030"]),studyDate:Tr.parseDA(en(n["00080020"])),studyTime:Tr.parseTM(en(n["00080030"],0,"")),accessionNumber:en(n["00080050"])};if(t===r.GENERAL_SERIES)return{modality:en(n["00080060"]),seriesInstanceUID:en(n["0020000E"]),seriesDescription:en(n["0008103E"]),seriesNumber:Kn(n["00200011"]),studyInstanceUID:en(n["0020000D"]),seriesDate:Tr.parseDA(en(n["00080021"])),seriesTime:Tr.parseTM(en(n["00080031"],0,"")),acquisitionDate:Tr.parseDA(en(n["00080022"])),acquisitionTime:Tr.parseTM(en(n["00080032"],0,""))};if(t===r.GENERAL_IMAGE)return{sopInstanceUID:en(n["00080018"]),instanceNumber:Kn(n["00200013"]),lossyImageCompression:en(n["00282110"]),lossyImageCompressionRatio:Kn(n["00282112"]),lossyImageCompressionMethod:en(n["00282114"])};if(t===r.PATIENT)return{patientID:en(n["00100020"]),patientName:en(n["00100010"])};if(t===r.PATIENT_STUDY)return{patientAge:Kn(n["00101010"]),patientSize:Kn(n["00101020"]),patientSex:en(n["00100040"]),patientWeight:Kn(n["00101030"])};if(t===r.NM_MULTIFRAME_GEOMETRY){const i=en(n["00080060"]),o=pE(n,2);return{modality:i,imageType:en(n["00080008"]),imageSubType:o,imageOrientationPatient:Tb(n),imagePositionPatient:Eb(n),sliceThickness:Kn(n["00180050"]),spacingBetweenSlices:Kn(n["00180088"]),pixelSpacing:ho(n["00280030"],2),numberOfFrames:Kn(n["00280008"]),isNMReconstructable:bh(o)&&i.includes("NM")}}if(t===r.IMAGE_PLANE){let i=Tb(n),o=Eb(n);const a=ho(n["00280030"],2);let s=null,c=null,l=null,f=null,u=!1;return a?(c=a[0],s=a[1]):(u=!0,c=1,s=1),i?(l=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],f=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]):(l=[1,0,0],f=[0,1,0],u=!0,i=[...l,...f]),o||(o=[0,0,0],u=!0),{frameOfReferenceUID:en(n["00200052"]),rows:Kn(n["00280010"]),columns:Kn(n["00280011"]),imageOrientationPatient:i,rowCosines:l,columnCosines:f,imagePositionPatient:o,sliceThickness:Kn(n["00180050"]),sliceLocation:Kn(n["00201041"]),pixelSpacing:a,rowPixelSpacing:c,columnPixelSpacing:s,usingDefaultValues:u}}if(t===r.ULTRASOUND_ENHANCED_REGION)return Db(n);if(t===r.CALIBRATION&&en(n["00080060"])==="US")return{sequenceOfUltrasoundRegions:Db(n)};if(t===r.IMAGE_URL)return N3e(e,n);if(t===r.CINE)return k3e(e,n);if(t===r.IMAGE_PIXEL)return{samplesPerPixel:Kn(n["00280002"]),photometricInterpretation:en(n["00280004"]),rows:Kn(n["00280010"]),columns:Kn(n["00280011"]),bitsAllocated:Kn(n["00280100"]),bitsStored:Kn(n["00280101"]),highBit:en(n["00280102"]),pixelRepresentation:Kn(n["00280103"]),planarConfiguration:Kn(n["00280006"]),pixelAspectRatio:en(n["00280034"]),smallestPixelValue:Kn(n["00280106"]),largestPixelValue:Kn(n["00280107"]),redPaletteColorLookupTableDescriptor:ho(n["00281101"]),greenPaletteColorLookupTableDescriptor:ho(n["00281102"]),bluePaletteColorLookupTableDescriptor:ho(n["00281103"]),redPaletteColorLookupTableData:ho(n["00281201"]),greenPaletteColorLookupTableData:ho(n["00281202"]),bluePaletteColorLookupTableData:ho(n["00281203"])};if(t===r.VOI_LUT)return{windowCenter:ho(n["00281050"],1),windowWidth:ho(n["00281051"],1),voiLUTFunction:en(n["00281056"])};if(t===r.MODALITY_LUT)return{rescaleIntercept:Kn(n["00281052"]),rescaleSlope:Kn(n["00281053"]),rescaleType:en(n["00281054"])};if(t===r.SOP_COMMON)return{sopClassUID:en(n["00080016"]),sopInstanceUID:en(n["00080018"])};if(t===r.PET_ISOTOPE){const i=en(n["00540016"]);return i===void 0?void 0:{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:Tr.parseTM(en(i["00181072"],0,"")),radiopharmaceuticalStartDateTime:en(i["00181078"],0,""),radionuclideTotalDose:Kn(i["00181074"]),radionuclideHalfLife:Kn(i["00181075"])}}}if(t===r.OVERLAY_PLANE)return T3e(n);if(t==="transferSyntax")return eG(e,n);if(t===r.PET_SERIES)return{correctedImage:en(n["00280051"]),units:en(n["00541001"]),decayCorrection:en(n["00541102"])};if(t===r.PET_IMAGE)return{frameReferenceTime:Kn(n["00541300"]),actualFrameDuration:Kn(n["00181242"])};if(t==="instance")return NB(e,mE,kB)}}function N3e(t,e){const{transferSyntaxUID:r}=eG(t,e),n=KA(r),i=t.substring(7),o=i.replace("/frames/","/thumbnail/");let a=i.replace("/frames/","/rendered/");return n&&(a=a.replace("/rendered/1","/rendered")),{isVideo:n,rendered:a,thumbnail:o}}function k3e(t,e){return{cineRate:en(e["00180040"]),numberOfFrames:Kn(e["00280008"])}}function eG(t,e){return{transferSyntaxUID:en(e["00020010"])||en(e["00083002"])}}function V3e(t,e,r={},n={}){const i=V1(),{retrieveOptions:o={},streamingData:a}=n,s=a.chunkSize||U3e(e,o,"chunkSize")||65536,c=f=>{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}else console.warn("rangeRequest:Caught",f)};return new Promise(async(f,u)=>{const d=Object.assign({},r);Object.keys(d).forEach(function(h){(d[h]===null||d[h]===void 0)&&delete d[h]});try{a.encodedData||(a.chunkSize=s,a.rangesFetched=0);const h=B3e(a,o),{encodedData:g,responseHeaders:p}=await F3e(t,d,h,a),v=p.get("content-type"),{totalBytes:y}=a,m=y===g.byteLength,w=aE(v,g,{isPartial:!0}),x=sE(o,m||w.extractDone);f({...w,imageQualityStatus:x,percentComplete:w.extractDone?100:s*100/y})}catch(h){c(h),console.error(h),u(h)}})}async function F3e(t,e,r,n){r&&(e=Object.assign(e,{Range:`bytes=${r[0]}-${r[1]}`}));let{encodedData:i}=n;if(r[1]&&(i==null?void 0:i.byteLength)>r[1])return n;const o=await fetch(t,{headers:e,signal:void 0}),a=await o.arrayBuffer(),s=new Uint8Array(a),{status:c}=o;let l;i?(l=new Uint8Array(i.length+s.length),l.set(i,0),l.set(s,i.length),n.rangesFetched=1):(l=new Uint8Array(s.length),l.set(s,0),n.rangesFetched++),n.encodedData=i=l,n.responseHeaders=o.headers;const f=o.headers.get("Content-Range");return f?n.totalBytes=Number(f.split("/")[1]):c!==206||!r?n.totalBytes=i==null?void 0:i.byteLength:r[1]===""||(i==null?void 0:i.length)r-i?[(n==null?void 0:n.byteLength)||0,""]:[(n==null?void 0:n.byteLength)||0,i*(o+1)-1]}function vE(t,e,r="application/octet-stream",n){const{streamingData:i,retrieveOptions:o={}}=n||{},a={Accept:r};let s=o.urlArguments?`${t}${t.indexOf("?")===-1?"?":"&"}${o.urlArguments}`:t;if(o.framesPath&&(s=s.replace("/frames/",o.framesPath)),(i==null?void 0:i.url)!==s&&(n.streamingData={url:s}),o.rangeIndex!==void 0)return V3e(s,e,a,n);if(o.streaming)return OB(s,e,a,n);const c=H5(s,e,a),{xhr:l}=c;return c.then(function(f){const u=l.getResponseHeader("Content-Type")||"application/octet-stream",d=aE(u,new Uint8Array(f));return d.imageQualityStatus=sE(o,!0),d})}const{ProgressiveIterator:bb}=Mn,{ImageQualityStatus:Ib}=ja,G3e=new Set(["3.2.840.10008.1.2.4.96","1.2.840.10008.1.2.4.202","1.2.840.10008.1.2.4.203"]);function W3e(t){const e="1.2.840.10008.1.2";if(!t)return e;const r=t.split(";"),n={};r.forEach(o=>{const a=o.split("=");if(a.length!==2)return;const s=a[1].trim().replace(/"/g,"");n[a[0].trim()]=s});const i={"image/jpeg":"1.2.840.10008.1.2.4.50","image/x-dicom-rle":"1.2.840.10008.1.2.5","image/x-jls":"1.2.840.10008.1.2.4.80","image/jls":"1.2.840.10008.1.2.4.80","image/jll":"1.2.840.10008.1.2.4.70","image/jp2":"1.2.840.10008.1.2.4.90","image/jpx":"1.2.840.10008.1.2.4.92","image/jphc":"3.2.840.10008.1.2.4.96","image/jxl":"1.2.840.10008.1.2.4.140"};return n["transfer-syntax"]?n["transfer-syntax"]:t&&!Object.keys(n).length&&i[t]?i[t]:n.type&&i[n.type]?i[n.type]:i[t]?i[t]:e}function z3e(){return x1}const $3e="multipart/related; type=application/octet-stream; transfer-syntax=*";function tG(t,e={}){const r=z3e(),n=new Date().getTime(),i=new bb("decompress");async function o(f,u,d){i.generate(async h=>{var v;const g=bb.as(vE(f,u,d,e));let p=10;for await(const y of g){const{pixelData:m,imageQualityStatus:w=Ib.FULL_RESOLUTION,percentComplete:x,done:C=!0,extractDone:S=!0}=y,_=W3e(y.contentType);if(!S&&!G3e.has(_))continue;const T=y.decodeLevel??(w===Ib.FULL_RESOLUTION?0:j3e(x,(v=e.retrieveOptions)==null?void 0:v.decodeLevel));if(!(!C&&p<=T))try{const E={...e,decodeLevel:T},D=await Y5(u,m,_,E),b=new Date().getTime();D.loadTimeInMS=b-n,D.transferSyntaxUID=_,D.imageQualityStatus=w,h.add(D,C),p=T}catch(E){if(S)throw console.warn("Couldn't decode",E),E}}})}const a=e.requestType||hn.Interaction,s=e.additionalDetails||{imageId:t},c=e.priority===void 0?5:e.priority,l=t.substring(7);return r.addRequest(o.bind(this,l,t,$3e),a,s,c),{promise:i.getDonePromise(),cancelFn:void 0}}function j3e(t,e=4){const r=t/100-.02;return r>1/4?Math.min(e,0):r>1/16?Math.min(e,1):r>1/64?Math.min(e,2):Math.min(e,3)}function nG(){b2("wadors",tG),ah(mE)}const H3e={getNumberString:_3e,getNumberValue:Kn,getNumberValues:ho,getValue:en,metaDataProvider:mE},K3e={metaData:H3e,findIndexOfString:aS,getPixelData:vE,loadImage:tG,metaDataManager:gE,register:nG};function q3e(){nG(),XB()}const X3e=()=>new Worker(new URL("/static/dv3d/assets/decodeImageFrameWorker-DhtpjVX0.js",import.meta.url),{type:"module"});function rG(t={}){IB(t),q3e();const e=il(),r=(t==null?void 0:t.maxWebWorkers)||Y3e();e.registerWorker("dicomImageLoader",X3e,{maxWorkerInstances:r})}function Y3e(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.max(1,Math.floor(navigator.hardwareConcurrency/2)):1}function J3e(t,e){if(e=e||t.transferSyntax,t.bitsAllocated===8&&e==="1.2.840.10008.1.2.4.50"&&(t.samplesPerPixel===3||t.samplesPerPixel===4))return!0}const Z3e={IMPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2",EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1",DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1.99",EXPLICIT_VR_BIG_ENDIAN:"1.2.840.10008.1.2.2",JPEG_BASELINE_PROCESS_1:"1.2.840.10008.1.2.4.50",JPEG_EXTENDED_PROCESS_2_4:"1.2.840.10008.1.2.4.51",JPEG_EXTENDED_PROCESSES_3_5:"1.2.840.10008.1.2.4.52",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_6_8:"1.2.840.10008.1.2.4.53",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_7_9:"1.2.840.10008.1.2.4.54",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_10_12:"1.2.840.10008.1.2.4.55",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_11_13:"1.2.840.10008.1.2.4.56",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_14:"1.2.840.10008.1.2.4.57",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_15:"1.2.840.10008.1.2.4.58",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_16_18:"1.2.840.10008.1.2.4.59",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_17_19:"1.2.840.10008.1.2.4.60",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_20_22:"1.2.840.10008.1.2.4.61",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_21_23:"1.2.840.10008.1.2.4.62",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_24_26:"1.2.840.10008.1.2.4.63",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_25_27:"1.2.840.10008.1.2.4.64",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_28:"1.2.840.10008.1.2.4.65",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_29:"1.2.840.10008.1.2.4.66",JPEG_LOSSLESS_NONHIERARCHICAL_FIRST_ORDER_PREDICTION_PROCESS_14:"1.2.840.10008.1.2.4.70",JPEG_LS_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.80",JPEG_LS_LOSSY_NEAR_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.81",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.90",JPEG_2000_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.91",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.92",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.93",JPIP_REFERENCED:"1.2.840.10008.1.2.4.94",JPIP_REFERENCED_DEFLATE:"1.2.840.10008.1.2.4.95",MPEG2_MAIN_PROFILE_MAIN_LEVEL:"1.2.840.10008.1.2.4.100",MPEG4_AVC_H264_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.101",MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.102",MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO:"1.2.840.10008.1.2.4.103",MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO:"1.2.840.10008.1.2.4.104",JPIP_LOSSLESS:"1.2.840.10008.1.2.4.96",JPIP_PART2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.97",RFC_2557_MIME_ENCAPSULATION:"1.2.840.10008.1.2.6.1",JPEG_XR_IMAGE_COMPRESSION:"1.2.840.10008.1.2.6.2",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.90R",JPEG_2000_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.91R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.92R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.93R"},Q3e=Object.freeze(Object.defineProperty({__proto__:null,transferSyntaxes:Z3e},Symbol.toStringTag,{value:"Module"}));function exe(t,e){const{rows:r,columns:n,data:i}=t,{rows:o,columns:a,data:s}=e,c=[],l=[],f=[];for(let u=0;u>8&255}async function rxe(t,e){if(t.bitsAllocated===16){let r=e.buffer,n=e.byteOffset;const i=e.length;n%2&&(r=r.slice(n),n=0),t.pixelRepresentation===0?t.pixelData=new Uint16Array(r,n,i/2):t.pixelData=new Int16Array(r,n,i/2);for(let o=0;o=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[d++];for(let v=0;v<-g+1&&f{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(R,U){a=R,s=U});var c=Object.assign({},o),l="./this.program",f=(R,U)=>{throw U},u=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function p(R){return o.locateFile?o.locateFile(R,g):g+R}var v,y,m;if(h){var w=Js,x=Js;d?g=x.dirname(g)+"/":g=__dirname+"/",v=(R,U)=>(R=se(R)?new URL(R):x.normalize(R),w.readFileSync(R,U?void 0:"utf8")),m=R=>{var U=v(R,!0);return U.buffer||(U=new Uint8Array(U)),U},y=(R,U,q)=>{R=se(R)?new URL(R):x.normalize(R),w.readFile(R,function(le,he){le?q(le):U(he.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(R){if(!(R instanceof wt))throw R}),process.on("unhandledRejection",function(R){throw R}),f=(R,U)=>{throw process.exitCode=R,U},o.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",v=R=>{var U=new XMLHttpRequest;return U.open("GET",R,!1),U.send(null),U.responseText},d&&(m=R=>{var U=new XMLHttpRequest;return U.open("GET",R,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),y=(R,U,q)=>{var le=new XMLHttpRequest;le.open("GET",R,!0),le.responseType="arraybuffer",le.onload=()=>{if(le.status==200||le.status==0&&le.response){U(le.response);return}q()},le.onerror=q,le.send(null)});var C=o.print||console.log.bind(console),S=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&(f=o.quit);var _;o.wasmBinary&&(_=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&ie("no native wasm support detected");var T,E=!1;function D(R,U){R||ie(U)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function I(R,U,q){for(var le=U+q,he=U;R[he]&&!(he>=le);)++he;if(he-U>16&&R.buffer&&b)return b.decode(R.subarray(U,he));for(var ve="";U>10,56320|Je&1023)}}return ve}function P(R,U){return R?I(k,R,U):""}function M(R,U,q,le){if(!(le>0))return 0;for(var he=q,ve=q+le-1,Te=0;Te=55296&&be<=57343){var ke=R.charCodeAt(++Te);be=65536+((be&1023)<<10)|ke&1023}if(be<=127){if(q>=ve)break;U[q++]=be}else if(be<=2047){if(q+1>=ve)break;U[q++]=192|be>>6,U[q++]=128|be&63}else if(be<=65535){if(q+2>=ve)break;U[q++]=224|be>>12,U[q++]=128|be>>6&63,U[q++]=128|be&63}else{if(q+3>=ve)break;U[q++]=240|be>>18,U[q++]=128|be>>12&63,U[q++]=128|be>>6&63,U[q++]=128|be&63}}return U[q]=0,q-he}function L(R,U,q){return M(R,k,U,q)}function V(R){for(var U=0,q=0;q=55296&&le<=57343?(U+=4,++q):U+=3}return U}var G,A,k,F,j,Y,re,ue,ce;function pe(R){G=R,o.HEAP8=A=new Int8Array(R),o.HEAP16=F=new Int16Array(R),o.HEAP32=Y=new Int32Array(R),o.HEAPU8=k=new Uint8Array(R),o.HEAPU16=j=new Uint16Array(R),o.HEAPU32=re=new Uint32Array(R),o.HEAPF32=ue=new Float32Array(R),o.HEAPF64=ce=new Float64Array(R)}o.INITIAL_MEMORY;var Ee,Oe=[],Se=[],B=[];function O(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)K(o.preRun.shift());gt(Oe)}function z(){gt(Se)}function W(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)ee(o.postRun.shift());gt(B)}function K(R){Oe.unshift(R)}function Z(R){Se.unshift(R)}function ee(R){B.unshift(R)}var xe=0,De=null;function Ne(R){xe++,o.monitorRunDependencies&&o.monitorRunDependencies(xe)}function ze(R){if(xe--,o.monitorRunDependencies&&o.monitorRunDependencies(xe),xe==0&&De){var U=De;De=null,U()}}function ie(R){o.onAbort&&o.onAbort(R),R="Aborted("+R+")",S(R),E=!0,R+=". Build with -sASSERTIONS for more info.";var U=new WebAssembly.RuntimeError(R);throw s(U),U}var ae="data:application/octet-stream;base64,";function we(R){return R.startsWith(ae)}function se(R){return R.startsWith("file://")}var ge;ge="libjpegturbowasm_decode.wasm",we(ge)||(ge=p(ge));function Fe(R){try{if(R==ge&&_)return new Uint8Array(_);if(m)return m(R);throw"both async and sync fetching of the wasm failed"}catch(U){ie(U)}}function oe(){if(!_&&(u||d)){if(typeof fetch=="function"&&!se(ge))return fetch(ge,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+ge+"'";return R.arrayBuffer()}).catch(function(){return Fe(ge)});if(y)return new Promise(function(R,U){y(ge,function(q){R(new Uint8Array(q))},U)})}return Promise.resolve().then(function(){return Fe(ge)})}function ht(){var R={a:qe};function U(Te,be){var ke=Te.exports;o.asm=ke,T=o.asm.K,pe(T.buffer),Ee=o.asm.M,Z(o.asm.L),ze()}Ne();function q(Te){U(Te.instance)}function le(Te){return oe().then(function(be){return WebAssembly.instantiate(be,R)}).then(function(be){return be}).then(Te,function(be){S("failed to asynchronously prepare wasm: "+be),ie(be)})}function he(){return!_&&typeof WebAssembly.instantiateStreaming=="function"&&!we(ge)&&!se(ge)&&!h&&typeof fetch=="function"?fetch(ge,{credentials:"same-origin"}).then(function(Te){var be=WebAssembly.instantiateStreaming(Te,R);return be.then(q,function(ke){return S("wasm streaming compile failed: "+ke),S("falling back to ArrayBuffer instantiation"),le(q)})}):le(q)}if(o.instantiateWasm)try{var ve=o.instantiateWasm(R,U);return ve}catch(Te){S("Module.instantiateWasm callback failed with error: "+Te),s(Te)}return he().catch(s),{}}function wt(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function gt(R){for(;R.length>0;)R.shift()(o)}function Ie(R){this.excPtr=R,this.ptr=R-24,this.set_type=function(U){re[this.ptr+4>>2]=U},this.get_type=function(){return re[this.ptr+4>>2]},this.set_destructor=function(U){re[this.ptr+8>>2]=U},this.get_destructor=function(){return re[this.ptr+8>>2]},this.set_refcount=function(U){Y[this.ptr>>2]=U},this.set_caught=function(U){U=U?1:0,A[this.ptr+12>>0]=U},this.get_caught=function(){return A[this.ptr+12>>0]!=0},this.set_rethrown=function(U){U=U?1:0,A[this.ptr+13>>0]=U},this.get_rethrown=function(){return A[this.ptr+13>>0]!=0},this.init=function(U,q){this.set_adjusted_ptr(0),this.set_type(U),this.set_destructor(q),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var U=Y[this.ptr>>2];Y[this.ptr>>2]=U+1},this.release_ref=function(){var U=Y[this.ptr>>2];return Y[this.ptr>>2]=U-1,U===1},this.set_adjusted_ptr=function(U){re[this.ptr+16>>2]=U},this.get_adjusted_ptr=function(){return re[this.ptr+16>>2]},this.get_exception_ptr=function(){var U=fe(this.get_type());if(U)return re[this.excPtr>>2];var q=this.get_adjusted_ptr();return q!==0?q:this.excPtr}}function $e(R,U,q){var le=new Ie(R);throw le.init(U,q),R}var tt={};function nt(R){for(;R.length;){var U=R.pop(),q=R.pop();q(U)}}function dt(R){return this.fromWireType(Y[R>>2])}var Lt={},xt={},Ft={},jt=48,Pn=57;function $n(R){if(R===void 0)return"_unknown";R=R.replace(/[^a-zA-Z0-9_]/g,"$");var U=R.charCodeAt(0);return U>=jt&&U<=Pn?"_"+R:R}function fn(R,U){return R=$n(R),new Function("body","return function "+R+`() { + See http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html for more information.`));const c=r.dataOffset,l=i*o*a;let f;if(n===8){if(f=c+e*l,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l))}else if(n===16){if(f=c+e*l*2,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*2))}else if(n===1){if(f=c+e*l*.125,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return BB(t.byteArray,f,l)}else if(n===32){if(f=c+e*l*4,f>=t.byteArray.length)throw new Error("frame exceeds size of pixelData");return new Uint8Array(t.byteArray.buffer.slice(f,f+l*4))}throw new Error("unsupported pixel format")}function WB(t){const e=k1(t),r=parseInt(e.url,10),n=FB.get(r);return new Promise((i,o)=>{const a=new FileReader;a.onload=s=>{const c=s.target.result;i(c)},a.onerror=o,a.readAsArrayBuffer(n)})}function fE(t,e=0){const r=t.elements.x7fe00010||t.elements.x7fe00008;return r?r.encapsulatedPixelData?UB(t,e):GB(t,e):null}function X5(t){let e=t[0],r=t[0],n;const i=t.length;for(let o=1;o{const s=new FileReader;s.readAsBinaryString===void 0?s.readAsArrayBuffer(i):s.readAsBinaryString(i),s.onload=function(){const c=new Image;c.onload=function(){r.height=c.height,r.width=c.width,t.rows=c.height,t.columns=c.width;const l=r.getContext("2d");l.drawImage(this,0,0);const f=l.getImageData(0,0,c.width,c.height),u=new Date().getTime();t.pixelData=new Uint8Array(f.data.buffer),t.imageData=f,t.decodeTimeInMS=u-n;const d=X5(t.pixelData);t.smallestPixelValue=d.min,t.largestPixelValue=d.max,t.pixelDataLength=t.pixelData.length,o(t)},c.onerror=function(l){a(l)},s.readAsBinaryString===void 0?c.src=`data:image/jpeg;base64,${window.btoa(f3e(s.result))}`:c.src=`data:image/jpeg;base64,${window.btoa(s.result)}`},s.onerror=c=>{a(c)}})}function zo(t,e,r,n,i){const o={...n};delete o.loader,delete o.streamingData;const a=il(),s=o.priority||void 0;return o.transferPixelData&&r.buffer,a.executeTask("dicomImageLoader","decodeTask",{imageFrame:t,transferSyntax:e,pixelData:r,options:o,decodeConfig:i},{priority:s,requestType:o==null?void 0:o.requestType})}function h3e(t,e,r,n,i={},o){switch(e){case"1.2.840.10008.1.2":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.1":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.2":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.1.99":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.5":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.50":return t.bitsAllocated===8&&(t.samplesPerPixel===3||t.samplesPerPixel===4)?$B(t,r,n):zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.51":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.57":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.70":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.80":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.81":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.90":return zo(t,e,r,i,o);case"1.2.840.10008.1.2.4.91":return zo(t,e,r,i,o);case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":return zo(t,e,r,i,o)}return Promise.reject(new Error(`No decoder for transfer syntax ${e}`))}function jB(t){const e=mt("imagePixelModule",t);return{samplesPerPixel:e.samplesPerPixel,photometricInterpretation:e.photometricInterpretation,planarConfiguration:e.planarConfiguration,rows:e.rows,columns:e.columns,bitsAllocated:e.bitsAllocated,bitsStored:e.bitsStored,pixelRepresentation:e.pixelRepresentation,smallestPixelValue:e.smallestPixelValue,largestPixelValue:e.largestPixelValue,redPaletteColorLookupTableDescriptor:e.redPaletteColorLookupTableDescriptor,greenPaletteColorLookupTableDescriptor:e.greenPaletteColorLookupTableDescriptor,bluePaletteColorLookupTableDescriptor:e.bluePaletteColorLookupTableDescriptor,redPaletteColorLookupTableData:e.redPaletteColorLookupTableData,greenPaletteColorLookupTableData:e.greenPaletteColorLookupTableData,bluePaletteColorLookupTableData:e.bluePaletteColorLookupTableData,pixelData:void 0,imageId:t}}function g3e(t,e){const r=t.get("modalityLutModule",e)||{},n=t.get("generalSeriesModule",e)||{},{modality:i}=n,o={rescaleSlope:r.rescaleSlope,rescaleIntercept:r.rescaleIntercept,modality:i},a=t.get("scalingModule",e)||{};return{...o,...i==="PT"&&{suvbw:a.suvbw},...i==="RTDOSE"&&{doseGridScaling:a.DoseGridScaling,doseSummation:a.DoseSummation,doseType:a.DoseType,doseUnit:a.DoseUnit}}}function dE(t){return t==="RGB"||t==="PALETTE COLOR"||t==="YBR_FULL"||t==="YBR_FULL_422"||t==="YBR_PARTIAL_422"||t==="YBR_PARTIAL_420"||t==="YBR_RCT"||t==="YBR_ICT"}function p3e(t,e){const r=t.length/4;let n=0,i=0;for(let o=0;o=0?e<=255?r=Uint8Array:e<=65535?r=Uint16Array:e<=4294967295&&(r=Uint32Array):t>=-128&&e<=127?r=Int8Array:t>=-32768&&e<=32767&&(r=Int16Array)),r||Float32Array}function v3e(t,e,r){return hE(t,e)===r}function y3e(t){const e=t.smallestPixelValue,r=t.largestPixelValue,n=hE(e,r);if(n){const i=new n(t.pixelData);t.pixelData=i}else throw new Error("Could not apply a typed array to the pixel data")}let _b="";function Y5(t,e,r,n={}){const i=n.useRGBA;if(n.preScale={enabled:n.preScale&&n.preScale.enabled!==void 0?n.preScale.enabled:!0},!(e!=null&&e.length))return Promise.reject(new Error("The pixel data is missing"));const{MetadataModules:o}=ja,a=document.createElement("canvas"),s=jB(t);if(s.decodeLevel=n.decodeLevel,n.allowFloatRendering=aT(),n.preScale.enabled){const u=g3e(rL,t);u&&(n.preScale={...n.preScale,scalingParameters:u})}const{decodeConfig:c}=V1();Object.keys(s).forEach(u=>{(typeof s[u]=="function"||s[u]instanceof Promise)&&delete s[u]});const l=h3e(s,r,e,a,n,c),f=dE(s.photometricInterpretation);return new Promise((u,d)=>{l.then(function(h){let g=!1;if(n.targetBuffer&&n.targetBuffer.type&&!f){const{arrayBuffer:T,type:E,offset:D=0,length:b}=n.targetBuffer,I=h.pixelDataLength,P=D,M=b??I-P,L={Uint8Array,Uint16Array,Int16Array,Float32Array,Uint32Array};if(M!==h.pixelDataLength)throw new Error(`target array for image does not have the same length (${M}) as the decoded image length (${h.pixelDataLength}).`);const V=L[E],G=T?new V(T,P,M):new V(h.pixelData);if(M!==h.pixelDataLength)throw new Error("target array for image does not have the same length as the decoded image length.");h.pixelData=G,g=!0}g||y3e(h);const p=mt(o.IMAGE_PLANE,t)||{},v=mt(o.VOI_LUT,t)||{},y=mt(o.MODALITY_LUT,t)||{},m=mt(o.SOP_COMMON,t)||{},w=mt(o.CALIBRATION,t)||{},{rows:x,columns:C}=h;if(f){if(u3e(h)){a.height=h.rows,a.width=h.columns;let D=a.getContext("2d").createImageData(h.columns,h.rows);i||(D={...D,data:new Uint8ClampedArray(3*h.columns*h.rows)}),zB(h,D.data,i),h.imageData=D,h.pixelData=D.data,h.pixelDataLength=D.data.length}else if(!i&&h.pixelDataLength===4*x*C){const E=new Uint8Array(h.pixelData.length/4*3);h.pixelData=p3e(h.pixelData,E),h.pixelDataLength=h.pixelData.length}const T=X5(h.pixelData);h.smallestPixelValue=T.min,h.largestPixelValue=T.max}const S=tc.createImageVoxelManager({scalarData:h.pixelData,width:h.columns,height:h.rows,numberOfComponents:h.samplesPerPixel}),_={imageId:t,dataType:h.pixelData.constructor.name,color:f,calibration:w,columnPixelSpacing:p.columnPixelSpacing,columns:h.columns,height:h.rows,preScale:h.preScale,intercept:y.rescaleIntercept?y.rescaleIntercept:0,slope:y.rescaleSlope?y.rescaleSlope:1,invert:h.photometricInterpretation==="MONOCHROME1",minPixelValue:h.smallestPixelValue,maxPixelValue:h.largestPixelValue,rowPixelSpacing:p.rowPixelSpacing,rows:h.rows,sizeInBytes:h.pixelData.byteLength,width:h.columns,windowCenter:v.windowCenter?v.windowCenter[0]:void 0,windowWidth:v.windowWidth?v.windowWidth[0]:void 0,voiLUTFunction:v.voiLUTFunction?v.voiLUTFunction:void 0,decodeTimeInMS:h.decodeTimeInMS,floatPixelData:void 0,imageFrame:h,voxelManager:S,rgba:f&&i,getPixelData:()=>h.pixelData,getCanvas:void 0,numberOfComponents:h.samplesPerPixel};if(_.color&&(_.getCanvas=function(){if(_b===t)return a;const T=_.columns,E=_.rows;a.height=E,a.width=T;const D=a.getContext("2d"),b=D.createImageData(T,E),I=h.pixelData;if(I.length===T*E*4)for(let P=0;P0&&m3e(m.sopClassUID)&&(_.modalityLUT=y.modalityLUTSequence[0]),v.voiLUTSequence&&v.voiLUTSequence.length>0&&(_.voiLUT=v.voiLUTSequence[0]),_.color&&(_.windowWidth=256,_.windowCenter=128),_.windowCenter===void 0||_.windowWidth===void 0){const T=_.imageFrame.smallestPixelValue,E=_.imageFrame.largestPixelValue;_.windowWidth=E-T,_.windowCenter=(E+T)/2}u(_)},d)})}const{ImageQualityStatus:HB}=ja;function w3e(t,e){t.decache=function(){const r=k1(e);T0.unload(r.url)}}function KB(t,e,r=0,n,i,o){const a=new Date().getTime(),s={cancelFn:void 0,promise:void 0};return s.promise=new Promise((c,l)=>{t.then(f=>{const u=fE(f,r),d=f.string("x00020010"),h=new Date().getTime(),g=Y5(e,u,d,i);w3e(s,e),g.then(p=>{p=p,p.data=f,p.sharedCacheKey=n;const v=new Date().getTime();p.loadTimeInMS=h-a,p.totalTimeInMS=v-a,p.imageQualityStatus=HB.FULL_RESOLUTION,o!==void 0&&o.imageDoneCallback!==void 0&&o.imageDoneCallback(p),c(p)},function(p){l({error:p,dataSet:f})})},function(f){l({error:f})})}),s}function x3e(t,e,r=0,n,i){const o=new Date().getTime();return{promise:new Promise((s,c)=>{const l=new Date().getTime();let f;try{const u=fE(t,r),d=t.string("x00020010");f=Y5(e,u,d,i)}catch(u){c({error:u,dataSet:t});return}f.then(u=>{u=u,u.data=t;const d=new Date().getTime();u.loadTimeInMS=l-o,u.totalTimeInMS=d-o,u.imageQualityStatus=HB.FULL_RESOLUTION,s(u)},c)}),cancelFn:void 0}}function qB(t){if(t==="dicomweb"||t==="wadouri")return H5;if(t==="dicomfile")return WB}function k2(t,e={}){const r=k1(t);e=Object.assign({},e),delete e.loader;const n=qB(r.scheme);if(T0.isLoaded(r.url)){const o=T0.get(r.url,n,t);return x3e(o,t,r.pixelDataFrame,r.url,e)}const i=T0.load(r.url,n,t);return KB(i,t,r.frame,r.url,e)}function XB(){b2("dicomweb",k2),b2("wadouri",k2),b2("dicomfile",k2),ah(uE)}const C3e={getImagePixelModule:EB,getLUTs:iS,getModalityLUTOutputPixelRepresentation:DB,getNumberValues:_s,metaDataProvider:uE,metadataForDataset:VB},S3e={metaData:C3e,dataSetCacheManager:T0,fileManager:FB,getEncapsulatedImageFrame:UB,getUncompressedImageFrame:GB,loadFileRequest:WB,loadImageFromPromise:KB,getLoaderForScheme:qB,getPixelData:fE,loadImage:k2,parseImageId:k1,unpackBinaryFrame:BB,register:XB};function en(t,e,r){return e=e||0,!t||!t.Value||Array.isArray(t.Value)&&t.Value.length<=e?r:t.Value[e]}function _3e(t,e,r){const n=en(t,e,r);if(n!==void 0)return parseFloat(String(n))}function Kn(t,e){const r=en(t,e);if(r!==void 0)return parseFloat(r)}function ho(t,e){if(!t||!t.Value||!Array.isArray(t.Value)||e&&t.Value.length>s&1}e.push({rows:Kn(t[`${n}0010`]),columns:Kn(t[`${n}0011`]),type:en(t[`${n}0040`]),x:Kn(t[`${n}0050`],1)-1,y:Kn(t[`${n}0050`],0)-1,pixelData:o,description:en(t[`${n}0022`]),label:en(t[`${n}1500`]),roiArea:en(t[`${n}1301`]),roiMean:en(t[`${n}1302`]),roiStandardDeviation:en(t[`${n}1303`])})}return{overlays:e}}function J5(t){const e=t.indexOf(":");return t.substring(e+1)}function E0(t,e=!0){return t&&t.Value?t.Value[0]&&e?t.Value[0]:t.Value:t}function YB(t,e,r){const n=(e?Object.values(e[0]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object"),i=(t?Object.values(t[r-1]):[]).map(o=>{var a;return(a=o.Value)==null?void 0:a[0]}).filter(o=>o!==void 0&&typeof o=="object");return{shared:n,perFrame:i}}function JB(t){let{52009230:e,52009229:r,"00280008":n,...i}=t;return e=E0(e,!1),r=E0(r,!1),n=E0(n),{PerFrameFunctionalGroupsSequence:e,SharedFunctionalGroupsSequence:r,NumberOfFrames:n,rest:i}}function E3e(t,e){const{PerFrameFunctionalGroupsSequence:r,SharedFunctionalGroupsSequence:n,NumberOfFrames:i,rest:o}=JB(e);if(r||i>1){const{shared:a,perFrame:s}=YB(r,n,t),c=Object.assign(e,{frameNumber:t});return[...a,...s].forEach(l=>{Object.entries(l).forEach(([f,u])=>{c[f]=u})}),Object.assign(o,{"00280008":i},c)}return e}let F1=[],Sy={};function ZB(t){const e=t.indexOf("/frames/")+8,r=t.slice(0,e),n=parseInt(t.slice(e),10);return{metadata:F1[`${r}1`],frame:n}}function D3e(t){const e=J5(t);return ZB(e)}function b3e(t){if(t[52009230]!==void 0||t[52009229]!==void 0)return!0;const e=en(t["00280008"]);return e&&e>1}function I3e(t,e){const r=J5(t);Object.defineProperty(e,"isMultiframe",{value:b3e(e),enumerable:!1}),F1[r]=e}function O3e(t){const e=J5(t),r=F1[e];if(r&&!(r!=null&&r.isMultiframe))return r;const n=Sy[e];if(n)return n;const i=ZB(e);if(!i||!i.metadata)return;const{metadata:o,frame:a}=i;if(o){const s=E3e(a,o);return Sy[e]=s,s}}function M3e(t){const e=J5(t);F1[e]=void 0,Sy[e]=void 0}function P3e(){F1=[],Sy={}}const gE={add:I3e,get:O3e,remove:M3e,purge:P3e};function QB(t){return en(t["00080060"]).includes("NM")}function pE(t,e){const r=E0(t["00080008"],!1);if(r)return r[e]}function R3e(t){let e;const r=pE(t,2);if(r&&bh(r)){const n=E0(t["00540022"]);n&&(e=ho(n["00200037"],6))}return e}function L3e(t){let e;const r=pE(t,2);if(r&&bh(r)){const n=E0(t["00540022"]);n&&(e=ho(n["00200032"],3))}return e}function Tb(t){let e=ho(t["00200037"],6);return!e&&QB(t)&&(e=R3e(t)),e}function Eb(t){let e=ho(t["00200032"],3);return!e&&QB(t)&&(e=L3e(t)),e}function uo(t,e){const r=ho(t[e]);return r?r[0]:null}function A3e(t){var e;return(e=t==null?void 0:t.Value)!=null&&e.length?Array.isArray(t.Value)?t.Value:typeof t.Value=="object"?(console.warn("Warning: Value should be an array, but an object was found. Encapsulating the object in an array."),[t.Value]):[]:[]}function Db(t){const e=A3e(t["00186011"]);return!e||!e.length?null:e.map(n=>{const i=uo(n,"0018602C"),o=uo(n,"0018602E"),a=uo(n,"00186024"),s=uo(n,"00186026"),c=uo(n,"0018601A"),l=uo(n,"0018601E"),f=uo(n,"00186018"),u=uo(n,"0018601C"),d=uo(n,"00186020"),h=uo(n,"00186022"),g=uo(n,"0018602A"),p=uo(n,"00186028"),v=uo(n,"00186012"),y=uo(n,"00186014"),m=uo(n,"00186016"),w=uo(n,"00186030");return{regionLocationMinY0:c,regionLocationMaxY1:l,regionLocationMinX0:f,regionLocationMaxX1:u,referencePixelX0:d,referencePixelY0:h,physicalDeltaX:i,physicalDeltaY:o,physicalUnitsXDirection:a,physicalUnitsYDirection:s,referencePhysicalPixelValueY:g,referencePhysicalPixelValueX:p,regionSpatialFormat:v,regionDataType:y,regionFlags:m,transducerFrequency:w}})}function mE(t,e){const{MetadataModules:r}=ja;if(t===r.MULTIFRAME){const{metadata:i,frame:o}=D3e(e);if(!i)return;const{PerFrameFunctionalGroupsSequence:a,SharedFunctionalGroupsSequence:s,NumberOfFrames:c}=JB(i);if(a||c>1){const{shared:l,perFrame:f}=YB(a,s,o);return{NumberOfFrames:c,PerFrameFunctionalInformation:f,SharedFunctionalInformation:l}}return{NumberOfFrames:c}}const n=gE.get(e);if(n){if(t===r.GENERAL_STUDY)return{studyDescription:en(n["00081030"]),studyDate:Tr.parseDA(en(n["00080020"])),studyTime:Tr.parseTM(en(n["00080030"],0,"")),accessionNumber:en(n["00080050"])};if(t===r.GENERAL_SERIES)return{modality:en(n["00080060"]),seriesInstanceUID:en(n["0020000E"]),seriesDescription:en(n["0008103E"]),seriesNumber:Kn(n["00200011"]),studyInstanceUID:en(n["0020000D"]),seriesDate:Tr.parseDA(en(n["00080021"])),seriesTime:Tr.parseTM(en(n["00080031"],0,"")),acquisitionDate:Tr.parseDA(en(n["00080022"])),acquisitionTime:Tr.parseTM(en(n["00080032"],0,""))};if(t===r.GENERAL_IMAGE)return{sopInstanceUID:en(n["00080018"]),instanceNumber:Kn(n["00200013"]),lossyImageCompression:en(n["00282110"]),lossyImageCompressionRatio:Kn(n["00282112"]),lossyImageCompressionMethod:en(n["00282114"])};if(t===r.PATIENT)return{patientID:en(n["00100020"]),patientName:en(n["00100010"])};if(t===r.PATIENT_STUDY)return{patientAge:Kn(n["00101010"]),patientSize:Kn(n["00101020"]),patientSex:en(n["00100040"]),patientWeight:Kn(n["00101030"])};if(t===r.NM_MULTIFRAME_GEOMETRY){const i=en(n["00080060"]),o=pE(n,2);return{modality:i,imageType:en(n["00080008"]),imageSubType:o,imageOrientationPatient:Tb(n),imagePositionPatient:Eb(n),sliceThickness:Kn(n["00180050"]),spacingBetweenSlices:Kn(n["00180088"]),pixelSpacing:ho(n["00280030"],2),numberOfFrames:Kn(n["00280008"]),isNMReconstructable:bh(o)&&i.includes("NM")}}if(t===r.IMAGE_PLANE){let i=Tb(n),o=Eb(n);const a=ho(n["00280030"],2);let s=null,c=null,l=null,f=null,u=!1;return a?(c=a[0],s=a[1]):(u=!0,c=1,s=1),i?(l=[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])],f=[parseFloat(i[3]),parseFloat(i[4]),parseFloat(i[5])]):(l=[1,0,0],f=[0,1,0],u=!0,i=[...l,...f]),o||(o=[0,0,0],u=!0),{frameOfReferenceUID:en(n["00200052"]),rows:Kn(n["00280010"]),columns:Kn(n["00280011"]),imageOrientationPatient:i,rowCosines:l,columnCosines:f,imagePositionPatient:o,sliceThickness:Kn(n["00180050"]),sliceLocation:Kn(n["00201041"]),pixelSpacing:a,rowPixelSpacing:c,columnPixelSpacing:s,usingDefaultValues:u}}if(t===r.ULTRASOUND_ENHANCED_REGION)return Db(n);if(t===r.CALIBRATION&&en(n["00080060"])==="US")return{sequenceOfUltrasoundRegions:Db(n)};if(t===r.IMAGE_URL)return N3e(e,n);if(t===r.CINE)return k3e(e,n);if(t===r.IMAGE_PIXEL)return{samplesPerPixel:Kn(n["00280002"]),photometricInterpretation:en(n["00280004"]),rows:Kn(n["00280010"]),columns:Kn(n["00280011"]),bitsAllocated:Kn(n["00280100"]),bitsStored:Kn(n["00280101"]),highBit:en(n["00280102"]),pixelRepresentation:Kn(n["00280103"]),planarConfiguration:Kn(n["00280006"]),pixelAspectRatio:en(n["00280034"]),smallestPixelValue:Kn(n["00280106"]),largestPixelValue:Kn(n["00280107"]),redPaletteColorLookupTableDescriptor:ho(n["00281101"]),greenPaletteColorLookupTableDescriptor:ho(n["00281102"]),bluePaletteColorLookupTableDescriptor:ho(n["00281103"]),redPaletteColorLookupTableData:ho(n["00281201"]),greenPaletteColorLookupTableData:ho(n["00281202"]),bluePaletteColorLookupTableData:ho(n["00281203"])};if(t===r.VOI_LUT)return{windowCenter:ho(n["00281050"],1),windowWidth:ho(n["00281051"],1),voiLUTFunction:en(n["00281056"])};if(t===r.MODALITY_LUT)return{rescaleIntercept:Kn(n["00281052"]),rescaleSlope:Kn(n["00281053"]),rescaleType:en(n["00281054"])};if(t===r.SOP_COMMON)return{sopClassUID:en(n["00080016"]),sopInstanceUID:en(n["00080018"])};if(t===r.PET_ISOTOPE){const i=en(n["00540016"]);return i===void 0?void 0:{radiopharmaceuticalInfo:{radiopharmaceuticalStartTime:Tr.parseTM(en(i["00181072"],0,"")),radiopharmaceuticalStartDateTime:en(i["00181078"],0,""),radionuclideTotalDose:Kn(i["00181074"]),radionuclideHalfLife:Kn(i["00181075"])}}}if(t===r.OVERLAY_PLANE)return T3e(n);if(t==="transferSyntax")return eG(e,n);if(t===r.PET_SERIES)return{correctedImage:en(n["00280051"]),units:en(n["00541001"]),decayCorrection:en(n["00541102"])};if(t===r.PET_IMAGE)return{frameReferenceTime:Kn(n["00541300"]),actualFrameDuration:Kn(n["00181242"])};if(t==="instance")return NB(e,mE,kB)}}function N3e(t,e){const{transferSyntaxUID:r}=eG(t,e),n=KA(r),i=t.substring(7),o=i.replace("/frames/","/thumbnail/");let a=i.replace("/frames/","/rendered/");return n&&(a=a.replace("/rendered/1","/rendered")),{isVideo:n,rendered:a,thumbnail:o}}function k3e(t,e){return{cineRate:en(e["00180040"]),numberOfFrames:Kn(e["00280008"])}}function eG(t,e){return{transferSyntaxUID:en(e["00020010"])||en(e["00083002"])}}function V3e(t,e,r={},n={}){const i=V1(),{retrieveOptions:o={},streamingData:a}=n,s=a.chunkSize||U3e(e,o,"chunkSize")||65536,c=f=>{if(typeof i.errorInterceptor=="function"){const u=new Error("request failed");i.errorInterceptor(u)}else console.warn("rangeRequest:Caught",f)};return new Promise(async(f,u)=>{const d=Object.assign({},r);Object.keys(d).forEach(function(h){(d[h]===null||d[h]===void 0)&&delete d[h]});try{a.encodedData||(a.chunkSize=s,a.rangesFetched=0);const h=B3e(a,o),{encodedData:g,responseHeaders:p}=await F3e(t,d,h,a),v=p.get("content-type"),{totalBytes:y}=a,m=y===g.byteLength,w=aE(v,g,{isPartial:!0}),x=sE(o,m||w.extractDone);f({...w,imageQualityStatus:x,percentComplete:w.extractDone?100:s*100/y})}catch(h){c(h),console.error(h),u(h)}})}async function F3e(t,e,r,n){r&&(e=Object.assign(e,{Range:`bytes=${r[0]}-${r[1]}`}));let{encodedData:i}=n;if(r[1]&&(i==null?void 0:i.byteLength)>r[1])return n;const o=await fetch(t,{headers:e,signal:void 0}),a=await o.arrayBuffer(),s=new Uint8Array(a),{status:c}=o;let l;i?(l=new Uint8Array(i.length+s.length),l.set(i,0),l.set(s,i.length),n.rangesFetched=1):(l=new Uint8Array(s.length),l.set(s,0),n.rangesFetched++),n.encodedData=i=l,n.responseHeaders=o.headers;const f=o.headers.get("Content-Range");return f?n.totalBytes=Number(f.split("/")[1]):c!==206||!r?n.totalBytes=i==null?void 0:i.byteLength:r[1]===""||(i==null?void 0:i.length)r-i?[(n==null?void 0:n.byteLength)||0,""]:[(n==null?void 0:n.byteLength)||0,i*(o+1)-1]}function vE(t,e,r="application/octet-stream",n){const{streamingData:i,retrieveOptions:o={}}=n||{},a={Accept:r};let s=o.urlArguments?`${t}${t.indexOf("?")===-1?"?":"&"}${o.urlArguments}`:t;if(o.framesPath&&(s=s.replace("/frames/",o.framesPath)),(i==null?void 0:i.url)!==s&&(n.streamingData={url:s}),o.rangeIndex!==void 0)return V3e(s,e,a,n);if(o.streaming)return OB(s,e,a,n);const c=H5(s,e,a),{xhr:l}=c;return c.then(function(f){const u=l.getResponseHeader("Content-Type")||"application/octet-stream",d=aE(u,new Uint8Array(f));return d.imageQualityStatus=sE(o,!0),d})}const{ProgressiveIterator:bb}=Mn,{ImageQualityStatus:Ib}=ja,G3e=new Set(["3.2.840.10008.1.2.4.96","1.2.840.10008.1.2.4.202","1.2.840.10008.1.2.4.203"]);function W3e(t){const e="1.2.840.10008.1.2";if(!t)return e;const r=t.split(";"),n={};r.forEach(o=>{const a=o.split("=");if(a.length!==2)return;const s=a[1].trim().replace(/"/g,"");n[a[0].trim()]=s});const i={"image/jpeg":"1.2.840.10008.1.2.4.50","image/x-dicom-rle":"1.2.840.10008.1.2.5","image/x-jls":"1.2.840.10008.1.2.4.80","image/jls":"1.2.840.10008.1.2.4.80","image/jll":"1.2.840.10008.1.2.4.70","image/jp2":"1.2.840.10008.1.2.4.90","image/jpx":"1.2.840.10008.1.2.4.92","image/jphc":"3.2.840.10008.1.2.4.96","image/jxl":"1.2.840.10008.1.2.4.140"};return n["transfer-syntax"]?n["transfer-syntax"]:t&&!Object.keys(n).length&&i[t]?i[t]:n.type&&i[n.type]?i[n.type]:i[t]?i[t]:e}function z3e(){return x1}const $3e="multipart/related; type=application/octet-stream; transfer-syntax=*";function tG(t,e={}){const r=z3e(),n=new Date().getTime(),i=new bb("decompress");async function o(f,u,d){i.generate(async h=>{var v;const g=bb.as(vE(f,u,d,e));let p=10;for await(const y of g){const{pixelData:m,imageQualityStatus:w=Ib.FULL_RESOLUTION,percentComplete:x,done:C=!0,extractDone:S=!0}=y,_=W3e(y.contentType);if(!S&&!G3e.has(_))continue;const T=y.decodeLevel??(w===Ib.FULL_RESOLUTION?0:j3e(x,(v=e.retrieveOptions)==null?void 0:v.decodeLevel));if(!(!C&&p<=T))try{const E={...e,decodeLevel:T},D=await Y5(u,m,_,E),b=new Date().getTime();D.loadTimeInMS=b-n,D.transferSyntaxUID=_,D.imageQualityStatus=w,h.add(D,C),p=T}catch(E){if(S)throw console.warn("Couldn't decode",E),E}}})}const a=e.requestType||hn.Interaction,s=e.additionalDetails||{imageId:t},c=e.priority===void 0?5:e.priority,l=t.substring(7);return r.addRequest(o.bind(this,l,t,$3e),a,s,c),{promise:i.getDonePromise(),cancelFn:void 0}}function j3e(t,e=4){const r=t/100-.02;return r>1/4?Math.min(e,0):r>1/16?Math.min(e,1):r>1/64?Math.min(e,2):Math.min(e,3)}function nG(){b2("wadors",tG),ah(mE)}const H3e={getNumberString:_3e,getNumberValue:Kn,getNumberValues:ho,getValue:en,metaDataProvider:mE},K3e={metaData:H3e,findIndexOfString:aS,getPixelData:vE,loadImage:tG,metaDataManager:gE,register:nG};function q3e(){nG(),XB()}const X3e=()=>new Worker(new URL("/static/dv3d/assets/decodeImageFrameWorker-DhtpjVX0.js",import.meta.url),{type:"module"});function rG(t={}){IB(t),q3e();const e=il(),r=(t==null?void 0:t.maxWebWorkers)||Y3e();e.registerWorker("dicomImageLoader",X3e,{maxWorkerInstances:r})}function Y3e(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.max(1,Math.floor(navigator.hardwareConcurrency/2)):1}function J3e(t,e){if(e=e||t.transferSyntax,t.bitsAllocated===8&&e==="1.2.840.10008.1.2.4.50"&&(t.samplesPerPixel===3||t.samplesPerPixel===4))return!0}const Z3e={IMPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2",EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1",DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN:"1.2.840.10008.1.2.1.99",EXPLICIT_VR_BIG_ENDIAN:"1.2.840.10008.1.2.2",JPEG_BASELINE_PROCESS_1:"1.2.840.10008.1.2.4.50",JPEG_EXTENDED_PROCESS_2_4:"1.2.840.10008.1.2.4.51",JPEG_EXTENDED_PROCESSES_3_5:"1.2.840.10008.1.2.4.52",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_6_8:"1.2.840.10008.1.2.4.53",JPEG_SPECTRAL_SELECTION_NONHIERARCHICAL_PROCESSES_7_9:"1.2.840.10008.1.2.4.54",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_10_12:"1.2.840.10008.1.2.4.55",JPEG_FULL_PROGRESSION_NONHIERARCHICAL_PROCESSES_11_13:"1.2.840.10008.1.2.4.56",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_14:"1.2.840.10008.1.2.4.57",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_15:"1.2.840.10008.1.2.4.58",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_16_18:"1.2.840.10008.1.2.4.59",JPEG_EXTENDED_HIERARCHICAL_PROCESSES_17_19:"1.2.840.10008.1.2.4.60",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_20_22:"1.2.840.10008.1.2.4.61",JPEG_SPECTRAL_SELECTION_HIERARCHICAL_PROCESSES_21_23:"1.2.840.10008.1.2.4.62",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_24_26:"1.2.840.10008.1.2.4.63",JPEG_FULL_PROGRESSION_HIERARCHICAL_PROCESSES_25_27:"1.2.840.10008.1.2.4.64",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_28:"1.2.840.10008.1.2.4.65",JPEG_LOSSLESS_NONHIERARCHICAL_PROCESS_29:"1.2.840.10008.1.2.4.66",JPEG_LOSSLESS_NONHIERARCHICAL_FIRST_ORDER_PREDICTION_PROCESS_14:"1.2.840.10008.1.2.4.70",JPEG_LS_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.80",JPEG_LS_LOSSY_NEAR_LOSSLESS_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.81",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.90",JPEG_2000_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.91",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY:"1.2.840.10008.1.2.4.92",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.93",JPIP_REFERENCED:"1.2.840.10008.1.2.4.94",JPIP_REFERENCED_DEFLATE:"1.2.840.10008.1.2.4.95",MPEG2_MAIN_PROFILE_MAIN_LEVEL:"1.2.840.10008.1.2.4.100",MPEG4_AVC_H264_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.101",MPEG4_AVC_H264_BD_COMPATIBLE_HIGH_PROFILE_LEVEL_4_1:"1.2.840.10008.1.2.4.102",MPEG4_AVC_H264_HIGH_PROFILE_FOR_2D_VIDEO:"1.2.840.10008.1.2.4.103",MPEG4_AVC_H264_HIGH_PROFILE_FOR_3D_VIDEO:"1.2.840.10008.1.2.4.104",JPIP_LOSSLESS:"1.2.840.10008.1.2.4.96",JPIP_PART2_MULTICOMPONENT_IMAGE_COMPRESSION:"1.2.840.10008.1.2.4.97",RFC_2557_MIME_ENCAPSULATION:"1.2.840.10008.1.2.6.1",JPEG_XR_IMAGE_COMPRESSION:"1.2.840.10008.1.2.6.2",JPEG_2000_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.90R",JPEG_2000_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.91R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_LOSSLESS_ONLY_RETIRED:"1.2.840.10008.1.2.4.92R",JPEG_2000_PART_2_MULTICOMPONENT_IMAGE_COMPRESSION_RETIRED:"1.2.840.10008.1.2.4.93R"},Q3e=Object.freeze(Object.defineProperty({__proto__:null,transferSyntaxes:Z3e},Symbol.toStringTag,{value:"Module"}));function exe(t,e){const{rows:r,columns:n,data:i}=t,{rows:o,columns:a,data:s}=e,c=[],l=[],f=[];for(let u=0;u>8&255}async function rxe(t,e){if(t.bitsAllocated===16){let r=e.buffer,n=e.byteOffset;const i=e.length;n%2&&(r=r.slice(n),n=0),t.pixelRepresentation===0?t.pixelData=new Uint16Array(r,n,i/2):t.pixelData=new Int16Array(r,n,i/2);for(let o=0;o=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[u++];for(let v=0;v<-g+1&&c=0&&g<=127)for(let p=0;p=-127){const p=a[d++];for(let v=0;v<-g+1&&f{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(R,U){a=R,s=U});var c=Object.assign({},o),l="./this.program",f=(R,U)=>{throw U},u=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function p(R){return o.locateFile?o.locateFile(R,g):g+R}var v,y,m;if(h){var w=Js,x=Js;d?g=x.dirname(g)+"/":g=__dirname+"/",v=(R,U)=>(R=se(R)?new URL(R):x.normalize(R),w.readFileSync(R,U?void 0:"utf8")),m=R=>{var U=v(R,!0);return U.buffer||(U=new Uint8Array(U)),U},y=(R,U,q)=>{R=se(R)?new URL(R):x.normalize(R),w.readFile(R,function(le,he){le?q(le):U(he.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(R){if(!(R instanceof wt))throw R}),process.on("unhandledRejection",function(R){throw R}),f=(R,U)=>{throw process.exitCode=R,U},o.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",v=R=>{var U=new XMLHttpRequest;return U.open("GET",R,!1),U.send(null),U.responseText},d&&(m=R=>{var U=new XMLHttpRequest;return U.open("GET",R,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),y=(R,U,q)=>{var le=new XMLHttpRequest;le.open("GET",R,!0),le.responseType="arraybuffer",le.onload=()=>{if(le.status==200||le.status==0&&le.response){U(le.response);return}q()},le.onerror=q,le.send(null)});var C=o.print||console.log.bind(console),S=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&(f=o.quit);var _;o.wasmBinary&&(_=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&ie("no native wasm support detected");var T,E=!1;function D(R,U){R||ie(U)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function I(R,U,q){for(var le=U+q,he=U;R[he]&&!(he>=le);)++he;if(he-U>16&&R.buffer&&b)return b.decode(R.subarray(U,he));for(var ve="";U>10,56320|Je&1023)}}return ve}function P(R,U){return R?I(k,R,U):""}function M(R,U,q,le){if(!(le>0))return 0;for(var he=q,ve=q+le-1,Te=0;Te=55296&&be<=57343){var ke=R.charCodeAt(++Te);be=65536+((be&1023)<<10)|ke&1023}if(be<=127){if(q>=ve)break;U[q++]=be}else if(be<=2047){if(q+1>=ve)break;U[q++]=192|be>>6,U[q++]=128|be&63}else if(be<=65535){if(q+2>=ve)break;U[q++]=224|be>>12,U[q++]=128|be>>6&63,U[q++]=128|be&63}else{if(q+3>=ve)break;U[q++]=240|be>>18,U[q++]=128|be>>12&63,U[q++]=128|be>>6&63,U[q++]=128|be&63}}return U[q]=0,q-he}function L(R,U,q){return M(R,k,U,q)}function V(R){for(var U=0,q=0;q=55296&&le<=57343?(U+=4,++q):U+=3}return U}var G,A,k,F,j,Y,re,ue,ce;function pe(R){G=R,o.HEAP8=A=new Int8Array(R),o.HEAP16=F=new Int16Array(R),o.HEAP32=Y=new Int32Array(R),o.HEAPU8=k=new Uint8Array(R),o.HEAPU16=j=new Uint16Array(R),o.HEAPU32=re=new Uint32Array(R),o.HEAPF32=ue=new Float32Array(R),o.HEAPF64=ce=new Float64Array(R)}o.INITIAL_MEMORY;var Ee,Oe=[],_e=[],B=[];function O(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)K(o.preRun.shift());gt(Oe)}function z(){gt(_e)}function W(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)ee(o.postRun.shift());gt(B)}function K(R){Oe.unshift(R)}function Z(R){_e.unshift(R)}function ee(R){B.unshift(R)}var xe=0,De=null;function Ne(R){xe++,o.monitorRunDependencies&&o.monitorRunDependencies(xe)}function $e(R){if(xe--,o.monitorRunDependencies&&o.monitorRunDependencies(xe),xe==0&&De){var U=De;De=null,U()}}function ie(R){o.onAbort&&o.onAbort(R),R="Aborted("+R+")",S(R),E=!0,R+=". Build with -sASSERTIONS for more info.";var U=new WebAssembly.RuntimeError(R);throw s(U),U}var ae="data:application/octet-stream;base64,";function ye(R){return R.startsWith(ae)}function se(R){return R.startsWith("file://")}var ge;ge="libjpegturbowasm_decode.wasm",ye(ge)||(ge=p(ge));function Fe(R){try{if(R==ge&&_)return new Uint8Array(_);if(m)return m(R);throw"both async and sync fetching of the wasm failed"}catch(U){ie(U)}}function oe(){if(!_&&(u||d)){if(typeof fetch=="function"&&!se(ge))return fetch(ge,{credentials:"same-origin"}).then(function(R){if(!R.ok)throw"failed to load wasm binary file at '"+ge+"'";return R.arrayBuffer()}).catch(function(){return Fe(ge)});if(y)return new Promise(function(R,U){y(ge,function(q){R(new Uint8Array(q))},U)})}return Promise.resolve().then(function(){return Fe(ge)})}function ht(){var R={a:qe};function U(Te,be){var ke=Te.exports;o.asm=ke,T=o.asm.K,pe(T.buffer),Ee=o.asm.M,Z(o.asm.L),$e()}Ne();function q(Te){U(Te.instance)}function le(Te){return oe().then(function(be){return WebAssembly.instantiate(be,R)}).then(function(be){return be}).then(Te,function(be){S("failed to asynchronously prepare wasm: "+be),ie(be)})}function he(){return!_&&typeof WebAssembly.instantiateStreaming=="function"&&!ye(ge)&&!se(ge)&&!h&&typeof fetch=="function"?fetch(ge,{credentials:"same-origin"}).then(function(Te){var be=WebAssembly.instantiateStreaming(Te,R);return be.then(q,function(ke){return S("wasm streaming compile failed: "+ke),S("falling back to ArrayBuffer instantiation"),le(q)})}):le(q)}if(o.instantiateWasm)try{var ve=o.instantiateWasm(R,U);return ve}catch(Te){S("Module.instantiateWasm callback failed with error: "+Te),s(Te)}return he().catch(s),{}}function wt(R){this.name="ExitStatus",this.message="Program terminated with exit("+R+")",this.status=R}function gt(R){for(;R.length>0;)R.shift()(o)}function Ie(R){this.excPtr=R,this.ptr=R-24,this.set_type=function(U){re[this.ptr+4>>2]=U},this.get_type=function(){return re[this.ptr+4>>2]},this.set_destructor=function(U){re[this.ptr+8>>2]=U},this.get_destructor=function(){return re[this.ptr+8>>2]},this.set_refcount=function(U){Y[this.ptr>>2]=U},this.set_caught=function(U){U=U?1:0,A[this.ptr+12>>0]=U},this.get_caught=function(){return A[this.ptr+12>>0]!=0},this.set_rethrown=function(U){U=U?1:0,A[this.ptr+13>>0]=U},this.get_rethrown=function(){return A[this.ptr+13>>0]!=0},this.init=function(U,q){this.set_adjusted_ptr(0),this.set_type(U),this.set_destructor(q),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var U=Y[this.ptr>>2];Y[this.ptr>>2]=U+1},this.release_ref=function(){var U=Y[this.ptr>>2];return Y[this.ptr>>2]=U-1,U===1},this.set_adjusted_ptr=function(U){re[this.ptr+16>>2]=U},this.get_adjusted_ptr=function(){return re[this.ptr+16>>2]},this.get_exception_ptr=function(){var U=fe(this.get_type());if(U)return re[this.excPtr>>2];var q=this.get_adjusted_ptr();return q!==0?q:this.excPtr}}function je(R,U,q){var le=new Ie(R);throw le.init(U,q),R}var nt={};function rt(R){for(;R.length;){var U=R.pop(),q=R.pop();q(U)}}function dt(R){return this.fromWireType(Y[R>>2])}var Lt={},xt={},Ft={},jt=48,Pn=57;function $n(R){if(R===void 0)return"_unknown";R=R.replace(/[^a-zA-Z0-9_]/g,"$");var U=R.charCodeAt(0);return U>=jt&&U<=Pn?"_"+R:R}function fn(R,U){return R=$n(R),new Function("body","return function "+R+`() { "use strict"; return body.apply(this, arguments); }; `)(U)}function bn(R,U){var q=fn(U,function(le){this.name=U,this.message=le;var he=new Error(le).stack;he!==void 0&&(this.stack=this.toString()+` -`+he.replace(/^Error(:[^\n]*)?\n/,""))});return q.prototype=Object.create(R.prototype),q.prototype.constructor=q,q.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},q}var Xi=void 0;function Mr(R){throw new Xi(R)}function Be(R,U,q){R.forEach(function(be){Ft[be]=U});function le(be){var ke=q(be);ke.length!==R.length&&Mr("Mismatched type converter count");for(var Je=0;Je{xt.hasOwnProperty(be)?he[ke]=xt[be]:(ve.push(be),Lt.hasOwnProperty(be)||(Lt[be]=[]),Lt[be].push(()=>{he[ke]=xt[be],++Te,Te===ve.length&&le(he)}))}),ve.length===0&&le(he)}function ft(R){var U=tt[R];delete tt[R];var q=U.rawConstructor,le=U.rawDestructor,he=U.fields,ve=he.map(Te=>Te.getterReturnType).concat(he.map(Te=>Te.setterArgumentType));Be([R],ve,Te=>{var be={};return he.forEach((ke,Je)=>{var pt=ke.fieldName,Mt=Te[Je],Tt=ke.getter,dn=ke.getterContext,ln=Te[Je+he.length],Xn=ke.setter,li=ke.setterContext;be[pt]={read:yi=>Mt.fromWireType(Tt(dn,yi)),write:(yi,rf)=>{var Oa=[];Xn(li,yi,ln.toWireType(Oa,rf)),nt(Oa)}}}),[{name:U.name,fromWireType:function(ke){var Je={};for(var pt in be)Je[pt]=be[pt].read(ke);return le(ke),Je},toWireType:function(ke,Je){for(var pt in be)if(!(pt in Je))throw new TypeError('Missing field: "'+pt+'"');var Mt=q();for(pt in be)be[pt].write(Mt,Je[pt]);return ke!==null&&ke.push(le,Mt),Mt},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:le}]})}function Ut(R,U,q,le,he){}function Sn(R){switch(R){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+R)}}function Qn(){for(var R=new Array(256),U=0;U<256;++U)R[U]=String.fromCharCode(U);Pt=R}var Pt=void 0;function _n(R){for(var U="",q=R;k[q];)U+=Pt[k[q++]];return U}var sn=void 0;function rn(R){throw new sn(R)}function pi(R,U,q={}){if(!("argPackAdvance"in U))throw new TypeError("registerType registeredInstance requires argPackAdvance");var le=U.name;if(R||rn('type "'+le+'" must have a positive integer typeid pointer'),xt.hasOwnProperty(R)){if(q.ignoreDuplicateRegistrations)return;rn("Cannot register type '"+le+"' twice")}if(xt[R]=U,delete Ft[R],Lt.hasOwnProperty(R)){var he=Lt[R];delete Lt[R],he.forEach(ve=>ve())}}function Vi(R,U,q,le,he){var ve=Sn(q);U=_n(U),pi(R,{name:U,fromWireType:function(Te){return!!Te},toWireType:function(Te,be){return be?le:he},argPackAdvance:8,readValueFromPointer:function(Te){var be;if(q===1)be=A;else if(q===2)be=F;else if(q===4)be=Y;else throw new TypeError("Unknown boolean type size: "+U);return this.fromWireType(be[Te>>ve])},destructorFunction:null})}function Ha(R){if(!(this instanceof ut)||!(R instanceof ut))return!1;for(var U=this.$$.ptrType.registeredClass,q=this.$$.ptr,le=R.$$.ptrType.registeredClass,he=R.$$.ptr;U.baseClass;)q=U.upcast(q),U=U.baseClass;for(;le.baseClass;)he=le.upcast(he),le=le.baseClass;return U===le&&q===he}function Ea(R){return{count:R.count,deleteScheduled:R.deleteScheduled,preservePointerOnDelete:R.preservePointerOnDelete,ptr:R.ptr,ptrType:R.ptrType,smartPtr:R.smartPtr,smartPtrType:R.smartPtrType}}function To(R){function U(q){return q.$$.ptrType.registeredClass.name}rn(U(R)+" instance already deleted")}var ra=!1;function Uo(R){}function fr(R){R.smartPtr?R.smartPtrType.rawDestructor(R.smartPtr):R.ptrType.registeredClass.rawDestructor(R.ptr)}function oo(R){R.count.value-=1;var U=R.count.value===0;U&&fr(R)}function yn(R,U,q){if(U===q)return R;if(q.baseClass===void 0)return null;var le=yn(R,U,q.baseClass);return le===null?null:q.downcast(le)}var Qr={};function Da(){return Object.keys(Bi).length}function Fi(){var R=[];for(var U in Bi)Bi.hasOwnProperty(U)&&R.push(Bi[U]);return R}var ao=[];function Ui(){for(;ao.length;){var R=ao.pop();R.$$.deleteScheduled=!1,R.delete()}}var mi=void 0;function Ka(R){mi=R,ao.length&&mi&&mi(Ui)}function Bo(){o.getInheritedInstanceCount=Da,o.getLiveInheritedInstances=Fi,o.flushPendingDeletes=Ui,o.setDelayFunction=Ka}var Bi={};function qa(R,U){for(U===void 0&&rn("ptr should not be undefined");R.baseClass;)U=R.upcast(U),R=R.baseClass;return U}function Gi(R,U){return U=qa(R,U),Bi[U]}function ia(R,U){(!U.ptrType||!U.ptr)&&Mr("makeClassHandle requires ptr and ptrType");var q=!!U.smartPtrType,le=!!U.smartPtr;return q!==le&&Mr("Both smartPtrType and smartPtr must be specified"),U.count={value:1},Ue(Object.create(R,{$$:{value:U}}))}function de(R){var U=this.getPointee(R);if(!U)return this.destructor(R),null;var q=Gi(this.registeredClass,U);if(q!==void 0){if(q.$$.count.value===0)return q.$$.ptr=U,q.$$.smartPtr=R,q.clone();var le=q.clone();return this.destructor(R),le}function he(){return this.isSmartPointer?ia(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:U,smartPtrType:this,smartPtr:R}):ia(this.registeredClass.instancePrototype,{ptrType:this,ptr:R})}var ve=this.registeredClass.getActualType(U),Te=Qr[ve];if(!Te)return he.call(this);var be;this.isConst?be=Te.constPointerType:be=Te.pointerType;var ke=yn(U,this.registeredClass,be.registeredClass);return ke===null?he.call(this):this.isSmartPointer?ia(be.registeredClass.instancePrototype,{ptrType:be,ptr:ke,smartPtrType:this,smartPtr:R}):ia(be.registeredClass.instancePrototype,{ptrType:be,ptr:ke})}function Ue(R){return typeof FinalizationRegistry>"u"?(Ue=U=>U,R):(ra=new FinalizationRegistry(U=>{oo(U.$$)}),Ue=U=>{var q=U.$$,le=!!q.smartPtr;if(le){var he={$$:q};ra.register(U,he,U)}return U},Uo=U=>ra.unregister(U),Ue(R))}function _e(){if(this.$$.ptr||To(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var R=Ue(Object.create(Object.getPrototypeOf(this),{$$:{value:Ea(this.$$)}}));return R.$$.count.value+=1,R.$$.deleteScheduled=!1,R}function ye(){this.$$.ptr||To(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&rn("Object already scheduled for deletion"),Uo(this),oo(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function je(){return!this.$$.ptr}function ot(){return this.$$.ptr||To(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&rn("Object already scheduled for deletion"),ao.push(this),ao.length===1&&mi&&mi(Ui),this.$$.deleteScheduled=!0,this}function st(){ut.prototype.isAliasOf=Ha,ut.prototype.clone=_e,ut.prototype.delete=ye,ut.prototype.isDeleted=je,ut.prototype.deleteLater=ot}function ut(){}function rt(R,U,q){if(R[U].overloadTable===void 0){var le=R[U];R[U]=function(){return R[U].overloadTable.hasOwnProperty(arguments.length)||rn("Function '"+q+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+R[U].overloadTable+")!"),R[U].overloadTable[arguments.length].apply(this,arguments)},R[U].overloadTable=[],R[U].overloadTable[le.argCount]=le}}function Ct(R,U,q){o.hasOwnProperty(R)?(rn("Cannot register public name '"+R+"' twice"),rt(o,R,R),o.hasOwnProperty(q)&&rn("Cannot register multiple overloads of a function with the same number of arguments ("+q+")!"),o[R].overloadTable[q]=U):o[R]=U}function Qt(R,U,q,le,he,ve,Te,be){this.name=R,this.constructor=U,this.instancePrototype=q,this.rawDestructor=le,this.baseClass=he,this.getActualType=ve,this.upcast=Te,this.downcast=be,this.pureVirtualFunctions=[]}function on(R,U,q){for(;U!==q;)U.upcast||rn("Expected null or instance of "+q.name+", got an instance of "+U.name),R=U.upcast(R),U=U.baseClass;return R}function cn(R,U){if(U===null)return this.isReference&&rn("null is not a valid "+this.name),0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name);var q=U.$$.ptrType.registeredClass,le=on(U.$$.ptr,q,this.registeredClass);return le}function Gt(R,U){var q;if(U===null)return this.isReference&&rn("null is not a valid "+this.name),this.isSmartPointer?(q=this.rawConstructor(),R!==null&&R.push(this.rawDestructor,q),q):0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&U.$$.ptrType.isConst&&rn("Cannot convert argument of type "+(U.$$.smartPtrType?U.$$.smartPtrType.name:U.$$.ptrType.name)+" to parameter type "+this.name);var le=U.$$.ptrType.registeredClass;if(q=on(U.$$.ptr,le,this.registeredClass),this.isSmartPointer)switch(U.$$.smartPtr===void 0&&rn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:U.$$.smartPtrType===this?q=U.$$.smartPtr:rn("Cannot convert argument of type "+(U.$$.smartPtrType?U.$$.smartPtrType.name:U.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:q=U.$$.smartPtr;break;case 2:if(U.$$.smartPtrType===this)q=U.$$.smartPtr;else{var he=U.clone();q=this.rawShare(q,Go.toHandle(function(){he.delete()})),R!==null&&R.push(this.rawDestructor,q)}break;default:rn("Unsupporting sharing policy")}return q}function xn(R,U){if(U===null)return this.isReference&&rn("null is not a valid "+this.name),0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name),U.$$.ptrType.isConst&&rn("Cannot convert argument of type "+U.$$.ptrType.name+" to parameter type "+this.name);var q=U.$$.ptrType.registeredClass,le=on(U.$$.ptr,q,this.registeredClass);return le}function er(R){return this.rawGetPointee&&(R=this.rawGetPointee(R)),R}function nr(R){this.rawDestructor&&this.rawDestructor(R)}function or(R){R!==null&&R.delete()}function qn(){At.prototype.getPointee=er,At.prototype.destructor=nr,At.prototype.argPackAdvance=8,At.prototype.readValueFromPointer=dt,At.prototype.deleteObject=or,At.prototype.fromWireType=de}function At(R,U,q,le,he,ve,Te,be,ke,Je,pt){this.name=R,this.registeredClass=U,this.isReference=q,this.isConst=le,this.isSmartPointer=he,this.pointeeType=ve,this.sharingPolicy=Te,this.rawGetPointee=be,this.rawConstructor=ke,this.rawShare=Je,this.rawDestructor=pt,!he&&U.baseClass===void 0?le?(this.toWireType=cn,this.destructorFunction=null):(this.toWireType=xn,this.destructorFunction=null):this.toWireType=Gt}function Bn(R,U,q){o.hasOwnProperty(R)||Mr("Replacing nonexistant public symbol"),o[R].overloadTable!==void 0&&q!==void 0||(o[R]=U,o[R].argCount=q)}function dr(R,U,q){var le=o["dynCall_"+R];return q&&q.length?le.apply(null,[U].concat(q)):le.call(null,U)}var si=[];function jn(R){var U=si[R];return U||(R>=si.length&&(si.length=R+1),si[R]=U=Ee.get(R)),U}function wr(R,U,q){if(R.includes("j"))return dr(R,U,q);var le=jn(U).apply(null,q);return le}function ei(R,U){var q=[];return function(){return q.length=0,Object.assign(q,arguments),wr(R,U,q)}}function xr(R,U){R=_n(R);function q(){return R.includes("j")?ei(R,U):jn(U)}var le=q();return typeof le!="function"&&rn("unknown function pointer with signature "+R+": "+U),le}var uc=void 0;function ba(R){var U=kt(R),q=_n(U);return vt(U),q}function Yi(R,U){var q=[],le={};function he(ve){if(!le[ve]&&!xt[ve]){if(Ft[ve]){Ft[ve].forEach(he);return}q.push(ve),le[ve]=!0}}throw U.forEach(he),new uc(R+": "+q.map(ba).join([", "]))}function Xa(R,U,q,le,he,ve,Te,be,ke,Je,pt,Mt,Tt){pt=_n(pt),ve=xr(he,ve),be&&(be=xr(Te,be)),Je&&(Je=xr(ke,Je)),Tt=xr(Mt,Tt);var dn=$n(pt);Ct(dn,function(){Yi("Cannot construct "+pt+" due to unbound types",[le])}),Be([R,U,q],le?[le]:[],function(ln){ln=ln[0];var Xn,li;le?(Xn=ln.registeredClass,li=Xn.instancePrototype):li=ut.prototype;var yi=fn(dn,function(){if(Object.getPrototypeOf(this)!==rf)throw new sn("Use 'new' to construct "+pt);if(Oa.constructor_body===void 0)throw new sn(pt+" has no accessible constructor");var kE=Oa.constructor_body[arguments.length];if(kE===void 0)throw new sn("Tried to invoke ctor of "+pt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(Oa.constructor_body).toString()+") parameters instead!");return kE.apply(this,arguments)}),rf=Object.create(li,{constructor:{value:yi}});yi.prototype=rf;var Oa=new Qt(pt,yi,rf,Tt,Xn,ve,be,Je),U1=new At(pt,Oa,!0,!1,!1),Ih=new At(pt+"*",Oa,!1,!1,!1),NE=new At(pt+" const*",Oa,!1,!0,!1);return Qr[R]={pointerType:Ih,constPointerType:NE},Bn(dn,yi),[U1,Ih,NE]})}function cl(R,U){for(var q=[],le=0;le>2]);return q}function ll(R,U){if(!(R instanceof Function))throw new TypeError("new_ called with constructor type "+typeof R+" which is not a function");var q=fn(R.name||"unknownFunctionName",function(){});q.prototype=R.prototype;var le=new q,he=R.apply(le,U);return he instanceof Object?he:le}function bs(R,U,q,le,he){var ve=U.length;ve<2&&rn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Te=U[1]!==null&&q!==null,be=!1,ke=1;ke{xt.hasOwnProperty(be)?he[ke]=xt[be]:(ve.push(be),Lt.hasOwnProperty(be)||(Lt[be]=[]),Lt[be].push(()=>{he[ke]=xt[be],++Te,Te===ve.length&&le(he)}))}),ve.length===0&&le(he)}function ft(R){var U=nt[R];delete nt[R];var q=U.rawConstructor,le=U.rawDestructor,he=U.fields,ve=he.map(Te=>Te.getterReturnType).concat(he.map(Te=>Te.setterArgumentType));Ue([R],ve,Te=>{var be={};return he.forEach((ke,Je)=>{var pt=ke.fieldName,Mt=Te[Je],Tt=ke.getter,dn=ke.getterContext,ln=Te[Je+he.length],Xn=ke.setter,li=ke.setterContext;be[pt]={read:yi=>Mt.fromWireType(Tt(dn,yi)),write:(yi,rf)=>{var Oa=[];Xn(li,yi,ln.toWireType(Oa,rf)),rt(Oa)}}}),[{name:U.name,fromWireType:function(ke){var Je={};for(var pt in be)Je[pt]=be[pt].read(ke);return le(ke),Je},toWireType:function(ke,Je){for(var pt in be)if(!(pt in Je))throw new TypeError('Missing field: "'+pt+'"');var Mt=q();for(pt in be)be[pt].write(Mt,Je[pt]);return ke!==null&&ke.push(le,Mt),Mt},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:le}]})}function Ut(R,U,q,le,he){}function Sn(R){switch(R){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+R)}}function Qn(){for(var R=new Array(256),U=0;U<256;++U)R[U]=String.fromCharCode(U);Pt=R}var Pt=void 0;function _n(R){for(var U="",q=R;k[q];)U+=Pt[k[q++]];return U}var sn=void 0;function rn(R){throw new sn(R)}function pi(R,U,q={}){if(!("argPackAdvance"in U))throw new TypeError("registerType registeredInstance requires argPackAdvance");var le=U.name;if(R||rn('type "'+le+'" must have a positive integer typeid pointer'),xt.hasOwnProperty(R)){if(q.ignoreDuplicateRegistrations)return;rn("Cannot register type '"+le+"' twice")}if(xt[R]=U,delete Ft[R],Lt.hasOwnProperty(R)){var he=Lt[R];delete Lt[R],he.forEach(ve=>ve())}}function Vi(R,U,q,le,he){var ve=Sn(q);U=_n(U),pi(R,{name:U,fromWireType:function(Te){return!!Te},toWireType:function(Te,be){return be?le:he},argPackAdvance:8,readValueFromPointer:function(Te){var be;if(q===1)be=A;else if(q===2)be=F;else if(q===4)be=Y;else throw new TypeError("Unknown boolean type size: "+U);return this.fromWireType(be[Te>>ve])},destructorFunction:null})}function Ha(R){if(!(this instanceof ut)||!(R instanceof ut))return!1;for(var U=this.$$.ptrType.registeredClass,q=this.$$.ptr,le=R.$$.ptrType.registeredClass,he=R.$$.ptr;U.baseClass;)q=U.upcast(q),U=U.baseClass;for(;le.baseClass;)he=le.upcast(he),le=le.baseClass;return U===le&&q===he}function Ea(R){return{count:R.count,deleteScheduled:R.deleteScheduled,preservePointerOnDelete:R.preservePointerOnDelete,ptr:R.ptr,ptrType:R.ptrType,smartPtr:R.smartPtr,smartPtrType:R.smartPtrType}}function To(R){function U(q){return q.$$.ptrType.registeredClass.name}rn(U(R)+" instance already deleted")}var ra=!1;function Uo(R){}function fr(R){R.smartPtr?R.smartPtrType.rawDestructor(R.smartPtr):R.ptrType.registeredClass.rawDestructor(R.ptr)}function oo(R){R.count.value-=1;var U=R.count.value===0;U&&fr(R)}function yn(R,U,q){if(U===q)return R;if(q.baseClass===void 0)return null;var le=yn(R,U,q.baseClass);return le===null?null:q.downcast(le)}var Qr={};function Da(){return Object.keys(Bi).length}function Fi(){var R=[];for(var U in Bi)Bi.hasOwnProperty(U)&&R.push(Bi[U]);return R}var ao=[];function Ui(){for(;ao.length;){var R=ao.pop();R.$$.deleteScheduled=!1,R.delete()}}var mi=void 0;function Ka(R){mi=R,ao.length&&mi&&mi(Ui)}function Bo(){o.getInheritedInstanceCount=Da,o.getLiveInheritedInstances=Fi,o.flushPendingDeletes=Ui,o.setDelayFunction=Ka}var Bi={};function qa(R,U){for(U===void 0&&rn("ptr should not be undefined");R.baseClass;)U=R.upcast(U),R=R.baseClass;return U}function Gi(R,U){return U=qa(R,U),Bi[U]}function ia(R,U){(!U.ptrType||!U.ptr)&&Mr("makeClassHandle requires ptr and ptrType");var q=!!U.smartPtrType,le=!!U.smartPtr;return q!==le&&Mr("Both smartPtrType and smartPtr must be specified"),U.count={value:1},We(Object.create(R,{$$:{value:U}}))}function de(R){var U=this.getPointee(R);if(!U)return this.destructor(R),null;var q=Gi(this.registeredClass,U);if(q!==void 0){if(q.$$.count.value===0)return q.$$.ptr=U,q.$$.smartPtr=R,q.clone();var le=q.clone();return this.destructor(R),le}function he(){return this.isSmartPointer?ia(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:U,smartPtrType:this,smartPtr:R}):ia(this.registeredClass.instancePrototype,{ptrType:this,ptr:R})}var ve=this.registeredClass.getActualType(U),Te=Qr[ve];if(!Te)return he.call(this);var be;this.isConst?be=Te.constPointerType:be=Te.pointerType;var ke=yn(U,this.registeredClass,be.registeredClass);return ke===null?he.call(this):this.isSmartPointer?ia(be.registeredClass.instancePrototype,{ptrType:be,ptr:ke,smartPtrType:this,smartPtr:R}):ia(be.registeredClass.instancePrototype,{ptrType:be,ptr:ke})}function We(R){return typeof FinalizationRegistry>"u"?(We=U=>U,R):(ra=new FinalizationRegistry(U=>{oo(U.$$)}),We=U=>{var q=U.$$,le=!!q.smartPtr;if(le){var he={$$:q};ra.register(U,he,U)}return U},Uo=U=>ra.unregister(U),We(R))}function Se(){if(this.$$.ptr||To(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var R=We(Object.create(Object.getPrototypeOf(this),{$$:{value:Ea(this.$$)}}));return R.$$.count.value+=1,R.$$.deleteScheduled=!1,R}function we(){this.$$.ptr||To(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&rn("Object already scheduled for deletion"),Uo(this),oo(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Ge(){return!this.$$.ptr}function tt(){return this.$$.ptr||To(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&rn("Object already scheduled for deletion"),ao.push(this),ao.length===1&&mi&&mi(Ui),this.$$.deleteScheduled=!0,this}function st(){ut.prototype.isAliasOf=Ha,ut.prototype.clone=Se,ut.prototype.delete=we,ut.prototype.isDeleted=Ge,ut.prototype.deleteLater=tt}function ut(){}function it(R,U,q){if(R[U].overloadTable===void 0){var le=R[U];R[U]=function(){return R[U].overloadTable.hasOwnProperty(arguments.length)||rn("Function '"+q+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+R[U].overloadTable+")!"),R[U].overloadTable[arguments.length].apply(this,arguments)},R[U].overloadTable=[],R[U].overloadTable[le.argCount]=le}}function Ct(R,U,q){o.hasOwnProperty(R)?(rn("Cannot register public name '"+R+"' twice"),it(o,R,R),o.hasOwnProperty(q)&&rn("Cannot register multiple overloads of a function with the same number of arguments ("+q+")!"),o[R].overloadTable[q]=U):o[R]=U}function Qt(R,U,q,le,he,ve,Te,be){this.name=R,this.constructor=U,this.instancePrototype=q,this.rawDestructor=le,this.baseClass=he,this.getActualType=ve,this.upcast=Te,this.downcast=be,this.pureVirtualFunctions=[]}function on(R,U,q){for(;U!==q;)U.upcast||rn("Expected null or instance of "+q.name+", got an instance of "+U.name),R=U.upcast(R),U=U.baseClass;return R}function cn(R,U){if(U===null)return this.isReference&&rn("null is not a valid "+this.name),0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name);var q=U.$$.ptrType.registeredClass,le=on(U.$$.ptr,q,this.registeredClass);return le}function Gt(R,U){var q;if(U===null)return this.isReference&&rn("null is not a valid "+this.name),this.isSmartPointer?(q=this.rawConstructor(),R!==null&&R.push(this.rawDestructor,q),q):0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&U.$$.ptrType.isConst&&rn("Cannot convert argument of type "+(U.$$.smartPtrType?U.$$.smartPtrType.name:U.$$.ptrType.name)+" to parameter type "+this.name);var le=U.$$.ptrType.registeredClass;if(q=on(U.$$.ptr,le,this.registeredClass),this.isSmartPointer)switch(U.$$.smartPtr===void 0&&rn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:U.$$.smartPtrType===this?q=U.$$.smartPtr:rn("Cannot convert argument of type "+(U.$$.smartPtrType?U.$$.smartPtrType.name:U.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:q=U.$$.smartPtr;break;case 2:if(U.$$.smartPtrType===this)q=U.$$.smartPtr;else{var he=U.clone();q=this.rawShare(q,Go.toHandle(function(){he.delete()})),R!==null&&R.push(this.rawDestructor,q)}break;default:rn("Unsupporting sharing policy")}return q}function xn(R,U){if(U===null)return this.isReference&&rn("null is not a valid "+this.name),0;U.$$||rn('Cannot pass "'+Ja(U)+'" as a '+this.name),U.$$.ptr||rn("Cannot pass deleted object as a pointer of type "+this.name),U.$$.ptrType.isConst&&rn("Cannot convert argument of type "+U.$$.ptrType.name+" to parameter type "+this.name);var q=U.$$.ptrType.registeredClass,le=on(U.$$.ptr,q,this.registeredClass);return le}function er(R){return this.rawGetPointee&&(R=this.rawGetPointee(R)),R}function nr(R){this.rawDestructor&&this.rawDestructor(R)}function or(R){R!==null&&R.delete()}function qn(){At.prototype.getPointee=er,At.prototype.destructor=nr,At.prototype.argPackAdvance=8,At.prototype.readValueFromPointer=dt,At.prototype.deleteObject=or,At.prototype.fromWireType=de}function At(R,U,q,le,he,ve,Te,be,ke,Je,pt){this.name=R,this.registeredClass=U,this.isReference=q,this.isConst=le,this.isSmartPointer=he,this.pointeeType=ve,this.sharingPolicy=Te,this.rawGetPointee=be,this.rawConstructor=ke,this.rawShare=Je,this.rawDestructor=pt,!he&&U.baseClass===void 0?le?(this.toWireType=cn,this.destructorFunction=null):(this.toWireType=xn,this.destructorFunction=null):this.toWireType=Gt}function Bn(R,U,q){o.hasOwnProperty(R)||Mr("Replacing nonexistant public symbol"),o[R].overloadTable!==void 0&&q!==void 0||(o[R]=U,o[R].argCount=q)}function dr(R,U,q){var le=o["dynCall_"+R];return q&&q.length?le.apply(null,[U].concat(q)):le.call(null,U)}var si=[];function jn(R){var U=si[R];return U||(R>=si.length&&(si.length=R+1),si[R]=U=Ee.get(R)),U}function wr(R,U,q){if(R.includes("j"))return dr(R,U,q);var le=jn(U).apply(null,q);return le}function ei(R,U){var q=[];return function(){return q.length=0,Object.assign(q,arguments),wr(R,U,q)}}function xr(R,U){R=_n(R);function q(){return R.includes("j")?ei(R,U):jn(U)}var le=q();return typeof le!="function"&&rn("unknown function pointer with signature "+R+": "+U),le}var uc=void 0;function ba(R){var U=kt(R),q=_n(U);return vt(U),q}function Yi(R,U){var q=[],le={};function he(ve){if(!le[ve]&&!xt[ve]){if(Ft[ve]){Ft[ve].forEach(he);return}q.push(ve),le[ve]=!0}}throw U.forEach(he),new uc(R+": "+q.map(ba).join([", "]))}function Xa(R,U,q,le,he,ve,Te,be,ke,Je,pt,Mt,Tt){pt=_n(pt),ve=xr(he,ve),be&&(be=xr(Te,be)),Je&&(Je=xr(ke,Je)),Tt=xr(Mt,Tt);var dn=$n(pt);Ct(dn,function(){Yi("Cannot construct "+pt+" due to unbound types",[le])}),Ue([R,U,q],le?[le]:[],function(ln){ln=ln[0];var Xn,li;le?(Xn=ln.registeredClass,li=Xn.instancePrototype):li=ut.prototype;var yi=fn(dn,function(){if(Object.getPrototypeOf(this)!==rf)throw new sn("Use 'new' to construct "+pt);if(Oa.constructor_body===void 0)throw new sn(pt+" has no accessible constructor");var kE=Oa.constructor_body[arguments.length];if(kE===void 0)throw new sn("Tried to invoke ctor of "+pt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(Oa.constructor_body).toString()+") parameters instead!");return kE.apply(this,arguments)}),rf=Object.create(li,{constructor:{value:yi}});yi.prototype=rf;var Oa=new Qt(pt,yi,rf,Tt,Xn,ve,be,Je),U1=new At(pt,Oa,!0,!1,!1),Ih=new At(pt+"*",Oa,!1,!1,!1),NE=new At(pt+" const*",Oa,!1,!0,!1);return Qr[R]={pointerType:Ih,constPointerType:NE},Bn(dn,yi),[U1,Ih,NE]})}function cl(R,U){for(var q=[],le=0;le>2]);return q}function ll(R,U){if(!(R instanceof Function))throw new TypeError("new_ called with constructor type "+typeof R+" which is not a function");var q=fn(R.name||"unknownFunctionName",function(){});q.prototype=R.prototype;var le=new q,he=R.apply(le,U);return he instanceof Object?he:le}function bs(R,U,q,le,he){var ve=U.length;ve<2&&rn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Te=U[1]!==null&&q!==null,be=!1,ke=1;ke0?", ":"")+Mt),Tt+=(Je?"var rv = ":"")+"invoker(fn"+(Mt.length>0?", ":"")+Mt+`); `,be)Tt+=`runDestructors(destructors); @@ -3779,7 +3779,7 @@ throwBindingError('function `+R+" called with ' + arguments.length + ' arguments `,ln.push(li+"_dtor"),Xn.push(U[ke].destructorFunction))}Je&&(Tt+=`var ret = retType.fromWireType(rv); return ret; `),Tt+=`} -`,ln.push(Tt);var yi=ll(Function,ln).apply(null,Xn);return yi}function gr(R,U,q,le,he,ve){D(U>0);var Te=cl(U,q);he=xr(le,he),Be([],[R],function(be){be=be[0];var ke="constructor "+be.name;if(be.registeredClass.constructor_body===void 0&&(be.registeredClass.constructor_body=[]),be.registeredClass.constructor_body[U-1]!==void 0)throw new sn("Cannot register multiple constructors with identical number of parameters ("+(U-1)+") for class '"+be.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return be.registeredClass.constructor_body[U-1]=()=>{Yi("Cannot construct "+be.name+" due to unbound types",Te)},Be([],Te,function(Je){return Je.splice(1,0,null),be.registeredClass.constructor_body[U-1]=bs(ke,Je,null,he,ve),[]}),[]})}function Ya(R,U,q,le,he,ve,Te,be){var ke=cl(q,le);U=_n(U),ve=xr(he,ve),Be([],[R],function(Je){Je=Je[0];var pt=Je.name+"."+U;U.startsWith("@@")&&(U=Symbol[U.substring(2)]),be&&Je.registeredClass.pureVirtualFunctions.push(U);function Mt(){Yi("Cannot call "+pt+" due to unbound types",ke)}var Tt=Je.registeredClass.instancePrototype,dn=Tt[U];return dn===void 0||dn.overloadTable===void 0&&dn.className!==Je.name&&dn.argCount===q-2?(Mt.argCount=q-2,Mt.className=Je.name,Tt[U]=Mt):(rt(Tt,U,pt),Tt[U].overloadTable[q-2]=Mt),Be([],ke,function(ln){var Xn=bs(pt,ln,Je,ve,Te);return Tt[U].overloadTable===void 0?(Xn.argCount=q-2,Tt[U]=Xn):Tt[U].overloadTable[q-2]=Xn,[]}),[]})}var vi=[],ci=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ul(R){R>4&&--ci[R].refcount===0&&(ci[R]=void 0,vi.push(R))}function so(){for(var R=0,U=5;U(R||rn("Cannot use deleted val. handle = "+R),ci[R].value),toHandle:R=>{switch(R){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var U=vi.length?vi.pop():ci.length;return ci[U]={refcount:1,value:R},U}}}};function fc(R,U){U=_n(U),pi(R,{name:U,fromWireType:function(q){var le=Go.toValue(q);return ul(q),le},toWireType:function(q,le){return Go.toHandle(le)},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:null})}function Ja(R){if(R===null)return"null";var U=typeof R;return U==="object"||U==="array"||U==="function"?R.toString():""+R}function Ji(R,U){switch(U){case 2:return function(q){return this.fromWireType(ue[q>>2])};case 3:return function(q){return this.fromWireType(ce[q>>3])};default:throw new TypeError("Unknown float type: "+R)}}function fl(R,U,q){var le=Sn(q);U=_n(U),pi(R,{name:U,fromWireType:function(he){return he},toWireType:function(he,ve){return ve},argPackAdvance:8,readValueFromPointer:Ji(U,le),destructorFunction:null})}function Bu(R,U,q){switch(U){case 0:return q?function(he){return A[he]}:function(he){return k[he]};case 1:return q?function(he){return F[he>>1]}:function(he){return j[he>>1]};case 2:return q?function(he){return Y[he>>2]}:function(he){return re[he>>2]};default:throw new TypeError("Unknown integer type: "+R)}}function Gu(R,U,q,le,he){U=_n(U);var ve=Sn(q),Te=Mt=>Mt;if(le===0){var be=32-8*q;Te=Mt=>Mt<>>be}var ke=U.includes("unsigned"),Je=(Mt,Tt)=>{},pt;ke?pt=function(Mt,Tt){return Je(Tt,this.name),Tt>>>0}:pt=function(Mt,Tt){return Je(Tt,this.name),Tt},pi(R,{name:U,fromWireType:Te,toWireType:pt,argPackAdvance:8,readValueFromPointer:Bu(U,ve,le!==0),destructorFunction:null})}function dl(R,U,q){var le=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],he=le[U];function ve(Te){Te=Te>>2;var be=re,ke=be[Te],Je=be[Te+1];return new he(G,Je,ke)}q=_n(q),pi(R,{name:q,fromWireType:ve,argPackAdvance:8,readValueFromPointer:ve},{ignoreDuplicateRegistrations:!0})}function Za(R,U){U=_n(U);var q=U==="std::string";pi(R,{name:U,fromWireType:function(le){var he=re[le>>2],ve=le+4,Te;if(q)for(var be=ve,ke=0;ke<=he;++ke){var Je=ve+ke;if(ke==he||k[Je]==0){var pt=Je-be,Mt=P(be,pt);Te===void 0?Te=Mt:(Te+="\0",Te+=Mt),be=Je+1}}else{for(var Tt=new Array(he),ke=0;ke>2]=ve,q&&Te)L(he,ke,ve+1);else if(Te)for(var Je=0;Je255&&(vt(ke),rn("String has UTF-16 code units that do not fit in 8 bits")),k[ke+Je]=pt}else for(var Je=0;Je>1,he=le+U/2;!(le>=he)&&j[le];)++le;if(q=le<<1,q-R>32&&hl)return hl.decode(k.subarray(R,q));for(var ve="",Te=0;!(Te>=U/2);++Te){var be=F[R+Te*2>>1];if(be==0)break;ve+=String.fromCharCode(be)}return ve}function Wu(R,U,q){if(q===void 0&&(q=2147483647),q<2)return 0;q-=2;for(var le=U,he=q>1]=Te,U+=2}return F[U>>1]=0,U-le}function zu(R){return R.length*2}function $u(R,U){for(var q=0,le="";!(q>=U/4);){var he=Y[R+q*4>>2];if(he==0)break;if(++q,he>=65536){var ve=he-65536;le+=String.fromCharCode(55296|ve>>10,56320|ve&1023)}else le+=String.fromCharCode(he)}return le}function ju(R,U,q){if(q===void 0&&(q=2147483647),q<4)return 0;for(var le=U,he=le+q-4,ve=0;ve=55296&&Te<=57343){var be=R.charCodeAt(++ve);Te=65536+((Te&1023)<<10)|be&1023}if(Y[U>>2]=Te,U+=4,U+4>he)break}return Y[U>>2]=0,U-le}function Hu(R){for(var U=0,q=0;q=55296&&le<=57343&&++q,U+=4}return U}function Ku(R,U,q){q=_n(q);var le,he,ve,Te,be;U===2?(le=dc,he=Wu,Te=zu,ve=()=>j,be=1):U===4&&(le=$u,he=ju,Te=Hu,ve=()=>re,be=2),pi(R,{name:q,fromWireType:function(ke){for(var Je=re[ke>>2],pt=ve(),Mt,Tt=ke+4,dn=0;dn<=Je;++dn){var ln=ke+4+dn*U;if(dn==Je||pt[ln>>be]==0){var Xn=ln-Tt,li=le(Tt,Xn);Mt===void 0?Mt=li:(Mt+="\0",Mt+=li),Tt=ln+U}}return vt(ke),Mt},toWireType:function(ke,Je){typeof Je!="string"&&rn("Cannot pass non-string to C++ string type "+q);var pt=Te(Je),Mt=it(4+pt+U);return re[Mt>>2]=pt>>be,he(Je,Mt+4,pt+U),ke!==null&&ke.push(vt,Mt),Mt},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:function(ke){vt(ke)}})}function qu(R,U,q,le,he,ve){tt[R]={name:_n(U),rawConstructor:xr(q,le),rawDestructor:xr(he,ve),fields:[]}}function gl(R,U,q,le,he,ve,Te,be,ke,Je){tt[R].fields.push({fieldName:_n(U),getterReturnType:q,getter:xr(le,he),getterContext:ve,setterArgumentType:Te,setter:xr(be,ke),setterContext:Je})}function Xu(R,U){U=_n(U),pi(R,{isVoid:!0,name:U,argPackAdvance:0,fromWireType:function(){},toWireType:function(q,le){}})}function pl(){throw 1/0}var ml={};function Yu(R){var U=ml[R];return U===void 0?_n(R):U}function hc(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function vl(R){return R===0?Go.toHandle(hc()):(R=Yu(R),Go.toHandle(hc()[R]))}function yl(R){R>4&&(ci[R].refcount+=1)}function gc(R,U){var q=xt[R];return q===void 0&&rn(U+" has unknown type "+ba(R)),q}function Ju(R){for(var U="",q=0;qre,he="return function emval_allocator_"+R+`(constructor, argTypes, args) { +`,ln.push(Tt);var yi=ll(Function,ln).apply(null,Xn);return yi}function gr(R,U,q,le,he,ve){D(U>0);var Te=cl(U,q);he=xr(le,he),Ue([],[R],function(be){be=be[0];var ke="constructor "+be.name;if(be.registeredClass.constructor_body===void 0&&(be.registeredClass.constructor_body=[]),be.registeredClass.constructor_body[U-1]!==void 0)throw new sn("Cannot register multiple constructors with identical number of parameters ("+(U-1)+") for class '"+be.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return be.registeredClass.constructor_body[U-1]=()=>{Yi("Cannot construct "+be.name+" due to unbound types",Te)},Ue([],Te,function(Je){return Je.splice(1,0,null),be.registeredClass.constructor_body[U-1]=bs(ke,Je,null,he,ve),[]}),[]})}function Ya(R,U,q,le,he,ve,Te,be){var ke=cl(q,le);U=_n(U),ve=xr(he,ve),Ue([],[R],function(Je){Je=Je[0];var pt=Je.name+"."+U;U.startsWith("@@")&&(U=Symbol[U.substring(2)]),be&&Je.registeredClass.pureVirtualFunctions.push(U);function Mt(){Yi("Cannot call "+pt+" due to unbound types",ke)}var Tt=Je.registeredClass.instancePrototype,dn=Tt[U];return dn===void 0||dn.overloadTable===void 0&&dn.className!==Je.name&&dn.argCount===q-2?(Mt.argCount=q-2,Mt.className=Je.name,Tt[U]=Mt):(it(Tt,U,pt),Tt[U].overloadTable[q-2]=Mt),Ue([],ke,function(ln){var Xn=bs(pt,ln,Je,ve,Te);return Tt[U].overloadTable===void 0?(Xn.argCount=q-2,Tt[U]=Xn):Tt[U].overloadTable[q-2]=Xn,[]}),[]})}var vi=[],ci=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ul(R){R>4&&--ci[R].refcount===0&&(ci[R]=void 0,vi.push(R))}function so(){for(var R=0,U=5;U(R||rn("Cannot use deleted val. handle = "+R),ci[R].value),toHandle:R=>{switch(R){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var U=vi.length?vi.pop():ci.length;return ci[U]={refcount:1,value:R},U}}}};function fc(R,U){U=_n(U),pi(R,{name:U,fromWireType:function(q){var le=Go.toValue(q);return ul(q),le},toWireType:function(q,le){return Go.toHandle(le)},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:null})}function Ja(R){if(R===null)return"null";var U=typeof R;return U==="object"||U==="array"||U==="function"?R.toString():""+R}function Ji(R,U){switch(U){case 2:return function(q){return this.fromWireType(ue[q>>2])};case 3:return function(q){return this.fromWireType(ce[q>>3])};default:throw new TypeError("Unknown float type: "+R)}}function fl(R,U,q){var le=Sn(q);U=_n(U),pi(R,{name:U,fromWireType:function(he){return he},toWireType:function(he,ve){return ve},argPackAdvance:8,readValueFromPointer:Ji(U,le),destructorFunction:null})}function Bu(R,U,q){switch(U){case 0:return q?function(he){return A[he]}:function(he){return k[he]};case 1:return q?function(he){return F[he>>1]}:function(he){return j[he>>1]};case 2:return q?function(he){return Y[he>>2]}:function(he){return re[he>>2]};default:throw new TypeError("Unknown integer type: "+R)}}function Gu(R,U,q,le,he){U=_n(U);var ve=Sn(q),Te=Mt=>Mt;if(le===0){var be=32-8*q;Te=Mt=>Mt<>>be}var ke=U.includes("unsigned"),Je=(Mt,Tt)=>{},pt;ke?pt=function(Mt,Tt){return Je(Tt,this.name),Tt>>>0}:pt=function(Mt,Tt){return Je(Tt,this.name),Tt},pi(R,{name:U,fromWireType:Te,toWireType:pt,argPackAdvance:8,readValueFromPointer:Bu(U,ve,le!==0),destructorFunction:null})}function dl(R,U,q){var le=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],he=le[U];function ve(Te){Te=Te>>2;var be=re,ke=be[Te],Je=be[Te+1];return new he(G,Je,ke)}q=_n(q),pi(R,{name:q,fromWireType:ve,argPackAdvance:8,readValueFromPointer:ve},{ignoreDuplicateRegistrations:!0})}function Za(R,U){U=_n(U);var q=U==="std::string";pi(R,{name:U,fromWireType:function(le){var he=re[le>>2],ve=le+4,Te;if(q)for(var be=ve,ke=0;ke<=he;++ke){var Je=ve+ke;if(ke==he||k[Je]==0){var pt=Je-be,Mt=P(be,pt);Te===void 0?Te=Mt:(Te+="\0",Te+=Mt),be=Je+1}}else{for(var Tt=new Array(he),ke=0;ke>2]=ve,q&&Te)L(he,ke,ve+1);else if(Te)for(var Je=0;Je255&&(vt(ke),rn("String has UTF-16 code units that do not fit in 8 bits")),k[ke+Je]=pt}else for(var Je=0;Je>1,he=le+U/2;!(le>=he)&&j[le];)++le;if(q=le<<1,q-R>32&&hl)return hl.decode(k.subarray(R,q));for(var ve="",Te=0;!(Te>=U/2);++Te){var be=F[R+Te*2>>1];if(be==0)break;ve+=String.fromCharCode(be)}return ve}function Wu(R,U,q){if(q===void 0&&(q=2147483647),q<2)return 0;q-=2;for(var le=U,he=q>1]=Te,U+=2}return F[U>>1]=0,U-le}function zu(R){return R.length*2}function $u(R,U){for(var q=0,le="";!(q>=U/4);){var he=Y[R+q*4>>2];if(he==0)break;if(++q,he>=65536){var ve=he-65536;le+=String.fromCharCode(55296|ve>>10,56320|ve&1023)}else le+=String.fromCharCode(he)}return le}function ju(R,U,q){if(q===void 0&&(q=2147483647),q<4)return 0;for(var le=U,he=le+q-4,ve=0;ve=55296&&Te<=57343){var be=R.charCodeAt(++ve);Te=65536+((Te&1023)<<10)|be&1023}if(Y[U>>2]=Te,U+=4,U+4>he)break}return Y[U>>2]=0,U-le}function Hu(R){for(var U=0,q=0;q=55296&&le<=57343&&++q,U+=4}return U}function Ku(R,U,q){q=_n(q);var le,he,ve,Te,be;U===2?(le=dc,he=Wu,Te=zu,ve=()=>j,be=1):U===4&&(le=$u,he=ju,Te=Hu,ve=()=>re,be=2),pi(R,{name:q,fromWireType:function(ke){for(var Je=re[ke>>2],pt=ve(),Mt,Tt=ke+4,dn=0;dn<=Je;++dn){var ln=ke+4+dn*U;if(dn==Je||pt[ln>>be]==0){var Xn=ln-Tt,li=le(Tt,Xn);Mt===void 0?Mt=li:(Mt+="\0",Mt+=li),Tt=ln+U}}return vt(ke),Mt},toWireType:function(ke,Je){typeof Je!="string"&&rn("Cannot pass non-string to C++ string type "+q);var pt=Te(Je),Mt=ot(4+pt+U);return re[Mt>>2]=pt>>be,he(Je,Mt+4,pt+U),ke!==null&&ke.push(vt,Mt),Mt},argPackAdvance:8,readValueFromPointer:dt,destructorFunction:function(ke){vt(ke)}})}function qu(R,U,q,le,he,ve){nt[R]={name:_n(U),rawConstructor:xr(q,le),rawDestructor:xr(he,ve),fields:[]}}function gl(R,U,q,le,he,ve,Te,be,ke,Je){nt[R].fields.push({fieldName:_n(U),getterReturnType:q,getter:xr(le,he),getterContext:ve,setterArgumentType:Te,setter:xr(be,ke),setterContext:Je})}function Xu(R,U){U=_n(U),pi(R,{isVoid:!0,name:U,argPackAdvance:0,fromWireType:function(){},toWireType:function(q,le){}})}function pl(){throw 1/0}var ml={};function Yu(R){var U=ml[R];return U===void 0?_n(R):U}function hc(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function vl(R){return R===0?Go.toHandle(hc()):(R=Yu(R),Go.toHandle(hc()[R]))}function yl(R){R>4&&(ci[R].refcount+=1)}function gc(R,U){var q=xt[R];return q===void 0&&rn(U+" has unknown type "+ba(R)),q}function Ju(R){for(var U="",q=0;qre,he="return function emval_allocator_"+R+`(constructor, argTypes, args) { var HEAPU32 = getMemory(); `,q=0;q>2)], 'parameter "+q+`'); var arg`+q+" = argType"+q+`.readValueFromPointer(args); @@ -3788,24 +3788,24 @@ argTypes += 4; `;return he+="var obj = new constructor("+U+`); return valueToHandle(obj); } -`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",he)(gc,o,Go.toHandle,le)}var wl={};function Zu(R,U,q,le){R=Go.toValue(R);var he=wl[U];return he||(he=Ju(U),wl[U]=he),he(R,q,le)}function xl(R,U){R=gc(R,"_emval_take_value");var q=R.readValueFromPointer(U);return Go.toHandle(q)}function Qu(){ie("")}function ef(R,U,q){k.copyWithin(R,U,U+q)}function tf(){return 2147483648}function nf(R){try{return T.grow(R-G.byteLength+65535>>>16),pe(T.buffer),1}catch{}}function pc(R){var U=k.length;R=R>>>0;var q=tf();if(R>q)return!1;let le=(ke,Je)=>ke+(Je-ke%Je)%Je;for(var he=1;he<=4;he*=2){var ve=U*(1+.2/he);ve=Math.min(ve,R+100663296);var Te=Math.min(q,le(Math.max(R,ve),65536)),be=nf(Te);if(be)return!0}return!1}var mc={};function oa(){return l||"./this.program"}function Ia(){if(!Ia.strings){var R=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",U={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:R,_:oa()};for(var q in mc)mc[q]===void 0?delete U[q]:U[q]=mc[q];var le=[];for(var q in U)le.push(q+"="+U[q]);Ia.strings=le}return Ia.strings}function Eo(R,U,q){for(var le=0;le>0]=R.charCodeAt(le);A[U>>0]=0}function Cl(R,U){var q=0;return Ia().forEach(function(le,he){var ve=U+q;re[R+he*4>>2]=ve,Eo(le,ve),q+=le.length+1}),0}function Sl(R,U){var q=Ia();re[R>>2]=q.length;var le=0;return q.forEach(function(he){le+=he.length+1}),re[U>>2]=le,0}function vc(R){f(R,new wt(R))}function _l(R,U){vc(R)}var Is=_l;function Tl(R){return 52}function Q(R,U,q,le,he){return 70}var te=[null,[],[]];function me(R,U){var q=te[R];U===0||U===10?((R===1?C:S)(I(q,0)),q.length=0):q.push(U)}function Ae(R,U,q,le){for(var he=0,ve=0;ve>2],be=re[U+4>>2];U+=8;for(var ke=0;ke>2]=he,0}function He(R){var U=o["_"+R];return U}function Ze(R,U){A.set(R,U)}function Qe(R,U,q,le,he){var ve={string:ln=>{var Xn=0;if(ln!=null&&ln!==0){var li=(ln.length<<2)+1;Xn=X(li),L(ln,Xn,li)}return Xn},array:ln=>{var Xn=X(ln.length);return Ze(ln,Xn),Xn}};function Te(ln){return U==="string"?P(ln):U==="boolean"?!!ln:ln}var be=He(R),ke=[],Je=0;if(le)for(var pt=0;pt0||(O(),xe>0))return;function U(){$||($=!0,o.calledRun=!0,!E&&(z(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),W()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),U()},1)):U()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return H(),i.ready}})();t.exports=r})(iG);var cxe=iG.exports;const lxe=ac(cxe),uxe=new URL("/static/dv3d/libjpegturbowasm_decode.wasm",import.meta.url),V2={codec:void 0,decoder:void 0};function fxe(){if(V2.codec)return Promise.resolve();const t=lxe({locateFile:e=>e.endsWith(".wasm")?uxe.toString():e});return new Promise((e,r)=>{t.then(n=>{V2.codec=n,V2.decoder=new n.JPEGDecoder,e()},r)})}async function dxe(t,e){await fxe();const r=V2.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer(),a={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},s=hxe(i,o),c={frameInfo:i};return{...e,pixelData:s,imageInfo:a,encodeOptions:c,...c,...a}}function hxe(t,e){return t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const gxe="modulepreload",pxe=function(t){return"/static/dv3d/"+t},Mb={},oG=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),s=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(r.map(c=>{if(c=pxe(c),c in Mb)return;Mb[c]=!0;const l=c.endsWith(".css"),f=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${f}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":gxe,l||(u.as="script"),u.crossOrigin="",u.href=c,s&&u.setAttribute("nonce",s),document.head.appendChild(u),l)return new Promise((d,h)=>{u.addEventListener("load",d),u.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return i.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},qg={JpegImage:void 0,decodeConfig:{}};function mxe(t){return qg.decodeConfig=t,qg.JpegImage?Promise.resolve():new Promise((e,r)=>{oG(()=>import("./jpeg.js"),[]).then(n=>{qg.JpegImage=n.default,e()}).catch(r)})}async function vxe(t,e){if(await mxe(),typeof qg.JpegImage>"u")throw new Error("No JPEG Baseline decoder loaded");const r=new qg.JpegImage;if(r.parse(e),r.colorTransform=!1,t.bitsAllocated===8)return t.pixelData=r.getData(t.columns,t.rows),t;if(t.bitsAllocated===16)return t.pixelData=r.getData16(t.columns,t.rows),t}const Xg={jpeg:void 0,decodeConfig:{}};function yxe(t){return Xg.decodeConfig=t,Xg.jpeg?Promise.resolve():new Promise((e,r)=>{oG(async()=>{const{Decoder:n}=await import("./lossless.js");return{Decoder:n}},[]).then(({Decoder:n})=>{const i=new n;Xg.jpeg=i,e()},r)})}async function Pb(t,e){if(await yxe(),typeof Xg.jpeg>"u")throw new Error("No JPEG Lossless decoder loaded");const r=t.bitsAllocated<=8?1:2,n=e.buffer,i=Xg.jpeg.decode(n,e.byteOffset,e.length,r);return t.pixelRepresentation===0?t.bitsAllocated===16?(t.pixelData=new Uint16Array(i.buffer),t):(t.pixelData=new Uint8Array(i.buffer),t):(t.pixelData=new Int16Array(i.buffer),t)}var aG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(Q,te){a=Q,s=te});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(Q){return o.locateFile?o.locateFile(Q,d):d+Q}var g,p,v;if(u){var y=Js,m=Js;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(Q,te)=>(Q=ie(Q)?new URL(Q):m.normalize(Q),y.readFileSync(Q,te?void 0:"utf8")),v=Q=>{var te=g(Q,!0);return te.buffer||(te=new Uint8Array(te)),te},p=(Q,te,me)=>{Q=ie(Q)?new URL(Q):m.normalize(Q),y.readFile(Q,function(Ae,He){Ae?me(Ae):te(He.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(Q){if(!(Q instanceof Fe))throw Q}),process.on("unhandledRejection",function(Q){throw Q}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=Q=>{var te=new XMLHttpRequest;return te.open("GET",Q,!1),te.send(null),te.responseText},f&&(v=Q=>{var te=new XMLHttpRequest;return te.open("GET",Q,!1),te.responseType="arraybuffer",te.send(null),new Uint8Array(te.response)}),p=(Q,te,me)=>{var Ae=new XMLHttpRequest;Ae.open("GET",Q,!0),Ae.responseType="arraybuffer",Ae.onload=()=>{if(Ae.status==200||Ae.status==0&&Ae.response){te(Ae.response);return}me()},Ae.onerror=me,Ae.send(null)});o.print||console.log.bind(console);var w=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var x;o.wasmBinary&&(x=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&De("no native wasm support detected");var C,S=!1;function _(Q,te){Q||De(te)}var T=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function E(Q,te,me){for(var Ae=te+me,He=te;Q[He]&&!(He>=Ae);)++He;if(He-te>16&&Q.buffer&&T)return T.decode(Q.subarray(te,He));for(var Ze="";te>10,56320|vt&1023)}}return Ze}function D(Q,te){return Q?E(V,Q,te):""}function b(Q,te,me,Ae){if(!(Ae>0))return 0;for(var He=me,Ze=me+Ae-1,Qe=0;Qe=55296&&qe<=57343){var it=Q.charCodeAt(++Qe);qe=65536+((qe&1023)<<10)|it&1023}if(qe<=127){if(me>=Ze)break;te[me++]=qe}else if(qe<=2047){if(me+1>=Ze)break;te[me++]=192|qe>>6,te[me++]=128|qe&63}else if(qe<=65535){if(me+2>=Ze)break;te[me++]=224|qe>>12,te[me++]=128|qe>>6&63,te[me++]=128|qe&63}else{if(me+3>=Ze)break;te[me++]=240|qe>>18,te[me++]=128|qe>>12&63,te[me++]=128|qe>>6&63,te[me++]=128|qe&63}}return te[me]=0,me-He}function I(Q,te,me){return b(Q,V,te,me)}function P(Q){for(var te=0,me=0;me=55296&&Ae<=57343?(te+=4,++me):te+=3}return te}var M,L,V,G,A,k,F,j,Y;function re(Q){M=Q,o.HEAP8=L=new Int8Array(Q),o.HEAP16=G=new Int16Array(Q),o.HEAP32=k=new Int32Array(Q),o.HEAPU8=V=new Uint8Array(Q),o.HEAPU16=A=new Uint16Array(Q),o.HEAPU32=F=new Uint32Array(Q),o.HEAPF32=j=new Float32Array(Q),o.HEAPF64=Y=new Float64Array(Q)}o.INITIAL_MEMORY;var ue,ce=[],pe=[],Ee=[];function Oe(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)O(o.preRun.shift());oe(ce)}function Se(){oe(pe)}function B(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)W(o.postRun.shift());oe(Ee)}function O(Q){ce.unshift(Q)}function z(Q){pe.unshift(Q)}function W(Q){Ee.unshift(Q)}var K=0,Z=null;function ee(Q){K++,o.monitorRunDependencies&&o.monitorRunDependencies(K)}function xe(Q){if(K--,o.monitorRunDependencies&&o.monitorRunDependencies(K),K==0&&Z){var te=Z;Z=null,te()}}function De(Q){o.onAbort&&o.onAbort(Q),Q="Aborted("+Q+")",w(Q),S=!0,Q+=". Build with -sASSERTIONS for more info.";var te=new WebAssembly.RuntimeError(Q);throw s(te),te}var Ne="data:application/octet-stream;base64,";function ze(Q){return Q.startsWith(Ne)}function ie(Q){return Q.startsWith("file://")}var ae;ae="charlswasm_decode.wasm",ze(ae)||(ae=h(ae));function we(Q){try{if(Q==ae&&x)return new Uint8Array(x);if(v)return v(Q);throw"both async and sync fetching of the wasm failed"}catch(te){De(te)}}function se(){if(!x&&(l||f)){if(typeof fetch=="function"&&!ie(ae))return fetch(ae,{credentials:"same-origin"}).then(function(Q){if(!Q.ok)throw"failed to load wasm binary file at '"+ae+"'";return Q.arrayBuffer()}).catch(function(){return we(ae)});if(p)return new Promise(function(Q,te){p(ae,function(me){Q(new Uint8Array(me))},te)})}return Promise.resolve().then(function(){return we(ae)})}function ge(){var Q={a:mc};function te(Qe,qe){var it=Qe.exports;o.asm=it,C=o.asm.z,re(C.buffer),ue=o.asm.C,z(o.asm.A),xe()}ee();function me(Qe){te(Qe.instance)}function Ae(Qe){return se().then(function(qe){return WebAssembly.instantiate(qe,Q)}).then(function(qe){return qe}).then(Qe,function(qe){w("failed to asynchronously prepare wasm: "+qe),De(qe)})}function He(){return!x&&typeof WebAssembly.instantiateStreaming=="function"&&!ze(ae)&&!ie(ae)&&!u&&typeof fetch=="function"?fetch(ae,{credentials:"same-origin"}).then(function(Qe){var qe=WebAssembly.instantiateStreaming(Qe,Q);return qe.then(me,function(it){return w("wasm streaming compile failed: "+it),w("falling back to ArrayBuffer instantiation"),Ae(me)})}):Ae(me)}if(o.instantiateWasm)try{var Ze=o.instantiateWasm(Q,te);return Ze}catch(Qe){w("Module.instantiateWasm callback failed with error: "+Qe),s(Qe)}return He().catch(s),{}}function Fe(Q){this.name="ExitStatus",this.message="Program terminated with exit("+Q+")",this.status=Q}function oe(Q){for(;Q.length>0;)Q.shift()(o)}function ht(Q){this.excPtr=Q,this.ptr=Q-24,this.set_type=function(te){F[this.ptr+4>>2]=te},this.get_type=function(){return F[this.ptr+4>>2]},this.set_destructor=function(te){F[this.ptr+8>>2]=te},this.get_destructor=function(){return F[this.ptr+8>>2]},this.set_refcount=function(te){k[this.ptr>>2]=te},this.set_caught=function(te){te=te?1:0,L[this.ptr+12>>0]=te},this.get_caught=function(){return L[this.ptr+12>>0]!=0},this.set_rethrown=function(te){te=te?1:0,L[this.ptr+13>>0]=te},this.get_rethrown=function(){return L[this.ptr+13>>0]!=0},this.init=function(te,me){this.set_adjusted_ptr(0),this.set_type(te),this.set_destructor(me),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var te=k[this.ptr>>2];k[this.ptr>>2]=te+1},this.release_ref=function(){var te=k[this.ptr>>2];return k[this.ptr>>2]=te-1,te===1},this.set_adjusted_ptr=function(te){F[this.ptr+16>>2]=te},this.get_adjusted_ptr=function(){return F[this.ptr+16>>2]},this.get_exception_ptr=function(){var te=_l(this.get_type());if(te)return F[this.excPtr>>2];var me=this.get_adjusted_ptr();return me!==0?me:this.excPtr}}function wt(Q,te,me){var Ae=new ht(Q);throw Ae.init(te,me),Q}var gt={};function Ie(Q){for(;Q.length;){var te=Q.pop(),me=Q.pop();me(te)}}function $e(Q){return this.fromWireType(k[Q>>2])}var tt={},nt={},dt={},Lt=48,xt=57;function Ft(Q){if(Q===void 0)return"_unknown";Q=Q.replace(/[^a-zA-Z0-9_]/g,"$");var te=Q.charCodeAt(0);return te>=Lt&&te<=xt?"_"+Q:Q}function jt(Q,te){return Q=Ft(Q),new Function("body","return function "+Q+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",he)(gc,o,Go.toHandle,le)}var wl={};function Zu(R,U,q,le){R=Go.toValue(R);var he=wl[U];return he||(he=Ju(U),wl[U]=he),he(R,q,le)}function xl(R,U){R=gc(R,"_emval_take_value");var q=R.readValueFromPointer(U);return Go.toHandle(q)}function Qu(){ie("")}function ef(R,U,q){k.copyWithin(R,U,U+q)}function tf(){return 2147483648}function nf(R){try{return T.grow(R-G.byteLength+65535>>>16),pe(T.buffer),1}catch{}}function pc(R){var U=k.length;R=R>>>0;var q=tf();if(R>q)return!1;let le=(ke,Je)=>ke+(Je-ke%Je)%Je;for(var he=1;he<=4;he*=2){var ve=U*(1+.2/he);ve=Math.min(ve,R+100663296);var Te=Math.min(q,le(Math.max(R,ve),65536)),be=nf(Te);if(be)return!0}return!1}var mc={};function oa(){return l||"./this.program"}function Ia(){if(!Ia.strings){var R=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",U={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:R,_:oa()};for(var q in mc)mc[q]===void 0?delete U[q]:U[q]=mc[q];var le=[];for(var q in U)le.push(q+"="+U[q]);Ia.strings=le}return Ia.strings}function Eo(R,U,q){for(var le=0;le>0]=R.charCodeAt(le);A[U>>0]=0}function Cl(R,U){var q=0;return Ia().forEach(function(le,he){var ve=U+q;re[R+he*4>>2]=ve,Eo(le,ve),q+=le.length+1}),0}function Sl(R,U){var q=Ia();re[R>>2]=q.length;var le=0;return q.forEach(function(he){le+=he.length+1}),re[U>>2]=le,0}function vc(R){f(R,new wt(R))}function _l(R,U){vc(R)}var Is=_l;function Tl(R){return 52}function Q(R,U,q,le,he){return 70}var te=[null,[],[]];function me(R,U){var q=te[R];U===0||U===10?((R===1?C:S)(I(q,0)),q.length=0):q.push(U)}function Ae(R,U,q,le){for(var he=0,ve=0;ve>2],be=re[U+4>>2];U+=8;for(var ke=0;ke>2]=he,0}function He(R){var U=o["_"+R];return U}function Ze(R,U){A.set(R,U)}function Qe(R,U,q,le,he){var ve={string:ln=>{var Xn=0;if(ln!=null&&ln!==0){var li=(ln.length<<2)+1;Xn=X(li),L(ln,Xn,li)}return Xn},array:ln=>{var Xn=X(ln.length);return Ze(ln,Xn),Xn}};function Te(ln){return U==="string"?P(ln):U==="boolean"?!!ln:ln}var be=He(R),ke=[],Je=0;if(le)for(var pt=0;pt0||(O(),xe>0))return;function U(){$||($=!0,o.calledRun=!0,!E&&(z(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),W()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),U()},1)):U()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return H(),i.ready}})();t.exports=r})(iG);var cxe=iG.exports;const lxe=ac(cxe),uxe=new URL("/static/dv3d/libjpegturbowasm_decode.wasm",import.meta.url),V2={codec:void 0,decoder:void 0};function fxe(){if(V2.codec)return Promise.resolve();const t=lxe({locateFile:e=>e.endsWith(".wasm")?uxe.toString():e});return new Promise((e,r)=>{t.then(n=>{V2.codec=n,V2.decoder=new n.JPEGDecoder,e()},r)})}async function dxe(t,e){await fxe();const r=V2.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer(),a={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},s=hxe(i,o),c={frameInfo:i};return{...e,pixelData:s,imageInfo:a,encodeOptions:c,...c,...a}}function hxe(t,e){return t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const gxe="modulepreload",pxe=function(t){return"/static/dv3d/"+t},Mb={},oG=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),s=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(r.map(c=>{if(c=pxe(c),c in Mb)return;Mb[c]=!0;const l=c.endsWith(".css"),f=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${f}`))return;const u=document.createElement("link");if(u.rel=l?"stylesheet":gxe,l||(u.as="script"),u.crossOrigin="",u.href=c,s&&u.setAttribute("nonce",s),document.head.appendChild(u),l)return new Promise((d,h)=>{u.addEventListener("load",d),u.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return i.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},qg={JpegImage:void 0,decodeConfig:{}};function mxe(t){return qg.decodeConfig=t,qg.JpegImage?Promise.resolve():new Promise((e,r)=>{oG(()=>import("./jpeg.js"),[]).then(n=>{qg.JpegImage=n.default,e()}).catch(r)})}async function vxe(t,e){if(await mxe(),typeof qg.JpegImage>"u")throw new Error("No JPEG Baseline decoder loaded");const r=new qg.JpegImage;if(r.parse(e),r.colorTransform=!1,t.bitsAllocated===8)return t.pixelData=r.getData(t.columns,t.rows),t;if(t.bitsAllocated===16)return t.pixelData=r.getData16(t.columns,t.rows),t}const Xg={jpeg:void 0,decodeConfig:{}};function yxe(t){return Xg.decodeConfig=t,Xg.jpeg?Promise.resolve():new Promise((e,r)=>{oG(async()=>{const{Decoder:n}=await import("./lossless.js");return{Decoder:n}},[]).then(({Decoder:n})=>{const i=new n;Xg.jpeg=i,e()},r)})}async function Pb(t,e){if(await yxe(),typeof Xg.jpeg>"u")throw new Error("No JPEG Lossless decoder loaded");const r=t.bitsAllocated<=8?1:2,n=e.buffer,i=Xg.jpeg.decode(n,e.byteOffset,e.length,r);return t.pixelRepresentation===0?t.bitsAllocated===16?(t.pixelData=new Uint16Array(i.buffer),t):(t.pixelData=new Uint8Array(i.buffer),t):(t.pixelData=new Int16Array(i.buffer),t)}var aG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(Q,te){a=Q,s=te});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h(Q){return o.locateFile?o.locateFile(Q,d):d+Q}var g,p,v;if(u){var y=Js,m=Js;f?d=m.dirname(d)+"/":d=__dirname+"/",g=(Q,te)=>(Q=ie(Q)?new URL(Q):m.normalize(Q),y.readFileSync(Q,te?void 0:"utf8")),v=Q=>{var te=g(Q,!0);return te.buffer||(te=new Uint8Array(te)),te},p=(Q,te,me)=>{Q=ie(Q)?new URL(Q):m.normalize(Q),y.readFile(Q,function(Ae,He){Ae?me(Ae):te(He.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(Q){if(!(Q instanceof Fe))throw Q}),process.on("unhandledRejection",function(Q){throw Q}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=Q=>{var te=new XMLHttpRequest;return te.open("GET",Q,!1),te.send(null),te.responseText},f&&(v=Q=>{var te=new XMLHttpRequest;return te.open("GET",Q,!1),te.responseType="arraybuffer",te.send(null),new Uint8Array(te.response)}),p=(Q,te,me)=>{var Ae=new XMLHttpRequest;Ae.open("GET",Q,!0),Ae.responseType="arraybuffer",Ae.onload=()=>{if(Ae.status==200||Ae.status==0&&Ae.response){te(Ae.response);return}me()},Ae.onerror=me,Ae.send(null)});o.print||console.log.bind(console);var w=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var x;o.wasmBinary&&(x=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&De("no native wasm support detected");var C,S=!1;function _(Q,te){Q||De(te)}var T=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function E(Q,te,me){for(var Ae=te+me,He=te;Q[He]&&!(He>=Ae);)++He;if(He-te>16&&Q.buffer&&T)return T.decode(Q.subarray(te,He));for(var Ze="";te>10,56320|vt&1023)}}return Ze}function D(Q,te){return Q?E(V,Q,te):""}function b(Q,te,me,Ae){if(!(Ae>0))return 0;for(var He=me,Ze=me+Ae-1,Qe=0;Qe=55296&&qe<=57343){var ot=Q.charCodeAt(++Qe);qe=65536+((qe&1023)<<10)|ot&1023}if(qe<=127){if(me>=Ze)break;te[me++]=qe}else if(qe<=2047){if(me+1>=Ze)break;te[me++]=192|qe>>6,te[me++]=128|qe&63}else if(qe<=65535){if(me+2>=Ze)break;te[me++]=224|qe>>12,te[me++]=128|qe>>6&63,te[me++]=128|qe&63}else{if(me+3>=Ze)break;te[me++]=240|qe>>18,te[me++]=128|qe>>12&63,te[me++]=128|qe>>6&63,te[me++]=128|qe&63}}return te[me]=0,me-He}function I(Q,te,me){return b(Q,V,te,me)}function P(Q){for(var te=0,me=0;me=55296&&Ae<=57343?(te+=4,++me):te+=3}return te}var M,L,V,G,A,k,F,j,Y;function re(Q){M=Q,o.HEAP8=L=new Int8Array(Q),o.HEAP16=G=new Int16Array(Q),o.HEAP32=k=new Int32Array(Q),o.HEAPU8=V=new Uint8Array(Q),o.HEAPU16=A=new Uint16Array(Q),o.HEAPU32=F=new Uint32Array(Q),o.HEAPF32=j=new Float32Array(Q),o.HEAPF64=Y=new Float64Array(Q)}o.INITIAL_MEMORY;var ue,ce=[],pe=[],Ee=[];function Oe(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)O(o.preRun.shift());oe(ce)}function _e(){oe(pe)}function B(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)W(o.postRun.shift());oe(Ee)}function O(Q){ce.unshift(Q)}function z(Q){pe.unshift(Q)}function W(Q){Ee.unshift(Q)}var K=0,Z=null;function ee(Q){K++,o.monitorRunDependencies&&o.monitorRunDependencies(K)}function xe(Q){if(K--,o.monitorRunDependencies&&o.monitorRunDependencies(K),K==0&&Z){var te=Z;Z=null,te()}}function De(Q){o.onAbort&&o.onAbort(Q),Q="Aborted("+Q+")",w(Q),S=!0,Q+=". Build with -sASSERTIONS for more info.";var te=new WebAssembly.RuntimeError(Q);throw s(te),te}var Ne="data:application/octet-stream;base64,";function $e(Q){return Q.startsWith(Ne)}function ie(Q){return Q.startsWith("file://")}var ae;ae="charlswasm_decode.wasm",$e(ae)||(ae=h(ae));function ye(Q){try{if(Q==ae&&x)return new Uint8Array(x);if(v)return v(Q);throw"both async and sync fetching of the wasm failed"}catch(te){De(te)}}function se(){if(!x&&(l||f)){if(typeof fetch=="function"&&!ie(ae))return fetch(ae,{credentials:"same-origin"}).then(function(Q){if(!Q.ok)throw"failed to load wasm binary file at '"+ae+"'";return Q.arrayBuffer()}).catch(function(){return ye(ae)});if(p)return new Promise(function(Q,te){p(ae,function(me){Q(new Uint8Array(me))},te)})}return Promise.resolve().then(function(){return ye(ae)})}function ge(){var Q={a:mc};function te(Qe,qe){var ot=Qe.exports;o.asm=ot,C=o.asm.z,re(C.buffer),ue=o.asm.C,z(o.asm.A),xe()}ee();function me(Qe){te(Qe.instance)}function Ae(Qe){return se().then(function(qe){return WebAssembly.instantiate(qe,Q)}).then(function(qe){return qe}).then(Qe,function(qe){w("failed to asynchronously prepare wasm: "+qe),De(qe)})}function He(){return!x&&typeof WebAssembly.instantiateStreaming=="function"&&!$e(ae)&&!ie(ae)&&!u&&typeof fetch=="function"?fetch(ae,{credentials:"same-origin"}).then(function(Qe){var qe=WebAssembly.instantiateStreaming(Qe,Q);return qe.then(me,function(ot){return w("wasm streaming compile failed: "+ot),w("falling back to ArrayBuffer instantiation"),Ae(me)})}):Ae(me)}if(o.instantiateWasm)try{var Ze=o.instantiateWasm(Q,te);return Ze}catch(Qe){w("Module.instantiateWasm callback failed with error: "+Qe),s(Qe)}return He().catch(s),{}}function Fe(Q){this.name="ExitStatus",this.message="Program terminated with exit("+Q+")",this.status=Q}function oe(Q){for(;Q.length>0;)Q.shift()(o)}function ht(Q){this.excPtr=Q,this.ptr=Q-24,this.set_type=function(te){F[this.ptr+4>>2]=te},this.get_type=function(){return F[this.ptr+4>>2]},this.set_destructor=function(te){F[this.ptr+8>>2]=te},this.get_destructor=function(){return F[this.ptr+8>>2]},this.set_refcount=function(te){k[this.ptr>>2]=te},this.set_caught=function(te){te=te?1:0,L[this.ptr+12>>0]=te},this.get_caught=function(){return L[this.ptr+12>>0]!=0},this.set_rethrown=function(te){te=te?1:0,L[this.ptr+13>>0]=te},this.get_rethrown=function(){return L[this.ptr+13>>0]!=0},this.init=function(te,me){this.set_adjusted_ptr(0),this.set_type(te),this.set_destructor(me),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var te=k[this.ptr>>2];k[this.ptr>>2]=te+1},this.release_ref=function(){var te=k[this.ptr>>2];return k[this.ptr>>2]=te-1,te===1},this.set_adjusted_ptr=function(te){F[this.ptr+16>>2]=te},this.get_adjusted_ptr=function(){return F[this.ptr+16>>2]},this.get_exception_ptr=function(){var te=_l(this.get_type());if(te)return F[this.excPtr>>2];var me=this.get_adjusted_ptr();return me!==0?me:this.excPtr}}function wt(Q,te,me){var Ae=new ht(Q);throw Ae.init(te,me),Q}var gt={};function Ie(Q){for(;Q.length;){var te=Q.pop(),me=Q.pop();me(te)}}function je(Q){return this.fromWireType(k[Q>>2])}var nt={},rt={},dt={},Lt=48,xt=57;function Ft(Q){if(Q===void 0)return"_unknown";Q=Q.replace(/[^a-zA-Z0-9_]/g,"$");var te=Q.charCodeAt(0);return te>=Lt&&te<=xt?"_"+Q:Q}function jt(Q,te){return Q=Ft(Q),new Function("body","return function "+Q+`() { "use strict"; return body.apply(this, arguments); }; `)(te)}function Pn(Q,te){var me=jt(te,function(Ae){this.name=te,this.message=Ae;var He=new Error(Ae).stack;He!==void 0&&(this.stack=this.toString()+` -`+He.replace(/^Error(:[^\n]*)?\n/,""))});return me.prototype=Object.create(Q.prototype),me.prototype.constructor=me,me.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},me}var $n=void 0;function fn(Q){throw new $n(Q)}function bn(Q,te,me){Q.forEach(function(qe){dt[qe]=te});function Ae(qe){var it=me(qe);it.length!==Q.length&&fn("Mismatched type converter count");for(var vt=0;vt{nt.hasOwnProperty(qe)?He[it]=nt[qe]:(Ze.push(qe),tt.hasOwnProperty(qe)||(tt[qe]=[]),tt[qe].push(()=>{He[it]=nt[qe],++Qe,Qe===Ze.length&&Ae(He)}))}),Ze.length===0&&Ae(He)}function Xi(Q){var te=gt[Q];delete gt[Q];var me=te.rawConstructor,Ae=te.rawDestructor,He=te.fields,Ze=He.map(Qe=>Qe.getterReturnType).concat(He.map(Qe=>Qe.setterArgumentType));bn([Q],Ze,Qe=>{var qe={};return He.forEach((it,vt)=>{var kt=it.fieldName,Wt=Qe[vt],Kt=it.getter,J=it.getterContext,X=Qe[vt+He.length],fe=it.setter,Me=it.setterContext;qe[kt]={read:We=>Wt.fromWireType(Kt(J,We)),write:(We,ct)=>{var et=[];fe(Me,We,X.toWireType(et,ct)),Ie(et)}}}),[{name:te.name,fromWireType:function(it){var vt={};for(var kt in qe)vt[kt]=qe[kt].read(it);return Ae(it),vt},toWireType:function(it,vt){for(var kt in qe)if(!(kt in vt))throw new TypeError('Missing field: "'+kt+'"');var Wt=me();for(kt in qe)qe[kt].write(Wt,vt[kt]);return it!==null&&it.push(Ae,Wt),Wt},argPackAdvance:8,readValueFromPointer:$e,destructorFunction:Ae}]})}function Mr(Q,te,me,Ae,He){}function Be(Q){switch(Q){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+Q)}}function ft(){for(var Q=new Array(256),te=0;te<256;++te)Q[te]=String.fromCharCode(te);Ut=Q}var Ut=void 0;function Sn(Q){for(var te="",me=Q;V[me];)te+=Ut[V[me++]];return te}var Qn=void 0;function Pt(Q){throw new Qn(Q)}function _n(Q,te,me={}){if(!("argPackAdvance"in te))throw new TypeError("registerType registeredInstance requires argPackAdvance");var Ae=te.name;if(Q||Pt('type "'+Ae+'" must have a positive integer typeid pointer'),nt.hasOwnProperty(Q)){if(me.ignoreDuplicateRegistrations)return;Pt("Cannot register type '"+Ae+"' twice")}if(nt[Q]=te,delete dt[Q],tt.hasOwnProperty(Q)){var He=tt[Q];delete tt[Q],He.forEach(Ze=>Ze())}}function sn(Q,te,me,Ae,He){var Ze=Be(me);te=Sn(te),_n(Q,{name:te,fromWireType:function(Qe){return!!Qe},toWireType:function(Qe,qe){return qe?Ae:He},argPackAdvance:8,readValueFromPointer:function(Qe){var qe;if(me===1)qe=L;else if(me===2)qe=G;else if(me===4)qe=k;else throw new TypeError("Unknown boolean type size: "+te);return this.fromWireType(qe[Qe>>Ze])},destructorFunction:null})}function rn(Q){if(!(this instanceof je)||!(Q instanceof je))return!1;for(var te=this.$$.ptrType.registeredClass,me=this.$$.ptr,Ae=Q.$$.ptrType.registeredClass,He=Q.$$.ptr;te.baseClass;)me=te.upcast(me),te=te.baseClass;for(;Ae.baseClass;)He=Ae.upcast(He),Ae=Ae.baseClass;return te===Ae&&me===He}function pi(Q){return{count:Q.count,deleteScheduled:Q.deleteScheduled,preservePointerOnDelete:Q.preservePointerOnDelete,ptr:Q.ptr,ptrType:Q.ptrType,smartPtr:Q.smartPtr,smartPtrType:Q.smartPtrType}}function Vi(Q){function te(me){return me.$$.ptrType.registeredClass.name}Pt(te(Q)+" instance already deleted")}var Ha=!1;function Ea(Q){}function To(Q){Q.smartPtr?Q.smartPtrType.rawDestructor(Q.smartPtr):Q.ptrType.registeredClass.rawDestructor(Q.ptr)}function ra(Q){Q.count.value-=1;var te=Q.count.value===0;te&&To(Q)}function Uo(Q,te,me){if(te===me)return Q;if(me.baseClass===void 0)return null;var Ae=Uo(Q,te,me.baseClass);return Ae===null?null:me.downcast(Ae)}var fr={};function oo(){return Object.keys(mi).length}function yn(){var Q=[];for(var te in mi)mi.hasOwnProperty(te)&&Q.push(mi[te]);return Q}var Qr=[];function Da(){for(;Qr.length;){var Q=Qr.pop();Q.$$.deleteScheduled=!1,Q.delete()}}var Fi=void 0;function ao(Q){Fi=Q,Qr.length&&Fi&&Fi(Da)}function Ui(){o.getInheritedInstanceCount=oo,o.getLiveInheritedInstances=yn,o.flushPendingDeletes=Da,o.setDelayFunction=ao}var mi={};function Ka(Q,te){for(te===void 0&&Pt("ptr should not be undefined");Q.baseClass;)te=Q.upcast(te),Q=Q.baseClass;return te}function Bo(Q,te){return te=Ka(Q,te),mi[te]}function Bi(Q,te){(!te.ptrType||!te.ptr)&&fn("makeClassHandle requires ptr and ptrType");var me=!!te.smartPtrType,Ae=!!te.smartPtr;return me!==Ae&&fn("Both smartPtrType and smartPtr must be specified"),te.count={value:1},Gi(Object.create(Q,{$$:{value:te}}))}function qa(Q){var te=this.getPointee(Q);if(!te)return this.destructor(Q),null;var me=Bo(this.registeredClass,te);if(me!==void 0){if(me.$$.count.value===0)return me.$$.ptr=te,me.$$.smartPtr=Q,me.clone();var Ae=me.clone();return this.destructor(Q),Ae}function He(){return this.isSmartPointer?Bi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:te,smartPtrType:this,smartPtr:Q}):Bi(this.registeredClass.instancePrototype,{ptrType:this,ptr:Q})}var Ze=this.registeredClass.getActualType(te),Qe=fr[Ze];if(!Qe)return He.call(this);var qe;this.isConst?qe=Qe.constPointerType:qe=Qe.pointerType;var it=Uo(te,this.registeredClass,qe.registeredClass);return it===null?He.call(this):this.isSmartPointer?Bi(qe.registeredClass.instancePrototype,{ptrType:qe,ptr:it,smartPtrType:this,smartPtr:Q}):Bi(qe.registeredClass.instancePrototype,{ptrType:qe,ptr:it})}function Gi(Q){return typeof FinalizationRegistry>"u"?(Gi=te=>te,Q):(Ha=new FinalizationRegistry(te=>{ra(te.$$)}),Gi=te=>{var me=te.$$,Ae=!!me.smartPtr;if(Ae){var He={$$:me};Ha.register(te,He,te)}return te},Ea=te=>Ha.unregister(te),Gi(Q))}function ia(){if(this.$$.ptr||Vi(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var Q=Gi(Object.create(Object.getPrototypeOf(this),{$$:{value:pi(this.$$)}}));return Q.$$.count.value+=1,Q.$$.deleteScheduled=!1,Q}function de(){this.$$.ptr||Vi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Pt("Object already scheduled for deletion"),Ea(this),ra(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Ue(){return!this.$$.ptr}function _e(){return this.$$.ptr||Vi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Pt("Object already scheduled for deletion"),Qr.push(this),Qr.length===1&&Fi&&Fi(Da),this.$$.deleteScheduled=!0,this}function ye(){je.prototype.isAliasOf=rn,je.prototype.clone=ia,je.prototype.delete=de,je.prototype.isDeleted=Ue,je.prototype.deleteLater=_e}function je(){}function ot(Q,te,me){if(Q[te].overloadTable===void 0){var Ae=Q[te];Q[te]=function(){return Q[te].overloadTable.hasOwnProperty(arguments.length)||Pt("Function '"+me+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+Q[te].overloadTable+")!"),Q[te].overloadTable[arguments.length].apply(this,arguments)},Q[te].overloadTable=[],Q[te].overloadTable[Ae.argCount]=Ae}}function st(Q,te,me){o.hasOwnProperty(Q)?((me===void 0||o[Q].overloadTable!==void 0&&o[Q].overloadTable[me]!==void 0)&&Pt("Cannot register public name '"+Q+"' twice"),ot(o,Q,Q),o.hasOwnProperty(me)&&Pt("Cannot register multiple overloads of a function with the same number of arguments ("+me+")!"),o[Q].overloadTable[me]=te):(o[Q]=te,me!==void 0&&(o[Q].numArguments=me))}function ut(Q,te,me,Ae,He,Ze,Qe,qe){this.name=Q,this.constructor=te,this.instancePrototype=me,this.rawDestructor=Ae,this.baseClass=He,this.getActualType=Ze,this.upcast=Qe,this.downcast=qe,this.pureVirtualFunctions=[]}function rt(Q,te,me){for(;te!==me;)te.upcast||Pt("Expected null or instance of "+me.name+", got an instance of "+te.name),Q=te.upcast(Q),te=te.baseClass;return Q}function Ct(Q,te){if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name);var me=te.$$.ptrType.registeredClass,Ae=rt(te.$$.ptr,me,this.registeredClass);return Ae}function Qt(Q,te){var me;if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),this.isSmartPointer?(me=this.rawConstructor(),Q!==null&&Q.push(this.rawDestructor,me),me):0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&te.$$.ptrType.isConst&&Pt("Cannot convert argument of type "+(te.$$.smartPtrType?te.$$.smartPtrType.name:te.$$.ptrType.name)+" to parameter type "+this.name);var Ae=te.$$.ptrType.registeredClass;if(me=rt(te.$$.ptr,Ae,this.registeredClass),this.isSmartPointer)switch(te.$$.smartPtr===void 0&&Pt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:te.$$.smartPtrType===this?me=te.$$.smartPtr:Pt("Cannot convert argument of type "+(te.$$.smartPtrType?te.$$.smartPtrType.name:te.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:me=te.$$.smartPtr;break;case 2:if(te.$$.smartPtrType===this)me=te.$$.smartPtr;else{var He=te.clone();me=this.rawShare(me,so.toHandle(function(){He.delete()})),Q!==null&&Q.push(this.rawDestructor,me)}break;default:Pt("Unsupporting sharing policy")}return me}function on(Q,te){if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name),te.$$.ptrType.isConst&&Pt("Cannot convert argument of type "+te.$$.ptrType.name+" to parameter type "+this.name);var me=te.$$.ptrType.registeredClass,Ae=rt(te.$$.ptr,me,this.registeredClass);return Ae}function cn(Q){return this.rawGetPointee&&(Q=this.rawGetPointee(Q)),Q}function Gt(Q){this.rawDestructor&&this.rawDestructor(Q)}function xn(Q){Q!==null&&Q.delete()}function er(){nr.prototype.getPointee=cn,nr.prototype.destructor=Gt,nr.prototype.argPackAdvance=8,nr.prototype.readValueFromPointer=$e,nr.prototype.deleteObject=xn,nr.prototype.fromWireType=qa}function nr(Q,te,me,Ae,He,Ze,Qe,qe,it,vt,kt){this.name=Q,this.registeredClass=te,this.isReference=me,this.isConst=Ae,this.isSmartPointer=He,this.pointeeType=Ze,this.sharingPolicy=Qe,this.rawGetPointee=qe,this.rawConstructor=it,this.rawShare=vt,this.rawDestructor=kt,!He&&te.baseClass===void 0?Ae?(this.toWireType=Ct,this.destructorFunction=null):(this.toWireType=on,this.destructorFunction=null):this.toWireType=Qt}function or(Q,te,me){o.hasOwnProperty(Q)||fn("Replacing nonexistant public symbol"),o[Q].overloadTable!==void 0&&me!==void 0?o[Q].overloadTable[me]=te:(o[Q]=te,o[Q].argCount=me)}function qn(Q,te,me){var Ae=o["dynCall_"+Q];return me&&me.length?Ae.apply(null,[te].concat(me)):Ae.call(null,te)}var At=[];function Bn(Q){var te=At[Q];return te||(Q>=At.length&&(At.length=Q+1),At[Q]=te=ue.get(Q)),te}function dr(Q,te,me){if(Q.includes("j"))return qn(Q,te,me);var Ae=Bn(te).apply(null,me);return Ae}function si(Q,te){var me=[];return function(){return me.length=0,Object.assign(me,arguments),dr(Q,te,me)}}function jn(Q,te){Q=Sn(Q);function me(){return Q.includes("j")?si(Q,te):Bn(te)}var Ae=me();return typeof Ae!="function"&&Pt("unknown function pointer with signature "+Q+": "+te),Ae}var wr=void 0;function ei(Q){var te=Ia(Q),me=Sn(te);return Eo(te),me}function xr(Q,te){var me=[],Ae={};function He(Ze){if(!Ae[Ze]&&!nt[Ze]){if(dt[Ze]){dt[Ze].forEach(He);return}me.push(Ze),Ae[Ze]=!0}}throw te.forEach(He),new wr(Q+": "+me.map(ei).join([", "]))}function uc(Q,te,me,Ae,He,Ze,Qe,qe,it,vt,kt,Wt,Kt){kt=Sn(kt),Ze=jn(He,Ze),qe&&(qe=jn(Qe,qe)),vt&&(vt=jn(it,vt)),Kt=jn(Wt,Kt);var J=Ft(kt);st(J,function(){xr("Cannot construct "+kt+" due to unbound types",[Ae])}),bn([Q,te,me],Ae?[Ae]:[],function(X){X=X[0];var fe,Me;Ae?(fe=X.registeredClass,Me=fe.instancePrototype):Me=je.prototype;var We=jt(J,function(){if(Object.getPrototypeOf(this)!==ct)throw new Qn("Use 'new' to construct "+kt);if(et.constructor_body===void 0)throw new Qn(kt+" has no accessible constructor");var R=et.constructor_body[arguments.length];if(R===void 0)throw new Qn("Tried to invoke ctor of "+kt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(et.constructor_body).toString()+") parameters instead!");return R.apply(this,arguments)}),ct=Object.create(Me,{constructor:{value:We}});We.prototype=ct;var et=new ut(kt,We,ct,Kt,fe,Ze,qe,vt),Ye=new nr(kt,et,!0,!1,!1),$=new nr(kt+"*",et,!1,!1,!1),H=new nr(kt+" const*",et,!1,!0,!1);return fr[Q]={pointerType:$,constPointerType:H},or(J,We),[Ye,$,H]})}function ba(Q,te){for(var me=[],Ae=0;Ae>2]);return me}function Yi(Q,te){if(!(Q instanceof Function))throw new TypeError("new_ called with constructor type "+typeof Q+" which is not a function");var me=jt(Q.name||"unknownFunctionName",function(){});me.prototype=Q.prototype;var Ae=new me,He=Q.apply(Ae,te);return He instanceof Object?He:Ae}function Xa(Q,te,me,Ae,He){var Ze=te.length;Ze<2&&Pt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Qe=te[1]!==null&&me!==null,qe=!1,it=1;it{rt.hasOwnProperty(qe)?He[ot]=rt[qe]:(Ze.push(qe),nt.hasOwnProperty(qe)||(nt[qe]=[]),nt[qe].push(()=>{He[ot]=rt[qe],++Qe,Qe===Ze.length&&Ae(He)}))}),Ze.length===0&&Ae(He)}function Xi(Q){var te=gt[Q];delete gt[Q];var me=te.rawConstructor,Ae=te.rawDestructor,He=te.fields,Ze=He.map(Qe=>Qe.getterReturnType).concat(He.map(Qe=>Qe.setterArgumentType));bn([Q],Ze,Qe=>{var qe={};return He.forEach((ot,vt)=>{var kt=ot.fieldName,Wt=Qe[vt],Kt=ot.getter,J=ot.getterContext,X=Qe[vt+He.length],fe=ot.setter,Me=ot.setterContext;qe[kt]={read:ze=>Wt.fromWireType(Kt(J,ze)),write:(ze,ct)=>{var et=[];fe(Me,ze,X.toWireType(et,ct)),Ie(et)}}}),[{name:te.name,fromWireType:function(ot){var vt={};for(var kt in qe)vt[kt]=qe[kt].read(ot);return Ae(ot),vt},toWireType:function(ot,vt){for(var kt in qe)if(!(kt in vt))throw new TypeError('Missing field: "'+kt+'"');var Wt=me();for(kt in qe)qe[kt].write(Wt,vt[kt]);return ot!==null&&ot.push(Ae,Wt),Wt},argPackAdvance:8,readValueFromPointer:je,destructorFunction:Ae}]})}function Mr(Q,te,me,Ae,He){}function Ue(Q){switch(Q){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+Q)}}function ft(){for(var Q=new Array(256),te=0;te<256;++te)Q[te]=String.fromCharCode(te);Ut=Q}var Ut=void 0;function Sn(Q){for(var te="",me=Q;V[me];)te+=Ut[V[me++]];return te}var Qn=void 0;function Pt(Q){throw new Qn(Q)}function _n(Q,te,me={}){if(!("argPackAdvance"in te))throw new TypeError("registerType registeredInstance requires argPackAdvance");var Ae=te.name;if(Q||Pt('type "'+Ae+'" must have a positive integer typeid pointer'),rt.hasOwnProperty(Q)){if(me.ignoreDuplicateRegistrations)return;Pt("Cannot register type '"+Ae+"' twice")}if(rt[Q]=te,delete dt[Q],nt.hasOwnProperty(Q)){var He=nt[Q];delete nt[Q],He.forEach(Ze=>Ze())}}function sn(Q,te,me,Ae,He){var Ze=Ue(me);te=Sn(te),_n(Q,{name:te,fromWireType:function(Qe){return!!Qe},toWireType:function(Qe,qe){return qe?Ae:He},argPackAdvance:8,readValueFromPointer:function(Qe){var qe;if(me===1)qe=L;else if(me===2)qe=G;else if(me===4)qe=k;else throw new TypeError("Unknown boolean type size: "+te);return this.fromWireType(qe[Qe>>Ze])},destructorFunction:null})}function rn(Q){if(!(this instanceof Ge)||!(Q instanceof Ge))return!1;for(var te=this.$$.ptrType.registeredClass,me=this.$$.ptr,Ae=Q.$$.ptrType.registeredClass,He=Q.$$.ptr;te.baseClass;)me=te.upcast(me),te=te.baseClass;for(;Ae.baseClass;)He=Ae.upcast(He),Ae=Ae.baseClass;return te===Ae&&me===He}function pi(Q){return{count:Q.count,deleteScheduled:Q.deleteScheduled,preservePointerOnDelete:Q.preservePointerOnDelete,ptr:Q.ptr,ptrType:Q.ptrType,smartPtr:Q.smartPtr,smartPtrType:Q.smartPtrType}}function Vi(Q){function te(me){return me.$$.ptrType.registeredClass.name}Pt(te(Q)+" instance already deleted")}var Ha=!1;function Ea(Q){}function To(Q){Q.smartPtr?Q.smartPtrType.rawDestructor(Q.smartPtr):Q.ptrType.registeredClass.rawDestructor(Q.ptr)}function ra(Q){Q.count.value-=1;var te=Q.count.value===0;te&&To(Q)}function Uo(Q,te,me){if(te===me)return Q;if(me.baseClass===void 0)return null;var Ae=Uo(Q,te,me.baseClass);return Ae===null?null:me.downcast(Ae)}var fr={};function oo(){return Object.keys(mi).length}function yn(){var Q=[];for(var te in mi)mi.hasOwnProperty(te)&&Q.push(mi[te]);return Q}var Qr=[];function Da(){for(;Qr.length;){var Q=Qr.pop();Q.$$.deleteScheduled=!1,Q.delete()}}var Fi=void 0;function ao(Q){Fi=Q,Qr.length&&Fi&&Fi(Da)}function Ui(){o.getInheritedInstanceCount=oo,o.getLiveInheritedInstances=yn,o.flushPendingDeletes=Da,o.setDelayFunction=ao}var mi={};function Ka(Q,te){for(te===void 0&&Pt("ptr should not be undefined");Q.baseClass;)te=Q.upcast(te),Q=Q.baseClass;return te}function Bo(Q,te){return te=Ka(Q,te),mi[te]}function Bi(Q,te){(!te.ptrType||!te.ptr)&&fn("makeClassHandle requires ptr and ptrType");var me=!!te.smartPtrType,Ae=!!te.smartPtr;return me!==Ae&&fn("Both smartPtrType and smartPtr must be specified"),te.count={value:1},Gi(Object.create(Q,{$$:{value:te}}))}function qa(Q){var te=this.getPointee(Q);if(!te)return this.destructor(Q),null;var me=Bo(this.registeredClass,te);if(me!==void 0){if(me.$$.count.value===0)return me.$$.ptr=te,me.$$.smartPtr=Q,me.clone();var Ae=me.clone();return this.destructor(Q),Ae}function He(){return this.isSmartPointer?Bi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:te,smartPtrType:this,smartPtr:Q}):Bi(this.registeredClass.instancePrototype,{ptrType:this,ptr:Q})}var Ze=this.registeredClass.getActualType(te),Qe=fr[Ze];if(!Qe)return He.call(this);var qe;this.isConst?qe=Qe.constPointerType:qe=Qe.pointerType;var ot=Uo(te,this.registeredClass,qe.registeredClass);return ot===null?He.call(this):this.isSmartPointer?Bi(qe.registeredClass.instancePrototype,{ptrType:qe,ptr:ot,smartPtrType:this,smartPtr:Q}):Bi(qe.registeredClass.instancePrototype,{ptrType:qe,ptr:ot})}function Gi(Q){return typeof FinalizationRegistry>"u"?(Gi=te=>te,Q):(Ha=new FinalizationRegistry(te=>{ra(te.$$)}),Gi=te=>{var me=te.$$,Ae=!!me.smartPtr;if(Ae){var He={$$:me};Ha.register(te,He,te)}return te},Ea=te=>Ha.unregister(te),Gi(Q))}function ia(){if(this.$$.ptr||Vi(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var Q=Gi(Object.create(Object.getPrototypeOf(this),{$$:{value:pi(this.$$)}}));return Q.$$.count.value+=1,Q.$$.deleteScheduled=!1,Q}function de(){this.$$.ptr||Vi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Pt("Object already scheduled for deletion"),Ea(this),ra(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function We(){return!this.$$.ptr}function Se(){return this.$$.ptr||Vi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Pt("Object already scheduled for deletion"),Qr.push(this),Qr.length===1&&Fi&&Fi(Da),this.$$.deleteScheduled=!0,this}function we(){Ge.prototype.isAliasOf=rn,Ge.prototype.clone=ia,Ge.prototype.delete=de,Ge.prototype.isDeleted=We,Ge.prototype.deleteLater=Se}function Ge(){}function tt(Q,te,me){if(Q[te].overloadTable===void 0){var Ae=Q[te];Q[te]=function(){return Q[te].overloadTable.hasOwnProperty(arguments.length)||Pt("Function '"+me+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+Q[te].overloadTable+")!"),Q[te].overloadTable[arguments.length].apply(this,arguments)},Q[te].overloadTable=[],Q[te].overloadTable[Ae.argCount]=Ae}}function st(Q,te,me){o.hasOwnProperty(Q)?((me===void 0||o[Q].overloadTable!==void 0&&o[Q].overloadTable[me]!==void 0)&&Pt("Cannot register public name '"+Q+"' twice"),tt(o,Q,Q),o.hasOwnProperty(me)&&Pt("Cannot register multiple overloads of a function with the same number of arguments ("+me+")!"),o[Q].overloadTable[me]=te):(o[Q]=te,me!==void 0&&(o[Q].numArguments=me))}function ut(Q,te,me,Ae,He,Ze,Qe,qe){this.name=Q,this.constructor=te,this.instancePrototype=me,this.rawDestructor=Ae,this.baseClass=He,this.getActualType=Ze,this.upcast=Qe,this.downcast=qe,this.pureVirtualFunctions=[]}function it(Q,te,me){for(;te!==me;)te.upcast||Pt("Expected null or instance of "+me.name+", got an instance of "+te.name),Q=te.upcast(Q),te=te.baseClass;return Q}function Ct(Q,te){if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name);var me=te.$$.ptrType.registeredClass,Ae=it(te.$$.ptr,me,this.registeredClass);return Ae}function Qt(Q,te){var me;if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),this.isSmartPointer?(me=this.rawConstructor(),Q!==null&&Q.push(this.rawDestructor,me),me):0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&te.$$.ptrType.isConst&&Pt("Cannot convert argument of type "+(te.$$.smartPtrType?te.$$.smartPtrType.name:te.$$.ptrType.name)+" to parameter type "+this.name);var Ae=te.$$.ptrType.registeredClass;if(me=it(te.$$.ptr,Ae,this.registeredClass),this.isSmartPointer)switch(te.$$.smartPtr===void 0&&Pt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:te.$$.smartPtrType===this?me=te.$$.smartPtr:Pt("Cannot convert argument of type "+(te.$$.smartPtrType?te.$$.smartPtrType.name:te.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:me=te.$$.smartPtr;break;case 2:if(te.$$.smartPtrType===this)me=te.$$.smartPtr;else{var He=te.clone();me=this.rawShare(me,so.toHandle(function(){He.delete()})),Q!==null&&Q.push(this.rawDestructor,me)}break;default:Pt("Unsupporting sharing policy")}return me}function on(Q,te){if(te===null)return this.isReference&&Pt("null is not a valid "+this.name),0;te.$$||Pt('Cannot pass "'+Wi(te)+'" as a '+this.name),te.$$.ptr||Pt("Cannot pass deleted object as a pointer of type "+this.name),te.$$.ptrType.isConst&&Pt("Cannot convert argument of type "+te.$$.ptrType.name+" to parameter type "+this.name);var me=te.$$.ptrType.registeredClass,Ae=it(te.$$.ptr,me,this.registeredClass);return Ae}function cn(Q){return this.rawGetPointee&&(Q=this.rawGetPointee(Q)),Q}function Gt(Q){this.rawDestructor&&this.rawDestructor(Q)}function xn(Q){Q!==null&&Q.delete()}function er(){nr.prototype.getPointee=cn,nr.prototype.destructor=Gt,nr.prototype.argPackAdvance=8,nr.prototype.readValueFromPointer=je,nr.prototype.deleteObject=xn,nr.prototype.fromWireType=qa}function nr(Q,te,me,Ae,He,Ze,Qe,qe,ot,vt,kt){this.name=Q,this.registeredClass=te,this.isReference=me,this.isConst=Ae,this.isSmartPointer=He,this.pointeeType=Ze,this.sharingPolicy=Qe,this.rawGetPointee=qe,this.rawConstructor=ot,this.rawShare=vt,this.rawDestructor=kt,!He&&te.baseClass===void 0?Ae?(this.toWireType=Ct,this.destructorFunction=null):(this.toWireType=on,this.destructorFunction=null):this.toWireType=Qt}function or(Q,te,me){o.hasOwnProperty(Q)||fn("Replacing nonexistant public symbol"),o[Q].overloadTable!==void 0&&me!==void 0?o[Q].overloadTable[me]=te:(o[Q]=te,o[Q].argCount=me)}function qn(Q,te,me){var Ae=o["dynCall_"+Q];return me&&me.length?Ae.apply(null,[te].concat(me)):Ae.call(null,te)}var At=[];function Bn(Q){var te=At[Q];return te||(Q>=At.length&&(At.length=Q+1),At[Q]=te=ue.get(Q)),te}function dr(Q,te,me){if(Q.includes("j"))return qn(Q,te,me);var Ae=Bn(te).apply(null,me);return Ae}function si(Q,te){var me=[];return function(){return me.length=0,Object.assign(me,arguments),dr(Q,te,me)}}function jn(Q,te){Q=Sn(Q);function me(){return Q.includes("j")?si(Q,te):Bn(te)}var Ae=me();return typeof Ae!="function"&&Pt("unknown function pointer with signature "+Q+": "+te),Ae}var wr=void 0;function ei(Q){var te=Ia(Q),me=Sn(te);return Eo(te),me}function xr(Q,te){var me=[],Ae={};function He(Ze){if(!Ae[Ze]&&!rt[Ze]){if(dt[Ze]){dt[Ze].forEach(He);return}me.push(Ze),Ae[Ze]=!0}}throw te.forEach(He),new wr(Q+": "+me.map(ei).join([", "]))}function uc(Q,te,me,Ae,He,Ze,Qe,qe,ot,vt,kt,Wt,Kt){kt=Sn(kt),Ze=jn(He,Ze),qe&&(qe=jn(Qe,qe)),vt&&(vt=jn(ot,vt)),Kt=jn(Wt,Kt);var J=Ft(kt);st(J,function(){xr("Cannot construct "+kt+" due to unbound types",[Ae])}),bn([Q,te,me],Ae?[Ae]:[],function(X){X=X[0];var fe,Me;Ae?(fe=X.registeredClass,Me=fe.instancePrototype):Me=Ge.prototype;var ze=jt(J,function(){if(Object.getPrototypeOf(this)!==ct)throw new Qn("Use 'new' to construct "+kt);if(et.constructor_body===void 0)throw new Qn(kt+" has no accessible constructor");var R=et.constructor_body[arguments.length];if(R===void 0)throw new Qn("Tried to invoke ctor of "+kt+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(et.constructor_body).toString()+") parameters instead!");return R.apply(this,arguments)}),ct=Object.create(Me,{constructor:{value:ze}});ze.prototype=ct;var et=new ut(kt,ze,ct,Kt,fe,Ze,qe,vt),Ye=new nr(kt,et,!0,!1,!1),$=new nr(kt+"*",et,!1,!1,!1),H=new nr(kt+" const*",et,!1,!0,!1);return fr[Q]={pointerType:$,constPointerType:H},or(J,ze),[Ye,$,H]})}function ba(Q,te){for(var me=[],Ae=0;Ae>2]);return me}function Yi(Q,te){if(!(Q instanceof Function))throw new TypeError("new_ called with constructor type "+typeof Q+" which is not a function");var me=jt(Q.name||"unknownFunctionName",function(){});me.prototype=Q.prototype;var Ae=new me,He=Q.apply(Ae,te);return He instanceof Object?He:Ae}function Xa(Q,te,me,Ae,He){var Ze=te.length;Ze<2&&Pt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Qe=te[1]!==null&&me!==null,qe=!1,ot=1;ot0?", ":"")+Wt),Kt+=(vt?"var rv = ":"")+"invoker(fn"+(Wt.length>0?", ":"")+Wt+`); +`);for(var ot=0;ot0?", ":"")+Wt),Kt+=(vt?"var rv = ":"")+"invoker(fn"+(Wt.length>0?", ":"")+Wt+`); `,qe)Kt+=`runDestructors(destructors); -`;else for(var it=Qe?1:2;it0);var Qe=ba(te,me);He=jn(Ae,He),bn([],[Q],function(qe){qe=qe[0];var it="constructor "+qe.name;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[te-1]!==void 0)throw new Qn("Cannot register multiple constructors with identical number of parameters ("+(te-1)+") for class '"+qe.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return qe.registeredClass.constructor_body[te-1]=()=>{xr("Cannot construct "+qe.name+" due to unbound types",Qe)},bn([],Qe,function(vt){return vt.splice(1,0,null),qe.registeredClass.constructor_body[te-1]=Xa(it,vt,null,He,Ze),[]}),[]})}function ll(Q,te,me,Ae,He,Ze,Qe,qe){var it=ba(me,Ae);te=Sn(te),Ze=jn(He,Ze),bn([],[Q],function(vt){vt=vt[0];var kt=vt.name+"."+te;te.startsWith("@@")&&(te=Symbol[te.substring(2)]),qe&&vt.registeredClass.pureVirtualFunctions.push(te);function Wt(){xr("Cannot call "+kt+" due to unbound types",it)}var Kt=vt.registeredClass.instancePrototype,J=Kt[te];return J===void 0||J.overloadTable===void 0&&J.className!==vt.name&&J.argCount===me-2?(Wt.argCount=me-2,Wt.className=vt.name,Kt[te]=Wt):(ot(Kt,te,kt),Kt[te].overloadTable[me-2]=Wt),bn([],it,function(X){var fe=Xa(kt,X,vt,Ze,Qe);return Kt[te].overloadTable===void 0?(fe.argCount=me-2,Kt[te]=fe):Kt[te].overloadTable[me-2]=fe,[]}),[]})}var bs=[],gr=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Ya(Q){Q>4&&--gr[Q].refcount===0&&(gr[Q]=void 0,bs.push(Q))}function vi(){for(var Q=0,te=5;te(Q||Pt("Cannot use deleted val. handle = "+Q),gr[Q].value),toHandle:Q=>{switch(Q){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var te=bs.length?bs.pop():gr.length;return gr[te]={refcount:1,value:Q},te}}}};function Uu(Q,te){te=Sn(te),_n(Q,{name:te,fromWireType:function(me){var Ae=so.toValue(me);return Ya(me),Ae},toWireType:function(me,Ae){return so.toHandle(Ae)},argPackAdvance:8,readValueFromPointer:$e,destructorFunction:null})}function Wi(Q){if(Q===null)return"null";var te=typeof Q;return te==="object"||te==="array"||te==="function"?Q.toString():""+Q}function Go(Q,te){switch(te){case 2:return function(me){return this.fromWireType(j[me>>2])};case 3:return function(me){return this.fromWireType(Y[me>>3])};default:throw new TypeError("Unknown float type: "+Q)}}function fc(Q,te,me){var Ae=Be(me);te=Sn(te),_n(Q,{name:te,fromWireType:function(He){return He},toWireType:function(He,Ze){return Ze},argPackAdvance:8,readValueFromPointer:Go(te,Ae),destructorFunction:null})}function Ja(Q,te,me,Ae,He,Ze){var Qe=ba(te,me);Q=Sn(Q),He=jn(Ae,He),st(Q,function(){xr("Cannot call "+Q+" due to unbound types",Qe)},te-1),bn([],Qe,function(qe){var it=[qe[0],null].concat(qe.slice(1));return or(Q,Xa(Q,it,null,He,Ze),te-1),[]})}function Ji(Q,te,me){switch(te){case 0:return me?function(He){return L[He]}:function(He){return V[He]};case 1:return me?function(He){return G[He>>1]}:function(He){return A[He>>1]};case 2:return me?function(He){return k[He>>2]}:function(He){return F[He>>2]};default:throw new TypeError("Unknown integer type: "+Q)}}function fl(Q,te,me,Ae,He){te=Sn(te);var Ze=Be(me),Qe=Wt=>Wt;if(Ae===0){var qe=32-8*me;Qe=Wt=>Wt<>>qe}var it=te.includes("unsigned"),vt=(Wt,Kt)=>{},kt;it?kt=function(Wt,Kt){return vt(Kt,this.name),Kt>>>0}:kt=function(Wt,Kt){return vt(Kt,this.name),Kt},_n(Q,{name:te,fromWireType:Qe,toWireType:kt,argPackAdvance:8,readValueFromPointer:Ji(te,Ze,Ae!==0),destructorFunction:null})}function Bu(Q,te,me){var Ae=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],He=Ae[te];function Ze(Qe){Qe=Qe>>2;var qe=F,it=qe[Qe],vt=qe[Qe+1];return new He(M,vt,it)}me=Sn(me),_n(Q,{name:me,fromWireType:Ze,argPackAdvance:8,readValueFromPointer:Ze},{ignoreDuplicateRegistrations:!0})}function Gu(Q,te){te=Sn(te);var me=te==="std::string";_n(Q,{name:te,fromWireType:function(Ae){var He=F[Ae>>2],Ze=Ae+4,Qe;if(me)for(var qe=Ze,it=0;it<=He;++it){var vt=Ze+it;if(it==He||V[vt]==0){var kt=vt-qe,Wt=D(qe,kt);Qe===void 0?Qe=Wt:(Qe+="\0",Qe+=Wt),qe=vt+1}}else{for(var Kt=new Array(He),it=0;it>2]=Ze,me&&Qe)I(He,it,Ze+1);else if(Qe)for(var vt=0;vt255&&(Eo(it),Pt("String has UTF-16 code units that do not fit in 8 bits")),V[it+vt]=kt}else for(var vt=0;vt>1,He=Ae+te/2;!(Ae>=He)&&A[Ae];)++Ae;if(me=Ae<<1,me-Q>32&&dl)return dl.decode(V.subarray(Q,me));for(var Ze="",Qe=0;!(Qe>=te/2);++Qe){var qe=G[Q+Qe*2>>1];if(qe==0)break;Ze+=String.fromCharCode(qe)}return Ze}function hl(Q,te,me){if(me===void 0&&(me=2147483647),me<2)return 0;me-=2;for(var Ae=te,He=me>1]=Qe,te+=2}return G[te>>1]=0,te-Ae}function dc(Q){return Q.length*2}function Wu(Q,te){for(var me=0,Ae="";!(me>=te/4);){var He=k[Q+me*4>>2];if(He==0)break;if(++me,He>=65536){var Ze=He-65536;Ae+=String.fromCharCode(55296|Ze>>10,56320|Ze&1023)}else Ae+=String.fromCharCode(He)}return Ae}function zu(Q,te,me){if(me===void 0&&(me=2147483647),me<4)return 0;for(var Ae=te,He=Ae+me-4,Ze=0;Ze=55296&&Qe<=57343){var qe=Q.charCodeAt(++Ze);Qe=65536+((Qe&1023)<<10)|qe&1023}if(k[te>>2]=Qe,te+=4,te+4>He)break}return k[te>>2]=0,te-Ae}function $u(Q){for(var te=0,me=0;me=55296&&Ae<=57343&&++me,te+=4}return te}function ju(Q,te,me){me=Sn(me);var Ae,He,Ze,Qe,qe;te===2?(Ae=Za,He=hl,Qe=dc,Ze=()=>A,qe=1):te===4&&(Ae=Wu,He=zu,Qe=$u,Ze=()=>F,qe=2),_n(Q,{name:me,fromWireType:function(it){for(var vt=F[it>>2],kt=Ze(),Wt,Kt=it+4,J=0;J<=vt;++J){var X=it+4+J*te;if(J==vt||kt[X>>qe]==0){var fe=X-Kt,Me=Ae(Kt,fe);Wt===void 0?Wt=Me:(Wt+="\0",Wt+=Me),Kt=X+te}}return Eo(it),Wt},toWireType:function(it,vt){typeof vt!="string"&&Pt("Cannot pass non-string to C++ string type "+me);var kt=Qe(vt),Wt=oa(4+kt+te);return F[Wt>>2]=kt>>qe,He(vt,Wt+4,kt+te),it!==null&&it.push(Eo,Wt),Wt},argPackAdvance:8,readValueFromPointer:$e,destructorFunction:function(it){Eo(it)}})}function Hu(Q,te,me,Ae,He,Ze){gt[Q]={name:Sn(te),rawConstructor:jn(me,Ae),rawDestructor:jn(He,Ze),fields:[]}}function Ku(Q,te,me,Ae,He,Ze,Qe,qe,it,vt){gt[Q].fields.push({fieldName:Sn(te),getterReturnType:me,getter:jn(Ae,He),getterContext:Ze,setterArgumentType:Qe,setter:jn(qe,it),setterContext:vt})}function qu(Q,te){te=Sn(te),_n(Q,{isVoid:!0,name:te,argPackAdvance:0,fromWireType:function(){},toWireType:function(me,Ae){}})}var gl={};function Xu(Q){var te=gl[Q];return te===void 0?Sn(Q):te}function pl(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function ml(Q){return Q===0?so.toHandle(pl()):(Q=Xu(Q),so.toHandle(pl()[Q]))}function Yu(Q){Q>4&&(gr[Q].refcount+=1)}function hc(Q,te){var me=nt[Q];return me===void 0&&Pt(te+" has unknown type "+ei(Q)),me}function vl(Q){for(var te="",me=0;meF,He="return function emval_allocator_"+Q+`(constructor, argTypes, args) { +`,X.push(Kt);var ze=Yi(Function,X).apply(null,fe);return ze}function cl(Q,te,me,Ae,He,Ze){_(te>0);var Qe=ba(te,me);He=jn(Ae,He),bn([],[Q],function(qe){qe=qe[0];var ot="constructor "+qe.name;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[te-1]!==void 0)throw new Qn("Cannot register multiple constructors with identical number of parameters ("+(te-1)+") for class '"+qe.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return qe.registeredClass.constructor_body[te-1]=()=>{xr("Cannot construct "+qe.name+" due to unbound types",Qe)},bn([],Qe,function(vt){return vt.splice(1,0,null),qe.registeredClass.constructor_body[te-1]=Xa(ot,vt,null,He,Ze),[]}),[]})}function ll(Q,te,me,Ae,He,Ze,Qe,qe){var ot=ba(me,Ae);te=Sn(te),Ze=jn(He,Ze),bn([],[Q],function(vt){vt=vt[0];var kt=vt.name+"."+te;te.startsWith("@@")&&(te=Symbol[te.substring(2)]),qe&&vt.registeredClass.pureVirtualFunctions.push(te);function Wt(){xr("Cannot call "+kt+" due to unbound types",ot)}var Kt=vt.registeredClass.instancePrototype,J=Kt[te];return J===void 0||J.overloadTable===void 0&&J.className!==vt.name&&J.argCount===me-2?(Wt.argCount=me-2,Wt.className=vt.name,Kt[te]=Wt):(tt(Kt,te,kt),Kt[te].overloadTable[me-2]=Wt),bn([],ot,function(X){var fe=Xa(kt,X,vt,Ze,Qe);return Kt[te].overloadTable===void 0?(fe.argCount=me-2,Kt[te]=fe):Kt[te].overloadTable[me-2]=fe,[]}),[]})}var bs=[],gr=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Ya(Q){Q>4&&--gr[Q].refcount===0&&(gr[Q]=void 0,bs.push(Q))}function vi(){for(var Q=0,te=5;te(Q||Pt("Cannot use deleted val. handle = "+Q),gr[Q].value),toHandle:Q=>{switch(Q){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var te=bs.length?bs.pop():gr.length;return gr[te]={refcount:1,value:Q},te}}}};function Uu(Q,te){te=Sn(te),_n(Q,{name:te,fromWireType:function(me){var Ae=so.toValue(me);return Ya(me),Ae},toWireType:function(me,Ae){return so.toHandle(Ae)},argPackAdvance:8,readValueFromPointer:je,destructorFunction:null})}function Wi(Q){if(Q===null)return"null";var te=typeof Q;return te==="object"||te==="array"||te==="function"?Q.toString():""+Q}function Go(Q,te){switch(te){case 2:return function(me){return this.fromWireType(j[me>>2])};case 3:return function(me){return this.fromWireType(Y[me>>3])};default:throw new TypeError("Unknown float type: "+Q)}}function fc(Q,te,me){var Ae=Ue(me);te=Sn(te),_n(Q,{name:te,fromWireType:function(He){return He},toWireType:function(He,Ze){return Ze},argPackAdvance:8,readValueFromPointer:Go(te,Ae),destructorFunction:null})}function Ja(Q,te,me,Ae,He,Ze){var Qe=ba(te,me);Q=Sn(Q),He=jn(Ae,He),st(Q,function(){xr("Cannot call "+Q+" due to unbound types",Qe)},te-1),bn([],Qe,function(qe){var ot=[qe[0],null].concat(qe.slice(1));return or(Q,Xa(Q,ot,null,He,Ze),te-1),[]})}function Ji(Q,te,me){switch(te){case 0:return me?function(He){return L[He]}:function(He){return V[He]};case 1:return me?function(He){return G[He>>1]}:function(He){return A[He>>1]};case 2:return me?function(He){return k[He>>2]}:function(He){return F[He>>2]};default:throw new TypeError("Unknown integer type: "+Q)}}function fl(Q,te,me,Ae,He){te=Sn(te);var Ze=Ue(me),Qe=Wt=>Wt;if(Ae===0){var qe=32-8*me;Qe=Wt=>Wt<>>qe}var ot=te.includes("unsigned"),vt=(Wt,Kt)=>{},kt;ot?kt=function(Wt,Kt){return vt(Kt,this.name),Kt>>>0}:kt=function(Wt,Kt){return vt(Kt,this.name),Kt},_n(Q,{name:te,fromWireType:Qe,toWireType:kt,argPackAdvance:8,readValueFromPointer:Ji(te,Ze,Ae!==0),destructorFunction:null})}function Bu(Q,te,me){var Ae=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],He=Ae[te];function Ze(Qe){Qe=Qe>>2;var qe=F,ot=qe[Qe],vt=qe[Qe+1];return new He(M,vt,ot)}me=Sn(me),_n(Q,{name:me,fromWireType:Ze,argPackAdvance:8,readValueFromPointer:Ze},{ignoreDuplicateRegistrations:!0})}function Gu(Q,te){te=Sn(te);var me=te==="std::string";_n(Q,{name:te,fromWireType:function(Ae){var He=F[Ae>>2],Ze=Ae+4,Qe;if(me)for(var qe=Ze,ot=0;ot<=He;++ot){var vt=Ze+ot;if(ot==He||V[vt]==0){var kt=vt-qe,Wt=D(qe,kt);Qe===void 0?Qe=Wt:(Qe+="\0",Qe+=Wt),qe=vt+1}}else{for(var Kt=new Array(He),ot=0;ot>2]=Ze,me&&Qe)I(He,ot,Ze+1);else if(Qe)for(var vt=0;vt255&&(Eo(ot),Pt("String has UTF-16 code units that do not fit in 8 bits")),V[ot+vt]=kt}else for(var vt=0;vt>1,He=Ae+te/2;!(Ae>=He)&&A[Ae];)++Ae;if(me=Ae<<1,me-Q>32&&dl)return dl.decode(V.subarray(Q,me));for(var Ze="",Qe=0;!(Qe>=te/2);++Qe){var qe=G[Q+Qe*2>>1];if(qe==0)break;Ze+=String.fromCharCode(qe)}return Ze}function hl(Q,te,me){if(me===void 0&&(me=2147483647),me<2)return 0;me-=2;for(var Ae=te,He=me>1]=Qe,te+=2}return G[te>>1]=0,te-Ae}function dc(Q){return Q.length*2}function Wu(Q,te){for(var me=0,Ae="";!(me>=te/4);){var He=k[Q+me*4>>2];if(He==0)break;if(++me,He>=65536){var Ze=He-65536;Ae+=String.fromCharCode(55296|Ze>>10,56320|Ze&1023)}else Ae+=String.fromCharCode(He)}return Ae}function zu(Q,te,me){if(me===void 0&&(me=2147483647),me<4)return 0;for(var Ae=te,He=Ae+me-4,Ze=0;Ze=55296&&Qe<=57343){var qe=Q.charCodeAt(++Ze);Qe=65536+((Qe&1023)<<10)|qe&1023}if(k[te>>2]=Qe,te+=4,te+4>He)break}return k[te>>2]=0,te-Ae}function $u(Q){for(var te=0,me=0;me=55296&&Ae<=57343&&++me,te+=4}return te}function ju(Q,te,me){me=Sn(me);var Ae,He,Ze,Qe,qe;te===2?(Ae=Za,He=hl,Qe=dc,Ze=()=>A,qe=1):te===4&&(Ae=Wu,He=zu,Qe=$u,Ze=()=>F,qe=2),_n(Q,{name:me,fromWireType:function(ot){for(var vt=F[ot>>2],kt=Ze(),Wt,Kt=ot+4,J=0;J<=vt;++J){var X=ot+4+J*te;if(J==vt||kt[X>>qe]==0){var fe=X-Kt,Me=Ae(Kt,fe);Wt===void 0?Wt=Me:(Wt+="\0",Wt+=Me),Kt=X+te}}return Eo(ot),Wt},toWireType:function(ot,vt){typeof vt!="string"&&Pt("Cannot pass non-string to C++ string type "+me);var kt=Qe(vt),Wt=oa(4+kt+te);return F[Wt>>2]=kt>>qe,He(vt,Wt+4,kt+te),ot!==null&&ot.push(Eo,Wt),Wt},argPackAdvance:8,readValueFromPointer:je,destructorFunction:function(ot){Eo(ot)}})}function Hu(Q,te,me,Ae,He,Ze){gt[Q]={name:Sn(te),rawConstructor:jn(me,Ae),rawDestructor:jn(He,Ze),fields:[]}}function Ku(Q,te,me,Ae,He,Ze,Qe,qe,ot,vt){gt[Q].fields.push({fieldName:Sn(te),getterReturnType:me,getter:jn(Ae,He),getterContext:Ze,setterArgumentType:Qe,setter:jn(qe,ot),setterContext:vt})}function qu(Q,te){te=Sn(te),_n(Q,{isVoid:!0,name:te,argPackAdvance:0,fromWireType:function(){},toWireType:function(me,Ae){}})}var gl={};function Xu(Q){var te=gl[Q];return te===void 0?Sn(Q):te}function pl(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function ml(Q){return Q===0?so.toHandle(pl()):(Q=Xu(Q),so.toHandle(pl()[Q]))}function Yu(Q){Q>4&&(gr[Q].refcount+=1)}function hc(Q,te){var me=rt[Q];return me===void 0&&Pt(te+" has unknown type "+ei(Q)),me}function vl(Q){for(var te="",me=0;meF,He="return function emval_allocator_"+Q+`(constructor, argTypes, args) { var HEAPU32 = getMemory(); `,me=0;me>2)], 'parameter "+me+`'); var arg`+me+" = argType"+me+`.readValueFromPointer(args); @@ -3814,16 +3814,16 @@ argTypes += 4; `;return He+="var obj = new constructor("+te+`); return valueToHandle(obj); } -`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",He)(hc,o,so.toHandle,Ae)}var yl={};function gc(Q,te,me,Ae){Q=so.toValue(Q);var He=yl[te];return He||(He=vl(te),yl[te]=He),He(Q,me,Ae)}function Ju(Q,te){Q=hc(Q,"_emval_take_value");var me=Q.readValueFromPointer(te);return so.toHandle(me)}function wl(){De("")}function Zu(Q,te,me){V.copyWithin(Q,te,te+me)}function xl(){return 2147483648}function Qu(Q){try{return C.grow(Q-M.byteLength+65535>>>16),re(C.buffer),1}catch{}}function ef(Q){var te=V.length;Q=Q>>>0;var me=xl();if(Q>me)return!1;let Ae=(it,vt)=>it+(vt-it%vt)%vt;for(var He=1;He<=4;He*=2){var Ze=te*(1+.2/He);Ze=Math.min(Ze,Q+100663296);var Qe=Math.min(me,Ae(Math.max(Q,Ze),65536)),qe=Qu(Qe);if(qe)return!0}return!1}function tf(Q){var te=o["_"+Q];return te}function nf(Q,te){L.set(Q,te)}function pc(Q,te,me,Ae,He){var Ze={string:X=>{var fe=0;if(X!=null&&X!==0){var Me=(X.length<<2)+1;fe=vc(Me),I(X,fe,Me)}return fe},array:X=>{var fe=vc(X.length);return nf(X,fe),fe}};function Qe(X){return te==="string"?D(X):te==="boolean"?!!X:X}var qe=tf(Q),it=[],vt=0;if(Ae)for(var kt=0;kt0||(Oe(),K>0))return;function te(){Is||(Is=!0,o.calledRun=!0,!S&&(Se(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),B()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),te()},1)):te()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Tl(),i.ready}})();t.exports=r})(aG);var wxe=aG.exports;const xxe=ac(wxe),Cxe=new URL("/static/dv3d/charlswasm_decode.wasm",import.meta.url),Jd={codec:void 0,decoder:void 0,decodeConfig:{}};function Sxe(t){return typeof t=="number"?Jd.codec.getExceptionMessage(t):t}function _xe(t){if(Jd.decodeConfig=t,Jd.codec)return Promise.resolve();const e=xxe({locateFile:r=>r.endsWith(".wasm")?Cxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Jd.codec=i,Jd.decoder=new i.JpegLSDecoder,r()},n)})}async function Rb(t,e){try{await _xe();const r=Jd.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getInterleaveMode(),a=r.getNearLossless(),s=r.getDecodedBuffer(),c={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},l=Txe(i,s,e.signed),f={nearLossless:a,interleaveMode:o,frameInfo:i};return{...e,pixelData:l,imageInfo:c,encodeOptions:f,...f,...c}}catch(r){throw Sxe(r)}}function Txe(t,e,r){return t.bitsPerSample>8?r?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):r?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var sG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(J,X){a=J,s=X});var c=Object.assign({},o),l="./this.program",f=typeof window=="object",u=typeof importScripts=="function",d=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",h="";function g(J){return o.locateFile?o.locateFile(J,h):h+J}var p,v,y;if(d){var m=Js,w=Js;u?h=w.dirname(h)+"/":h=__dirname+"/",p=(J,X)=>(J=we(J)?new URL(J):w.normalize(J),m.readFileSync(J,X?void 0:"utf8")),y=J=>{var X=p(J,!0);return X.buffer||(X=new Uint8Array(X)),X},v=(J,X,fe)=>{J=we(J)?new URL(J):w.normalize(J),m.readFile(J,function(Me,We){Me?fe(Me):X(We.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(J){if(!(J instanceof ht))throw J}),process.on("unhandledRejection",function(J){throw J}),o.inspect=function(){return"[Emscripten Module object]"}}else(f||u)&&(u?h=self.location.href:typeof document<"u"&&document.currentScript&&(h=document.currentScript.src),n&&(h=n),h.indexOf("blob:")!==0?h=h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):h="",p=J=>{var X=new XMLHttpRequest;return X.open("GET",J,!1),X.send(null),X.responseText},u&&(y=J=>{var X=new XMLHttpRequest;return X.open("GET",J,!1),X.responseType="arraybuffer",X.send(null),new Uint8Array(X.response)}),v=(J,X,fe)=>{var Me=new XMLHttpRequest;Me.open("GET",J,!0),Me.responseType="arraybuffer",Me.onload=()=>{if(Me.status==200||Me.status==0&&Me.response){X(Me.response);return}fe()},Me.onerror=fe,Me.send(null)});var x=o.print||console.log.bind(console),C=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&o.quit;var S;o.wasmBinary&&(S=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&ze("no native wasm support detected");var _,T=!1;function E(J,X){J||ze(X)}var D=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function b(J,X,fe){for(var Me=X+fe,We=X;J[We]&&!(We>=Me);)++We;if(We-X>16&&J.buffer&&D)return D.decode(J.subarray(X,We));for(var ct="";X>10,56320|H&1023)}}return ct}function I(J,X){return J?b(A,J,X):""}function P(J,X,fe,Me){if(!(Me>0))return 0;for(var We=fe,ct=fe+Me-1,et=0;et=55296&&Ye<=57343){var $=J.charCodeAt(++et);Ye=65536+((Ye&1023)<<10)|$&1023}if(Ye<=127){if(fe>=ct)break;X[fe++]=Ye}else if(Ye<=2047){if(fe+1>=ct)break;X[fe++]=192|Ye>>6,X[fe++]=128|Ye&63}else if(Ye<=65535){if(fe+2>=ct)break;X[fe++]=224|Ye>>12,X[fe++]=128|Ye>>6&63,X[fe++]=128|Ye&63}else{if(fe+3>=ct)break;X[fe++]=240|Ye>>18,X[fe++]=128|Ye>>12&63,X[fe++]=128|Ye>>6&63,X[fe++]=128|Ye&63}}return X[fe]=0,fe-We}function M(J,X,fe){return P(J,A,X,fe)}function L(J){for(var X=0,fe=0;fe=55296&&Me<=57343?(X+=4,++fe):X+=3}return X}var V,G,A,k,F,j,Y,re,ue;function ce(J){V=J,o.HEAP8=G=new Int8Array(J),o.HEAP16=k=new Int16Array(J),o.HEAP32=j=new Int32Array(J),o.HEAPU8=A=new Uint8Array(J),o.HEAPU16=F=new Uint16Array(J),o.HEAPU32=Y=new Uint32Array(J),o.HEAPF32=re=new Float32Array(J),o.HEAPF64=ue=new Float64Array(J)}o.INITIAL_MEMORY;var pe,Ee=[],Oe=[],Se=[];function B(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)W(o.preRun.shift());wt(Ee)}function O(){wt(Oe)}function z(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)Z(o.postRun.shift());wt(Se)}function W(J){Ee.unshift(J)}function K(J){Oe.unshift(J)}function Z(J){Se.unshift(J)}var ee=0,xe=null;function De(J){ee++,o.monitorRunDependencies&&o.monitorRunDependencies(ee)}function Ne(J){if(ee--,o.monitorRunDependencies&&o.monitorRunDependencies(ee),ee==0&&xe){var X=xe;xe=null,X()}}function ze(J){o.onAbort&&o.onAbort(J),J="Aborted("+J+")",C(J),T=!0,J+=". Build with -sASSERTIONS for more info.";var X=new WebAssembly.RuntimeError(J);throw s(X),X}var ie="data:application/octet-stream;base64,";function ae(J){return J.startsWith(ie)}function we(J){return J.startsWith("file://")}var se;se="openjpegwasm_decode.wasm",ae(se)||(se=g(se));function ge(J){try{if(J==se&&S)return new Uint8Array(S);if(y)return y(J);throw"both async and sync fetching of the wasm failed"}catch(X){ze(X)}}function Fe(){if(!S&&(f||u)){if(typeof fetch=="function"&&!we(se))return fetch(se,{credentials:"same-origin"}).then(function(J){if(!J.ok)throw"failed to load wasm binary file at '"+se+"'";return J.arrayBuffer()}).catch(function(){return ge(se)});if(v)return new Promise(function(J,X){v(se,function(fe){J(new Uint8Array(fe))},X)})}return Promise.resolve().then(function(){return ge(se)})}function oe(){var J={a:Ae};function X(et,Ye){var $=et.exports;o.asm=$,_=o.asm.E,ce(_.buffer),pe=o.asm.G,K(o.asm.F),Ne()}De();function fe(et){X(et.instance)}function Me(et){return Fe().then(function(Ye){return WebAssembly.instantiate(Ye,J)}).then(function(Ye){return Ye}).then(et,function(Ye){C("failed to asynchronously prepare wasm: "+Ye),ze(Ye)})}function We(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!ae(se)&&!we(se)&&!d&&typeof fetch=="function"?fetch(se,{credentials:"same-origin"}).then(function(et){var Ye=WebAssembly.instantiateStreaming(et,J);return Ye.then(fe,function($){return C("wasm streaming compile failed: "+$),C("falling back to ArrayBuffer instantiation"),Me(fe)})}):Me(fe)}if(o.instantiateWasm)try{var ct=o.instantiateWasm(J,X);return ct}catch(et){C("Module.instantiateWasm callback failed with error: "+et),s(et)}return We().catch(s),{}}function ht(J){this.name="ExitStatus",this.message="Program terminated with exit("+J+")",this.status=J}function wt(J){for(;J.length>0;)J.shift()(o)}function gt(J){this.excPtr=J,this.ptr=J-24,this.set_type=function(X){Y[this.ptr+4>>2]=X},this.get_type=function(){return Y[this.ptr+4>>2]},this.set_destructor=function(X){Y[this.ptr+8>>2]=X},this.get_destructor=function(){return Y[this.ptr+8>>2]},this.set_refcount=function(X){j[this.ptr>>2]=X},this.set_caught=function(X){X=X?1:0,G[this.ptr+12>>0]=X},this.get_caught=function(){return G[this.ptr+12>>0]!=0},this.set_rethrown=function(X){X=X?1:0,G[this.ptr+13>>0]=X},this.get_rethrown=function(){return G[this.ptr+13>>0]!=0},this.init=function(X,fe){this.set_adjusted_ptr(0),this.set_type(X),this.set_destructor(fe),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var X=j[this.ptr>>2];j[this.ptr>>2]=X+1},this.release_ref=function(){var X=j[this.ptr>>2];return j[this.ptr>>2]=X-1,X===1},this.set_adjusted_ptr=function(X){Y[this.ptr+16>>2]=X},this.get_adjusted_ptr=function(){return Y[this.ptr+16>>2]},this.get_exception_ptr=function(){var X=kt(this.get_type());if(X)return Y[this.excPtr>>2];var fe=this.get_adjusted_ptr();return fe!==0?fe:this.excPtr}}function Ie(J,X,fe){var Me=new gt(J);throw Me.init(X,fe),J}var $e={};function tt(J){for(;J.length;){var X=J.pop(),fe=J.pop();fe(X)}}function nt(J){return this.fromWireType(j[J>>2])}var dt={},Lt={},xt={},Ft=48,jt=57;function Pn(J){if(J===void 0)return"_unknown";J=J.replace(/[^a-zA-Z0-9_]/g,"$");var X=J.charCodeAt(0);return X>=Ft&&X<=jt?"_"+J:J}function $n(J,X){return J=Pn(J),new Function("body","return function "+J+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",He)(hc,o,so.toHandle,Ae)}var yl={};function gc(Q,te,me,Ae){Q=so.toValue(Q);var He=yl[te];return He||(He=vl(te),yl[te]=He),He(Q,me,Ae)}function Ju(Q,te){Q=hc(Q,"_emval_take_value");var me=Q.readValueFromPointer(te);return so.toHandle(me)}function wl(){De("")}function Zu(Q,te,me){V.copyWithin(Q,te,te+me)}function xl(){return 2147483648}function Qu(Q){try{return C.grow(Q-M.byteLength+65535>>>16),re(C.buffer),1}catch{}}function ef(Q){var te=V.length;Q=Q>>>0;var me=xl();if(Q>me)return!1;let Ae=(ot,vt)=>ot+(vt-ot%vt)%vt;for(var He=1;He<=4;He*=2){var Ze=te*(1+.2/He);Ze=Math.min(Ze,Q+100663296);var Qe=Math.min(me,Ae(Math.max(Q,Ze),65536)),qe=Qu(Qe);if(qe)return!0}return!1}function tf(Q){var te=o["_"+Q];return te}function nf(Q,te){L.set(Q,te)}function pc(Q,te,me,Ae,He){var Ze={string:X=>{var fe=0;if(X!=null&&X!==0){var Me=(X.length<<2)+1;fe=vc(Me),I(X,fe,Me)}return fe},array:X=>{var fe=vc(X.length);return nf(X,fe),fe}};function Qe(X){return te==="string"?D(X):te==="boolean"?!!X:X}var qe=tf(Q),ot=[],vt=0;if(Ae)for(var kt=0;kt0||(Oe(),K>0))return;function te(){Is||(Is=!0,o.calledRun=!0,!S&&(_e(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),B()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),te()},1)):te()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Tl(),i.ready}})();t.exports=r})(aG);var wxe=aG.exports;const xxe=ac(wxe),Cxe=new URL("/static/dv3d/charlswasm_decode.wasm",import.meta.url),Jd={codec:void 0,decoder:void 0,decodeConfig:{}};function Sxe(t){return typeof t=="number"?Jd.codec.getExceptionMessage(t):t}function _xe(t){if(Jd.decodeConfig=t,Jd.codec)return Promise.resolve();const e=xxe({locateFile:r=>r.endsWith(".wasm")?Cxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Jd.codec=i,Jd.decoder=new i.JpegLSDecoder,r()},n)})}async function Rb(t,e){try{await _xe();const r=Jd.decoder;r.getEncodedBuffer(t.length).set(t),r.decode();const i=r.getFrameInfo(),o=r.getInterleaveMode(),a=r.getNearLossless(),s=r.getDecodedBuffer(),c={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:e.signed,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},l=Txe(i,s,e.signed),f={nearLossless:a,interleaveMode:o,frameInfo:i};return{...e,pixelData:l,imageInfo:c,encodeOptions:f,...f,...c}}catch(r){throw Sxe(r)}}function Txe(t,e,r){return t.bitsPerSample>8?r?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):r?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var sG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(i){i=i||{};var o=typeof i<"u"?i:{},a,s;o.ready=new Promise(function(J,X){a=J,s=X});var c=Object.assign({},o),l="./this.program",f=typeof window=="object",u=typeof importScripts=="function",d=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",h="";function g(J){return o.locateFile?o.locateFile(J,h):h+J}var p,v,y;if(d){var m=Js,w=Js;u?h=w.dirname(h)+"/":h=__dirname+"/",p=(J,X)=>(J=ye(J)?new URL(J):w.normalize(J),m.readFileSync(J,X?void 0:"utf8")),y=J=>{var X=p(J,!0);return X.buffer||(X=new Uint8Array(X)),X},v=(J,X,fe)=>{J=ye(J)?new URL(J):w.normalize(J),m.readFile(J,function(Me,ze){Me?fe(Me):X(ze.buffer)})},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(J){if(!(J instanceof ht))throw J}),process.on("unhandledRejection",function(J){throw J}),o.inspect=function(){return"[Emscripten Module object]"}}else(f||u)&&(u?h=self.location.href:typeof document<"u"&&document.currentScript&&(h=document.currentScript.src),n&&(h=n),h.indexOf("blob:")!==0?h=h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):h="",p=J=>{var X=new XMLHttpRequest;return X.open("GET",J,!1),X.send(null),X.responseText},u&&(y=J=>{var X=new XMLHttpRequest;return X.open("GET",J,!1),X.responseType="arraybuffer",X.send(null),new Uint8Array(X.response)}),v=(J,X,fe)=>{var Me=new XMLHttpRequest;Me.open("GET",J,!0),Me.responseType="arraybuffer",Me.onload=()=>{if(Me.status==200||Me.status==0&&Me.response){X(Me.response);return}fe()},Me.onerror=fe,Me.send(null)});var x=o.print||console.log.bind(console),C=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&o.quit;var S;o.wasmBinary&&(S=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&$e("no native wasm support detected");var _,T=!1;function E(J,X){J||$e(X)}var D=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function b(J,X,fe){for(var Me=X+fe,ze=X;J[ze]&&!(ze>=Me);)++ze;if(ze-X>16&&J.buffer&&D)return D.decode(J.subarray(X,ze));for(var ct="";X>10,56320|H&1023)}}return ct}function I(J,X){return J?b(A,J,X):""}function P(J,X,fe,Me){if(!(Me>0))return 0;for(var ze=fe,ct=fe+Me-1,et=0;et=55296&&Ye<=57343){var $=J.charCodeAt(++et);Ye=65536+((Ye&1023)<<10)|$&1023}if(Ye<=127){if(fe>=ct)break;X[fe++]=Ye}else if(Ye<=2047){if(fe+1>=ct)break;X[fe++]=192|Ye>>6,X[fe++]=128|Ye&63}else if(Ye<=65535){if(fe+2>=ct)break;X[fe++]=224|Ye>>12,X[fe++]=128|Ye>>6&63,X[fe++]=128|Ye&63}else{if(fe+3>=ct)break;X[fe++]=240|Ye>>18,X[fe++]=128|Ye>>12&63,X[fe++]=128|Ye>>6&63,X[fe++]=128|Ye&63}}return X[fe]=0,fe-ze}function M(J,X,fe){return P(J,A,X,fe)}function L(J){for(var X=0,fe=0;fe=55296&&Me<=57343?(X+=4,++fe):X+=3}return X}var V,G,A,k,F,j,Y,re,ue;function ce(J){V=J,o.HEAP8=G=new Int8Array(J),o.HEAP16=k=new Int16Array(J),o.HEAP32=j=new Int32Array(J),o.HEAPU8=A=new Uint8Array(J),o.HEAPU16=F=new Uint16Array(J),o.HEAPU32=Y=new Uint32Array(J),o.HEAPF32=re=new Float32Array(J),o.HEAPF64=ue=new Float64Array(J)}o.INITIAL_MEMORY;var pe,Ee=[],Oe=[],_e=[];function B(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)W(o.preRun.shift());wt(Ee)}function O(){wt(Oe)}function z(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)Z(o.postRun.shift());wt(_e)}function W(J){Ee.unshift(J)}function K(J){Oe.unshift(J)}function Z(J){_e.unshift(J)}var ee=0,xe=null;function De(J){ee++,o.monitorRunDependencies&&o.monitorRunDependencies(ee)}function Ne(J){if(ee--,o.monitorRunDependencies&&o.monitorRunDependencies(ee),ee==0&&xe){var X=xe;xe=null,X()}}function $e(J){o.onAbort&&o.onAbort(J),J="Aborted("+J+")",C(J),T=!0,J+=". Build with -sASSERTIONS for more info.";var X=new WebAssembly.RuntimeError(J);throw s(X),X}var ie="data:application/octet-stream;base64,";function ae(J){return J.startsWith(ie)}function ye(J){return J.startsWith("file://")}var se;se="openjpegwasm_decode.wasm",ae(se)||(se=g(se));function ge(J){try{if(J==se&&S)return new Uint8Array(S);if(y)return y(J);throw"both async and sync fetching of the wasm failed"}catch(X){$e(X)}}function Fe(){if(!S&&(f||u)){if(typeof fetch=="function"&&!ye(se))return fetch(se,{credentials:"same-origin"}).then(function(J){if(!J.ok)throw"failed to load wasm binary file at '"+se+"'";return J.arrayBuffer()}).catch(function(){return ge(se)});if(v)return new Promise(function(J,X){v(se,function(fe){J(new Uint8Array(fe))},X)})}return Promise.resolve().then(function(){return ge(se)})}function oe(){var J={a:Ae};function X(et,Ye){var $=et.exports;o.asm=$,_=o.asm.E,ce(_.buffer),pe=o.asm.G,K(o.asm.F),Ne()}De();function fe(et){X(et.instance)}function Me(et){return Fe().then(function(Ye){return WebAssembly.instantiate(Ye,J)}).then(function(Ye){return Ye}).then(et,function(Ye){C("failed to asynchronously prepare wasm: "+Ye),$e(Ye)})}function ze(){return!S&&typeof WebAssembly.instantiateStreaming=="function"&&!ae(se)&&!ye(se)&&!d&&typeof fetch=="function"?fetch(se,{credentials:"same-origin"}).then(function(et){var Ye=WebAssembly.instantiateStreaming(et,J);return Ye.then(fe,function($){return C("wasm streaming compile failed: "+$),C("falling back to ArrayBuffer instantiation"),Me(fe)})}):Me(fe)}if(o.instantiateWasm)try{var ct=o.instantiateWasm(J,X);return ct}catch(et){C("Module.instantiateWasm callback failed with error: "+et),s(et)}return ze().catch(s),{}}function ht(J){this.name="ExitStatus",this.message="Program terminated with exit("+J+")",this.status=J}function wt(J){for(;J.length>0;)J.shift()(o)}function gt(J){this.excPtr=J,this.ptr=J-24,this.set_type=function(X){Y[this.ptr+4>>2]=X},this.get_type=function(){return Y[this.ptr+4>>2]},this.set_destructor=function(X){Y[this.ptr+8>>2]=X},this.get_destructor=function(){return Y[this.ptr+8>>2]},this.set_refcount=function(X){j[this.ptr>>2]=X},this.set_caught=function(X){X=X?1:0,G[this.ptr+12>>0]=X},this.get_caught=function(){return G[this.ptr+12>>0]!=0},this.set_rethrown=function(X){X=X?1:0,G[this.ptr+13>>0]=X},this.get_rethrown=function(){return G[this.ptr+13>>0]!=0},this.init=function(X,fe){this.set_adjusted_ptr(0),this.set_type(X),this.set_destructor(fe),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var X=j[this.ptr>>2];j[this.ptr>>2]=X+1},this.release_ref=function(){var X=j[this.ptr>>2];return j[this.ptr>>2]=X-1,X===1},this.set_adjusted_ptr=function(X){Y[this.ptr+16>>2]=X},this.get_adjusted_ptr=function(){return Y[this.ptr+16>>2]},this.get_exception_ptr=function(){var X=kt(this.get_type());if(X)return Y[this.excPtr>>2];var fe=this.get_adjusted_ptr();return fe!==0?fe:this.excPtr}}function Ie(J,X,fe){var Me=new gt(J);throw Me.init(X,fe),J}var je={};function nt(J){for(;J.length;){var X=J.pop(),fe=J.pop();fe(X)}}function rt(J){return this.fromWireType(j[J>>2])}var dt={},Lt={},xt={},Ft=48,jt=57;function Pn(J){if(J===void 0)return"_unknown";J=J.replace(/[^a-zA-Z0-9_]/g,"$");var X=J.charCodeAt(0);return X>=Ft&&X<=jt?"_"+J:J}function $n(J,X){return J=Pn(J),new Function("body","return function "+J+`() { "use strict"; return body.apply(this, arguments); }; -`)(X)}function fn(J,X){var fe=$n(X,function(Me){this.name=X,this.message=Me;var We=new Error(Me).stack;We!==void 0&&(this.stack=this.toString()+` -`+We.replace(/^Error(:[^\n]*)?\n/,""))});return fe.prototype=Object.create(J.prototype),fe.prototype.constructor=fe,fe.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},fe}var bn=void 0;function Xi(J){throw new bn(J)}function Mr(J,X,fe){J.forEach(function(Ye){xt[Ye]=X});function Me(Ye){var $=fe(Ye);$.length!==J.length&&Xi("Mismatched type converter count");for(var H=0;H{Lt.hasOwnProperty(Ye)?We[$]=Lt[Ye]:(ct.push(Ye),dt.hasOwnProperty(Ye)||(dt[Ye]=[]),dt[Ye].push(()=>{We[$]=Lt[Ye],++et,et===ct.length&&Me(We)}))}),ct.length===0&&Me(We)}function Be(J){var X=$e[J];delete $e[J];var fe=X.rawConstructor,Me=X.rawDestructor,We=X.fields,ct=We.map(et=>et.getterReturnType).concat(We.map(et=>et.setterArgumentType));Mr([J],ct,et=>{var Ye={};return We.forEach(($,H)=>{var R=$.fieldName,U=et[H],q=$.getter,le=$.getterContext,he=et[H+We.length],ve=$.setter,Te=$.setterContext;Ye[R]={read:be=>U.fromWireType(q(le,be)),write:(be,ke)=>{var Je=[];ve(Te,be,he.toWireType(Je,ke)),tt(Je)}}}),[{name:X.name,fromWireType:function($){var H={};for(var R in Ye)H[R]=Ye[R].read($);return Me($),H},toWireType:function($,H){for(var R in Ye)if(!(R in H))throw new TypeError('Missing field: "'+R+'"');var U=fe();for(R in Ye)Ye[R].write(U,H[R]);return $!==null&&$.push(Me,U),U},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:Me}]})}function ft(J,X,fe,Me,We){}function Ut(J){switch(J){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+J)}}function Sn(){for(var J=new Array(256),X=0;X<256;++X)J[X]=String.fromCharCode(X);Qn=J}var Qn=void 0;function Pt(J){for(var X="",fe=J;A[fe];)X+=Qn[A[fe++]];return X}var _n=void 0;function sn(J){throw new _n(J)}function rn(J,X,fe={}){if(!("argPackAdvance"in X))throw new TypeError("registerType registeredInstance requires argPackAdvance");var Me=X.name;if(J||sn('type "'+Me+'" must have a positive integer typeid pointer'),Lt.hasOwnProperty(J)){if(fe.ignoreDuplicateRegistrations)return;sn("Cannot register type '"+Me+"' twice")}if(Lt[J]=X,delete xt[J],dt.hasOwnProperty(J)){var We=dt[J];delete dt[J],We.forEach(ct=>ct())}}function pi(J,X,fe,Me,We){var ct=Ut(fe);X=Pt(X),rn(J,{name:X,fromWireType:function(et){return!!et},toWireType:function(et,Ye){return Ye?Me:We},argPackAdvance:8,readValueFromPointer:function(et){var Ye;if(fe===1)Ye=G;else if(fe===2)Ye=k;else if(fe===4)Ye=j;else throw new TypeError("Unknown boolean type size: "+X);return this.fromWireType(Ye[et>>ct])},destructorFunction:null})}function Vi(J){if(!(this instanceof st)||!(J instanceof st))return!1;for(var X=this.$$.ptrType.registeredClass,fe=this.$$.ptr,Me=J.$$.ptrType.registeredClass,We=J.$$.ptr;X.baseClass;)fe=X.upcast(fe),X=X.baseClass;for(;Me.baseClass;)We=Me.upcast(We),Me=Me.baseClass;return X===Me&&fe===We}function Ha(J){return{count:J.count,deleteScheduled:J.deleteScheduled,preservePointerOnDelete:J.preservePointerOnDelete,ptr:J.ptr,ptrType:J.ptrType,smartPtr:J.smartPtr,smartPtrType:J.smartPtrType}}function Ea(J){function X(fe){return fe.$$.ptrType.registeredClass.name}sn(X(J)+" instance already deleted")}var To=!1;function ra(J){}function Uo(J){J.smartPtr?J.smartPtrType.rawDestructor(J.smartPtr):J.ptrType.registeredClass.rawDestructor(J.ptr)}function fr(J){J.count.value-=1;var X=J.count.value===0;X&&Uo(J)}function oo(J,X,fe){if(X===fe)return J;if(fe.baseClass===void 0)return null;var Me=oo(J,X,fe.baseClass);return Me===null?null:fe.downcast(Me)}var yn={};function Qr(){return Object.keys(Bo).length}function Da(){var J=[];for(var X in Bo)Bo.hasOwnProperty(X)&&J.push(Bo[X]);return J}var Fi=[];function ao(){for(;Fi.length;){var J=Fi.pop();J.$$.deleteScheduled=!1,J.delete()}}var Ui=void 0;function mi(J){Ui=J,Fi.length&&Ui&&Ui(ao)}function Ka(){o.getInheritedInstanceCount=Qr,o.getLiveInheritedInstances=Da,o.flushPendingDeletes=ao,o.setDelayFunction=mi}var Bo={};function Bi(J,X){for(X===void 0&&sn("ptr should not be undefined");J.baseClass;)X=J.upcast(X),J=J.baseClass;return X}function qa(J,X){return X=Bi(J,X),Bo[X]}function Gi(J,X){(!X.ptrType||!X.ptr)&&Xi("makeClassHandle requires ptr and ptrType");var fe=!!X.smartPtrType,Me=!!X.smartPtr;return fe!==Me&&Xi("Both smartPtrType and smartPtr must be specified"),X.count={value:1},de(Object.create(J,{$$:{value:X}}))}function ia(J){var X=this.getPointee(J);if(!X)return this.destructor(J),null;var fe=qa(this.registeredClass,X);if(fe!==void 0){if(fe.$$.count.value===0)return fe.$$.ptr=X,fe.$$.smartPtr=J,fe.clone();var Me=fe.clone();return this.destructor(J),Me}function We(){return this.isSmartPointer?Gi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:X,smartPtrType:this,smartPtr:J}):Gi(this.registeredClass.instancePrototype,{ptrType:this,ptr:J})}var ct=this.registeredClass.getActualType(X),et=yn[ct];if(!et)return We.call(this);var Ye;this.isConst?Ye=et.constPointerType:Ye=et.pointerType;var $=oo(X,this.registeredClass,Ye.registeredClass);return $===null?We.call(this):this.isSmartPointer?Gi(Ye.registeredClass.instancePrototype,{ptrType:Ye,ptr:$,smartPtrType:this,smartPtr:J}):Gi(Ye.registeredClass.instancePrototype,{ptrType:Ye,ptr:$})}function de(J){return typeof FinalizationRegistry>"u"?(de=X=>X,J):(To=new FinalizationRegistry(X=>{fr(X.$$)}),de=X=>{var fe=X.$$,Me=!!fe.smartPtr;if(Me){var We={$$:fe};To.register(X,We,X)}return X},ra=X=>To.unregister(X),de(J))}function Ue(){if(this.$$.ptr||Ea(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var J=de(Object.create(Object.getPrototypeOf(this),{$$:{value:Ha(this.$$)}}));return J.$$.count.value+=1,J.$$.deleteScheduled=!1,J}function _e(){this.$$.ptr||Ea(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&sn("Object already scheduled for deletion"),ra(this),fr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function ye(){return!this.$$.ptr}function je(){return this.$$.ptr||Ea(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&sn("Object already scheduled for deletion"),Fi.push(this),Fi.length===1&&Ui&&Ui(ao),this.$$.deleteScheduled=!0,this}function ot(){st.prototype.isAliasOf=Vi,st.prototype.clone=Ue,st.prototype.delete=_e,st.prototype.isDeleted=ye,st.prototype.deleteLater=je}function st(){}function ut(J,X,fe){if(J[X].overloadTable===void 0){var Me=J[X];J[X]=function(){return J[X].overloadTable.hasOwnProperty(arguments.length)||sn("Function '"+fe+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+J[X].overloadTable+")!"),J[X].overloadTable[arguments.length].apply(this,arguments)},J[X].overloadTable=[],J[X].overloadTable[Me.argCount]=Me}}function rt(J,X,fe){o.hasOwnProperty(J)?(sn("Cannot register public name '"+J+"' twice"),ut(o,J,J),o.hasOwnProperty(fe)&&sn("Cannot register multiple overloads of a function with the same number of arguments ("+fe+")!"),o[J].overloadTable[fe]=X):o[J]=X}function Ct(J,X,fe,Me,We,ct,et,Ye){this.name=J,this.constructor=X,this.instancePrototype=fe,this.rawDestructor=Me,this.baseClass=We,this.getActualType=ct,this.upcast=et,this.downcast=Ye,this.pureVirtualFunctions=[]}function Qt(J,X,fe){for(;X!==fe;)X.upcast||sn("Expected null or instance of "+fe.name+", got an instance of "+X.name),J=X.upcast(J),X=X.baseClass;return J}function on(J,X){if(X===null)return this.isReference&&sn("null is not a valid "+this.name),0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name);var fe=X.$$.ptrType.registeredClass,Me=Qt(X.$$.ptr,fe,this.registeredClass);return Me}function cn(J,X){var fe;if(X===null)return this.isReference&&sn("null is not a valid "+this.name),this.isSmartPointer?(fe=this.rawConstructor(),J!==null&&J.push(this.rawDestructor,fe),fe):0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&X.$$.ptrType.isConst&&sn("Cannot convert argument of type "+(X.$$.smartPtrType?X.$$.smartPtrType.name:X.$$.ptrType.name)+" to parameter type "+this.name);var Me=X.$$.ptrType.registeredClass;if(fe=Qt(X.$$.ptr,Me,this.registeredClass),this.isSmartPointer)switch(X.$$.smartPtr===void 0&&sn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:X.$$.smartPtrType===this?fe=X.$$.smartPtr:sn("Cannot convert argument of type "+(X.$$.smartPtrType?X.$$.smartPtrType.name:X.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:fe=X.$$.smartPtr;break;case 2:if(X.$$.smartPtrType===this)fe=X.$$.smartPtr;else{var We=X.clone();fe=this.rawShare(fe,Wi.toHandle(function(){We.delete()})),J!==null&&J.push(this.rawDestructor,fe)}break;default:sn("Unsupporting sharing policy")}return fe}function Gt(J,X){if(X===null)return this.isReference&&sn("null is not a valid "+this.name),0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name),X.$$.ptrType.isConst&&sn("Cannot convert argument of type "+X.$$.ptrType.name+" to parameter type "+this.name);var fe=X.$$.ptrType.registeredClass,Me=Qt(X.$$.ptr,fe,this.registeredClass);return Me}function xn(J){return this.rawGetPointee&&(J=this.rawGetPointee(J)),J}function er(J){this.rawDestructor&&this.rawDestructor(J)}function nr(J){J!==null&&J.delete()}function or(){qn.prototype.getPointee=xn,qn.prototype.destructor=er,qn.prototype.argPackAdvance=8,qn.prototype.readValueFromPointer=nt,qn.prototype.deleteObject=nr,qn.prototype.fromWireType=ia}function qn(J,X,fe,Me,We,ct,et,Ye,$,H,R){this.name=J,this.registeredClass=X,this.isReference=fe,this.isConst=Me,this.isSmartPointer=We,this.pointeeType=ct,this.sharingPolicy=et,this.rawGetPointee=Ye,this.rawConstructor=$,this.rawShare=H,this.rawDestructor=R,!We&&X.baseClass===void 0?Me?(this.toWireType=on,this.destructorFunction=null):(this.toWireType=Gt,this.destructorFunction=null):this.toWireType=cn}function At(J,X,fe){o.hasOwnProperty(J)||Xi("Replacing nonexistant public symbol"),o[J].overloadTable!==void 0&&fe!==void 0||(o[J]=X,o[J].argCount=fe)}function Bn(J,X,fe){var Me=o["dynCall_"+J];return fe&&fe.length?Me.apply(null,[X].concat(fe)):Me.call(null,X)}var dr=[];function si(J){var X=dr[J];return X||(J>=dr.length&&(dr.length=J+1),dr[J]=X=pe.get(J)),X}function jn(J,X,fe){if(J.includes("j"))return Bn(J,X,fe);var Me=si(X).apply(null,fe);return Me}function wr(J,X){var fe=[];return function(){return fe.length=0,Object.assign(fe,arguments),jn(J,X,fe)}}function ei(J,X){J=Pt(J);function fe(){return J.includes("j")?wr(J,X):si(X)}var Me=fe();return typeof Me!="function"&&sn("unknown function pointer with signature "+J+": "+X),Me}var xr=void 0;function uc(J){var X=Qe(J),fe=Pt(X);return Ze(X),fe}function ba(J,X){var fe=[],Me={};function We(ct){if(!Me[ct]&&!Lt[ct]){if(xt[ct]){xt[ct].forEach(We);return}fe.push(ct),Me[ct]=!0}}throw X.forEach(We),new xr(J+": "+fe.map(uc).join([", "]))}function Yi(J,X,fe,Me,We,ct,et,Ye,$,H,R,U,q){R=Pt(R),ct=ei(We,ct),Ye&&(Ye=ei(et,Ye)),H&&(H=ei($,H)),q=ei(U,q);var le=Pn(R);rt(le,function(){ba("Cannot construct "+R+" due to unbound types",[Me])}),Mr([J,X,fe],Me?[Me]:[],function(he){he=he[0];var ve,Te;Me?(ve=he.registeredClass,Te=ve.instancePrototype):Te=st.prototype;var be=$n(le,function(){if(Object.getPrototypeOf(this)!==ke)throw new _n("Use 'new' to construct "+R);if(Je.constructor_body===void 0)throw new _n(R+" has no accessible constructor");var dn=Je.constructor_body[arguments.length];if(dn===void 0)throw new _n("Tried to invoke ctor of "+R+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(Je.constructor_body).toString()+") parameters instead!");return dn.apply(this,arguments)}),ke=Object.create(Te,{constructor:{value:be}});be.prototype=ke;var Je=new Ct(R,be,ke,q,ve,ct,Ye,H),pt=new qn(R,Je,!0,!1,!1),Mt=new qn(R+"*",Je,!1,!1,!1),Tt=new qn(R+" const*",Je,!1,!0,!1);return yn[J]={pointerType:Mt,constPointerType:Tt},At(le,be),[pt,Mt,Tt]})}function Xa(J,X){for(var fe=[],Me=0;Me>2]);return fe}function cl(J,X){if(!(J instanceof Function))throw new TypeError("new_ called with constructor type "+typeof J+" which is not a function");var fe=$n(J.name||"unknownFunctionName",function(){});fe.prototype=J.prototype;var Me=new fe,We=J.apply(Me,X);return We instanceof Object?We:Me}function ll(J,X,fe,Me,We){var ct=X.length;ct<2&&sn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var et=X[1]!==null&&fe!==null,Ye=!1,$=1;${Lt.hasOwnProperty(Ye)?ze[$]=Lt[Ye]:(ct.push(Ye),dt.hasOwnProperty(Ye)||(dt[Ye]=[]),dt[Ye].push(()=>{ze[$]=Lt[Ye],++et,et===ct.length&&Me(ze)}))}),ct.length===0&&Me(ze)}function Ue(J){var X=je[J];delete je[J];var fe=X.rawConstructor,Me=X.rawDestructor,ze=X.fields,ct=ze.map(et=>et.getterReturnType).concat(ze.map(et=>et.setterArgumentType));Mr([J],ct,et=>{var Ye={};return ze.forEach(($,H)=>{var R=$.fieldName,U=et[H],q=$.getter,le=$.getterContext,he=et[H+ze.length],ve=$.setter,Te=$.setterContext;Ye[R]={read:be=>U.fromWireType(q(le,be)),write:(be,ke)=>{var Je=[];ve(Te,be,he.toWireType(Je,ke)),nt(Je)}}}),[{name:X.name,fromWireType:function($){var H={};for(var R in Ye)H[R]=Ye[R].read($);return Me($),H},toWireType:function($,H){for(var R in Ye)if(!(R in H))throw new TypeError('Missing field: "'+R+'"');var U=fe();for(R in Ye)Ye[R].write(U,H[R]);return $!==null&&$.push(Me,U),U},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:Me}]})}function ft(J,X,fe,Me,ze){}function Ut(J){switch(J){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+J)}}function Sn(){for(var J=new Array(256),X=0;X<256;++X)J[X]=String.fromCharCode(X);Qn=J}var Qn=void 0;function Pt(J){for(var X="",fe=J;A[fe];)X+=Qn[A[fe++]];return X}var _n=void 0;function sn(J){throw new _n(J)}function rn(J,X,fe={}){if(!("argPackAdvance"in X))throw new TypeError("registerType registeredInstance requires argPackAdvance");var Me=X.name;if(J||sn('type "'+Me+'" must have a positive integer typeid pointer'),Lt.hasOwnProperty(J)){if(fe.ignoreDuplicateRegistrations)return;sn("Cannot register type '"+Me+"' twice")}if(Lt[J]=X,delete xt[J],dt.hasOwnProperty(J)){var ze=dt[J];delete dt[J],ze.forEach(ct=>ct())}}function pi(J,X,fe,Me,ze){var ct=Ut(fe);X=Pt(X),rn(J,{name:X,fromWireType:function(et){return!!et},toWireType:function(et,Ye){return Ye?Me:ze},argPackAdvance:8,readValueFromPointer:function(et){var Ye;if(fe===1)Ye=G;else if(fe===2)Ye=k;else if(fe===4)Ye=j;else throw new TypeError("Unknown boolean type size: "+X);return this.fromWireType(Ye[et>>ct])},destructorFunction:null})}function Vi(J){if(!(this instanceof st)||!(J instanceof st))return!1;for(var X=this.$$.ptrType.registeredClass,fe=this.$$.ptr,Me=J.$$.ptrType.registeredClass,ze=J.$$.ptr;X.baseClass;)fe=X.upcast(fe),X=X.baseClass;for(;Me.baseClass;)ze=Me.upcast(ze),Me=Me.baseClass;return X===Me&&fe===ze}function Ha(J){return{count:J.count,deleteScheduled:J.deleteScheduled,preservePointerOnDelete:J.preservePointerOnDelete,ptr:J.ptr,ptrType:J.ptrType,smartPtr:J.smartPtr,smartPtrType:J.smartPtrType}}function Ea(J){function X(fe){return fe.$$.ptrType.registeredClass.name}sn(X(J)+" instance already deleted")}var To=!1;function ra(J){}function Uo(J){J.smartPtr?J.smartPtrType.rawDestructor(J.smartPtr):J.ptrType.registeredClass.rawDestructor(J.ptr)}function fr(J){J.count.value-=1;var X=J.count.value===0;X&&Uo(J)}function oo(J,X,fe){if(X===fe)return J;if(fe.baseClass===void 0)return null;var Me=oo(J,X,fe.baseClass);return Me===null?null:fe.downcast(Me)}var yn={};function Qr(){return Object.keys(Bo).length}function Da(){var J=[];for(var X in Bo)Bo.hasOwnProperty(X)&&J.push(Bo[X]);return J}var Fi=[];function ao(){for(;Fi.length;){var J=Fi.pop();J.$$.deleteScheduled=!1,J.delete()}}var Ui=void 0;function mi(J){Ui=J,Fi.length&&Ui&&Ui(ao)}function Ka(){o.getInheritedInstanceCount=Qr,o.getLiveInheritedInstances=Da,o.flushPendingDeletes=ao,o.setDelayFunction=mi}var Bo={};function Bi(J,X){for(X===void 0&&sn("ptr should not be undefined");J.baseClass;)X=J.upcast(X),J=J.baseClass;return X}function qa(J,X){return X=Bi(J,X),Bo[X]}function Gi(J,X){(!X.ptrType||!X.ptr)&&Xi("makeClassHandle requires ptr and ptrType");var fe=!!X.smartPtrType,Me=!!X.smartPtr;return fe!==Me&&Xi("Both smartPtrType and smartPtr must be specified"),X.count={value:1},de(Object.create(J,{$$:{value:X}}))}function ia(J){var X=this.getPointee(J);if(!X)return this.destructor(J),null;var fe=qa(this.registeredClass,X);if(fe!==void 0){if(fe.$$.count.value===0)return fe.$$.ptr=X,fe.$$.smartPtr=J,fe.clone();var Me=fe.clone();return this.destructor(J),Me}function ze(){return this.isSmartPointer?Gi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:X,smartPtrType:this,smartPtr:J}):Gi(this.registeredClass.instancePrototype,{ptrType:this,ptr:J})}var ct=this.registeredClass.getActualType(X),et=yn[ct];if(!et)return ze.call(this);var Ye;this.isConst?Ye=et.constPointerType:Ye=et.pointerType;var $=oo(X,this.registeredClass,Ye.registeredClass);return $===null?ze.call(this):this.isSmartPointer?Gi(Ye.registeredClass.instancePrototype,{ptrType:Ye,ptr:$,smartPtrType:this,smartPtr:J}):Gi(Ye.registeredClass.instancePrototype,{ptrType:Ye,ptr:$})}function de(J){return typeof FinalizationRegistry>"u"?(de=X=>X,J):(To=new FinalizationRegistry(X=>{fr(X.$$)}),de=X=>{var fe=X.$$,Me=!!fe.smartPtr;if(Me){var ze={$$:fe};To.register(X,ze,X)}return X},ra=X=>To.unregister(X),de(J))}function We(){if(this.$$.ptr||Ea(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var J=de(Object.create(Object.getPrototypeOf(this),{$$:{value:Ha(this.$$)}}));return J.$$.count.value+=1,J.$$.deleteScheduled=!1,J}function Se(){this.$$.ptr||Ea(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&sn("Object already scheduled for deletion"),ra(this),fr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function we(){return!this.$$.ptr}function Ge(){return this.$$.ptr||Ea(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&sn("Object already scheduled for deletion"),Fi.push(this),Fi.length===1&&Ui&&Ui(ao),this.$$.deleteScheduled=!0,this}function tt(){st.prototype.isAliasOf=Vi,st.prototype.clone=We,st.prototype.delete=Se,st.prototype.isDeleted=we,st.prototype.deleteLater=Ge}function st(){}function ut(J,X,fe){if(J[X].overloadTable===void 0){var Me=J[X];J[X]=function(){return J[X].overloadTable.hasOwnProperty(arguments.length)||sn("Function '"+fe+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+J[X].overloadTable+")!"),J[X].overloadTable[arguments.length].apply(this,arguments)},J[X].overloadTable=[],J[X].overloadTable[Me.argCount]=Me}}function it(J,X,fe){o.hasOwnProperty(J)?(sn("Cannot register public name '"+J+"' twice"),ut(o,J,J),o.hasOwnProperty(fe)&&sn("Cannot register multiple overloads of a function with the same number of arguments ("+fe+")!"),o[J].overloadTable[fe]=X):o[J]=X}function Ct(J,X,fe,Me,ze,ct,et,Ye){this.name=J,this.constructor=X,this.instancePrototype=fe,this.rawDestructor=Me,this.baseClass=ze,this.getActualType=ct,this.upcast=et,this.downcast=Ye,this.pureVirtualFunctions=[]}function Qt(J,X,fe){for(;X!==fe;)X.upcast||sn("Expected null or instance of "+fe.name+", got an instance of "+X.name),J=X.upcast(J),X=X.baseClass;return J}function on(J,X){if(X===null)return this.isReference&&sn("null is not a valid "+this.name),0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name);var fe=X.$$.ptrType.registeredClass,Me=Qt(X.$$.ptr,fe,this.registeredClass);return Me}function cn(J,X){var fe;if(X===null)return this.isReference&&sn("null is not a valid "+this.name),this.isSmartPointer?(fe=this.rawConstructor(),J!==null&&J.push(this.rawDestructor,fe),fe):0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&X.$$.ptrType.isConst&&sn("Cannot convert argument of type "+(X.$$.smartPtrType?X.$$.smartPtrType.name:X.$$.ptrType.name)+" to parameter type "+this.name);var Me=X.$$.ptrType.registeredClass;if(fe=Qt(X.$$.ptr,Me,this.registeredClass),this.isSmartPointer)switch(X.$$.smartPtr===void 0&&sn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:X.$$.smartPtrType===this?fe=X.$$.smartPtr:sn("Cannot convert argument of type "+(X.$$.smartPtrType?X.$$.smartPtrType.name:X.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:fe=X.$$.smartPtr;break;case 2:if(X.$$.smartPtrType===this)fe=X.$$.smartPtr;else{var ze=X.clone();fe=this.rawShare(fe,Wi.toHandle(function(){ze.delete()})),J!==null&&J.push(this.rawDestructor,fe)}break;default:sn("Unsupporting sharing policy")}return fe}function Gt(J,X){if(X===null)return this.isReference&&sn("null is not a valid "+this.name),0;X.$$||sn('Cannot pass "'+fc(X)+'" as a '+this.name),X.$$.ptr||sn("Cannot pass deleted object as a pointer of type "+this.name),X.$$.ptrType.isConst&&sn("Cannot convert argument of type "+X.$$.ptrType.name+" to parameter type "+this.name);var fe=X.$$.ptrType.registeredClass,Me=Qt(X.$$.ptr,fe,this.registeredClass);return Me}function xn(J){return this.rawGetPointee&&(J=this.rawGetPointee(J)),J}function er(J){this.rawDestructor&&this.rawDestructor(J)}function nr(J){J!==null&&J.delete()}function or(){qn.prototype.getPointee=xn,qn.prototype.destructor=er,qn.prototype.argPackAdvance=8,qn.prototype.readValueFromPointer=rt,qn.prototype.deleteObject=nr,qn.prototype.fromWireType=ia}function qn(J,X,fe,Me,ze,ct,et,Ye,$,H,R){this.name=J,this.registeredClass=X,this.isReference=fe,this.isConst=Me,this.isSmartPointer=ze,this.pointeeType=ct,this.sharingPolicy=et,this.rawGetPointee=Ye,this.rawConstructor=$,this.rawShare=H,this.rawDestructor=R,!ze&&X.baseClass===void 0?Me?(this.toWireType=on,this.destructorFunction=null):(this.toWireType=Gt,this.destructorFunction=null):this.toWireType=cn}function At(J,X,fe){o.hasOwnProperty(J)||Xi("Replacing nonexistant public symbol"),o[J].overloadTable!==void 0&&fe!==void 0||(o[J]=X,o[J].argCount=fe)}function Bn(J,X,fe){var Me=o["dynCall_"+J];return fe&&fe.length?Me.apply(null,[X].concat(fe)):Me.call(null,X)}var dr=[];function si(J){var X=dr[J];return X||(J>=dr.length&&(dr.length=J+1),dr[J]=X=pe.get(J)),X}function jn(J,X,fe){if(J.includes("j"))return Bn(J,X,fe);var Me=si(X).apply(null,fe);return Me}function wr(J,X){var fe=[];return function(){return fe.length=0,Object.assign(fe,arguments),jn(J,X,fe)}}function ei(J,X){J=Pt(J);function fe(){return J.includes("j")?wr(J,X):si(X)}var Me=fe();return typeof Me!="function"&&sn("unknown function pointer with signature "+J+": "+X),Me}var xr=void 0;function uc(J){var X=Qe(J),fe=Pt(X);return Ze(X),fe}function ba(J,X){var fe=[],Me={};function ze(ct){if(!Me[ct]&&!Lt[ct]){if(xt[ct]){xt[ct].forEach(ze);return}fe.push(ct),Me[ct]=!0}}throw X.forEach(ze),new xr(J+": "+fe.map(uc).join([", "]))}function Yi(J,X,fe,Me,ze,ct,et,Ye,$,H,R,U,q){R=Pt(R),ct=ei(ze,ct),Ye&&(Ye=ei(et,Ye)),H&&(H=ei($,H)),q=ei(U,q);var le=Pn(R);it(le,function(){ba("Cannot construct "+R+" due to unbound types",[Me])}),Mr([J,X,fe],Me?[Me]:[],function(he){he=he[0];var ve,Te;Me?(ve=he.registeredClass,Te=ve.instancePrototype):Te=st.prototype;var be=$n(le,function(){if(Object.getPrototypeOf(this)!==ke)throw new _n("Use 'new' to construct "+R);if(Je.constructor_body===void 0)throw new _n(R+" has no accessible constructor");var dn=Je.constructor_body[arguments.length];if(dn===void 0)throw new _n("Tried to invoke ctor of "+R+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(Je.constructor_body).toString()+") parameters instead!");return dn.apply(this,arguments)}),ke=Object.create(Te,{constructor:{value:be}});be.prototype=ke;var Je=new Ct(R,be,ke,q,ve,ct,Ye,H),pt=new qn(R,Je,!0,!1,!1),Mt=new qn(R+"*",Je,!1,!1,!1),Tt=new qn(R+" const*",Je,!1,!0,!1);return yn[J]={pointerType:Mt,constPointerType:Tt},At(le,be),[pt,Mt,Tt]})}function Xa(J,X){for(var fe=[],Me=0;Me>2]);return fe}function cl(J,X){if(!(J instanceof Function))throw new TypeError("new_ called with constructor type "+typeof J+" which is not a function");var fe=$n(J.name||"unknownFunctionName",function(){});fe.prototype=J.prototype;var Me=new fe,ze=J.apply(Me,X);return ze instanceof Object?ze:Me}function ll(J,X,fe,Me,ze){var ct=X.length;ct<2&&sn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var et=X[1]!==null&&fe!==null,Ye=!1,$=1;$0?", ":"")+U),q+=(H?"var rv = ":"")+"invoker(fn"+(U.length>0?", ":"")+U+`); `,Ye)q+=`runDestructors(destructors); @@ -3831,20 +3831,20 @@ throwBindingError('function `+J+" called with ' + arguments.length + ' arguments `,he.push(Te+"_dtor"),ve.push(X[$].destructorFunction))}H&&(q+=`var ret = retType.fromWireType(rv); return ret; `),q+=`} -`,he.push(q);var be=cl(Function,he).apply(null,ve);return be}function bs(J,X,fe,Me,We,ct){E(X>0);var et=Xa(X,fe);We=ei(Me,We),Mr([],[J],function(Ye){Ye=Ye[0];var $="constructor "+Ye.name;if(Ye.registeredClass.constructor_body===void 0&&(Ye.registeredClass.constructor_body=[]),Ye.registeredClass.constructor_body[X-1]!==void 0)throw new _n("Cannot register multiple constructors with identical number of parameters ("+(X-1)+") for class '"+Ye.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return Ye.registeredClass.constructor_body[X-1]=()=>{ba("Cannot construct "+Ye.name+" due to unbound types",et)},Mr([],et,function(H){return H.splice(1,0,null),Ye.registeredClass.constructor_body[X-1]=ll($,H,null,We,ct),[]}),[]})}function gr(J,X,fe,Me,We,ct,et,Ye){var $=Xa(fe,Me);X=Pt(X),ct=ei(We,ct),Mr([],[J],function(H){H=H[0];var R=H.name+"."+X;X.startsWith("@@")&&(X=Symbol[X.substring(2)]),Ye&&H.registeredClass.pureVirtualFunctions.push(X);function U(){ba("Cannot call "+R+" due to unbound types",$)}var q=H.registeredClass.instancePrototype,le=q[X];return le===void 0||le.overloadTable===void 0&&le.className!==H.name&&le.argCount===fe-2?(U.argCount=fe-2,U.className=H.name,q[X]=U):(ut(q,X,R),q[X].overloadTable[fe-2]=U),Mr([],$,function(he){var ve=ll(R,he,H,ct,et);return q[X].overloadTable===void 0?(ve.argCount=fe-2,q[X]=ve):q[X].overloadTable[fe-2]=ve,[]}),[]})}var Ya=[],vi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ci(J){J>4&&--vi[J].refcount===0&&(vi[J]=void 0,Ya.push(J))}function ul(){for(var J=0,X=5;X(J||sn("Cannot use deleted val. handle = "+J),vi[J].value),toHandle:J=>{switch(J){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var X=Ya.length?Ya.pop():vi.length;return vi[X]={refcount:1,value:J},X}}}};function Go(J,X){X=Pt(X),rn(J,{name:X,fromWireType:function(fe){var Me=Wi.toValue(fe);return ci(fe),Me},toWireType:function(fe,Me){return Wi.toHandle(Me)},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:null})}function fc(J){if(J===null)return"null";var X=typeof J;return X==="object"||X==="array"||X==="function"?J.toString():""+J}function Ja(J,X){switch(X){case 2:return function(fe){return this.fromWireType(re[fe>>2])};case 3:return function(fe){return this.fromWireType(ue[fe>>3])};default:throw new TypeError("Unknown float type: "+J)}}function Ji(J,X,fe){var Me=Ut(fe);X=Pt(X),rn(J,{name:X,fromWireType:function(We){return We},toWireType:function(We,ct){return ct},argPackAdvance:8,readValueFromPointer:Ja(X,Me),destructorFunction:null})}function fl(J,X,fe){switch(X){case 0:return fe?function(We){return G[We]}:function(We){return A[We]};case 1:return fe?function(We){return k[We>>1]}:function(We){return F[We>>1]};case 2:return fe?function(We){return j[We>>2]}:function(We){return Y[We>>2]};default:throw new TypeError("Unknown integer type: "+J)}}function Bu(J,X,fe,Me,We){X=Pt(X);var ct=Ut(fe),et=U=>U;if(Me===0){var Ye=32-8*fe;et=U=>U<>>Ye}var $=X.includes("unsigned"),H=(U,q)=>{},R;$?R=function(U,q){return H(q,this.name),q>>>0}:R=function(U,q){return H(q,this.name),q},rn(J,{name:X,fromWireType:et,toWireType:R,argPackAdvance:8,readValueFromPointer:fl(X,ct,Me!==0),destructorFunction:null})}function Gu(J,X,fe){var Me=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],We=Me[X];function ct(et){et=et>>2;var Ye=Y,$=Ye[et],H=Ye[et+1];return new We(V,H,$)}fe=Pt(fe),rn(J,{name:fe,fromWireType:ct,argPackAdvance:8,readValueFromPointer:ct},{ignoreDuplicateRegistrations:!0})}function dl(J,X){X=Pt(X);var fe=X==="std::string";rn(J,{name:X,fromWireType:function(Me){var We=Y[Me>>2],ct=Me+4,et;if(fe)for(var Ye=ct,$=0;$<=We;++$){var H=ct+$;if($==We||A[H]==0){var R=H-Ye,U=I(Ye,R);et===void 0?et=U:(et+="\0",et+=U),Ye=H+1}}else{for(var q=new Array(We),$=0;$>2]=ct,fe&&et)M(We,$,ct+1);else if(et)for(var H=0;H255&&(Ze($),sn("String has UTF-16 code units that do not fit in 8 bits")),A[$+H]=R}else for(var H=0;H>1,We=Me+X/2;!(Me>=We)&&F[Me];)++Me;if(fe=Me<<1,fe-J>32&&Za)return Za.decode(A.subarray(J,fe));for(var ct="",et=0;!(et>=X/2);++et){var Ye=k[J+et*2>>1];if(Ye==0)break;ct+=String.fromCharCode(Ye)}return ct}function dc(J,X,fe){if(fe===void 0&&(fe=2147483647),fe<2)return 0;fe-=2;for(var Me=X,We=fe>1]=et,X+=2}return k[X>>1]=0,X-Me}function Wu(J){return J.length*2}function zu(J,X){for(var fe=0,Me="";!(fe>=X/4);){var We=j[J+fe*4>>2];if(We==0)break;if(++fe,We>=65536){var ct=We-65536;Me+=String.fromCharCode(55296|ct>>10,56320|ct&1023)}else Me+=String.fromCharCode(We)}return Me}function $u(J,X,fe){if(fe===void 0&&(fe=2147483647),fe<4)return 0;for(var Me=X,We=Me+fe-4,ct=0;ct=55296&&et<=57343){var Ye=J.charCodeAt(++ct);et=65536+((et&1023)<<10)|Ye&1023}if(j[X>>2]=et,X+=4,X+4>We)break}return j[X>>2]=0,X-Me}function ju(J){for(var X=0,fe=0;fe=55296&&Me<=57343&&++fe,X+=4}return X}function Hu(J,X,fe){fe=Pt(fe);var Me,We,ct,et,Ye;X===2?(Me=hl,We=dc,et=Wu,ct=()=>F,Ye=1):X===4&&(Me=zu,We=$u,et=ju,ct=()=>Y,Ye=2),rn(J,{name:fe,fromWireType:function($){for(var H=Y[$>>2],R=ct(),U,q=$+4,le=0;le<=H;++le){var he=$+4+le*X;if(le==H||R[he>>Ye]==0){var ve=he-q,Te=Me(q,ve);U===void 0?U=Te:(U+="\0",U+=Te),q=he+X}}return Ze($),U},toWireType:function($,H){typeof H!="string"&&sn("Cannot pass non-string to C++ string type "+fe);var R=et(H),U=He(4+R+X);return Y[U>>2]=R>>Ye,We(H,U+4,R+X),$!==null&&$.push(Ze,U),U},argPackAdvance:8,readValueFromPointer:nt,destructorFunction:function($){Ze($)}})}function Ku(J,X,fe,Me,We,ct){$e[J]={name:Pt(X),rawConstructor:ei(fe,Me),rawDestructor:ei(We,ct),fields:[]}}function qu(J,X,fe,Me,We,ct,et,Ye,$,H){$e[J].fields.push({fieldName:Pt(X),getterReturnType:fe,getter:ei(Me,We),getterContext:ct,setterArgumentType:et,setter:ei(Ye,$),setterContext:H})}function gl(J,X){X=Pt(X),rn(J,{isVoid:!0,name:X,argPackAdvance:0,fromWireType:function(){},toWireType:function(fe,Me){}})}var Xu={};function pl(J){var X=Xu[J];return X===void 0?Pt(J):X}function ml(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function Yu(J){return J===0?Wi.toHandle(ml()):(J=pl(J),Wi.toHandle(ml()[J]))}function hc(J){J>4&&(vi[J].refcount+=1)}function vl(J,X){var fe=Lt[J];return fe===void 0&&sn(X+" has unknown type "+uc(J)),fe}function yl(J){for(var X="",fe=0;feY,We="return function emval_allocator_"+J+`(constructor, argTypes, args) { +`,he.push(q);var be=cl(Function,he).apply(null,ve);return be}function bs(J,X,fe,Me,ze,ct){E(X>0);var et=Xa(X,fe);ze=ei(Me,ze),Mr([],[J],function(Ye){Ye=Ye[0];var $="constructor "+Ye.name;if(Ye.registeredClass.constructor_body===void 0&&(Ye.registeredClass.constructor_body=[]),Ye.registeredClass.constructor_body[X-1]!==void 0)throw new _n("Cannot register multiple constructors with identical number of parameters ("+(X-1)+") for class '"+Ye.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return Ye.registeredClass.constructor_body[X-1]=()=>{ba("Cannot construct "+Ye.name+" due to unbound types",et)},Mr([],et,function(H){return H.splice(1,0,null),Ye.registeredClass.constructor_body[X-1]=ll($,H,null,ze,ct),[]}),[]})}function gr(J,X,fe,Me,ze,ct,et,Ye){var $=Xa(fe,Me);X=Pt(X),ct=ei(ze,ct),Mr([],[J],function(H){H=H[0];var R=H.name+"."+X;X.startsWith("@@")&&(X=Symbol[X.substring(2)]),Ye&&H.registeredClass.pureVirtualFunctions.push(X);function U(){ba("Cannot call "+R+" due to unbound types",$)}var q=H.registeredClass.instancePrototype,le=q[X];return le===void 0||le.overloadTable===void 0&&le.className!==H.name&&le.argCount===fe-2?(U.argCount=fe-2,U.className=H.name,q[X]=U):(ut(q,X,R),q[X].overloadTable[fe-2]=U),Mr([],$,function(he){var ve=ll(R,he,H,ct,et);return q[X].overloadTable===void 0?(ve.argCount=fe-2,q[X]=ve):q[X].overloadTable[fe-2]=ve,[]}),[]})}var Ya=[],vi=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ci(J){J>4&&--vi[J].refcount===0&&(vi[J]=void 0,Ya.push(J))}function ul(){for(var J=0,X=5;X(J||sn("Cannot use deleted val. handle = "+J),vi[J].value),toHandle:J=>{switch(J){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var X=Ya.length?Ya.pop():vi.length;return vi[X]={refcount:1,value:J},X}}}};function Go(J,X){X=Pt(X),rn(J,{name:X,fromWireType:function(fe){var Me=Wi.toValue(fe);return ci(fe),Me},toWireType:function(fe,Me){return Wi.toHandle(Me)},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:null})}function fc(J){if(J===null)return"null";var X=typeof J;return X==="object"||X==="array"||X==="function"?J.toString():""+J}function Ja(J,X){switch(X){case 2:return function(fe){return this.fromWireType(re[fe>>2])};case 3:return function(fe){return this.fromWireType(ue[fe>>3])};default:throw new TypeError("Unknown float type: "+J)}}function Ji(J,X,fe){var Me=Ut(fe);X=Pt(X),rn(J,{name:X,fromWireType:function(ze){return ze},toWireType:function(ze,ct){return ct},argPackAdvance:8,readValueFromPointer:Ja(X,Me),destructorFunction:null})}function fl(J,X,fe){switch(X){case 0:return fe?function(ze){return G[ze]}:function(ze){return A[ze]};case 1:return fe?function(ze){return k[ze>>1]}:function(ze){return F[ze>>1]};case 2:return fe?function(ze){return j[ze>>2]}:function(ze){return Y[ze>>2]};default:throw new TypeError("Unknown integer type: "+J)}}function Bu(J,X,fe,Me,ze){X=Pt(X);var ct=Ut(fe),et=U=>U;if(Me===0){var Ye=32-8*fe;et=U=>U<>>Ye}var $=X.includes("unsigned"),H=(U,q)=>{},R;$?R=function(U,q){return H(q,this.name),q>>>0}:R=function(U,q){return H(q,this.name),q},rn(J,{name:X,fromWireType:et,toWireType:R,argPackAdvance:8,readValueFromPointer:fl(X,ct,Me!==0),destructorFunction:null})}function Gu(J,X,fe){var Me=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],ze=Me[X];function ct(et){et=et>>2;var Ye=Y,$=Ye[et],H=Ye[et+1];return new ze(V,H,$)}fe=Pt(fe),rn(J,{name:fe,fromWireType:ct,argPackAdvance:8,readValueFromPointer:ct},{ignoreDuplicateRegistrations:!0})}function dl(J,X){X=Pt(X);var fe=X==="std::string";rn(J,{name:X,fromWireType:function(Me){var ze=Y[Me>>2],ct=Me+4,et;if(fe)for(var Ye=ct,$=0;$<=ze;++$){var H=ct+$;if($==ze||A[H]==0){var R=H-Ye,U=I(Ye,R);et===void 0?et=U:(et+="\0",et+=U),Ye=H+1}}else{for(var q=new Array(ze),$=0;$>2]=ct,fe&&et)M(ze,$,ct+1);else if(et)for(var H=0;H255&&(Ze($),sn("String has UTF-16 code units that do not fit in 8 bits")),A[$+H]=R}else for(var H=0;H>1,ze=Me+X/2;!(Me>=ze)&&F[Me];)++Me;if(fe=Me<<1,fe-J>32&&Za)return Za.decode(A.subarray(J,fe));for(var ct="",et=0;!(et>=X/2);++et){var Ye=k[J+et*2>>1];if(Ye==0)break;ct+=String.fromCharCode(Ye)}return ct}function dc(J,X,fe){if(fe===void 0&&(fe=2147483647),fe<2)return 0;fe-=2;for(var Me=X,ze=fe>1]=et,X+=2}return k[X>>1]=0,X-Me}function Wu(J){return J.length*2}function zu(J,X){for(var fe=0,Me="";!(fe>=X/4);){var ze=j[J+fe*4>>2];if(ze==0)break;if(++fe,ze>=65536){var ct=ze-65536;Me+=String.fromCharCode(55296|ct>>10,56320|ct&1023)}else Me+=String.fromCharCode(ze)}return Me}function $u(J,X,fe){if(fe===void 0&&(fe=2147483647),fe<4)return 0;for(var Me=X,ze=Me+fe-4,ct=0;ct=55296&&et<=57343){var Ye=J.charCodeAt(++ct);et=65536+((et&1023)<<10)|Ye&1023}if(j[X>>2]=et,X+=4,X+4>ze)break}return j[X>>2]=0,X-Me}function ju(J){for(var X=0,fe=0;fe=55296&&Me<=57343&&++fe,X+=4}return X}function Hu(J,X,fe){fe=Pt(fe);var Me,ze,ct,et,Ye;X===2?(Me=hl,ze=dc,et=Wu,ct=()=>F,Ye=1):X===4&&(Me=zu,ze=$u,et=ju,ct=()=>Y,Ye=2),rn(J,{name:fe,fromWireType:function($){for(var H=Y[$>>2],R=ct(),U,q=$+4,le=0;le<=H;++le){var he=$+4+le*X;if(le==H||R[he>>Ye]==0){var ve=he-q,Te=Me(q,ve);U===void 0?U=Te:(U+="\0",U+=Te),q=he+X}}return Ze($),U},toWireType:function($,H){typeof H!="string"&&sn("Cannot pass non-string to C++ string type "+fe);var R=et(H),U=He(4+R+X);return Y[U>>2]=R>>Ye,ze(H,U+4,R+X),$!==null&&$.push(Ze,U),U},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:function($){Ze($)}})}function Ku(J,X,fe,Me,ze,ct){je[J]={name:Pt(X),rawConstructor:ei(fe,Me),rawDestructor:ei(ze,ct),fields:[]}}function qu(J,X,fe,Me,ze,ct,et,Ye,$,H){je[J].fields.push({fieldName:Pt(X),getterReturnType:fe,getter:ei(Me,ze),getterContext:ct,setterArgumentType:et,setter:ei(Ye,$),setterContext:H})}function gl(J,X){X=Pt(X),rn(J,{isVoid:!0,name:X,argPackAdvance:0,fromWireType:function(){},toWireType:function(fe,Me){}})}var Xu={};function pl(J){var X=Xu[J];return X===void 0?Pt(J):X}function ml(){return typeof globalThis=="object"?globalThis:function(){return Function}()("return this")()}function Yu(J){return J===0?Wi.toHandle(ml()):(J=pl(J),Wi.toHandle(ml()[J]))}function hc(J){J>4&&(vi[J].refcount+=1)}function vl(J,X){var fe=Lt[J];return fe===void 0&&sn(X+" has unknown type "+uc(J)),fe}function yl(J){for(var X="",fe=0;feY,ze="return function emval_allocator_"+J+`(constructor, argTypes, args) { var HEAPU32 = getMemory(); -`,fe=0;fe>2)], 'parameter "+fe+`'); +`,fe=0;fe>2)], 'parameter "+fe+`'); var arg`+fe+" = argType"+fe+`.readValueFromPointer(args); args += argType`+fe+`['argPackAdvance']; argTypes += 4; -`;return We+="var obj = new constructor("+X+`); +`;return ze+="var obj = new constructor("+X+`); return valueToHandle(obj); } -`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",We)(vl,o,Wi.toHandle,Me)}var gc={};function Ju(J,X,fe,Me){J=Wi.toValue(J);var We=gc[X];return We||(We=yl(X),gc[X]=We),We(J,fe,Me)}function wl(J,X){J=vl(J,"_emval_take_value");var fe=J.readValueFromPointer(X);return Wi.toHandle(fe)}function Zu(){ze("")}function xl(){return 2147483648}function Qu(){return xl()}function ef(J,X,fe){A.copyWithin(J,X,X+fe)}function tf(J){try{return _.grow(J-V.byteLength+65535>>>16),ce(_.buffer),1}catch{}}function nf(J){var X=A.length;J=J>>>0;var fe=xl();if(J>fe)return!1;let Me=($,H)=>$+(H-$%H)%H;for(var We=1;We<=4;We*=2){var ct=X*(1+.2/We);ct=Math.min(ct,J+100663296);var et=Math.min(fe,Me(Math.max(J,ct),65536)),Ye=tf(et);if(Ye)return!0}return!1}var pc={};function mc(){return l||"./this.program"}function oa(){if(!oa.strings){var J=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",X={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:J,_:mc()};for(var fe in pc)pc[fe]===void 0?delete X[fe]:X[fe]=pc[fe];var Me=[];for(var fe in X)Me.push(fe+"="+X[fe]);oa.strings=Me}return oa.strings}function Ia(J,X,fe){for(var Me=0;Me>0]=J.charCodeAt(Me);G[X>>0]=0}function Eo(J,X){var fe=0;return oa().forEach(function(Me,We){var ct=X+fe;Y[J+We*4>>2]=ct,Ia(Me,ct),fe+=Me.length+1}),0}function Cl(J,X){var fe=oa();Y[J>>2]=fe.length;var Me=0;return fe.forEach(function(We){Me+=We.length+1}),Y[X>>2]=Me,0}function Sl(J){return 52}function vc(J,X,fe,Me,We){return 70}var _l=[null,[],[]];function Is(J,X){var fe=_l[J];X===0||X===10?((J===1?x:C)(b(fe,0)),fe.length=0):fe.push(X)}function Tl(J,X,fe,Me){for(var We=0,ct=0;ct>2],Ye=Y[X+4>>2];X+=8;for(var $=0;$>2]=We,0}function Q(J){var X=o["_"+J];return X}function te(J,X){G.set(J,X)}function me(J,X,fe,Me,We){var ct={string:he=>{var ve=0;if(he!=null&&he!==0){var Te=(he.length<<2)+1;ve=vt(Te),M(he,ve,Te)}return ve},array:he=>{var ve=vt(he.length);return te(he,ve),ve}};function et(he){return X==="string"?I(he):X==="boolean"?!!he:he}var Ye=Q(J),$=[],H=0;if(Me)for(var R=0;R0||(B(),ee>0))return;function X(){Wt||(Wt=!0,o.calledRun=!0,!T&&(O(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),z()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),X()},1)):X()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Kt(),i.ready}})();t.exports=r})(sG);var Exe=sG.exports;const Dxe=ac(Exe),bxe=new URL("/static/dv3d/openjpegwasm_decode.wasm",import.meta.url),Cg={codec:void 0,decoder:void 0,decodeConfig:{}};function Ixe(t){if(Cg.decodeConfig=t,Cg.codec)return Promise.resolve();const e=Dxe({locateFile:r=>r.endsWith(".wasm")?bxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Cg.codec=i,Cg.decoder=new i.J2KDecoder,r()},n)})}async function Lb(t,e){await Ixe();const r=Cg.decoder,n=r.getEncodedBuffer(t.length);n.set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer();new Uint8Array(o.length).set(o);const s=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,c=r.getNumDecompositions(),l=r.getNumLayers(),f=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],u=r.getIsReversible(),d=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,h=`${r.getTileSize().width} x ${r.getTileSize().height}`,g=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,p=r.getColorSpace(),v=`${o.length.toLocaleString()} bytes`,y=`${(o.length/n.length).toFixed(2)}:1`,m={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:i.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},w=Oxe(i,o),x={imageOffset:s,numDecompositions:c,numLayers:l,progessionOrder:f,reversible:u,blockDimensions:d,tileSize:h,tileOffset:g,colorTransform:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:x,...x,...m}}function Oxe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var cG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(o){o=o||{};var o=typeof o<"u"?o:{},a,s;o.ready=new Promise(function($,H){a=$,s=H});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h($){return o.locateFile?o.locateFile($,d):d+$}var g,p,v;if(u){var y=Js,m=Js;f?d=m.dirname(d)+"/":d=__dirname+"/",g=($,H)=>($=ae($)?new URL($):m.normalize($),y.readFileSync($,H?void 0:"utf8")),v=$=>{var H=g($,!0);return H.buffer||(H=new Uint8Array(H)),H},p=($,H,R)=>{$=ae($)?new URL($):m.normalize($),y.readFile($,function(U,q){U?R(U):H(q.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function($){if(!($ instanceof oe))throw $}),process.on("unhandledRejection",function($){throw $}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=$=>{var H=new XMLHttpRequest;return H.open("GET",$,!1),H.send(null),H.responseText},f&&(v=$=>{var H=new XMLHttpRequest;return H.open("GET",$,!1),H.responseType="arraybuffer",H.send(null),new Uint8Array(H.response)}),p=($,H,R)=>{var U=new XMLHttpRequest;U.open("GET",$,!0),U.responseType="arraybuffer",U.onload=()=>{if(U.status==200||U.status==0&&U.response){H(U.response);return}R()},U.onerror=R,U.send(null)});var w=o.print||console.log.bind(console),x=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var C;o.wasmBinary&&(C=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Ne("no native wasm support detected");var S,_=!1;function T($,H){$||Ne(H)}var E=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function D($,H,R){for(var U=H+R,q=H;$[q]&&!(q>=U);)++q;if(q-H>16&&$.buffer&&E)return E.decode($.subarray(H,q));for(var le="";H>10,56320|be&1023)}}return le}function b($,H){return $?D(G,$,H):""}function I($,H,R,U){if(!(U>0))return 0;for(var q=R,le=R+U-1,he=0;he<$.length;++he){var ve=$.charCodeAt(he);if(ve>=55296&&ve<=57343){var Te=$.charCodeAt(++he);ve=65536+((ve&1023)<<10)|Te&1023}if(ve<=127){if(R>=le)break;H[R++]=ve}else if(ve<=2047){if(R+1>=le)break;H[R++]=192|ve>>6,H[R++]=128|ve&63}else if(ve<=65535){if(R+2>=le)break;H[R++]=224|ve>>12,H[R++]=128|ve>>6&63,H[R++]=128|ve&63}else{if(R+3>=le)break;H[R++]=240|ve>>18,H[R++]=128|ve>>12&63,H[R++]=128|ve>>6&63,H[R++]=128|ve&63}}return H[R]=0,R-q}function P($,H,R){return I($,G,H,R)}function M($){for(var H=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U<=127?H++:U<=2047?H+=2:U>=55296&&U<=57343?(H+=4,++R):H+=3}return H}var L,V,G,A,k,F,j,Y,re;function ue($){L=$,o.HEAP8=V=new Int8Array($),o.HEAP16=A=new Int16Array($),o.HEAP32=F=new Int32Array($),o.HEAPU8=G=new Uint8Array($),o.HEAPU16=k=new Uint16Array($),o.HEAPU32=j=new Uint32Array($),o.HEAPF32=Y=new Float32Array($),o.HEAPF64=re=new Float64Array($)}o.INITIAL_MEMORY;var ce,pe=[],Ee=[],Oe=[];function Se(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)z(o.preRun.shift());ht(pe)}function B(){ht(Ee)}function O(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)K(o.postRun.shift());ht(Oe)}function z($){pe.unshift($)}function W($){Ee.unshift($)}function K($){Oe.unshift($)}var Z=0,ee=null;function xe($){Z++,o.monitorRunDependencies&&o.monitorRunDependencies(Z)}function De($){if(Z--,o.monitorRunDependencies&&o.monitorRunDependencies(Z),Z==0&&ee){var H=ee;ee=null,H()}}function Ne($){o.onAbort&&o.onAbort($),$="Aborted("+$+")",x($),_=!0,$+=". Build with -sASSERTIONS for more info.";var H=new WebAssembly.RuntimeError($);throw s(H),H}var ze="data:application/octet-stream;base64,";function ie($){return $.startsWith(ze)}function ae($){return $.startsWith("file://")}var we;we="openjphjs.wasm",ie(we)||(we=h(we));function se($){try{if($==we&&C)return new Uint8Array(C);if(v)return v($);throw"both async and sync fetching of the wasm failed"}catch(H){Ne(H)}}function ge(){if(!C&&(l||f)){if(typeof fetch=="function"&&!ae(we))return fetch(we,{credentials:"same-origin"}).then(function($){if(!$.ok)throw"failed to load wasm binary file at '"+we+"'";return $.arrayBuffer()}).catch(function(){return se(we)});if(p)return new Promise(function($,H){p(we,function(R){$(new Uint8Array(R))},H)})}return Promise.resolve().then(function(){return se(we)})}function Fe(){var $={env:Q,wasi_snapshot_preview1:Q};function H(he,ve){var Te=he.exports;o.asm=Te,S=o.asm.memory,ue(S.buffer),ce=o.asm.__indirect_function_table,W(o.asm.__wasm_call_ctors),De()}xe();function R(he){H(he.instance)}function U(he){return ge().then(function(ve){return WebAssembly.instantiate(ve,$)}).then(function(ve){return ve}).then(he,function(ve){x("failed to asynchronously prepare wasm: "+ve),Ne(ve)})}function q(){return!C&&typeof WebAssembly.instantiateStreaming=="function"&&!ie(we)&&!ae(we)&&!u&&typeof fetch=="function"?fetch(we,{credentials:"same-origin"}).then(function(he){var ve=WebAssembly.instantiateStreaming(he,$);return ve.then(R,function(Te){return x("wasm streaming compile failed: "+Te),x("falling back to ArrayBuffer instantiation"),U(R)})}):U(R)}if(o.instantiateWasm)try{var le=o.instantiateWasm($,H);return le}catch(he){x("Module.instantiateWasm callback failed with error: "+he),s(he)}return q().catch(s),{}}function oe($){this.name="ExitStatus",this.message="Program terminated with exit("+$+")",this.status=$}function ht($){for(;$.length>0;)$.shift()(o)}function wt($,H,R,U){Ne("Assertion failed: "+b($)+", at: "+[H?b(H):"unknown filename",R,U?b(U):"unknown function"])}var gt=[];function Ie($){$.add_ref()}function $e($){var H=new Ft($);return H.get_caught()||H.set_caught(!0),H.set_rethrown(!1),gt.push(H),Ie(H),H.get_exception_ptr()}var tt=0,nt=[];function dt($){var H=nt[$];return H||($>=nt.length&&(nt.length=$+1),nt[$]=H=ce.get($)),H}function Lt($){if($.release_ref()&&!$.get_rethrown()){var H=$.get_destructor();H&&dt(H)($.excPtr),Ae($.excPtr)}}function xt(){_setThrew(0);var $=gt.pop();Lt($),tt=0}function Ft($){this.excPtr=$,this.ptr=$-24,this.set_type=function(H){j[this.ptr+4>>2]=H},this.get_type=function(){return j[this.ptr+4>>2]},this.set_destructor=function(H){j[this.ptr+8>>2]=H},this.get_destructor=function(){return j[this.ptr+8>>2]},this.set_refcount=function(H){F[this.ptr>>2]=H},this.set_caught=function(H){H=H?1:0,V[this.ptr+12>>0]=H},this.get_caught=function(){return V[this.ptr+12>>0]!=0},this.set_rethrown=function(H){H=H?1:0,V[this.ptr+13>>0]=H},this.get_rethrown=function(){return V[this.ptr+13>>0]!=0},this.init=function(H,R){this.set_adjusted_ptr(0),this.set_type(H),this.set_destructor(R),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var H=F[this.ptr>>2];F[this.ptr>>2]=H+1},this.release_ref=function(){var H=F[this.ptr>>2];return F[this.ptr>>2]=H-1,H===1},this.set_adjusted_ptr=function(H){j[this.ptr+16>>2]=H},this.get_adjusted_ptr=function(){return j[this.ptr+16>>2]},this.get_exception_ptr=function(){var H=kt(this.get_type());if(H)return j[this.excPtr>>2];var R=this.get_adjusted_ptr();return R!==0?R:this.excPtr}}function jt($){throw tt||(tt=$),$}function Pn(){var $=tt;if(!$)return Ze(0),0;var H=new Ft($);H.set_adjusted_ptr($);var R=H.get_type();if(!R)return Ze(0),$;for(var U=0;U>2])}var Be={},ft={},Ut={},Sn=48,Qn=57;function Pt($){if($===void 0)return"_unknown";$=$.replace(/[^a-zA-Z0-9_]/g,"$");var H=$.charCodeAt(0);return H>=Sn&&H<=Qn?"_"+$:$}function _n($,H){return $=Pt($),new Function("body","return function "+$+`() { +`,new Function("requireRegisteredType","Module","valueToHandle","getMemory",ze)(vl,o,Wi.toHandle,Me)}var gc={};function Ju(J,X,fe,Me){J=Wi.toValue(J);var ze=gc[X];return ze||(ze=yl(X),gc[X]=ze),ze(J,fe,Me)}function wl(J,X){J=vl(J,"_emval_take_value");var fe=J.readValueFromPointer(X);return Wi.toHandle(fe)}function Zu(){$e("")}function xl(){return 2147483648}function Qu(){return xl()}function ef(J,X,fe){A.copyWithin(J,X,X+fe)}function tf(J){try{return _.grow(J-V.byteLength+65535>>>16),ce(_.buffer),1}catch{}}function nf(J){var X=A.length;J=J>>>0;var fe=xl();if(J>fe)return!1;let Me=($,H)=>$+(H-$%H)%H;for(var ze=1;ze<=4;ze*=2){var ct=X*(1+.2/ze);ct=Math.min(ct,J+100663296);var et=Math.min(fe,Me(Math.max(J,ct),65536)),Ye=tf(et);if(Ye)return!0}return!1}var pc={};function mc(){return l||"./this.program"}function oa(){if(!oa.strings){var J=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",X={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:J,_:mc()};for(var fe in pc)pc[fe]===void 0?delete X[fe]:X[fe]=pc[fe];var Me=[];for(var fe in X)Me.push(fe+"="+X[fe]);oa.strings=Me}return oa.strings}function Ia(J,X,fe){for(var Me=0;Me>0]=J.charCodeAt(Me);G[X>>0]=0}function Eo(J,X){var fe=0;return oa().forEach(function(Me,ze){var ct=X+fe;Y[J+ze*4>>2]=ct,Ia(Me,ct),fe+=Me.length+1}),0}function Cl(J,X){var fe=oa();Y[J>>2]=fe.length;var Me=0;return fe.forEach(function(ze){Me+=ze.length+1}),Y[X>>2]=Me,0}function Sl(J){return 52}function vc(J,X,fe,Me,ze){return 70}var _l=[null,[],[]];function Is(J,X){var fe=_l[J];X===0||X===10?((J===1?x:C)(b(fe,0)),fe.length=0):fe.push(X)}function Tl(J,X,fe,Me){for(var ze=0,ct=0;ct>2],Ye=Y[X+4>>2];X+=8;for(var $=0;$>2]=ze,0}function Q(J){var X=o["_"+J];return X}function te(J,X){G.set(J,X)}function me(J,X,fe,Me,ze){var ct={string:he=>{var ve=0;if(he!=null&&he!==0){var Te=(he.length<<2)+1;ve=vt(Te),M(he,ve,Te)}return ve},array:he=>{var ve=vt(he.length);return te(he,ve),ve}};function et(he){return X==="string"?I(he):X==="boolean"?!!he:he}var Ye=Q(J),$=[],H=0;if(Me)for(var R=0;R0||(B(),ee>0))return;function X(){Wt||(Wt=!0,o.calledRun=!0,!T&&(O(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),z()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),X()},1)):X()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Kt(),i.ready}})();t.exports=r})(sG);var Exe=sG.exports;const Dxe=ac(Exe),bxe=new URL("/static/dv3d/openjpegwasm_decode.wasm",import.meta.url),Cg={codec:void 0,decoder:void 0,decodeConfig:{}};function Ixe(t){if(Cg.decodeConfig=t,Cg.codec)return Promise.resolve();const e=Dxe({locateFile:r=>r.endsWith(".wasm")?bxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Cg.codec=i,Cg.decoder=new i.J2KDecoder,r()},n)})}async function Lb(t,e){await Ixe();const r=Cg.decoder,n=r.getEncodedBuffer(t.length);n.set(t),r.decode();const i=r.getFrameInfo(),o=r.getDecodedBuffer();new Uint8Array(o.length).set(o);const s=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,c=r.getNumDecompositions(),l=r.getNumLayers(),f=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],u=r.getIsReversible(),d=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,h=`${r.getTileSize().width} x ${r.getTileSize().height}`,g=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,p=r.getColorSpace(),v=`${o.length.toLocaleString()} bytes`,y=`${(o.length/n.length).toFixed(2)}:1`,m={columns:i.width,rows:i.height,bitsPerPixel:i.bitsPerSample,signed:i.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:i.componentCount},w=Oxe(i,o),x={imageOffset:s,numDecompositions:c,numLayers:l,progessionOrder:f,reversible:u,blockDimensions:d,tileSize:h,tileOffset:g,colorTransform:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:x,...x,...m}}function Oxe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var cG={exports:{}};(function(t,e){var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(o){o=o||{};var o=typeof o<"u"?o:{},a,s;o.ready=new Promise(function($,H){a=$,s=H});var c=Object.assign({},o),l=typeof window=="object",f=typeof importScripts=="function",u=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",d="";function h($){return o.locateFile?o.locateFile($,d):d+$}var g,p,v;if(u){var y=Js,m=Js;f?d=m.dirname(d)+"/":d=__dirname+"/",g=($,H)=>($=ae($)?new URL($):m.normalize($),y.readFileSync($,H?void 0:"utf8")),v=$=>{var H=g($,!0);return H.buffer||(H=new Uint8Array(H)),H},p=($,H,R)=>{$=ae($)?new URL($):m.normalize($),y.readFile($,function(U,q){U?R(U):H(q.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function($){if(!($ instanceof oe))throw $}),process.on("unhandledRejection",function($){throw $}),o.inspect=function(){return"[Emscripten Module object]"}}else(l||f)&&(f?d=self.location.href:typeof document<"u"&&document.currentScript&&(d=document.currentScript.src),n&&(d=n),d.indexOf("blob:")!==0?d=d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):d="",g=$=>{var H=new XMLHttpRequest;return H.open("GET",$,!1),H.send(null),H.responseText},f&&(v=$=>{var H=new XMLHttpRequest;return H.open("GET",$,!1),H.responseType="arraybuffer",H.send(null),new Uint8Array(H.response)}),p=($,H,R)=>{var U=new XMLHttpRequest;U.open("GET",$,!0),U.responseType="arraybuffer",U.onload=()=>{if(U.status==200||U.status==0&&U.response){H(U.response);return}R()},U.onerror=R,U.send(null)});var w=o.print||console.log.bind(console),x=o.printErr||console.warn.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit;var C;o.wasmBinary&&(C=o.wasmBinary),o.noExitRuntime,typeof WebAssembly!="object"&&Ne("no native wasm support detected");var S,_=!1;function T($,H){$||Ne(H)}var E=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function D($,H,R){for(var U=H+R,q=H;$[q]&&!(q>=U);)++q;if(q-H>16&&$.buffer&&E)return E.decode($.subarray(H,q));for(var le="";H>10,56320|be&1023)}}return le}function b($,H){return $?D(G,$,H):""}function I($,H,R,U){if(!(U>0))return 0;for(var q=R,le=R+U-1,he=0;he<$.length;++he){var ve=$.charCodeAt(he);if(ve>=55296&&ve<=57343){var Te=$.charCodeAt(++he);ve=65536+((ve&1023)<<10)|Te&1023}if(ve<=127){if(R>=le)break;H[R++]=ve}else if(ve<=2047){if(R+1>=le)break;H[R++]=192|ve>>6,H[R++]=128|ve&63}else if(ve<=65535){if(R+2>=le)break;H[R++]=224|ve>>12,H[R++]=128|ve>>6&63,H[R++]=128|ve&63}else{if(R+3>=le)break;H[R++]=240|ve>>18,H[R++]=128|ve>>12&63,H[R++]=128|ve>>6&63,H[R++]=128|ve&63}}return H[R]=0,R-q}function P($,H,R){return I($,G,H,R)}function M($){for(var H=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U<=127?H++:U<=2047?H+=2:U>=55296&&U<=57343?(H+=4,++R):H+=3}return H}var L,V,G,A,k,F,j,Y,re;function ue($){L=$,o.HEAP8=V=new Int8Array($),o.HEAP16=A=new Int16Array($),o.HEAP32=F=new Int32Array($),o.HEAPU8=G=new Uint8Array($),o.HEAPU16=k=new Uint16Array($),o.HEAPU32=j=new Uint32Array($),o.HEAPF32=Y=new Float32Array($),o.HEAPF64=re=new Float64Array($)}o.INITIAL_MEMORY;var ce,pe=[],Ee=[],Oe=[];function _e(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)z(o.preRun.shift());ht(pe)}function B(){ht(Ee)}function O(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)K(o.postRun.shift());ht(Oe)}function z($){pe.unshift($)}function W($){Ee.unshift($)}function K($){Oe.unshift($)}var Z=0,ee=null;function xe($){Z++,o.monitorRunDependencies&&o.monitorRunDependencies(Z)}function De($){if(Z--,o.monitorRunDependencies&&o.monitorRunDependencies(Z),Z==0&&ee){var H=ee;ee=null,H()}}function Ne($){o.onAbort&&o.onAbort($),$="Aborted("+$+")",x($),_=!0,$+=". Build with -sASSERTIONS for more info.";var H=new WebAssembly.RuntimeError($);throw s(H),H}var $e="data:application/octet-stream;base64,";function ie($){return $.startsWith($e)}function ae($){return $.startsWith("file://")}var ye;ye="openjphjs.wasm",ie(ye)||(ye=h(ye));function se($){try{if($==ye&&C)return new Uint8Array(C);if(v)return v($);throw"both async and sync fetching of the wasm failed"}catch(H){Ne(H)}}function ge(){if(!C&&(l||f)){if(typeof fetch=="function"&&!ae(ye))return fetch(ye,{credentials:"same-origin"}).then(function($){if(!$.ok)throw"failed to load wasm binary file at '"+ye+"'";return $.arrayBuffer()}).catch(function(){return se(ye)});if(p)return new Promise(function($,H){p(ye,function(R){$(new Uint8Array(R))},H)})}return Promise.resolve().then(function(){return se(ye)})}function Fe(){var $={env:Q,wasi_snapshot_preview1:Q};function H(he,ve){var Te=he.exports;o.asm=Te,S=o.asm.memory,ue(S.buffer),ce=o.asm.__indirect_function_table,W(o.asm.__wasm_call_ctors),De()}xe();function R(he){H(he.instance)}function U(he){return ge().then(function(ve){return WebAssembly.instantiate(ve,$)}).then(function(ve){return ve}).then(he,function(ve){x("failed to asynchronously prepare wasm: "+ve),Ne(ve)})}function q(){return!C&&typeof WebAssembly.instantiateStreaming=="function"&&!ie(ye)&&!ae(ye)&&!u&&typeof fetch=="function"?fetch(ye,{credentials:"same-origin"}).then(function(he){var ve=WebAssembly.instantiateStreaming(he,$);return ve.then(R,function(Te){return x("wasm streaming compile failed: "+Te),x("falling back to ArrayBuffer instantiation"),U(R)})}):U(R)}if(o.instantiateWasm)try{var le=o.instantiateWasm($,H);return le}catch(he){x("Module.instantiateWasm callback failed with error: "+he),s(he)}return q().catch(s),{}}function oe($){this.name="ExitStatus",this.message="Program terminated with exit("+$+")",this.status=$}function ht($){for(;$.length>0;)$.shift()(o)}function wt($,H,R,U){Ne("Assertion failed: "+b($)+", at: "+[H?b(H):"unknown filename",R,U?b(U):"unknown function"])}var gt=[];function Ie($){$.add_ref()}function je($){var H=new Ft($);return H.get_caught()||H.set_caught(!0),H.set_rethrown(!1),gt.push(H),Ie(H),H.get_exception_ptr()}var nt=0,rt=[];function dt($){var H=rt[$];return H||($>=rt.length&&(rt.length=$+1),rt[$]=H=ce.get($)),H}function Lt($){if($.release_ref()&&!$.get_rethrown()){var H=$.get_destructor();H&&dt(H)($.excPtr),Ae($.excPtr)}}function xt(){_setThrew(0);var $=gt.pop();Lt($),nt=0}function Ft($){this.excPtr=$,this.ptr=$-24,this.set_type=function(H){j[this.ptr+4>>2]=H},this.get_type=function(){return j[this.ptr+4>>2]},this.set_destructor=function(H){j[this.ptr+8>>2]=H},this.get_destructor=function(){return j[this.ptr+8>>2]},this.set_refcount=function(H){F[this.ptr>>2]=H},this.set_caught=function(H){H=H?1:0,V[this.ptr+12>>0]=H},this.get_caught=function(){return V[this.ptr+12>>0]!=0},this.set_rethrown=function(H){H=H?1:0,V[this.ptr+13>>0]=H},this.get_rethrown=function(){return V[this.ptr+13>>0]!=0},this.init=function(H,R){this.set_adjusted_ptr(0),this.set_type(H),this.set_destructor(R),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var H=F[this.ptr>>2];F[this.ptr>>2]=H+1},this.release_ref=function(){var H=F[this.ptr>>2];return F[this.ptr>>2]=H-1,H===1},this.set_adjusted_ptr=function(H){j[this.ptr+16>>2]=H},this.get_adjusted_ptr=function(){return j[this.ptr+16>>2]},this.get_exception_ptr=function(){var H=kt(this.get_type());if(H)return j[this.excPtr>>2];var R=this.get_adjusted_ptr();return R!==0?R:this.excPtr}}function jt($){throw nt||(nt=$),$}function Pn(){var $=nt;if(!$)return Ze(0),0;var H=new Ft($);H.set_adjusted_ptr($);var R=H.get_type();if(!R)return Ze(0),$;for(var U=0;U>2])}var Ue={},ft={},Ut={},Sn=48,Qn=57;function Pt($){if($===void 0)return"_unknown";$=$.replace(/[^a-zA-Z0-9_]/g,"$");var H=$.charCodeAt(0);return H>=Sn&&H<=Qn?"_"+$:$}function _n($,H){return $=Pt($),new Function("body","return function "+$+`() { "use strict"; return body.apply(this, arguments); }; `)(H)}function sn($,H){var R=_n(H,function(U){this.name=H,this.message=U;var q=new Error(U).stack;q!==void 0&&(this.stack=this.toString()+` -`+q.replace(/^Error(:[^\n]*)?\n/,""))});return R.prototype=Object.create($.prototype),R.prototype.constructor=R,R.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},R}var rn=void 0;function pi($){throw new rn($)}function Vi($,H,R){$.forEach(function(ve){Ut[ve]=H});function U(ve){var Te=R(ve);Te.length!==$.length&&pi("Mismatched type converter count");for(var be=0;be<$.length;++be)Qr($[be],Te[be])}var q=new Array(H.length),le=[],he=0;H.forEach((ve,Te)=>{ft.hasOwnProperty(ve)?q[Te]=ft[ve]:(le.push(ve),Be.hasOwnProperty(ve)||(Be[ve]=[]),Be[ve].push(()=>{q[Te]=ft[ve],++he,he===le.length&&U(q)}))}),le.length===0&&U(q)}function Ha($){var H=bn[$];delete bn[$];var R=H.rawConstructor,U=H.rawDestructor,q=H.fields,le=q.map(he=>he.getterReturnType).concat(q.map(he=>he.setterArgumentType));Vi([$],le,he=>{var ve={};return q.forEach((Te,be)=>{var ke=Te.fieldName,Je=he[be],pt=Te.getter,Mt=Te.getterContext,Tt=he[be+q.length],dn=Te.setter,ln=Te.setterContext;ve[ke]={read:Xn=>Je.fromWireType(pt(Mt,Xn)),write:(Xn,li)=>{var yi=[];dn(ln,Xn,Tt.toWireType(yi,li)),Xi(yi)}}}),[{name:H.name,fromWireType:function(Te){var be={};for(var ke in ve)be[ke]=ve[ke].read(Te);return U(Te),be},toWireType:function(Te,be){for(var ke in ve)if(!(ke in be))throw new TypeError('Missing field: "'+ke+'"');var Je=R();for(ke in ve)ve[ke].write(Je,be[ke]);return Te!==null&&Te.push(U,Je),Je},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:U}]})}function Ea($,H,R,U,q){}function To($){switch($){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+$)}}function ra(){for(var $=new Array(256),H=0;H<256;++H)$[H]=String.fromCharCode(H);Uo=$}var Uo=void 0;function fr($){for(var H="",R=$;G[R];)H+=Uo[G[R++]];return H}var oo=void 0;function yn($){throw new oo($)}function Qr($,H,R={}){if(!("argPackAdvance"in H))throw new TypeError("registerType registeredInstance requires argPackAdvance");var U=H.name;if($||yn('type "'+U+'" must have a positive integer typeid pointer'),ft.hasOwnProperty($)){if(R.ignoreDuplicateRegistrations)return;yn("Cannot register type '"+U+"' twice")}if(ft[$]=H,delete Ut[$],Be.hasOwnProperty($)){var q=Be[$];delete Be[$],q.forEach(le=>le())}}function Da($,H,R,U,q){var le=To(R);H=fr(H),Qr($,{name:H,fromWireType:function(he){return!!he},toWireType:function(he,ve){return ve?U:q},argPackAdvance:8,readValueFromPointer:function(he){var ve;if(R===1)ve=V;else if(R===2)ve=A;else if(R===4)ve=F;else throw new TypeError("Unknown boolean type size: "+H);return this.fromWireType(ve[he>>le])},destructorFunction:null})}function Fi($){if(!(this instanceof or)||!($ instanceof or))return!1;for(var H=this.$$.ptrType.registeredClass,R=this.$$.ptr,U=$.$$.ptrType.registeredClass,q=$.$$.ptr;H.baseClass;)R=H.upcast(R),H=H.baseClass;for(;U.baseClass;)q=U.upcast(q),U=U.baseClass;return H===U&&R===q}function ao($){return{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType}}function Ui($){function H(R){return R.$$.ptrType.registeredClass.name}yn(H($)+" instance already deleted")}var mi=!1;function Ka($){}function Bo($){$.smartPtr?$.smartPtrType.rawDestructor($.smartPtr):$.ptrType.registeredClass.rawDestructor($.ptr)}function Bi($){$.count.value-=1;var H=$.count.value===0;H&&Bo($)}function qa($,H,R){if(H===R)return $;if(R.baseClass===void 0)return null;var U=qa($,H,R.baseClass);return U===null?null:R.downcast(U)}var Gi={};function ia(){return Object.keys(st).length}function de(){var $=[];for(var H in st)st.hasOwnProperty(H)&&$.push(st[H]);return $}var Ue=[];function _e(){for(;Ue.length;){var $=Ue.pop();$.$$.deleteScheduled=!1,$.delete()}}var ye=void 0;function je($){ye=$,Ue.length&&ye&&ye(_e)}function ot(){o.getInheritedInstanceCount=ia,o.getLiveInheritedInstances=de,o.flushPendingDeletes=_e,o.setDelayFunction=je}var st={};function ut($,H){for(H===void 0&&yn("ptr should not be undefined");$.baseClass;)H=$.upcast(H),$=$.baseClass;return H}function rt($,H){return H=ut($,H),st[H]}function Ct($,H){(!H.ptrType||!H.ptr)&&pi("makeClassHandle requires ptr and ptrType");var R=!!H.smartPtrType,U=!!H.smartPtr;return R!==U&&pi("Both smartPtrType and smartPtr must be specified"),H.count={value:1},on(Object.create($,{$$:{value:H}}))}function Qt($){var H=this.getPointee($);if(!H)return this.destructor($),null;var R=rt(this.registeredClass,H);if(R!==void 0){if(R.$$.count.value===0)return R.$$.ptr=H,R.$$.smartPtr=$,R.clone();var U=R.clone();return this.destructor($),U}function q(){return this.isSmartPointer?Ct(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:H,smartPtrType:this,smartPtr:$}):Ct(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var le=this.registeredClass.getActualType(H),he=Gi[le];if(!he)return q.call(this);var ve;this.isConst?ve=he.constPointerType:ve=he.pointerType;var Te=qa(H,this.registeredClass,ve.registeredClass);return Te===null?q.call(this):this.isSmartPointer?Ct(ve.registeredClass.instancePrototype,{ptrType:ve,ptr:Te,smartPtrType:this,smartPtr:$}):Ct(ve.registeredClass.instancePrototype,{ptrType:ve,ptr:Te})}function on($){return typeof FinalizationRegistry>"u"?(on=H=>H,$):(mi=new FinalizationRegistry(H=>{Bi(H.$$)}),on=H=>{var R=H.$$,U=!!R.smartPtr;if(U){var q={$$:R};mi.register(H,q,H)}return H},Ka=H=>mi.unregister(H),on($))}function cn(){if(this.$$.ptr||Ui(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $=on(Object.create(Object.getPrototypeOf(this),{$$:{value:ao(this.$$)}}));return $.$$.count.value+=1,$.$$.deleteScheduled=!1,$}function Gt(){this.$$.ptr||Ui(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&yn("Object already scheduled for deletion"),Ka(this),Bi(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function xn(){return!this.$$.ptr}function er(){return this.$$.ptr||Ui(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&yn("Object already scheduled for deletion"),Ue.push(this),Ue.length===1&&ye&&ye(_e),this.$$.deleteScheduled=!0,this}function nr(){or.prototype.isAliasOf=Fi,or.prototype.clone=cn,or.prototype.delete=Gt,or.prototype.isDeleted=xn,or.prototype.deleteLater=er}function or(){}function qn($,H,R){if($[H].overloadTable===void 0){var U=$[H];$[H]=function(){return $[H].overloadTable.hasOwnProperty(arguments.length)||yn("Function '"+R+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+$[H].overloadTable+")!"),$[H].overloadTable[arguments.length].apply(this,arguments)},$[H].overloadTable=[],$[H].overloadTable[U.argCount]=U}}function At($,H,R){o.hasOwnProperty($)?((R===void 0||o[$].overloadTable!==void 0&&o[$].overloadTable[R]!==void 0)&&yn("Cannot register public name '"+$+"' twice"),qn(o,$,$),o.hasOwnProperty(R)&&yn("Cannot register multiple overloads of a function with the same number of arguments ("+R+")!"),o[$].overloadTable[R]=H):(o[$]=H,R!==void 0&&(o[$].numArguments=R))}function Bn($,H,R,U,q,le,he,ve){this.name=$,this.constructor=H,this.instancePrototype=R,this.rawDestructor=U,this.baseClass=q,this.getActualType=le,this.upcast=he,this.downcast=ve,this.pureVirtualFunctions=[]}function dr($,H,R){for(;H!==R;)H.upcast||yn("Expected null or instance of "+R.name+", got an instance of "+H.name),$=H.upcast($),H=H.baseClass;return $}function si($,H){if(H===null)return this.isReference&&yn("null is not a valid "+this.name),0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name);var R=H.$$.ptrType.registeredClass,U=dr(H.$$.ptr,R,this.registeredClass);return U}function jn($,H){var R;if(H===null)return this.isReference&&yn("null is not a valid "+this.name),this.isSmartPointer?(R=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,R),R):0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&H.$$.ptrType.isConst&&yn("Cannot convert argument of type "+(H.$$.smartPtrType?H.$$.smartPtrType.name:H.$$.ptrType.name)+" to parameter type "+this.name);var U=H.$$.ptrType.registeredClass;if(R=dr(H.$$.ptr,U,this.registeredClass),this.isSmartPointer)switch(H.$$.smartPtr===void 0&&yn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:H.$$.smartPtrType===this?R=H.$$.smartPtr:yn("Cannot convert argument of type "+(H.$$.smartPtrType?H.$$.smartPtrType.name:H.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:R=H.$$.smartPtr;break;case 2:if(H.$$.smartPtrType===this)R=H.$$.smartPtr;else{var q=H.clone();R=this.rawShare(R,Za.toHandle(function(){q.delete()})),$!==null&&$.push(this.rawDestructor,R)}break;default:yn("Unsupporting sharing policy")}return R}function wr($,H){if(H===null)return this.isReference&&yn("null is not a valid "+this.name),0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name),H.$$.ptrType.isConst&&yn("Cannot convert argument of type "+H.$$.ptrType.name+" to parameter type "+this.name);var R=H.$$.ptrType.registeredClass,U=dr(H.$$.ptr,R,this.registeredClass);return U}function ei($){return this.rawGetPointee&&($=this.rawGetPointee($)),$}function xr($){this.rawDestructor&&this.rawDestructor($)}function uc($){$!==null&&$.delete()}function ba(){Yi.prototype.getPointee=ei,Yi.prototype.destructor=xr,Yi.prototype.argPackAdvance=8,Yi.prototype.readValueFromPointer=Mr,Yi.prototype.deleteObject=uc,Yi.prototype.fromWireType=Qt}function Yi($,H,R,U,q,le,he,ve,Te,be,ke){this.name=$,this.registeredClass=H,this.isReference=R,this.isConst=U,this.isSmartPointer=q,this.pointeeType=le,this.sharingPolicy=he,this.rawGetPointee=ve,this.rawConstructor=Te,this.rawShare=be,this.rawDestructor=ke,!q&&H.baseClass===void 0?U?(this.toWireType=si,this.destructorFunction=null):(this.toWireType=wr,this.destructorFunction=null):this.toWireType=jn}function Xa($,H,R){o.hasOwnProperty($)||pi("Replacing nonexistant public symbol"),o[$].overloadTable!==void 0&&R!==void 0?o[$].overloadTable[R]=H:(o[$]=H,o[$].argCount=R)}function cl($,H,R){var U=o["dynCall_"+$];return R&&R.length?U.apply(null,[H].concat(R)):U.call(null,H)}function ll($,H,R){if($.includes("j"))return cl($,H,R);var U=dt(H).apply(null,R);return U}function bs($,H){var R=[];return function(){return R.length=0,Object.assign(R,arguments),ll($,H,R)}}function gr($,H){$=fr($);function R(){return $.includes("j")?bs($,H):dt(H)}var U=R();return typeof U!="function"&&yn("unknown function pointer with signature "+$+": "+H),U}var Ya=void 0;function vi($){var H=He($),R=fr(H);return me(H),R}function ci($,H){var R=[],U={};function q(le){if(!U[le]&&!ft[le]){if(Ut[le]){Ut[le].forEach(q);return}R.push(le),U[le]=!0}}throw H.forEach(q),new Ya($+": "+R.map(vi).join([", "]))}function ul($,H,R,U,q,le,he,ve,Te,be,ke,Je,pt){ke=fr(ke),le=gr(q,le),ve&&(ve=gr(he,ve)),be&&(be=gr(Te,be)),pt=gr(Je,pt);var Mt=Pt(ke);At(Mt,function(){ci("Cannot construct "+ke+" due to unbound types",[U])}),Vi([$,H,R],U?[U]:[],function(Tt){Tt=Tt[0];var dn,ln;U?(dn=Tt.registeredClass,ln=dn.instancePrototype):ln=or.prototype;var Xn=_n(Mt,function(){if(Object.getPrototypeOf(this)!==li)throw new oo("Use 'new' to construct "+ke);if(yi.constructor_body===void 0)throw new oo(ke+" has no accessible constructor");var Ih=yi.constructor_body[arguments.length];if(Ih===void 0)throw new oo("Tried to invoke ctor of "+ke+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(yi.constructor_body).toString()+") parameters instead!");return Ih.apply(this,arguments)}),li=Object.create(ln,{constructor:{value:Xn}});Xn.prototype=li;var yi=new Bn(ke,Xn,li,pt,dn,le,ve,be),rf=new Yi(ke,yi,!0,!1,!1),Oa=new Yi(ke+"*",yi,!1,!1,!1),U1=new Yi(ke+" const*",yi,!1,!0,!1);return Gi[$]={pointerType:Oa,constPointerType:U1},Xa(Mt,Xn),[rf,Oa,U1]})}function so($,H){for(var R=[],U=0;U<$;U++)R.push(j[H+U*4>>2]);return R}function Uu($,H){if(!($ instanceof Function))throw new TypeError("new_ called with constructor type "+typeof $+" which is not a function");var R=_n($.name||"unknownFunctionName",function(){});R.prototype=$.prototype;var U=new R,q=$.apply(U,H);return q instanceof Object?q:U}function Wi($,H,R,U,q){var le=H.length;le<2&&yn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var he=H[1]!==null&&R!==null,ve=!1,Te=1;Te{ft.hasOwnProperty(ve)?q[Te]=ft[ve]:(le.push(ve),Ue.hasOwnProperty(ve)||(Ue[ve]=[]),Ue[ve].push(()=>{q[Te]=ft[ve],++he,he===le.length&&U(q)}))}),le.length===0&&U(q)}function Ha($){var H=bn[$];delete bn[$];var R=H.rawConstructor,U=H.rawDestructor,q=H.fields,le=q.map(he=>he.getterReturnType).concat(q.map(he=>he.setterArgumentType));Vi([$],le,he=>{var ve={};return q.forEach((Te,be)=>{var ke=Te.fieldName,Je=he[be],pt=Te.getter,Mt=Te.getterContext,Tt=he[be+q.length],dn=Te.setter,ln=Te.setterContext;ve[ke]={read:Xn=>Je.fromWireType(pt(Mt,Xn)),write:(Xn,li)=>{var yi=[];dn(ln,Xn,Tt.toWireType(yi,li)),Xi(yi)}}}),[{name:H.name,fromWireType:function(Te){var be={};for(var ke in ve)be[ke]=ve[ke].read(Te);return U(Te),be},toWireType:function(Te,be){for(var ke in ve)if(!(ke in be))throw new TypeError('Missing field: "'+ke+'"');var Je=R();for(ke in ve)ve[ke].write(Je,be[ke]);return Te!==null&&Te.push(U,Je),Je},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:U}]})}function Ea($,H,R,U,q){}function To($){switch($){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+$)}}function ra(){for(var $=new Array(256),H=0;H<256;++H)$[H]=String.fromCharCode(H);Uo=$}var Uo=void 0;function fr($){for(var H="",R=$;G[R];)H+=Uo[G[R++]];return H}var oo=void 0;function yn($){throw new oo($)}function Qr($,H,R={}){if(!("argPackAdvance"in H))throw new TypeError("registerType registeredInstance requires argPackAdvance");var U=H.name;if($||yn('type "'+U+'" must have a positive integer typeid pointer'),ft.hasOwnProperty($)){if(R.ignoreDuplicateRegistrations)return;yn("Cannot register type '"+U+"' twice")}if(ft[$]=H,delete Ut[$],Ue.hasOwnProperty($)){var q=Ue[$];delete Ue[$],q.forEach(le=>le())}}function Da($,H,R,U,q){var le=To(R);H=fr(H),Qr($,{name:H,fromWireType:function(he){return!!he},toWireType:function(he,ve){return ve?U:q},argPackAdvance:8,readValueFromPointer:function(he){var ve;if(R===1)ve=V;else if(R===2)ve=A;else if(R===4)ve=F;else throw new TypeError("Unknown boolean type size: "+H);return this.fromWireType(ve[he>>le])},destructorFunction:null})}function Fi($){if(!(this instanceof or)||!($ instanceof or))return!1;for(var H=this.$$.ptrType.registeredClass,R=this.$$.ptr,U=$.$$.ptrType.registeredClass,q=$.$$.ptr;H.baseClass;)R=H.upcast(R),H=H.baseClass;for(;U.baseClass;)q=U.upcast(q),U=U.baseClass;return H===U&&R===q}function ao($){return{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType}}function Ui($){function H(R){return R.$$.ptrType.registeredClass.name}yn(H($)+" instance already deleted")}var mi=!1;function Ka($){}function Bo($){$.smartPtr?$.smartPtrType.rawDestructor($.smartPtr):$.ptrType.registeredClass.rawDestructor($.ptr)}function Bi($){$.count.value-=1;var H=$.count.value===0;H&&Bo($)}function qa($,H,R){if(H===R)return $;if(R.baseClass===void 0)return null;var U=qa($,H,R.baseClass);return U===null?null:R.downcast(U)}var Gi={};function ia(){return Object.keys(st).length}function de(){var $=[];for(var H in st)st.hasOwnProperty(H)&&$.push(st[H]);return $}var We=[];function Se(){for(;We.length;){var $=We.pop();$.$$.deleteScheduled=!1,$.delete()}}var we=void 0;function Ge($){we=$,We.length&&we&&we(Se)}function tt(){o.getInheritedInstanceCount=ia,o.getLiveInheritedInstances=de,o.flushPendingDeletes=Se,o.setDelayFunction=Ge}var st={};function ut($,H){for(H===void 0&&yn("ptr should not be undefined");$.baseClass;)H=$.upcast(H),$=$.baseClass;return H}function it($,H){return H=ut($,H),st[H]}function Ct($,H){(!H.ptrType||!H.ptr)&&pi("makeClassHandle requires ptr and ptrType");var R=!!H.smartPtrType,U=!!H.smartPtr;return R!==U&&pi("Both smartPtrType and smartPtr must be specified"),H.count={value:1},on(Object.create($,{$$:{value:H}}))}function Qt($){var H=this.getPointee($);if(!H)return this.destructor($),null;var R=it(this.registeredClass,H);if(R!==void 0){if(R.$$.count.value===0)return R.$$.ptr=H,R.$$.smartPtr=$,R.clone();var U=R.clone();return this.destructor($),U}function q(){return this.isSmartPointer?Ct(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:H,smartPtrType:this,smartPtr:$}):Ct(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var le=this.registeredClass.getActualType(H),he=Gi[le];if(!he)return q.call(this);var ve;this.isConst?ve=he.constPointerType:ve=he.pointerType;var Te=qa(H,this.registeredClass,ve.registeredClass);return Te===null?q.call(this):this.isSmartPointer?Ct(ve.registeredClass.instancePrototype,{ptrType:ve,ptr:Te,smartPtrType:this,smartPtr:$}):Ct(ve.registeredClass.instancePrototype,{ptrType:ve,ptr:Te})}function on($){return typeof FinalizationRegistry>"u"?(on=H=>H,$):(mi=new FinalizationRegistry(H=>{Bi(H.$$)}),on=H=>{var R=H.$$,U=!!R.smartPtr;if(U){var q={$$:R};mi.register(H,q,H)}return H},Ka=H=>mi.unregister(H),on($))}function cn(){if(this.$$.ptr||Ui(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $=on(Object.create(Object.getPrototypeOf(this),{$$:{value:ao(this.$$)}}));return $.$$.count.value+=1,$.$$.deleteScheduled=!1,$}function Gt(){this.$$.ptr||Ui(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&yn("Object already scheduled for deletion"),Ka(this),Bi(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function xn(){return!this.$$.ptr}function er(){return this.$$.ptr||Ui(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&yn("Object already scheduled for deletion"),We.push(this),We.length===1&&we&&we(Se),this.$$.deleteScheduled=!0,this}function nr(){or.prototype.isAliasOf=Fi,or.prototype.clone=cn,or.prototype.delete=Gt,or.prototype.isDeleted=xn,or.prototype.deleteLater=er}function or(){}function qn($,H,R){if($[H].overloadTable===void 0){var U=$[H];$[H]=function(){return $[H].overloadTable.hasOwnProperty(arguments.length)||yn("Function '"+R+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+$[H].overloadTable+")!"),$[H].overloadTable[arguments.length].apply(this,arguments)},$[H].overloadTable=[],$[H].overloadTable[U.argCount]=U}}function At($,H,R){o.hasOwnProperty($)?((R===void 0||o[$].overloadTable!==void 0&&o[$].overloadTable[R]!==void 0)&&yn("Cannot register public name '"+$+"' twice"),qn(o,$,$),o.hasOwnProperty(R)&&yn("Cannot register multiple overloads of a function with the same number of arguments ("+R+")!"),o[$].overloadTable[R]=H):(o[$]=H,R!==void 0&&(o[$].numArguments=R))}function Bn($,H,R,U,q,le,he,ve){this.name=$,this.constructor=H,this.instancePrototype=R,this.rawDestructor=U,this.baseClass=q,this.getActualType=le,this.upcast=he,this.downcast=ve,this.pureVirtualFunctions=[]}function dr($,H,R){for(;H!==R;)H.upcast||yn("Expected null or instance of "+R.name+", got an instance of "+H.name),$=H.upcast($),H=H.baseClass;return $}function si($,H){if(H===null)return this.isReference&&yn("null is not a valid "+this.name),0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name);var R=H.$$.ptrType.registeredClass,U=dr(H.$$.ptr,R,this.registeredClass);return U}function jn($,H){var R;if(H===null)return this.isReference&&yn("null is not a valid "+this.name),this.isSmartPointer?(R=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,R),R):0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&H.$$.ptrType.isConst&&yn("Cannot convert argument of type "+(H.$$.smartPtrType?H.$$.smartPtrType.name:H.$$.ptrType.name)+" to parameter type "+this.name);var U=H.$$.ptrType.registeredClass;if(R=dr(H.$$.ptr,U,this.registeredClass),this.isSmartPointer)switch(H.$$.smartPtr===void 0&&yn("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:H.$$.smartPtrType===this?R=H.$$.smartPtr:yn("Cannot convert argument of type "+(H.$$.smartPtrType?H.$$.smartPtrType.name:H.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:R=H.$$.smartPtr;break;case 2:if(H.$$.smartPtrType===this)R=H.$$.smartPtr;else{var q=H.clone();R=this.rawShare(R,Za.toHandle(function(){q.delete()})),$!==null&&$.push(this.rawDestructor,R)}break;default:yn("Unsupporting sharing policy")}return R}function wr($,H){if(H===null)return this.isReference&&yn("null is not a valid "+this.name),0;H.$$||yn('Cannot pass "'+dc(H)+'" as a '+this.name),H.$$.ptr||yn("Cannot pass deleted object as a pointer of type "+this.name),H.$$.ptrType.isConst&&yn("Cannot convert argument of type "+H.$$.ptrType.name+" to parameter type "+this.name);var R=H.$$.ptrType.registeredClass,U=dr(H.$$.ptr,R,this.registeredClass);return U}function ei($){return this.rawGetPointee&&($=this.rawGetPointee($)),$}function xr($){this.rawDestructor&&this.rawDestructor($)}function uc($){$!==null&&$.delete()}function ba(){Yi.prototype.getPointee=ei,Yi.prototype.destructor=xr,Yi.prototype.argPackAdvance=8,Yi.prototype.readValueFromPointer=Mr,Yi.prototype.deleteObject=uc,Yi.prototype.fromWireType=Qt}function Yi($,H,R,U,q,le,he,ve,Te,be,ke){this.name=$,this.registeredClass=H,this.isReference=R,this.isConst=U,this.isSmartPointer=q,this.pointeeType=le,this.sharingPolicy=he,this.rawGetPointee=ve,this.rawConstructor=Te,this.rawShare=be,this.rawDestructor=ke,!q&&H.baseClass===void 0?U?(this.toWireType=si,this.destructorFunction=null):(this.toWireType=wr,this.destructorFunction=null):this.toWireType=jn}function Xa($,H,R){o.hasOwnProperty($)||pi("Replacing nonexistant public symbol"),o[$].overloadTable!==void 0&&R!==void 0?o[$].overloadTable[R]=H:(o[$]=H,o[$].argCount=R)}function cl($,H,R){var U=o["dynCall_"+$];return R&&R.length?U.apply(null,[H].concat(R)):U.call(null,H)}function ll($,H,R){if($.includes("j"))return cl($,H,R);var U=dt(H).apply(null,R);return U}function bs($,H){var R=[];return function(){return R.length=0,Object.assign(R,arguments),ll($,H,R)}}function gr($,H){$=fr($);function R(){return $.includes("j")?bs($,H):dt(H)}var U=R();return typeof U!="function"&&yn("unknown function pointer with signature "+$+": "+H),U}var Ya=void 0;function vi($){var H=He($),R=fr(H);return me(H),R}function ci($,H){var R=[],U={};function q(le){if(!U[le]&&!ft[le]){if(Ut[le]){Ut[le].forEach(q);return}R.push(le),U[le]=!0}}throw H.forEach(q),new Ya($+": "+R.map(vi).join([", "]))}function ul($,H,R,U,q,le,he,ve,Te,be,ke,Je,pt){ke=fr(ke),le=gr(q,le),ve&&(ve=gr(he,ve)),be&&(be=gr(Te,be)),pt=gr(Je,pt);var Mt=Pt(ke);At(Mt,function(){ci("Cannot construct "+ke+" due to unbound types",[U])}),Vi([$,H,R],U?[U]:[],function(Tt){Tt=Tt[0];var dn,ln;U?(dn=Tt.registeredClass,ln=dn.instancePrototype):ln=or.prototype;var Xn=_n(Mt,function(){if(Object.getPrototypeOf(this)!==li)throw new oo("Use 'new' to construct "+ke);if(yi.constructor_body===void 0)throw new oo(ke+" has no accessible constructor");var Ih=yi.constructor_body[arguments.length];if(Ih===void 0)throw new oo("Tried to invoke ctor of "+ke+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(yi.constructor_body).toString()+") parameters instead!");return Ih.apply(this,arguments)}),li=Object.create(ln,{constructor:{value:Xn}});Xn.prototype=li;var yi=new Bn(ke,Xn,li,pt,dn,le,ve,be),rf=new Yi(ke,yi,!0,!1,!1),Oa=new Yi(ke+"*",yi,!1,!1,!1),U1=new Yi(ke+" const*",yi,!1,!0,!1);return Gi[$]={pointerType:Oa,constPointerType:U1},Xa(Mt,Xn),[rf,Oa,U1]})}function so($,H){for(var R=[],U=0;U<$;U++)R.push(j[H+U*4>>2]);return R}function Uu($,H){if(!($ instanceof Function))throw new TypeError("new_ called with constructor type "+typeof $+" which is not a function");var R=_n($.name||"unknownFunctionName",function(){});R.prototype=$.prototype;var U=new R,q=$.apply(U,H);return q instanceof Object?q:U}function Wi($,H,R,U,q){var le=H.length;le<2&&yn("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var he=H[1]!==null&&R!==null,ve=!1,Te=1;Te0);var he=so(H,R);q=gr(U,q),Vi([],[$],function(ve){ve=ve[0];var Te="constructor "+ve.name;if(ve.registeredClass.constructor_body===void 0&&(ve.registeredClass.constructor_body=[]),ve.registeredClass.constructor_body[H-1]!==void 0)throw new oo("Cannot register multiple constructors with identical number of parameters ("+(H-1)+") for class '"+ve.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return ve.registeredClass.constructor_body[H-1]=()=>{ci("Cannot construct "+ve.name+" due to unbound types",he)},Vi([],he,function(be){return be.splice(1,0,null),ve.registeredClass.constructor_body[H-1]=Wi(Te,be,null,q,le),[]}),[]})}function fc($,H,R,U,q,le,he,ve){var Te=so(R,U);H=fr(H),le=gr(q,le),Vi([],[$],function(be){be=be[0];var ke=be.name+"."+H;H.startsWith("@@")&&(H=Symbol[H.substring(2)]),ve&&be.registeredClass.pureVirtualFunctions.push(H);function Je(){ci("Cannot call "+ke+" due to unbound types",Te)}var pt=be.registeredClass.instancePrototype,Mt=pt[H];return Mt===void 0||Mt.overloadTable===void 0&&Mt.className!==be.name&&Mt.argCount===R-2?(Je.argCount=R-2,Je.className=be.name,pt[H]=Je):(qn(pt,H,ke),pt[H].overloadTable[R-2]=Je),Vi([],Te,function(Tt){var dn=Wi(ke,Tt,be,le,he);return pt[H].overloadTable===void 0?(dn.argCount=R-2,pt[H]=dn):pt[H].overloadTable[R-2]=dn,[]}),[]})}var Ja=[],Ji=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function fl($){$>4&&--Ji[$].refcount===0&&(Ji[$]=void 0,Ja.push($))}function Bu(){for(var $=0,H=5;H($||yn("Cannot use deleted val. handle = "+$),Ji[$].value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var H=Ja.length?Ja.pop():Ji.length;return Ji[H]={refcount:1,value:$},H}}}};function hl($,H){H=fr(H),Qr($,{name:H,fromWireType:function(R){var U=Za.toValue(R);return fl(R),U},toWireType:function(R,U){return Za.toHandle(U)},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:null})}function dc($){if($===null)return"null";var H=typeof $;return H==="object"||H==="array"||H==="function"?$.toString():""+$}function Wu($,H){switch(H){case 2:return function(R){return this.fromWireType(Y[R>>2])};case 3:return function(R){return this.fromWireType(re[R>>3])};default:throw new TypeError("Unknown float type: "+$)}}function zu($,H,R){var U=To(R);H=fr(H),Qr($,{name:H,fromWireType:function(q){return q},toWireType:function(q,le){return le},argPackAdvance:8,readValueFromPointer:Wu(H,U),destructorFunction:null})}function $u($,H,R,U,q,le){var he=so(H,R);$=fr($),q=gr(U,q),At($,function(){ci("Cannot call "+$+" due to unbound types",he)},H-1),Vi([],he,function(ve){var Te=[ve[0],null].concat(ve.slice(1));return Xa($,Wi($,Te,null,q,le),H-1),[]})}function ju($,H,R){switch(H){case 0:return R?function(q){return V[q]}:function(q){return G[q]};case 1:return R?function(q){return A[q>>1]}:function(q){return k[q>>1]};case 2:return R?function(q){return F[q>>2]}:function(q){return j[q>>2]};default:throw new TypeError("Unknown integer type: "+$)}}function Hu($,H,R,U,q){H=fr(H);var le=To(R),he=Je=>Je;if(U===0){var ve=32-8*R;he=Je=>Je<>>ve}var Te=H.includes("unsigned"),be=(Je,pt)=>{},ke;Te?ke=function(Je,pt){return be(pt,this.name),pt>>>0}:ke=function(Je,pt){return be(pt,this.name),pt},Qr($,{name:H,fromWireType:he,toWireType:ke,argPackAdvance:8,readValueFromPointer:ju(H,le,U!==0),destructorFunction:null})}function Ku($,H,R){var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],q=U[H];function le(he){he=he>>2;var ve=j,Te=ve[he],be=ve[he+1];return new q(L,be,Te)}R=fr(R),Qr($,{name:R,fromWireType:le,argPackAdvance:8,readValueFromPointer:le},{ignoreDuplicateRegistrations:!0})}function qu($,H){H=fr(H);var R=H==="std::string";Qr($,{name:H,fromWireType:function(U){var q=j[U>>2],le=U+4,he;if(R)for(var ve=le,Te=0;Te<=q;++Te){var be=le+Te;if(Te==q||G[be]==0){var ke=be-ve,Je=b(ve,ke);he===void 0?he=Je:(he+="\0",he+=Je),ve=be+1}}else{for(var pt=new Array(q),Te=0;Te>2]=le,R&&he)P(q,Te,le+1);else if(he)for(var be=0;be255&&(me(Te),yn("String has UTF-16 code units that do not fit in 8 bits")),G[Te+be]=ke}else for(var be=0;be>1,q=U+H/2;!(U>=q)&&k[U];)++U;if(R=U<<1,R-$>32&&gl)return gl.decode(G.subarray($,R));for(var le="",he=0;!(he>=H/2);++he){var ve=A[$+he*2>>1];if(ve==0)break;le+=String.fromCharCode(ve)}return le}function pl($,H,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var U=H,q=R<$.length*2?R/2:$.length,le=0;le>1]=he,H+=2}return A[H>>1]=0,H-U}function ml($){return $.length*2}function Yu($,H){for(var R=0,U="";!(R>=H/4);){var q=F[$+R*4>>2];if(q==0)break;if(++R,q>=65536){var le=q-65536;U+=String.fromCharCode(55296|le>>10,56320|le&1023)}else U+=String.fromCharCode(q)}return U}function hc($,H,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var U=H,q=U+R-4,le=0;le<$.length;++le){var he=$.charCodeAt(le);if(he>=55296&&he<=57343){var ve=$.charCodeAt(++le);he=65536+((he&1023)<<10)|ve&1023}if(F[H>>2]=he,H+=4,H+4>q)break}return F[H>>2]=0,H-U}function vl($){for(var H=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U>=55296&&U<=57343&&++R,H+=4}return H}function yl($,H,R){R=fr(R);var U,q,le,he,ve;H===2?(U=Xu,q=pl,he=ml,le=()=>k,ve=1):H===4&&(U=Yu,q=hc,he=vl,le=()=>j,ve=2),Qr($,{name:R,fromWireType:function(Te){for(var be=j[Te>>2],ke=le(),Je,pt=Te+4,Mt=0;Mt<=be;++Mt){var Tt=Te+4+Mt*H;if(Mt==be||ke[Tt>>ve]==0){var dn=Tt-pt,ln=U(pt,dn);Je===void 0?Je=ln:(Je+="\0",Je+=ln),pt=Tt+H}}return me(Te),Je},toWireType:function(Te,be){typeof be!="string"&&yn("Cannot pass non-string to C++ string type "+R);var ke=he(be),Je=te(4+ke+H);return j[Je>>2]=ke>>ve,q(be,Je+4,ke+H),Te!==null&&Te.push(me,Je),Je},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:function(Te){me(Te)}})}function gc($,H,R,U,q,le){bn[$]={name:fr(H),rawConstructor:gr(R,U),rawDestructor:gr(q,le),fields:[]}}function Ju($,H,R,U,q,le,he,ve,Te,be){bn[$].fields.push({fieldName:fr(H),getterReturnType:R,getter:gr(U,q),getterContext:le,setterArgumentType:he,setter:gr(ve,Te),setterContext:be})}function wl($,H){H=fr(H),Qr($,{isVoid:!0,name:H,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,U){}})}function Zu($){$>4&&(Ji[$].refcount+=1)}function xl($,H){var R=ft[$];return R===void 0&&yn(H+" has unknown type "+vi($)),R}function Qu($,H){$=xl($,"_emval_take_value");var R=$.readValueFromPointer(H);return Za.toHandle(R)}function ef(){Ne("")}function tf($,H,R){G.copyWithin($,H,H+R)}function nf(){return 2147483648}function pc($){try{return S.grow($-L.byteLength+65535>>>16),ue(S.buffer),1}catch{}}function mc($){var H=G.length;$=$>>>0;var R=nf();if($>R)return!1;let U=(Te,be)=>Te+(be-Te%be)%be;for(var q=1;q<=4;q*=2){var le=H*(1+.2/q);le=Math.min(le,$+100663296);var he=Math.min(R,U(Math.max($,le),65536)),ve=pc(he);if(ve)return!0}return!1}function oa($){return 52}function Ia($,H,R,U,q){return 70}var Eo=[null,[],[]];function Cl($,H){var R=Eo[$];H===0||H===10?(($===1?w:x)(D(R,0)),R.length=0):R.push(H)}function Sl($,H,R,U){for(var q=0,le=0;le>2],ve=j[H+4>>2];H+=8;for(var Te=0;Te>2]=q,0}function vc($){return $}function _l($){var H=o["_"+$];return H}function Is($,H){V.set($,H)}function Tl($,H,R,U,q){var le={string:Tt=>{var dn=0;if(Tt!=null&&Tt!==0){var ln=(Tt.length<<2)+1;dn=it(ln),P(Tt,dn,ln)}return dn},array:Tt=>{var dn=it(Tt.length);return Is(Tt,dn),dn}};function he(Tt){return H==="string"?b(Tt):H==="boolean"?!!Tt:Tt}var ve=_l($),Te=[],be=0;if(U)for(var ke=0;ke0||(Se(),Z>0))return;function H(){et||(et=!0,o.calledRun=!0,!_&&(B(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),O()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),H()},1)):H()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Ye(),o.ready}})();t.exports=r})(cG);var Mxe=cG.exports;const Pxe=ac(Mxe),Rxe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),Sg={codec:void 0,decoder:void 0,decodeConfig:{}};function Lxe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function Axe(t){if(Sg.decodeConfig=t,Sg.codec)return Promise.resolve();const e=Pxe({locateFile:r=>r.endsWith(".wasm")?Rxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Sg.codec=i,Sg.decoder=new i.HTJ2KDecoder,r()},n)})}async function Nxe(t,e){await Axe();const r=new Sg.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:D}=Lxe(e.decodeLevel,o.width,o.height);o.width=E,o.height=D}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=kxe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,_=x.slice(C,C+S);w=new w.constructor(_);const T={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:T,...T,...m}}function kxe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Vxe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=X5(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=dE(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=sS(s,c,C);f=!v3e(S.min,S.max,Ab[g])}g&&!f?a=Gxe(e,t,Ab,a):e.preScale.enabled&&!h?a=Wxe(e,s,c,t):a=lG(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(uG(C),Bxe(C)){Vxe(a,C),t.preScale={...e.preScale,scaled:!0};const _=sS(s,c,C);p=_.min,v=_.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function Bxe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function Gxe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&$xe(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function Wxe(t,e,r,n){const i=t.preScale.scalingParameters;uG(i);const o=sS(e,r,i);return lG(o.min,o.max,n)}function lG(t,e,r){const n=hE(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function sS(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function uG(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function zxe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function $xe(t,e,r){const n=zxe(t,e,r),{scalingType:i="replicate"}=e;return Fxe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function fG(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=Ob(t,r);break;case"1.2.840.10008.1.2.2":s=rxe(t,r);break;case"1.2.840.10008.1.2.1.99":s=Ob(t,r);break;case"1.2.840.10008.1.2.5":s=ixe(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=dxe(r,c);break;case"1.2.840.10008.1.2.4.51":s=vxe(t,r);break;case"1.2.840.10008.1.2.4.57":s=Pb(t,r);break;case"1.2.840.10008.1.2.4.70":s=Pb(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=Rb(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=Rb(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=Lb(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=Lb(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=Nxe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=Uxe(l,i,a);return o==null||o(f),f}const jxe={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return fG(t,e,i,r,n,o)}};iT(jxe);const Nb={constants:Q3e,convertRGBColorByPixel:xB,convertRGBColorByPlane:CB,convertYBRFullByPixel:SB,convertYBRFullByPlane:_B,convertPALETTECOLOR:TB,wadouri:S3e,wadors:K3e,init:rG,convertColorSpace:zB,createImage:Y5,decodeJPEGBaseline8BitColor:$B,getImageFrame:jB,getPixelData:vE,getMinMax:X5,isColorImage:dE,isJPEGBaseline8BitColor:J3e,internal:Vwe,decodeImageFrame:fG};class Z0 extends Ou{}VE(Z0,"toolName","NoLabelArrowAnnotate");function kb(t,e){const r=mt("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1,f=n,u=i,d=o;return[d[0]+e.x*u[0]*c+e.y*f[0]*l,d[1]+e.x*u[1]*c+e.y*f[1]*l,d[2]+e.x*u[2]*c+e.y*f[2]*l]}window.cornerstone3dTools=Twe;const{MouseBindings:tg,KeyboardBindings:Vb}=nN,{IMAGE_RENDERED:qm}=Xe,Hxe=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],ng=[{label:"Window/Level",value:H0.toolName},{label:"Pan",value:j0.toolName},{label:"Zoom",value:q0.toolName},{label:"Stack Scroll",value:id.toolName},{label:"Rotate",value:K0.toolName},{label:"Length",value:Iu.toolName},{label:"Probe",value:nl.toolName},{label:"Arrow (No Label)",value:Z0.toolName},{label:"Arrow Annotate",value:Ou.toolName},{label:"Rectangle ROI",value:tl.toolName},{label:"Ellipse ROI",value:od.toolName},{label:"Freehand ROI",value:bu.toolName},{label:"Freehand Contour Segmentation",value:ic.toolName},{label:"Sculptor",value:X0.toolName},{label:"Reference Cursors",value:ua.toolName}],Fb=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],Xm=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function Ub({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,...o}){var Fi,ao,Ui,mi,Ka,Bo,Bi,qa,Gi,ia;const a=Nt.useRef(null),s=Nt.useRef(null),c=Nt.useRef(!1),[l,f]=Nt.useState(!1),[u,d]=Nt.useState(!1),[h,g]=Nt.useState(null),[p,v]=Nt.useState(null),y=9,m="renderingEngine_"+t,w="TOOL_GROUP_"+t,x=Nt.useRef(null),C=Nt.useRef(!1),[S,_]=Nt.useState(!0),[T,E]=Nt.useState([]),[D,b]=Nt.useState(0),[I,P]=Nt.useState(()=>Array(y).fill([])),M=de=>{typeof de=="function"?P(Ue=>{const _e=de(Ue);return console.log("setViewportImageIds (fn):",_e),_e}):(console.log("setViewportImageIds:",de),P(de))},[L,V]=Nt.useState(()=>Array(y).fill(0)),[G,A]=Nt.useState(!1),[k,F]=Nt.useState(null);Nt.useEffect(()=>{let de=!1;if(n||i){F(n?"annotations":"viewerState");const Ue=setTimeout(()=>{if(de)return;const _e=t||"default";if(n)try{const ye=window[`importAnnotations_${_e}`]||window.importAnnotations;typeof ye=="function"&&ye(n)}catch(ye){console.error("Failed to import annotations from prop:",ye)}if(i)try{const ye=window[`importViewerState_${_e}`]||window.importViewerState;typeof ye=="function"&&ye(i)}catch(ye){console.error("Failed to import viewer state from prop:",ye)}F(null)},2e3);return()=>{de=!0,clearTimeout(Ue),F(null)}}},[n,i,t]),Nt.useEffect(()=>{e().then(async de=>{const Ue=await Promise.all(de.map(async _e=>{let ye;try{const je=_e[0];if(je&&je.startsWith("wadouri:")){const ot=je.slice(8),ut=await(await fetch(ot)).arrayBuffer();ye=Tr.parseDicom(new Uint8Array(ut)).string("x0020000d")}}catch{}return{imageIds:_e,studyInstanceUID:ye}}));E(Ue),await O(de[0]),M(Array(y).fill(de[0]||[]))})},[]);const j=async(de,Ue)=>{const _e=T[Ue];if(!_e)return;const ye=_e.imageIds;oe(je=>{const ot=[...je];return ot[de]="stack",ot}),M(je=>{const ot=[...je];return ot[de]=ye,ot}),V(je=>{const ot=[...je];return ot[de]=Ue,ot}),await O(ye)},[Y,re]=Nt.useState(!1),[ue,ce]=Nt.useState(!0),[pe,Ee]=Nt.useState(!1),[Oe,Se]=Nt.useState(!1),B=()=>{console.log("Sorting viewport imageIds by slice location"),M(de=>{const Ue=de.map((_e,ye)=>{if(!_e||_e.length===0)return _e;const st=[..._e.map(ut=>{const rt=mt("imagePlaneModule",ut);let Ct=null;return rt&&(rt.sliceLocation!==void 0?Ct=Number(rt.sliceLocation):rt.imagePositionPatient&&Array.isArray(rt.imagePositionPatient)&&rt.imagePositionPatient.length===3&&(Ct=Number(rt.imagePositionPatient[2]))),{imageId:ut,sortKey:Ct}})].sort((ut,rt)=>ut.sortKey!==null&&rt.sortKey!==null?ut.sortKey-rt.sortKey:ut.imageId.localeCompare(rt.imageId)).map(ut=>ut.imageId);return JSON.stringify(st)===JSON.stringify(_e)?_e:st});return A(!0),Ue})},O=async de=>{console.log("Setting loaded imageIds:",de),console.log("autoCacheStack:",r);const Ue=[];if(r){for(const _e of de)if(_e.startsWith("wadouri:"))try{const ye=_e.slice(8);if(Nb.wadouri.dataSetCacheManager){const je=Nb.wadouri.dataSetCacheManager.load(ye);je&&typeof je.then=="function"&&Ue.push(je)}else console.warn("MetaDataManager not found. Unable to cache metadata.")}catch(ye){console.warn(`Failed to cache metadata for ${_e}:`,ye)}await Promise.all(Ue),Ne&&(console.log("Sorting viewport imageIds by slice location"),B())}},[z,W]=Nt.useState({rows:1,cols:1}),[K,Z]=Nt.useState(!1),ee=Nt.useRef([]),xe=Nt.useRef({}),De=Nt.useRef({}),[Ne,ze]=Nt.useState(!1),[ie,ae]=Nt.useState(!0),we=[];for(let de=1;de<=3;de++)for(let Ue=1;Ue<=3;Ue++)we.push({rows:de,cols:Ue});const[se,ge]=Nt.useState(()=>Array(z.rows*z.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:0})),[Fe,oe]=Nt.useState(()=>Array(y).fill("stack")),[ht,wt]=Nt.useState(()=>Array(z.rows*z.cols).fill(!1)),[gt,Ie]=Nt.useState({Primary:id.toolName,Auxiliary:j0.toolName,Secondary:H0.toolName,Primary_and_Secondary:q0.toolName,Fourth_Button:K0.toolName,Wheel:id.toolName}),[$e,tt]=Nt.useState({Primary:Iu.toolName,Auxiliary:nl.toolName,Secondary:Z0.toolName}),[nt,dt]=Nt.useState(!1);Nt.useEffect(()=>{const de=_e=>{_e.ctrlKey&&dt(!0)},Ue=_e=>{_e.ctrlKey||dt(!1)};return window.addEventListener("keydown",de),window.addEventListener("keyup",Ue),()=>{window.removeEventListener("keydown",de),window.removeEventListener("keyup",Ue)}},[]);const[Lt,xt]=Nt.useState(!1),[Ft,jt]=Nt.useState(null),Pn=(de,Ue)=>{Ro&&Ro(Ue),yn(_e=>{const ye=[..._e];return ye[de]=Ue,ye})},$n=(de,Ue,_e)=>{const ye=Rr.getAllAnnotations()||[];ye.forEach(ot=>{ot.annotationUID===Ue&&(ot.isSelected=!1)}),Rr.removeAnnotation(Ue),x.current.render();const je=_e.filter(ot=>ot.annotationUID!==Ue);yn(ot=>{const st=[...ot],ut=je.length>0?je[0].annotationUID:null;return st[de]=ut,ye.forEach(rt=>{rt.isSelected=rt.annotationUID===ut}),Ro(ut),x.current.render(),st})},fn=()=>{const de=I.findIndex(je=>je&&je.length>0);if(de===-1){jt("No images loaded."),xt(!0);return}const Ue=I[de][0],_e=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],ye={};_e.forEach(je=>{const ot=mt(je,Ue);ot!==void 0&&(ye[je]=ot)}),jt(lt.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(ye,null,2)})),xt(!0)};Nt.useEffect(()=>(window.loadDicomStackFromFiles=de=>{const Ue=Array.from(de);Sn({target:{files:Ue}})},()=>{window.loadDicomStackFromFiles=void 0}),[]);const[bn,Xi]=Nt.useState(!1);Nt.useEffect(()=>{const de=Kr(w);de&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(Ue=>{de.setToolConfiguration(Ue,{color:"#00e676",selectedColor:"#ffeb3b"})})},[w]),Nt.useEffect(()=>{const de=_e=>{_e.altKey&&Xi(!0)},Ue=_e=>{_e.altKey||Xi(!1)};return window.addEventListener("keydown",de),window.addEventListener("keyup",Ue),()=>{window.removeEventListener("keydown",de),window.removeEventListener("keyup",Ue)}},[]),Nt.useEffect(()=>{if(!ie)return;const de=Kr(w);de&&(bn?(de.hasTool(ua.toolName)||de.addTool(ua.toolName),de.setToolEnabled(ua.toolName),de.setToolActive(ua.toolName)):de.hasTool(ua.toolName)&&de.setToolDisabled(ua.toolName))},[bn,ie]);const Mr=Nt.useCallback(()=>{[Kr(w)].forEach(Ue=>{if(Ue){ng.forEach(ye=>{Ue.setToolPassive(ye.value,{removeAllBindings:!0})}),Ue.setToolDisabled(ua.toolName);const _e={};Object.entries(gt).forEach(([ye,je])=>{_e[je]||(_e[je]=[]);const ot=Xm.find(st=>st.value===ye);ot?_e[je].push({mouseButton:ot.mask}):tg[ye]&&_e[je].push({mouseButton:tg[ye]})}),Object.entries($e).forEach(([ye,je])=>{if(!je)return;_e[je]||(_e[je]=[]);const ot=Xm.find(st=>st.value===ye);ot?_e[je].push({mouseButton:ot.mask,modifierKey:Vb.Ctrl}):tg[ye]&&_e[je].push({mouseButton:tg[ye],modifierKey:Vb.Ctrl})}),Object.entries(_e).forEach(([ye,je])=>{Ue.setToolActive(ye,{bindings:je})})}})},[gt,$e]),[Be,ft]=Nt.useState(!1),Ut=Nt.useRef(null),Sn=async de=>{const Ue=de.target.files;if(!Ue||Ue.length===0)return;ze(!1);const _e=Array.from(Ue).sort((ut,rt)=>ut.name.localeCompare(rt.name));let ye;const je=await _e[0].arrayBuffer();ye=Tr.parseDicom(new Uint8Array(je)).string("x0020000d"),console.log("StudyInstanceUID:",ye);const st=_e.map(ut=>`wadouri:${URL.createObjectURL(ut)}`);E(ut=>{const rt=[...ut,{imageIds:st,studyInstanceUID:ye}];return M(Ct=>{const Qt=[...Ct];return Qt[0]=st,Qt}),V(Ct=>{const Qt=[...Ct];return Qt[0]=rt.length-1,Qt}),O(st),rt})},Qn=Nt.useCallback((de,Ue)=>{if(!Ue)return;let _e=0,ye=0,je="",ot="",st="";if(Fe[de]==="stack"){if(_e=typeof Ue.getCurrentImageIdIndex=="function"?Ue.getCurrentImageIdIndex():0,ye=(typeof Ue.getImageIds=="function"?Ue.getImageIds():[]).length,typeof Ue.getProperties=="function"){const rt=Ue.getProperties();if(rt.voiRange){const{lower:Ct,upper:Qt}=rt.voiRange;je=((Qt+Ct)/2).toFixed(0),ot=(Qt-Ct).toFixed(0)}}}else if(Fe[de]==="volume"){if(typeof Ue.getSliceIndex=="function"&&(_e=Ue.getSliceIndex()),typeof Ue.getNumberOfSlices=="function"&&(ye=Ue.getNumberOfSlices()),typeof Ue.getProperties=="function"){let ut;if(Ue.volumeIds&&Ue.volumeIds.size>0){const rt=Array.from(Ue.volumeIds)[0];ut=Ue.getProperties(rt)}else ut=Ue.getProperties();if(ut&&ut.voiRange){const{lower:rt,upper:Ct}=ut.voiRange;je=((Ct+rt)/2).toFixed(0),ot=(Ct-rt).toFixed(0)}}if(typeof Ue.getSlicePlaneCoordinates=="function"){const ut=Ue.getSlicePlaneCoordinates();ut&&typeof ut.position=="number"&&(st=ut.position.toFixed(2)+" mm")}}ge(ut=>{const rt=[...ut];return rt[de]={index:_e+1,total:ye,windowCenter:je,windowWidth:ot,slicePosition:st},rt})},[Fe]),[Pt,_n]=Nt.useState(!1);function sn(){for(let de=0;de{const de=async()=>{var ot;console.log("setup"),c.current||(c.current=!0,await WZ(),await iF(),rG());let _e=x.current;_e||(_e=new CA(m),x.current=_e);let ye=Kr(w);ye||(ye=Kxe(w)),Fe.slice(0,z.rows*z.cols).filter(st=>st==="volume").length,Vi(ye);for(let st=0;st{if(Ct.offsetWidth>0&&Ct.offsetHeight>0){_e.resize();const xn=_e.getViewport(rt);xn&&typeof xn.resize=="function"&&xn.resize(),xn&&typeof xn.render=="function"&&xn.render()}});Gt.observe(Ct),Ct._resizeObserver=Gt}if(Fe[st]==="stack")ut&&ut.length>0&&on.setStack(ut),Y?ye.removeViewports(m,rt):ye.addViewport(rt,m);else if(Fe[st]==="volume"){ye.addViewport(rt,m);const Gt=`myVolumeId_${st}`;(await Vv(Gt,{imageIds:ut})).load(),on.setVolumes([{volumeId:Gt}]),on.render(),Ct._overlayListener&&on.element.removeEventListener(qm,Ct._overlayListener);const er=()=>Qn(st,on);on.element.addEventListener(qm,er),Ct._overlayListener=er,Qn(st,on);continue}if(on.render(),!C.current){De.current[st]!==void 0&&typeof on.setImageIdIndex=="function"&&Aa(on.element,{imageIndex:De.current[st]});const Gt=xe.current[st];if(Gt&&typeof on.setProperties=="function"){const{voiRange:xn,invert:er,interpolationType:nr,VOILUTFunction:or,colormap:qn}=Gt,At={};xn&&xn.lower!==void 0&&xn.upper!==void 0&&(At.voiRange=xn),er!==void 0&&(At.invert=er),nr!==void 0&&(At.interpolationType=nr),or&&(At.VOILUTFunction=or),qn!=null&&(typeof qn=="string"||typeof qn=="object"&&!("actor"in qn))&&(At.colormap=qn),setTimeout(()=>{console.log("Restoring properties (timeout) for viewport",st,At),on.setProperties(At),on.render()},100)}}Ct._overlayListener&&on.element.removeEventListener(qm,Ct._overlayListener);const cn=()=>Qn(st,on);on.element.addEventListener(qm,cn),Ct._overlayListener=cn,Qn(st,on)}for(let st=0;st=2?(ye.hasTool(Fs.toolName)||ye.addTool(Fs.toolName),ye.setToolEnabled(Fs.toolName),ye.setToolConfiguration(Fs.toolName,{}),ye.setToolActive(Fs.toolName,{bindings:[{mouseButton:tg.Primary}]})):ye.hasTool(Fs.toolName)&&ye.setToolDisabled(Fs.toolName)),Mr()},Ue=requestAnimationFrame(()=>{de()});return()=>{ee.current.forEach(_e=>{_e&&_e._resizeObserver&&(_e._resizeObserver.disconnect(),delete _e._resizeObserver)}),cancelAnimationFrame(Ue)}},[s,Qn,z,Fe,I]);const rn=Nt.useCallback(de=>{const Ue=`CT_${de}`,ye=x.current.getViewport(Ue);ye&&typeof ye.resetCamera=="function"&&(ye.resetCamera(),console.log("Restoring viewport properties for viewport",de),ye.resetProperties(),ye.render())},[]),pi=Nt.useCallback((de,Ue,_e)=>{const ye=`CT_${de}`;try{const je=x.current;if(je){const ot=je.getViewport(ye);ot&&typeof ot.setProperties=="function"&&(console.log(`Applying preset to viewport ${de}: center=${Ue}, width=${_e}`),ot.setProperties({voiRange:{lower:Ue-_e/2,upper:Ue+_e/2}}),ot.render(),Qn(de,ot))}}catch{}},[Qn]);Nt.useEffect(()=>{ge(Array(z.rows*z.cols).fill({index:0,total:0,windowCenter:"",windowWidth:""})),wt(Array(z.rows*z.cols).fill(!1))},[z]),Nt.useEffect(()=>{Mr()},[gt,$e,nt,Mr]),Nt.useEffect(()=>{if(!l)return;const de=Ue=>{const _e=document.querySelector(".preset-menu");_e&&!_e.contains(Ue.target)&&f(!1)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[l]),Nt.useEffect(()=>{const de=Ue=>{if(Ue.button===3||Ue.button===4)return Ue.preventDefault(),!1};return window.addEventListener("mousedown",de,!0),window.addEventListener("mouseup",de,!0),window.addEventListener("auxclick",de,!0),()=>{window.removeEventListener("mousedown",de,!0),window.removeEventListener("mouseup",de,!0),window.removeEventListener("auxclick",de,!0)}},[]),Nt.useEffect(()=>{const de=a.current;if(!de)return;const Ue=_e=>{_e.preventDefault()};return de.addEventListener("contextmenu",Ue),()=>{de.removeEventListener("contextmenu",Ue)}},[]),Nt.useEffect(()=>{if(!ue)return;const de=Kr(w);Vi(de)},[D,ue]),Nt.useEffect(()=>{Ut.current&&(Ut.current.setAttribute("webkitdirectory","true"),Ut.current.setAttribute("directory","true"))},[]),Nt.useEffect(()=>(window.loadDicomStackFromWadouriList=async de=>{if(!de||de.length===0)return;let Ue;try{const _e=de[0];if(_e&&_e.startsWith("wadouri:")){const ye=_e.slice(8),ot=await(await fetch(ye)).arrayBuffer();Ue=Tr.parseDicom(new Uint8Array(ot)).string("x0020000d")}}catch{}E(_e=>{const ye=[..._e,{imageIds:de,studyInstanceUID:Ue}];return M(je=>{const ot=[...je];return ot[0]=de,ot}),V(je=>{const ot=[...je];return ot[0]=ye.length-1,ot}),O(de),ye})},()=>{window.loadDicomStackFromWadouriList=void 0}),[E,M,V,O]),Nt.useEffect(()=>{!Ne||!I.every(Ue=>!Ue||Ue.length===0||Ue.every(_e=>!!mt("imagePlaneModule",_e)))||M(Ue=>{let _e=!1;const ye=Ue.map(je=>{if(!je||je.length===0)return je;const ut=[...je.map(rt=>({imageId:rt,sliceLoc:(()=>{const Ct=mt("imagePlaneModule",rt);return Ct&&Ct.sliceLocation!==void 0?Number(Ct.sliceLocation):null})()}))].sort((rt,Ct)=>rt.sliceLoc!==null&&Ct.sliceLoc!==null?rt.sliceLoc-Ct.sliceLoc:rt.imageId.localeCompare(Ct.imageId)).map(rt=>rt.imageId);return JSON.stringify(ut)!==JSON.stringify(je)?(_e=!0,ut):je});return _e&&A(!0),ye})},[Ne,T]);function Vi(de){if(!de)return;const Ue=`CT_${D}`;ue?(de.setToolEnabled(Gf.toolName),de.setToolConfiguration(Gf.toolName,{sourceViewportId:Ue})):de.setToolDisabled(Gf.toolName)}function Ha(){var Ue,_e,ye;const de=x.current;if(de)for(let je=0;je=ye.length||de>=Ue)return alert("Invalid truncation bounds."),!1;const je=ye.slice(de,Ue+1);E([{..._e,imageIds:je}]),M([je]),V([0]);const ot=x.current;if(ot){const rt=ot.getViewport("CT_0");rt&&typeof rt.setStack=="function"&&(rt.setStack(je),(st=rt.setImageIdIndex)==null||st.call(rt,0),(ut=rt.render)==null||ut.call(rt))}return!0}function To(de=0){const Ue=x.current;if(!Ue)return null;const _e=Ue.getViewport(`CT_${de}`);return!_e||typeof _e.getCurrentImageIdIndex!="function"?null:_e.getCurrentImageIdIndex()}Nt.useEffect(()=>{const de=t||"default";function Ue(_e,ye){const je=x.current;if(!je)return;const ot=je.getViewport(`CT_${_e}`);if(!ot||typeof ot.getImageIds!="function")return;const ut=ot.getImageIds().map(Qt=>Qt.replace(/^wadouri:/,"")),rt=ye.replace(/^wadouri:/,""),Ct=ut.indexOf(rt);Ct!==-1&&typeof ot.setImageIdIndex=="function"&&(Aa(ot.element,{imageIndex:Ct}),Qn(_e,ot))}return window[`getViewport_${de}`]=_e=>{const ye=x.current;if(ye)return ye.getViewport(`CT_${_e}`)},window[`getAllViewports_${de}`]=()=>{const _e=x.current;return _e?Array.from({length:y},(ye,je)=>_e.getViewport(`CT_${je}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${de}`]=Ue,window[`resetViewer_${de}`]=Ha,window[`truncateStack_${de}`]=Ea,window[`getCurrentStackPosition_${de}`]=To,window[`loadAdditionalStack_${de}`]=async(_e,ye)=>{var ot;if(!Array.isArray(_e)||_e.length===0)return;let je=ye;if(!je&&((ot=_e[0])!=null&&ot.startsWith("wadouri:")))try{const st=_e[0].slice(8),rt=await(await fetch(st)).arrayBuffer();je=Tr.parseDicom(new Uint8Array(rt)).string("x0020000d")}catch{}E(st=>[...st,{imageIds:_e,studyInstanceUID:je}]),M(st=>{const ut=[...st],rt=ut.findIndex(Ct=>!Ct||Ct.length===0);return rt!==-1&&(ut[rt]=_e),ut}),O(_e)},window[`exportViewerState_${de}`]=()=>{var Gt;const _e=z.rows*z.cols,ye=Fe.slice(0,_e),je=L.slice(0,_e),ot=T.map(xn=>({i:xn.imageIds,u:xn.studyInstanceUID}));console.log("Exporting viewer state with",_e,"active viewports"),console.log("modes",ye);const st=x.current,ut=[],rt=[],Ct=[],Qt=[],on=[];for(let xn=0;xn<_e;xn++){let er=null,nr=null,or=null,qn=null,At=null;if(console.log("Exporting state for viewport",xn),st){console.log("Rendering engine found, exporting state for viewport",xn);const Bn=`CT_${xn}`,dr=st.getViewport(Bn);if(dr){if(typeof dr.getProperties=="function"){const{voiRange:si,invert:jn,interpolationType:wr,VOILUTFunction:ei,colormap:xr}=dr.getProperties();er={voiRange:si,invert:jn,interpolationType:wr,VOILUTFunction:ei,colormap:xr}}typeof dr.getCurrentImageIdIndex=="function"&&(nr=dr.getCurrentImageIdIndex()),typeof dr.getCamera=="function"&&(or=dr.getCamera()),console.log("viewport",Bn,"properties",er),ye[xn]==="volume"&&(console.log("Getting orientation for viewport",xn),console.log("viewport.viewportProperties",dr.viewportProperties),qn=((Gt=dr.viewportProperties)==null?void 0:Gt.orientation)||null,typeof dr.getSliceIndex=="function"&&(At=dr.getSliceIndex()))}}ut.push(er),rt.push(nr),Ct.push(or),Qt.push(qn),on.push(At)}return JSON.stringify({grid:z,modes:ye,stacks:ot,stackIdx:je,stackPos:rt,props:ut,cam:Ct,orientations:Qt,volumeSliceIndices:on})},window[`importViewerState_${de}`]=_e=>{try{C.current=!0;const ye=typeof _e=="string"?JSON.parse(_e):_e;if(ye.grid&&W(ye.grid),ye.modes&&oe(ye.modes),ye.stacks&&E(ye.stacks.map(ut=>({imageIds:ut.i,studyInstanceUID:ut.u}))),ye.stackIdx&&ye.stacks){const ut=ye.stackIdx.map(rt=>{var Ct;return((Ct=ye.stacks[rt])==null?void 0:Ct.i)||[]});M(ut),V(ye.stackIdx)}const je=30;let ot=0;async function st(){var Qt,on,cn,Gt,xn,er,nr,or,qn;const ut=x.current;if(!ut){C.current=!1;return}const rt=((Qt=ye.grid)==null?void 0:Qt.rows)*((on=ye.grid)==null?void 0:on.cols)||1;let Ct=!0;for(let At=0;Atei===jn[xr])){console.warn(`Viewport ${At}: importedImageIds do not match viewportImageIds`,{importedImageIds:jn,viewportImageIds:wr}),Ct=!1;break}}catch{Ct=!1}}if(!Ct&&ot{st()},500);return}for(let At=0;At{Aa(Bn.element,{imageIndex:ye.volumeSliceIndices[At]})},100)),Bn.render()}else Bn.setStack&&(Bn.setStack(jn),Bn.render()),ye.stackPos&&typeof ye.stackPos[At]=="number"&&typeof Bn.setImageIdIndex=="function"&&(Mn&&Aa?Aa(Bn.element,{imageIndex:ye.stackPos[At]}):Bn.setImageIdIndex(ye.stackPos[At]));if(ye.props&&ye.props[At]&&typeof Bn.setProperties=="function"){console.log("Restoring properties for viewport",At,ye.props[At]);const wr={...ye.props[At]};wr.colormap!==void 0&&wr.colormap!==null&&typeof wr.colormap!="string"&&(typeof wr.colormap!="object"||!("name"in wr.colormap))&&delete wr.colormap,setTimeout(()=>{Bn.setProperties(wr),Bn.render()},100)}else console.warn("No properties to restore for viewport",At);ye.cam&&ye.cam[At]&&typeof Bn.setCamera=="function"&&(console.log("Restoring camera for viewport",At,ye.cam[At]),Bn.setCamera(ye.cam[At]),Bn.render())}}C.current=!1}setTimeout(()=>{st()},100)}catch(ye){C.current=!1,alert("Failed to import viewer state: "+ye)}},window[`exportAnnotations_${de}`]=()=>{try{let _e=Rr.getAllAnnotations();if(console.log("Exporting annotations:",_e),Array.isArray(_e)){const ye=[Iu.toolName,Z0.toolName,Ou.toolName,tl.toolName,od.toolName,bu.toolName,ic.toolName,nl.toolName,X0.toolName];_e=_e.filter(je=>ye.includes(je.metadata.toolName))}else return"{}";return JSON.stringify(_e,null,2)}catch(_e){return alert("Failed to export annotations: "+_e),"{}"}},window[`importAnnotations_${de}`]=_e=>{try{const ye=typeof _e=="string"?JSON.parse(_e):_e;Rr.removeAllAnnotations&&Rr.removeAllAnnotations(),Array.isArray(ye)&&ye.forEach(je=>{Rr.addAnnotation(je,je.annotationUID)}),x.current&&x.current.render()}catch(ye){alert("Failed to import annotations: "+ye)}},window[`importLegacyAnnotations_${de}`]=_e=>{Rr.removeAllAnnotations&&Rr.removeAllAnnotations();let ye;try{ye=typeof _e=="string"?JSON.parse(_e):_e}catch{alert("Invalid legacy annotation JSON");return}const je={ArrowAnnotate:"ArrowAnnotate"};Object.entries(ye).forEach(([ot,st])=>{console.log("Importing legacy annotations for imageId:",ot),Object.entries(st).forEach(([ut,rt])=>{const Ct=je[ut]||ut;rt.data&&Array.isArray(rt.data)&&rt.data.forEach(Qt=>{const on=kb(ot,{x:Qt.handles.start.y,y:Qt.handles.start.x}),cn=kb(ot,{x:Qt.handles.end.y,y:Qt.handles.end.x});console.log("Importing legacy annotation:"),console.log(" Image ID:",ot),console.log(" Start World:",on),console.log(" End World:",cn);const Gt=mt("imagePlaneModule",ot);console.log(rL);let xn=mt("frameOfReferenceUID",ot);!xn&&Gt&&Gt.frameOfReferenceUID&&(xn=Gt.frameOfReferenceUID);const er=Gt!=null&&Gt.rowCosines&&(Gt!=null&&Gt.columnCosines)?[Gt.rowCosines[1]*Gt.columnCosines[2]-Gt.rowCosines[2]*Gt.columnCosines[1],Gt.rowCosines[2]*Gt.columnCosines[0]-Gt.rowCosines[0]*Gt.columnCosines[2],Gt.rowCosines[0]*Gt.columnCosines[1]-Gt.rowCosines[1]*Gt.columnCosines[0]]:void 0;Array.isArray(er)&&er.length,typeof Qt.rotation=="number"&&Qt.rotation;const nr={annotationUID:Qt.uuid,metadata:{toolName:Ct,referencedImageId:ot,FrameOfReferenceUID:xn,viewPlaneNormal:er},data:{handles:{points:[on,cn],textBox:Qt.handles.textBox},text:Qt.text||""},visibility:Qt.visible!==!1,active:Qt.active||!1};Rr.addAnnotation(nr,nr.annotationUID)})})}),x.current&&x.current.render()},window[`importLegacyViewport_${de}`]=_e=>{let ye;try{ye=typeof _e=="string"?JSON.parse(_e):_e}catch{alert("Invalid legacy viewport JSON");return}const je=x.current;if(!je)return;const ot=`CT_${D??0}`,st=je.getViewport(ot);if(!st)return;const ut={};if(ye.voi&&(ut.voiRange={lower:ye.voi.windowCenter-ye.voi.windowWidth/2,upper:ye.voi.windowCenter+ye.voi.windowWidth/2}),typeof ye.invert=="boolean"&&(ut.invert=ye.invert),typeof ye.pixelReplication=="boolean"&&(ut.interpolationType=ye.pixelReplication?0:1),typeof ye.hflip=="boolean"&&(ut.hflip=ye.hflip),typeof ye.vflip=="boolean"&&(ut.vflip=ye.vflip),typeof st.setProperties=="function"&&st.setProperties(ut),ye.translation||ye.scale){const rt=st.getCamera?st.getCamera():{};ye.translation&&(rt.translation={...rt.translation,...ye.translation}),ye.scale&&(rt.parallelScale=200/ye.scale),console.log("Applying legacy camera properties:",rt),typeof st.setCamera=="function"&&st.setCamera(rt)}typeof ye.rotation=="number"&&st.setRotation(ye.rotation),st.render(),Qn(D??0,st)},()=>{window[`exportViewerState_${de}`]=void 0,window[`importViewerState_${de}`]=void 0,window[`exportAnnotations_${de}`]=void 0,window[`importAnnotations_${de}`]=void 0,window[`importLegacyAnnotations_${de}`]=void 0,window[`importLegacyViewport_${de}`]=void 0,window[`jumpToSliceByImageId_${de}`]=void 0,window[`resetViewer_${de}`]=void 0,window[`truncateStack_${de}`]=void 0,window[`getCurrentStackPosition_${de}`]=void 0,window[`loadAdditionalStack_${de}`]=void 0,window[`getViewport_${de}`]=void 0,window[`getAllViewports_${de}`]=void 0}},[z,Fe,L,T,I,W,oe,V,E,M,E,M,O]),Nt.useEffect(()=>{function de(Ue){if(console.log("Handling arrow key navigation",Ue.key),console.log("activeViewport",D),D===null)return;const _e=x.current;if(!_e)return;const ye=_e.getViewport(`CT_${D}`);if(ye){if(console.log(ye),Fe[D]==="stack"){if(typeof ye.getCurrentImageIdIndex!="function"||typeof ye.setImageIdIndex!="function")return;const je=I[D];if(!je||je.length===0)return;Ue.key==="ArrowUp"||Ue.key==="ArrowRight"?(ps(ye,{delta:-1}),Ue.preventDefault()):(Ue.key==="ArrowDown"||Ue.key==="ArrowLeft")&&(ps(ye,{delta:1}),Ue.preventDefault())}Fe[D]==="volume"&&typeof ye.getSliceIndex=="function"&&typeof ye.getNumberOfSlices=="function"&&ye.getNumberOfSlices()>1&&(Ue.key==="ArrowUp"||Ue.key==="ArrowRight"?(ps(ye,{delta:-1}),Ue.preventDefault()):(Ue.key==="ArrowDown"||Ue.key==="ArrowLeft")&&(ps(ye,{delta:1}),Ue.preventDefault()))}}return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[D,Fe,I,Qn]);const ra=D!==null?L[D]:0,Uo=T[ra],fr=Uo==null?void 0:Uo.studyInstanceUID,[oo,yn]=Nt.useState(()=>Array(y).fill(null)),Qr=z.rows*z.cols,Da=[];for(let de=0;deee.current[de]=_e,style:{flex:1,border:Ue?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(de/z.cols)+1,gridColumn:de%z.cols+1,height:"100%",boxShadow:D===de?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:D===de?10:1},onClick:()=>{b(de),Z(!1)},onDoubleClick:()=>rn(de),children:[lt.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{oe(_e=>{const ye=[..._e];return ye[de]=_e[de]==="stack"?"volume":"stack",ye})},children:Fe[de]==="stack"?"Volume":"Stack"}),Fe[de]==="volume"&<.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const _e=x.current,ye=_e==null?void 0:_e.getViewport(`CT_${de}`);ye&&ye.setOrientation&&(ye.setOrientation("axial"),ye.render())},children:"Axial"}),lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const _e=x.current,ye=_e==null?void 0:_e.getViewport(`CT_${de}`);ye&&ye.setOrientation&&(ye.setOrientation("sagittal"),ye.render())},children:"Sagittal"}),lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const _e=x.current,ye=_e==null?void 0:_e.getViewport(`CT_${de}`);ye&&ye.setOrientation&&(ye.setOrientation("coronal"),ye.render())},children:"Coronal"})]}),lt.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:_e=>{_e.stopPropagation();const ye=ee.current[de];document.fullscreenElement===ye?document.exitFullscreen():ye!=null&&ye.requestFullscreen?ye.requestFullscreen():ye!=null&&ye.webkitRequestFullscreen?ye.webkitRequestFullscreen():ye!=null&&ye.msRequestFullscreen&&ye.msRequestFullscreen()},onMouseEnter:()=>g(de),onMouseLeave:()=>g(null),children:[lt.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),h===de&<.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===ee.current[de]?"Exit Fullscreen":"Fullscreen"})]}),Fe[de]==="stack"&&S&&(()=>{var on;const _e=I[de],je=(Rr.getAllAnnotations()||[]).filter(cn=>cn.metadata&&cn.metadata.referencedImageId&&_e.includes(cn.metadata.referencedImageId)&&cn.metadata.toolName!==ua.toolName);if(!je.length)return null;const ot=x.current,st=ot==null?void 0:ot.getViewport(`CT_${de}`),ut=((on=st==null?void 0:st.getCurrentImageIdIndex)==null?void 0:on.call(st))??0,rt=_e[ut],Ct=je.filter(cn=>cn.metadata.referencedImageId===rt),Qt=oo[de];return lt.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[lt.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const cn=x.current,Gt=cn==null?void 0:cn.getViewport(`CT_${de}`);if(!Gt||typeof Gt.getCurrentImageIdIndex!="function")return;const xn=Gt.getCurrentImageIdIndex(),er=Bb(xn,_e,je,-1);if(er!==null&&typeof Gt.setImageIdIndex=="function"){Aa(Gt.element,{imageIndex:er}),Qn(de,Gt);const nr=_e[er],or=je.filter(qn=>qn.metadata.referencedImageId===nr);Pn(de,or.length>0?or[0].annotationUID:null)}},children:lt.jsx("span",{"aria-hidden":"true",children:"◀"})}),lt.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const cn=x.current,Gt=cn==null?void 0:cn.getViewport(`CT_${de}`);if(!Gt||typeof Gt.getCurrentImageIdIndex!="function")return;const xn=Gt.getCurrentImageIdIndex(),er=Bb(xn,_e,je,1);if(er!==null&&typeof Gt.setImageIdIndex=="function"){Aa(Gt.element,{imageIndex:er}),Qn(de,Gt);const nr=_e[er],or=je.filter(qn=>qn.metadata.referencedImageId===nr);Pn(de,or.length>0?or[0].annotationUID:null)}},children:lt.jsx("span",{"aria-hidden":"true",children:"▶"})}),Ct.length>0&<.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:Ct.map(cn=>lt.jsxs("div",{style:{display:"flex",alignItems:"center",background:Qt===cn.annotationUID?"rgb(4, 225, 0)":"#444",color:Qt===cn.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Qt===cn.annotationUID?"2px solid #1976d2":"none",fontWeight:Qt===cn.annotationUID?"bold":"normal"},onClick:()=>Pn(de,cn.annotationUID),children:[lt.jsxs("span",{style:{marginRight:4},children:[Qt===cn.annotationUID?"★ ":"",cn.metadata.toolName||"Annotation"]}),lt.jsx("button",{style:{background:"#b71c1c",color:"#fff",border:"none",borderRadius:"50%",width:20,height:20,fontSize:"13px",fontWeight:"bold",cursor:"pointer",marginLeft:2,display:"flex",alignItems:"center",justifyContent:"center",opacity:.85},title:"Delete this annotation","aria-label":"Delete annotation",onClick:Gt=>{Gt.stopPropagation(),$n(de,cn.annotationUID,Ct)},children:"🗑️"})]},cn.annotationUID))})]})})(),lt.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:Fe[de]==="stack"?lt.jsxs(lt.Fragment,{children:[lt.jsxs("div",{children:["Image: ",(Fi=se[de])==null?void 0:Fi.index," / ",(ao=se[de])==null?void 0:ao.total]}),lt.jsxs("div",{children:["WC: ",(Ui=se[de])==null?void 0:Ui.windowCenter,"   WW: ",(mi=se[de])==null?void 0:mi.windowWidth]})]}):lt.jsxs("div",{children:["Slice: ",(Ka=se[de])==null?void 0:Ka.index," / ",(Bo=se[de])==null?void 0:Bo.total,((Bi=se[de])==null?void 0:Bi.slicePosition)&<.jsxs("span",{children:["   (",(qa=se[de])==null?void 0:qa.slicePosition,")"]}),lt.jsx("br",{}),"WC: ",(Gi=se[de])==null?void 0:Gi.windowCenter,"   WW: ",(ia=se[de])==null?void 0:ia.windowWidth]})}),lt.jsx("div",{style:{position:"absolute",right:8,bottom:8,zIndex:10,pointerEvents:"auto"},children:lt.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:ht[de]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:_e=>_e.stopPropagation(),children:[lt.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:_e=>{_e.stopPropagation(),wt(ye=>{const je=[...ye];return je[de]=!je[de],je})},children:["Presets",lt.jsx("span",{style:{float:"right",fontWeight:"normal"},children:ht[de]?"▲":"▼"})]}),ht[de]&<.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:11,pointerEvents:"auto"},onClick:_e=>_e.stopPropagation(),children:Hxe.map(_e=>lt.jsx("button",{style:{display:"block",width:"100%",margin:"2px 0",background:"#333",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:"4px 0",fontSize:"13px",opacity:.9},onClick:ye=>{ye.stopPropagation(),pi(de,_e.center,_e.width),wt(je=>{const ot=[...je];return ot[de]=!1,ot})},children:_e.name},_e.name))})]})}),Fe[de]==="stack"&&I[de]&<.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:I[de].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"none",flexDirection:"column",padding:0},children:lt.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden"},children:I[de].map((_e,ye)=>{const je=!!mt("imagePlaneModule",_e),ot=x.current;let st=-1;if(ot&&typeof ot.getViewport=="function"){const rt=ot.getViewport(`CT_${de}`);rt&&typeof rt.getCurrentImageIdIndex=="function"&&(st=rt.getCurrentImageIdIndex())}const ut=ye===st;return lt.jsx("div",{style:{width:"100%",height:`${100/I[de].length}%`,background:ut?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":je?"linear-gradient(to right, #4caf50 60%, #2196f3 100%)":"#444",opacity:je?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:ye{const rt=x.current,Ct=rt==null?void 0:rt.getViewport(`CT_${de}`);Ct&&typeof Ct.setImageIdIndex=="function"&&Fe[de]==="stack"&&(Aa(Ct.element,{imageIndex:ye}),Qn(de,Ct))}},_e)})})}),Fe[de]==="volume"&&(()=>{const _e=x.current,ye=_e==null?void 0:_e.getViewport(`CT_${de}`);let je=0,ot=0;return ye&&typeof ye.getNumberOfSlices=="function"&&typeof ye.getSliceIndex=="function"&&(je=ye.getNumberOfSlices(),ot=ye.getSliceIndex()),je>1?lt.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:lt.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:st=>{const rt=st.currentTarget.getBoundingClientRect(),Ct=st.clientY-rt.top,Qt=Math.floor(Ct/rt.height*je),on=x.current,cn=on==null?void 0:on.getViewport(`CT_${de}`);cn&&(Aa(cn.element,{imageIndex:Qt}),cn.render(),Qn(de,cn))},children:Array.from({length:je}).map((st,ut)=>{const rt=ut===ot;return lt.jsx("div",{style:{width:"100%",height:`${100/je}%`,minHeight:rt?1:0,background:rt?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:rt?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:ut1||!I[de]||I[de].length===0)&<.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:lt.jsxs("div",{style:{position:"relative"},children:[lt.jsxs("button",{style:{background:"#222",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"2px 8px",fontSize:"13px",marginRight:"6px",minWidth:120,textAlign:"left",cursor:"pointer"},onClick:()=>v(p===de?null:de),"aria-haspopup":"listbox","aria-expanded":p===de,children:[(()=>{const _e=T[L[de]||0],ye=_e==null?void 0:_e.studyInstanceUID,ot=fr&&ye&&fr===ye?"#4caf50":"#888";return lt.jsxs("span",{children:[lt.jsx("span",{style:{color:ot,fontWeight:"bold",marginRight:6,fontSize:"16px",verticalAlign:"middle"},children:"●"}),"Stack ",L[de]+1," (",(_e==null?void 0:_e.imageIds.length)||0," images)"]})})(),lt.jsx("span",{style:{float:"right",fontSize:"12px"},children:"▼"})]}),p===de&<.jsx("div",{ref:_e=>{_e&&_e.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:180,maxHeight:220,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin"},role:"listbox",onMouseDown:_e=>_e.stopPropagation(),onWheel:_e=>{const ye=_e.currentTarget,{scrollTop:je,scrollHeight:ot,clientHeight:st}=ye,ut=je===0,rt=je+st>=ot-1;_e.deltaY<0&&ut||_e.deltaY>0&&rt||(_e.stopPropagation(),_e.preventDefault(),ye.scrollTop+=_e.deltaY)},onBlur:_e=>{const ye=_e.relatedTarget,je=_e.currentTarget.parentElement;je!=null&&je.contains(ye)||setTimeout(()=>v(null),100)},children:T.map((_e,ye)=>{const je=_e.studyInstanceUID,st=fr&&je&&fr===je?"#4caf50":"#888",ut=_e.imageIds.length===0;return lt.jsxs("div",{role:"option","aria-selected":L[de]===ye,style:{padding:"6px 12px",background:L[de]===ye?"#444":"#222",color:ut?"#aaa":"#fff",cursor:ut?"not-allowed":"pointer",display:"flex",alignItems:"center",fontWeight:L[de]===ye?"bold":"normal",borderBottom:"1px solid #333",userSelect:"none",opacity:ut?.6:1},tabIndex:-1,onMouseDown:rt=>{rt.preventDefault(),ut||(j(de,ye),v(null))},children:[lt.jsx("span",{style:{color:st,fontWeight:"bold",marginRight:8,fontSize:"16px",verticalAlign:"middle"},children:"●"}),"Stack ",ye+1," (",_e.imageIds.length," images",ut&<.jsx("span",{style:{color:"#f44336",marginLeft:6},children:"(empty)"}),")"]},ye)})})]})})]},de))}return lt.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:"#222",padding:"12px",overflow:"hidden"},children:[k&<.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:k==="annotations"?"Loading Annotations...":"Loading Viewer State..."}),lt.jsxs("div",{children:[lt.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:Be?250:-20,zIndex:200,width:40,height:40,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>ft(de=>!de),"aria-label":"Open menu",children:"☰"}),Be&<.jsx("div",{style:{position:"absolute",top:0,left:0,width:220,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:lt.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[lt.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",lt.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>ft(!1),"aria-label":"Close menu",children:"×"})]}),lt.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>{var de;return(de=Ut.current)==null?void 0:de.click()},children:"Load DICOM Folder"}),lt.jsx("input",{ref:Ut,type:"file",style:{display:"none"},multiple:!0,onChange:Sn,accept:".dcm,application/dicom"}),lt.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[lt.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:Ne,onChange:de=>ze(de.target.checked),style:{accentColor:"#666"}}),lt.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),lt.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:fn,children:"Show DICOM Metadata"}),lt.jsxs("button",{style:{padding:"10px 18px",background:Y?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>re(de=>!de),children:[Y?"Disable":"Enable"," Cross Reference Lines"]}),lt.jsxs("button",{style:{padding:"10px 18px",background:ue?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ce(de=>!de),children:[ue?"Disable":"Enable"," Reference Lines"]}),lt.jsx("button",{onClick:B,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),lt.jsx("button",{style:{padding:"10px 18px",background:ie?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ae(de=>!de),children:ie?"Disable Alt Key for Reference Cursors":"Enable Alt Key for Reference Cursors"}),lt.jsxs("button",{style:{padding:"10px 18px",background:S?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>_(de=>!de),children:[S?"Hide":"Show"," Annotation Navigation"]})]})})]}),lt.jsxs("div",{className:"grid-menu-hover-container",style:{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"column",alignItems:"center",width:"auto",height:"48px",pointerEvents:"none"},children:[lt.jsx("div",{style:{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",width:80,height:14,zIndex:1,pointerEvents:"auto",background:"transparent"},onMouseEnter:()=>_n(!0),onFocus:()=>_n(!0),tabIndex:-1}),lt.jsx("button",{style:{position:"relative",top:Pt?"0":"-22px",opacity:Pt?1:.5,transition:"top 0.25s cubic-bezier(.4,2,.6,1), opacity 0.2s",padding:"6px 16px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginLeft:"4px",marginRight:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",pointerEvents:Pt?"auto":"none",zIndex:2,display:Pt?"block":"none"},title:"Toggle Fullscreen",onClick:()=>{const de=document.querySelector(".dicom-viewer-root");de&&(document.fullscreenElement===de?document.exitFullscreen():de.requestFullscreen?de.requestFullscreen():de.webkitRequestFullscreen?de.webkitRequestFullscreen():de.msRequestFullscreen&&de.msRequestFullscreen())},children:"⛶ Fullscreen"}),lt.jsxs("button",{className:"grid-menu-btn",style:{position:"relative",top:Pt?"0":"-22px",opacity:Pt?1:.5,transition:"top 0.25s cubic-bezier(.4,2,.6,1), opacity 0.2s",padding:"6px 16px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginRight:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",pointerEvents:Pt?"auto":"none",zIndex:2,display:Pt?"block":"none"},onMouseLeave:()=>_n(!1),onBlur:()=>_n(!1),onClick:()=>Z(de=>!de),tabIndex:0,children:["Grid: ",z.rows,"x",z.cols," ▼"]}),K&<.jsx("div",{style:{position:"absolute",top:"110%",left:"50%",transform:"translateX(-50%)",background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, 40px)",gap:"8px",zIndex:200,pointerEvents:"auto"},children:we.map(de=>lt.jsxs("button",{style:{width:"40px",height:"40px",background:de.rows===z.rows&&de.cols===z.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px"},onClick:()=>{sn(),W({rows:de.rows,cols:de.cols}),Z(!1)},children:[de.rows,"x",de.cols]},`${de.rows}x${de.cols}`))})]}),lt.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"grid",margin:3,gridTemplateRows:`repeat(${z.rows}, 1fr)`,gridTemplateColumns:`repeat(${z.cols}, 1fr)`,gap:"5px",zIndex:1},children:Da}),lt.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:20,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>d(!0),children:"Settings"}),u&<.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>d(!1),children:lt.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative"},onClick:de=>de.stopPropagation(),children:[lt.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),lt.jsxs("div",{style:{marginBottom:"24px"},children:[lt.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),Fb.map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," Button:"]}),lt.jsx("select",{value:gt[de.value],onChange:Ue=>Ie(_e=>({..._e,[de.value]:Ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:ng.map(Ue=>lt.jsx("option",{value:Ue.value,children:Ue.label},Ue.value))})]},de.value)),lt.jsxs("div",{style:{margin:"12px 0"},children:[lt.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Ee(de=>!de),children:[pe?"Hide":"Show"," Advanced Mouse Bindings"]}),pe&<.jsx("div",{style:{marginTop:8},children:Xm.slice(3).map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label,":"]}),lt.jsxs("select",{value:gt[de.value]||"",onChange:Ue=>Ie(_e=>({..._e,[de.value]:Ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(Ue=>lt.jsx("option",{value:Ue.value,children:Ue.label},Ue.value))]})]},de.value))})]}),lt.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),Fb.map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," + Ctrl:"]}),lt.jsxs("select",{value:$e[de.value]||"",onChange:Ue=>tt(_e=>({..._e,[de.value]:Ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(Ue=>lt.jsx("option",{value:Ue.value,children:Ue.label},Ue.value))]})]},de.value+"_ctrl")),lt.jsxs("div",{style:{margin:"12px 0"},children:[lt.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Se(de=>!de),children:[Oe?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),Oe&<.jsx("div",{style:{marginTop:8},children:Xm.slice(3).map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," + Ctrl:"]}),lt.jsxs("select",{value:$e[de.value]||"",onChange:Ue=>tt(_e=>({..._e,[de.value]:Ue.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(Ue=>lt.jsx("option",{value:Ue.value,children:Ue.label},Ue.value))]})]},de.value+"_ctrl"))})]})]}),lt.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>d(!1),"aria-label":"Close",children:"×"})]})}),Lt&<.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>xt(!1),children:lt.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:de=>de.stopPropagation(),children:[lt.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),Ft,lt.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>xt(!1),"aria-label":"Close",children:"×"})]})})]})}function Kxe(t){console.log("Setting up tools...",t),Ci(j0),Ci(H0),Ci(id),Ci(q0),Ci(K0),Ci(Iu),Ci(nl),Ci(Ou),Ci(tl),Ci(od),Ci(bu),Ci(ic),Ci(X0),Ci(ua),Ci(Fs),Ci(Gf),Ci(Z0);let e=Kr(t);return e||(e=hN(t),e.addTool(H0.toolName),e.addTool(j0.toolName),e.addTool(q0.toolName),e.addTool(id.toolName,{loop:!1}),e.addTool(K0.toolName),e.addTool(Iu.toolName),e.addTool(Z0.toolName,{getTextCallback:()=>""}),e.addTool(Ou.toolName),e.addTool(nl.toolName,{statsCalculator:()=>null}),e.addTool(tl.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(od.toolName,{getTextCallback:()=>""}),e.addTool(bu.toolName,{calculateStats:!1}),e.addTool(ic.toolName,{}),e.addTool(X0.toolName,{}),e.addTool(Gf.toolName),e.addTool(ua.toolName)),e}function Bb(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const Gb=t=>t.map(e=>e.startsWith("wadouri:")?e:`wadouri:${e}`);function dG(){document.querySelectorAll(".dicom-viewer-test-root").forEach(r=>{const n=r.id||"",i=()=>qxe();Tx(r).render(lt.jsx(Ub,{container_id:n,imageStacks:i}))}),document.querySelectorAll(".dicom-viewer-root").forEach(r=>{const n=r.id||"";let i;const o=r.getAttribute("data-images");if(o){let f;try{f=JSON.parse(o)}catch(u){console.error("Invalid data-images JSON:",u),f=[]}Array.isArray(f)&&f.length>0&&typeof f[0]=="string"?i=()=>Promise.resolve([Gb(f)]):Array.isArray(f)?i=()=>Promise.resolve(f.map(u=>Array.isArray(u)?Gb(u):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([[]]);const a=r.getAttribute("data-auto-cache-stack"),s=a==="true"||a==="1",c=r.getAttribute("data-annotationjson"),l=r.getAttribute("data-viewerstate");console.log("Mounting DICOM viewer:"),console.log(l,c,s),Tx(r).render(lt.jsx(Ub,{container_id:n,imageStacks:i,autoCacheStack:s,annotationJson:c||void 0,viewerState:l||void 0}))})}dG();window.mountDicomViewers=dG; +`,Tt.push(pt);var Xn=Uu(Function,Tt).apply(null,dn);return Xn}function Go($,H,R,U,q,le){T(H>0);var he=so(H,R);q=gr(U,q),Vi([],[$],function(ve){ve=ve[0];var Te="constructor "+ve.name;if(ve.registeredClass.constructor_body===void 0&&(ve.registeredClass.constructor_body=[]),ve.registeredClass.constructor_body[H-1]!==void 0)throw new oo("Cannot register multiple constructors with identical number of parameters ("+(H-1)+") for class '"+ve.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return ve.registeredClass.constructor_body[H-1]=()=>{ci("Cannot construct "+ve.name+" due to unbound types",he)},Vi([],he,function(be){return be.splice(1,0,null),ve.registeredClass.constructor_body[H-1]=Wi(Te,be,null,q,le),[]}),[]})}function fc($,H,R,U,q,le,he,ve){var Te=so(R,U);H=fr(H),le=gr(q,le),Vi([],[$],function(be){be=be[0];var ke=be.name+"."+H;H.startsWith("@@")&&(H=Symbol[H.substring(2)]),ve&&be.registeredClass.pureVirtualFunctions.push(H);function Je(){ci("Cannot call "+ke+" due to unbound types",Te)}var pt=be.registeredClass.instancePrototype,Mt=pt[H];return Mt===void 0||Mt.overloadTable===void 0&&Mt.className!==be.name&&Mt.argCount===R-2?(Je.argCount=R-2,Je.className=be.name,pt[H]=Je):(qn(pt,H,ke),pt[H].overloadTable[R-2]=Je),Vi([],Te,function(Tt){var dn=Wi(ke,Tt,be,le,he);return pt[H].overloadTable===void 0?(dn.argCount=R-2,pt[H]=dn):pt[H].overloadTable[R-2]=dn,[]}),[]})}var Ja=[],Ji=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function fl($){$>4&&--Ji[$].refcount===0&&(Ji[$]=void 0,Ja.push($))}function Bu(){for(var $=0,H=5;H($||yn("Cannot use deleted val. handle = "+$),Ji[$].value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:{var H=Ja.length?Ja.pop():Ji.length;return Ji[H]={refcount:1,value:$},H}}}};function hl($,H){H=fr(H),Qr($,{name:H,fromWireType:function(R){var U=Za.toValue(R);return fl(R),U},toWireType:function(R,U){return Za.toHandle(U)},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:null})}function dc($){if($===null)return"null";var H=typeof $;return H==="object"||H==="array"||H==="function"?$.toString():""+$}function Wu($,H){switch(H){case 2:return function(R){return this.fromWireType(Y[R>>2])};case 3:return function(R){return this.fromWireType(re[R>>3])};default:throw new TypeError("Unknown float type: "+$)}}function zu($,H,R){var U=To(R);H=fr(H),Qr($,{name:H,fromWireType:function(q){return q},toWireType:function(q,le){return le},argPackAdvance:8,readValueFromPointer:Wu(H,U),destructorFunction:null})}function $u($,H,R,U,q,le){var he=so(H,R);$=fr($),q=gr(U,q),At($,function(){ci("Cannot call "+$+" due to unbound types",he)},H-1),Vi([],he,function(ve){var Te=[ve[0],null].concat(ve.slice(1));return Xa($,Wi($,Te,null,q,le),H-1),[]})}function ju($,H,R){switch(H){case 0:return R?function(q){return V[q]}:function(q){return G[q]};case 1:return R?function(q){return A[q>>1]}:function(q){return k[q>>1]};case 2:return R?function(q){return F[q>>2]}:function(q){return j[q>>2]};default:throw new TypeError("Unknown integer type: "+$)}}function Hu($,H,R,U,q){H=fr(H);var le=To(R),he=Je=>Je;if(U===0){var ve=32-8*R;he=Je=>Je<>>ve}var Te=H.includes("unsigned"),be=(Je,pt)=>{},ke;Te?ke=function(Je,pt){return be(pt,this.name),pt>>>0}:ke=function(Je,pt){return be(pt,this.name),pt},Qr($,{name:H,fromWireType:he,toWireType:ke,argPackAdvance:8,readValueFromPointer:ju(H,le,U!==0),destructorFunction:null})}function Ku($,H,R){var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],q=U[H];function le(he){he=he>>2;var ve=j,Te=ve[he],be=ve[he+1];return new q(L,be,Te)}R=fr(R),Qr($,{name:R,fromWireType:le,argPackAdvance:8,readValueFromPointer:le},{ignoreDuplicateRegistrations:!0})}function qu($,H){H=fr(H);var R=H==="std::string";Qr($,{name:H,fromWireType:function(U){var q=j[U>>2],le=U+4,he;if(R)for(var ve=le,Te=0;Te<=q;++Te){var be=le+Te;if(Te==q||G[be]==0){var ke=be-ve,Je=b(ve,ke);he===void 0?he=Je:(he+="\0",he+=Je),ve=be+1}}else{for(var pt=new Array(q),Te=0;Te>2]=le,R&&he)P(q,Te,le+1);else if(he)for(var be=0;be255&&(me(Te),yn("String has UTF-16 code units that do not fit in 8 bits")),G[Te+be]=ke}else for(var be=0;be>1,q=U+H/2;!(U>=q)&&k[U];)++U;if(R=U<<1,R-$>32&&gl)return gl.decode(G.subarray($,R));for(var le="",he=0;!(he>=H/2);++he){var ve=A[$+he*2>>1];if(ve==0)break;le+=String.fromCharCode(ve)}return le}function pl($,H,R){if(R===void 0&&(R=2147483647),R<2)return 0;R-=2;for(var U=H,q=R<$.length*2?R/2:$.length,le=0;le>1]=he,H+=2}return A[H>>1]=0,H-U}function ml($){return $.length*2}function Yu($,H){for(var R=0,U="";!(R>=H/4);){var q=F[$+R*4>>2];if(q==0)break;if(++R,q>=65536){var le=q-65536;U+=String.fromCharCode(55296|le>>10,56320|le&1023)}else U+=String.fromCharCode(q)}return U}function hc($,H,R){if(R===void 0&&(R=2147483647),R<4)return 0;for(var U=H,q=U+R-4,le=0;le<$.length;++le){var he=$.charCodeAt(le);if(he>=55296&&he<=57343){var ve=$.charCodeAt(++le);he=65536+((he&1023)<<10)|ve&1023}if(F[H>>2]=he,H+=4,H+4>q)break}return F[H>>2]=0,H-U}function vl($){for(var H=0,R=0;R<$.length;++R){var U=$.charCodeAt(R);U>=55296&&U<=57343&&++R,H+=4}return H}function yl($,H,R){R=fr(R);var U,q,le,he,ve;H===2?(U=Xu,q=pl,he=ml,le=()=>k,ve=1):H===4&&(U=Yu,q=hc,he=vl,le=()=>j,ve=2),Qr($,{name:R,fromWireType:function(Te){for(var be=j[Te>>2],ke=le(),Je,pt=Te+4,Mt=0;Mt<=be;++Mt){var Tt=Te+4+Mt*H;if(Mt==be||ke[Tt>>ve]==0){var dn=Tt-pt,ln=U(pt,dn);Je===void 0?Je=ln:(Je+="\0",Je+=ln),pt=Tt+H}}return me(Te),Je},toWireType:function(Te,be){typeof be!="string"&&yn("Cannot pass non-string to C++ string type "+R);var ke=he(be),Je=te(4+ke+H);return j[Je>>2]=ke>>ve,q(be,Je+4,ke+H),Te!==null&&Te.push(me,Je),Je},argPackAdvance:8,readValueFromPointer:Mr,destructorFunction:function(Te){me(Te)}})}function gc($,H,R,U,q,le){bn[$]={name:fr(H),rawConstructor:gr(R,U),rawDestructor:gr(q,le),fields:[]}}function Ju($,H,R,U,q,le,he,ve,Te,be){bn[$].fields.push({fieldName:fr(H),getterReturnType:R,getter:gr(U,q),getterContext:le,setterArgumentType:he,setter:gr(ve,Te),setterContext:be})}function wl($,H){H=fr(H),Qr($,{isVoid:!0,name:H,argPackAdvance:0,fromWireType:function(){},toWireType:function(R,U){}})}function Zu($){$>4&&(Ji[$].refcount+=1)}function xl($,H){var R=ft[$];return R===void 0&&yn(H+" has unknown type "+vi($)),R}function Qu($,H){$=xl($,"_emval_take_value");var R=$.readValueFromPointer(H);return Za.toHandle(R)}function ef(){Ne("")}function tf($,H,R){G.copyWithin($,H,H+R)}function nf(){return 2147483648}function pc($){try{return S.grow($-L.byteLength+65535>>>16),ue(S.buffer),1}catch{}}function mc($){var H=G.length;$=$>>>0;var R=nf();if($>R)return!1;let U=(Te,be)=>Te+(be-Te%be)%be;for(var q=1;q<=4;q*=2){var le=H*(1+.2/q);le=Math.min(le,$+100663296);var he=Math.min(R,U(Math.max($,le),65536)),ve=pc(he);if(ve)return!0}return!1}function oa($){return 52}function Ia($,H,R,U,q){return 70}var Eo=[null,[],[]];function Cl($,H){var R=Eo[$];H===0||H===10?(($===1?w:x)(D(R,0)),R.length=0):R.push(H)}function Sl($,H,R,U){for(var q=0,le=0;le>2],ve=j[H+4>>2];H+=8;for(var Te=0;Te>2]=q,0}function vc($){return $}function _l($){var H=o["_"+$];return H}function Is($,H){V.set($,H)}function Tl($,H,R,U,q){var le={string:Tt=>{var dn=0;if(Tt!=null&&Tt!==0){var ln=(Tt.length<<2)+1;dn=ot(ln),P(Tt,dn,ln)}return dn},array:Tt=>{var dn=ot(Tt.length);return Is(Tt,dn),dn}};function he(Tt){return H==="string"?b(Tt):H==="boolean"?!!Tt:Tt}var ve=_l($),Te=[],be=0;if(U)for(var ke=0;ke0||(_e(),Z>0))return;function H(){et||(et=!0,o.calledRun=!0,!_&&(B(),a(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),O()))}o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),H()},1)):H()}if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Ye(),o.ready}})();t.exports=r})(cG);var Mxe=cG.exports;const Pxe=ac(Mxe),Rxe=new URL("/static/dv3d/openjphjs.wasm",import.meta.url),Sg={codec:void 0,decoder:void 0,decodeConfig:{}};function Lxe(t,e,r){const n={width:e,height:r};for(;t>0;)n.width=Math.ceil(n.width/2),n.height=Math.ceil(n.height/2),t--;return n}function Axe(t){if(Sg.decodeConfig=t,Sg.codec)return Promise.resolve();const e=Pxe({locateFile:r=>r.endsWith(".wasm")?Rxe.toString():r});return new Promise((r,n)=>{e.then(i=>{Sg.codec=i,Sg.decoder=new i.HTJ2KDecoder,r()},n)})}async function Nxe(t,e){await Axe();const r=new Sg.codec.HTJ2KDecoder,n=r.getEncodedBuffer(t.length);n.set(t);const i=e.decodeLevel||0;r.decodeSubResolution(i);const o=r.getFrameInfo();if(e.decodeLevel>0){const{width:E,height:D}=Lxe(e.decodeLevel,o.width,o.height);o.width=E,o.height=D}const a=r.getDecodedBuffer();new Uint8Array(a.length).set(a);const c=`x: ${r.getImageOffset().x}, y: ${r.getImageOffset().y}`,l=r.getNumDecompositions(),f=r.getNumLayers(),u=["unknown","LRCP","RLCP","RPCL","PCRL","CPRL"][r.getProgressionOrder()+1],d=r.getIsReversible(),h=`${r.getBlockDimensions().width} x ${r.getBlockDimensions().height}`,g=`${r.getTileSize().width} x ${r.getTileSize().height}`,p=`${r.getTileOffset().x}, ${r.getTileOffset().y}`,v=`${a.length.toLocaleString()} bytes`,y=`${(a.length/n.length).toFixed(2)}:1`,m={columns:o.width,rows:o.height,bitsPerPixel:o.bitsPerSample,signed:o.isSigned,bytesPerPixel:e.bytesPerPixel,componentsPerPixel:o.componentCount};let w=kxe(o,a);const{buffer:x,byteOffset:C,byteLength:S}=w,_=x.slice(C,C+S);w=new w.constructor(_);const T={imageOffset:c,numDecompositions:l,numLayers:f,progessionOrder:u,reversible:d,blockDimensions:h,tileSize:g,tileOffset:p,decodedSize:v,compressionRatio:y};return{...e,pixelData:w,imageInfo:m,encodeOptions:T,...T,...m}}function kxe(t,e){return t.bitsPerSample>8?t.isSigned?new Int16Array(e.buffer,e.byteOffset,e.byteLength/2):new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2):t.isSigned?new Int8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Vxe(t,e){const r=t.length,{rescaleSlope:n,rescaleIntercept:i,suvbw:o,doseGridScaling:a}=e;if(e.modality==="PT"&&typeof o=="number"&&!isNaN(o))for(let s=0;s>o;let a=t.pixelData;t.pixelDataLength=t.pixelData.length;const{min:s,max:c}=X5(t.pixelData),l=typeof e.allowFloatRendering<"u"?e.allowFloatRendering:!0;let f=dE(t.photometricInterpretation)&&((m=e.targetBuffer)==null?void 0:m.offset)===void 0;const d=((w=e.preScale)==null?void 0:w.enabled)&&Object.values(e.preScale.scalingParameters).some(C=>typeof C=="number"&&!Number.isInteger(C)),h=!e.preScale.enabled||!l&&d,g=(x=e.targetBuffer)==null?void 0:x.type;if(g&&e.preScale.enabled&&!h){const C=e.preScale.scalingParameters,S=sS(s,c,C);f=!v3e(S.min,S.max,Ab[g])}g&&!f?a=Gxe(e,t,Ab,a):e.preScale.enabled&&!h?a=Wxe(e,s,c,t):a=lG(s,c,t);let p=s,v=c;if(e.preScale.enabled&&!h){const C=e.preScale.scalingParameters;if(uG(C),Bxe(C)){Vxe(a,C),t.preScale={...e.preScale,scaled:!0};const _=sS(s,c,C);p=_.min,v=_.max}}else h&&(t.preScale={enabled:!0,scaled:!1},p=s,v=c);t.pixelData=a,t.smallestPixelValue=p,t.largestPixelValue=v;const y=new Date().getTime();return t.decodeTimeInMS=y-r,t}function Bxe(t){const{rescaleSlope:e,rescaleIntercept:r,modality:n,doseGridScaling:i,suvbw:o}=t;return typeof e=="number"&&typeof r=="number"||n==="RTDOSE"&&typeof i=="number"||n==="PT"&&typeof o=="number"}function Gxe(t,e,r,n){const{arrayBuffer:i,type:o,offset:a=0,length:s,rows:c}=t.targetBuffer,l=r[o];if(!l)throw new Error(`target array ${o} is not supported, or doesn't exist.`);c&&c!=e.rows&&$xe(e,t.targetBuffer,l);const f=e.pixelDataLength,u=a,d=s??f-u,h=e.pixelData;if(d!==h.length)throw new Error(`target array for image does not have the same length (${d}) as the decoded image length (${h.length}).`);const g=i?new l(i,u,d):new l(d);return g.set(h,0),n=g,n}function Wxe(t,e,r,n){const i=t.preScale.scalingParameters;uG(i);const o=sS(e,r,i);return lG(o.min,o.max,n)}function lG(t,e,r){const n=hE(t,e),i=new n(r.pixelData.length);return i.set(r.pixelData,0),i}function sS(t,e,r){const{rescaleSlope:n,rescaleIntercept:i,modality:o,doseGridScaling:a,suvbw:s}=r;return o==="PT"&&typeof s=="number"&&!isNaN(s)?{min:s*(t*n+i),max:s*(e*n+i)}:o==="RTDOSE"&&typeof a=="number"&&!isNaN(a)?{min:t*a,max:e*a}:typeof n=="number"&&typeof i=="number"?{min:n*t+i,max:n*e+i}:{min:t,max:e}}function uG(t){if(!t)throw new Error("options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.")}function zxe(t,e,r){const{samplesPerPixel:n}=t,{rows:i,columns:o}=e,a=i*o*n,s=new r(a),c=s.byteLength/a;return{pixelData:s,rows:i,columns:o,frameInfo:{...t.frameInfo,rows:i,columns:o},imageInfo:{...t.imageInfo,rows:i,columns:o,bytesPerPixel:c}}}function $xe(t,e,r){const n=zxe(t,e,r),{scalingType:i="replicate"}=e;return Fxe[i](t,n),Object.assign(t,n),t.pixelDataLength=t.pixelData.length,t}async function fG(t,e,r,n,i,o){const a=new Date().getTime();let s=null,c;switch(e){case"1.2.840.10008.1.2":case"1.2.840.10008.1.2.1":s=Ob(t,r);break;case"1.2.840.10008.1.2.2":s=rxe(t,r);break;case"1.2.840.10008.1.2.1.99":s=Ob(t,r);break;case"1.2.840.10008.1.2.5":s=ixe(t,r);break;case"1.2.840.10008.1.2.4.50":c={...t},s=dxe(r,c);break;case"1.2.840.10008.1.2.4.51":s=vxe(t,r);break;case"1.2.840.10008.1.2.4.57":s=Pb(t,r);break;case"1.2.840.10008.1.2.4.70":s=Pb(t,r);break;case"1.2.840.10008.1.2.4.80":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=Rb(r,c);break;case"1.2.840.10008.1.2.4.81":c={signed:t.pixelRepresentation===1,bytesPerPixel:t.bitsAllocated<=8?1:2,...t},s=Rb(r,c);break;case"1.2.840.10008.1.2.4.90":c={...t},s=Lb(r,c);break;case"1.2.840.10008.1.2.4.91":c={...t},s=Lb(r,c);break;case"3.2.840.10008.1.2.4.96":case"1.2.840.10008.1.2.4.201":case"1.2.840.10008.1.2.4.202":case"1.2.840.10008.1.2.4.203":c={...t},s=Nxe(r,c);break;default:throw new Error(`no decoder for transfer syntax ${e}`)}if(!s)throw new Error("decodePromise not defined");const l=await s,f=Uxe(l,i,a);return o==null||o(f),f}const jxe={decodeTask({imageFrame:t,transferSyntax:e,decodeConfig:r,options:n,pixelData:i,callbackFn:o}){return fG(t,e,i,r,n,o)}};iT(jxe);const Nb={constants:Q3e,convertRGBColorByPixel:xB,convertRGBColorByPlane:CB,convertYBRFullByPixel:SB,convertYBRFullByPlane:_B,convertPALETTECOLOR:TB,wadouri:S3e,wadors:K3e,init:rG,convertColorSpace:zB,createImage:Y5,decodeJPEGBaseline8BitColor:$B,getImageFrame:jB,getPixelData:vE,getMinMax:X5,isColorImage:dE,isJPEGBaseline8BitColor:J3e,internal:Vwe,decodeImageFrame:fG};class Z0 extends Ou{}VE(Z0,"toolName","NoLabelArrowAnnotate");function kb(t,e){const r=mt("imagePlaneModule",t);if(!r)return;const{rowCosines:n,columnCosines:i,imagePositionPatient:o,rowPixelSpacing:a,columnPixelSpacing:s}=r;if(!n||!i||!o)return;const c=s||1,l=a||1,f=n,u=i,d=o;return[d[0]+e.x*u[0]*c+e.y*f[0]*l,d[1]+e.x*u[1]*c+e.y*f[1]*l,d[2]+e.x*u[2]*c+e.y*f[2]*l]}window.cornerstone3dTools=Twe;const{MouseBindings:tg,KeyboardBindings:Vb}=nN,{IMAGE_RENDERED:qm}=Xe,Hxe=[{name:"Soft Tissue",center:40,width:400},{name:"Lung",center:-600,width:1500},{name:"Bone",center:300,width:1500},{name:"Brain",center:40,width:80},{name:"Abdomen",center:60,width:400}],ng=[{label:"Window/Level",value:H0.toolName},{label:"Pan",value:j0.toolName},{label:"Zoom",value:q0.toolName},{label:"Stack Scroll",value:id.toolName},{label:"Rotate",value:K0.toolName},{label:"Length",value:Iu.toolName},{label:"Probe",value:nl.toolName},{label:"Arrow (No Label)",value:Z0.toolName},{label:"Arrow Annotate",value:Ou.toolName},{label:"Rectangle ROI",value:tl.toolName},{label:"Ellipse ROI",value:od.toolName},{label:"Freehand ROI",value:bu.toolName},{label:"Freehand Contour Segmentation",value:ic.toolName},{label:"Sculptor",value:X0.toolName},{label:"Reference Cursors",value:ua.toolName}],Fb=[{label:"Left",value:"Primary"},{label:"Middle",value:"Auxiliary"},{label:"Right",value:"Secondary"}],Xm=[{label:"Left",value:"Primary",mask:1},{label:"Middle",value:"Auxiliary",mask:4},{label:"Right",value:"Secondary",mask:2},{label:"Left + Right",value:"Primary_and_Secondary",mask:3},{label:"Left + Middle",value:"Primary_and_Auxiliary",mask:5},{label:"Right + Middle",value:"Secondary_and_Auxiliary",mask:6},{label:"Left + Right + Middle",value:"Primary_and_Secondary_and_Auxiliary",mask:7},{label:"Fourth Button",value:"Fourth_Button",mask:8},{label:"Fifth Button",value:"Fifth_Button",mask:16},{label:"Mouse Wheel",value:"Wheel",mask:524288},{label:"Mouse Wheel + Left",value:"Wheel_Primary",mask:524289}];function Ub({container_id:t,imageStacks:e,autoCacheStack:r,annotationJson:n,viewerState:i,...o}){var Fi,ao,Ui,mi,Ka,Bo,Bi,qa,Gi,ia;const a=Nt.useRef(null),s=Nt.useRef(null),c=Nt.useRef(!1),[l,f]=Nt.useState(!1),[u,d]=Nt.useState(!1),[h,g]=Nt.useState(null),[p,v]=Nt.useState(null),y=9,m="renderingEngine_"+t,w="TOOL_GROUP_"+t,x=Nt.useRef(null),C=Nt.useRef(!1),[S,_]=Nt.useState(!0),[T,E]=Nt.useState([]),[D,b]=Nt.useState(0),[I,P]=Nt.useState(()=>Array(y).fill([])),M=de=>{typeof de=="function"?P(We=>{const Se=de(We);return console.log("setViewportImageIds (fn):",Se),Se}):(console.log("setViewportImageIds:",de),P(de))},[L,V]=Nt.useState(()=>Array(y).fill(0)),[G,A]=Nt.useState(!1),[k,F]=Nt.useState(null);Nt.useEffect(()=>{let de=!1;if(n||i){F(n?"annotations":"viewerState");const We=setTimeout(()=>{if(de)return;const Se=t||"default";if(n)try{const we=window[`importAnnotations_${Se}`]||window.importAnnotations;typeof we=="function"&&we(n)}catch(we){console.error("Failed to import annotations from prop:",we)}if(i)try{const we=window[`importViewerState_${Se}`]||window.importViewerState;typeof we=="function"&&we(i)}catch(we){console.error("Failed to import viewer state from prop:",we)}F(null)},2e3);return()=>{de=!0,clearTimeout(We),F(null)}}},[n,i,t]),Nt.useEffect(()=>{e().then(async de=>{const We=await Promise.all(de.map(async Se=>{let we;try{const Ge=Se[0];if(Ge&&Ge.startsWith("wadouri:")){const tt=Ge.slice(8),ut=await(await fetch(tt)).arrayBuffer();we=Tr.parseDicom(new Uint8Array(ut)).string("x0020000d")}}catch{}return{imageIds:Se,studyInstanceUID:we}}));E(We),await O(de[0]),M(Array(y).fill(de[0]||[]))})},[]);const j=async(de,We)=>{const Se=T[We];if(!Se)return;const we=Se.imageIds;oe(Ge=>{const tt=[...Ge];return tt[de]="stack",tt}),M(Ge=>{const tt=[...Ge];return tt[de]=we,tt}),V(Ge=>{const tt=[...Ge];return tt[de]=We,tt}),await O(we)},[Y,re]=Nt.useState(!1),[ue,ce]=Nt.useState(!0),[pe,Ee]=Nt.useState(!1),[Oe,_e]=Nt.useState(!1),B=()=>{console.log("Sorting viewport imageIds by slice location"),M(de=>{const We=de.map((Se,we)=>{if(!Se||Se.length===0)return Se;const st=[...Se.map(ut=>{const it=mt("imagePlaneModule",ut);let Ct=null;return it&&(it.sliceLocation!==void 0?Ct=Number(it.sliceLocation):it.imagePositionPatient&&Array.isArray(it.imagePositionPatient)&&it.imagePositionPatient.length===3&&(Ct=Number(it.imagePositionPatient[2]))),{imageId:ut,sortKey:Ct}})].sort((ut,it)=>ut.sortKey!==null&&it.sortKey!==null?ut.sortKey-it.sortKey:ut.imageId.localeCompare(it.imageId)).map(ut=>ut.imageId);return JSON.stringify(st)===JSON.stringify(Se)?Se:st});return A(!0),We})},O=async de=>{console.log("Setting loaded imageIds:",de),console.log("autoCacheStack:",r);const We=[];if(r){for(const Se of de)if(Se.startsWith("wadouri:"))try{const we=Se.slice(8);if(Nb.wadouri.dataSetCacheManager){const Ge=Nb.wadouri.dataSetCacheManager.load(we);Ge&&typeof Ge.then=="function"&&We.push(Ge)}else console.warn("MetaDataManager not found. Unable to cache metadata.")}catch(we){console.warn(`Failed to cache metadata for ${Se}:`,we)}await Promise.all(We),Ne&&(console.log("Sorting viewport imageIds by slice location"),B())}},[z,W]=Nt.useState({rows:1,cols:1}),[K,Z]=Nt.useState(!1),ee=Nt.useRef([]),xe=Nt.useRef({}),De=Nt.useRef({}),[Ne,$e]=Nt.useState(!1),[ie,ae]=Nt.useState(!0),ye=[];for(let de=1;de<=3;de++)for(let We=1;We<=3;We++)ye.push({rows:de,cols:We});const[se,ge]=Nt.useState(()=>Array(z.rows*z.cols).fill({index:0,total:0,windowCenter:"",windowWidth:"",slicePosition:0})),[Fe,oe]=Nt.useState(()=>Array(y).fill("stack")),[ht,wt]=Nt.useState(()=>Array(z.rows*z.cols).fill(!1)),[gt,Ie]=Nt.useState({Primary:id.toolName,Auxiliary:j0.toolName,Secondary:H0.toolName,Primary_and_Secondary:q0.toolName,Fourth_Button:K0.toolName,Wheel:id.toolName}),[je,nt]=Nt.useState({Primary:Iu.toolName,Auxiliary:nl.toolName,Secondary:Z0.toolName}),[rt,dt]=Nt.useState(!1);Nt.useEffect(()=>{const de=Se=>{Se.ctrlKey&&dt(!0)},We=Se=>{Se.ctrlKey||dt(!1)};return window.addEventListener("keydown",de),window.addEventListener("keyup",We),()=>{window.removeEventListener("keydown",de),window.removeEventListener("keyup",We)}},[]);const[Lt,xt]=Nt.useState(!1),[Ft,jt]=Nt.useState(null),Pn=(de,We)=>{Ro&&Ro(We),yn(Se=>{const we=[...Se];return we[de]=We,we})},$n=(de,We,Se)=>{const we=Rr.getAllAnnotations()||[];we.forEach(tt=>{tt.annotationUID===We&&(tt.isSelected=!1)}),Rr.removeAnnotation(We),x.current.render();const Ge=Se.filter(tt=>tt.annotationUID!==We);yn(tt=>{const st=[...tt],ut=Ge.length>0?Ge[0].annotationUID:null;return st[de]=ut,we.forEach(it=>{it.isSelected=it.annotationUID===ut}),Ro(ut),x.current.render(),st})},fn=()=>{const de=I.findIndex(Ge=>Ge&&Ge.length>0);if(de===-1){jt("No images loaded."),xt(!0);return}const We=I[de][0],Se=["imagePlaneModule","generalSeriesModule","generalStudyModule","patientModule","imagePixelModule","voiLutModule","modalityLutModule","sopCommonModule","petIsotopeModule","multiframeModule","cineModule","overlayPlaneModule","generalImageModule","stackModule","voiLutModule","modalityLutModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule","petSeriesModule","petImageModule","petIsotopeModule"],we={};Se.forEach(Ge=>{const tt=mt(Ge,We);tt!==void 0&&(we[Ge]=tt)}),jt(lt.jsx("pre",{style:{maxHeight:600,overflow:"auto",fontSize:13,color:"#fff"},children:JSON.stringify(we,null,2)})),xt(!0)};Nt.useEffect(()=>(window.loadDicomStackFromFiles=de=>{const We=Array.from(de);Sn({target:{files:We}})},()=>{window.loadDicomStackFromFiles=void 0}),[]);const[bn,Xi]=Nt.useState(!1);Nt.useEffect(()=>{const de=Kr(w);de&&["ArrowAnnotate","NoLabelArrowAnnotate","Length","RectangleROI","EllipticalROI","PlanarFreehandROI","PlanarFreehandContourSegmentation"].forEach(We=>{de.setToolConfiguration(We,{color:"#00e676",selectedColor:"#ffeb3b"})})},[w]),Nt.useEffect(()=>{const de=Se=>{Se.altKey&&Xi(!0)},We=Se=>{Se.altKey||Xi(!1)};return window.addEventListener("keydown",de),window.addEventListener("keyup",We),()=>{window.removeEventListener("keydown",de),window.removeEventListener("keyup",We)}},[]),Nt.useEffect(()=>{if(!ie)return;const de=Kr(w);de&&(bn?(de.hasTool(ua.toolName)||de.addTool(ua.toolName),de.setToolEnabled(ua.toolName),de.setToolActive(ua.toolName)):de.hasTool(ua.toolName)&&de.setToolDisabled(ua.toolName))},[bn,ie]);const Mr=Nt.useCallback(()=>{[Kr(w)].forEach(We=>{if(We){ng.forEach(we=>{We.setToolPassive(we.value,{removeAllBindings:!0})}),We.setToolDisabled(ua.toolName);const Se={};Object.entries(gt).forEach(([we,Ge])=>{Se[Ge]||(Se[Ge]=[]);const tt=Xm.find(st=>st.value===we);tt?Se[Ge].push({mouseButton:tt.mask}):tg[we]&&Se[Ge].push({mouseButton:tg[we]})}),Object.entries(je).forEach(([we,Ge])=>{if(!Ge)return;Se[Ge]||(Se[Ge]=[]);const tt=Xm.find(st=>st.value===we);tt?Se[Ge].push({mouseButton:tt.mask,modifierKey:Vb.Ctrl}):tg[we]&&Se[Ge].push({mouseButton:tg[we],modifierKey:Vb.Ctrl})}),Object.entries(Se).forEach(([we,Ge])=>{We.setToolActive(we,{bindings:Ge})})}})},[gt,je]),[Ue,ft]=Nt.useState(!1),Ut=Nt.useRef(null),Sn=async de=>{const We=de.target.files;if(!We||We.length===0)return;$e(!1);const Se=Array.from(We).sort((ut,it)=>ut.name.localeCompare(it.name));let we;const Ge=await Se[0].arrayBuffer();we=Tr.parseDicom(new Uint8Array(Ge)).string("x0020000d"),console.log("StudyInstanceUID:",we);const st=Se.map(ut=>`wadouri:${URL.createObjectURL(ut)}`);E(ut=>{const it=[...ut,{imageIds:st,studyInstanceUID:we}];return M(Ct=>{const Qt=[...Ct];return Qt[0]=st,Qt}),V(Ct=>{const Qt=[...Ct];return Qt[0]=it.length-1,Qt}),O(st),it})},Qn=Nt.useCallback((de,We)=>{if(!We)return;let Se=0,we=0,Ge="",tt="",st="";if(Fe[de]==="stack"){if(Se=typeof We.getCurrentImageIdIndex=="function"?We.getCurrentImageIdIndex():0,we=(typeof We.getImageIds=="function"?We.getImageIds():[]).length,typeof We.getProperties=="function"){const it=We.getProperties();if(it.voiRange){const{lower:Ct,upper:Qt}=it.voiRange;Ge=((Qt+Ct)/2).toFixed(0),tt=(Qt-Ct).toFixed(0)}}}else if(Fe[de]==="volume"){if(typeof We.getSliceIndex=="function"&&(Se=We.getSliceIndex()),typeof We.getNumberOfSlices=="function"&&(we=We.getNumberOfSlices()),typeof We.getProperties=="function"){let ut;if(We.volumeIds&&We.volumeIds.size>0){const it=Array.from(We.volumeIds)[0];ut=We.getProperties(it)}else ut=We.getProperties();if(ut&&ut.voiRange){const{lower:it,upper:Ct}=ut.voiRange;Ge=((Ct+it)/2).toFixed(0),tt=(Ct-it).toFixed(0)}}if(typeof We.getSlicePlaneCoordinates=="function"){const ut=We.getSlicePlaneCoordinates();ut&&typeof ut.position=="number"&&(st=ut.position.toFixed(2)+" mm")}}ge(ut=>{const it=[...ut];return it[de]={index:Se+1,total:we,windowCenter:Ge,windowWidth:tt,slicePosition:st},it})},[Fe]),[Pt,_n]=Nt.useState(!1);function sn(){for(let de=0;de{const de=async()=>{var tt;console.log("setup"),c.current||(c.current=!0,await WZ(),await iF(),rG());let Se=x.current;Se||(Se=new CA(m),x.current=Se);let we=Kr(w);we||(we=Kxe(w)),Fe.slice(0,z.rows*z.cols).filter(st=>st==="volume").length,Vi(we);for(let st=0;st{if(Ct.offsetWidth>0&&Ct.offsetHeight>0){Se.resize();const xn=Se.getViewport(it);xn&&typeof xn.resize=="function"&&xn.resize(),xn&&typeof xn.render=="function"&&xn.render()}});Gt.observe(Ct),Ct._resizeObserver=Gt}if(Fe[st]==="stack")ut&&ut.length>0&&on.setStack(ut),Y?we.removeViewports(m,it):we.addViewport(it,m);else if(Fe[st]==="volume"){we.addViewport(it,m);const Gt=`myVolumeId_${st}`;(await Vv(Gt,{imageIds:ut})).load(),on.setVolumes([{volumeId:Gt}]),on.render(),Ct._overlayListener&&on.element.removeEventListener(qm,Ct._overlayListener);const er=()=>Qn(st,on);on.element.addEventListener(qm,er),Ct._overlayListener=er,Qn(st,on);continue}if(on.render(),!C.current){De.current[st]!==void 0&&typeof on.setImageIdIndex=="function"&&Aa(on.element,{imageIndex:De.current[st]});const Gt=xe.current[st];if(Gt&&typeof on.setProperties=="function"){const{voiRange:xn,invert:er,interpolationType:nr,VOILUTFunction:or,colormap:qn}=Gt,At={};xn&&xn.lower!==void 0&&xn.upper!==void 0&&(At.voiRange=xn),er!==void 0&&(At.invert=er),nr!==void 0&&(At.interpolationType=nr),or&&(At.VOILUTFunction=or),qn!=null&&(typeof qn=="string"||typeof qn=="object"&&!("actor"in qn))&&(At.colormap=qn),setTimeout(()=>{console.log("Restoring properties (timeout) for viewport",st,At),on.setProperties(At),on.render()},100)}}Ct._overlayListener&&on.element.removeEventListener(qm,Ct._overlayListener);const cn=()=>Qn(st,on);on.element.addEventListener(qm,cn),Ct._overlayListener=cn,Qn(st,on)}for(let st=0;st=2?(we.hasTool(Fs.toolName)||we.addTool(Fs.toolName),we.setToolEnabled(Fs.toolName),we.setToolConfiguration(Fs.toolName,{}),we.setToolActive(Fs.toolName,{bindings:[{mouseButton:tg.Primary}]})):we.hasTool(Fs.toolName)&&we.setToolDisabled(Fs.toolName)),Mr()},We=requestAnimationFrame(()=>{de()});return()=>{ee.current.forEach(Se=>{Se&&Se._resizeObserver&&(Se._resizeObserver.disconnect(),delete Se._resizeObserver)}),cancelAnimationFrame(We)}},[s,Qn,z,Fe,I]);const rn=Nt.useCallback(de=>{const We=`CT_${de}`,we=x.current.getViewport(We);we&&typeof we.resetCamera=="function"&&(we.resetCamera(),console.log("Restoring viewport properties for viewport",de),we.resetProperties(),we.render())},[]),pi=Nt.useCallback((de,We,Se)=>{const we=`CT_${de}`;try{const Ge=x.current;if(Ge){const tt=Ge.getViewport(we);tt&&typeof tt.setProperties=="function"&&(console.log(`Applying preset to viewport ${de}: center=${We}, width=${Se}`),tt.setProperties({voiRange:{lower:We-Se/2,upper:We+Se/2}}),tt.render(),Qn(de,tt))}}catch{}},[Qn]);Nt.useEffect(()=>{ge(Array(z.rows*z.cols).fill({index:0,total:0,windowCenter:"",windowWidth:""})),wt(Array(z.rows*z.cols).fill(!1))},[z]),Nt.useEffect(()=>{Mr()},[gt,je,rt,Mr]),Nt.useEffect(()=>{if(!l)return;const de=We=>{const Se=document.querySelector(".preset-menu");Se&&!Se.contains(We.target)&&f(!1)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[l]),Nt.useEffect(()=>{const de=We=>{if(We.button===3||We.button===4)return We.preventDefault(),!1};return window.addEventListener("mousedown",de,!0),window.addEventListener("mouseup",de,!0),window.addEventListener("auxclick",de,!0),()=>{window.removeEventListener("mousedown",de,!0),window.removeEventListener("mouseup",de,!0),window.removeEventListener("auxclick",de,!0)}},[]),Nt.useEffect(()=>{const de=a.current;if(!de)return;const We=Se=>{Se.preventDefault()};return de.addEventListener("contextmenu",We),()=>{de.removeEventListener("contextmenu",We)}},[]),Nt.useEffect(()=>{if(!ue)return;const de=Kr(w);Vi(de)},[D,ue]),Nt.useEffect(()=>{Ut.current&&(Ut.current.setAttribute("webkitdirectory","true"),Ut.current.setAttribute("directory","true"))},[]),Nt.useEffect(()=>(window.loadDicomStackFromWadouriList=async de=>{if(!de||de.length===0)return;let We;try{const Se=de[0];if(Se&&Se.startsWith("wadouri:")){const we=Se.slice(8),tt=await(await fetch(we)).arrayBuffer();We=Tr.parseDicom(new Uint8Array(tt)).string("x0020000d")}}catch{}E(Se=>{const we=[...Se,{imageIds:de,studyInstanceUID:We}];return M(Ge=>{const tt=[...Ge];return tt[0]=de,tt}),V(Ge=>{const tt=[...Ge];return tt[0]=we.length-1,tt}),O(de),we})},()=>{window.loadDicomStackFromWadouriList=void 0}),[E,M,V,O]),Nt.useEffect(()=>{!Ne||!I.every(We=>!We||We.length===0||We.every(Se=>!!mt("imagePlaneModule",Se)))||M(We=>{let Se=!1;const we=We.map(Ge=>{if(!Ge||Ge.length===0)return Ge;const ut=[...Ge.map(it=>({imageId:it,sliceLoc:(()=>{const Ct=mt("imagePlaneModule",it);return Ct&&Ct.sliceLocation!==void 0?Number(Ct.sliceLocation):null})()}))].sort((it,Ct)=>it.sliceLoc!==null&&Ct.sliceLoc!==null?it.sliceLoc-Ct.sliceLoc:it.imageId.localeCompare(Ct.imageId)).map(it=>it.imageId);return JSON.stringify(ut)!==JSON.stringify(Ge)?(Se=!0,ut):Ge});return Se&&A(!0),we})},[Ne,T]);function Vi(de){if(!de)return;const We=`CT_${D}`;ue?(de.setToolEnabled(Gf.toolName),de.setToolConfiguration(Gf.toolName,{sourceViewportId:We})):de.setToolDisabled(Gf.toolName)}function Ha(){var We,Se,we;const de=x.current;if(de)for(let Ge=0;Ge=we.length||de>=We)return alert("Invalid truncation bounds."),!1;const Ge=we.slice(de,We+1);E([{...Se,imageIds:Ge}]),M([Ge]),V([0]);const tt=x.current;if(tt){const it=tt.getViewport("CT_0");it&&typeof it.setStack=="function"&&(it.setStack(Ge),(st=it.setImageIdIndex)==null||st.call(it,0),(ut=it.render)==null||ut.call(it))}return!0}function To(de=0){const We=x.current;if(!We)return null;const Se=We.getViewport(`CT_${de}`);return!Se||typeof Se.getCurrentImageIdIndex!="function"?null:Se.getCurrentImageIdIndex()}Nt.useEffect(()=>{const de=t||"default";function We(Se,we){const Ge=x.current;if(!Ge)return;const tt=Ge.getViewport(`CT_${Se}`);if(!tt||typeof tt.getImageIds!="function")return;const ut=tt.getImageIds().map(Qt=>Qt.replace(/^wadouri:/,"")),it=we.replace(/^wadouri:/,""),Ct=ut.indexOf(it);Ct!==-1&&typeof tt.setImageIdIndex=="function"&&(Aa(tt.element,{imageIndex:Ct}),Qn(Se,tt))}return window[`getViewport_${de}`]=Se=>{const we=x.current;if(we)return we.getViewport(`CT_${Se}`)},window[`getAllViewports_${de}`]=()=>{const Se=x.current;return Se?Array.from({length:y},(we,Ge)=>Se.getViewport(`CT_${Ge}`)).filter(Boolean):[]},window[`jumpToSliceByImageId_${de}`]=We,window[`resetViewer_${de}`]=Ha,window[`truncateStack_${de}`]=Ea,window[`getCurrentStackPosition_${de}`]=To,window[`loadAdditionalStack_${de}`]=async(Se,we)=>{var tt;if(!Array.isArray(Se)||Se.length===0)return;let Ge=we;if(!Ge&&((tt=Se[0])!=null&&tt.startsWith("wadouri:")))try{const st=Se[0].slice(8),it=await(await fetch(st)).arrayBuffer();Ge=Tr.parseDicom(new Uint8Array(it)).string("x0020000d")}catch{}E(st=>[...st,{imageIds:Se,studyInstanceUID:Ge}]),M(st=>{const ut=[...st],it=ut.findIndex(Ct=>!Ct||Ct.length===0);return it!==-1&&(ut[it]=Se),ut}),O(Se)},window[`exportViewerState_${de}`]=()=>{var Gt;const Se=z.rows*z.cols,we=Fe.slice(0,Se),Ge=L.slice(0,Se),tt=T.map(xn=>({i:xn.imageIds,u:xn.studyInstanceUID}));console.log("Exporting viewer state with",Se,"active viewports"),console.log("modes",we);const st=x.current,ut=[],it=[],Ct=[],Qt=[],on=[];for(let xn=0;xn{try{C.current=!0;const we=typeof Se=="string"?JSON.parse(Se):Se;if(we.grid&&W(we.grid),we.modes&&oe(we.modes),we.stacks&&E(we.stacks.map(ut=>({imageIds:ut.i,studyInstanceUID:ut.u}))),we.stackIdx&&we.stacks){const ut=we.stackIdx.map(it=>{var Ct;return((Ct=we.stacks[it])==null?void 0:Ct.i)||[]});M(ut),V(we.stackIdx)}const Ge=30;let tt=0;async function st(){var Qt,on,cn,Gt,xn,er,nr,or,qn;const ut=x.current;if(!ut){C.current=!1;return}const it=((Qt=we.grid)==null?void 0:Qt.rows)*((on=we.grid)==null?void 0:on.cols)||1;let Ct=!0;for(let At=0;Atei===jn[xr])){console.warn(`Viewport ${At}: importedImageIds do not match viewportImageIds`,{importedImageIds:jn,viewportImageIds:wr}),Ct=!1;break}}catch{Ct=!1}}if(!Ct&&tt{st()},500);return}for(let At=0;At{Aa(Bn.element,{imageIndex:we.volumeSliceIndices[At]})},100)),Bn.render()}else Bn.setStack&&(Bn.setStack(jn),Bn.render()),we.stackPos&&typeof we.stackPos[At]=="number"&&typeof Bn.setImageIdIndex=="function"&&(Mn&&Aa?Aa(Bn.element,{imageIndex:we.stackPos[At]}):Bn.setImageIdIndex(we.stackPos[At]));if(we.props&&we.props[At]&&typeof Bn.setProperties=="function"){console.log("Restoring properties for viewport",At,we.props[At]);const wr={...we.props[At]};wr.colormap!==void 0&&wr.colormap!==null&&typeof wr.colormap!="string"&&(typeof wr.colormap!="object"||!("name"in wr.colormap))&&delete wr.colormap,setTimeout(()=>{Bn.setProperties(wr),Bn.render()},100)}else console.warn("No properties to restore for viewport",At);we.cam&&we.cam[At]&&typeof Bn.setCamera=="function"&&(console.log("Restoring camera for viewport",At,we.cam[At]),Bn.setCamera(we.cam[At]),Bn.render())}}C.current=!1}setTimeout(()=>{st()},100)}catch(we){C.current=!1,alert("Failed to import viewer state: "+we)}},window[`exportAnnotations_${de}`]=()=>{try{let Se=Rr.getAllAnnotations();if(console.log("Exporting annotations:",Se),Array.isArray(Se)){const we=[Iu.toolName,Z0.toolName,Ou.toolName,tl.toolName,od.toolName,bu.toolName,ic.toolName,nl.toolName,X0.toolName];Se=Se.filter(Ge=>we.includes(Ge.metadata.toolName))}else return"{}";return JSON.stringify(Se,null,2)}catch(Se){return alert("Failed to export annotations: "+Se),"{}"}},window[`importAnnotations_${de}`]=Se=>{try{const we=typeof Se=="string"?JSON.parse(Se):Se;Rr.removeAllAnnotations&&Rr.removeAllAnnotations(),Array.isArray(we)&&we.forEach(Ge=>{Rr.addAnnotation(Ge,Ge.annotationUID)}),x.current&&x.current.render()}catch(we){alert("Failed to import annotations: "+we)}},window[`importLegacyAnnotations_${de}`]=Se=>{Rr.removeAllAnnotations&&Rr.removeAllAnnotations();let we;try{we=typeof Se=="string"?JSON.parse(Se):Se}catch{alert("Invalid legacy annotation JSON");return}const Ge={ArrowAnnotate:"ArrowAnnotate"};Object.entries(we).forEach(([tt,st])=>{console.log("Importing legacy annotations for imageId:",tt),Object.entries(st).forEach(([ut,it])=>{const Ct=Ge[ut]||ut;it.data&&Array.isArray(it.data)&&it.data.forEach(Qt=>{const on=kb(tt,{x:Qt.handles.start.y,y:Qt.handles.start.x}),cn=kb(tt,{x:Qt.handles.end.y,y:Qt.handles.end.x});console.log("Importing legacy annotation:"),console.log(" Image ID:",tt),console.log(" Start World:",on),console.log(" End World:",cn);const Gt=mt("imagePlaneModule",tt);console.log(rL);let xn=mt("frameOfReferenceUID",tt);!xn&&Gt&&Gt.frameOfReferenceUID&&(xn=Gt.frameOfReferenceUID);const er=Gt!=null&&Gt.rowCosines&&(Gt!=null&&Gt.columnCosines)?[Gt.rowCosines[1]*Gt.columnCosines[2]-Gt.rowCosines[2]*Gt.columnCosines[1],Gt.rowCosines[2]*Gt.columnCosines[0]-Gt.rowCosines[0]*Gt.columnCosines[2],Gt.rowCosines[0]*Gt.columnCosines[1]-Gt.rowCosines[1]*Gt.columnCosines[0]]:void 0;Array.isArray(er)&&er.length,typeof Qt.rotation=="number"&&Qt.rotation;const nr={annotationUID:Qt.uuid,metadata:{toolName:Ct,referencedImageId:tt,FrameOfReferenceUID:xn,viewPlaneNormal:er},data:{handles:{points:[on,cn],textBox:Qt.handles.textBox},text:Qt.text||""},visibility:Qt.visible!==!1,active:Qt.active||!1};Rr.addAnnotation(nr,nr.annotationUID)})})}),x.current&&x.current.render()},window[`importLegacyViewport_${de}`]=Se=>{let we;try{we=typeof Se=="string"?JSON.parse(Se):Se}catch{alert("Invalid legacy viewport JSON");return}const Ge=x.current;if(!Ge)return;const tt=`CT_${D??0}`,st=Ge.getViewport(tt);if(!st)return;const ut={};if(we.voi&&(ut.voiRange={lower:we.voi.windowCenter-we.voi.windowWidth/2,upper:we.voi.windowCenter+we.voi.windowWidth/2}),typeof we.invert=="boolean"&&(ut.invert=we.invert),typeof we.pixelReplication=="boolean"&&(ut.interpolationType=we.pixelReplication?0:1),typeof we.hflip=="boolean"&&(ut.hflip=we.hflip),typeof we.vflip=="boolean"&&(ut.vflip=we.vflip),typeof st.setProperties=="function"&&st.setProperties(ut),we.translation||we.scale){const it=st.getCamera?st.getCamera():{};we.translation&&(it.translation={...it.translation,...we.translation}),we.scale&&(it.parallelScale=200/we.scale),console.log("Applying legacy camera properties:",it),typeof st.setCamera=="function"&&st.setCamera(it)}typeof we.rotation=="number"&&st.setRotation(we.rotation),st.render(),Qn(D??0,st)},()=>{window[`exportViewerState_${de}`]=void 0,window[`importViewerState_${de}`]=void 0,window[`exportAnnotations_${de}`]=void 0,window[`importAnnotations_${de}`]=void 0,window[`importLegacyAnnotations_${de}`]=void 0,window[`importLegacyViewport_${de}`]=void 0,window[`jumpToSliceByImageId_${de}`]=void 0,window[`resetViewer_${de}`]=void 0,window[`truncateStack_${de}`]=void 0,window[`getCurrentStackPosition_${de}`]=void 0,window[`loadAdditionalStack_${de}`]=void 0,window[`getViewport_${de}`]=void 0,window[`getAllViewports_${de}`]=void 0}},[z,Fe,L,T,I,W,oe,V,E,M,E,M,O]),Nt.useEffect(()=>{const de=a.current;if(!de)return;function We(Se){if(console.log("Handling arrow key navigation",Se.key),console.log("activeViewport",D),D===null)return;const we=x.current;if(!we)return;const Ge=we.getViewport(`CT_${D}`);if(Ge){if(console.log(Ge),Fe[D]==="stack"){if(typeof Ge.getCurrentImageIdIndex!="function"||typeof Ge.setImageIdIndex!="function")return;const tt=I[D];if(!tt||tt.length===0)return;Se.key==="ArrowUp"||Se.key==="ArrowRight"?(ps(Ge,{delta:-1}),Se.preventDefault()):(Se.key==="ArrowDown"||Se.key==="ArrowLeft")&&(ps(Ge,{delta:1}),Se.preventDefault())}Fe[D]==="volume"&&typeof Ge.getSliceIndex=="function"&&typeof Ge.getNumberOfSlices=="function"&&Ge.getNumberOfSlices()>1&&(Se.key==="ArrowUp"||Se.key==="ArrowRight"?(ps(Ge,{delta:-1}),Se.preventDefault()):(Se.key==="ArrowDown"||Se.key==="ArrowLeft")&&(ps(Ge,{delta:1}),Se.preventDefault()))}}return de.addEventListener("keydown",We),()=>{de.removeEventListener("keydown",We)}},[D,Fe,I,Qn]);const ra=D!==null?L[D]:0,Uo=T[ra],fr=Uo==null?void 0:Uo.studyInstanceUID,[oo,yn]=Nt.useState(()=>Array(y).fill(null)),Qr=z.rows*z.cols,Da=[];for(let de=0;deee.current[de]=Se,style:{flex:1,border:We?"1px solid #222":"none",background:"#000",minWidth:0,minHeight:0,position:"relative",overflow:"hidden",flexDirection:"column",gridRow:Math.floor(de/z.cols)+1,gridColumn:de%z.cols+1,height:"100%",boxShadow:D===de?"0 0 0 4px #1976d2, 0 0 16px 4px #1976d2cc":void 0,zIndex:D===de?10:1},onClick:()=>{b(de),Z(!1)},onDoubleClick:()=>rn(de),children:[lt.jsx("button",{style:{position:"absolute",top:8,left:8,zIndex:20,background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"12px",opacity:.85},onClick:()=>{oe(Se=>{const we=[...Se];return we[de]=Se[de]==="stack"?"volume":"stack",we})},children:Fe[de]==="stack"?"Volume":"Stack"}),Fe[de]==="volume"&<.jsxs("div",{style:{position:"absolute",top:8,left:70,zIndex:21,display:"flex",gap:"6px",background:"rgba(34,34,34,0.85)",borderRadius:"4px",padding:"2px 6px",alignItems:"center"},children:[lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Se=x.current,we=Se==null?void 0:Se.getViewport(`CT_${de}`);we&&we.setOrientation&&(we.setOrientation("axial"),we.render())},children:"Axial"}),lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px",marginRight:"2px"},onClick:()=>{const Se=x.current,we=Se==null?void 0:Se.getViewport(`CT_${de}`);we&&we.setOrientation&&(we.setOrientation("sagittal"),we.render())},children:"Sagittal"}),lt.jsx("button",{style:{background:"#444",color:"#fff",border:"none",borderRadius:"3px",padding:"2px 8px",cursor:"pointer",fontSize:"12px"},onClick:()=>{const Se=x.current,we=Se==null?void 0:Se.getViewport(`CT_${de}`);we&&we.setOrientation&&(we.setOrientation("coronal"),we.render())},children:"Coronal"})]}),lt.jsxs("button",{style:{position:"absolute",top:40,left:8,zIndex:20,background:"#111",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 8px",cursor:"pointer",fontSize:"13px",opacity:.85,marginTop:"4px",display:"flex",alignItems:"center",gap:"6px"},title:"Toggle Fullscreen",onClick:Se=>{Se.stopPropagation();const we=ee.current[de];document.fullscreenElement===we?document.exitFullscreen():we!=null&&we.requestFullscreen?we.requestFullscreen():we!=null&&we.webkitRequestFullscreen?we.webkitRequestFullscreen():we!=null&&we.msRequestFullscreen&&we.msRequestFullscreen()},onMouseEnter:()=>g(de),onMouseLeave:()=>g(null),children:[lt.jsx("span",{style:{fontSize:"18px",lineHeight:1},children:"⛶"}),h===de&<.jsx("span",{style:{marginLeft:6},children:document.fullscreenElement===ee.current[de]?"Exit Fullscreen":"Fullscreen"})]}),Fe[de]==="stack"&&S&&(()=>{var on;const Se=I[de],Ge=(Rr.getAllAnnotations()||[]).filter(cn=>cn.metadata&&cn.metadata.referencedImageId&&Se.includes(cn.metadata.referencedImageId)&&cn.metadata.toolName!==ua.toolName);if(!Ge.length)return null;const tt=x.current,st=tt==null?void 0:tt.getViewport(`CT_${de}`),ut=((on=st==null?void 0:st.getCurrentImageIdIndex)==null?void 0:on.call(st))??0,it=Se[ut],Ct=Ge.filter(cn=>cn.metadata.referencedImageId===it),Qt=oo[de];return lt.jsxs("div",{style:{position:"absolute",left:"50%",bottom:60,transform:"translateX(-50%)",zIndex:30,display:"flex",gap:4,pointerEvents:"auto",alignItems:"center"},children:[lt.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Previous Annotation","aria-label":"Previous Annotation",onClick:()=>{const cn=x.current,Gt=cn==null?void 0:cn.getViewport(`CT_${de}`);if(!Gt||typeof Gt.getCurrentImageIdIndex!="function")return;const xn=Gt.getCurrentImageIdIndex(),er=Bb(xn,Se,Ge,-1);if(er!==null&&typeof Gt.setImageIdIndex=="function"){Aa(Gt.element,{imageIndex:er}),Qn(de,Gt);const nr=Se[er],or=Ge.filter(qn=>qn.metadata.referencedImageId===nr);Pn(de,or.length>0?or[0].annotationUID:null)}},children:lt.jsx("span",{"aria-hidden":"true",children:"◀"})}),lt.jsx("button",{style:{background:"rgba(30,30,30,0.7)",color:"#fff",border:"none",borderRadius:"50%",width:28,height:28,fontSize:"16px",fontWeight:"bold",cursor:"pointer",opacity:.7,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 1px 4px rgba(0,0,0,0.18)",transition:"opacity 0.2s"},title:"Next Annotation","aria-label":"Next Annotation",onClick:()=>{const cn=x.current,Gt=cn==null?void 0:cn.getViewport(`CT_${de}`);if(!Gt||typeof Gt.getCurrentImageIdIndex!="function")return;const xn=Gt.getCurrentImageIdIndex(),er=Bb(xn,Se,Ge,1);if(er!==null&&typeof Gt.setImageIdIndex=="function"){Aa(Gt.element,{imageIndex:er}),Qn(de,Gt);const nr=Se[er],or=Ge.filter(qn=>qn.metadata.referencedImageId===nr);Pn(de,or.length>0?or[0].annotationUID:null)}},children:lt.jsx("span",{"aria-hidden":"true",children:"▶"})}),Ct.length>0&<.jsx("div",{style:{display:"flex",gap:2,alignItems:"center"},children:Ct.map(cn=>lt.jsxs("div",{style:{display:"flex",alignItems:"center",background:Qt===cn.annotationUID?"rgb(4, 225, 0)":"#444",color:Qt===cn.annotationUID?"#222":"#fff",borderRadius:"4px",padding:"2px 6px",marginRight:2,cursor:"pointer",border:Qt===cn.annotationUID?"2px solid #1976d2":"none",fontWeight:Qt===cn.annotationUID?"bold":"normal"},onClick:()=>Pn(de,cn.annotationUID),children:[lt.jsxs("span",{style:{marginRight:4},children:[Qt===cn.annotationUID?"★ ":"",cn.metadata.toolName||"Annotation"]}),lt.jsx("button",{style:{background:"#b71c1c",color:"#fff",border:"none",borderRadius:"50%",width:20,height:20,fontSize:"13px",fontWeight:"bold",cursor:"pointer",marginLeft:2,display:"flex",alignItems:"center",justifyContent:"center",opacity:.85},title:"Delete this annotation","aria-label":"Delete annotation",onClick:Gt=>{Gt.stopPropagation(),$n(de,cn.annotationUID,Ct)},children:"🗑️"})]},cn.annotationUID))})]})})(),lt.jsx("div",{style:{position:"absolute",left:8,bottom:8,background:"rgba(0,0,0,0.7)",color:"#fff",padding:"6px 12px",borderRadius:"4px",fontSize:"14px",zIndex:10,pointerEvents:"none",minWidth:"120px",userSelect:"none"},children:Fe[de]==="stack"?lt.jsxs(lt.Fragment,{children:[lt.jsxs("div",{children:["Image: ",(Fi=se[de])==null?void 0:Fi.index," / ",(ao=se[de])==null?void 0:ao.total]}),lt.jsxs("div",{children:["WC: ",(Ui=se[de])==null?void 0:Ui.windowCenter,"   WW: ",(mi=se[de])==null?void 0:mi.windowWidth]})]}):lt.jsxs("div",{children:["Slice: ",(Ka=se[de])==null?void 0:Ka.index," / ",(Bo=se[de])==null?void 0:Bo.total,((Bi=se[de])==null?void 0:Bi.slicePosition)&<.jsxs("span",{children:["   (",(qa=se[de])==null?void 0:qa.slicePosition,")"]}),lt.jsx("br",{}),"WC: ",(Gi=se[de])==null?void 0:Gi.windowCenter,"   WW: ",(ia=se[de])==null?void 0:ia.windowWidth]})}),lt.jsx("div",{style:{position:"absolute",right:8,bottom:8,zIndex:10,pointerEvents:"auto"},children:lt.jsxs("div",{className:"preset-menu",style:{background:"rgba(0,0,0,0.7)",color:"#fff",borderRadius:"4px",fontSize:"14px",minWidth:"120px",overflow:"hidden",cursor:"pointer",position:"relative",boxShadow:ht[de]?"0 2px 8px rgba(0,0,0,0.3)":void 0,pointerEvents:"auto"},onClick:Se=>Se.stopPropagation(),children:[lt.jsxs("div",{style:{padding:"6px 12px",fontWeight:"bold",userSelect:"none"},onClick:Se=>{Se.stopPropagation(),wt(we=>{const Ge=[...we];return Ge[de]=!Ge[de],Ge})},children:["Presets",lt.jsx("span",{style:{float:"right",fontWeight:"normal"},children:ht[de]?"▲":"▼"})]}),ht[de]&<.jsx("div",{className:"preset-menu-content",style:{background:"rgba(0,0,0,0.95)",borderRadius:"0 0 4px 4px",padding:"6px 0 6px 0",display:"flex",flexDirection:"column",zIndex:11,pointerEvents:"auto"},onClick:Se=>Se.stopPropagation(),children:Hxe.map(Se=>lt.jsx("button",{style:{display:"block",width:"100%",margin:"2px 0",background:"#333",color:"#fff",border:"none",borderRadius:"3px",cursor:"pointer",padding:"4px 0",fontSize:"13px",opacity:.9},onClick:we=>{we.stopPropagation(),pi(de,Se.center,Se.width),wt(Ge=>{const tt=[...Ge];return tt[de]=!1,tt})},children:Se.name},Se.name))})]})}),Fe[de]==="stack"&&I[de]&<.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:I[de].length>0?"flex":"none",alignItems:"flex-start",justifyContent:"center",pointerEvents:"none",flexDirection:"column",padding:0},children:lt.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden"},children:I[de].map((Se,we)=>{const Ge=!!mt("imagePlaneModule",Se),tt=x.current;let st=-1;if(tt&&typeof tt.getViewport=="function"){const it=tt.getViewport(`CT_${de}`);it&&typeof it.getCurrentImageIdIndex=="function"&&(st=it.getCurrentImageIdIndex())}const ut=we===st;return lt.jsx("div",{style:{width:"100%",height:`${100/I[de].length}%`,background:ut?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":Ge?"linear-gradient(to right, #4caf50 60%, #2196f3 100%)":"#444",opacity:Ge?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:we{const it=x.current,Ct=it==null?void 0:it.getViewport(`CT_${de}`);Ct&&typeof Ct.setImageIdIndex=="function"&&Fe[de]==="stack"&&(Aa(Ct.element,{imageIndex:we}),Qn(de,Ct))}},Se)})})}),Fe[de]==="volume"&&(()=>{const Se=x.current,we=Se==null?void 0:Se.getViewport(`CT_${de}`);let Ge=0,tt=0;return we&&typeof we.getNumberOfSlices=="function"&&typeof we.getSliceIndex=="function"&&(Ge=we.getNumberOfSlices(),tt=we.getSliceIndex()),Ge>1?lt.jsx("div",{style:{position:"absolute",top:"10%",right:8,width:"12px",height:"80%",maxHeight:"100%",minHeight:0,zIndex:30,display:"flex",alignItems:"flex-start",justifyContent:"center",pointerEvents:"auto",flexDirection:"column",padding:0},children:lt.jsx("div",{style:{width:"8px",height:"100%",maxHeight:"100%",minHeight:0,borderRadius:"6px",background:"#222",position:"relative",display:"flex",flexDirection:"column",justifyContent:"flex-start",boxShadow:"0 0 8px #2196f3cc",overflow:"hidden",cursor:"pointer"},onClick:st=>{const it=st.currentTarget.getBoundingClientRect(),Ct=st.clientY-it.top,Qt=Math.floor(Ct/it.height*Ge),on=x.current,cn=on==null?void 0:on.getViewport(`CT_${de}`);cn&&(Aa(cn.element,{imageIndex:Qt}),cn.render(),Qn(de,cn))},children:Array.from({length:Ge}).map((st,ut)=>{const it=ut===tt;return lt.jsx("div",{style:{width:"100%",height:`${100/Ge}%`,minHeight:it?1:0,background:it?"linear-gradient(to right, #ffeb3b 60%, #ff9800 100%)":"#444",opacity:it?.95:.4,transition:"background 0.3s, opacity 0.3s",borderBottom:ut1||!I[de]||I[de].length===0)&<.jsx("div",{style:{position:"absolute",left:0,right:0,bottom:8,zIndex:20,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"auto",width:"100%",background:"none",borderRadius:"0",padding:0},children:lt.jsxs("div",{style:{position:"relative"},children:[lt.jsxs("button",{style:{background:"#222",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"2px 8px",fontSize:"13px",marginRight:"6px",minWidth:120,textAlign:"left",cursor:"pointer"},onClick:()=>v(p===de?null:de),"aria-haspopup":"listbox","aria-expanded":p===de,children:[(()=>{const Se=T[L[de]||0],we=Se==null?void 0:Se.studyInstanceUID,tt=fr&&we&&fr===we?"#4caf50":"#888";return lt.jsxs("span",{children:[lt.jsx("span",{style:{color:tt,fontWeight:"bold",marginRight:6,fontSize:"16px",verticalAlign:"middle"},children:"●"}),"Stack ",L[de]+1," (",(Se==null?void 0:Se.imageIds.length)||0," images)"]})})(),lt.jsx("span",{style:{float:"right",fontSize:"12px"},children:"▼"})]}),p===de&<.jsx("div",{ref:Se=>{Se&&Se.focus()},tabIndex:0,style:{position:"absolute",left:0,bottom:"110%",background:"#222",border:"1px solid #444",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",zIndex:100,minWidth:180,maxHeight:220,overflowY:"auto",overscrollBehavior:"contain",scrollbarWidth:"thin"},role:"listbox",onMouseDown:Se=>Se.stopPropagation(),onWheel:Se=>{const we=Se.currentTarget,{scrollTop:Ge,scrollHeight:tt,clientHeight:st}=we,ut=Ge===0,it=Ge+st>=tt-1;Se.deltaY<0&&ut||Se.deltaY>0&&it||(Se.stopPropagation(),Se.preventDefault(),we.scrollTop+=Se.deltaY)},onBlur:Se=>{const we=Se.relatedTarget,Ge=Se.currentTarget.parentElement;Ge!=null&&Ge.contains(we)||setTimeout(()=>v(null),100)},children:T.map((Se,we)=>{const Ge=Se.studyInstanceUID,st=fr&&Ge&&fr===Ge?"#4caf50":"#888",ut=Se.imageIds.length===0;return lt.jsxs("div",{role:"option","aria-selected":L[de]===we,style:{padding:"6px 12px",background:L[de]===we?"#444":"#222",color:ut?"#aaa":"#fff",cursor:ut?"not-allowed":"pointer",display:"flex",alignItems:"center",fontWeight:L[de]===we?"bold":"normal",borderBottom:"1px solid #333",userSelect:"none",opacity:ut?.6:1},tabIndex:-1,onMouseDown:it=>{it.preventDefault(),ut||(j(de,we),v(null))},children:[lt.jsx("span",{style:{color:st,fontWeight:"bold",marginRight:8,fontSize:"16px",verticalAlign:"middle"},children:"●"}),"Stack ",we+1," (",Se.imageIds.length," images",ut&<.jsx("span",{style:{color:"#f44336",marginLeft:6},children:"(empty)"}),")"]},we)})})]})})]},de))}return lt.jsxs("div",{ref:a,style:{position:"relative",inset:0,width:"100%",height:"100%",boxSizing:"border-box",background:"#222",padding:"12px",overflow:"hidden"},children:[k&<.jsx("div",{style:{position:"absolute",zIndex:3e3,top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.7)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:28,fontWeight:"bold",letterSpacing:1},children:k==="annotations"?"Loading Annotations...":"Loading Viewer State..."}),lt.jsxs("div",{children:[lt.jsx("button",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:Ue?250:-20,zIndex:200,width:40,height:40,background:"#222",color:"#fff",border:"none",borderRadius:"50%",fontWeight:"bold",cursor:"pointer",fontSize:"22px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",transition:"left 0.25s cubic-bezier(.4,2,.6,1), background 0.2s"},onClick:()=>ft(de=>!de),"aria-label":"Open menu",children:"☰"}),Ue&<.jsx("div",{style:{position:"absolute",top:0,left:0,width:220,height:"100%",background:"#222",color:"#fff",zIndex:199,boxShadow:"2px 0 12px rgba(0,0,0,0.3)",flexDirection:"column",padding:"24px 16px 16px 16px",display:"flex",overflow:"hidden"},children:lt.jsxs("div",{style:{flex:1,minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column"},children:[lt.jsxs("div",{style:{fontWeight:"bold",fontSize:18,marginBottom:24},children:["Menu",lt.jsx("button",{style:{float:"right",background:"transparent",color:"#fff",border:"none",fontSize:"22px",cursor:"pointer"},onClick:()=>ft(!1),"aria-label":"Close menu",children:"×"})]}),lt.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>{var de;return(de=Ut.current)==null?void 0:de.click()},children:"Load DICOM Folder"}),lt.jsx("input",{ref:Ut,type:"file",style:{display:"none"},multiple:!0,onChange:Sn,accept:".dcm,application/dicom"}),lt.jsxs("div",{style:{marginBottom:"18px",display:"flex",alignItems:"center",gap:"8px"},children:[lt.jsx("input",{type:"checkbox",id:"orderBySliceLocation",checked:Ne,onChange:de=>$e(de.target.checked),style:{accentColor:"#666"}}),lt.jsx("label",{htmlFor:"orderBySliceLocation",style:{fontSize:"15px",cursor:"pointer"},children:"Order by Slice Location"})]}),lt.jsx("button",{style:{padding:"10px 18px",background:"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:fn,children:"Show DICOM Metadata"}),lt.jsxs("button",{style:{padding:"10px 18px",background:Y?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>re(de=>!de),children:[Y?"Disable":"Enable"," Cross Reference Lines"]}),lt.jsxs("button",{style:{padding:"10px 18px",background:ue?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ce(de=>!de),children:[ue?"Disable":"Enable"," Reference Lines"]}),lt.jsx("button",{onClick:B,style:{margin:8,padding:8},children:"Sort All Viewports by Slice Location"}),lt.jsx("button",{style:{padding:"10px 18px",background:ie?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>ae(de=>!de),children:ie?"Disable Alt Key for Reference Cursors":"Enable Alt Key for Reference Cursors"}),lt.jsxs("button",{style:{padding:"10px 18px",background:S?"#1976d2":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginBottom:"18px",width:"100%"},onClick:()=>_(de=>!de),children:[S?"Hide":"Show"," Annotation Navigation"]})]})})]}),lt.jsxs("div",{className:"grid-menu-hover-container",style:{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",zIndex:100,display:"flex",flexDirection:"column",alignItems:"center",width:"auto",height:"48px",pointerEvents:"none"},children:[lt.jsx("div",{style:{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",width:80,height:14,zIndex:1,pointerEvents:"auto",background:"transparent"},onMouseEnter:()=>_n(!0),onFocus:()=>_n(!0),tabIndex:-1}),lt.jsx("button",{style:{position:"relative",top:Pt?"0":"-22px",opacity:Pt?1:.5,transition:"top 0.25s cubic-bezier(.4,2,.6,1), opacity 0.2s",padding:"6px 16px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginLeft:"4px",marginRight:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",pointerEvents:Pt?"auto":"none",zIndex:2,display:Pt?"block":"none"},title:"Toggle Fullscreen",onClick:()=>{const de=document.querySelector(".dicom-viewer-root");de&&(document.fullscreenElement===de?document.exitFullscreen():de.requestFullscreen?de.requestFullscreen():de.webkitRequestFullscreen?de.webkitRequestFullscreen():de.msRequestFullscreen&&de.msRequestFullscreen())},children:"⛶ Fullscreen"}),lt.jsxs("button",{className:"grid-menu-btn",style:{position:"relative",top:Pt?"0":"-22px",opacity:Pt?1:.5,transition:"top 0.25s cubic-bezier(.4,2,.6,1), opacity 0.2s",padding:"6px 16px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px",marginRight:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",pointerEvents:Pt?"auto":"none",zIndex:2,display:Pt?"block":"none"},onMouseLeave:()=>_n(!1),onBlur:()=>_n(!1),onClick:()=>Z(de=>!de),tabIndex:0,children:["Grid: ",z.rows,"x",z.cols," ▼"]}),K&<.jsx("div",{style:{position:"absolute",top:"110%",left:"50%",transform:"translateX(-50%)",background:"#222",color:"#fff",borderRadius:"6px",boxShadow:"0 2px 12px rgba(0,0,0,0.4)",padding:"12px",display:"grid",gridTemplateColumns:"repeat(3, 40px)",gap:"8px",zIndex:200,pointerEvents:"auto"},children:ye.map(de=>lt.jsxs("button",{style:{width:"40px",height:"40px",background:de.rows===z.rows&&de.cols===z.cols?"#444":"#333",color:"#fff",border:"none",borderRadius:"4px",fontWeight:"bold",cursor:"pointer",fontSize:"15px"},onClick:()=>{sn(),W({rows:de.rows,cols:de.cols}),Z(!1)},children:[de.rows,"x",de.cols]},`${de.rows}x${de.cols}`))})]}),lt.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",display:"grid",margin:3,gridTemplateRows:`repeat(${z.rows}, 1fr)`,gridTemplateColumns:`repeat(${z.cols}, 1fr)`,gap:"5px",zIndex:1},children:Da}),lt.jsx("button",{style:{position:"absolute",top:8,right:8,zIndex:20,padding:"6px 12px",background:"#222",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:.85,userSelect:"none"},onClick:()=>d(!0),children:"Settings"}),u&<.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:"rgba(0,0,0,0.4)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>d(!1),children:lt.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",minHeight:"180px",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative"},onClick:de=>de.stopPropagation(),children:[lt.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"Settings"}),lt.jsxs("div",{style:{marginBottom:"24px"},children:[lt.jsx("div",{style:{marginBottom:12,fontWeight:"bold"},children:"Mouse Button Tool Bindings"}),Fb.map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," Button:"]}),lt.jsx("select",{value:gt[de.value],onChange:We=>Ie(Se=>({...Se,[de.value]:We.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:ng.map(We=>lt.jsx("option",{value:We.value,children:We.label},We.value))})]},de.value)),lt.jsxs("div",{style:{margin:"12px 0"},children:[lt.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>Ee(de=>!de),children:[pe?"Hide":"Show"," Advanced Mouse Bindings"]}),pe&<.jsx("div",{style:{marginTop:8},children:Xm.slice(3).map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label,":"]}),lt.jsxs("select",{value:gt[de.value]||"",onChange:We=>Ie(Se=>({...Se,[de.value]:We.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(We=>lt.jsx("option",{value:We.value,children:We.label},We.value))]})]},de.value))})]}),lt.jsx("div",{style:{margin:"18px 0 8px 0",fontWeight:"bold"},children:"Ctrl + Mouse Button Tool Bindings"}),Fb.map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," + Ctrl:"]}),lt.jsxs("select",{value:je[de.value]||"",onChange:We=>nt(Se=>({...Se,[de.value]:We.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(We=>lt.jsx("option",{value:We.value,children:We.label},We.value))]})]},de.value+"_ctrl")),lt.jsxs("div",{style:{margin:"12px 0"},children:[lt.jsxs("button",{style:{background:"#333",color:"#fff",border:"none",borderRadius:"4px",padding:"4px 12px",cursor:"pointer",fontSize:"14px",marginBottom:"8px"},onClick:()=>_e(de=>!de),children:[Oe?"Hide":"Show"," Advanced Ctrl + Mouse Bindings"]}),Oe&<.jsx("div",{style:{marginTop:8},children:Xm.slice(3).map(de=>lt.jsxs("div",{style:{marginBottom:10},children:[lt.jsxs("label",{style:{marginRight:8},children:[de.label," + Ctrl:"]}),lt.jsxs("select",{value:je[de.value]||"",onChange:We=>nt(Se=>({...Se,[de.value]:We.target.value})),style:{background:"#333",color:"#fff",border:"1px solid #444",borderRadius:"4px",padding:"4px 8px",fontSize:"14px"},children:[lt.jsx("option",{value:"",children:"(None)"}),ng.map(We=>lt.jsx("option",{value:We.value,children:We.label},We.value))]})]},de.value+"_ctrl"))})]})]}),lt.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>d(!1),"aria-label":"Close",children:"×"})]})}),Lt&<.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"rgba(0,0,0,0.5)",zIndex:2e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>xt(!1),children:lt.jsxs("div",{style:{background:"#222",color:"#fff",borderRadius:"8px",minWidth:"320px",maxWidth:"80vw",maxHeight:"80vh",padding:"24px",boxShadow:"0 4px 24px rgba(0,0,0,0.4)",position:"relative",overflow:"auto"},onClick:de=>de.stopPropagation(),children:[lt.jsx("div",{style:{fontSize:"20px",marginBottom:"16px"},children:"DICOM Metadata"}),Ft,lt.jsx("button",{style:{position:"absolute",top:12,right:12,background:"transparent",color:"#fff",border:"none",fontSize:"20px",cursor:"pointer"},onClick:()=>xt(!1),"aria-label":"Close",children:"×"})]})})]})}function Kxe(t){console.log("Setting up tools...",t),Ci(j0),Ci(H0),Ci(id),Ci(q0),Ci(K0),Ci(Iu),Ci(nl),Ci(Ou),Ci(tl),Ci(od),Ci(bu),Ci(ic),Ci(X0),Ci(ua),Ci(Fs),Ci(Gf),Ci(Z0);let e=Kr(t);return e||(e=hN(t),e.addTool(H0.toolName),e.addTool(j0.toolName),e.addTool(q0.toolName),e.addTool(id.toolName,{loop:!1}),e.addTool(K0.toolName),e.addTool(Iu.toolName),e.addTool(Z0.toolName,{getTextCallback:()=>""}),e.addTool(Ou.toolName),e.addTool(nl.toolName,{statsCalculator:()=>null}),e.addTool(tl.toolName,{calculateStats:!1,getTextCallback:()=>""}),e.addTool(od.toolName,{getTextCallback:()=>""}),e.addTool(bu.toolName,{calculateStats:!1}),e.addTool(ic.toolName,{}),e.addTool(X0.toolName,{}),e.addTool(Gf.toolName),e.addTool(ua.toolName)),e}function Bb(t,e,r,n){if(!r.length||!e.length)return null;const i=r.map(o=>e.findIndex(a=>a===o.metadata.referencedImageId)).filter(o=>o!==-1).sort((o,a)=>o-a);if(!i.length)return null;if(n===1){for(let o of i)if(o>t)return o;return i[0]}else{for(let o=i.length-1;o>=0;o--)if(i[o]`wadouri:/test_images/stack2/IMG${r+1}.dcm`),Array.from({length:25},(e,r)=>`wadouri:/test_images/stack5/IMG${r+1}.dcm`),Array.from({length:26},(e,r)=>`wadouri:/test_images/stack3/IMG${r+1}.dcm`)]}const Gb=t=>t.map(e=>e.startsWith("wadouri:")?e:`wadouri:${e}`);function dG(){document.querySelectorAll(".dicom-viewer-test-root").forEach(r=>{const n=r.id||"",i=()=>qxe();Tx(r).render(lt.jsx(Ub,{container_id:n,imageStacks:i}))}),document.querySelectorAll(".dicom-viewer-root").forEach(r=>{const n=r.id||"";let i;const o=r.getAttribute("data-images");if(o){let f;try{f=JSON.parse(o)}catch(u){console.error("Invalid data-images JSON:",u),f=[]}Array.isArray(f)&&f.length>0&&typeof f[0]=="string"?i=()=>Promise.resolve([Gb(f)]):Array.isArray(f)?i=()=>Promise.resolve(f.map(u=>Array.isArray(u)?Gb(u):[])):i=()=>Promise.resolve([[]])}else i=()=>Promise.resolve([[]]);const a=r.getAttribute("data-auto-cache-stack"),s=a==="true"||a==="1",c=r.getAttribute("data-annotationjson"),l=r.getAttribute("data-viewerstate");console.log("Mounting DICOM viewer:"),console.log(l,c,s),Tx(r).render(lt.jsx(Ub,{container_id:n,imageStacks:i,autoCacheStack:s,annotationJson:c||void 0,viewerState:l||void 0}))})}dG();window.mountDicomViewers=dG;