live-quiz 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/live-quiz.js CHANGED
@@ -2147,10 +2147,11 @@ class os extends nn {
2147
2147
  }, 200);
2148
2148
  }
2149
2149
  applySync(e) {
2150
- var t;
2151
2150
  this.activeQuizId = e.activeQuizId, this.results = e.results, e.questions && (this.questions = e.questions);
2152
- for (const n of Object.keys(this.submitted))
2153
- (((t = e.results[n]) == null ? void 0 : t.total) ?? 0) === 0 && this.clearVotedAnswer(n);
2151
+ for (const t of Object.keys(this.submitted)) {
2152
+ const n = e.results[t];
2153
+ n && n.total === 0 && this.clearVotedAnswer(t);
2154
+ }
2154
2155
  this.notifyStateChange();
2155
2156
  }
2156
2157
  // ── Persistence ──
@@ -3866,31 +3867,29 @@ function Js(s) {
3866
3867
  </div>
3867
3868
  `;
3868
3869
  }
3869
- function Hs(s, e, t, n) {
3870
- const i = e === "text" ? B`
3871
- <p class="lq-question__hint">
3872
- Open your phone and type your answer!
3873
- </p>
3874
- ` : Gs(s, n);
3870
+ function Hs(s, e, t, n, i) {
3871
+ const r = e === "text" && i ? B`
3872
+ <p class="lq-question__hint">${i}</p>
3873
+ ` : e === "text" ? null : Gs(s, n);
3875
3874
  return B`
3876
3875
  <div class="lq-question__content">
3877
3876
  <p class="lq-question__text">${t}</p>
3878
- ${i}
3877
+ ${r}
3879
3878
  ${Js(s)}
3880
3879
  </div>
3881
3880
  `;
3882
3881
  }
3883
- async function $s(s, e, t = "Pop quiz!") {
3884
- const n = s.dataset.quizId, i = s.dataset.quizQuestion || "", r = He(he, s.dataset.quizType), o = await Vs(e, s), c = B`
3882
+ async function $s(s, e, t, n) {
3883
+ const i = s.dataset.quizId, r = s.dataset.quizQuestion || "", o = He(he, s.dataset.quizType), c = await Vs(e, s), u = B`
3885
3884
  <div class="${k.question}">
3886
- <h2 class="lq-question__title">${t}</h2>
3885
+ ${t ? B`<h2 class="lq-question__title">${t}</h2>` : null}
3887
3886
  <div class="lq-question__body">
3888
- ${o}
3889
- ${Hs(n, r, i, s.dataset.quizOptions)}
3887
+ ${c}
3888
+ ${Hs(i, o, r, s.dataset.quizOptions, n)}
3890
3889
  </div>
3891
3890
  </div>
3892
3891
  `;
3893
- s.appendChild(c);
3892
+ s.appendChild(u);
3894
3893
  }
3895
3894
  function Ks(s) {
3896
3895
  const e = s.dataset.quizResults, t = s.dataset.quizQuestion || "", n = /* @__PURE__ */ G(Ze, s.dataset.quizOptions);
@@ -3990,7 +3989,8 @@ const ti = /* @__PURE__ */ N({
3990
3989
  quizGroupId: /* @__PURE__ */ K(/* @__PURE__ */ R(), /* @__PURE__ */ $(1)),
3991
3990
  quizUrl: /* @__PURE__ */ M(/* @__PURE__ */ R()),
3992
3991
  endpoints: /* @__PURE__ */ M(/* @__PURE__ */ Xe(et)),
3993
- titleText: /* @__PURE__ */ M(/* @__PURE__ */ R())
3992
+ titleText: /* @__PURE__ */ M(/* @__PURE__ */ R()),
3993
+ hintText: /* @__PURE__ */ M(/* @__PURE__ */ R())
3994
3994
  });
3995
3995
  function ui() {
3996
3996
  let s = null, e, t = null, n = null;
@@ -4049,7 +4049,7 @@ function ui() {
4049
4049
  "section[data-quiz-id]"
4050
4050
  ), f = [], d = [];
4051
4051
  for (const p of h) {
4052
- const _ = $s(p, e.quizUrl, e.titleText).catch(
4052
+ const _ = $s(p, e.quizUrl, e.titleText, e.hintText).catch(
4053
4053
  (v) => console.warn("[live-quiz] Failed to render question slide:", v)
4054
4054
  );
4055
4055
  f.push(_);
@@ -1,56 +1,54 @@
1
- (function(k,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(k=typeof globalThis<"u"?globalThis:k||self,B(k.RevealLiveQuiz={}))})(this,(function(k){"use strict";var oi=Object.defineProperty;var ci=(k,B,V)=>B in k?oi(k,B,{enumerable:!0,configurable:!0,writable:!0,value:V}):k[B]=V;var it=(k,B,V)=>ci(k,typeof B!="symbol"?B+"":B,V);let B;function V(s){return{lang:(s==null?void 0:s.lang)??(B==null?void 0:B.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(B==null?void 0:B.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(B==null?void 0:B.abortPipeEarly)}}let be;function vn(s){return be==null?void 0:be.get(s)}let ye;function Sn(s){return ye==null?void 0:ye.get(s)}let we;function En(s,e){var t;return(t=we==null?void 0:we.get(s))==null?void 0:t.get(e)}function rt(s){var t,n;const e=typeof s;return e==="string"?`"${s}"`:e==="number"||e==="bigint"||e==="boolean"?`${s}`:e==="object"||e==="function"?(s&&((n=(t=Object.getPrototypeOf(s))==null?void 0:t.constructor)==null?void 0:n.name))??"null":e}function U(s,e,t,n,i){const r=i&&"input"in i?i.input:t.value,o=(i==null?void 0:i.expected)??s.expects??null,c=(i==null?void 0:i.received)??rt(r),u={kind:s.kind,type:s.type,input:r,expected:o,received:c,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${c}`,requirement:s.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},a=s.kind==="schema",l=(i==null?void 0:i.message)??s.message??En(s.reference,u.lang)??(a?Sn(u.lang):null)??n.message??vn(u.lang);l!==void 0&&(u.message=typeof l=="function"?l(u):l),a&&(t.typed=!1),t.issues?t.issues.push(u):t.issues=[u]}function j(s){return{version:1,vendor:"valibot",validate(e){return s["~run"]({value:e},V())}}}function In(s,e){return Object.hasOwn(s,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function qn(s,e){const t=[...new Set(s)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}var Cn=class extends Error{constructor(s){super(s[0].message),this.name="ValiError",this.issues=s}};function $(s,e){return{kind:"validation",type:"min_length",reference:$,async:!1,expects:`>=${s}`,requirement:s,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&U(this,"length",t,n,{received:`${t.value.length}`}),t}}}function ot(s){return{kind:"transformation",type:"raw_transform",reference:ot,async:!1,"~run"(e,t){const n=s({dataset:e,config:t,addIssue:i=>U(this,(i==null?void 0:i.label)??"input",e,t,i),NEVER:null});return e.issues?e.typed=!1:e.value=n,e}}}function _n(s,e,t){return typeof s.fallback=="function"?s.fallback(e,t):s.fallback}function ve(s,e,t){return typeof s.default=="function"?s.default(e,t):s.default}function ee(s,e){return{kind:"schema",type:"array",reference:ee,expects:"Array",async:!1,item:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){var r;const i=t.value;if(Array.isArray(i)){t.typed=!0,t.value=[];for(let o=0;o<i.length;o++){const c=i[o],u=this.item["~run"]({value:c},n);if(u.issues){const a={type:"array",origin:"value",input:i,key:o,value:c};for(const l of u.issues)l.path?l.path.unshift(a):l.path=[a],(r=t.issues)==null||r.push(l);if(t.issues||(t.issues=u.issues),n.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value.push(u.value)}}else U(this,"type",t,n);return t}}}function ct(s){return{kind:"schema",type:"boolean",reference:ct,expects:"boolean",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="boolean"?e.typed=!0:U(this,"type",e,t),e}}}function Se(s,e){return{kind:"schema",type:"nullable",reference:Se,expects:`(${s.expects} | null)`,async:!1,wrapped:s,default:e,get"~standard"(){return j(this)},"~run"(t,n){return t.value===null&&(this.default!==void 0&&(t.value=ve(this,t,n)),t.value===null)?(t.typed=!0,t):this.wrapped["~run"](t,n)}}}function Ee(s){return{kind:"schema",type:"number",reference:Ee,expects:"number",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:U(this,"type",e,t),e}}}function L(s,e){return{kind:"schema",type:"object",reference:L,expects:"Object",async:!1,entries:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){var r;const i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(const o in this.entries){const c=this.entries[o];if(o in i||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){const u=o in i?i[o]:ve(c),a=c["~run"]({value:u},n);if(a.issues){const l={type:"object",origin:"value",input:i,key:o,value:u};for(const h of a.issues)h.path?h.path.unshift(l):h.path=[l],(r=t.issues)==null||r.push(h);if(t.issues||(t.issues=a.issues),n.abortEarly){t.typed=!1;break}}a.typed||(t.typed=!1),t.value[o]=a.value}else if(c.fallback!==void 0)t.value[o]=_n(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(U(this,"key",t,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),n.abortEarly))break}}else U(this,"type",t,n);return t}}}function N(s,e){return{kind:"schema",type:"optional",reference:N,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,default:e,get"~standard"(){return j(this)},"~run"(t,n){return t.value===void 0&&(this.default!==void 0&&(t.value=ve(this,t,n)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,n)}}}function ut(s,e){return{kind:"schema",type:"picklist",reference:ut,expects:qn(s.map(rt),"|"),async:!1,options:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){return this.options.includes(t.value)?t.typed=!0:U(this,"type",t,n),t}}}function te(s,e,t){return{kind:"schema",type:"record",reference:te,expects:"Object",async:!1,key:s,value:e,message:t,get"~standard"(){return j(this)},"~run"(n,i){var o,c;const r=n.value;if(r&&typeof r=="object"){n.typed=!0,n.value={};for(const u in r)if(In(r,u)){const a=r[u],l=this.key["~run"]({value:u},i);if(l.issues){const f={type:"object",origin:"key",input:r,key:u,value:a};for(const d of l.issues)d.path=[f],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=l.issues),i.abortEarly){n.typed=!1;break}}const h=this.value["~run"]({value:a},i);if(h.issues){const f={type:"object",origin:"value",input:r,key:u,value:a};for(const d of h.issues)d.path?d.path.unshift(f):d.path=[f],(c=n.issues)==null||c.push(d);if(n.issues||(n.issues=h.issues),i.abortEarly){n.typed=!1;break}}(!l.typed||!h.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=h.value)}}else U(this,"type",n,i);return n}}}function R(s){return{kind:"schema",type:"string",reference:R,expects:"string",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:U(this,"type",e,t),e}}}function Ie(s,e,t){const n=s["~run"]({value:e},V(t));if(n.issues)throw new Cn(n.issues);return n.value}function qe(s,e){const t={};for(const n in s.entries)t[n]=N(s.entries[n]);return{...s,entries:t,get"~standard"(){return j(this)}}}function K(...s){return{...s[0],pipe:s,get"~standard"(){return j(this)},"~run"(e,t){for(const n of s)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function G(s,e,t){const n=s["~run"]({value:e},V(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}let le=()=>({emit(s,...e){for(let t=this.events[s]||[],n=0,i=t.length;n<i;n++)t[n](...e)},events:{},on(s,e){var t;return((t=this.events)[s]||(t[s]=[])).push(e),()=>{var n;this.events[s]=(n=this.events[s])==null?void 0:n.filter(i=>e!==i)}}});class re extends Error{constructor(e,t){e instanceof Error?(super(e.message),this.cause=e):super(e),this.reason=t,this.name="ReasonError"}}class at extends re{constructor(e){super("Rejected",e),this.name="SubscriptionRejectedError"}}class Pn extends re{constructor(e){super(e||"Timed out to receive subscription ack"),this.name="SubscriptionTimeoutError"}}class F extends re{constructor(e,t){t?super(e,t):super("Disconnected",e),this.name="DisconnectedError"}}class Tn extends F{constructor(e){super(e,"stale_connection"),this.name="StaleConnectionError"}}function lt(s){return s?`{${Object.keys(s).sort().filter(t=>s[t]!==void 0).map(t=>{let n=JSON.stringify(s[t]);return`${JSON.stringify(t)}:${n}`}).join(",")}}`:""}class Rn{constructor(e){this.channel=e,this.listeners=[]}watch(){this.listeners.push(this.channel.on("presence",e=>{if(e.type==="info"){this._state||(this._state=this.stateFromInfo(e));return}this._state&&(e.type==="join"?this._state[e.id]=e.info:e.type==="leave"&&delete this._state[e.id])}))}reset(){delete this._state}dispose(){delete this._info,delete this._state,this.listeners.forEach(e=>e()),this.listeners.length=0}async join(e,t){if(!this._info)return this._info={id:String(e),info:t},this.channel.perform("$presence:join",this._info)}async leave(){if(!this._info)return;let e=await this.channel.perform("$presence:leave");return delete this._info,e}async info(){return this._state?this._state:(this._promise||(this._promise=this._sync()),await this._promise,this._state)}async _sync(){this.watch();try{let e=await this.channel.perform("$presence:info",{});return this._state=this.stateFromInfo(e),this._state}finally{delete this._promise}}stateFromInfo(e){return e.records?e.records.reduce((t,{id:n,info:i})=>(t[n]=i,t),{}):{}}}const W=Symbol("state");class ht{constructor(e={}){this.emitter=le(),this.params=Object.freeze(e),this.presence=new Rn(this),this.initialConnect=!0,this[W]="idle"}get identifier(){return this._identifier?this._identifier:(this._identifier=lt({channel:this.channelId,...this.params}),this._identifier)}get channelId(){return this.constructor.identifier}get state(){return this[W]}attached(e){if(this.receiver){if(this.receiver!==e)throw Error("Already connected to a different receiver");return!1}return this.receiver=e,!0}connecting(){this[W]="connecting"}connected(){if(this.state==="connected"||this.state==="closed")return;this[W]="connected";let e=!1;this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(){if(this.state==="connected")throw Error("Already connected");this[W]="connected";let e=!0,t=!0;this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:e})}disconnected(e){this.state==="disconnected"||this.state==="closed"||(this[W]="disconnected",this.presence.reset(),this.emit("disconnect",e))}closed(e){this.state!=="closed"&&(this[W]="closed",delete this.receiver,this.initialConnect=!0,this.presence.dispose(),this.emit("close",e))}disconnect(){this.state==="idle"||this.state==="closed"||this.receiver.unsubscribe(this)}async perform(e,t){if(this.state==="idle"||this.state==="closed")throw Error("Channel is not subscribed");return this.receiver.perform(this.identifier,e,t)}async send(e){return this.perform(void 0,e)}async whisper(e){try{await this.perform("$whisper",e)}catch(t){let n=this.receiver?this.receiver.logger:null;n&&n.warn("whisper failed: ",t)}}receive(e,t){this.emit("message",e,t)}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}emit(e,...t){return this.emitter.emit(e,...t)}ensureSubscribed(){return this.state==="connected"?Promise.resolve():this.state==="closed"?Promise.reject(Error("Channel is unsubscribed")):this.pendingSubscribe()}pendingSubscribe(){return this._pendingSubscribe?this._pendingSubscribe:(this._pendingSubscribe=new Promise((e,t)=>{let n=[()=>delete this._pendingSubscribe];n.push(this.on("connect",()=>{n.forEach(i=>i()),e()})),n.push(this.on("close",i=>{n.forEach(r=>r()),t(i||new re("Channel was disconnected before subscribing","canceled"))}))}),this._pendingSubscribe)}}class zn{constructor(e){this.id=e,this.intent="unsubscribed",this.state="idle",this.channels=[],this.disposed=!1,this._pendings=[]}add(e){this.channels.includes(e)||this.channels.push(e)}remove(e){let t=this.channels.indexOf(e);t>-1&&this.channels.splice(t,1)}notify(e,...t){this.state=e==="restored"?"connected":e,t.length===1?this.channels.forEach(n=>n[e](t[0])):this.channels.forEach(n=>n[e]())}pending(e){this._checkIntent(e);let t=this._pendings[0];return!t||t.intent!==e?Promise.resolve():t.promise}ensureResubscribed(){this.disposed||(this.intent=void 0,this.ensureSubscribed())}ensureSubscribed(){if(this.intent==="subscribed")return;if(this.disposed)throw Error("Subscription is disposed");this.intent="subscribed",!this._mergeWithPending("unsubscribed")&&this.subscriber(this)}maybeUnsubscribe(){this.disposed||this.intent==="unsubscribed"||this.channels.length>0||(this.intent="unsubscribed",this._mergeWithPending("subscribed"))||this.unsubscriber(this)}async acquire(e){this._checkIntent(e);let t,i={promise:new Promise(o=>{t=o}),intent:e,release:()=>{this._pendings.splice(this._pendings.indexOf(i),1),t(i)},canceled:!1,acquired:!1},r=this._pendingTop;return this._pendings.push(i),r&&await r.promise,this.gvl&&await this.gvl.acquire(i,e),i.acquired=!0,i}close(e){this.disposed=!0,this.intent=void 0,this.notify("closed",e)}_checkIntent(e){if(!(e==="unsubscribed"||e==="subscribed"))throw Error(`Unknown subscription intent: ${e}`)}get _pendingTop(){return this._pendings.length?this._pendings[this._pendings.length-1]:void 0}_mergeWithPending(e){let t=this._pendingTop;return!t||t.acquired||t.intent!==e?!1:(this._pendings.pop(),t.canceled=!0,!0)}}class kn{constructor(){this.queue=[]}async acquire(e,t){t==="subscribed"&&(this.queue.push(e.promise.then(()=>{this.queue.splice(this.queue.indexOf(e),1)})),this.queue.length>1&&await this.queue[this.queue.length-2])}}class An{constructor(e){e.concurrentSubscribes===!1&&(this.glv=new kn),this._subscriptions={},this._localToRemote={}}all(){return Object.values(this._subscriptions)}get(e){return this._subscriptions[e]}create(e,{subscribe:t,unsubscribe:n}){let i=this._subscriptions[e]=new zn(e);return i.remoteId=this._localToRemote[e],i.subscriber=t,i.unsubscriber=n,i.gvl=this.glv,i}remove(e){delete this._subscriptions[e],delete this._localToRemote[e]}storeRemoteId(e,t){this._localToRemote[e]=t;let n=this.get(e);n&&(n.remoteId=t)}}class Mn{constructor(e={}){this.subscriptions=new An(e),this._pendingMessages=[],this._remoteToLocal={}}subscribe(e,t){this._remoteToLocal[t]=e,this.subscriptions.storeRemoteId(e,t),this.flush(t)}unsubscribe(e){let t=this.subscriptions.get(e);if(!t)return;let n=t.remoteId;n&&delete this._remoteToLocal[n],this.subscriptions.remove(e)}transmit(e,t,n){let i=this._remoteToLocal[e];if(!i){this._pendingMessages.push([e,t,n]);return}let r=this.subscriptions.get(i);r&&r.channels.forEach(o=>{o.receive(t,n)})}notify(e,t,n){let i=this._remoteToLocal[e];if(!i)return;let r=this.subscriptions.get(i);r&&r.channels.forEach(o=>o.emit(t,n))}close(){this._pendingMessages.length=0}get size(){return this.channels.length}get channels(){return this.subscriptions.all().flatMap(e=>e.channels)}flush(e){let t=[];for(let n of this._pendingMessages)n[0]===e?this.transmit(n[0],n[1],n[2]):t.push(n);this._pendingMessages=t}}const dt={debug:0,info:1,warn:2,error:3};class ft{constructor(e){this.level=e||"warn"}log(e,t,n){dt[e]<dt[this.level]||this.writeLogEntry(e,t,n)}writeLogEntry(){throw Error("Not implemented")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}class oe extends ft{writeLogEntry(){}}class Bn{encode(e){return JSON.stringify(e)}decode(e){try{return JSON.parse(e)}catch{}}}let Nn=0;class gt{constructor(e={}){let{logger:t}=e;this.logger=t||new oe,this.pendingSubscriptions={},this.pendingUnsubscriptions={},this.subscribeCooldownInterval=e.subscribeCooldownInterval||250,this.subscribeRetryInterval=e.subscribeRetryInterval||5e3}attached(e){this.cable=e}subscribe(e,t){let n={channel:e};t&&Object.assign(n,t);let i=lt(n);if(this.pendingUnsubscriptions[i]){let o=this.subscribeCooldownInterval*1.5;return this.logger.debug(`unsubscribed recently, cooldown for ${o}`,i),new Promise(c=>{setTimeout(()=>{c(this.subscribe(e,t))},o)})}if(this.pendingSubscriptions[i])return this.logger.warn("subscription is already pending, skipping",i),Promise.reject(Error("Already subscribing"));let r=this.subscribeRetryInterval;return new Promise((o,c)=>{let u=++Nn;this.pendingSubscriptions[i]={resolve:o,reject:c,id:u},this.cable.send(this.buildSubscribeRequest(i)),this.maybeRetrySubscribe(u,i,r)})}buildSubscribeRequest(e){return{command:"subscribe",identifier:e}}maybeRetrySubscribe(e,t,n){setTimeout(()=>{let i=this.pendingSubscriptions[t];i&&i.id===e&&(this.logger.warn(`no subscription ack received in ${n}ms, retrying subscribe`,t),this.cable.send(this.buildSubscribeRequest(t)),this.maybeExpireSubscribe(e,t,n))},n)}maybeExpireSubscribe(e,t,n){setTimeout(()=>{let i=this.pendingSubscriptions[t];i&&i.id===e&&(delete this.pendingSubscriptions[t],i.reject(new Pn(`Haven't received subscription ack in ${n*2}ms for ${t}`)))},n)}unsubscribe(e){return this.cable.send({command:"unsubscribe",identifier:e}),this.pendingUnsubscriptions[e]=!0,setTimeout(()=>{delete this.pendingUnsubscriptions[e]},this.subscribeCooldownInterval),Promise.resolve()}perform(e,t,n){return t==="$whisper"?this.whisper(e,n):(n||(n={}),n.action||(n.action=t),this.cable.send({command:"message",identifier:e,data:JSON.stringify(n)}),Promise.resolve())}whisper(e,t){return this.cable.send({command:"whisper",identifier:e,data:t}),Promise.resolve()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:i,reason:r,reconnect:o}=e;if(t==="ping")return this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="welcome"){let c=e.sid;return c&&this.cable.setSessionId(c),this.cable.connected()}if(t==="disconnect"){let c=new F(r);this.reset(c),o===!1?this.cable.closed(c):this.cable.disconnected(c);return}if(t==="confirm_subscription"){let c=this.pendingSubscriptions[n];if(!c){this.logger.error("subscription not found, unsubscribing",{type:t,identifier:n}),this.unsubscribe(n);return}return delete this.pendingSubscriptions[n],c.resolve(n)}if(t==="reject_subscription"){let c=this.pendingSubscriptions[n];return c?(delete this.pendingSubscriptions[n],c.reject(new at)):this.logger.error("subscription not found",{type:t,identifier:n})}if(i)return{identifier:n,message:i};this.logger.warn(`unknown message type: ${t}`,{message:e})}reset(e){for(let t in this.pendingSubscriptions)this.pendingSubscriptions[t].reject(e);this.pendingSubscriptions={}}recoverableClosure(){return!1}}const pt=()=>Date.now()/1e3|0;class Ln extends gt{constructor(e={}){super(e),this.streamsPositions={},this.subscriptionStreams={},this.pendingHistory={},this.pendingPresence={},this.presenceInfo={},this.restoreSince=e.historyTimestamp,this.disableSessionRecovery=e.disableSessionRecovery,this.restoreSince===void 0&&(this.restoreSince=pt()),this.sessionId=void 0,this.sendPongs=e.pongs}reset(e){for(let t in this.pendingPresence)this.pendingPresence[t].reject(e);return this.pendingPresence={},super.reset()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:i}=e;if(t==="disconnect")return delete this.sessionId,this.cable.setSessionId(""),super.receive(e);if(t==="reject_subscription")return super.receive(e);if(t==="confirm_subscription")return this.subscriptionStreams[n]||(this.subscriptionStreams[n]=new Set),super.receive(e);if(t==="ping")return this.restoreSince&&(this.restoreSince=pt()),this.sendPongs&&this.sendPong(),this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="confirm_history"){this.logger.debug("history result received",e),this.cable.notify("history_received",n);return}if(t==="reject_history"){this.logger.warn("failed to retrieve history",e),this.cable.notify("history_not_found",n);return}if(t==="welcome"){if(this.disableSessionRecovery||(this.sessionId=e.sid,this.sessionId&&this.cable.setSessionId(this.sessionId)),e.restored){let r=e.restored_ids||Object.keys(this.subscriptionStreams);for(let o of r)this.cable.send({identifier:o,command:"history",history:this.historyRequestFor(o)}),this.presenceInfo[o]&&this.cable.send({identifier:o,command:"join",presence:this.presenceInfo[o]});return this.cable.restored(r)}return this.cable.connected(this.sessionId)}if(t==="presence"){let r=i.type;if(r==="info"){let o=this.pendingPresence[n];o&&(delete this.pendingPresence[n],o.resolve(i))}else if(r==="error"){let o=this.pendingPresence[n];o&&(delete this.pendingPresence[n],o.reject(new Error("failed to retrieve presence")))}return{type:t,identifier:n,message:i}}if(i){let r=this.trackStreamPosition(n,e.stream_id,e.epoch,e.offset);return{identifier:n,message:i,meta:r}}this.logger.warn(`unknown message type: ${t}`,{message:e})}perform(e,t,n){switch(t){case"$presence:join":return this.join(e,n);case"$presence:leave":return this.leave(e,n);case"$presence:info":return this.presence(e,n)}return super.perform(e,t,n)}unsubscribe(e){return delete this.presenceInfo[e],super.unsubscribe(e)}buildSubscribeRequest(e){let t=super.buildSubscribeRequest(e),n=this.historyRequestFor(e);n&&(t.history=n,this.pendingHistory[e]=!0);let i=this.presenceInfo[e];return i&&(t.presence=i),t}recoverableClosure(){return!!this.sessionId}historyRequestFor(e){let t={},n=!1;if(this.subscriptionStreams[e])for(let i of this.subscriptionStreams[e]){let r=this.streamsPositions[i];r&&(n=!0,t[i]=r)}if(!(!n&&!this.restoreSince))return{since:this.restoreSince,streams:t}}trackStreamPosition(e,t,n,i){if(!(!t||!n))return this.subscriptionStreams[e]||(this.subscriptionStreams[e]=new Set),this.subscriptionStreams[e].add(t),this.streamsPositions[t]={epoch:n,offset:i},{stream:t,epoch:n,offset:i}}async sendPong(){await new Promise(e=>setTimeout(e,0)),this.cable.state==="connected"&&this.cable.send({command:"pong"})}async join(e,t){return this.presenceInfo[e]=t,this.cable.send({command:"join",identifier:e,presence:t}),Promise.resolve()}async leave(e,t){return delete this.presenceInfo[e],this.cable.send({command:"leave",identifier:e,presence:t}),Promise.resolve()}presence(e,t){return this.pendingPresence[e]?(this.logger.warn("presence is already pending, skipping",e),Promise.reject(Error("presence request is already pending"))):new Promise((n,i)=>{this.pendingPresence[e]={resolve:n,reject:i},this.cable.send({command:"presence",identifier:e,data:t})})}}class On extends re{constructor(){super("No connection","closed"),this.name="NoConnectionError"}}class mt extends ht{constructor(e,t){super(t),this.channelId=e}set channelId(e){this._channelId=e}get channelId(){return this._channelId}}it(mt,"identifier","__ghost__");const jn="$pubsub";class Ce extends ht{async perform(e,t){if(e.startsWith("$"))return super.perform(e,t);throw Error("not implemented")}}it(Ce,"identifier",jn);const Y=Symbol("state");class Fn{constructor({transport:e,protocol:t,encoder:n,logger:i,lazy:r,hubOptions:o,performFailures:c,transportConfigurator:u}){this.emitter=le(),this.transport=e,this.encoder=n,this.logger=i||new oe,this.protocol=t,this.performFailures=c||"throw",this.protocol.attached(this),this.hub=new Mn(o||{}),this[Y]="idle",this.handleClose=this.handleClose.bind(this),this.handleIncoming=this.handleIncoming.bind(this),this.transportConfigurator=u,this.transport.on("close",this.handleClose),this.transport.on("data",this.handleIncoming),this.initialConnect=!0,this.recovering=!1,r===!1&&this.connect().catch(()=>{})}get state(){return this[Y]}async connect(){if(this.state==="connected")return Promise.resolve();if(this.state==="connecting")return this.pendingConnect();let e=this.state==="idle";this[Y]="connecting";let t=this.pendingConnect();this.logger.debug("connecting");try{this.transportConfigurator&&await this.transportConfigurator(this.transport,{initial:e}),await this.transport.open()}catch(n){this.handleClose(n)}return t}setSessionId(e){this.sessionId=e,this.transport.setParam("sid",e)}connected(){if(this.state==="connected")return;this.logger.info("connected"),this[Y]="connected",this.recovering&&this.hub.subscriptions.all().forEach(t=>t.notify("disconnected",new F("recovery_failed"))),this.hub.subscriptions.all().forEach(t=>this._resubscribe(t));let e=!1;this.recovering=!1,this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(e){this.logger.info("connection recovered",{remoteIds:e}),this[Y]="connected",this.hub.subscriptions.all().forEach(i=>{e&&i.remoteId&&e.includes(i.remoteId)?i.notify("restored"):(i.notify("disconnected",new F("recovery_failed")),this._resubscribe(i))});let t=!this.initialConnect,n=!0;this.recovering=!1,this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:n})}notify(e,t,n){t&&typeof t!="string"&&(n=t,t=void 0),t?this.hub.notify(t,"info",{type:e,data:n}):this.emit("info",{type:e,data:n})}handleClose(e){this.logger.debug("transport closed",{error:e}),this.disconnected(new F(e,"transport_closed"))}disconnected(e){(this.state==="connected"||this.state==="connecting")&&(this.logger.info("disconnected",{reason:e}),this[Y]="disconnected",this.recovering=this.protocol.recoverableClosure(e),this.recovering?this.hub.subscriptions.all().forEach(t=>t.notify("connecting")):this.hub.subscriptions.all().forEach(t=>{t.notify("disconnected",e)}),this.protocol.reset(e),this.hub.close(),this.transport.close(),this.emit("disconnect",e))}closed(e){if(this.state==="closed"||this.state==="idle")return;let t;e&&(t=e instanceof F?e:new F(e,void 0)),this.logger.info("closed",{reason:e||"user"}),this[Y]="closed";let n=t||new F("cable_closed");this.hub.subscriptions.all().forEach(i=>i.notify("disconnected",n)),this.hub.close(),this.protocol.reset(),this.transport.close(),this.initialConnect=!0,this.emit("close",t)}disconnect(){this.closed()}handleIncoming(e){if(this.state==="closed"||this.state==="idle")return;let t=this.encoder.decode(e);if(t===void 0){this.logger.error("failed to decode message",{message:e});return}this.logger.debug("incoming data",t);let n=this.protocol.receive(t);if(n){this.logger.debug("processed incoming message",n);let{type:i,identifier:r,message:o,meta:c}=n;i?this.hub.notify(r,i,o):this.hub.transmit(r,o,c)}}send(e){if(this.state==="closed")throw Error("Cable is closed");let t=this.encoder.encode(e);if(t===void 0){this.logger.error("failed to encode message",{message:e});return}this.logger.debug("outgoing message",e),this.transport.send(t)}keepalive(e){this.emit("keepalive",e)}streamFrom(e){let t=new Ce({stream_name:e});return this.subscribe(t)}streamFromSigned(e){let t=new Ce({signed_stream_name:e});return this.subscribe(t)}subscribeTo(e,t){let n,i;return typeof e=="string"&&(i=e,e=mt),n=i?new e(i,t):new e(t),this.subscribe(n)}subscribe(e){if(!e.attached(this))return e;let t=e.identifier;e.connecting();let n=this.hub.subscriptions.get(t)||this.hub.subscriptions.create(t,{subscribe:i=>this._subscribe(i,e.channelId,e.params),unsubscribe:i=>this._unsubscribe(i)});return n.add(e),n.intent==="subscribed"&&n.state==="connected"&&e.connected(),n.ensureSubscribed(),e}async _resubscribe(e){e.intent!=="subscribed"||!e.channels[0]||(e.notify("connecting"),e.ensureResubscribed())}async _subscribe(e,t,n){let i=e.id;if(this.state==="idle"&&this.connect().catch(()=>{}),this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:i});return}this.logger.debug("acquiring subscribe lock",{identifier:i});let r=await e.acquire("subscribed");if(r.canceled){this.logger.debug("subscribe lock has been canceled",{identifier:i}),r.release();return}if(this.logger.debug("subscribe lock has been acquired",{identifier:i}),e.intent!=="subscribed"){this.logger.debug("cancel subscribe request, already unsubscribed"),r.release();return}if(this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:i}),r.release();return}if(e.state==="connected"){this.logger.debug("already connected, skip subscribe command",{identifier:i}),e.notify("connected"),r.release();return}let o={identifier:t,params:n};this.logger.debug("subscribing",o);try{let c=await this.protocol.subscribe(t,n);this.hub.subscribe(i,c),this.logger.debug("subscribed",{...o,remoteId:c}),e.notify("connected")}catch(c){if(c){if(c instanceof at&&this.logger.warn("rejected",o),c instanceof F){this.logger.debug("disconnected during subscription; will retry on connect",o),r.release();return}this.logger.error("failed to subscribe",{error:c,...o})}e.close(c),this.hub.unsubscribe(i)}r.release()}unsubscribe(e){let t=e.identifier,n=this.hub.subscriptions.get(t);if(!n)throw Error(`Subscription not found: ${t}`);n.remove(e),e.closed(),n.maybeUnsubscribe()}async _unsubscribe(e){let t=e.id;this.logger.debug("acquiring unsubscribe lock",{identifier:t});let n=await e.acquire("unsubscribed");if(n.canceled){this.logger.debug("unsubscribe lock has been canceled",{identifier:t}),n.release();return}if(this.logger.debug("unsubscribe lock has been acquired",{identifier:t}),e.intent!=="unsubscribed"){this.logger.debug("cancel unsubscribe, no longer needed",{identifier:t,intent:e.intent}),n.release();return}if(e.state==="disconnected"||e.state==="closed"){this.logger.debug(`already ${e.state} connected, skip unsubscribe command`,{identifier:t}),n.release();return}let i=e.remoteId;if(this.logger.debug("unsubscribing...",{remoteId:i}),this.state!=="connected"){this.logger.debug("unsubscribe skipped (cable is not connected)",{id:t}),e.close(),this.hub.unsubscribe(t),n.release();return}try{await this.protocol.unsubscribe(i),this.logger.debug("unsubscribed remotely",{id:t})}catch(r){r&&(r instanceof F?this.logger.debug("cable disconnected during the unsubscribe command execution",{id:t,error:r}):this.logger.error("unsubscribe failed",{id:t,error:r}))}e.intent==="unsubscribed"?(e.close(),this.hub.unsubscribe(t)):e.state="closed",n.release()}async perform(e,t,n){if(this.performFailures==="throw")return this._perform(e,t,n);try{return await this._perform(e,t,n)}catch(i){this.performFailures==="warn"&&this.logger.warn("perform failed",{error:i});return}}async _perform(e,t,n){if(this.state==="connecting"&&await this.pendingConnect(),this.state==="closed"||this.state==="disconnected")throw new On;let i=this.hub.subscriptions.get(e);if(!i)throw Error(`Subscription not found: ${e}`);if(await i.pending("subscribed"),i.intent!=="subscribed")throw Error(`Subscription is closed: ${e}`);let r=i.remoteId,o={id:r,action:t,payload:n};this.logger.debug("perform",o);try{let c=await this.protocol.perform(r,t,n);return c&&this.logger.debug("perform result",{message:c,request:o}),c}catch(c){throw this.logger.error("perform failed",{error:c,request:o}),c}}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}emit(e,...t){return this.emitter.emit(e,...t)}pendingConnect(){return this._pendingConnect?this._pendingConnect:(this._pendingConnect=new Promise((e,t)=>{let n=[()=>delete this._pendingConnect];n.push(this.on("connect",()=>{n.forEach(i=>i()),e()})),n.push(this.on("close",i=>{n.forEach(r=>r()),t(i)})),n.push(this.on("disconnect",i=>{n.forEach(r=>r()),t(i)}))}),this._pendingConnect)}}const Un={maxMissingPings:2,maxReconnectAttempts:1/0},ne=()=>Date.now(),bt=(s,e)=>{e=e||{};let{backoffRate:t,jitterRatio:n,maxInterval:i}=e;return t=t||2,n===void 0&&(n=.5),r=>{let o=s*t**r,c=o*t,u=o+(c-o)*Math.random(),a=2*(Math.random()-.5)*n;return u=u*(1+a),i&&i<u&&(u=i),u}};let yt=class{constructor({pingInterval:e,...t}){if(this.pingInterval=e,!this.pingInterval)throw Error(`Incorrect pingInterval is provided: ${e}`);if(t=Object.assign({},Un,t),this.strategy=t.reconnectStrategy,!this.strategy)throw Error("Reconnect strategy must be provided");this.maxMissingPings=t.maxMissingPings,this.maxReconnectAttempts=t.maxReconnectAttempts,this.logger=t.logger||new oe,this.state="pending_connect",this.attempts=0,this.disconnectedAt=ne()}watch(e){this.target=e,this.initListeners()}reconnectNow(){return this.state==="connected"||this.state==="pending_connect"||this.state==="closed"?!1:(this.cancelReconnect(),this.state="pending_connect",this.target.connect().catch(e=>{this.logger.info("Failed at reconnecting: "+e)}),!0)}initListeners(){this.unbind=[],this.unbind.push(this.target.on("connect",()=>{this.attempts=0,this.pingedAt=ne(),this.state="connected",this.cancelReconnect(),this.startPolling()})),this.unbind.push(this.target.on("disconnect",()=>{this.disconnectedAt=ne(),this.state="disconnected",this.stopPolling(),this.scheduleReconnect()})),this.unbind.push(this.target.on("close",()=>{this.disconnectedAt=ne(),this.state="closed",this.cancelReconnect(),this.stopPolling()})),this.unbind.push(this.target.on("keepalive",()=>{this.pingedAt=ne()})),this.unbind.push(()=>{this.cancelReconnect(),this.stopPolling()})}dispose(){delete this.target,this.unbind&&this.unbind.forEach(e=>e()),delete this.unbind}startPolling(){this.pollId&&clearTimeout(this.pollId);let e=this.pingInterval+(Math.random()-.5)*this.pingInterval*.5;this.pollId=setTimeout(()=>{this.checkStale(),this.state==="connected"&&this.startPolling()},e)}stopPolling(){this.pollId&&clearTimeout(this.pollId)}checkStale(){let e=ne()-this.pingedAt;e>this.maxMissingPings*this.pingInterval&&(this.logger.warn(`Stale connection: ${e}ms without pings`),this.state="pending_disconnect",this.target.disconnected(new Tn))}scheduleReconnect(){if(this.attempts>=this.maxReconnectAttempts){this.target.close();return}let e=this.strategy(this.attempts);this.attempts++,this.logger.info(`Reconnecting in ${e}ms (${this.attempts} attempt)`),this.state="pending_reconnect",this.reconnnectId=setTimeout(()=>this.reconnectNow(),e)}cancelReconnect(){this.reconnnectId&&(clearTimeout(this.reconnnectId),delete this.reconnnectId)}};class Dn{constructor(e,t={}){this.transports=e,this.transport=null,this.emitter=le(),this.unbind=[],this.logger=t.logger||new oe}displayName(){return"fallbacked transport"}async open(){for(let e=0;e<this.transports.length;e++){let t=this.transports[e];try{this.transport=t,this.resetListeners(),this.logger.debug(`Trying to connect via ${t.displayName()}`),await t.open(),this.logger.debug(`Connected via ${t.displayName()}`);return}catch(n){this.logger.debug(`Failed to connect via ${t.displayName()}: ${n.message}`)}}throw this.transport=null,this.resetListeners(),new Error("Couldn't connect via any available transport")}send(e){if(!this.transport)throw new Error("No transport is open");this.transport.send(e)}async close(){if(!this.transport)throw new Error("No transport is open");await this.transport.close(),this.transport=null}setURL(){throw new Error("Not implemented. Set URL for each transport separately")}setParam(e,t){this.transports.forEach(n=>{n.setParam(e,t)})}setToken(e,t){this.transports.forEach(n=>{n.setToken(e,t)})}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}get url(){return this.transport?this.transport.url:""}resetListeners(){this.unbind.forEach(e=>e()),this.unbind.length=0,this.transport&&this.unbind.push(this.transport.on("open",()=>{this.emitter.emit("open")}),this.transport.on("data",e=>{this.emitter.emit("data",e)}),this.transport.on("close",e=>{this.emitter.emit("close",e)}),this.transport.on("error",e=>{this.emitter.emit("error",e)}))}}class Qn{constructor(e,t={}){this.url=e;let n=t.websocketImplementation;if(n)this.Impl=n;else if(typeof WebSocket<"u")this.Impl=WebSocket;else throw new Error("No WebSocket support");this.connected=!1,this.emitter=le();let{format:i,subprotocol:r,authStrategy:o}=t;this.format=i||"text",this.connectionOptions=t.websocketOptions,this.authStrategy=o||"param",this.authProtocol="",this.subprotocol=r}displayName(){return"WebSocket("+this.url+")"}open(){let e=this.subprotocol;return this.authStrategy==="sub-protocol"&&(e=[this.subprotocol,this.authProtocol]),this.connectionOptions?this.ws=new this.Impl(this.url,e,this.connectionOptions):this.ws=new this.Impl(this.url,e),this.ws.binaryType="arraybuffer",this.initListeners(),new Promise((t,n)=>{let i=[];i.push(this.once("open",()=>{i.forEach(r=>r()),t()})),i.push(this.once("close",()=>{i.forEach(r=>r()),n(Error("WS connection closed"))}))})}setURL(e){this.url=e}setParam(e,t){let n=new URL(this.url);n.searchParams.set(e,t);let i=`${n.protocol}//${n.host}${n.pathname}?${n.searchParams}`;this.setURL(i)}setToken(e,t="jid"){if(this.authStrategy==="param")this.setParam(t,e);else if(this.authStrategy==="header"){this.connectionOptions=this.connectionOptions||{},this.connectionOptions.headers=this.connectionOptions.headers||{};let n=`x-${t}`.toLowerCase();n=Object.keys(this.connectionOptions.headers).find(r=>r.toLowerCase()===n)||n,this.connectionOptions.headers[n]=e}else if(this.authStrategy==="sub-protocol")this.authProtocol=`anycable-token.${e}`;else throw new Error("Unknown auth strategy: "+this.authStrategy)}send(e){if(!this.ws||!this.connected)throw Error("WebSocket is not connected");this.ws.send(e)}close(){this.ws?this.onclose():this.connected=!1}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}initListeners(){this.ws.onerror=e=>{this.connected&&this.emitter.emit("error",e.error||new Error("WS Error"))},this.ws.onclose=()=>{this.onclose()},this.ws.onmessage=e=>{let t=e.data;this.format==="binary"&&(t=new Uint8Array(t)),this.emitter.emit("data",t)},this.ws.onopen=()=>{this.connected=!0,this.emitter.emit("open")}}onclose(){this.ws.onclose=void 0,this.ws.onmessage=void 0,this.ws.onopen=void 0,this.ws.close(),delete this.ws,this.connected=!1,this.emitter.emit("close")}}const wt={protocol:"actioncable-v1-json",pingInterval:3e3,maxReconnectAttempts:1/0,maxMissingPings:2,logLevel:"warn",lazy:!0};function xn(s,e){if(typeof s=="object"&&typeof e>"u"&&(e=s,s=void 0),e=e||{},!s&&!e.transport)throw Error("URL or transport must be specified");e=Object.assign({},wt,e);let{protocol:t,websocketImplementation:n,websocketFormat:i,websocketOptions:r,websocketAuthStrategy:o,fallbacks:c,logLevel:u,logger:a,transport:l,encoder:h,lazy:f,monitor:d,pingInterval:p,reconnectStrategy:_,maxMissingPings:A,maxReconnectAttempts:q,subprotocol:P,tokenRefresher:v,historyTimestamp:E,protocolOptions:M,concurrentSubscribes:m,performFailures:I,transportConfigurator:S,auth:g}=e;if(a=a||new oe(u),typeof t=="string"){P=P||t;let w=t.substring(0,t.lastIndexOf("-")),y=t.substring(t.lastIndexOf("-")+1);if(M=M||{},w==="actioncable-v1")t=new gt({logger:a,...M});else if(w==="actioncable-v1-ext")t=new Ln({logger:a,historyTimestamp:E,...M});else throw Error(`Protocol is not supported yet: ${t}`);if(y==="json")h=h||new Bn,i=i||"text";else if(y==="msgpack"){if(i="binary",!h)throw Error("Msgpack encoder must be specified explicitly. Use `@anycable/msgpack-encoder` package or build your own")}else if(y==="protobuf"){if(i=i||"binary",!h)throw Error("Protobuf encoder must be specified explicitly. Use `@anycable/protobuf-encoder` package or build your own")}else throw Error(`Protocol is not supported yet: ${t}`)}if(!t)throw Error("Protocol must be specified");l=l||new Qn(s,{websocketImplementation:n,websocketOptions:r,subprotocol:P,authStrategy:o,format:i}),c&&(l=new Dn([l,...c],{logger:a})),g&&g.token&&l.setToken(g.token,g.param||"jid"),_=_||bt(p),d!==!1&&(d=d||new yt({pingInterval:p,reconnectStrategy:_,maxMissingPings:A,maxReconnectAttempts:q,logger:a}));let C={concurrentSubscribes:m},b=new Fn({protocol:t,transport:l,encoder:h,logger:a,lazy:f,hubOptions:C,performFailures:I,transportConfigurator:S});return d&&(d.watch(b),b.monitor=d),v&&Vn(b,async()=>{try{await v(l)}catch(w){return a.error("Failed to refresh authentication token: "+w),!1}return b.connect().catch(()=>{}),!0}),b}function Vn(s,e){let t=!1;s.on("connect",()=>t=!1),s.on("close",async n=>{if(n){if(t){s.logger.warn("Token auto-refresh is disabled",n);return}n.reason==="token_expired"&&(t=!0,await e())}})}class Gn extends ft{writeLogEntry(e,t,n){n?console[e](t,n):console[e](t)}}class Jn extends yt{watch(e){super.watch(e),this.initActivityListeners()}initActivityListeners(){if(typeof document<"u"&&typeof window<"u"&&document.addEventListener&&window.addEventListener){let e=()=>{document.hidden||this.reconnectNow()&&this.logger.debug("Trigger reconnect due to visibility change")},t=i=>{this.reconnectNow()&&this.logger.debug("Trigger reconnect",{event:i})},n=()=>this.disconnect(new F("page_frozen"));document.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",t,!1),window.addEventListener("online",t,!1),window.addEventListener("resume",t,!1),window.addEventListener("freeze",n,!1),this.unbind.push(()=>{document.removeEventListener("visibilitychange",e,!1),window.removeEventListener("focus",t,!1),window.removeEventListener("online",t,!1),window.removeEventListener("resume",t,!1),window.removeEventListener("freeze",n,!1)})}}disconnect(e){this.state==="disconnected"||this.state==="closed"||(this.logger.info("Disconnecting",{reason:e.message}),this.cancelReconnect(),this.stopPolling(),this.state="pending_disconnect",this.target.disconnected(e))}}const Hn=["cable","action-cable"],$n="/cable",he=(s,e)=>{for(let t of Hn){let n=s.head.querySelector(`meta[name='${t}-${e}']`);if(n)return n.getAttribute("content")}},vt=s=>s.match(/wss?:\/\//)?s:typeof window<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.host}${s}`:s,Kn=()=>{if(typeof document<"u"&&document.head){let s=he(document,"url");if(s)return vt(s)}return vt($n)},Wn=()=>{if(typeof document<"u"&&document.head){let s=he(document,"history-timestamp");if(s)return s|0}},Yn=()=>{if(typeof document<"u"&&document.head)return he(document,"token")},Xn=()=>{if(typeof document<"u"&&document.head)return he(document,"token-param")};function Zn(s,e){typeof s=="object"&&typeof e>"u"&&(e=s,s=void 0),s=s||Kn(),e=e||{},e.historyTimestamp||(e.historyTimestamp=Wn());let t=Yn();if(t){let a=Xn();e.auth=Object.assign({token:t,param:a},e.auth||{})}e=Object.assign({},wt,e);let{logLevel:n,logger:i,pingInterval:r,reconnectStrategy:o,maxMissingPings:c,maxReconnectAttempts:u}=e;return i=e.logger=e.logger||new Gn(n),o=e.reconnectStrategy=e.reconnectStrategy||bt(r),e.monitor!==!1&&(e.monitor=e.monitor||new Jn({pingInterval:r,reconnectStrategy:o,maxMissingPings:c,maxReconnectAttempts:u,logger:i})),xn(s,e)}const ce=N(ut(["choice","text"]),"choice"),St=L({votes:te(R(),Ee()),total:Ee()}),Et=L({quizId:R(),question:R(),type:ce,options:N(ee(L({label:R(),text:R()})),[])}),es=L({activeQuizId:Se(R()),sessionId:R(),results:te(R(),St),questions:N(ee(Et))}),ts=L({quizId:R(),answer:R(),sessionId:R()}),It=L({label:R(),text:R(),correct:N(ct())}),_e=K(N(R(),"[]"),ot(({dataset:s,addIssue:e,NEVER:t})=>{try{return JSON.parse(s.value)}catch{return e({message:"Invalid JSON"}),t}}),ee(It)),de=L({answer:R(),sync:R()}),ns=L({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),sessionId:N(R()),endpoints:N(qe(de))}),ss=L({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),questions:N(ee(Et)),endpoints:N(qe(de)),brandText:N(R()),footerText:N(R())}),is=L({activeQuizId:N(Se(R())),results:N(te(R(),St)),voters:N(te(R(),ee(R())))}),rs=te(R(),R()),Pe=.8,qt=3;function Ct(s){const e=Object.entries(s);if(e.length===0)return[];const t=Math.max(...e.map(([,n])=>n));return e.map(([n,i])=>({word:n,count:i,fontSize:t>1?Pe+(i-1)/(t-1)*(qt-Pe):(Pe+qt)/2,isTop:i===t}))}function _t(s){return`quiz:${s}:results`}function Pt(s){return`quiz:${s}:sync`}const os={answer:"/.netlify/functions/quiz-answer",sync:"/.netlify/functions/quiz-sync"};function Tt(s){return G(es,s).success}function cs(s){return G(ts,s).success}class Te{constructor(e,t){this.activeQuizId=null,this.results={},this.online=0,this.submitted={},this.questions=[],this.listeners=[],this.quizGroupId=e.quizGroupId,this.sessionId=e.sessionId||this.getOrCreateSessionId(),this.endpoints={...os,...e.endpoints},this.cable=Zn(e.wsUrl,{protocol:"actioncable-v1-ext-json",protocolOptions:{historyTimestamp:Math.floor((Date.now()-t)/1e3)}}),this.syncChannel=this.cable.streamFrom(Pt(e.quizGroupId)),this.syncChannel.on("message",this.onSyncMessage.bind(this));const n=this.syncChannel.presence;if(typeof n.stateFromInfo=="function"){const i=n.stateFromInfo.bind(n);n.stateFromInfo=r=>{if(!(r!=null&&r.records)){if(r&&typeof r=="object"){const{type:o,...c}=r;return c}return{}}return i(r)}}this.syncChannel.on("presence",this.onPresence.bind(this)),this.syncChannel.presence.info().then(i=>{i&&(this.online=Object.keys(i).length,this.notifyStateChange())}).catch(()=>{})}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{const t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}}getState(){return{activeQuizId:this.activeQuizId,results:structuredClone(this.results),online:this.online,submitted:{...this.submitted},questions:structuredClone(this.questions)}}getQuizState(e){return this.results[e]||{votes:{},total:0}}hasVoted(e){return e in this.submitted}getVotedAnswer(e){return this.submitted[e]??null}disconnect(){this.cable.disconnect()}onSyncMessage(e){}async onPresence(){try{const e=await this.syncChannel.presence.info();e&&(this.online=Object.keys(e).length,this.notifyStateChange())}catch{}}getOrCreateSessionId(){const e=`quiz-session-${this.quizGroupId}`;let t=sessionStorage.getItem(e);return t||(t=crypto.randomUUID(),sessionStorage.setItem(e,t)),t}notifyStateChange(){const e=this.getState();for(const t of this.listeners)t(e)}parse(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return}return e}}class Rt extends Te{constructor(e){super(e,3e5),this.voters={},this.syncTimer=null,this.syncPending=!1,this.resultsChannel=this.cable.streamFrom(_t(e.quizGroupId)),this.resultsChannel.on("message",this.onResultsMessage.bind(this)),this.restoreState(),this.activeQuizId&&this.sendSync()}setQuestions(e){this.questions=e}setActiveQuiz(e){this.activeQuizId!==e&&(this.activeQuizId=e,this.saveState(),this.sendSync())}onSyncMessage(e){const t=this.parse(e);Tt(t)&&(t.sessionId,this.sessionId)}async onPresence(){try{const e=await this.syncChannel.presence.info();e&&(this.online=Object.keys(e).length,this.notifyStateChange(),this.activeQuizId&&this.sendSyncThrottled())}catch{}}getQuizType(e){var t;return((t=this.questions.find(n=>n.quizId===e))==null?void 0:t.type)??"choice"}normalizeAnswer(e,t){return this.getQuizType(e)==="text"?t.trim().toLowerCase():t}onResultsMessage(e){const t=this.parse(e);if(!cs(t)||t.sessionId===this.sessionId)return;const{quizId:n,sessionId:i}=t,r=this.normalizeAnswer(n,t.answer);this.voters[n]||(this.voters[n]=new Set),!this.voters[n].has(i)&&(this.voters[n].add(i),this.results[n]||(this.results[n]={votes:{},total:0}),this.results[n].votes[r]=(this.results[n].votes[r]||0)+1,this.results[n].total+=1,this.saveState(),this.notifyStateChange(),this.sendSyncThrottled())}sendSyncThrottled(){if(this.syncTimer){this.syncPending=!0;return}this.sendSync(),this.syncTimer=setTimeout(()=>{this.syncTimer=null,this.syncPending&&(this.syncPending=!1,this.sendSync())},200)}async sendSync(){try{await fetch(this.endpoints.sync,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({activeQuizId:this.activeQuizId,sessionId:this.sessionId,quizGroupId:this.quizGroupId,results:this.results,questions:this.questions})})}catch{}}saveState(){try{sessionStorage.setItem(`quiz-presenter-${this.quizGroupId}`,JSON.stringify({activeQuizId:this.activeQuizId,results:this.results,voters:Object.fromEntries(Object.entries(this.voters).map(([e,t])=>[e,[...t]]))}))}catch(e){console.warn("[QuizManager] saveState failed:",e)}}restoreState(){try{const e=sessionStorage.getItem(`quiz-presenter-${this.quizGroupId}`);if(!e)return;const t=G(is,JSON.parse(e));if(!t.success)return;const n=t.output;if(n.activeQuizId&&(this.activeQuizId=n.activeQuizId),n.results&&(this.results=n.results),n.voters)for(const[i,r]of Object.entries(n.voters))this.voters[i]=new Set(r)}catch{}}}class zt extends Te{constructor(e){super(e,6e4),this.incomingSyncTimer=null,this.incomingSyncData=null,this.syncChannel.presence.join(this.sessionId,{id:this.sessionId}),this.restoreSubmitted()}async submitAnswer(e,t){if(this.hasVoted(e))return!1;try{const n=await fetch(this.endpoints.answer,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quizId:e,answer:t,sessionId:this.sessionId,quizGroupId:this.quizGroupId})});return n.ok&&(this.submitted[e]=t,this.saveSubmitted(),this.notifyStateChange()),n.ok}catch{return!1}}disconnect(){this.syncChannel.presence.leave(),this.cable.disconnect()}onSyncMessage(e){const t=this.parse(e);Tt(t)&&t.sessionId!==this.sessionId&&this.applySyncThrottled(t)}applySyncThrottled(e){if(this.incomingSyncTimer){this.incomingSyncData=e;return}this.applySync(e),this.incomingSyncData=null,this.incomingSyncTimer=setTimeout(()=>{this.incomingSyncTimer=null,this.incomingSyncData&&(this.applySync(this.incomingSyncData),this.incomingSyncData=null)},200)}applySync(e){var t;this.activeQuizId=e.activeQuizId,this.results=e.results,e.questions&&(this.questions=e.questions);for(const n of Object.keys(this.submitted))(((t=e.results[n])==null?void 0:t.total)??0)===0&&this.clearVotedAnswer(n);this.notifyStateChange()}saveSubmitted(){try{sessionStorage.setItem(`quiz-submitted-${this.quizGroupId}`,JSON.stringify(this.submitted))}catch{}}restoreSubmitted(){try{const e=sessionStorage.getItem(`quiz-submitted-${this.quizGroupId}`);if(!e)return;const t=G(rs,JSON.parse(e));if(!t.success)return;this.submitted=t.output}catch{}}clearVotedAnswer(e){delete this.submitted[e],this.saveSubmitted()}}const fe=new Map;function kt(s){return fe.has(s.quizGroupId)||fe.set(s.quizGroupId,new Rt(s)),fe.get(s.quizGroupId)}function At(s){fe.delete(s)}const ge=new Map;function us(s){return ge.has(s.quizGroupId)||ge.set(s.quizGroupId,new zt(s)),ge.get(s.quizGroupId)}function as(s){ge.delete(s)}function Re(s,e){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){s.textContent=String(e);return}const n=parseInt(s.textContent||"0",10);if(n===e)return;const i=300,r=performance.now(),o=n;function c(u){const a=u-r,l=Math.min(a/i,1),h=1-Math.pow(1-l,3),f=Math.round(o+(e-o)*h);s.textContent=String(f),l<1&&requestAnimationFrame(c)}requestAnimationFrame(c)}function ls(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var se={},ze,Mt;function hs(){return Mt||(Mt=1,ze=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ze}var ke={},J={},Bt;function X(){if(Bt)return J;Bt=1;let s;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return J.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},J.getSymbolTotalCodewords=function(n){return e[n]},J.getBCHDigit=function(t){let n=0;for(;t!==0;)n++,t>>>=1;return n},J.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');s=n},J.isKanjiModeEnabled=function(){return typeof s<"u"},J.toSJIS=function(n){return s(n)},J}var Ae={},Nt;function Me(){return Nt||(Nt=1,(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function e(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+t)}}s.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},s.from=function(n,i){if(s.isValid(n))return n;try{return e(n)}catch{return i}}})(Ae)),Ae}var Be,Lt;function ds(){if(Lt)return Be;Lt=1;function s(){this.buffer=[],this.length=0}return s.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},Be=s,Be}var Ne,Ot;function fs(){if(Ot)return Ne;Ot=1;function s(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return s.prototype.set=function(e,t,n,i){const r=e*this.size+t;this.data[r]=n,i&&(this.reservedBit[r]=!0)},s.prototype.get=function(e,t){return this.data[e*this.size+t]},s.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},s.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},Ne=s,Ne}var Le={},jt;function gs(){return jt||(jt=1,(function(s){const e=X().getSymbolSize;s.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,r=e(n),o=r===145?26:Math.ceil((r-13)/(2*i-2))*2,c=[r-7];for(let u=1;u<i-1;u++)c[u]=c[u-1]-o;return c.push(6),c.reverse()},s.getPositions=function(n){const i=[],r=s.getRowColCoords(n),o=r.length;for(let c=0;c<o;c++)for(let u=0;u<o;u++)c===0&&u===0||c===0&&u===o-1||c===o-1&&u===0||i.push([r[c],r[u]]);return i}})(Le)),Le}var Oe={},Ft;function ps(){if(Ft)return Oe;Ft=1;const s=X().getSymbolSize,e=7;return Oe.getPositions=function(n){const i=s(n);return[[0,0],[i-e,0],[0,i-e]]},Oe}var je={},Ut;function ms(){return Ut||(Ut=1,(function(s){s.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};s.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},s.from=function(i){return s.isValid(i)?parseInt(i,10):void 0},s.getPenaltyN1=function(i){const r=i.size;let o=0,c=0,u=0,a=null,l=null;for(let h=0;h<r;h++){c=u=0,a=l=null;for(let f=0;f<r;f++){let d=i.get(h,f);d===a?c++:(c>=5&&(o+=e.N1+(c-5)),a=d,c=1),d=i.get(f,h),d===l?u++:(u>=5&&(o+=e.N1+(u-5)),l=d,u=1)}c>=5&&(o+=e.N1+(c-5)),u>=5&&(o+=e.N1+(u-5))}return o},s.getPenaltyN2=function(i){const r=i.size;let o=0;for(let c=0;c<r-1;c++)for(let u=0;u<r-1;u++){const a=i.get(c,u)+i.get(c,u+1)+i.get(c+1,u)+i.get(c+1,u+1);(a===4||a===0)&&o++}return o*e.N2},s.getPenaltyN3=function(i){const r=i.size;let o=0,c=0,u=0;for(let a=0;a<r;a++){c=u=0;for(let l=0;l<r;l++)c=c<<1&2047|i.get(a,l),l>=10&&(c===1488||c===93)&&o++,u=u<<1&2047|i.get(l,a),l>=10&&(u===1488||u===93)&&o++}return o*e.N3},s.getPenaltyN4=function(i){let r=0;const o=i.data.length;for(let u=0;u<o;u++)r+=i.data[u];return Math.abs(Math.ceil(r*100/o/5)-10)*e.N4};function t(n,i,r){switch(n){case s.Patterns.PATTERN000:return(i+r)%2===0;case s.Patterns.PATTERN001:return i%2===0;case s.Patterns.PATTERN010:return r%3===0;case s.Patterns.PATTERN011:return(i+r)%3===0;case s.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(r/3))%2===0;case s.Patterns.PATTERN101:return i*r%2+i*r%3===0;case s.Patterns.PATTERN110:return(i*r%2+i*r%3)%2===0;case s.Patterns.PATTERN111:return(i*r%3+(i+r)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}s.applyMask=function(i,r){const o=r.size;for(let c=0;c<o;c++)for(let u=0;u<o;u++)r.isReserved(u,c)||r.xor(u,c,t(i,u,c))},s.getBestMask=function(i,r){const o=Object.keys(s.Patterns).length;let c=0,u=1/0;for(let a=0;a<o;a++){r(a),s.applyMask(a,i);const l=s.getPenaltyN1(i)+s.getPenaltyN2(i)+s.getPenaltyN3(i)+s.getPenaltyN4(i);s.applyMask(a,i),l<u&&(u=l,c=a)}return c}})(je)),je}var pe={},Dt;function Qt(){if(Dt)return pe;Dt=1;const s=Me(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],t=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return pe.getBlocksCount=function(i,r){switch(r){case s.L:return e[(i-1)*4+0];case s.M:return e[(i-1)*4+1];case s.Q:return e[(i-1)*4+2];case s.H:return e[(i-1)*4+3];default:return}},pe.getTotalCodewordsCount=function(i,r){switch(r){case s.L:return t[(i-1)*4+0];case s.M:return t[(i-1)*4+1];case s.Q:return t[(i-1)*4+2];case s.H:return t[(i-1)*4+3];default:return}},pe}var Fe={},ue={},xt;function bs(){if(xt)return ue;xt=1;const s=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)s[i]=n,e[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)s[i]=s[i-255]})(),ue.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},ue.exp=function(n){return s[n]},ue.mul=function(n,i){return n===0||i===0?0:s[e[n]+e[i]]},ue}var Vt;function ys(){return Vt||(Vt=1,(function(s){const e=bs();s.mul=function(n,i){const r=new Uint8Array(n.length+i.length-1);for(let o=0;o<n.length;o++)for(let c=0;c<i.length;c++)r[o+c]^=e.mul(n[o],i[c]);return r},s.mod=function(n,i){let r=new Uint8Array(n);for(;r.length-i.length>=0;){const o=r[0];for(let u=0;u<i.length;u++)r[u]^=e.mul(i[u],o);let c=0;for(;c<r.length&&r[c]===0;)c++;r=r.slice(c)}return r},s.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let r=0;r<n;r++)i=s.mul(i,new Uint8Array([1,e.exp(r)]));return i}})(Fe)),Fe}var Ue,Gt;function ws(){if(Gt)return Ue;Gt=1;const s=ys();function e(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=s.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const r=s.mod(i,this.genPoly),o=this.degree-r.length;if(o>0){const c=new Uint8Array(this.degree);return c.set(r,o),c}return r},Ue=e,Ue}var De={},Qe={},xe={},Jt;function Ht(){return Jt||(Jt=1,xe.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),xe}var D={},$t;function Kt(){if($t)return D;$t=1;const s="[0-9]+",e="[A-Z $%*+\\-./:]+";let t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";t=t.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+t+`)(?:.|[\r
1
+ (function(k,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(k=typeof globalThis<"u"?globalThis:k||self,B(k.RevealLiveQuiz={}))})(this,(function(k){"use strict";var oi=Object.defineProperty;var ci=(k,B,V)=>B in k?oi(k,B,{enumerable:!0,configurable:!0,writable:!0,value:V}):k[B]=V;var it=(k,B,V)=>ci(k,typeof B!="symbol"?B+"":B,V);let B;function V(s){return{lang:(s==null?void 0:s.lang)??(B==null?void 0:B.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(B==null?void 0:B.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(B==null?void 0:B.abortPipeEarly)}}let be;function vn(s){return be==null?void 0:be.get(s)}let ye;function Sn(s){return ye==null?void 0:ye.get(s)}let we;function En(s,e){var t;return(t=we==null?void 0:we.get(s))==null?void 0:t.get(e)}function rt(s){var t,n;const e=typeof s;return e==="string"?`"${s}"`:e==="number"||e==="bigint"||e==="boolean"?`${s}`:e==="object"||e==="function"?(s&&((n=(t=Object.getPrototypeOf(s))==null?void 0:t.constructor)==null?void 0:n.name))??"null":e}function U(s,e,t,n,i){const r=i&&"input"in i?i.input:t.value,o=(i==null?void 0:i.expected)??s.expects??null,c=(i==null?void 0:i.received)??rt(r),u={kind:s.kind,type:s.type,input:r,expected:o,received:c,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${c}`,requirement:s.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},a=s.kind==="schema",l=(i==null?void 0:i.message)??s.message??En(s.reference,u.lang)??(a?Sn(u.lang):null)??n.message??vn(u.lang);l!==void 0&&(u.message=typeof l=="function"?l(u):l),a&&(t.typed=!1),t.issues?t.issues.push(u):t.issues=[u]}function j(s){return{version:1,vendor:"valibot",validate(e){return s["~run"]({value:e},V())}}}function In(s,e){return Object.hasOwn(s,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}function qn(s,e){const t=[...new Set(s)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}var Cn=class extends Error{constructor(s){super(s[0].message),this.name="ValiError",this.issues=s}};function $(s,e){return{kind:"validation",type:"min_length",reference:$,async:!1,expects:`>=${s}`,requirement:s,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&U(this,"length",t,n,{received:`${t.value.length}`}),t}}}function ot(s){return{kind:"transformation",type:"raw_transform",reference:ot,async:!1,"~run"(e,t){const n=s({dataset:e,config:t,addIssue:i=>U(this,(i==null?void 0:i.label)??"input",e,t,i),NEVER:null});return e.issues?e.typed=!1:e.value=n,e}}}function _n(s,e,t){return typeof s.fallback=="function"?s.fallback(e,t):s.fallback}function ve(s,e,t){return typeof s.default=="function"?s.default(e,t):s.default}function ee(s,e){return{kind:"schema",type:"array",reference:ee,expects:"Array",async:!1,item:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){var r;const i=t.value;if(Array.isArray(i)){t.typed=!0,t.value=[];for(let o=0;o<i.length;o++){const c=i[o],u=this.item["~run"]({value:c},n);if(u.issues){const a={type:"array",origin:"value",input:i,key:o,value:c};for(const l of u.issues)l.path?l.path.unshift(a):l.path=[a],(r=t.issues)==null||r.push(l);if(t.issues||(t.issues=u.issues),n.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value.push(u.value)}}else U(this,"type",t,n);return t}}}function ct(s){return{kind:"schema",type:"boolean",reference:ct,expects:"boolean",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="boolean"?e.typed=!0:U(this,"type",e,t),e}}}function Se(s,e){return{kind:"schema",type:"nullable",reference:Se,expects:`(${s.expects} | null)`,async:!1,wrapped:s,default:e,get"~standard"(){return j(this)},"~run"(t,n){return t.value===null&&(this.default!==void 0&&(t.value=ve(this,t,n)),t.value===null)?(t.typed=!0,t):this.wrapped["~run"](t,n)}}}function Ee(s){return{kind:"schema",type:"number",reference:Ee,expects:"number",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:U(this,"type",e,t),e}}}function O(s,e){return{kind:"schema",type:"object",reference:O,expects:"Object",async:!1,entries:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){var r;const i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(const o in this.entries){const c=this.entries[o];if(o in i||(c.type==="exact_optional"||c.type==="optional"||c.type==="nullish")&&c.default!==void 0){const u=o in i?i[o]:ve(c),a=c["~run"]({value:u},n);if(a.issues){const l={type:"object",origin:"value",input:i,key:o,value:u};for(const h of a.issues)h.path?h.path.unshift(l):h.path=[l],(r=t.issues)==null||r.push(h);if(t.issues||(t.issues=a.issues),n.abortEarly){t.typed=!1;break}}a.typed||(t.typed=!1),t.value[o]=a.value}else if(c.fallback!==void 0)t.value[o]=_n(c);else if(c.type!=="exact_optional"&&c.type!=="optional"&&c.type!=="nullish"&&(U(this,"key",t,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),n.abortEarly))break}}else U(this,"type",t,n);return t}}}function N(s,e){return{kind:"schema",type:"optional",reference:N,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,default:e,get"~standard"(){return j(this)},"~run"(t,n){return t.value===void 0&&(this.default!==void 0&&(t.value=ve(this,t,n)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,n)}}}function ut(s,e){return{kind:"schema",type:"picklist",reference:ut,expects:qn(s.map(rt),"|"),async:!1,options:s,message:e,get"~standard"(){return j(this)},"~run"(t,n){return this.options.includes(t.value)?t.typed=!0:U(this,"type",t,n),t}}}function te(s,e,t){return{kind:"schema",type:"record",reference:te,expects:"Object",async:!1,key:s,value:e,message:t,get"~standard"(){return j(this)},"~run"(n,i){var o,c;const r=n.value;if(r&&typeof r=="object"){n.typed=!0,n.value={};for(const u in r)if(In(r,u)){const a=r[u],l=this.key["~run"]({value:u},i);if(l.issues){const f={type:"object",origin:"key",input:r,key:u,value:a};for(const d of l.issues)d.path=[f],(o=n.issues)==null||o.push(d);if(n.issues||(n.issues=l.issues),i.abortEarly){n.typed=!1;break}}const h=this.value["~run"]({value:a},i);if(h.issues){const f={type:"object",origin:"value",input:r,key:u,value:a};for(const d of h.issues)d.path?d.path.unshift(f):d.path=[f],(c=n.issues)==null||c.push(d);if(n.issues||(n.issues=h.issues),i.abortEarly){n.typed=!1;break}}(!l.typed||!h.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=h.value)}}else U(this,"type",n,i);return n}}}function R(s){return{kind:"schema",type:"string",reference:R,expects:"string",async:!1,message:s,get"~standard"(){return j(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:U(this,"type",e,t),e}}}function Ie(s,e,t){const n=s["~run"]({value:e},V(t));if(n.issues)throw new Cn(n.issues);return n.value}function qe(s,e){const t={};for(const n in s.entries)t[n]=N(s.entries[n]);return{...s,entries:t,get"~standard"(){return j(this)}}}function K(...s){return{...s[0],pipe:s,get"~standard"(){return j(this)},"~run"(e,t){for(const n of s)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function G(s,e,t){const n=s["~run"]({value:e},V(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}let le=()=>({emit(s,...e){for(let t=this.events[s]||[],n=0,i=t.length;n<i;n++)t[n](...e)},events:{},on(s,e){var t;return((t=this.events)[s]||(t[s]=[])).push(e),()=>{var n;this.events[s]=(n=this.events[s])==null?void 0:n.filter(i=>e!==i)}}});class re extends Error{constructor(e,t){e instanceof Error?(super(e.message),this.cause=e):super(e),this.reason=t,this.name="ReasonError"}}class at extends re{constructor(e){super("Rejected",e),this.name="SubscriptionRejectedError"}}class Pn extends re{constructor(e){super(e||"Timed out to receive subscription ack"),this.name="SubscriptionTimeoutError"}}class F extends re{constructor(e,t){t?super(e,t):super("Disconnected",e),this.name="DisconnectedError"}}class Tn extends F{constructor(e){super(e,"stale_connection"),this.name="StaleConnectionError"}}function lt(s){return s?`{${Object.keys(s).sort().filter(t=>s[t]!==void 0).map(t=>{let n=JSON.stringify(s[t]);return`${JSON.stringify(t)}:${n}`}).join(",")}}`:""}class Rn{constructor(e){this.channel=e,this.listeners=[]}watch(){this.listeners.push(this.channel.on("presence",e=>{if(e.type==="info"){this._state||(this._state=this.stateFromInfo(e));return}this._state&&(e.type==="join"?this._state[e.id]=e.info:e.type==="leave"&&delete this._state[e.id])}))}reset(){delete this._state}dispose(){delete this._info,delete this._state,this.listeners.forEach(e=>e()),this.listeners.length=0}async join(e,t){if(!this._info)return this._info={id:String(e),info:t},this.channel.perform("$presence:join",this._info)}async leave(){if(!this._info)return;let e=await this.channel.perform("$presence:leave");return delete this._info,e}async info(){return this._state?this._state:(this._promise||(this._promise=this._sync()),await this._promise,this._state)}async _sync(){this.watch();try{let e=await this.channel.perform("$presence:info",{});return this._state=this.stateFromInfo(e),this._state}finally{delete this._promise}}stateFromInfo(e){return e.records?e.records.reduce((t,{id:n,info:i})=>(t[n]=i,t),{}):{}}}const W=Symbol("state");class ht{constructor(e={}){this.emitter=le(),this.params=Object.freeze(e),this.presence=new Rn(this),this.initialConnect=!0,this[W]="idle"}get identifier(){return this._identifier?this._identifier:(this._identifier=lt({channel:this.channelId,...this.params}),this._identifier)}get channelId(){return this.constructor.identifier}get state(){return this[W]}attached(e){if(this.receiver){if(this.receiver!==e)throw Error("Already connected to a different receiver");return!1}return this.receiver=e,!0}connecting(){this[W]="connecting"}connected(){if(this.state==="connected"||this.state==="closed")return;this[W]="connected";let e=!1;this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(){if(this.state==="connected")throw Error("Already connected");this[W]="connected";let e=!0,t=!0;this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:e})}disconnected(e){this.state==="disconnected"||this.state==="closed"||(this[W]="disconnected",this.presence.reset(),this.emit("disconnect",e))}closed(e){this.state!=="closed"&&(this[W]="closed",delete this.receiver,this.initialConnect=!0,this.presence.dispose(),this.emit("close",e))}disconnect(){this.state==="idle"||this.state==="closed"||this.receiver.unsubscribe(this)}async perform(e,t){if(this.state==="idle"||this.state==="closed")throw Error("Channel is not subscribed");return this.receiver.perform(this.identifier,e,t)}async send(e){return this.perform(void 0,e)}async whisper(e){try{await this.perform("$whisper",e)}catch(t){let n=this.receiver?this.receiver.logger:null;n&&n.warn("whisper failed: ",t)}}receive(e,t){this.emit("message",e,t)}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}emit(e,...t){return this.emitter.emit(e,...t)}ensureSubscribed(){return this.state==="connected"?Promise.resolve():this.state==="closed"?Promise.reject(Error("Channel is unsubscribed")):this.pendingSubscribe()}pendingSubscribe(){return this._pendingSubscribe?this._pendingSubscribe:(this._pendingSubscribe=new Promise((e,t)=>{let n=[()=>delete this._pendingSubscribe];n.push(this.on("connect",()=>{n.forEach(i=>i()),e()})),n.push(this.on("close",i=>{n.forEach(r=>r()),t(i||new re("Channel was disconnected before subscribing","canceled"))}))}),this._pendingSubscribe)}}class zn{constructor(e){this.id=e,this.intent="unsubscribed",this.state="idle",this.channels=[],this.disposed=!1,this._pendings=[]}add(e){this.channels.includes(e)||this.channels.push(e)}remove(e){let t=this.channels.indexOf(e);t>-1&&this.channels.splice(t,1)}notify(e,...t){this.state=e==="restored"?"connected":e,t.length===1?this.channels.forEach(n=>n[e](t[0])):this.channels.forEach(n=>n[e]())}pending(e){this._checkIntent(e);let t=this._pendings[0];return!t||t.intent!==e?Promise.resolve():t.promise}ensureResubscribed(){this.disposed||(this.intent=void 0,this.ensureSubscribed())}ensureSubscribed(){if(this.intent==="subscribed")return;if(this.disposed)throw Error("Subscription is disposed");this.intent="subscribed",!this._mergeWithPending("unsubscribed")&&this.subscriber(this)}maybeUnsubscribe(){this.disposed||this.intent==="unsubscribed"||this.channels.length>0||(this.intent="unsubscribed",this._mergeWithPending("subscribed"))||this.unsubscriber(this)}async acquire(e){this._checkIntent(e);let t,i={promise:new Promise(o=>{t=o}),intent:e,release:()=>{this._pendings.splice(this._pendings.indexOf(i),1),t(i)},canceled:!1,acquired:!1},r=this._pendingTop;return this._pendings.push(i),r&&await r.promise,this.gvl&&await this.gvl.acquire(i,e),i.acquired=!0,i}close(e){this.disposed=!0,this.intent=void 0,this.notify("closed",e)}_checkIntent(e){if(!(e==="unsubscribed"||e==="subscribed"))throw Error(`Unknown subscription intent: ${e}`)}get _pendingTop(){return this._pendings.length?this._pendings[this._pendings.length-1]:void 0}_mergeWithPending(e){let t=this._pendingTop;return!t||t.acquired||t.intent!==e?!1:(this._pendings.pop(),t.canceled=!0,!0)}}class kn{constructor(){this.queue=[]}async acquire(e,t){t==="subscribed"&&(this.queue.push(e.promise.then(()=>{this.queue.splice(this.queue.indexOf(e),1)})),this.queue.length>1&&await this.queue[this.queue.length-2])}}class An{constructor(e){e.concurrentSubscribes===!1&&(this.glv=new kn),this._subscriptions={},this._localToRemote={}}all(){return Object.values(this._subscriptions)}get(e){return this._subscriptions[e]}create(e,{subscribe:t,unsubscribe:n}){let i=this._subscriptions[e]=new zn(e);return i.remoteId=this._localToRemote[e],i.subscriber=t,i.unsubscriber=n,i.gvl=this.glv,i}remove(e){delete this._subscriptions[e],delete this._localToRemote[e]}storeRemoteId(e,t){this._localToRemote[e]=t;let n=this.get(e);n&&(n.remoteId=t)}}class Mn{constructor(e={}){this.subscriptions=new An(e),this._pendingMessages=[],this._remoteToLocal={}}subscribe(e,t){this._remoteToLocal[t]=e,this.subscriptions.storeRemoteId(e,t),this.flush(t)}unsubscribe(e){let t=this.subscriptions.get(e);if(!t)return;let n=t.remoteId;n&&delete this._remoteToLocal[n],this.subscriptions.remove(e)}transmit(e,t,n){let i=this._remoteToLocal[e];if(!i){this._pendingMessages.push([e,t,n]);return}let r=this.subscriptions.get(i);r&&r.channels.forEach(o=>{o.receive(t,n)})}notify(e,t,n){let i=this._remoteToLocal[e];if(!i)return;let r=this.subscriptions.get(i);r&&r.channels.forEach(o=>o.emit(t,n))}close(){this._pendingMessages.length=0}get size(){return this.channels.length}get channels(){return this.subscriptions.all().flatMap(e=>e.channels)}flush(e){let t=[];for(let n of this._pendingMessages)n[0]===e?this.transmit(n[0],n[1],n[2]):t.push(n);this._pendingMessages=t}}const dt={debug:0,info:1,warn:2,error:3};class ft{constructor(e){this.level=e||"warn"}log(e,t,n){dt[e]<dt[this.level]||this.writeLogEntry(e,t,n)}writeLogEntry(){throw Error("Not implemented")}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}class oe extends ft{writeLogEntry(){}}class Bn{encode(e){return JSON.stringify(e)}decode(e){try{return JSON.parse(e)}catch{}}}let Nn=0;class gt{constructor(e={}){let{logger:t}=e;this.logger=t||new oe,this.pendingSubscriptions={},this.pendingUnsubscriptions={},this.subscribeCooldownInterval=e.subscribeCooldownInterval||250,this.subscribeRetryInterval=e.subscribeRetryInterval||5e3}attached(e){this.cable=e}subscribe(e,t){let n={channel:e};t&&Object.assign(n,t);let i=lt(n);if(this.pendingUnsubscriptions[i]){let o=this.subscribeCooldownInterval*1.5;return this.logger.debug(`unsubscribed recently, cooldown for ${o}`,i),new Promise(c=>{setTimeout(()=>{c(this.subscribe(e,t))},o)})}if(this.pendingSubscriptions[i])return this.logger.warn("subscription is already pending, skipping",i),Promise.reject(Error("Already subscribing"));let r=this.subscribeRetryInterval;return new Promise((o,c)=>{let u=++Nn;this.pendingSubscriptions[i]={resolve:o,reject:c,id:u},this.cable.send(this.buildSubscribeRequest(i)),this.maybeRetrySubscribe(u,i,r)})}buildSubscribeRequest(e){return{command:"subscribe",identifier:e}}maybeRetrySubscribe(e,t,n){setTimeout(()=>{let i=this.pendingSubscriptions[t];i&&i.id===e&&(this.logger.warn(`no subscription ack received in ${n}ms, retrying subscribe`,t),this.cable.send(this.buildSubscribeRequest(t)),this.maybeExpireSubscribe(e,t,n))},n)}maybeExpireSubscribe(e,t,n){setTimeout(()=>{let i=this.pendingSubscriptions[t];i&&i.id===e&&(delete this.pendingSubscriptions[t],i.reject(new Pn(`Haven't received subscription ack in ${n*2}ms for ${t}`)))},n)}unsubscribe(e){return this.cable.send({command:"unsubscribe",identifier:e}),this.pendingUnsubscriptions[e]=!0,setTimeout(()=>{delete this.pendingUnsubscriptions[e]},this.subscribeCooldownInterval),Promise.resolve()}perform(e,t,n){return t==="$whisper"?this.whisper(e,n):(n||(n={}),n.action||(n.action=t),this.cable.send({command:"message",identifier:e,data:JSON.stringify(n)}),Promise.resolve())}whisper(e,t){return this.cable.send({command:"whisper",identifier:e,data:t}),Promise.resolve()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:i,reason:r,reconnect:o}=e;if(t==="ping")return this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="welcome"){let c=e.sid;return c&&this.cable.setSessionId(c),this.cable.connected()}if(t==="disconnect"){let c=new F(r);this.reset(c),o===!1?this.cable.closed(c):this.cable.disconnected(c);return}if(t==="confirm_subscription"){let c=this.pendingSubscriptions[n];if(!c){this.logger.error("subscription not found, unsubscribing",{type:t,identifier:n}),this.unsubscribe(n);return}return delete this.pendingSubscriptions[n],c.resolve(n)}if(t==="reject_subscription"){let c=this.pendingSubscriptions[n];return c?(delete this.pendingSubscriptions[n],c.reject(new at)):this.logger.error("subscription not found",{type:t,identifier:n})}if(i)return{identifier:n,message:i};this.logger.warn(`unknown message type: ${t}`,{message:e})}reset(e){for(let t in this.pendingSubscriptions)this.pendingSubscriptions[t].reject(e);this.pendingSubscriptions={}}recoverableClosure(){return!1}}const pt=()=>Date.now()/1e3|0;class Ln extends gt{constructor(e={}){super(e),this.streamsPositions={},this.subscriptionStreams={},this.pendingHistory={},this.pendingPresence={},this.presenceInfo={},this.restoreSince=e.historyTimestamp,this.disableSessionRecovery=e.disableSessionRecovery,this.restoreSince===void 0&&(this.restoreSince=pt()),this.sessionId=void 0,this.sendPongs=e.pongs}reset(e){for(let t in this.pendingPresence)this.pendingPresence[t].reject(e);return this.pendingPresence={},super.reset()}receive(e){if(typeof e!="object"){this.logger.error("unsupported message format",{message:e});return}let{type:t,identifier:n,message:i}=e;if(t==="disconnect")return delete this.sessionId,this.cable.setSessionId(""),super.receive(e);if(t==="reject_subscription")return super.receive(e);if(t==="confirm_subscription")return this.subscriptionStreams[n]||(this.subscriptionStreams[n]=new Set),super.receive(e);if(t==="ping")return this.restoreSince&&(this.restoreSince=pt()),this.sendPongs&&this.sendPong(),this.cable.keepalive(e.message);if(this.cable.keepalive(),t==="confirm_history"){this.logger.debug("history result received",e),this.cable.notify("history_received",n);return}if(t==="reject_history"){this.logger.warn("failed to retrieve history",e),this.cable.notify("history_not_found",n);return}if(t==="welcome"){if(this.disableSessionRecovery||(this.sessionId=e.sid,this.sessionId&&this.cable.setSessionId(this.sessionId)),e.restored){let r=e.restored_ids||Object.keys(this.subscriptionStreams);for(let o of r)this.cable.send({identifier:o,command:"history",history:this.historyRequestFor(o)}),this.presenceInfo[o]&&this.cable.send({identifier:o,command:"join",presence:this.presenceInfo[o]});return this.cable.restored(r)}return this.cable.connected(this.sessionId)}if(t==="presence"){let r=i.type;if(r==="info"){let o=this.pendingPresence[n];o&&(delete this.pendingPresence[n],o.resolve(i))}else if(r==="error"){let o=this.pendingPresence[n];o&&(delete this.pendingPresence[n],o.reject(new Error("failed to retrieve presence")))}return{type:t,identifier:n,message:i}}if(i){let r=this.trackStreamPosition(n,e.stream_id,e.epoch,e.offset);return{identifier:n,message:i,meta:r}}this.logger.warn(`unknown message type: ${t}`,{message:e})}perform(e,t,n){switch(t){case"$presence:join":return this.join(e,n);case"$presence:leave":return this.leave(e,n);case"$presence:info":return this.presence(e,n)}return super.perform(e,t,n)}unsubscribe(e){return delete this.presenceInfo[e],super.unsubscribe(e)}buildSubscribeRequest(e){let t=super.buildSubscribeRequest(e),n=this.historyRequestFor(e);n&&(t.history=n,this.pendingHistory[e]=!0);let i=this.presenceInfo[e];return i&&(t.presence=i),t}recoverableClosure(){return!!this.sessionId}historyRequestFor(e){let t={},n=!1;if(this.subscriptionStreams[e])for(let i of this.subscriptionStreams[e]){let r=this.streamsPositions[i];r&&(n=!0,t[i]=r)}if(!(!n&&!this.restoreSince))return{since:this.restoreSince,streams:t}}trackStreamPosition(e,t,n,i){if(!(!t||!n))return this.subscriptionStreams[e]||(this.subscriptionStreams[e]=new Set),this.subscriptionStreams[e].add(t),this.streamsPositions[t]={epoch:n,offset:i},{stream:t,epoch:n,offset:i}}async sendPong(){await new Promise(e=>setTimeout(e,0)),this.cable.state==="connected"&&this.cable.send({command:"pong"})}async join(e,t){return this.presenceInfo[e]=t,this.cable.send({command:"join",identifier:e,presence:t}),Promise.resolve()}async leave(e,t){return delete this.presenceInfo[e],this.cable.send({command:"leave",identifier:e,presence:t}),Promise.resolve()}presence(e,t){return this.pendingPresence[e]?(this.logger.warn("presence is already pending, skipping",e),Promise.reject(Error("presence request is already pending"))):new Promise((n,i)=>{this.pendingPresence[e]={resolve:n,reject:i},this.cable.send({command:"presence",identifier:e,data:t})})}}class On extends re{constructor(){super("No connection","closed"),this.name="NoConnectionError"}}class mt extends ht{constructor(e,t){super(t),this.channelId=e}set channelId(e){this._channelId=e}get channelId(){return this._channelId}}it(mt,"identifier","__ghost__");const jn="$pubsub";class Ce extends ht{async perform(e,t){if(e.startsWith("$"))return super.perform(e,t);throw Error("not implemented")}}it(Ce,"identifier",jn);const Y=Symbol("state");class Fn{constructor({transport:e,protocol:t,encoder:n,logger:i,lazy:r,hubOptions:o,performFailures:c,transportConfigurator:u}){this.emitter=le(),this.transport=e,this.encoder=n,this.logger=i||new oe,this.protocol=t,this.performFailures=c||"throw",this.protocol.attached(this),this.hub=new Mn(o||{}),this[Y]="idle",this.handleClose=this.handleClose.bind(this),this.handleIncoming=this.handleIncoming.bind(this),this.transportConfigurator=u,this.transport.on("close",this.handleClose),this.transport.on("data",this.handleIncoming),this.initialConnect=!0,this.recovering=!1,r===!1&&this.connect().catch(()=>{})}get state(){return this[Y]}async connect(){if(this.state==="connected")return Promise.resolve();if(this.state==="connecting")return this.pendingConnect();let e=this.state==="idle";this[Y]="connecting";let t=this.pendingConnect();this.logger.debug("connecting");try{this.transportConfigurator&&await this.transportConfigurator(this.transport,{initial:e}),await this.transport.open()}catch(n){this.handleClose(n)}return t}setSessionId(e){this.sessionId=e,this.transport.setParam("sid",e)}connected(){if(this.state==="connected")return;this.logger.info("connected"),this[Y]="connected",this.recovering&&this.hub.subscriptions.all().forEach(t=>t.notify("disconnected",new F("recovery_failed"))),this.hub.subscriptions.all().forEach(t=>this._resubscribe(t));let e=!1;this.recovering=!1,this.initialConnect?(this.initialConnect=!1,this.emit("connect",{reconnect:!1,restored:e})):this.emit("connect",{reconnect:!0,restored:e})}restored(e){this.logger.info("connection recovered",{remoteIds:e}),this[Y]="connected",this.hub.subscriptions.all().forEach(i=>{e&&i.remoteId&&e.includes(i.remoteId)?i.notify("restored"):(i.notify("disconnected",new F("recovery_failed")),this._resubscribe(i))});let t=!this.initialConnect,n=!0;this.recovering=!1,this.initialConnect=!1,this.emit("connect",{reconnect:t,restored:n})}notify(e,t,n){t&&typeof t!="string"&&(n=t,t=void 0),t?this.hub.notify(t,"info",{type:e,data:n}):this.emit("info",{type:e,data:n})}handleClose(e){this.logger.debug("transport closed",{error:e}),this.disconnected(new F(e,"transport_closed"))}disconnected(e){(this.state==="connected"||this.state==="connecting")&&(this.logger.info("disconnected",{reason:e}),this[Y]="disconnected",this.recovering=this.protocol.recoverableClosure(e),this.recovering?this.hub.subscriptions.all().forEach(t=>t.notify("connecting")):this.hub.subscriptions.all().forEach(t=>{t.notify("disconnected",e)}),this.protocol.reset(e),this.hub.close(),this.transport.close(),this.emit("disconnect",e))}closed(e){if(this.state==="closed"||this.state==="idle")return;let t;e&&(t=e instanceof F?e:new F(e,void 0)),this.logger.info("closed",{reason:e||"user"}),this[Y]="closed";let n=t||new F("cable_closed");this.hub.subscriptions.all().forEach(i=>i.notify("disconnected",n)),this.hub.close(),this.protocol.reset(),this.transport.close(),this.initialConnect=!0,this.emit("close",t)}disconnect(){this.closed()}handleIncoming(e){if(this.state==="closed"||this.state==="idle")return;let t=this.encoder.decode(e);if(t===void 0){this.logger.error("failed to decode message",{message:e});return}this.logger.debug("incoming data",t);let n=this.protocol.receive(t);if(n){this.logger.debug("processed incoming message",n);let{type:i,identifier:r,message:o,meta:c}=n;i?this.hub.notify(r,i,o):this.hub.transmit(r,o,c)}}send(e){if(this.state==="closed")throw Error("Cable is closed");let t=this.encoder.encode(e);if(t===void 0){this.logger.error("failed to encode message",{message:e});return}this.logger.debug("outgoing message",e),this.transport.send(t)}keepalive(e){this.emit("keepalive",e)}streamFrom(e){let t=new Ce({stream_name:e});return this.subscribe(t)}streamFromSigned(e){let t=new Ce({signed_stream_name:e});return this.subscribe(t)}subscribeTo(e,t){let n,i;return typeof e=="string"&&(i=e,e=mt),n=i?new e(i,t):new e(t),this.subscribe(n)}subscribe(e){if(!e.attached(this))return e;let t=e.identifier;e.connecting();let n=this.hub.subscriptions.get(t)||this.hub.subscriptions.create(t,{subscribe:i=>this._subscribe(i,e.channelId,e.params),unsubscribe:i=>this._unsubscribe(i)});return n.add(e),n.intent==="subscribed"&&n.state==="connected"&&e.connected(),n.ensureSubscribed(),e}async _resubscribe(e){e.intent!=="subscribed"||!e.channels[0]||(e.notify("connecting"),e.ensureResubscribed())}async _subscribe(e,t,n){let i=e.id;if(this.state==="idle"&&this.connect().catch(()=>{}),this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:i});return}this.logger.debug("acquiring subscribe lock",{identifier:i});let r=await e.acquire("subscribed");if(r.canceled){this.logger.debug("subscribe lock has been canceled",{identifier:i}),r.release();return}if(this.logger.debug("subscribe lock has been acquired",{identifier:i}),e.intent!=="subscribed"){this.logger.debug("cancel subscribe request, already unsubscribed"),r.release();return}if(this.state!=="connected"){this.logger.debug("cancel subscribe, no connection",{identifier:i}),r.release();return}if(e.state==="connected"){this.logger.debug("already connected, skip subscribe command",{identifier:i}),e.notify("connected"),r.release();return}let o={identifier:t,params:n};this.logger.debug("subscribing",o);try{let c=await this.protocol.subscribe(t,n);this.hub.subscribe(i,c),this.logger.debug("subscribed",{...o,remoteId:c}),e.notify("connected")}catch(c){if(c){if(c instanceof at&&this.logger.warn("rejected",o),c instanceof F){this.logger.debug("disconnected during subscription; will retry on connect",o),r.release();return}this.logger.error("failed to subscribe",{error:c,...o})}e.close(c),this.hub.unsubscribe(i)}r.release()}unsubscribe(e){let t=e.identifier,n=this.hub.subscriptions.get(t);if(!n)throw Error(`Subscription not found: ${t}`);n.remove(e),e.closed(),n.maybeUnsubscribe()}async _unsubscribe(e){let t=e.id;this.logger.debug("acquiring unsubscribe lock",{identifier:t});let n=await e.acquire("unsubscribed");if(n.canceled){this.logger.debug("unsubscribe lock has been canceled",{identifier:t}),n.release();return}if(this.logger.debug("unsubscribe lock has been acquired",{identifier:t}),e.intent!=="unsubscribed"){this.logger.debug("cancel unsubscribe, no longer needed",{identifier:t,intent:e.intent}),n.release();return}if(e.state==="disconnected"||e.state==="closed"){this.logger.debug(`already ${e.state} connected, skip unsubscribe command`,{identifier:t}),n.release();return}let i=e.remoteId;if(this.logger.debug("unsubscribing...",{remoteId:i}),this.state!=="connected"){this.logger.debug("unsubscribe skipped (cable is not connected)",{id:t}),e.close(),this.hub.unsubscribe(t),n.release();return}try{await this.protocol.unsubscribe(i),this.logger.debug("unsubscribed remotely",{id:t})}catch(r){r&&(r instanceof F?this.logger.debug("cable disconnected during the unsubscribe command execution",{id:t,error:r}):this.logger.error("unsubscribe failed",{id:t,error:r}))}e.intent==="unsubscribed"?(e.close(),this.hub.unsubscribe(t)):e.state="closed",n.release()}async perform(e,t,n){if(this.performFailures==="throw")return this._perform(e,t,n);try{return await this._perform(e,t,n)}catch(i){this.performFailures==="warn"&&this.logger.warn("perform failed",{error:i});return}}async _perform(e,t,n){if(this.state==="connecting"&&await this.pendingConnect(),this.state==="closed"||this.state==="disconnected")throw new On;let i=this.hub.subscriptions.get(e);if(!i)throw Error(`Subscription not found: ${e}`);if(await i.pending("subscribed"),i.intent!=="subscribed")throw Error(`Subscription is closed: ${e}`);let r=i.remoteId,o={id:r,action:t,payload:n};this.logger.debug("perform",o);try{let c=await this.protocol.perform(r,t,n);return c&&this.logger.debug("perform result",{message:c,request:o}),c}catch(c){throw this.logger.error("perform failed",{error:c,request:o}),c}}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}emit(e,...t){return this.emitter.emit(e,...t)}pendingConnect(){return this._pendingConnect?this._pendingConnect:(this._pendingConnect=new Promise((e,t)=>{let n=[()=>delete this._pendingConnect];n.push(this.on("connect",()=>{n.forEach(i=>i()),e()})),n.push(this.on("close",i=>{n.forEach(r=>r()),t(i)})),n.push(this.on("disconnect",i=>{n.forEach(r=>r()),t(i)}))}),this._pendingConnect)}}const Un={maxMissingPings:2,maxReconnectAttempts:1/0},ne=()=>Date.now(),bt=(s,e)=>{e=e||{};let{backoffRate:t,jitterRatio:n,maxInterval:i}=e;return t=t||2,n===void 0&&(n=.5),r=>{let o=s*t**r,c=o*t,u=o+(c-o)*Math.random(),a=2*(Math.random()-.5)*n;return u=u*(1+a),i&&i<u&&(u=i),u}};let yt=class{constructor({pingInterval:e,...t}){if(this.pingInterval=e,!this.pingInterval)throw Error(`Incorrect pingInterval is provided: ${e}`);if(t=Object.assign({},Un,t),this.strategy=t.reconnectStrategy,!this.strategy)throw Error("Reconnect strategy must be provided");this.maxMissingPings=t.maxMissingPings,this.maxReconnectAttempts=t.maxReconnectAttempts,this.logger=t.logger||new oe,this.state="pending_connect",this.attempts=0,this.disconnectedAt=ne()}watch(e){this.target=e,this.initListeners()}reconnectNow(){return this.state==="connected"||this.state==="pending_connect"||this.state==="closed"?!1:(this.cancelReconnect(),this.state="pending_connect",this.target.connect().catch(e=>{this.logger.info("Failed at reconnecting: "+e)}),!0)}initListeners(){this.unbind=[],this.unbind.push(this.target.on("connect",()=>{this.attempts=0,this.pingedAt=ne(),this.state="connected",this.cancelReconnect(),this.startPolling()})),this.unbind.push(this.target.on("disconnect",()=>{this.disconnectedAt=ne(),this.state="disconnected",this.stopPolling(),this.scheduleReconnect()})),this.unbind.push(this.target.on("close",()=>{this.disconnectedAt=ne(),this.state="closed",this.cancelReconnect(),this.stopPolling()})),this.unbind.push(this.target.on("keepalive",()=>{this.pingedAt=ne()})),this.unbind.push(()=>{this.cancelReconnect(),this.stopPolling()})}dispose(){delete this.target,this.unbind&&this.unbind.forEach(e=>e()),delete this.unbind}startPolling(){this.pollId&&clearTimeout(this.pollId);let e=this.pingInterval+(Math.random()-.5)*this.pingInterval*.5;this.pollId=setTimeout(()=>{this.checkStale(),this.state==="connected"&&this.startPolling()},e)}stopPolling(){this.pollId&&clearTimeout(this.pollId)}checkStale(){let e=ne()-this.pingedAt;e>this.maxMissingPings*this.pingInterval&&(this.logger.warn(`Stale connection: ${e}ms without pings`),this.state="pending_disconnect",this.target.disconnected(new Tn))}scheduleReconnect(){if(this.attempts>=this.maxReconnectAttempts){this.target.close();return}let e=this.strategy(this.attempts);this.attempts++,this.logger.info(`Reconnecting in ${e}ms (${this.attempts} attempt)`),this.state="pending_reconnect",this.reconnnectId=setTimeout(()=>this.reconnectNow(),e)}cancelReconnect(){this.reconnnectId&&(clearTimeout(this.reconnnectId),delete this.reconnnectId)}};class Dn{constructor(e,t={}){this.transports=e,this.transport=null,this.emitter=le(),this.unbind=[],this.logger=t.logger||new oe}displayName(){return"fallbacked transport"}async open(){for(let e=0;e<this.transports.length;e++){let t=this.transports[e];try{this.transport=t,this.resetListeners(),this.logger.debug(`Trying to connect via ${t.displayName()}`),await t.open(),this.logger.debug(`Connected via ${t.displayName()}`);return}catch(n){this.logger.debug(`Failed to connect via ${t.displayName()}: ${n.message}`)}}throw this.transport=null,this.resetListeners(),new Error("Couldn't connect via any available transport")}send(e){if(!this.transport)throw new Error("No transport is open");this.transport.send(e)}async close(){if(!this.transport)throw new Error("No transport is open");await this.transport.close(),this.transport=null}setURL(){throw new Error("Not implemented. Set URL for each transport separately")}setParam(e,t){this.transports.forEach(n=>{n.setParam(e,t)})}setToken(e,t){this.transports.forEach(n=>{n.setToken(e,t)})}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}get url(){return this.transport?this.transport.url:""}resetListeners(){this.unbind.forEach(e=>e()),this.unbind.length=0,this.transport&&this.unbind.push(this.transport.on("open",()=>{this.emitter.emit("open")}),this.transport.on("data",e=>{this.emitter.emit("data",e)}),this.transport.on("close",e=>{this.emitter.emit("close",e)}),this.transport.on("error",e=>{this.emitter.emit("error",e)}))}}class Qn{constructor(e,t={}){this.url=e;let n=t.websocketImplementation;if(n)this.Impl=n;else if(typeof WebSocket<"u")this.Impl=WebSocket;else throw new Error("No WebSocket support");this.connected=!1,this.emitter=le();let{format:i,subprotocol:r,authStrategy:o}=t;this.format=i||"text",this.connectionOptions=t.websocketOptions,this.authStrategy=o||"param",this.authProtocol="",this.subprotocol=r}displayName(){return"WebSocket("+this.url+")"}open(){let e=this.subprotocol;return this.authStrategy==="sub-protocol"&&(e=[this.subprotocol,this.authProtocol]),this.connectionOptions?this.ws=new this.Impl(this.url,e,this.connectionOptions):this.ws=new this.Impl(this.url,e),this.ws.binaryType="arraybuffer",this.initListeners(),new Promise((t,n)=>{let i=[];i.push(this.once("open",()=>{i.forEach(r=>r()),t()})),i.push(this.once("close",()=>{i.forEach(r=>r()),n(Error("WS connection closed"))}))})}setURL(e){this.url=e}setParam(e,t){let n=new URL(this.url);n.searchParams.set(e,t);let i=`${n.protocol}//${n.host}${n.pathname}?${n.searchParams}`;this.setURL(i)}setToken(e,t="jid"){if(this.authStrategy==="param")this.setParam(t,e);else if(this.authStrategy==="header"){this.connectionOptions=this.connectionOptions||{},this.connectionOptions.headers=this.connectionOptions.headers||{};let n=`x-${t}`.toLowerCase();n=Object.keys(this.connectionOptions.headers).find(r=>r.toLowerCase()===n)||n,this.connectionOptions.headers[n]=e}else if(this.authStrategy==="sub-protocol")this.authProtocol=`anycable-token.${e}`;else throw new Error("Unknown auth strategy: "+this.authStrategy)}send(e){if(!this.ws||!this.connected)throw Error("WebSocket is not connected");this.ws.send(e)}close(){this.ws?this.onclose():this.connected=!1}on(e,t){return this.emitter.on(e,t)}once(e,t){let n=this.emitter.on(e,(...i)=>{n(),t(...i)});return n}initListeners(){this.ws.onerror=e=>{this.connected&&this.emitter.emit("error",e.error||new Error("WS Error"))},this.ws.onclose=()=>{this.onclose()},this.ws.onmessage=e=>{let t=e.data;this.format==="binary"&&(t=new Uint8Array(t)),this.emitter.emit("data",t)},this.ws.onopen=()=>{this.connected=!0,this.emitter.emit("open")}}onclose(){this.ws.onclose=void 0,this.ws.onmessage=void 0,this.ws.onopen=void 0,this.ws.close(),delete this.ws,this.connected=!1,this.emitter.emit("close")}}const wt={protocol:"actioncable-v1-json",pingInterval:3e3,maxReconnectAttempts:1/0,maxMissingPings:2,logLevel:"warn",lazy:!0};function xn(s,e){if(typeof s=="object"&&typeof e>"u"&&(e=s,s=void 0),e=e||{},!s&&!e.transport)throw Error("URL or transport must be specified");e=Object.assign({},wt,e);let{protocol:t,websocketImplementation:n,websocketFormat:i,websocketOptions:r,websocketAuthStrategy:o,fallbacks:c,logLevel:u,logger:a,transport:l,encoder:h,lazy:f,monitor:d,pingInterval:p,reconnectStrategy:_,maxMissingPings:A,maxReconnectAttempts:q,subprotocol:P,tokenRefresher:v,historyTimestamp:E,protocolOptions:M,concurrentSubscribes:m,performFailures:I,transportConfigurator:S,auth:g}=e;if(a=a||new oe(u),typeof t=="string"){P=P||t;let w=t.substring(0,t.lastIndexOf("-")),y=t.substring(t.lastIndexOf("-")+1);if(M=M||{},w==="actioncable-v1")t=new gt({logger:a,...M});else if(w==="actioncable-v1-ext")t=new Ln({logger:a,historyTimestamp:E,...M});else throw Error(`Protocol is not supported yet: ${t}`);if(y==="json")h=h||new Bn,i=i||"text";else if(y==="msgpack"){if(i="binary",!h)throw Error("Msgpack encoder must be specified explicitly. Use `@anycable/msgpack-encoder` package or build your own")}else if(y==="protobuf"){if(i=i||"binary",!h)throw Error("Protobuf encoder must be specified explicitly. Use `@anycable/protobuf-encoder` package or build your own")}else throw Error(`Protocol is not supported yet: ${t}`)}if(!t)throw Error("Protocol must be specified");l=l||new Qn(s,{websocketImplementation:n,websocketOptions:r,subprotocol:P,authStrategy:o,format:i}),c&&(l=new Dn([l,...c],{logger:a})),g&&g.token&&l.setToken(g.token,g.param||"jid"),_=_||bt(p),d!==!1&&(d=d||new yt({pingInterval:p,reconnectStrategy:_,maxMissingPings:A,maxReconnectAttempts:q,logger:a}));let C={concurrentSubscribes:m},b=new Fn({protocol:t,transport:l,encoder:h,logger:a,lazy:f,hubOptions:C,performFailures:I,transportConfigurator:S});return d&&(d.watch(b),b.monitor=d),v&&Vn(b,async()=>{try{await v(l)}catch(w){return a.error("Failed to refresh authentication token: "+w),!1}return b.connect().catch(()=>{}),!0}),b}function Vn(s,e){let t=!1;s.on("connect",()=>t=!1),s.on("close",async n=>{if(n){if(t){s.logger.warn("Token auto-refresh is disabled",n);return}n.reason==="token_expired"&&(t=!0,await e())}})}class Gn extends ft{writeLogEntry(e,t,n){n?console[e](t,n):console[e](t)}}class Jn extends yt{watch(e){super.watch(e),this.initActivityListeners()}initActivityListeners(){if(typeof document<"u"&&typeof window<"u"&&document.addEventListener&&window.addEventListener){let e=()=>{document.hidden||this.reconnectNow()&&this.logger.debug("Trigger reconnect due to visibility change")},t=i=>{this.reconnectNow()&&this.logger.debug("Trigger reconnect",{event:i})},n=()=>this.disconnect(new F("page_frozen"));document.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",t,!1),window.addEventListener("online",t,!1),window.addEventListener("resume",t,!1),window.addEventListener("freeze",n,!1),this.unbind.push(()=>{document.removeEventListener("visibilitychange",e,!1),window.removeEventListener("focus",t,!1),window.removeEventListener("online",t,!1),window.removeEventListener("resume",t,!1),window.removeEventListener("freeze",n,!1)})}}disconnect(e){this.state==="disconnected"||this.state==="closed"||(this.logger.info("Disconnecting",{reason:e.message}),this.cancelReconnect(),this.stopPolling(),this.state="pending_disconnect",this.target.disconnected(e))}}const Hn=["cable","action-cable"],$n="/cable",he=(s,e)=>{for(let t of Hn){let n=s.head.querySelector(`meta[name='${t}-${e}']`);if(n)return n.getAttribute("content")}},vt=s=>s.match(/wss?:\/\//)?s:typeof window<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.host}${s}`:s,Kn=()=>{if(typeof document<"u"&&document.head){let s=he(document,"url");if(s)return vt(s)}return vt($n)},Wn=()=>{if(typeof document<"u"&&document.head){let s=he(document,"history-timestamp");if(s)return s|0}},Yn=()=>{if(typeof document<"u"&&document.head)return he(document,"token")},Xn=()=>{if(typeof document<"u"&&document.head)return he(document,"token-param")};function Zn(s,e){typeof s=="object"&&typeof e>"u"&&(e=s,s=void 0),s=s||Kn(),e=e||{},e.historyTimestamp||(e.historyTimestamp=Wn());let t=Yn();if(t){let a=Xn();e.auth=Object.assign({token:t,param:a},e.auth||{})}e=Object.assign({},wt,e);let{logLevel:n,logger:i,pingInterval:r,reconnectStrategy:o,maxMissingPings:c,maxReconnectAttempts:u}=e;return i=e.logger=e.logger||new Gn(n),o=e.reconnectStrategy=e.reconnectStrategy||bt(r),e.monitor!==!1&&(e.monitor=e.monitor||new Jn({pingInterval:r,reconnectStrategy:o,maxMissingPings:c,maxReconnectAttempts:u,logger:i})),xn(s,e)}const ce=N(ut(["choice","text"]),"choice"),St=O({votes:te(R(),Ee()),total:Ee()}),Et=O({quizId:R(),question:R(),type:ce,options:N(ee(O({label:R(),text:R()})),[])}),es=O({activeQuizId:Se(R()),sessionId:R(),results:te(R(),St),questions:N(ee(Et))}),ts=O({quizId:R(),answer:R(),sessionId:R()}),It=O({label:R(),text:R(),correct:N(ct())}),_e=K(N(R(),"[]"),ot(({dataset:s,addIssue:e,NEVER:t})=>{try{return JSON.parse(s.value)}catch{return e({message:"Invalid JSON"}),t}}),ee(It)),de=O({answer:R(),sync:R()}),ns=O({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),sessionId:N(R()),endpoints:N(qe(de))}),ss=O({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),questions:N(ee(Et)),endpoints:N(qe(de)),brandText:N(R()),footerText:N(R())}),is=O({activeQuizId:N(Se(R())),results:N(te(R(),St)),voters:N(te(R(),ee(R())))}),rs=te(R(),R()),Pe=.8,qt=3;function Ct(s){const e=Object.entries(s);if(e.length===0)return[];const t=Math.max(...e.map(([,n])=>n));return e.map(([n,i])=>({word:n,count:i,fontSize:t>1?Pe+(i-1)/(t-1)*(qt-Pe):(Pe+qt)/2,isTop:i===t}))}function _t(s){return`quiz:${s}:results`}function Pt(s){return`quiz:${s}:sync`}const os={answer:"/.netlify/functions/quiz-answer",sync:"/.netlify/functions/quiz-sync"};function Tt(s){return G(es,s).success}function cs(s){return G(ts,s).success}class Te{constructor(e,t){this.activeQuizId=null,this.results={},this.online=0,this.submitted={},this.questions=[],this.listeners=[],this.quizGroupId=e.quizGroupId,this.sessionId=e.sessionId||this.getOrCreateSessionId(),this.endpoints={...os,...e.endpoints},this.cable=Zn(e.wsUrl,{protocol:"actioncable-v1-ext-json",protocolOptions:{historyTimestamp:Math.floor((Date.now()-t)/1e3)}}),this.syncChannel=this.cable.streamFrom(Pt(e.quizGroupId)),this.syncChannel.on("message",this.onSyncMessage.bind(this));const n=this.syncChannel.presence;if(typeof n.stateFromInfo=="function"){const i=n.stateFromInfo.bind(n);n.stateFromInfo=r=>{if(!(r!=null&&r.records)){if(r&&typeof r=="object"){const{type:o,...c}=r;return c}return{}}return i(r)}}this.syncChannel.on("presence",this.onPresence.bind(this)),this.syncChannel.presence.info().then(i=>{i&&(this.online=Object.keys(i).length,this.notifyStateChange())}).catch(()=>{})}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{const t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}}getState(){return{activeQuizId:this.activeQuizId,results:structuredClone(this.results),online:this.online,submitted:{...this.submitted},questions:structuredClone(this.questions)}}getQuizState(e){return this.results[e]||{votes:{},total:0}}hasVoted(e){return e in this.submitted}getVotedAnswer(e){return this.submitted[e]??null}disconnect(){this.cable.disconnect()}onSyncMessage(e){}async onPresence(){try{const e=await this.syncChannel.presence.info();e&&(this.online=Object.keys(e).length,this.notifyStateChange())}catch{}}getOrCreateSessionId(){const e=`quiz-session-${this.quizGroupId}`;let t=sessionStorage.getItem(e);return t||(t=crypto.randomUUID(),sessionStorage.setItem(e,t)),t}notifyStateChange(){const e=this.getState();for(const t of this.listeners)t(e)}parse(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return}return e}}class Rt extends Te{constructor(e){super(e,3e5),this.voters={},this.syncTimer=null,this.syncPending=!1,this.resultsChannel=this.cable.streamFrom(_t(e.quizGroupId)),this.resultsChannel.on("message",this.onResultsMessage.bind(this)),this.restoreState(),this.activeQuizId&&this.sendSync()}setQuestions(e){this.questions=e}setActiveQuiz(e){this.activeQuizId!==e&&(this.activeQuizId=e,this.saveState(),this.sendSync())}onSyncMessage(e){const t=this.parse(e);Tt(t)&&(t.sessionId,this.sessionId)}async onPresence(){try{const e=await this.syncChannel.presence.info();e&&(this.online=Object.keys(e).length,this.notifyStateChange(),this.activeQuizId&&this.sendSyncThrottled())}catch{}}getQuizType(e){var t;return((t=this.questions.find(n=>n.quizId===e))==null?void 0:t.type)??"choice"}normalizeAnswer(e,t){return this.getQuizType(e)==="text"?t.trim().toLowerCase():t}onResultsMessage(e){const t=this.parse(e);if(!cs(t)||t.sessionId===this.sessionId)return;const{quizId:n,sessionId:i}=t,r=this.normalizeAnswer(n,t.answer);this.voters[n]||(this.voters[n]=new Set),!this.voters[n].has(i)&&(this.voters[n].add(i),this.results[n]||(this.results[n]={votes:{},total:0}),this.results[n].votes[r]=(this.results[n].votes[r]||0)+1,this.results[n].total+=1,this.saveState(),this.notifyStateChange(),this.sendSyncThrottled())}sendSyncThrottled(){if(this.syncTimer){this.syncPending=!0;return}this.sendSync(),this.syncTimer=setTimeout(()=>{this.syncTimer=null,this.syncPending&&(this.syncPending=!1,this.sendSync())},200)}async sendSync(){try{await fetch(this.endpoints.sync,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({activeQuizId:this.activeQuizId,sessionId:this.sessionId,quizGroupId:this.quizGroupId,results:this.results,questions:this.questions})})}catch{}}saveState(){try{sessionStorage.setItem(`quiz-presenter-${this.quizGroupId}`,JSON.stringify({activeQuizId:this.activeQuizId,results:this.results,voters:Object.fromEntries(Object.entries(this.voters).map(([e,t])=>[e,[...t]]))}))}catch(e){console.warn("[QuizManager] saveState failed:",e)}}restoreState(){try{const e=sessionStorage.getItem(`quiz-presenter-${this.quizGroupId}`);if(!e)return;const t=G(is,JSON.parse(e));if(!t.success)return;const n=t.output;if(n.activeQuizId&&(this.activeQuizId=n.activeQuizId),n.results&&(this.results=n.results),n.voters)for(const[i,r]of Object.entries(n.voters))this.voters[i]=new Set(r)}catch{}}}class zt extends Te{constructor(e){super(e,6e4),this.incomingSyncTimer=null,this.incomingSyncData=null,this.syncChannel.presence.join(this.sessionId,{id:this.sessionId}),this.restoreSubmitted()}async submitAnswer(e,t){if(this.hasVoted(e))return!1;try{const n=await fetch(this.endpoints.answer,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({quizId:e,answer:t,sessionId:this.sessionId,quizGroupId:this.quizGroupId})});return n.ok&&(this.submitted[e]=t,this.saveSubmitted(),this.notifyStateChange()),n.ok}catch{return!1}}disconnect(){this.syncChannel.presence.leave(),this.cable.disconnect()}onSyncMessage(e){const t=this.parse(e);Tt(t)&&t.sessionId!==this.sessionId&&this.applySyncThrottled(t)}applySyncThrottled(e){if(this.incomingSyncTimer){this.incomingSyncData=e;return}this.applySync(e),this.incomingSyncData=null,this.incomingSyncTimer=setTimeout(()=>{this.incomingSyncTimer=null,this.incomingSyncData&&(this.applySync(this.incomingSyncData),this.incomingSyncData=null)},200)}applySync(e){this.activeQuizId=e.activeQuizId,this.results=e.results,e.questions&&(this.questions=e.questions);for(const t of Object.keys(this.submitted)){const n=e.results[t];n&&n.total===0&&this.clearVotedAnswer(t)}this.notifyStateChange()}saveSubmitted(){try{sessionStorage.setItem(`quiz-submitted-${this.quizGroupId}`,JSON.stringify(this.submitted))}catch{}}restoreSubmitted(){try{const e=sessionStorage.getItem(`quiz-submitted-${this.quizGroupId}`);if(!e)return;const t=G(rs,JSON.parse(e));if(!t.success)return;this.submitted=t.output}catch{}}clearVotedAnswer(e){delete this.submitted[e],this.saveSubmitted()}}const fe=new Map;function kt(s){return fe.has(s.quizGroupId)||fe.set(s.quizGroupId,new Rt(s)),fe.get(s.quizGroupId)}function At(s){fe.delete(s)}const ge=new Map;function us(s){return ge.has(s.quizGroupId)||ge.set(s.quizGroupId,new zt(s)),ge.get(s.quizGroupId)}function as(s){ge.delete(s)}function Re(s,e){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){s.textContent=String(e);return}const n=parseInt(s.textContent||"0",10);if(n===e)return;const i=300,r=performance.now(),o=n;function c(u){const a=u-r,l=Math.min(a/i,1),h=1-Math.pow(1-l,3),f=Math.round(o+(e-o)*h);s.textContent=String(f),l<1&&requestAnimationFrame(c)}requestAnimationFrame(c)}function ls(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var se={},ze,Mt;function hs(){return Mt||(Mt=1,ze=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ze}var ke={},J={},Bt;function X(){if(Bt)return J;Bt=1;let s;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return J.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},J.getSymbolTotalCodewords=function(n){return e[n]},J.getBCHDigit=function(t){let n=0;for(;t!==0;)n++,t>>>=1;return n},J.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');s=n},J.isKanjiModeEnabled=function(){return typeof s<"u"},J.toSJIS=function(n){return s(n)},J}var Ae={},Nt;function Me(){return Nt||(Nt=1,(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function e(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+t)}}s.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},s.from=function(n,i){if(s.isValid(n))return n;try{return e(n)}catch{return i}}})(Ae)),Ae}var Be,Lt;function ds(){if(Lt)return Be;Lt=1;function s(){this.buffer=[],this.length=0}return s.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},Be=s,Be}var Ne,Ot;function fs(){if(Ot)return Ne;Ot=1;function s(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return s.prototype.set=function(e,t,n,i){const r=e*this.size+t;this.data[r]=n,i&&(this.reservedBit[r]=!0)},s.prototype.get=function(e,t){return this.data[e*this.size+t]},s.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},s.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},Ne=s,Ne}var Le={},jt;function gs(){return jt||(jt=1,(function(s){const e=X().getSymbolSize;s.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,r=e(n),o=r===145?26:Math.ceil((r-13)/(2*i-2))*2,c=[r-7];for(let u=1;u<i-1;u++)c[u]=c[u-1]-o;return c.push(6),c.reverse()},s.getPositions=function(n){const i=[],r=s.getRowColCoords(n),o=r.length;for(let c=0;c<o;c++)for(let u=0;u<o;u++)c===0&&u===0||c===0&&u===o-1||c===o-1&&u===0||i.push([r[c],r[u]]);return i}})(Le)),Le}var Oe={},Ft;function ps(){if(Ft)return Oe;Ft=1;const s=X().getSymbolSize,e=7;return Oe.getPositions=function(n){const i=s(n);return[[0,0],[i-e,0],[0,i-e]]},Oe}var je={},Ut;function ms(){return Ut||(Ut=1,(function(s){s.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};s.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},s.from=function(i){return s.isValid(i)?parseInt(i,10):void 0},s.getPenaltyN1=function(i){const r=i.size;let o=0,c=0,u=0,a=null,l=null;for(let h=0;h<r;h++){c=u=0,a=l=null;for(let f=0;f<r;f++){let d=i.get(h,f);d===a?c++:(c>=5&&(o+=e.N1+(c-5)),a=d,c=1),d=i.get(f,h),d===l?u++:(u>=5&&(o+=e.N1+(u-5)),l=d,u=1)}c>=5&&(o+=e.N1+(c-5)),u>=5&&(o+=e.N1+(u-5))}return o},s.getPenaltyN2=function(i){const r=i.size;let o=0;for(let c=0;c<r-1;c++)for(let u=0;u<r-1;u++){const a=i.get(c,u)+i.get(c,u+1)+i.get(c+1,u)+i.get(c+1,u+1);(a===4||a===0)&&o++}return o*e.N2},s.getPenaltyN3=function(i){const r=i.size;let o=0,c=0,u=0;for(let a=0;a<r;a++){c=u=0;for(let l=0;l<r;l++)c=c<<1&2047|i.get(a,l),l>=10&&(c===1488||c===93)&&o++,u=u<<1&2047|i.get(l,a),l>=10&&(u===1488||u===93)&&o++}return o*e.N3},s.getPenaltyN4=function(i){let r=0;const o=i.data.length;for(let u=0;u<o;u++)r+=i.data[u];return Math.abs(Math.ceil(r*100/o/5)-10)*e.N4};function t(n,i,r){switch(n){case s.Patterns.PATTERN000:return(i+r)%2===0;case s.Patterns.PATTERN001:return i%2===0;case s.Patterns.PATTERN010:return r%3===0;case s.Patterns.PATTERN011:return(i+r)%3===0;case s.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(r/3))%2===0;case s.Patterns.PATTERN101:return i*r%2+i*r%3===0;case s.Patterns.PATTERN110:return(i*r%2+i*r%3)%2===0;case s.Patterns.PATTERN111:return(i*r%3+(i+r)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}s.applyMask=function(i,r){const o=r.size;for(let c=0;c<o;c++)for(let u=0;u<o;u++)r.isReserved(u,c)||r.xor(u,c,t(i,u,c))},s.getBestMask=function(i,r){const o=Object.keys(s.Patterns).length;let c=0,u=1/0;for(let a=0;a<o;a++){r(a),s.applyMask(a,i);const l=s.getPenaltyN1(i)+s.getPenaltyN2(i)+s.getPenaltyN3(i)+s.getPenaltyN4(i);s.applyMask(a,i),l<u&&(u=l,c=a)}return c}})(je)),je}var pe={},Dt;function Qt(){if(Dt)return pe;Dt=1;const s=Me(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],t=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return pe.getBlocksCount=function(i,r){switch(r){case s.L:return e[(i-1)*4+0];case s.M:return e[(i-1)*4+1];case s.Q:return e[(i-1)*4+2];case s.H:return e[(i-1)*4+3];default:return}},pe.getTotalCodewordsCount=function(i,r){switch(r){case s.L:return t[(i-1)*4+0];case s.M:return t[(i-1)*4+1];case s.Q:return t[(i-1)*4+2];case s.H:return t[(i-1)*4+3];default:return}},pe}var Fe={},ue={},xt;function bs(){if(xt)return ue;xt=1;const s=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)s[i]=n,e[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)s[i]=s[i-255]})(),ue.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},ue.exp=function(n){return s[n]},ue.mul=function(n,i){return n===0||i===0?0:s[e[n]+e[i]]},ue}var Vt;function ys(){return Vt||(Vt=1,(function(s){const e=bs();s.mul=function(n,i){const r=new Uint8Array(n.length+i.length-1);for(let o=0;o<n.length;o++)for(let c=0;c<i.length;c++)r[o+c]^=e.mul(n[o],i[c]);return r},s.mod=function(n,i){let r=new Uint8Array(n);for(;r.length-i.length>=0;){const o=r[0];for(let u=0;u<i.length;u++)r[u]^=e.mul(i[u],o);let c=0;for(;c<r.length&&r[c]===0;)c++;r=r.slice(c)}return r},s.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let r=0;r<n;r++)i=s.mul(i,new Uint8Array([1,e.exp(r)]));return i}})(Fe)),Fe}var Ue,Gt;function ws(){if(Gt)return Ue;Gt=1;const s=ys();function e(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=s.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const r=s.mod(i,this.genPoly),o=this.degree-r.length;if(o>0){const c=new Uint8Array(this.degree);return c.set(r,o),c}return r},Ue=e,Ue}var De={},Qe={},xe={},Jt;function Ht(){return Jt||(Jt=1,xe.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),xe}var D={},$t;function Kt(){if($t)return D;$t=1;const s="[0-9]+",e="[A-Z $%*+\\-./:]+";let t="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";t=t.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+t+`)(?:.|[\r
2
2
  ]))+`;D.KANJI=new RegExp(t,"g"),D.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),D.BYTE=new RegExp(n,"g"),D.NUMERIC=new RegExp(s,"g"),D.ALPHANUMERIC=new RegExp(e,"g");const i=new RegExp("^"+t+"$"),r=new RegExp("^"+s+"$"),o=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return D.testKanji=function(u){return i.test(u)},D.testNumeric=function(u){return r.test(u)},D.testAlphanumeric=function(u){return o.test(u)},D}var Wt;function Z(){return Wt||(Wt=1,(function(s){const e=Ht(),t=Kt();s.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},s.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},s.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},s.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},s.MIXED={bit:-1},s.getCharCountIndicator=function(r,o){if(!r.ccBits)throw new Error("Invalid mode: "+r);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?r.ccBits[0]:o<27?r.ccBits[1]:r.ccBits[2]},s.getBestModeForData=function(r){return t.testNumeric(r)?s.NUMERIC:t.testAlphanumeric(r)?s.ALPHANUMERIC:t.testKanji(r)?s.KANJI:s.BYTE},s.toString=function(r){if(r&&r.id)return r.id;throw new Error("Invalid mode")},s.isValid=function(r){return r&&r.bit&&r.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return s.NUMERIC;case"alphanumeric":return s.ALPHANUMERIC;case"kanji":return s.KANJI;case"byte":return s.BYTE;default:throw new Error("Unknown mode: "+i)}}s.from=function(r,o){if(s.isValid(r))return r;try{return n(r)}catch{return o}}})(Qe)),Qe}var Yt;function vs(){return Yt||(Yt=1,(function(s){const e=X(),t=Qt(),n=Me(),i=Z(),r=Ht(),o=7973,c=e.getBCHDigit(o);function u(f,d,p){for(let _=1;_<=40;_++)if(d<=s.getCapacity(_,p,f))return _}function a(f,d){return i.getCharCountIndicator(f,d)+4}function l(f,d){let p=0;return f.forEach(function(_){const A=a(_.mode,d);p+=A+_.getBitsLength()}),p}function h(f,d){for(let p=1;p<=40;p++)if(l(f,p)<=s.getCapacity(p,d,i.MIXED))return p}s.from=function(d,p){return r.isValid(d)?parseInt(d,10):p},s.getCapacity=function(d,p,_){if(!r.isValid(d))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=i.BYTE);const A=e.getSymbolTotalCodewords(d),q=t.getTotalCodewordsCount(d,p),P=(A-q)*8;if(_===i.MIXED)return P;const v=P-a(_,d);switch(_){case i.NUMERIC:return Math.floor(v/10*3);case i.ALPHANUMERIC:return Math.floor(v/11*2);case i.KANJI:return Math.floor(v/13);case i.BYTE:default:return Math.floor(v/8)}},s.getBestVersionForData=function(d,p){let _;const A=n.from(p,n.M);if(Array.isArray(d)){if(d.length>1)return h(d,A);if(d.length===0)return 1;_=d[0]}else _=d;return u(_.mode,_.getLength(),A)},s.getEncodedBits=function(d){if(!r.isValid(d)||d<7)throw new Error("Invalid QR Code version");let p=d<<12;for(;e.getBCHDigit(p)-c>=0;)p^=o<<e.getBCHDigit(p)-c;return d<<12|p}})(De)),De}var Ve={},Xt;function Ss(){if(Xt)return Ve;Xt=1;const s=X(),e=1335,t=21522,n=s.getBCHDigit(e);return Ve.getEncodedBits=function(r,o){const c=r.bit<<3|o;let u=c<<10;for(;s.getBCHDigit(u)-n>=0;)u^=e<<s.getBCHDigit(u)-n;return(c<<10|u)^t},Ve}var Ge={},Je,Zt;function Es(){if(Zt)return Je;Zt=1;const s=Z();function e(t){this.mode=s.NUMERIC,this.data=t.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let i,r,o;for(i=0;i+3<=this.data.length;i+=3)r=this.data.substr(i,3),o=parseInt(r,10),n.put(o,10);const c=this.data.length-i;c>0&&(r=this.data.substr(i),o=parseInt(r,10),n.put(o,c*3+1))},Je=e,Je}var He,en;function Is(){if(en)return He;en=1;const s=Z(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function t(n){this.mode=s.ALPHANUMERIC,this.data=n}return t.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(i){let r;for(r=0;r+2<=this.data.length;r+=2){let o=e.indexOf(this.data[r])*45;o+=e.indexOf(this.data[r+1]),i.put(o,11)}this.data.length%2&&i.put(e.indexOf(this.data[r]),6)},He=t,He}var $e,tn;function qs(){if(tn)return $e;tn=1;const s=Z();function e(t){this.mode=s.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(t){for(let n=0,i=this.data.length;n<i;n++)t.put(this.data[n],8)},$e=e,$e}var Ke,nn;function Cs(){if(nn)return Ke;nn=1;const s=Z(),e=X();function t(n){this.mode=s.KANJI,this.data=n}return t.getBitsLength=function(i){return i*13},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let r=e.toSJIS(this.data[i]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
3
3
  Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),n.put(r,13)}},Ke=t,Ke}var We={exports:{}},sn;function _s(){return sn||(sn=1,(function(s){var e={single_source_shortest_paths:function(t,n,i){var r={},o={};o[n]=0;var c=e.PriorityQueue.make();c.push(n,0);for(var u,a,l,h,f,d,p,_,A;!c.empty();){u=c.pop(),a=u.value,h=u.cost,f=t[a]||{};for(l in f)f.hasOwnProperty(l)&&(d=f[l],p=h+d,_=o[l],A=typeof o[l]>"u",(A||_>p)&&(o[l]=p,c.push(l,p),r[l]=a))}if(typeof i<"u"&&typeof o[i]>"u"){var q=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(q)}return r},extract_shortest_path_from_predecessor_list:function(t,n){for(var i=[],r=n;r;)i.push(r),t[r],r=t[r];return i.reverse(),i},find_path:function(t,n,i){var r=e.single_source_shortest_paths(t,n,i);return e.extract_shortest_path_from_predecessor_list(r,i)},PriorityQueue:{make:function(t){var n=e.PriorityQueue,i={},r;t=t||{};for(r in n)n.hasOwnProperty(r)&&(i[r]=n[r]);return i.queue=[],i.sorter=t.sorter||n.default_sorter,i},default_sorter:function(t,n){return t.cost-n.cost},push:function(t,n){var i={value:t,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=e})(We)),We.exports}var rn;function Ps(){return rn||(rn=1,(function(s){const e=Z(),t=Es(),n=Is(),i=qs(),r=Cs(),o=Kt(),c=X(),u=_s();function a(q){return unescape(encodeURIComponent(q)).length}function l(q,P,v){const E=[];let M;for(;(M=q.exec(v))!==null;)E.push({data:M[0],index:M.index,mode:P,length:M[0].length});return E}function h(q){const P=l(o.NUMERIC,e.NUMERIC,q),v=l(o.ALPHANUMERIC,e.ALPHANUMERIC,q);let E,M;return c.isKanjiModeEnabled()?(E=l(o.BYTE,e.BYTE,q),M=l(o.KANJI,e.KANJI,q)):(E=l(o.BYTE_KANJI,e.BYTE,q),M=[]),P.concat(v,E,M).sort(function(I,S){return I.index-S.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function f(q,P){switch(P){case e.NUMERIC:return t.getBitsLength(q);case e.ALPHANUMERIC:return n.getBitsLength(q);case e.KANJI:return r.getBitsLength(q);case e.BYTE:return i.getBitsLength(q)}}function d(q){return q.reduce(function(P,v){const E=P.length-1>=0?P[P.length-1]:null;return E&&E.mode===v.mode?(P[P.length-1].data+=v.data,P):(P.push(v),P)},[])}function p(q){const P=[];for(let v=0;v<q.length;v++){const E=q[v];switch(E.mode){case e.NUMERIC:P.push([E,{data:E.data,mode:e.ALPHANUMERIC,length:E.length},{data:E.data,mode:e.BYTE,length:E.length}]);break;case e.ALPHANUMERIC:P.push([E,{data:E.data,mode:e.BYTE,length:E.length}]);break;case e.KANJI:P.push([E,{data:E.data,mode:e.BYTE,length:a(E.data)}]);break;case e.BYTE:P.push([{data:E.data,mode:e.BYTE,length:a(E.data)}])}}return P}function _(q,P){const v={},E={start:{}};let M=["start"];for(let m=0;m<q.length;m++){const I=q[m],S=[];for(let g=0;g<I.length;g++){const C=I[g],b=""+m+g;S.push(b),v[b]={node:C,lastCount:0},E[b]={};for(let w=0;w<M.length;w++){const y=M[w];v[y]&&v[y].node.mode===C.mode?(E[y][b]=f(v[y].lastCount+C.length,C.mode)-f(v[y].lastCount,C.mode),v[y].lastCount+=C.length):(v[y]&&(v[y].lastCount=C.length),E[y][b]=f(C.length,C.mode)+4+e.getCharCountIndicator(C.mode,P))}}M=S}for(let m=0;m<M.length;m++)E[M[m]].end=0;return{map:E,table:v}}function A(q,P){let v;const E=e.getBestModeForData(q);if(v=e.from(P,E),v!==e.BYTE&&v.bit<E.bit)throw new Error('"'+q+'" cannot be encoded with mode '+e.toString(v)+`.
4
4
  Suggested mode is: `+e.toString(E));switch(v===e.KANJI&&!c.isKanjiModeEnabled()&&(v=e.BYTE),v){case e.NUMERIC:return new t(q);case e.ALPHANUMERIC:return new n(q);case e.KANJI:return new r(q);case e.BYTE:return new i(q)}}s.fromArray=function(P){return P.reduce(function(v,E){return typeof E=="string"?v.push(A(E,null)):E.data&&v.push(A(E.data,E.mode)),v},[])},s.fromString=function(P,v){const E=h(P,c.isKanjiModeEnabled()),M=p(E),m=_(M,v),I=u.find_path(m.map,"start","end"),S=[];for(let g=1;g<I.length-1;g++)S.push(m.table[I[g]].node);return s.fromArray(d(S))},s.rawSplit=function(P){return s.fromArray(h(P,c.isKanjiModeEnabled()))}})(Ge)),Ge}var on;function Ts(){if(on)return ke;on=1;const s=X(),e=Me(),t=ds(),n=fs(),i=gs(),r=ps(),o=ms(),c=Qt(),u=ws(),a=vs(),l=Ss(),h=Z(),f=Ps();function d(m,I){const S=m.size,g=r.getPositions(I);for(let C=0;C<g.length;C++){const b=g[C][0],w=g[C][1];for(let y=-1;y<=7;y++)if(!(b+y<=-1||S<=b+y))for(let T=-1;T<=7;T++)w+T<=-1||S<=w+T||(y>=0&&y<=6&&(T===0||T===6)||T>=0&&T<=6&&(y===0||y===6)||y>=2&&y<=4&&T>=2&&T<=4?m.set(b+y,w+T,!0,!0):m.set(b+y,w+T,!1,!0))}}function p(m){const I=m.size;for(let S=8;S<I-8;S++){const g=S%2===0;m.set(S,6,g,!0),m.set(6,S,g,!0)}}function _(m,I){const S=i.getPositions(I);for(let g=0;g<S.length;g++){const C=S[g][0],b=S[g][1];for(let w=-2;w<=2;w++)for(let y=-2;y<=2;y++)w===-2||w===2||y===-2||y===2||w===0&&y===0?m.set(C+w,b+y,!0,!0):m.set(C+w,b+y,!1,!0)}}function A(m,I){const S=m.size,g=a.getEncodedBits(I);let C,b,w;for(let y=0;y<18;y++)C=Math.floor(y/3),b=y%3+S-8-3,w=(g>>y&1)===1,m.set(C,b,w,!0),m.set(b,C,w,!0)}function q(m,I,S){const g=m.size,C=l.getEncodedBits(I,S);let b,w;for(b=0;b<15;b++)w=(C>>b&1)===1,b<6?m.set(b,8,w,!0):b<8?m.set(b+1,8,w,!0):m.set(g-15+b,8,w,!0),b<8?m.set(8,g-b-1,w,!0):b<9?m.set(8,15-b-1+1,w,!0):m.set(8,15-b-1,w,!0);m.set(g-8,8,1,!0)}function P(m,I){const S=m.size;let g=-1,C=S-1,b=7,w=0;for(let y=S-1;y>0;y-=2)for(y===6&&y--;;){for(let T=0;T<2;T++)if(!m.isReserved(C,y-T)){let H=!1;w<I.length&&(H=(I[w]>>>b&1)===1),m.set(C,y-T,H),b--,b===-1&&(w++,b=7)}if(C+=g,C<0||S<=C){C-=g,g=-g;break}}}function v(m,I,S){const g=new t;S.forEach(function(T){g.put(T.mode.bit,4),g.put(T.getLength(),h.getCharCountIndicator(T.mode,m)),T.write(g)});const C=s.getSymbolTotalCodewords(m),b=c.getTotalCodewordsCount(m,I),w=(C-b)*8;for(g.getLengthInBits()+4<=w&&g.put(0,4);g.getLengthInBits()%8!==0;)g.putBit(0);const y=(w-g.getLengthInBits())/8;for(let T=0;T<y;T++)g.put(T%2?17:236,8);return E(g,m,I)}function E(m,I,S){const g=s.getSymbolTotalCodewords(I),C=c.getTotalCodewordsCount(I,S),b=g-C,w=c.getBlocksCount(I,S),y=g%w,T=w-y,H=Math.floor(g/w),ae=Math.floor(b/w),si=ae+1,bn=H-ae,ii=new u(bn);let et=0;const me=new Array(w),yn=new Array(w);let tt=0;const ri=new Uint8Array(m.buffer);for(let ie=0;ie<w;ie++){const st=ie<T?ae:si;me[ie]=ri.slice(et,et+st),yn[ie]=ii.encode(me[ie]),et+=st,tt=Math.max(tt,st)}const nt=new Uint8Array(g);let wn=0,Q,x;for(Q=0;Q<tt;Q++)for(x=0;x<w;x++)Q<me[x].length&&(nt[wn++]=me[x][Q]);for(Q=0;Q<bn;Q++)for(x=0;x<w;x++)nt[wn++]=yn[x][Q];return nt}function M(m,I,S,g){let C;if(Array.isArray(m))C=f.fromArray(m);else if(typeof m=="string"){let H=I;if(!H){const ae=f.rawSplit(m);H=a.getBestVersionForData(ae,S)}C=f.fromString(m,H||40)}else throw new Error("Invalid data");const b=a.getBestVersionForData(C,S);if(!b)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=b;else if(I<b)throw new Error(`
5
5
  The chosen QR Code version cannot contain this amount of data.
6
6
  Minimum version required to store current data is: `+b+`.
7
7
  `);const w=v(I,S,C),y=s.getSymbolSize(I),T=new n(y);return d(T,I),p(T),_(T,I),q(T,S,0),I>=7&&A(T,I),P(T,w),isNaN(g)&&(g=o.getBestMask(T,q.bind(null,T,S))),o.applyMask(g,T),q(T,S,g),{modules:T,version:I,errorCorrectionLevel:S,maskPattern:g,segments:C}}return ke.create=function(I,S){if(typeof I>"u"||I==="")throw new Error("No input text");let g=e.M,C,b;return typeof S<"u"&&(g=e.from(S.errorCorrectionLevel,e.M),C=a.from(S.version),b=o.from(S.maskPattern),S.toSJISFunc&&s.setToSJISFunction(S.toSJISFunc)),M(I,C,g,b)},ke}var Ye={},Xe={},cn;function un(){return cn||(cn=1,(function(s){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let n=t.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+t);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(r){return[r,r]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}s.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,r=n.width&&n.width>=21?n.width:void 0,o=n.scale||4;return{width:r,scale:r?4:o,margin:i,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},s.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},s.getImageWidth=function(n,i){const r=s.getScale(n,i);return Math.floor((n+i.margin*2)*r)},s.qrToImageData=function(n,i,r){const o=i.modules.size,c=i.modules.data,u=s.getScale(o,r),a=Math.floor((o+r.margin*2)*u),l=r.margin*u,h=[r.color.light,r.color.dark];for(let f=0;f<a;f++)for(let d=0;d<a;d++){let p=(f*a+d)*4,_=r.color.light;if(f>=l&&d>=l&&f<a-l&&d<a-l){const A=Math.floor((f-l)/u),q=Math.floor((d-l)/u);_=h[c[A*o+q]?1:0]}n[p++]=_.r,n[p++]=_.g,n[p++]=_.b,n[p]=_.a}}})(Xe)),Xe}var an;function Rs(){return an||(an=1,(function(s){const e=un();function t(i,r,o){i.clearRect(0,0,r.width,r.height),r.style||(r.style={}),r.height=o,r.width=o,r.style.height=o+"px",r.style.width=o+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}s.render=function(r,o,c){let u=c,a=o;typeof u>"u"&&(!o||!o.getContext)&&(u=o,o=void 0),o||(a=n()),u=e.getOptions(u);const l=e.getImageWidth(r.modules.size,u),h=a.getContext("2d"),f=h.createImageData(l,l);return e.qrToImageData(f.data,r,u),t(h,a,l),h.putImageData(f,0,0),a},s.renderToDataURL=function(r,o,c){let u=c;typeof u>"u"&&(!o||!o.getContext)&&(u=o,o=void 0),u||(u={});const a=s.render(r,o,u),l=u.type||"image/png",h=u.rendererOpts||{};return a.toDataURL(l,h.quality)}})(Ye)),Ye}var Ze={},ln;function zs(){if(ln)return Ze;ln=1;const s=un();function e(i,r){const o=i.a/255,c=r+'="'+i.hex+'"';return o<1?c+" "+r+'-opacity="'+o.toFixed(2).slice(1)+'"':c}function t(i,r,o){let c=i+r;return typeof o<"u"&&(c+=" "+o),c}function n(i,r,o){let c="",u=0,a=!1,l=0;for(let h=0;h<i.length;h++){const f=Math.floor(h%r),d=Math.floor(h/r);!f&&!a&&(a=!0),i[h]?(l++,h>0&&f>0&&i[h-1]||(c+=a?t("M",f+o,.5+d+o):t("m",u,0),u=0,a=!1),f+1<r&&i[h+1]||(c+=t("h",l),l=0)):u++}return c}return Ze.render=function(r,o,c){const u=s.getOptions(o),a=r.modules.size,l=r.modules.data,h=a+u.margin*2,f=u.color.light.a?"<path "+e(u.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",d="<path "+e(u.color.dark,"stroke")+' d="'+n(l,a,u.margin)+'"/>',p='viewBox="0 0 '+h+" "+h+'"',A='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+p+' shape-rendering="crispEdges">'+f+d+`</svg>
8
- `;return typeof c=="function"&&c(null,A),A},Ze}var hn;function ks(){if(hn)return se;hn=1;const s=hs(),e=Ts(),t=Rs(),n=zs();function i(r,o,c,u,a){const l=[].slice.call(arguments,1),h=l.length,f=typeof l[h-1]=="function";if(!f&&!s())throw new Error("Callback required as last argument");if(f){if(h<2)throw new Error("Too few arguments provided");h===2?(a=c,c=o,o=u=void 0):h===3&&(o.getContext&&typeof a>"u"?(a=u,u=void 0):(a=u,u=c,c=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(c=o,o=u=void 0):h===2&&!o.getContext&&(u=c,c=o,o=void 0),new Promise(function(d,p){try{const _=e.create(c,u);d(r(_,o,u))}catch(_){p(_)}})}try{const d=e.create(c,u);a(null,r(d,o,u))}catch(d){a(d)}}return se.create=e.create,se.toCanvas=i.bind(null,t.render),se.toDataURL=i.bind(null,t.renderToDataURL),se.toString=i.bind(null,function(r,o,c){return n.render(r,c)}),se}var As=ks();const Ms=ls(As);function Bs(s){if(s){const t=getComputedStyle(s).backgroundColor,n=dn(t);if(n)return fn(n)>128}const e=getComputedStyle(document.documentElement).getPropertyValue("--r-background-color").trim();if(e){const t=dn(e)??Ns(e);if(t)return fn(t)>128}return!1}function dn(s){const e=s.match(/rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?/);return!e||e[4]!==void 0&&parseFloat(e[4])===0?null:[Number(e[1]),Number(e[2]),Number(e[3])]}function Ns(s){const e=s.replace("#","");if(!/^[0-9a-fA-F]{3,8}$/.test(e))return null;const t=e.length<=4?e.split("").map(n=>n+n).join(""):e;return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function fn([s,e,t]){return(s*299+e*587+t*114)/1e3}async function Ls(s,e=240,t){const n=Bs(t),i=await Ms.toDataURL(s,{width:e,margin:1,color:{dark:n?"#000000":"#ffffff",light:"#00000000"}}),r=document.createElement("img");return r.src=i,r.alt=`Scan to join: ${s}`,r.className="lq-qr",r.width=e,r.height=e,r}function Os(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function gn(s){if(s==null||s===!1)return"";if(Array.isArray(s))return s.map(gn).join("");if(s instanceof Node){const e=document.createElement("div");return e.appendChild(s),e.innerHTML}return Os(String(s))}function O(s,...e){const t=document.createElement("template");let n="";return s.forEach((i,r)=>{n+=i,r<e.length&&(n+=gn(e[r]))}),t.innerHTML=n,t.content}const z={question:"lq-question",results:"lq-results",wordcloud:"lq-wordcloud",online:"lq-online",answered:"lq-answered",resultBar:"lq-result-bar",resultBarCorrect:"lq-result-bar--correct",resultBarFill:"lq-result-bar__fill",resultBarPct:"lq-result-bar__pct",resultBarCount:"lq-result-bar__count",wordcloudCloud:"lq-wordcloud__cloud",wordcloudWord:"lq-wordcloud__word",wordcloudWordTop:"lq-wordcloud__word--top"};function js(s,e){return s.querySelector(`.${z.wordcloud}[data-lq-quiz="${e}"]`)}function Fs(s,e){return s.querySelector(`.${z.results}[data-lq-quiz="${e}"]`)}function Us(s){return s.querySelectorAll(`.${z.online}`)}function Ds(s,e){return s.querySelectorAll(`.${z.answered}[data-lq-quiz="${e}"]`)}function Qs(s,e){return s.querySelectorAll(`.${z.wordcloud}[data-lq-quiz="${e}"]`)}function xs(s,e){return s.querySelectorAll(`.${z.results}[data-lq-quiz="${e}"]`)}function Vs(s){return s.querySelectorAll(`.${z.question}, .${z.results}, .${z.wordcloud}`)}async function Gs(s,e){if(!s)return null;const t=await Ls(s,240,e);return O`
8
+ `;return typeof c=="function"&&c(null,A),A},Ze}var hn;function ks(){if(hn)return se;hn=1;const s=hs(),e=Ts(),t=Rs(),n=zs();function i(r,o,c,u,a){const l=[].slice.call(arguments,1),h=l.length,f=typeof l[h-1]=="function";if(!f&&!s())throw new Error("Callback required as last argument");if(f){if(h<2)throw new Error("Too few arguments provided");h===2?(a=c,c=o,o=u=void 0):h===3&&(o.getContext&&typeof a>"u"?(a=u,u=void 0):(a=u,u=c,c=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(c=o,o=u=void 0):h===2&&!o.getContext&&(u=c,c=o,o=void 0),new Promise(function(d,p){try{const _=e.create(c,u);d(r(_,o,u))}catch(_){p(_)}})}try{const d=e.create(c,u);a(null,r(d,o,u))}catch(d){a(d)}}return se.create=e.create,se.toCanvas=i.bind(null,t.render),se.toDataURL=i.bind(null,t.renderToDataURL),se.toString=i.bind(null,function(r,o,c){return n.render(r,c)}),se}var As=ks();const Ms=ls(As);function Bs(s){if(s){const t=getComputedStyle(s).backgroundColor,n=dn(t);if(n)return fn(n)>128}const e=getComputedStyle(document.documentElement).getPropertyValue("--r-background-color").trim();if(e){const t=dn(e)??Ns(e);if(t)return fn(t)>128}return!1}function dn(s){const e=s.match(/rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?/);return!e||e[4]!==void 0&&parseFloat(e[4])===0?null:[Number(e[1]),Number(e[2]),Number(e[3])]}function Ns(s){const e=s.replace("#","");if(!/^[0-9a-fA-F]{3,8}$/.test(e))return null;const t=e.length<=4?e.split("").map(n=>n+n).join(""):e;return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function fn([s,e,t]){return(s*299+e*587+t*114)/1e3}async function Ls(s,e=240,t){const n=Bs(t),i=await Ms.toDataURL(s,{width:e,margin:1,color:{dark:n?"#000000":"#ffffff",light:"#00000000"}}),r=document.createElement("img");return r.src=i,r.alt=`Scan to join: ${s}`,r.className="lq-qr",r.width=e,r.height=e,r}function Os(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function gn(s){if(s==null||s===!1)return"";if(Array.isArray(s))return s.map(gn).join("");if(s instanceof Node){const e=document.createElement("div");return e.appendChild(s),e.innerHTML}return Os(String(s))}function L(s,...e){const t=document.createElement("template");let n="";return s.forEach((i,r)=>{n+=i,r<e.length&&(n+=gn(e[r]))}),t.innerHTML=n,t.content}const z={question:"lq-question",results:"lq-results",wordcloud:"lq-wordcloud",online:"lq-online",answered:"lq-answered",resultBar:"lq-result-bar",resultBarCorrect:"lq-result-bar--correct",resultBarFill:"lq-result-bar__fill",resultBarPct:"lq-result-bar__pct",resultBarCount:"lq-result-bar__count",wordcloudCloud:"lq-wordcloud__cloud",wordcloudWord:"lq-wordcloud__word",wordcloudWordTop:"lq-wordcloud__word--top"};function js(s,e){return s.querySelector(`.${z.wordcloud}[data-lq-quiz="${e}"]`)}function Fs(s,e){return s.querySelector(`.${z.results}[data-lq-quiz="${e}"]`)}function Us(s){return s.querySelectorAll(`.${z.online}`)}function Ds(s,e){return s.querySelectorAll(`.${z.answered}[data-lq-quiz="${e}"]`)}function Qs(s,e){return s.querySelectorAll(`.${z.wordcloud}[data-lq-quiz="${e}"]`)}function xs(s,e){return s.querySelectorAll(`.${z.results}[data-lq-quiz="${e}"]`)}function Vs(s){return s.querySelectorAll(`.${z.question}, .${z.results}, .${z.wordcloud}`)}async function Gs(s,e){if(!s)return null;const t=await Ls(s,240,e);return L`
9
9
  <div class="lq-question__qr-side">
10
10
  ${t}
11
11
  <p class="lq-question__url">
12
12
  ${s.replace(/^https?:\/\//,"")}
13
13
  </p>
14
14
  </div>
15
- `}function Js(s,e){const t=G(_e,e);return t.success?O`
15
+ `}function Js(s,e){const t=G(_e,e);return t.success?L`
16
16
  <div class="lq-question__options">
17
- ${t.output.map(n=>O`
17
+ ${t.output.map(n=>L`
18
18
  <div class="lq-question__option">
19
19
  <span class="lq-question__option-label">${n.label}</span>
20
20
  <span class="lq-question__option-text">${n.text}</span>
21
21
  </div>
22
22
  `)}
23
23
  </div>
24
- `:(console.warn(`[live-quiz] Invalid data-quiz-options on quiz "${s}"`),null)}function Hs(s){return O`
24
+ `:(console.warn(`[live-quiz] Invalid data-quiz-options on quiz "${s}"`),null)}function Hs(s){return L`
25
25
  <div class="lq-question__counter">
26
26
  <span class="${z.online}" data-lq-quiz="${s}">0</span>
27
27
  online ·
28
28
  <span class="${z.answered}" data-lq-quiz="${s}">0</span>
29
29
  answered
30
30
  </div>
31
- `}function $s(s,e,t,n){const i=e==="text"?O`
32
- <p class="lq-question__hint">
33
- Open your phone and type your answer!
34
- </p>
35
- `:Js(s,n);return O`
31
+ `}function $s(s,e,t,n,i){const r=e==="text"&&i?L`
32
+ <p class="lq-question__hint">${i}</p>
33
+ `:e==="text"?null:Js(s,n);return L`
36
34
  <div class="lq-question__content">
37
35
  <p class="lq-question__text">${t}</p>
38
- ${i}
36
+ ${r}
39
37
  ${Hs(s)}
40
38
  </div>
41
- `}async function Ks(s,e,t="Pop quiz!"){const n=s.dataset.quizId,i=s.dataset.quizQuestion||"",r=Ie(ce,s.dataset.quizType),o=await Gs(e,s),c=O`
39
+ `}async function Ks(s,e,t,n){const i=s.dataset.quizId,r=s.dataset.quizQuestion||"",o=Ie(ce,s.dataset.quizType),c=await Gs(e,s),u=L`
42
40
  <div class="${z.question}">
43
- <h2 class="lq-question__title">${t}</h2>
41
+ ${t?L`<h2 class="lq-question__title">${t}</h2>`:null}
44
42
  <div class="lq-question__body">
45
- ${o}
46
- ${$s(n,r,i,s.dataset.quizOptions)}
43
+ ${c}
44
+ ${$s(i,o,r,s.dataset.quizOptions,n)}
47
45
  </div>
48
46
  </div>
49
- `;s.appendChild(c)}function Ws(s){const e=s.dataset.quizResults,t=s.dataset.quizQuestion||"",n=G(_e,s.dataset.quizOptions);if(!n.success){console.warn(`[live-quiz] Invalid data-quiz-options on results "${e}"`);return}const i=O`
47
+ `;s.appendChild(u)}function Ws(s){const e=s.dataset.quizResults,t=s.dataset.quizQuestion||"",n=G(_e,s.dataset.quizOptions);if(!n.success){console.warn(`[live-quiz] Invalid data-quiz-options on results "${e}"`);return}const i=L`
50
48
  <div class="${z.results}" data-lq-quiz="${e}">
51
- ${t?O`<h2 class="lq-results__title">${t}</h2>`:null}
49
+ ${t?L`<h2 class="lq-results__title">${t}</h2>`:null}
52
50
  <div class="lq-results__bars">
53
- ${n.output.map(r=>O`
51
+ ${n.output.map(r=>L`
54
52
  <div class="${z.resultBar}${r.correct?` ${z.resultBarCorrect}`:""}" data-option="${r.label}">
55
53
  <div class="lq-result-bar__label">
56
54
  <span class="lq-result-bar__letter">${r.label}</span>
@@ -67,9 +65,9 @@ Minimum version required to store current data is: `+b+`.
67
65
  `)}
68
66
  </div>
69
67
  </div>
70
- `;s.appendChild(i)}function Ys(s,e){const t=s.querySelectorAll(`.${z.resultBar}`),n=e.total||1;for(const i of t){const r=i.dataset.option||"",o=e.votes[r]||0,c=Math.round(o/n*100),u=i.querySelector(`.${z.resultBarFill}`),a=i.querySelector(`.${z.resultBarPct}`),l=i.querySelector(`.${z.resultBarCount}`);u&&(u.style.width=`${c}%`),a&&(a.textContent=`${c}%`),l&&(l.textContent=String(o))}}function Xs(s,e){const t=window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=s.querySelectorAll(`.${z.resultBar}`),i=e.total||1;let r=0;for(const o of n){const c=o.dataset.option||"",u=e.votes[c]||0,a=Math.round(u/i*100),l=o.querySelector(`.${z.resultBarFill}`),h=o.querySelector(`.${z.resultBarPct}`),f=o.querySelector(`.${z.resultBarCount}`);l&&(t?l.style.width=`${a}%`:(l.style.transitionDelay=`${r*.15}s`,requestAnimationFrame(()=>{l.style.width=`${a}%`}))),h&&(h.textContent=`${a}%`),f&&(f.textContent=String(u)),r++}}function Zs(s){const e=s.dataset.quizResults,t=s.dataset.quizQuestion||"",n=O`
68
+ `;s.appendChild(i)}function Ys(s,e){const t=s.querySelectorAll(`.${z.resultBar}`),n=e.total||1;for(const i of t){const r=i.dataset.option||"",o=e.votes[r]||0,c=Math.round(o/n*100),u=i.querySelector(`.${z.resultBarFill}`),a=i.querySelector(`.${z.resultBarPct}`),l=i.querySelector(`.${z.resultBarCount}`);u&&(u.style.width=`${c}%`),a&&(a.textContent=`${c}%`),l&&(l.textContent=String(o))}}function Xs(s,e){const t=window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=s.querySelectorAll(`.${z.resultBar}`),i=e.total||1;let r=0;for(const o of n){const c=o.dataset.option||"",u=e.votes[c]||0,a=Math.round(u/i*100),l=o.querySelector(`.${z.resultBarFill}`),h=o.querySelector(`.${z.resultBarPct}`),f=o.querySelector(`.${z.resultBarCount}`);l&&(t?l.style.width=`${a}%`:(l.style.transitionDelay=`${r*.15}s`,requestAnimationFrame(()=>{l.style.width=`${a}%`}))),h&&(h.textContent=`${a}%`),f&&(f.textContent=String(u)),r++}}function Zs(s){const e=s.dataset.quizResults,t=s.dataset.quizQuestion||"",n=L`
71
69
  <div class="${z.wordcloud}" data-lq-quiz="${e}">
72
- ${t?O`<h2 class="lq-wordcloud__title">${t}</h2>`:null}
70
+ ${t?L`<h2 class="lq-wordcloud__title">${t}</h2>`:null}
73
71
  <div class="${z.wordcloudCloud}"></div>
74
72
  </div>
75
- `;s.appendChild(n)}function ei(s,e){pn(s,e,!1)}function ti(s,e){pn(s,e,!0)}function pn(s,e,t){const n=s.querySelector(`.${z.wordcloudCloud}`);if(!n)return;const i=Ct(e.votes);if(i.length===0)return;const r=window.matchMedia("(prefers-reduced-motion: reduce)").matches;let o=0;for(const{word:c,count:u,fontSize:a,isTop:l}of i){const h=`[data-word="${CSS.escape(c)}"]`;let f=n.querySelector(h);if(!f){if(f=document.createElement("span"),f.className=z.wordcloudWord,f.dataset.word=c,f.textContent=c,t&&!r){f.style.opacity="0";const d=o*.08;f.style.transitionDelay=`${d}s`;const p=f;requestAnimationFrame(()=>{p.style.opacity="1"})}n.appendChild(f)}f.style.fontSize=`${a}rem`,f.classList.toggle(z.wordcloudWordTop,l),f.title=`${c}: ${u}`,o++}}const mn=L({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),quizUrl:N(R()),endpoints:N(qe(de)),titleText:N(R())});function ni(){let s=null,e,t=null,n=null;const i=new Set;function r(c){if(!t)return;const a=c.currentSlide;if(!(a instanceof HTMLElement))return;const l=a.dataset.quizId;l&&t.setActiveQuiz(l);const h=a.dataset.quizResults;if(h&&!i.has(h)){i.add(h);const f=t.getQuizState(h),d=js(a,h);if(d)ti(d,f);else{const p=Fs(a,h);p&&Xs(p,f)}}}function o(){if(!t||!s)return;const c=t.getState(),u=s.getRevealElement();for(const a of Us(u))Re(a,c.online);for(const[a,l]of Object.entries(c.results)){for(const h of Ds(u,a))Re(h,l.total);if(i.has(a)){for(const h of Qs(u,a))ei(h,l);for(const h of xs(u,a))Ys(h,l)}}}return{id:"live-quiz",init:async c=>{s=c;const u=s.getConfig().liveQuiz??{},a=G(mn,u);if(!a.success){console.warn("[live-quiz] Missing required config: wsUrl and quizGroupId. Pass them in Reveal.initialize({ liveQuiz: { wsUrl, quizGroupId } }).");return}e=a.output,t=kt({wsUrl:e.wsUrl,quizGroupId:e.quizGroupId,endpoints:e.endpoints});const l=s.getRevealElement(),h=l.querySelectorAll("section[data-quiz-id]"),f=[],d=[];for(const p of h){const _=Ks(p,e.quizUrl,e.titleText).catch(v=>console.warn("[live-quiz] Failed to render question slide:",v));f.push(_);const A=p.dataset.quizId,q=p.dataset.quizQuestion||"",P=Ie(ce,p.dataset.quizType);if(P==="text")d.push({quizId:A,question:q,type:P,options:[]});else{const v=G(_e,p.dataset.quizOptions);v.success&&d.push({quizId:A,question:q,type:P,options:v.output.map(E=>({label:E.label,text:E.text}))})}}t.setQuestions(d);for(const p of l.querySelectorAll("section[data-quiz-results]"))Ie(ce,p.dataset.quizType)==="text"?Zs(p):Ws(p);await Promise.all(f),n=t.subscribe(o),s.on("slidechanged",r)},destroy:()=>{if(!s)return;s.off("slidechanged",r),n&&(n(),n=null),t&&(At(e.quizGroupId),t.disconnect(),t=null);const c=s.getRevealElement();for(const u of Vs(c))u.remove();i.clear(),s=null}}}k.LiveQuizConfigSchema=mn,k.ParticipantConfigSchema=ss,k.ParticipantQuizManager=zt,k.PresenterQuizManager=Rt,k.QuizEndpointsSchema=de,k.QuizManager=Te,k.QuizManagerConfigSchema=ns,k.QuizOptionSchema=It,k.QuizTypeSchema=ce,k.animateCount=Re,k.computeWordSizes=Ct,k.default=ni,k.getQuizParticipant=us,k.getQuizPresenter=kt,k.removeQuizParticipant=as,k.removeQuizPresenter=At,k.resultsStream=_t,k.syncStream=Pt,Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
73
+ `;s.appendChild(n)}function ei(s,e){pn(s,e,!1)}function ti(s,e){pn(s,e,!0)}function pn(s,e,t){const n=s.querySelector(`.${z.wordcloudCloud}`);if(!n)return;const i=Ct(e.votes);if(i.length===0)return;const r=window.matchMedia("(prefers-reduced-motion: reduce)").matches;let o=0;for(const{word:c,count:u,fontSize:a,isTop:l}of i){const h=`[data-word="${CSS.escape(c)}"]`;let f=n.querySelector(h);if(!f){if(f=document.createElement("span"),f.className=z.wordcloudWord,f.dataset.word=c,f.textContent=c,t&&!r){f.style.opacity="0";const d=o*.08;f.style.transitionDelay=`${d}s`;const p=f;requestAnimationFrame(()=>{p.style.opacity="1"})}n.appendChild(f)}f.style.fontSize=`${a}rem`,f.classList.toggle(z.wordcloudWordTop,l),f.title=`${c}: ${u}`,o++}}const mn=O({wsUrl:K(R(),$(1)),quizGroupId:K(R(),$(1)),quizUrl:N(R()),endpoints:N(qe(de)),titleText:N(R()),hintText:N(R())});function ni(){let s=null,e,t=null,n=null;const i=new Set;function r(c){if(!t)return;const a=c.currentSlide;if(!(a instanceof HTMLElement))return;const l=a.dataset.quizId;l&&t.setActiveQuiz(l);const h=a.dataset.quizResults;if(h&&!i.has(h)){i.add(h);const f=t.getQuizState(h),d=js(a,h);if(d)ti(d,f);else{const p=Fs(a,h);p&&Xs(p,f)}}}function o(){if(!t||!s)return;const c=t.getState(),u=s.getRevealElement();for(const a of Us(u))Re(a,c.online);for(const[a,l]of Object.entries(c.results)){for(const h of Ds(u,a))Re(h,l.total);if(i.has(a)){for(const h of Qs(u,a))ei(h,l);for(const h of xs(u,a))Ys(h,l)}}}return{id:"live-quiz",init:async c=>{s=c;const u=s.getConfig().liveQuiz??{},a=G(mn,u);if(!a.success){console.warn("[live-quiz] Missing required config: wsUrl and quizGroupId. Pass them in Reveal.initialize({ liveQuiz: { wsUrl, quizGroupId } }).");return}e=a.output,t=kt({wsUrl:e.wsUrl,quizGroupId:e.quizGroupId,endpoints:e.endpoints});const l=s.getRevealElement(),h=l.querySelectorAll("section[data-quiz-id]"),f=[],d=[];for(const p of h){const _=Ks(p,e.quizUrl,e.titleText,e.hintText).catch(v=>console.warn("[live-quiz] Failed to render question slide:",v));f.push(_);const A=p.dataset.quizId,q=p.dataset.quizQuestion||"",P=Ie(ce,p.dataset.quizType);if(P==="text")d.push({quizId:A,question:q,type:P,options:[]});else{const v=G(_e,p.dataset.quizOptions);v.success&&d.push({quizId:A,question:q,type:P,options:v.output.map(E=>({label:E.label,text:E.text}))})}}t.setQuestions(d);for(const p of l.querySelectorAll("section[data-quiz-results]"))Ie(ce,p.dataset.quizType)==="text"?Zs(p):Ws(p);await Promise.all(f),n=t.subscribe(o),s.on("slidechanged",r)},destroy:()=>{if(!s)return;s.off("slidechanged",r),n&&(n(),n=null),t&&(At(e.quizGroupId),t.disconnect(),t=null);const c=s.getRevealElement();for(const u of Vs(c))u.remove();i.clear(),s=null}}}k.LiveQuizConfigSchema=mn,k.ParticipantConfigSchema=ss,k.ParticipantQuizManager=zt,k.PresenterQuizManager=Rt,k.QuizEndpointsSchema=de,k.QuizManager=Te,k.QuizManagerConfigSchema=ns,k.QuizOptionSchema=It,k.QuizTypeSchema=ce,k.animateCount=Re,k.computeWordSizes=Ct,k.default=ni,k.getQuizParticipant=us,k.getQuizPresenter=kt,k.removeQuizParticipant=as,k.removeQuizPresenter=At,k.resultsStream=_t,k.syncStream=Pt,Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../participant/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,mBAAmB,CAAC;AAK3B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAG3D,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAElC,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,OAAO,GACjB;IAAE,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA4VzB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../participant/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,mBAAmB,CAAC;AAK3B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAG3D,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAElC,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,OAAO,GACjB;IAAE,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CAiWzB"}
@@ -1 +1 @@
1
- :root{--lq-p-bg: #1a1a2e;--lq-p-text: #f0f0f0;--lq-p-text-muted: #9ca3af;--lq-p-text-dim: #6b7280;--lq-p-text-faint: #4b5563;--lq-p-accent: var(--lq-accent, #f59e0b);--lq-p-accent-bright: oklch(62% .28 65);--lq-p-brand: #9ca3af;--lq-p-status-text: #d1d5db;--lq-p-btn-border: rgba(156, 163, 175, .3);--lq-p-btn-bg: rgba(30, 30, 50, .6);--lq-p-btn-selected-bg: rgba(245, 158, 11, .15);--lq-p-btn-selected-glow: 0 0 8px rgba(245, 158, 11, .3), 0 0 20px rgba(245, 158, 11, .15);--lq-p-font: system-ui, -apple-system, sans-serif;--lq-p-border-radius: .75rem}.lq-participant{display:flex;flex-direction:column;align-items:center;min-height:100%;padding:1.5rem;gap:2rem;background:var(--lq-p-bg);color:var(--lq-p-text);font-family:var(--lq-p-font);-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased}.lq-participant__brand{font-size:.75rem;font-weight:500;color:var(--lq-p-brand);letter-spacing:.1em;text-transform:uppercase;padding-top:.5rem}.lq-participant__stats{font-size:.8rem;color:var(--lq-p-text-muted);font-variant-numeric:tabular-nums}.lq-participant__online,.lq-participant__answered{color:var(--lq-p-accent);font-weight:700}.lq-participant__waiting{font-size:clamp(.9rem,3.5vw,1.1rem);color:var(--lq-p-text-muted);text-align:center;padding:3rem 0}.lq-participant__section.lq-participant__section--hidden{display:none}.lq-participant__section{display:flex;flex-direction:column;align-items:center;gap:1rem;width:100%;max-width:28rem}.lq-participant__number{font-size:.7rem;font-weight:600;color:var(--lq-p-text-dim);letter-spacing:.12em;text-transform:uppercase}.lq-participant__question{font-size:clamp(1rem,4vw,1.4rem);font-weight:600;line-height:1.3;text-align:center}.lq-participant__options{display:flex;flex-direction:column;gap:.6rem;width:100%}.lq-participant__btn{display:flex;align-items:center;gap:1rem;width:100%;padding:.85rem 1.1rem;border:1px solid var(--lq-p-btn-border);border-radius:var(--lq-p-border-radius);background:var(--lq-p-btn-bg);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);color:var(--lq-p-text);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);font-weight:500;cursor:pointer;transition:all .2s ease;text-align:left}.lq-participant__btn:active{transform:scale(.97)}.lq-participant__btn-label{font-weight:700;color:var(--lq-p-accent);flex-shrink:0;font-size:.9em}.lq-participant__btn--selected{border-color:var(--lq-p-accent-bright);background:var(--lq-p-btn-selected-bg);box-shadow:var(--lq-p-btn-selected-glow)}.lq-participant__btn--faded{opacity:.35}.lq-participant__input-wrapper{display:flex;gap:.5rem;width:100%}.lq-participant__input{flex:1;padding:.85rem 1.1rem;border:1px solid var(--lq-p-btn-border);border-radius:var(--lq-p-border-radius);background:var(--lq-p-btn-bg);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);color:var(--lq-p-text);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);outline:none}.lq-participant__input:focus{border-color:var(--lq-p-accent)}.lq-participant__input:disabled{opacity:.5}.lq-participant__submit{padding:.85rem 1.2rem;border:none;border-radius:var(--lq-p-border-radius);background:var(--lq-p-accent);color:var(--lq-p-bg);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);font-weight:700;cursor:pointer;flex-shrink:0}.lq-participant__submit:active{transform:scale(.97)}.lq-participant__submit:disabled{opacity:.5;cursor:default}.lq-participant__status{font-size:clamp(.8rem,3vw,.95rem);color:var(--lq-p-status-text);text-align:center;line-height:1.5;min-height:1.5em}.lq-participant__status strong{color:var(--lq-p-accent)}.lq-participant__footer{font-size:.7rem;color:var(--lq-p-text-faint);text-align:center;padding-bottom:1rem}
1
+ :root{--lq-p-bg: #1a1a2e;--lq-p-text: #f0f0f0;--lq-p-text-muted: #9ca3af;--lq-p-text-dim: #6b7280;--lq-p-text-faint: #4b5563;--lq-p-accent: #f64242;--lq-p-accent-bright: oklch(65% .28 28);--lq-p-brand: #9ca3af;--lq-p-status-text: #d1d5db;--lq-p-btn-border: rgba(156, 163, 175, .3);--lq-p-btn-bg: rgba(30, 30, 50, .6);--lq-p-btn-selected-bg: rgba(246, 66, 66, .15);--lq-p-btn-selected-glow: 0 0 8px rgba(246, 66, 66, .3), 0 0 20px rgba(246, 66, 66, .15);--lq-p-font: system-ui, -apple-system, sans-serif;--lq-p-border-radius: .75rem}.lq-participant{display:flex;flex-direction:column;align-items:center;min-height:100vh;min-height:100dvh;padding:1.5rem;gap:2rem;background:var(--lq-p-bg);color:var(--lq-p-text);font-family:var(--lq-p-font);-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased}.lq-participant__brand{font-size:.75rem;font-weight:500;color:var(--lq-p-brand);letter-spacing:.1em;text-transform:uppercase;padding-top:.5rem}.lq-participant__stats{font-size:.8rem;color:var(--lq-p-text-muted);font-variant-numeric:tabular-nums}.lq-participant__online,.lq-participant__answered{color:var(--lq-p-accent);font-weight:700}.lq-participant__waiting{font-size:clamp(.9rem,3.5vw,1.1rem);color:var(--lq-p-text-muted);text-align:center;padding:3rem 0}.lq-participant__section.lq-participant__section--hidden{display:none}.lq-participant__section{display:flex;flex-direction:column;align-items:center;gap:1rem;width:100%;max-width:28rem}.lq-participant__number{font-size:.7rem;font-weight:600;color:var(--lq-p-text-dim);letter-spacing:.12em;text-transform:uppercase}.lq-participant__question{font-size:clamp(1rem,4vw,1.4rem);font-weight:600;line-height:1.3;text-align:center}.lq-participant__options{display:flex;flex-direction:column;gap:.6rem;width:100%}.lq-participant__btn{display:flex;align-items:center;gap:1rem;width:100%;padding:.85rem 1.1rem;border:1px solid var(--lq-p-btn-border);border-radius:var(--lq-p-border-radius);background:var(--lq-p-btn-bg);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);color:var(--lq-p-text);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);font-weight:500;cursor:pointer;transition:all .2s ease;text-align:left}.lq-participant__btn:active{transform:scale(.97)}.lq-participant__btn-label{font-weight:700;color:var(--lq-p-accent);flex-shrink:0;font-size:.9em}.lq-participant__btn--selected{border-color:var(--lq-p-accent-bright);background:var(--lq-p-btn-selected-bg);box-shadow:var(--lq-p-btn-selected-glow)}.lq-participant__btn--faded{opacity:.35}.lq-participant__input-wrapper{display:flex;gap:.5rem;width:100%}.lq-participant__input{flex:1;padding:.85rem 1.1rem;border:1px solid var(--lq-p-btn-border);border-radius:var(--lq-p-border-radius);background:var(--lq-p-btn-bg);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);color:var(--lq-p-text);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);outline:none}.lq-participant__input:focus{border-color:var(--lq-p-accent)}.lq-participant__input:disabled{opacity:.5}.lq-participant__submit{padding:.85rem 1.2rem;border:none;border-radius:var(--lq-p-border-radius);background:var(--lq-p-accent);color:var(--lq-p-bg);font-family:var(--lq-p-font);font-size:clamp(.9rem,3.5vw,1.1rem);font-weight:700;cursor:pointer;flex-shrink:0}.lq-participant__submit:active{transform:scale(.97)}.lq-participant__submit:disabled{opacity:.5;cursor:default}.lq-participant__status{font-size:clamp(.8rem,3vw,.95rem);color:var(--lq-p-status-text);text-align:center;line-height:1.5;min-height:1.5em}.lq-participant__status strong{color:var(--lq-p-accent)}.lq-participant__footer{font-size:.7rem;color:var(--lq-p-text-faint);text-align:center;padding-bottom:1rem}